ProductService.coffee 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. # app/services/ProductService.coffee
  2. { Product } = require 'app/types/data'
  3. class ProductService
  4. constructor: ->
  5. @pouchService = require 'app/utils/pouch'
  6. @initialized = false
  7. init: ->
  8. return Promise.resolve() if @initialized
  9. try
  10. await @pouchService.init()
  11. @initialized = true
  12. log '✅ ProductService инициализирован'
  13. return Promise.resolve()
  14. catch error
  15. log '❌ Ошибка инициализации ProductService:', error
  16. return Promise.reject(error)
  17. getAllProducts: (options = {}) ->
  18. await @ensureInit()
  19. try
  20. result = await @pouchService.queryView('products', 'all_active', {
  21. include_docs: true
  22. })
  23. products = result.rows.map (row) ->
  24. new Product(row.doc)
  25. log '📦 Загружены товары: ' + products.length
  26. return products
  27. catch error
  28. log '❌ Ошибка загрузки товаров:', error
  29. throw error
  30. getProductsByCategory: (category, options = {}) ->
  31. await @ensureInit()
  32. try
  33. result = await @pouchService.queryView('products', 'by_category', {
  34. startkey: [category]
  35. endkey: [category, {}]
  36. include_docs: true
  37. })
  38. products = result.rows.map (row) ->
  39. new Product(row.doc)
  40. log "📦 Загружены товары категории " + category + ": " + products.length
  41. return products
  42. catch error
  43. log "❌ Ошибка загрузки товаров категории " + category + ":", error
  44. throw error
  45. getProductBySku: (sku) ->
  46. await @ensureInit()
  47. try
  48. result = await @pouchService.queryView('products', 'by_sku', {
  49. key: sku
  50. include_docs: true
  51. })
  52. if result.rows.length > 0
  53. product = new Product(result.rows[0].doc)
  54. log "📦 Загружен товар по SKU: " + sku
  55. return product
  56. else
  57. log "⚠️ Товар не найден по SKU: " + sku
  58. return null
  59. catch error
  60. log "❌ Ошибка поиска товара по SKU " + sku + ":", error
  61. throw error
  62. bulkSaveProducts: (products) ->
  63. await @ensureInit()
  64. try
  65. # Преобразуем товары в документы для PouchDB
  66. docs = products.map (product) =>
  67. if product._id and product._rev
  68. return product
  69. else
  70. # Новый товар
  71. return {
  72. _id: product._id
  73. type: 'product'
  74. name: product.name
  75. sku: product.sku
  76. price: product.price
  77. oldPrice: product.oldPrice
  78. brand: product.brand
  79. category: product.category
  80. description: product.description
  81. domains: product.domains || [window.location.hostname]
  82. active: product.active != false
  83. inStock: product.inStock != false
  84. attributes: product.attributes || {}
  85. images: product.images || []
  86. createdAt: product.createdAt || new Date().toISOString()
  87. updatedAt: new Date().toISOString()
  88. }
  89. result = await @pouchService.bulkDocs(docs)
  90. success = []
  91. errors = []
  92. result.forEach (item, index) =>
  93. if item.ok
  94. success.push(products[index])
  95. else
  96. errors.push({
  97. product: products[index]
  98. error: item.error || 'Unknown error'
  99. index: index
  100. })
  101. log "📦 Пакетное сохранение: успешно " + success.length + ", ошибок " + errors.length
  102. return { success, errors }
  103. catch error
  104. log '❌ Ошибка пакетного сохранения товаров:', error
  105. throw error
  106. ensureInit: ->
  107. unless @initialized
  108. throw new Error('ProductService не инициализирован. Вызовите init() сначала.')
  109. module.exports = new ProductService()