product.rb 15 KB

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