products_controller.rb 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. class ProductsController < ApplicationController
  2. ##--- Abilities
  3. load_and_authorize_resource
  4. ##--- Breadcrum_rails
  5. add_breadcrumb I18n.t("breadcrumbs." + controller_name), :products_path, only: [:index, :new, :show, :edit]
  6. add_breadcrumb "Nuevo " + I18n.t("breadcrumbs." + controller_name).singularize, :new_product_path, only: :new
  7. add_breadcrumb "Detalle del " + I18n.t("breadcrumbs." + controller_name).singularize, :product_path, only: :show
  8. add_breadcrumb "Editar " + I18n.t("breadcrumbs." + controller_name).singularize, :edit_product_path, only: :edit
  9. add_breadcrumb "Seguimiento de productos", :product_track_path, only: :product_track
  10. before_action :set_product, only: [:show, :edit, :update, :destroy]
  11. before_action :set_product_id, only: [:list_prices, :list_prices_variants, :edit_variants, :update_variants, :edit_from_purchase, :update_from_purchase, :update_status]
  12. before_action :get_categories, only: [:create, :update]
  13. before_action :get_attrs, only: [:show, :edit, :update]
  14. before_action :get_filters, only: [:index, :show, :edit, :new]
  15. skip_before_action :get_categories, only: [:edit_from_purchase]
  16. # GET /products
  17. # GET /products.json
  18. def index
  19. respond_to do |format|
  20. format.html
  21. format.json { render json: ProductsDatatable.new(view_context, current_user) }
  22. end
  23. end
  24. def list_prices
  25. if @product.presentation
  26. # @available_products = @product.get_available_children(false)
  27. @pointsales = @product.get_available_children(true)
  28. end
  29. end
  30. def list_prices_variants
  31. children = Product.where("parent_id = ? and status != 0 ", params[:product_id]).pluck(:id)
  32. @variants = AvailableProduct.where("pointsale_id = ? and product_id IN (?)", params[:pointsale_id], children).includes(:product)
  33. @variants_json = Array.new
  34. @variants.each do |v|
  35. @variants_json.push(name: v.product.sku + " " + v.product.name + " <br><small>" + v.product.display_attributes + "</small>", price: v.product.get_price_sale(params[:pointsale_id]), available_product_id: v.id)
  36. end
  37. render json: @variants_json.to_json
  38. end
  39. def edit_variants; end
  40. def update_variants
  41. if @product.is_parent
  42. @product.update_attributes_to_variants(params[:new_size_list], params[:new_color_list], params[:new_style_list])
  43. @product.save_new_attributes(params[:mynewsizes], params[:mynewcolors], params[:mynewstyles])
  44. end
  45. respond_to do |format|
  46. if @product.save(validate: false)
  47. format.html { redirect_to products_url, success: 'Se modificaron las variantes del producto ' + @product.sku + ' - ' + @product.name + '.' }
  48. format.json { render :show, status: :ok, location: @product }
  49. else
  50. format.html { render :edit_variants }
  51. format.json { render json: @product.errors, status: :unprocessable_entity }
  52. end
  53. end
  54. end
  55. # GET /products/1
  56. # GET /products/1.json
  57. def show; end
  58. # GET /products/new
  59. def new
  60. @product = Product.new
  61. # Default unit is 'Pieza'
  62. @product.unit = Unit.where(unit: 'Pieza').first
  63. if params[:remoto].present?
  64. @remoto = params[:remoto]
  65. @pointsale = params[:pointsale]
  66. @warehouse = params[:warehouse]
  67. @supplier = params[:supplier]
  68. @exchange = params[:exchange]
  69. end
  70. @product.price_base = nil
  71. @product.price_sale = nil
  72. end
  73. # GET /products/1/edit
  74. def edit
  75. has_variants = @product.children.any?
  76. @with_presentation = has_variants ? true : false # si aun no tiene variantes, permitir clickear el switch
  77. end
  78. # POST /products
  79. # POST /products.json
  80. # rubocop:disable Metrics/BlockLength
  81. def create
  82. @product = Product.new(product_params)
  83. if @product.presentation
  84. @product.is_parent = true
  85. end
  86. message = 'El producto ' + @product.sku + ' fue creado.'
  87. @product.audit_comment = message
  88. respond_to do |format|
  89. if @product.save
  90. unless @product.is_parent?
  91. @product.generate_barcode
  92. @product.save
  93. end
  94. @product.save_variants(current_user)
  95. ##--- Para cuando se agrega un producto desde purchase
  96. if params[:remoto] == "true"
  97. ##--- Guardar pre_purchase
  98. @pre_purchases = Array.new
  99. if @product.presentation && @product.is_parent
  100. @product.children.each do |variant|
  101. save_pre_purchase(variant)
  102. set_available
  103. @pre_purchases << @pre_purchase
  104. end
  105. else
  106. save_pre_purchase(@product)
  107. set_available
  108. @pre_purchases << @pre_purchase
  109. end
  110. format.json { head :no_content }
  111. format.js
  112. else
  113. # crear available product para el p.v, cuando es sin variantes
  114. if current_user.usertype == 'G' && !@product.presentation && !@product.is_parent
  115. AvailableProduct.create(product_id: @product.id, pointsale_id: current_user.pointsale_id, stock: 0)
  116. end
  117. format.html { redirect_to products_url, success: message }
  118. format.json { render :show, status: :created, location: @product }
  119. end
  120. else
  121. format.html { render :new }
  122. format.json { render json: @product.errors, status: :unprocessable_entity }
  123. end
  124. end
  125. end
  126. # rubocop:enable Metrics/BlockLength
  127. # PATCH/PUT /products/1
  128. # PATCH/PUT /products/1.json
  129. def update
  130. respond_to do |format|
  131. @product.skip_sku_validation = true
  132. @product.is_parent = params[:product][:presentation] == 'true' ? true : false
  133. message = 'El producto ' + @product.sku + ' fue modificado.'
  134. @product.audit_comment = message
  135. if @product.update(product_params)
  136. if @product.is_parent
  137. @product.children.each_with_index do |variant, index|
  138. variant.skip_sku_validation = true
  139. params_to_edit = product_params
  140. params_to_edit[:sku] = @product.sku + (index + 1).to_s + "A"
  141. variant.update_attributes(params_to_edit)
  142. end
  143. end
  144. format.html { redirect_to products_url, success: message }
  145. format.json { render :show, status: :ok, location: @product }
  146. else
  147. format.html { render :edit }
  148. format.json { render json: @product.errors, status: :unprocessable_entity }
  149. end
  150. end
  151. end
  152. def edit_from_purchase
  153. purchase_in_dollars = params[:is_in_dollars]
  154. exchange = params[:exchange].to_f
  155. if purchase_in_dollars == "true"
  156. @product.price_base_dollars = params[:product][:price_base].to_f
  157. price_in_peso = @product.price_base_dollars * exchange
  158. @product.price_base = @product.price_base.present? ? price_in_peso : nil
  159. @suggested_price_sale = (price_in_peso * (@pos_config.gain_margin / 100)) + price_in_peso
  160. else
  161. @product.price_base = params[:product][:price_base].to_f
  162. price_in_dollars = @product.price_base / exchange if exchange != 0
  163. @product.price_base_dollars = @product.price_base_dollars.present? ? price_in_dollars : nil
  164. @suggested_price_sale = (@product.price_base * (@pos_config.gain_margin / 100)) + @product.price_base
  165. end
  166. @suggested_price_sale = 0 if @suggested_price_sale.nil?
  167. respond_to do |format|
  168. @product.audit_comment = 'El producto ' + @product.sku + ' fue modificado.'
  169. @product.save
  170. format.json { head :no_content }
  171. format.js
  172. end
  173. end
  174. def update_from_purchase
  175. ##--- Si el producto es hijo, sacar el registro del padre para cambiar todos los valores
  176. unless @product.parent_id.nil?
  177. @product = Product.find(@product.parent_id)
  178. end
  179. @product.price_base = params[:product][:price_base].to_f
  180. @product.price_sale = params[:product][:price_sale].to_f
  181. message = "Se ha modificado el precio de venta base del producto " + @product.name
  182. respond_to do |format|
  183. if @product.save
  184. @product.children.each do |variant|
  185. variant.update_attributes(product_params)
  186. variant.save
  187. end
  188. @product.audit_comment = message
  189. format.json { head :no_content }
  190. format.js { flash[:success] = message }
  191. else
  192. @suggested_price_sale = params[:suggested_price_sale].to_f
  193. format.js { render :edit_from_purchase }
  194. format.json { render json: @available_product.errors, status: :unprocessable_entity }
  195. end
  196. end
  197. end
  198. def update_status
  199. product = @product
  200. if product.active?
  201. product.status = 2
  202. elsif product.inactive?
  203. product.status = 1
  204. end
  205. if product.presentation
  206. product.children.each do |pv|
  207. pv.status = product.status
  208. pv.save(validate: false)
  209. end
  210. end
  211. respond_to do |format|
  212. message = "El producto " + product.name + " fue " + (product.active? ? "activado" : "desactivado") + "."
  213. product.audit_comment = message
  214. if product.save(validate: false)
  215. format.html { redirect_to products_url, warning: message }
  216. # format.json { render :show, status: :ok, location: @pointsale }
  217. format.json { head :no_content }
  218. else
  219. format.html { redirect_to products_url }
  220. format.json { render json: @product.errors, status: :unprocessable_entity }
  221. end
  222. end
  223. end
  224. # DELETE /products/1
  225. # DELETE /products/1.json
  226. def destroy
  227. respond_to do |format|
  228. message = "El producto " + @product.name + " fue eliminado."
  229. @product.audit_comment = message
  230. if @product.update_attributes(status: 0)
  231. if @product.is_parent
  232. @product.children.each_with_index do |variant|
  233. variant.update_attributes(status: 0)
  234. variant.save
  235. end
  236. end
  237. format.html { redirect_to products_url, warning: message }
  238. format.json { head :no_content }
  239. else
  240. format.html { redirect_to products_url }
  241. format.json { render json: @product.errors, status: :unprocessable_entity }
  242. end
  243. end
  244. end
  245. def validate_unique_barcode
  246. respond_to do |format|
  247. @product = Product.find_by(barcode: params[:barcode])
  248. if @product.blank?
  249. format.js { head :ok }
  250. else
  251. format.js
  252. end
  253. end
  254. end
  255. def product_track
  256. #--Seguimiento de productos
  257. # @sales = SalesDetail.new
  258. product_id = params[:product_id]
  259. pointsale_id = params[:pointsale_id]
  260. start_date = DateTime.parse(params[:start_date]) if params[:start_date].present?
  261. end_date = DateTime.parse(params[:end_date]) if params[:end_date].present?
  262. if product_id.present?
  263. respond_to do |format|
  264. @sales = pointsale_id.present? ? Pointsale.find(pointsale_id).sales_details.includes(:sale).where('sales.status > 1 and sales_details.product_id = ? and sales.date_sale BETWEEN ? AND ?', product_id, start_date, end_date).order("sales_details.id DESC") : SalesDetail.find_by_sql("SELECT sales_details.* FROM sales_details INNER JOIN sales ON sales_details.sale_id = sales.id INNER JOIN open_cash_registers ON sales.open_cash_register_id = open_cash_registers.id INNER JOIN cash_registers ON open_cash_registers.cash_register_id = cash_registers.id WHERE ( sales.status > 1 AND sales_details.product_id = #{product_id} and sales.date_sale BETWEEN '#{start_date}' AND '#{end_date}') ORDER BY sales_details.ID DESC")
  265. @purchases = pointsale_id.present? ? PurchaseDetail.joins(:purchase).where('purchases.pointsale_id = ? AND purchases.status != 1 and purchase_details.product_id = ? and purchases.purchase_date BETWEEN ? AND ?', pointsale_id, product_id, start_date, end_date).order('purchase_details.id DESC') : PurchaseDetail.find_by_sql("SELECT purchase_details.* FROM purchase_details INNER JOIN purchases ON purchase_details.purchase_id = purchases.id WHERE ( purchases.status != 1 AND purchase_details.product_id = #{product_id} and purchases.purchase_date BETWEEN '#{start_date}' AND '#{end_date}') ORDER BY purchase_details.ID DESC")
  266. @total_quantity = pointsale_id.present? ? @sales.sum(:quantity) : ActiveRecord::Base.connection.select_value("SELECT SUM(quantity) as quantity FROM sales LEFT OUTER JOIN sales_details ON sales_details.sale_id = sales.id WHERE (sales.status > 1 and sales_details.product_id = #{product_id} and sales.date_sale BETWEEN '#{start_date}' AND '#{end_date}')")
  267. @total_quantity_purchases = pointsale_id.present? ? @purchases.sum(:quantity) : ActiveRecord::Base.connection.select_value("SELECT SUM(quantity) as quantity FROM purchases LEFT OUTER JOIN purchase_details ON purchase_details.purchase_id = purchases.id WHERE (purchases.status != 1 and purchase_details.product_id = #{product_id} and purchases.purchase_date BETWEEN '#{start_date}' AND '#{end_date}')")
  268. @total_sales = pointsale_id.present? ? @sales.sum(:total) : ActiveRecord::Base.connection.select_value("SELECT SUM(sales.total) as total FROM sales LEFT OUTER JOIN sales_details ON sales_details.sale_id = sales.id WHERE (sales.status > 1 and sales_details.product_id = #{product_id})")
  269. format.js
  270. end
  271. end
  272. end
  273. def labels_list
  274. @product = Product.find(params[:product_id])
  275. if @product.presentation
  276. @pointsales = @product.get_available_children(true)
  277. end
  278. end
  279. def print_labels
  280. @products = JSON.parse params[:products]
  281. @pointsale_id = params[:pointsale_id]
  282. @products.each do |obj|
  283. obj['product'] = Product.find(obj['id'])
  284. obj['price'] = @pointsale_id.present? ? obj['product'].get_price_sale(@pointsale_id) : obj['product'].price_sale
  285. end
  286. file_name = "etiquetas_#{Time.now.to_i}"
  287. pdf = render_to_string pdf: file_name, template: "products/print_labels.pdf.erb", layout: 'labels.html.erb', locals: { objs: @products }, show_as_html: params.key?('debug'), page_width: '62mm', page_height: '300mm'
  288. save_path = Rails.public_path.join("pdfs", "#{file_name}.pdf")
  289. File.open(save_path, 'wb') do |file|
  290. file << pdf
  291. end
  292. respond_to do |format|
  293. format.js { render action: "print_labels", locals: { pdf_path: "pdfs/#{file_name}.pdf" } }
  294. end
  295. end
  296. private
  297. # Use callbacks to share common setup or constraints between actions.
  298. def set_product
  299. @product = Product.find(params[:id])
  300. end
  301. def set_product_id
  302. @product = Product.find(params[:product_id])
  303. end
  304. def get_filters
  305. @current_page = params[:current_page].blank? ? 1 : params[:current_page]
  306. @filter = params[:filter]
  307. end
  308. # Never trust parameters from the scary internet, only allow the white list through.
  309. def product_params
  310. params.require(:product).permit(:sku, :name, :description, :price_base, :price_sale, :img_product, :img_product_cache, :presentation, :inventory, :unit_id, :content, :status, :categorias, :category_ids, :include_purchase_tax, :include_sale_tax, :barcode, :is_in_dollars, :price_base_dollars, size_list: [], color_list: [], style_list: [], available_products_attributes: [:id, :price_sale])
  311. end
  312. def get_categories
  313. @categories = Array.new
  314. unless params[:product][:category_ids].blank?
  315. @categories << Category.find(params[:product][:category_ids])
  316. @product.categories = @categories
  317. end
  318. end
  319. def save_pre_purchase(product)
  320. @pre_purchase = PrePurchase.new
  321. @pre_purchase.supplier_id = params[:supplier]
  322. @pre_purchase.pointsale_id = params[:pointsale] if params[:pointsale].present?
  323. @pre_purchase.warehouse_id = params[:warehouse] if params[:warehouse].present?
  324. @pre_purchase.exchange = params[:exchange] if params[:exchange].present?
  325. @pre_purchase.user_id = current_user.id
  326. @pre_purchase.product_id = product.id
  327. @pre_purchase.quantity = 1
  328. @pre_purchase.get_totals
  329. @pre_purchase.save
  330. end
  331. def set_available
  332. ##--- agregar a productos disponibles ya sea punto de venta o almacen
  333. if params[:pointsale].present?
  334. available_product = AvailableProduct.new
  335. available_product.pointsale_id = @pre_purchase.pointsale_id
  336. else
  337. available_product = WarehouseStock.new
  338. available_product.warehouse_id = @pre_purchase.warehouse_id
  339. end
  340. available_product.product_id = @pre_purchase.product_id
  341. available_product.stock_min = params[:stock_min]
  342. available_product.stock_max = params[:stock_max]
  343. available_product.save
  344. end
  345. def get_attrs
  346. @attrs = Array.new
  347. @product.variants_attributes.each do |attri|
  348. @attrs << attri.context
  349. end
  350. end
  351. end