ProductService.coffee 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  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. opts =
  21. include_docs: true
  22. startkey: ['product']
  23. endkey: ['product', {}]
  24. result = await @pouchService.queryView('products', 'by_category', opts)
  25. products = result.rows.map (row) ->
  26. new Product(row.doc)
  27. log '📦 Загружены товары:', products.length
  28. return products
  29. catch error
  30. log '❌ Ошибка загрузки товаров:', error
  31. throw error
  32. getProductsByCategory: (category, options = {}) ->
  33. await @ensureInit()
  34. try
  35. opts =
  36. include_docs: true
  37. key: [category]
  38. result = await @pouchService.queryView('products', 'by_category', opts)
  39. products = result.rows.map (row) ->
  40. new Product(row.doc)
  41. log "📦 Загружены товары категории #{category}:", products.length
  42. return products
  43. catch error
  44. log "❌ Ошибка загрузки товаров категории #{category}:", error
  45. throw error
  46. getProductBySku: (sku) ->
  47. await @ensureInit()
  48. try
  49. result = await @pouchService.queryView('products', 'by_sku', {
  50. key: sku
  51. include_docs: true
  52. })
  53. if result.rows.length > 0
  54. product = new Product(result.rows[0].doc)
  55. log "📦 Загружен товар по SKU: #{sku}"
  56. return product
  57. else
  58. log "⚠️ Товар не найден по SKU: #{sku}"
  59. return null
  60. catch error
  61. log "❌ Ошибка поиска товара по SKU #{sku}:", error
  62. throw error
  63. searchProducts: (query, options = {}) ->
  64. await @ensureInit()
  65. try
  66. # Простой поиск по индексу
  67. searchTerms = query.toLowerCase().split(/\s+/).filter (term) -> term.length > 2
  68. if searchTerms.length == 0
  69. return []
  70. # Здесь будет реализация полнотекстового поиска
  71. # Временная реализация - поиск по всем товарам и фильтрация
  72. allProducts = await @getAllProducts()
  73. filteredProducts = allProducts.filter (product) ->
  74. searchable = [
  75. product.name
  76. product.brand
  77. product.category
  78. product.description
  79. ].join(' ').toLowerCase()
  80. searchTerms.every (term) -> searchable.includes(term)
  81. log "🔍 Результаты поиска '#{query}':", filteredProducts.length
  82. return filteredProducts
  83. catch error
  84. log "❌ Ошибка поиска товаров '#{query}':", error
  85. throw error
  86. saveProduct: (productData) ->
  87. await @ensureInit()
  88. try
  89. product = new Product(productData)
  90. # Генерация ID если не установлен
  91. if not product._id
  92. product._id = "product:#{product.sku}"
  93. result = await @pouchService.saveDocument(product)
  94. log "💾 Товар сохранен: #{product.name}"
  95. return result
  96. catch error
  97. log "❌ Ошибка сохранения товара:", error
  98. throw error
  99. ensureInit: ->
  100. unless @initialized
  101. throw new Error('ProductService не инициализирован. Вызовите init() сначала.')
  102. module.exports = new ProductService()