product.rb 18 KB

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