product.rb 18 KB

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