product.rb 16 KB

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