| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132 |
- # app/services/ProductService.coffee
- { Product } = require 'app/types/data'
- class ProductService
- constructor: ->
- @pouchService = require 'app/utils/pouch'
- @initialized = false
- init: ->
- return Promise.resolve() if @initialized
-
- try
- await @pouchService.init()
- @initialized = true
- log '✅ ProductService инициализирован'
- return Promise.resolve()
- catch error
- log '❌ Ошибка инициализации ProductService:', error
- return Promise.reject(error)
- getAllProducts: (options = {}) ->
- await @ensureInit()
-
- try
- result = await @pouchService.queryView('products', 'all_active', {
- include_docs: true
- })
-
- products = result.rows.map (row) ->
- new Product(row.doc)
-
- log '📦 Загружены товары: ' + products.length
- return products
- catch error
- log '❌ Ошибка загрузки товаров:', error
- throw error
- getProductsByCategory: (category, options = {}) ->
- await @ensureInit()
-
- try
- result = await @pouchService.queryView('products', 'by_category', {
- startkey: [category]
- endkey: [category, {}]
- include_docs: true
- })
-
- products = result.rows.map (row) ->
- new Product(row.doc)
-
- log "📦 Загружены товары категории " + category + ": " + products.length
- return products
- catch error
- log "❌ Ошибка загрузки товаров категории " + category + ":", error
- throw error
- getProductBySku: (sku) ->
- await @ensureInit()
-
- try
- result = await @pouchService.queryView('products', 'by_sku', {
- key: sku
- include_docs: true
- })
-
- if result.rows.length > 0
- product = new Product(result.rows[0].doc)
- log "📦 Загружен товар по SKU: " + sku
- return product
- else
- log "⚠️ Товар не найден по SKU: " + sku
- return null
- catch error
- log "❌ Ошибка поиска товара по SKU " + sku + ":", error
- throw error
- bulkSaveProducts: (products) ->
- await @ensureInit()
-
- try
- # Преобразуем товары в документы для PouchDB
- docs = products.map (product) =>
- if product._id and product._rev
- return product
- else
- # Новый товар
- return {
- _id: product._id
- type: 'product'
- name: product.name
- sku: product.sku
- price: product.price
- oldPrice: product.oldPrice
- brand: product.brand
- category: product.category
- description: product.description
- domains: product.domains || [window.location.hostname]
- active: product.active != false
- inStock: product.inStock != false
- attributes: product.attributes || {}
- images: product.images || []
- createdAt: product.createdAt || new Date().toISOString()
- updatedAt: new Date().toISOString()
- }
-
- result = await @pouchService.bulkDocs(docs)
-
- success = []
- errors = []
-
- result.forEach (item, index) =>
- if item.ok
- success.push(products[index])
- else
- errors.push({
- product: products[index]
- error: item.error || 'Unknown error'
- index: index
- })
-
- log "📦 Пакетное сохранение: успешно " + success.length + ", ошибок " + errors.length
- return { success, errors }
-
- catch error
- log '❌ Ошибка пакетного сохранения товаров:', error
- throw error
- ensureInit: ->
- unless @initialized
- throw new Error('ProductService не инициализирован. Вызовите init() сначала.')
- module.exports = new ProductService()
|