import dotenv from 'dotenv' import axios from 'axios' import path from 'path' import fs from 'fs' dotenv.config() const categoriesPath = path.resolve('categories.json') const barsyApiUrl = 'https://vkashtibar.barsyonline.com/endpoints/json/' const barsyUser = process.env.BARSY_USER const barsyPassword = process.env.BARSY_PASSWORD // Fetch categories from the Barsy API const fetchCategories = async () => { try { const response = await axios.post( `${barsyApiUrl}Categories_getlist`, {}, { auth: { username: barsyUser, password: barsyPassword, }, headers: { 'Content-Type': 'application/json', }, } ) return response.data || [] } catch (error) { console.error('Error fetching categories:', error) return [] } } // Fetch articles for a specific category const fetchArticlesByCategory = async (categoryId) => { try { const response = await axios.post( `${barsyApiUrl}Articles_getlistobject`, { action_type: 'values', filters: { single_cat_id: categoryId, }, columns: [ 'article_id', 'article_name', 'actual_price', ], }, { auth: { username: barsyUser, password: barsyPassword, }, headers: { 'Content-Type': 'application/json', }, } ) return response.data.list || [] } catch (error) { console.error( `Error fetching articles for category ID ${categoryId}:`, error ) return [] } } // Save categories with articles to a file const saveCategoriesToFile = (categories) => { try { // Include only the required fields for each category const sanitizedCategories = categories.map((category) => ({ cat_id: category.cat_id, parent_id: category.parent_id, cat_name: category.cat_name, articles: category.articles.map((article) => ({ article_id: article.article_id, article_name: article.article_name, actual_price: article.actual_price, })), })) fs.writeFileSync( categoriesPath, JSON.stringify(sanitizedCategories, null, 2) ) console.log('Categories with articles saved to categories.json') } catch (error) { console.error('Error saving categories to file:', error) } } // Main function to fetch categories and their articles const fetchCategoriesWithArticles = async () => { const categories = await fetchCategories() if (categories.length === 0) { console.log('No categories found.') return } for (const category of categories) { const articles = await fetchArticlesByCategory(category.cat_id) category.articles = articles.map((article) => ({ article_id: article.article_id, article_name: article.article_name, actual_price: article.actual_price, amount_type_name_short: article.amount_type_name_short, article_name_public: article.article_name_public, })) } saveCategoriesToFile(categories) } // Execute the main function fetchCategoriesWithArticles()