product.rb 14 KB

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