2019-01-09 12:07:31 +01:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
# API Controller for resources of Invoice and Avoir
|
2016-03-23 18:39:41 +01:00
|
|
|
class API::InvoicesController < API::ApiController
|
|
|
|
before_action :authenticate_user!
|
2019-01-09 12:07:31 +01:00
|
|
|
before_action :set_invoice, only: %i[show download]
|
2016-03-23 18:39:41 +01:00
|
|
|
|
|
|
|
def index
|
|
|
|
authorize Invoice
|
2019-01-09 12:07:31 +01:00
|
|
|
@invoices = Invoice.includes(
|
2019-05-28 16:49:36 +02:00
|
|
|
:avoir, :invoiced, :invoicing_profile, invoice_items: %i[subscription invoice_item]
|
2019-01-09 12:07:31 +01:00
|
|
|
).all.order('reference DESC')
|
2016-03-23 18:39:41 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
def download
|
|
|
|
authorize @invoice
|
2019-01-09 12:07:31 +01:00
|
|
|
send_file File.join(Rails.root, @invoice.file), type: 'application/pdf', disposition: 'attachment'
|
2016-03-23 18:39:41 +01:00
|
|
|
end
|
|
|
|
|
2016-05-31 10:02:27 +02:00
|
|
|
def list
|
|
|
|
authorize Invoice
|
|
|
|
|
|
|
|
p = params.require(:query).permit(:number, :customer, :date, :order_by, :page, :size)
|
|
|
|
|
2019-01-09 12:07:31 +01:00
|
|
|
render json: { error: 'page must be an integer' }, status: :unprocessable_entity and return unless p[:page].is_a? Integer
|
2016-05-31 10:02:27 +02:00
|
|
|
|
2019-01-09 12:07:31 +01:00
|
|
|
render json: { error: 'size must be an integer' }, status: :unprocessable_entity and return unless p[:size].is_a? Integer
|
2016-05-31 10:02:27 +02:00
|
|
|
|
2019-01-09 12:07:31 +01:00
|
|
|
order = InvoicesService.parse_order(p[:order_by])
|
|
|
|
@invoices = InvoicesService.list(
|
|
|
|
order[:order_key],
|
|
|
|
order[:direction],
|
|
|
|
p[:page],
|
|
|
|
p[:size],
|
|
|
|
number: p[:number], customer: p[:customer], date: p[:date]
|
|
|
|
)
|
2016-05-31 10:02:27 +02:00
|
|
|
end
|
|
|
|
|
2016-12-12 14:20:26 +01:00
|
|
|
# only for create refund invoices (avoir)
|
2016-03-23 18:39:41 +01:00
|
|
|
def create
|
|
|
|
authorize Invoice
|
|
|
|
invoice = Invoice.only_invoice.find(avoir_params[:invoice_id])
|
|
|
|
@avoir = invoice.build_avoir(avoir_params)
|
|
|
|
if @avoir.save
|
2017-12-13 13:16:32 +01:00
|
|
|
# when saved, expire the subscription if needed
|
2019-01-09 12:07:31 +01:00
|
|
|
@avoir.expire_subscription if @avoir.subscription_to_expire
|
2017-12-13 13:16:32 +01:00
|
|
|
# then answer the API call
|
2016-03-23 18:39:41 +01:00
|
|
|
render :avoir, status: :created
|
|
|
|
else
|
|
|
|
render json: @avoir.errors, status: :unprocessable_entity
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2019-01-09 12:07:31 +01:00
|
|
|
def avoir_params
|
|
|
|
params.require(:avoir).permit(:invoice_id, :avoir_date, :avoir_mode, :subscription_to_expire, :description,
|
|
|
|
invoice_items_ids: [])
|
|
|
|
end
|
|
|
|
|
|
|
|
def set_invoice
|
|
|
|
@invoice = Invoice.find(params[:id])
|
|
|
|
end
|
2016-03-23 18:39:41 +01:00
|
|
|
end
|