# Invoicing to 24SO
[TOC]
## Order's invoices
#### Flow
```plantuml
@startuml
start
:order is delivered;
floating note: all its bookings are completed,\n completed_at is NOT NULL
:OrdersInvoicerJob is called;
floating note: every day at 23:00
:Invoicing::OrdersInvoicerService is called;
:orders to be invoiced are filtered;
floating note
1) having invoiced_at empty
2) order_state=delivered
3) delivered before 7-day grace period
(delivered_at < (Date.today - 7.days))
end note
:orders are pushed to 24SO which returns 202;
:LogEvent object is created for every invoice \ncontaining API request and response for logging;
:order state gets changed;
floating note
order.order_state => `captured_or_invoiced`
order.invoiced_at => current_time
order.payment.state => `captured_or_invoiced`
end note
end
@enduml
```
#### Triggering
1) via UI: FRADMIN/Orders/ button "initiate invoicing to 24SO"
2) Rails console
```ruby=
# for one order
order = V2::Order.find(999)
ser = Invoicing::OrdersInvoicerService.new
ser.send(:process_invoice_for_order, order)
# for all unsent orders starting from month ago until now, except for 7-day grace period
ser = Invoicing::OrdersInvoicerService.call
```
## Doctors Compensations' invoices
#### Flow
```plantuml
@startuml
start
:BookingCompensationsEnsurerJob is called;
floating note
- for creation of compenation items
- creates compensation items 2 days \n
after booking is completed
- runs at 23:0 every day
end note
:compensation items are created;
:CompensationsInvoicerJob is called;
floating note: on 7th day of the month!
:Invoicing::CompensationsInvoicerService is called;
:compensation items to be invoiced are filtered;
floating note
1) having invoiced_at empty
2) not from data migration
3) effective_at before 7-day grace period
(delivered_at < (Date.today - 7.days))
4) effective_at on or after beginning of last month
end note
:c.items are pushed to 24SO grouped by Service Provider (1 service provider = 1 invoice);
:LogEvent object is created for every invoice \ncontaining API request and response for logging;
:compensation item invoiced_at gets set to now;
end
@enduml
```
#### Triggering
1) via UI: FRADMIN/Compensation Items/ button "initiate invoicing to 24SO"
2) Rails console
```ruby=
# the normal way
Invoicing::CompensationsInvoicerService.call
# certain subset of compensation items
service_provider = ServiceProvider.find(999)
ser = Invoicing::CompensationsInvoicerService.new
citems = ser.send(:citems_for_provider, service_provider)
citems.update_all(invoiced_at: nil)
ser.send(:process_compensation_items_batch, service_provider, citems)
```