product.rb 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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_presence_of :price_sale, message: "Debe capturar el precio de venta del producto."
  36. def valid_categories
  37. categories.count > 0
  38. end
  39. def small_img
  40. if img_product?
  41. img_product.url(:medium).to_s
  42. else
  43. img = "/images/original/missing.png"
  44. end
  45. end
  46. ##--- Tipo de vistas / consultas
  47. scope :vigentes, -> { where.not(products: { status: 0 }).order(" products.status ASC, products.name ASC") }
  48. scope :activos, -> { where(status: 1).order("products.name ASC") }
  49. scope :activos_children, -> { activos.where(is_parent: false).order("products.name ASC") }
  50. scope :vigentes_parents, -> { vigentes.where("parent_id IS NULL") }
  51. scope :name_sku_barcode_like, ->(name) { activos.where("is_parent = ? and (name ilike ? or sku ilike ? or barcode ilike ?)", false, "%#{name}%", "%#{name}%", "%#{name}%") }
  52. 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}%") }
  53. # para special_prices
  54. scope :name_sku_barcode_like_sp, ->(name) { activos.where("is_parent = ? and (name ilike ? or sku ilike ? or barcode ilike ?)", true, "%#{name}%", "%#{name}%", "%#{name}%") }
  55. def name_with_sku
  56. sku.to_s + " - " + name.to_s
  57. end
  58. def get_promotion
  59. category_id = categories[0].parent.present? ? categories[0].parent.id : categories[0].id
  60. category_array = [category_id, categories.ids].flatten
  61. product_ids = [id, parent_id]
  62. promos = Promotion.where("product_id IN (?) OR category_id IN (?)", product_ids, category_array).order("percent, id DESC").vigentes.first
  63. end
  64. def display_sku_name_attributes
  65. sku.to_s + " | " + name.to_s + " | " + display_attributes.to_s
  66. end
  67. def full_display
  68. show_name = name + "\n" + "SKU: " + sku + "\n"
  69. show_name += "\n" + display_attributes.to_s if parent_id.present?
  70. show_name += " Código de barras: " + barcode if parent_id.present? && barcode.present?
  71. show_name
  72. end
  73. def stock_in_pointsale(pointsale_id)
  74. stock = 0
  75. # checar si hay existencias en los almacenes.
  76. warehouses_stock = WarehouseStock.where(product_id: id)
  77. warehouses_stock.each do |warehouse|
  78. # solamente hacerlo cuando pointsale id sea nil porque es el index de producto
  79. stock += warehouse.stock if pointsale_id.zero?
  80. end
  81. # existencias en puntos de venta.
  82. availables = AvailableProduct.where(product_id: id)
  83. availables.each do |available|
  84. if pointsale_id == available.pointsale_id
  85. stock = available.stock
  86. elsif pointsale_id.zero?
  87. stock += available.stock
  88. end
  89. end
  90. stock
  91. end
  92. def can_be_deleted?
  93. if is_parent
  94. children_ids = Product.where(parent_id: id).pluck(:id)
  95. in_available = AvailableProduct.where("product_id IN (?) and stock > 0", children_ids).any?
  96. in_warehouse = WarehouseStock.where("product_id IN (?) and stock > 0", children_ids).any?
  97. else
  98. in_warehouse = WarehouseStock.where("product_id = #{id} and stock > 0").any?
  99. in_available = AvailableProduct.where("product_id = #{id} and stock > 0").any?
  100. end
  101. in_available == true || in_warehouse == true ? false : true
  102. end
  103. def last_sale(pointsale_id)
  104. unless pointsale_id.nil?
  105. last_time = Pointsale.find(pointsale_id).sales_details.where(product_id: id).last
  106. end
  107. end
  108. def available_in_pointsale?(pointsale_id)
  109. if pointsales.exists?(id: pointsale_id)
  110. true
  111. else
  112. false
  113. end
  114. end
  115. def get_available_in_pointsale(pointsale_id)
  116. AvailableProduct.find_by(pointsale_id: pointsale_id, product_id: id)
  117. end
  118. def get_price_sale(pointsale_id)
  119. available = get_available_in_pointsale(pointsale_id)
  120. if available.present? && available.price_sale.present?
  121. available.price_sale
  122. else
  123. price_sale
  124. end
  125. end
  126. def pointsales_prices
  127. AvailableProduct.where("product_id = ? and price_sale IS NOT NULL", id)
  128. end
  129. def variants_attributes
  130. ActsAsTaggableOn::Tagging.where(taggable_id: id, taggable_type: 'Product').distinct(:context).select(:context)
  131. end
  132. def get_combinations(combinations, attributes)
  133. if presentation
  134. ##--- crear el array de los arrays de atributos
  135. if size_list.count > 0
  136. attributes << size_list
  137. end
  138. if color_list.count > 0
  139. attributes << color_list
  140. end
  141. if style_list.count > 0
  142. attributes << style_list
  143. end
  144. ##--- verificar que atributos tenga mas de una categoria
  145. if attributes.count > 1
  146. ##--- Making combinations from arrays
  147. first_array, *rest_of_arrays = attributes
  148. combinations = first_array.product(*rest_of_arrays)
  149. else
  150. attributes[0].each do |attribute|
  151. combinations << attribute
  152. end
  153. end
  154. combinations
  155. end
  156. end
  157. # rubocop:disable Metrics/BlockLength
  158. def save_variants(current_user)
  159. Thread.new do
  160. combinations = Array.new
  161. attributes = Array.new
  162. combinations = get_combinations(combinations, attributes)
  163. ##--- recorrer combinaciones para crear las variantes de productos
  164. unless combinations.nil?
  165. combinations.each_with_index do |combination, index|
  166. @products_variant = Product.new
  167. @products_variant = dup
  168. @products_variant.parent_id = id
  169. @products_variant.is_parent = false
  170. @products_variant.sku = sku + (index + 1).to_s + "A"
  171. @products_variant.category_ids = category_ids
  172. attributes_json = {}
  173. if combination.is_a?(Array)
  174. combination.each do |attrib|
  175. attributes_json = @products_variant.assign_attributes_to_variant(attrib, id, attributes_json)
  176. end
  177. else
  178. attributes_json = @products_variant.assign_attributes_to_variant(combination, id, attributes_json)
  179. end
  180. @products_variant.attributes_json = attributes_json.to_json
  181. @products_variant.save
  182. @products_variant.generate_barcode
  183. @products_variant.save
  184. if current_user.usertype == 'G'
  185. AvailableProduct.create(product_id: @products_variant.id, pointsale_id: current_user.pointsale_id, stock: 0)
  186. end
  187. end
  188. end
  189. end
  190. end
  191. # rubocop:enable Metrics/BlockLength
  192. def assign_attributes_to_variant(attri, parent_id, attributes_json)
  193. attri_id = ActsAsTaggableOn::Tag.where("lower(name) = lower(?)", attri).select(:id).first
  194. get_context = ActsAsTaggableOn::Tagging.where(tag_id: attri_id, taggable_id: parent_id, taggable_type: 'Product').select(:context).first
  195. context = get_context.context
  196. if id != parent_id
  197. if context == "sizes"
  198. self.size_list = attri.to_s
  199. elsif context == "colors"
  200. self.color_list = attri.to_s
  201. elsif context == "styles"
  202. self.style_list = attri.to_s
  203. end
  204. end
  205. attributes_json[context] = attri.to_s
  206. attributes_json
  207. end
  208. def update_attributes_to_variants(new_sizes, new_colors, new_styles)
  209. unless new_sizes.nil?
  210. (JSON.parse new_sizes).each do |s|
  211. sizes.each do |p|
  212. next unless p.id.to_s == s["id"].to_s && p.name.to_s != s["name"].to_s
  213. # if p.id.to_s == s["id"].to_s && p.name.to_s != s["name"].to_s
  214. size_list.remove(p.name.to_s)
  215. variants = children.tagged_with(p.name.to_s, on: :sizes, any: true)
  216. variants.each do |v|
  217. v.size_list.remove(p.name.to_s)
  218. v.size_list.add(s["name"].to_s)
  219. v.save(validate: false)
  220. end
  221. size_list.add(s["name"].to_s)
  222. end
  223. end
  224. end
  225. unless new_colors.nil?
  226. (JSON.parse new_colors).each do |s|
  227. colors.each do |p|
  228. next unless p.id.to_s == s["id"].to_s && p.name.to_s != s["name"].to_s
  229. # if p.id.to_s == s["id"].to_s && p.name.to_s != s["name"].to_s
  230. color_list.remove(p.name.to_s)
  231. variants = children.tagged_with(p.name.to_s, on: :colors, any: true)
  232. variants.each do |v|
  233. v.color_list.remove(p.name.to_s)
  234. v.color_list.add(s["name"].to_s)
  235. v.save(validate: false)
  236. end
  237. color_list.add(s["name"].to_s)
  238. end
  239. end
  240. end
  241. unless new_styles.nil?
  242. (JSON.parse new_styles).each do |s|
  243. styles.each do |p|
  244. next unless p.id.to_s == s["id"].to_s && p.name.to_s != s["name"].to_s
  245. # if p.id.to_s == s["id"].to_s && p.name.to_s != s["name"].to_s
  246. style_list.remove(p.name.to_s)
  247. variants = children.tagged_with(p.name.to_s, on: :styles, any: true)
  248. variants.each do |v|
  249. v.style_list.remove(p.name.to_s)
  250. v.style_list.add(s["name"].to_s)
  251. v.save(validate: false)
  252. end
  253. style_list.add(s["name"].to_s)
  254. end
  255. end
  256. end
  257. if save(validate: false)
  258. children.each do |variant|
  259. attributes_json = {}
  260. attributes_json = variant.assign_attributes_to_variant(variant.size_list, id, attributes_json) unless variant.size_list.count.zero?
  261. attributes_json = variant.assign_attributes_to_variant(variant.color_list, id, attributes_json) unless variant.color_list.count.zero?
  262. attributes_json = variant.assign_attributes_to_variant(variant.style_list, id, attributes_json) unless variant.style_list.count.zero?
  263. variant.attributes_json = attributes_json.to_json
  264. variant.save(validate: false)
  265. end
  266. end
  267. end
  268. # rubocop:disable Metrics/BlockLength
  269. def save_new_attributes(new_sizes, new_colors, new_styles)
  270. Thread.new do
  271. combinations = Array.new
  272. attributes = Array.new
  273. unless new_sizes.nil?
  274. new_sizes.each do |s|
  275. size_list.add(s.to_s)
  276. save(validate: false)
  277. end
  278. end
  279. unless new_colors.nil?
  280. new_colors.each do |s|
  281. color_list.add(s.to_s)
  282. save(validate: false)
  283. end
  284. end
  285. unless new_styles.nil?
  286. new_styles.each do |s|
  287. style_list.add(s.to_s)
  288. save(validate: false)
  289. end
  290. end
  291. combinations = get_combinations(combinations, attributes)
  292. # self.save(:validate: false)
  293. combinations.each_with_index do |combination, index|
  294. attributes = {}
  295. if combination.is_a?(Array)
  296. combination.each do |c|
  297. attributes = assign_attributes_to_variant(c, id, attributes)
  298. end
  299. else
  300. attributes = assign_attributes_to_variant(combination, id, attributes)
  301. end
  302. next unless children.where("attributes_json = ?", attributes.to_json).select(:id).first.nil?
  303. # if children.where("attributes_json = ?", attributes.to_json).select(:id).first.nil?
  304. @products_variant = Product.new
  305. @products_variant = dup
  306. @products_variant.parent_id = id
  307. @products_variant.is_parent = false
  308. @products_variant.sku = sku + (index + 1).to_s + "A"
  309. @products_variant.category_ids = category_ids
  310. attrs_json = {}
  311. if combination.is_a?(Array)
  312. combination.each do |attrib|
  313. attrs_json = @products_variant.assign_attributes_to_variant(attrib, id, attrs_json)
  314. end
  315. else
  316. attrs_json = @products_variant.assign_attributes_to_variant(combination, id, attrs_json)
  317. end
  318. @products_variant.attributes_json = attributes.to_json
  319. @products_variant.save(validate: false)
  320. end
  321. end
  322. end
  323. # rubocop:enable Metrics/BlockLength
  324. def children
  325. Product.where("parent_id = ? and status != ? ", id, 0)
  326. end
  327. def attributes_to_hash
  328. JSON.parse attributes_json.gsub('=>', ':')
  329. end
  330. def display_attributes
  331. attributes = ""
  332. unless attributes_json.nil?
  333. attributes_to_hash.each do |attr_, value|
  334. description = I18n.t("dictionary." + attr_) + ": #{value}"
  335. attributes = attributes.blank? ? description.to_s : attributes.to_s + " " + description.to_s
  336. end
  337. end
  338. attributes
  339. end
  340. def display_attributes_receipt
  341. attributes = ""
  342. unless attributes_json.nil?
  343. attributes_to_hash.each do |_attr_, value|
  344. attributes = attributes.blank? ? value.to_s : attributes.to_s + " " + value.to_s
  345. end
  346. end
  347. attributes.upcase
  348. end
  349. def self.most_selled_products(period, user)
  350. # se envia al user porque no se puede acceder al current, esto es, para que el gerente
  351. # vea los mas vendidos de su punto de venta.
  352. all_products = Array.new
  353. if period == 'week'
  354. beg_period = Date.current.beginning_of_week
  355. end_period = Date.current.end_of_week
  356. elsif period == 'month'
  357. beg_period = Date.current.beginning_of_month
  358. end_period = Date.current.end_of_month
  359. end
  360. if user.usertype == "A" || user.usertype == "SS"
  361. 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)
  362. 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)
  363. total_sold = SalesDetail.activos.joins(:sale).where('sales.date_sale between ? and ?', beg_period, end_period).sum(:quantity)
  364. elsif user.usertype == 'G'
  365. 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)
  366. 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)
  367. total_sold = user.pointsale.sales_details.joins(:sale).where('sales.status != ? and sales.date_sale between ? and ?', 1, beg_period, end_period).sum(:quantity)
  368. end
  369. others = total_sold - total_top_products
  370. if others > 0
  371. quantities_top_products[:Otros] = others
  372. end
  373. quantities_top_products
  374. end
  375. def get_available_children(just_pointsales)
  376. children = Product.vigentes.where("parent_id = ?", id).pluck(:id)
  377. if just_pointsales
  378. AvailableProduct.where("product_id IN (?)", children).joins(:pointsale).select(:pointsale_id, :name).distinct(:pointsale_id)
  379. else
  380. AvailableProduct.where("product_id IN (?)", children)
  381. end
  382. end
  383. def generate_barcode
  384. if barcode.blank?
  385. barcode_generated = format('%07d', id)
  386. self.barcode = barcode_generated
  387. save_path = Rails.public_path.join('barcodes', "#{barcode_generated}.png")
  388. File.open(save_path, 'wb'){ |f|
  389. f.write Barby::Code39.new(barcode_generated).to_png(:height => 30, :margin => 5)
  390. }
  391. end
  392. end
  393. end