product.rb 15 KB

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