product.rb 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. require 'barby'
  2. require 'barby/barcode/code_39'
  3. require 'barby/outputter/png_outputter'
  4. class Product < ActiveRecord::Base
  5. ##--- Asociaciones
  6. belongs_to :unit
  7. has_and_belongs_to_many :categories
  8. has_and_belongs_to_many :pointsales, join_table: :available_products
  9. has_many :sales_details
  10. has_many :purchase_details
  11. has_many :inventories_moves
  12. has_many :pre_sales
  13. has_many :pre_purchases
  14. has_many :special_prices
  15. has_many :pre_transfers
  16. has_many :available_products
  17. has_many :promotions
  18. enum status: [:erased, :active, :inactive]
  19. acts_as_taggable_on :sizes, :colors, :styles
  20. accepts_nested_attributes_for :available_products
  21. audited
  22. attr_accessor :skip_sku_validation
  23. mount_uploader :img_product, ImageUploader
  24. ##--- Validaciones previas de guardar
  25. validates :sku,
  26. presence: { message: "Debe capturar el SKU del producto." },
  27. length: { maximum: 30, too_long: "El máximo de caracteres para el SKU debe ser %{count}." },
  28. uniqueness: { message: "El SKU ya fue utilizado, favor de especificar otro." },
  29. unless: :skip_sku_validation
  30. validates_presence_of :name, message: "Debe capturar el nombre del producto."
  31. validates_presence_of :unit_id, message: "Debe seleccionar la unidad de medida correspondiente al producto."
  32. validates_presence_of :category_ids, message: "Debe elegir por lo menos una línea de producto relacionada al producto."
  33. validates :barcode, uniqueness: { message: "El código de barras ya fue utilizado, favor de especificar otro." }, allow_blank: true
  34. validates_presence_of :name, message: "Debe capturar el nombre del producto."
  35. validates :price_sale,
  36. presence: { message: "Debe capturar el precio de venta del producto." },
  37. numericality: { greater_than: 0.00 }
  38. def valid_categories
  39. categories.count > 0
  40. end
  41. def small_img
  42. if img_product?
  43. img_product.url(:medium).to_s
  44. else
  45. img = "/images/original/missing.png"
  46. end
  47. end
  48. ##--- Tipo de vistas / consultas
  49. scope :vigentes, -> { where.not(products: { status: 0 }).order(" products.status ASC, products.name ASC") }
  50. scope :activos, -> { where(status: 1).order("products.name ASC") }
  51. scope :activos_children, -> { activos.where(is_parent: false).order("products.name ASC") }
  52. scope :vigentes_parents, -> { vigentes.where("parent_id IS NULL") }
  53. scope :name_sku_barcode_like, ->(name) { activos.where("is_parent = ? and (name ilike ? or sku ilike ? or barcode ilike ?)", false, "%#{name}%", "%#{name}%", "%#{name}%") }
  54. scope :name_sku_barcode_attribute_like, ->(name, attributes_string) { activos.where("is_parent = ? and (name ilike ? or sku ilike ? or barcode ilike ?) #{attributes_string}", false, "%#{name}%", "%#{name}%", "%#{name}%") }
  55. # para special_prices
  56. scope :name_sku_barcode_like_sp, ->(name) { activos.where("is_parent = ? and (name ilike ? or sku ilike ? or barcode ilike ?)", true, "%#{name}%", "%#{name}%", "%#{name}%") }
  57. def name_with_sku
  58. sku.to_s + " - " + name.to_s
  59. end
  60. def get_promotion
  61. category_id = categories[0].parent.present? ? categories[0].parent.id : categories[0].id
  62. category_array = [category_id, categories.ids].flatten
  63. product_ids = [id, parent_id]
  64. promos = Promotion.where("product_id IN (?) OR category_id IN (?)", product_ids, category_array).order("percent, id DESC").vigentes.first
  65. end
  66. def display_sku_name_attributes
  67. sku.to_s + " | " + name.to_s + " | " + display_attributes.to_s
  68. end
  69. def full_display
  70. show_name = name + "\n" + "SKU: " + sku + "\n"
  71. show_name += "\n" + display_attributes.to_s if parent_id.present?
  72. show_name += " Código de barras: " + barcode if parent_id.present? && barcode.present?
  73. show_name
  74. end
  75. def stock_in_pointsale(pointsale_id)
  76. stock = 0
  77. # checar si hay existencias en los almacenes.
  78. warehouses_stock = WarehouseStock.where(product_id: id)
  79. warehouses_stock.each do |warehouse|
  80. # solamente hacerlo cuando pointsale id sea nil porque es el index de producto
  81. stock += warehouse.stock if pointsale_id.zero?
  82. end
  83. # existencias en puntos de venta.
  84. availables = AvailableProduct.where(product_id: id)
  85. availables.each do |available|
  86. if pointsale_id == available.pointsale_id
  87. stock = available.stock
  88. elsif pointsale_id.zero?
  89. stock += available.stock
  90. end
  91. end
  92. stock
  93. end
  94. def can_be_deleted?
  95. if is_parent
  96. children_ids = Product.where(parent_id: id).pluck(:id)
  97. in_available = AvailableProduct.where("product_id IN (?) and stock > 0", children_ids).any?
  98. in_warehouse = WarehouseStock.where("product_id IN (?) and stock > 0", children_ids).any?
  99. else
  100. in_warehouse = WarehouseStock.where("product_id = #{id} and stock > 0").any?
  101. in_available = AvailableProduct.where("product_id = #{id} and stock > 0").any?
  102. end
  103. in_available == true || in_warehouse == true ? false : true
  104. end
  105. def last_sale(pointsale_id)
  106. unless pointsale_id.nil?
  107. last_time = Pointsale.find(pointsale_id).sales_details.where(product_id: id).last
  108. end
  109. end
  110. def available_in_pointsale?(pointsale_id)
  111. if pointsales.exists?(id: pointsale_id)
  112. true
  113. else
  114. false
  115. end
  116. end
  117. def get_available_in_pointsale(pointsale_id)
  118. AvailableProduct.find_by(pointsale_id: pointsale_id, product_id: id)
  119. end
  120. def get_price_sale(pointsale_id)
  121. available = get_available_in_pointsale(pointsale_id)
  122. if available.present? && available.price_sale.present?
  123. available.price_sale
  124. else
  125. price_sale
  126. end
  127. end
  128. def pointsales_prices
  129. AvailableProduct.where("product_id = ? and price_sale IS NOT NULL", id)
  130. end
  131. def variants_attributes
  132. ActsAsTaggableOn::Tagging.where(taggable_id: id, taggable_type: 'Product').distinct(:context).select(:context)
  133. end
  134. def get_combinations(combinations, attributes)
  135. if presentation
  136. ##--- crear el array de los arrays de atributos
  137. if size_list.count > 0
  138. attributes << size_list
  139. end
  140. if color_list.count > 0
  141. attributes << color_list
  142. end
  143. if style_list.count > 0
  144. attributes << style_list
  145. end
  146. ##--- verificar que atributos tenga mas de una categoria
  147. if attributes.count > 1
  148. ##--- Making combinations from arrays
  149. first_array, *rest_of_arrays = attributes
  150. combinations = first_array.product(*rest_of_arrays)
  151. else
  152. attributes[0].each do |attribute|
  153. combinations << attribute
  154. end
  155. end
  156. combinations
  157. end
  158. end
  159. # rubocop:disable Metrics/BlockLength
  160. def save_variants(current_user)
  161. Thread.new do
  162. combinations = Array.new
  163. attributes = Array.new
  164. combinations = get_combinations(combinations, attributes)
  165. ##--- recorrer combinaciones para crear las variantes de productos
  166. unless combinations.nil?
  167. combinations.each_with_index do |combination, index|
  168. @products_variant = Product.new
  169. @products_variant = dup
  170. @products_variant.parent_id = id
  171. @products_variant.is_parent = false
  172. @products_variant.sku = sku + (index + 1).to_s + "A"
  173. @products_variant.category_ids = category_ids
  174. attributes_json = {}
  175. if combination.is_a?(Array)
  176. combination.each do |attrib|
  177. attributes_json = @products_variant.assign_attributes_to_variant(attrib, id, attributes_json)
  178. end
  179. else
  180. attributes_json = @products_variant.assign_attributes_to_variant(combination, id, attributes_json)
  181. end
  182. @products_variant.attributes_json = attributes_json.to_json
  183. @products_variant.save
  184. @products_variant.generate_barcode
  185. @products_variant.save
  186. if current_user.usertype == 'G'
  187. AvailableProduct.create(product_id: @products_variant.id, pointsale_id: current_user.pointsale_id, stock: 0)
  188. end
  189. end
  190. end
  191. end
  192. end
  193. # rubocop:enable Metrics/BlockLength
  194. def assign_attributes_to_variant(attri, parent_id, attributes_json)
  195. attri_id = ActsAsTaggableOn::Tag.where("lower(name) = lower(?)", attri).select(:id).first
  196. get_context = ActsAsTaggableOn::Tagging.where(tag_id: attri_id, taggable_id: parent_id, taggable_type: 'Product').select(:context).first
  197. context = get_context.context
  198. if id != parent_id
  199. if context == "sizes"
  200. self.size_list = attri.to_s
  201. elsif context == "colors"
  202. self.color_list = attri.to_s
  203. elsif context == "styles"
  204. self.style_list = attri.to_s
  205. end
  206. end
  207. attributes_json[context] = attri.to_s
  208. attributes_json
  209. end
  210. def update_attributes_to_variants(new_sizes, new_colors, new_styles)
  211. unless new_sizes.nil?
  212. (JSON.parse new_sizes).each do |s|
  213. sizes.each do |p|
  214. next unless p.id.to_s == s["id"].to_s && p.name.to_s != s["name"].to_s
  215. # if p.id.to_s == s["id"].to_s && p.name.to_s != s["name"].to_s
  216. size_list.remove(p.name.to_s)
  217. variants = children.tagged_with(p.name.to_s, on: :sizes, any: true)
  218. variants.each do |v|
  219. v.size_list.remove(p.name.to_s)
  220. v.size_list.add(s["name"].to_s)
  221. v.save(validate: false)
  222. end
  223. size_list.add(s["name"].to_s)
  224. end
  225. end
  226. end
  227. unless new_colors.nil?
  228. (JSON.parse new_colors).each do |s|
  229. colors.each do |p|
  230. next unless p.id.to_s == s["id"].to_s && p.name.to_s != s["name"].to_s
  231. # if p.id.to_s == s["id"].to_s && p.name.to_s != s["name"].to_s
  232. color_list.remove(p.name.to_s)
  233. variants = children.tagged_with(p.name.to_s, on: :colors, any: true)
  234. variants.each do |v|
  235. v.color_list.remove(p.name.to_s)
  236. v.color_list.add(s["name"].to_s)
  237. v.save(validate: false)
  238. end
  239. color_list.add(s["name"].to_s)
  240. end
  241. end
  242. end
  243. unless new_styles.nil?
  244. (JSON.parse new_styles).each do |s|
  245. styles.each do |p|
  246. next unless p.id.to_s == s["id"].to_s && p.name.to_s != s["name"].to_s
  247. # if p.id.to_s == s["id"].to_s && p.name.to_s != s["name"].to_s
  248. style_list.remove(p.name.to_s)
  249. variants = children.tagged_with(p.name.to_s, on: :styles, any: true)
  250. variants.each do |v|
  251. v.style_list.remove(p.name.to_s)
  252. v.style_list.add(s["name"].to_s)
  253. v.save(validate: false)
  254. end
  255. style_list.add(s["name"].to_s)
  256. end
  257. end
  258. end
  259. if save(validate: false)
  260. children.each do |variant|
  261. attributes_json = {}
  262. attributes_json = variant.assign_attributes_to_variant(variant.size_list, id, attributes_json) unless variant.size_list.count.zero?
  263. attributes_json = variant.assign_attributes_to_variant(variant.color_list, id, attributes_json) unless variant.color_list.count.zero?
  264. attributes_json = variant.assign_attributes_to_variant(variant.style_list, id, attributes_json) unless variant.style_list.count.zero?
  265. variant.attributes_json = attributes_json.to_json
  266. variant.save(validate: false)
  267. end
  268. end
  269. end
  270. # rubocop:disable Metrics/BlockLength
  271. def save_new_attributes(new_sizes, new_colors, new_styles)
  272. Thread.new do
  273. combinations = Array.new
  274. attributes = Array.new
  275. unless new_sizes.nil?
  276. new_sizes.each do |s|
  277. size_list.add(s.to_s)
  278. save(validate: false)
  279. end
  280. end
  281. unless new_colors.nil?
  282. new_colors.each do |s|
  283. color_list.add(s.to_s)
  284. save(validate: false)
  285. end
  286. end
  287. unless new_styles.nil?
  288. new_styles.each do |s|
  289. style_list.add(s.to_s)
  290. save(validate: false)
  291. end
  292. end
  293. combinations = get_combinations(combinations, attributes)
  294. # self.save(:validate: false)
  295. combinations.each_with_index do |combination, index|
  296. attributes = {}
  297. if combination.is_a?(Array)
  298. combination.each do |c|
  299. attributes = assign_attributes_to_variant(c, id, attributes)
  300. end
  301. else
  302. attributes = assign_attributes_to_variant(combination, id, attributes)
  303. end
  304. next unless children.where("attributes_json = ?", attributes.to_json).select(:id).first.nil?
  305. # if children.where("attributes_json = ?", attributes.to_json).select(:id).first.nil?
  306. @products_variant = Product.new
  307. @products_variant = dup
  308. @products_variant.parent_id = id
  309. @products_variant.is_parent = false
  310. @products_variant.sku = sku + (index + 1).to_s + "A"
  311. @products_variant.category_ids = category_ids
  312. @products_variant.barcode = ''
  313. attrs_json = {}
  314. if combination.is_a?(Array)
  315. combination.each do |attrib|
  316. attrs_json = @products_variant.assign_attributes_to_variant(attrib, id, attrs_json)
  317. end
  318. else
  319. attrs_json = @products_variant.assign_attributes_to_variant(combination, id, attrs_json)
  320. end
  321. @products_variant.attributes_json = attributes.to_json
  322. @products_variant.save(validate: false)
  323. @products_variant.generate_barcode
  324. @products_variant.save(validate: false)
  325. end
  326. end
  327. end
  328. # rubocop:enable Metrics/BlockLength
  329. def children
  330. Product.where("parent_id = ? and status != ? ", id, 0)
  331. end
  332. def attributes_to_hash
  333. JSON.parse attributes_json.gsub('=>', ':')
  334. end
  335. def display_attributes
  336. attributes = ""
  337. unless attributes_json.nil?
  338. attributes_to_hash.each do |attr_, value|
  339. description = I18n.t("dictionary." + attr_) + ": #{value}"
  340. attributes = attributes.blank? ? description.to_s : attributes.to_s + " " + description.to_s
  341. end
  342. end
  343. attributes
  344. end
  345. def attrs_array
  346. attributes = []
  347. unless attributes_json.nil?
  348. attributes_to_hash.each do |attr_, value|
  349. attributes << I18n.t("dictionary." + attr_) + ": #{value.capitalize}"
  350. end
  351. end
  352. attributes
  353. end
  354. def display_attributes_receipt
  355. attributes = ""
  356. unless attributes_json.nil?
  357. attributes_to_hash.each do |_attr_, value|
  358. attributes = attributes.blank? ? value.to_s : attributes.to_s + " " + value.to_s
  359. end
  360. end
  361. attributes.upcase
  362. end
  363. def self.most_selled_products(period, user)
  364. # se envia al user porque no se puede acceder al current, esto es, para que el gerente
  365. # vea los mas vendidos de su punto de venta.
  366. all_products = Array.new
  367. if period == 'week'
  368. beg_period = Date.current.beginning_of_week
  369. end_period = Date.current.end_of_week
  370. elsif period == 'month'
  371. beg_period = Date.current.beginning_of_month
  372. end_period = Date.current.end_of_month
  373. end
  374. if user.usertype == "A" || user.usertype == "SS"
  375. quantities_top_products = SalesDetail.activos.joins(:sale, :product).where("sales.date_sale between ? and ?", beg_period, end_period).group('products.name').order('sum_quantity desc').limit(10).sum(:quantity)
  376. total_top_products = SalesDetail.activos.joins(:sale).where('sales.date_sale between ? and ?', beg_period, end_period).order('sum_quantity desc').limit(10).sum(:quantity)
  377. total_sold = SalesDetail.activos.joins(:sale).where('sales.date_sale between ? and ?', beg_period, end_period).sum(:quantity)
  378. elsif user.usertype == 'G'
  379. quantities_top_products = user.pointsale.sales_details.joins(:sale, :product).where("sales.status != ? and sales.date_sale between ? and ?", 1, beg_period, end_period).group('products.name').order('sum_quantity desc').limit(10).sum(:quantity)
  380. total_top_products = user.pointsale.sales_details.joins(:sale).where('sales.status != ? and sales.date_sale between ? and ?', 1, beg_period, end_period).order('sum_quantity desc').limit(10).sum(:quantity)
  381. total_sold = user.pointsale.sales_details.joins(:sale).where('sales.status != ? and sales.date_sale between ? and ?', 1, beg_period, end_period).sum(:quantity)
  382. end
  383. others = total_sold - total_top_products
  384. if others > 0
  385. quantities_top_products[:Otros] = others
  386. end
  387. quantities_top_products
  388. end
  389. def get_available_children(just_pointsales)
  390. children = Product.vigentes.where("parent_id = ?", id).pluck(:id)
  391. if just_pointsales
  392. AvailableProduct.where("product_id IN (?)", children).joins(:pointsale).select(:pointsale_id, :name).distinct(:pointsale_id)
  393. else
  394. AvailableProduct.where("product_id IN (?)", children)
  395. end
  396. end
  397. def generate_barcode
  398. if barcode.blank?
  399. barcode_generated = format('%07d', id)
  400. self.barcode = barcode_generated
  401. save_path = Rails.public_path.join('barcodes', "#{barcode_generated}.png")
  402. File.open(save_path, 'wb') { |f| f.write Barby::Code39.new(barcode_generated).to_png(height: 50, margin: 5) }
  403. end
  404. end
  405. def self.gen_barcodes_existing_prods
  406. products = Product.vigentes
  407. products.each do |product|
  408. product.generate_barcode
  409. product.save
  410. end
  411. end
  412. def self.gen_only_barcodes_w_empty
  413. products = Product.activos_children.where(barcode: '')
  414. products.each do |product|
  415. product.skip_sku_validation = true
  416. product.barcode = format('%07d', product.id)
  417. product.save
  418. end
  419. puts 'termine'
  420. end
  421. def self.gen_barcode_img_for_existing_barcodes
  422. products = Product.activos_children
  423. counter = 0
  424. products.each do |product|
  425. if product.barcode?
  426. unless File.file?(Rails.public_path.join('barcodes', "#{product.barcode}.png"))
  427. save_path = Rails.public_path.join('barcodes', "#{product.barcode}.png")
  428. File.open(save_path, 'wb') { |f| f.write Barby::Code39.new(product.barcode).to_png(height: 50, margin: 5) }
  429. counter += 1;
  430. end
  431. else
  432. puts "***** NO TIENE BARCODE! #{product.id}"
  433. end
  434. end
  435. puts "TERMINÉ, generé: #{counter} imagenes de barcode"
  436. end
  437. end