product.rb 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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.not(status: 0).order(" products.status ASC, products.name ASC") }
  44. scope :activos, -> { where(status: 1).order("products.name ASC") }
  45. scope :activos_children, -> { activos.where(is_parent: false).order("products.name ASC") }
  46. scope :vigentes_parents, -> { vigentes.where("parent_id IS NULL") }
  47. scope :name_sku_barcode_like, ->(name) { activos.where("is_parent = ? and (name ilike ? or sku ilike ? or barcode ilike ?)", false, "%#{name}%", "%#{name}%", "%#{name}%") }
  48. 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}%") }
  49. # para special_prices
  50. scope :name_sku_barcode_like_sp, ->(name) { activos.where("is_parent = ? and (name ilike ? or sku ilike ? or barcode ilike ?)", true, "%#{name}%", "%#{name}%", "%#{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. available = get_available_in_pointsale(pointsale_id)
  104. if available.present? && available.price_sale.present?
  105. available.price_sale
  106. else
  107. price_sale
  108. end
  109. end
  110. def pointsales_prices
  111. AvailableProduct.where("product_id = ? and price_sale IS NOT NULL", id)
  112. end
  113. def variants_attributes
  114. ActsAsTaggableOn::Tagging.where(taggable_id: id, taggable_type: 'Product').distinct(:context).select(:context)
  115. end
  116. def get_combinations(combinations, attributes)
  117. if presentation
  118. ##--- crear el array de los arrays de atributos
  119. if size_list.count > 0
  120. attributes << size_list
  121. end
  122. if color_list.count > 0
  123. attributes << color_list
  124. end
  125. if style_list.count > 0
  126. attributes << style_list
  127. end
  128. ##--- verificar que atributos tenga mas de una categoria
  129. if attributes.count > 1
  130. ##--- Making combinations from arrays
  131. first_array, *rest_of_arrays = attributes
  132. combinations = first_array.product(*rest_of_arrays)
  133. else
  134. attributes[0].each do |attribute|
  135. combinations << attribute
  136. end
  137. end
  138. combinations
  139. end
  140. end
  141. # rubocop:disable Metrics/BlockLength
  142. def save_variants(current_user)
  143. Thread.new do
  144. combinations = Array.new
  145. attributes = Array.new
  146. combinations = get_combinations(combinations, attributes)
  147. ##--- recorrer combinaciones para crear las variantes de productos
  148. unless combinations.nil?
  149. combinations.each_with_index do |combination, index|
  150. @products_variant = Product.new
  151. @products_variant = dup
  152. @products_variant.parent_id = id
  153. @products_variant.is_parent = false
  154. @products_variant.sku = sku + (index + 1).to_s + "A"
  155. @products_variant.category_ids = category_ids
  156. attributes_json = {}
  157. if combination.is_a?(Array)
  158. combination.each do |attrib|
  159. attributes_json = @products_variant.assign_attributes_to_variant(attrib, id, attributes_json)
  160. end
  161. else
  162. attributes_json = @products_variant.assign_attributes_to_variant(combination, id, attributes_json)
  163. end
  164. @products_variant.attributes_json = attributes_json.to_json
  165. @products_variant.save
  166. if current_user.usertype == 'G'
  167. AvailableProduct.create(product_id: @products_variant.id, pointsale_id: current_user.pointsale_id, stock: 0)
  168. end
  169. end
  170. end
  171. end
  172. end
  173. # rubocop:enable Metrics/BlockLength
  174. def assign_attributes_to_variant(attri, parent_id, attributes_json)
  175. attri_id = ActsAsTaggableOn::Tag.where("lower(name) = lower(?)", attri).select(:id).first
  176. get_context = ActsAsTaggableOn::Tagging.where(tag_id: attri_id, taggable_id: parent_id, taggable_type: 'Product').select(:context).first
  177. context = get_context.context
  178. if id != parent_id
  179. if context == "sizes"
  180. self.size_list = attri.to_s
  181. elsif context == "colors"
  182. self.color_list = attri.to_s
  183. elsif context == "styles"
  184. self.style_list = attri.to_s
  185. end
  186. end
  187. attributes_json[context] = attri.to_s
  188. attributes_json
  189. end
  190. def update_attributes_to_variants(new_sizes, new_colors, new_styles)
  191. unless new_sizes.nil?
  192. (JSON.parse new_sizes).each do |s|
  193. sizes.each do |p|
  194. next unless p.id.to_s == s["id"].to_s && p.name.to_s != s["name"].to_s
  195. # if p.id.to_s == s["id"].to_s && p.name.to_s != s["name"].to_s
  196. size_list.remove(p.name.to_s)
  197. variants = children.tagged_with(p.name.to_s, on: :sizes, any: true)
  198. variants.each do |v|
  199. v.size_list.remove(p.name.to_s)
  200. v.size_list.add(s["name"].to_s)
  201. v.save(validate: false)
  202. end
  203. size_list.add(s["name"].to_s)
  204. end
  205. end
  206. end
  207. unless new_colors.nil?
  208. (JSON.parse new_colors).each do |s|
  209. colors.each do |p|
  210. next unless p.id.to_s == s["id"].to_s && p.name.to_s != s["name"].to_s
  211. # if p.id.to_s == s["id"].to_s && p.name.to_s != s["name"].to_s
  212. color_list.remove(p.name.to_s)
  213. variants = children.tagged_with(p.name.to_s, on: :colors, any: true)
  214. variants.each do |v|
  215. v.color_list.remove(p.name.to_s)
  216. v.color_list.add(s["name"].to_s)
  217. v.save(validate: false)
  218. end
  219. color_list.add(s["name"].to_s)
  220. end
  221. end
  222. end
  223. unless new_styles.nil?
  224. (JSON.parse new_styles).each do |s|
  225. styles.each do |p|
  226. next unless p.id.to_s == s["id"].to_s && p.name.to_s != s["name"].to_s
  227. # if p.id.to_s == s["id"].to_s && p.name.to_s != s["name"].to_s
  228. style_list.remove(p.name.to_s)
  229. variants = children.tagged_with(p.name.to_s, on: :styles, any: true)
  230. variants.each do |v|
  231. v.style_list.remove(p.name.to_s)
  232. v.style_list.add(s["name"].to_s)
  233. v.save(validate: false)
  234. end
  235. style_list.add(s["name"].to_s)
  236. end
  237. end
  238. end
  239. if save(validate: false)
  240. children.each do |variant|
  241. attributes_json = {}
  242. attributes_json = variant.assign_attributes_to_variant(variant.size_list, id, attributes_json) unless variant.size_list.count.zero?
  243. attributes_json = variant.assign_attributes_to_variant(variant.color_list, id, attributes_json) unless variant.color_list.count.zero?
  244. attributes_json = variant.assign_attributes_to_variant(variant.style_list, id, attributes_json) unless variant.style_list.count.zero?
  245. variant.attributes_json = attributes_json.to_json
  246. variant.save(validate: false)
  247. end
  248. end
  249. end
  250. # rubocop:disable Metrics/BlockLength
  251. def save_new_attributes(new_sizes, new_colors, new_styles)
  252. Thread.new do
  253. combinations = Array.new
  254. attributes = Array.new
  255. unless new_sizes.nil?
  256. new_sizes.each do |s|
  257. size_list.add(s.to_s)
  258. save(validate: false)
  259. end
  260. end
  261. unless new_colors.nil?
  262. new_colors.each do |s|
  263. color_list.add(s.to_s)
  264. save(validate: false)
  265. end
  266. end
  267. unless new_styles.nil?
  268. new_styles.each do |s|
  269. style_list.add(s.to_s)
  270. save(validate: false)
  271. end
  272. end
  273. combinations = get_combinations(combinations, attributes)
  274. # self.save(:validate: false)
  275. combinations.each_with_index do |combination, index|
  276. attributes = {}
  277. if combination.is_a?(Array)
  278. combination.each do |c|
  279. attributes = assign_attributes_to_variant(c, id, attributes)
  280. end
  281. else
  282. attributes = assign_attributes_to_variant(combination, id, attributes)
  283. end
  284. next unless children.where("attributes_json = ?", attributes.to_json).select(:id).first.nil?
  285. # if children.where("attributes_json = ?", attributes.to_json).select(:id).first.nil?
  286. @products_variant = Product.new
  287. @products_variant = dup
  288. @products_variant.parent_id = id
  289. @products_variant.is_parent = false
  290. @products_variant.sku = sku + (index + 1).to_s + "A"
  291. @products_variant.category_ids = category_ids
  292. attrs_json = {}
  293. if combination.is_a?(Array)
  294. combination.each do |attrib|
  295. attrs_json = @products_variant.assign_attributes_to_variant(attrib, id, attrs_json)
  296. end
  297. else
  298. attrs_json = @products_variant.assign_attributes_to_variant(combination, id, attrs_json)
  299. end
  300. @products_variant.attributes_json = attributes.to_json
  301. @products_variant.save(validate: false)
  302. end
  303. end
  304. end
  305. # rubocop:enable Metrics/BlockLength
  306. def children
  307. Product.where("parent_id = ? and status != 0 ", id)
  308. end
  309. def attributes_to_hash
  310. JSON.parse attributes_json.gsub('=>', ':')
  311. end
  312. def display_attributes
  313. attributes = ""
  314. unless attributes_json.nil?
  315. attributes_to_hash.each do |attr_, value|
  316. description = I18n.t("dictionary." + attr_) + ": #{value}"
  317. attributes = attributes.blank? ? description.to_s : attributes.to_s + " " + description.to_s
  318. end
  319. end
  320. attributes
  321. end
  322. def display_attributes_receipt
  323. attributes = ""
  324. unless attributes_json.nil?
  325. attributes_to_hash.each do |_attr_, value|
  326. attributes = attributes.blank? ? value.to_s : attributes.to_s + " " + value.to_s
  327. end
  328. end
  329. attributes.upcase
  330. end
  331. def self.most_selled_products(period, user)
  332. # se envia al user porque no se puede acceder al current, esto es, para que el gerente
  333. # vea los mas vendidos de su punto de venta.
  334. all_products = Array.new
  335. if period == 'week'
  336. beg_period = Date.current.beginning_of_week
  337. end_period = Date.current.end_of_week
  338. elsif period == 'month'
  339. beg_period = Date.current.beginning_of_month
  340. end_period = Date.current.end_of_month
  341. end
  342. if user.usertype == "A" || user.usertype == "SS"
  343. 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)
  344. 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)
  345. total_sold = SalesDetail.activos.joins(:sale).where('sales.date_sale between ? and ?', beg_period, end_period).sum(:quantity)
  346. elsif user.usertype == 'G'
  347. 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)
  348. 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)
  349. total_sold = user.pointsale.sales_details.joins(:sale).where('sales.status != ? and sales.date_sale between ? and ?', 1, beg_period, end_period).sum(:quantity)
  350. end
  351. others = total_sold - total_top_products
  352. if others > 0
  353. quantities_top_products[:Otros] = others
  354. end
  355. quantities_top_products
  356. end
  357. def get_available_children(just_pointsales)
  358. children = Product.vigentes.where("parent_id = ?", id).pluck(:id)
  359. if just_pointsales
  360. AvailableProduct.where("product_id IN (?)", children).joins(:pointsale).select(:pointsale_id, :name).distinct(:pointsale_id)
  361. else
  362. AvailableProduct.where("product_id IN (?)", children)
  363. end
  364. end
  365. end