| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131 |
- # 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
- opts =
- include_docs: true
- startkey: ['product']
- endkey: ['product', {}]
-
- result = await @pouchService.queryView('products', 'by_category', opts)
-
- 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
- opts =
- include_docs: true
- key: [category]
-
- result = await @pouchService.queryView('products', 'by_category', opts)
-
- 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
- searchProducts: (query, options = {}) ->
- await @ensureInit()
-
- try
- # Простой поиск по индексу
- searchTerms = query.toLowerCase().split(/\s+/).filter (term) -> term.length > 2
-
- if searchTerms.length == 0
- return []
-
- # Здесь будет реализация полнотекстового поиска
- # Временная реализация - поиск по всем товарам и фильтрация
- allProducts = await @getAllProducts()
-
- filteredProducts = allProducts.filter (product) ->
- searchable = [
- product.name
- product.brand
- product.category
- product.description
- ].join(' ').toLowerCase()
-
- searchTerms.every (term) -> searchable.includes(term)
-
- log "🔍 Результаты поиска '#{query}':", filteredProducts.length
- return filteredProducts
- catch error
- log "❌ Ошибка поиска товаров '#{query}':", error
- throw error
- saveProduct: (productData) ->
- await @ensureInit()
-
- try
- product = new Product(productData)
-
- # Генерация ID если не установлен
- if not product._id
- product._id = "product:#{product.sku}"
-
- result = await @pouchService.saveDocument(product)
- log "💾 Товар сохранен: #{product.name}"
- return result
- catch error
- log "❌ Ошибка сохранения товара:", error
- throw error
- ensureInit: ->
- unless @initialized
- throw new Error('ProductService не инициализирован. Вызовите init() сначала.')
- module.exports = new ProductService()
|