docs
0
# Billing & Financial Management
1
2
Comprehensive billing system with invoice generation, quotations, credit notes, sales orders, and financial document workflows. Includes PDF generation, email integration, and payment tracking.
3
4
## Capabilities
5
6
### Invoice Management
7
8
Invoice creation and management for billing customers.
9
10
```python { .api }
11
class Invoice(CremeEntity):
12
"""
13
Invoice entity for billing customers with line items and tax calculations.
14
15
Attributes:
16
- name: str, invoice reference/number
17
- number: int, sequential invoice number
18
- issuing_date: DateField, invoice issue date
19
- expiration_date: DateField, payment due date
20
- discount: DecimalField, overall discount percentage
21
- additional_info: TextField, additional notes
22
- payment_terms: TextField, payment terms and conditions
23
- payment_type: int, payment method
24
- currency: ForeignKey, invoice currency
25
- total_vat: DecimalField, total VAT amount
26
- total_no_vat: DecimalField, subtotal before VAT
27
- status: ForeignKey, invoice status
28
- buyers_order_number: str, customer purchase order reference
29
- source: ForeignKey, related quote or sales order
30
31
Methods:
32
- get_absolute_url(): Get invoice detail URL
33
- get_total(): Calculate total amount including VAT
34
- get_total_with_tax(): Get total with all taxes
35
- get_lines(): Get invoice line items
36
- generate_number(): Generate sequential invoice number
37
- build_pdf(): Generate PDF document
38
- send_email(): Email invoice to customer
39
"""
40
41
def get_invoice_model():
42
"""
43
Get the active Invoice model class from settings.
44
45
Returns:
46
type[Invoice]: The configured invoice model class
47
48
Example:
49
InvoiceModel = get_invoice_model()
50
invoice = InvoiceModel.objects.create(
51
name="INV-2023-001",
52
issuing_date=date.today()
53
)
54
"""
55
```
56
57
### Quote Management
58
59
Quotation system for price estimates and proposals.
60
61
```python { .api }
62
class Quote(CremeEntity):
63
"""
64
Quotation entity for providing price estimates to prospects.
65
66
Attributes:
67
- name: str, quote reference/number
68
- number: int, sequential quote number
69
- issuing_date: DateField, quote creation date
70
- expiration_date: DateField, quote expiration date
71
- acceptation_date: DateField, date quote was accepted
72
- discount: DecimalField, overall discount percentage
73
- additional_info: TextField, additional notes
74
- payment_terms: TextField, payment terms
75
- currency: ForeignKey, quote currency
76
- total_vat: DecimalField, total VAT amount
77
- total_no_vat: DecimalField, subtotal before VAT
78
- status: ForeignKey, quote status
79
80
Methods:
81
- get_absolute_url(): Get quote detail URL
82
- get_total(): Calculate total amount
83
- convert_to_invoice(): Convert accepted quote to invoice
84
- convert_to_sales_order(): Convert to sales order
85
- is_expired(): Check if quote has expired
86
- accept(): Mark quote as accepted
87
"""
88
89
def get_quote_model():
90
"""
91
Get the active Quote model class from settings.
92
93
Returns:
94
type[Quote]: The configured quote model class
95
"""
96
```
97
98
### Credit Note Management
99
100
Credit note system for refunds and billing corrections.
101
102
```python { .api }
103
class CreditNote(CremeEntity):
104
"""
105
Credit note entity for refunds and billing corrections.
106
107
Attributes:
108
- name: str, credit note reference/number
109
- number: int, sequential credit note number
110
- issuing_date: DateField, issue date
111
- discount: DecimalField, discount percentage
112
- additional_info: TextField, reason for credit
113
- currency: ForeignKey, currency
114
- total_vat: DecimalField, total VAT amount
115
- total_no_vat: DecimalField, subtotal before VAT
116
- status: ForeignKey, credit note status
117
118
Methods:
119
- get_absolute_url(): Get credit note detail URL
120
- get_total(): Calculate total credit amount
121
- apply_to_invoice(invoice): Apply credit to specific invoice
122
"""
123
124
def get_creditnote_model():
125
"""
126
Get the active CreditNote model class from settings.
127
128
Returns:
129
type[CreditNote]: The configured credit note model class
130
"""
131
```
132
133
### Sales Order Management
134
135
Sales order processing between quotes and invoices.
136
137
```python { .api }
138
class SalesOrder(CremeEntity):
139
"""
140
Sales order entity for managing confirmed orders before invoicing.
141
142
Attributes:
143
- name: str, sales order reference/number
144
- number: int, sequential order number
145
- issuing_date: DateField, order creation date
146
- expected_delivery_date: DateField, expected delivery
147
- discount: DecimalField, discount percentage
148
- additional_info: TextField, order notes
149
- payment_terms: TextField, payment terms
150
- currency: ForeignKey, order currency
151
- total_vat: DecimalField, total VAT amount
152
- total_no_vat: DecimalField, subtotal before VAT
153
- status: ForeignKey, order status
154
155
Methods:
156
- get_absolute_url(): Get sales order detail URL
157
- get_total(): Calculate total order amount
158
- convert_to_invoice(): Convert to invoice
159
- ship(): Mark order as shipped
160
- complete(): Mark order as completed
161
"""
162
163
def get_salesorder_model():
164
"""
165
Get the active SalesOrder model class from settings.
166
167
Returns:
168
type[SalesOrder]: The configured sales order model class
169
"""
170
```
171
172
### Line Items
173
174
Product and service line items for billing documents.
175
176
```python { .api }
177
class ProductLine(CremeEntity):
178
"""
179
Product line item for billing documents.
180
181
Attributes:
182
- on_the_fly_item: str, custom product description
183
- comment: TextField, line item notes
184
- quantity: DecimalField, item quantity
185
- unit_price: DecimalField, price per unit
186
- unit: str, unit of measurement
187
- discount: DecimalField, line discount percentage
188
- discount_unit: int, discount type (percentage/amount)
189
- vat_value: ForeignKey, VAT rate
190
- related_document: GenericForeignKey, parent billing document
191
- related_item: ForeignKey, linked product entity
192
193
Methods:
194
- get_price(): Calculate line total before VAT
195
- get_price_inclusive(): Calculate line total with VAT
196
- get_raw_price(): Get base price before discounts
197
- __str__(): String representation
198
"""
199
200
class ServiceLine(CremeEntity):
201
"""
202
Service line item for billing documents.
203
204
Attributes:
205
- on_the_fly_item: str, custom service description
206
- comment: TextField, line item notes
207
- quantity: DecimalField, service quantity
208
- unit_price: DecimalField, price per unit
209
- unit: str, unit of measurement
210
- discount: DecimalField, line discount percentage
211
- discount_unit: int, discount type
212
- vat_value: ForeignKey, VAT rate
213
- related_document: GenericForeignKey, parent billing document
214
- related_item: ForeignKey, linked service entity
215
216
Methods:
217
- get_price(): Calculate line total before VAT
218
- get_price_inclusive(): Calculate line total with VAT
219
- get_raw_price(): Get base price before discounts
220
"""
221
```
222
223
### Status Management
224
225
Status tracking for billing documents.
226
227
```python { .api }
228
class InvoiceStatus(CremeModel):
229
"""
230
Status options for invoices.
231
232
Attributes:
233
- name: str, status name
234
- color: str, display color code
235
- order: int, display order
236
- is_default: bool, default status flag
237
238
Common Statuses:
239
- Draft, Pending, Sent, Paid, Overdue, Cancelled
240
"""
241
242
class QuoteStatus(CremeModel):
243
"""
244
Status options for quotes.
245
246
Attributes:
247
- name: str, status name
248
- color: str, display color code
249
- order: int, display order
250
- is_default: bool, default status flag
251
252
Common Statuses:
253
- Draft, Sent, Accepted, Rejected, Expired
254
"""
255
256
class SalesOrderStatus(CremeModel):
257
"""
258
Status options for sales orders.
259
260
Common Statuses:
261
- Pending, Confirmed, Processing, Shipped, Delivered, Cancelled
262
"""
263
264
class CreditNoteStatus(CremeModel):
265
"""
266
Status options for credit notes.
267
268
Common Statuses:
269
- Draft, Issued, Applied, Cancelled
270
"""
271
```
272
273
### Payment Terms
274
275
Payment terms and conditions management.
276
277
```python { .api }
278
class PaymentTerms(CremeModel):
279
"""
280
Payment terms templates for billing documents.
281
282
Attributes:
283
- name: str, terms name
284
- description: TextField, detailed terms text
285
- is_default: bool, default terms flag
286
287
Methods:
288
- __str__(): Return terms name
289
"""
290
291
class SettlementTerms(CremeModel):
292
"""
293
Settlement terms for payment conditions.
294
295
Attributes:
296
- name: str, settlement terms name
297
298
Examples:
299
- "Net 30", "Due on receipt", "2/10 Net 30"
300
"""
301
```
302
303
## Usage Examples
304
305
### Creating Invoices
306
307
```python
308
from creme.billing import get_invoice_model
309
from creme.billing.models import InvoiceStatus, ProductLine
310
from datetime import date, timedelta
311
312
InvoiceModel = get_invoice_model()
313
314
# Create basic invoice
315
invoice = InvoiceModel.objects.create(
316
name="INV-2023-001",
317
issuing_date=date.today(),
318
expiration_date=date.today() + timedelta(days=30),
319
currency=default_currency,
320
status=InvoiceStatus.objects.get(name="Draft")
321
)
322
323
# Add product lines
324
ProductLine.objects.create(
325
related_document=invoice,
326
on_the_fly_item="Web Development Services",
327
quantity=40,
328
unit_price=75.00,
329
unit="hours",
330
vat_value=default_vat
331
)
332
333
ProductLine.objects.create(
334
related_document=invoice,
335
on_the_fly_item="Hosting Setup",
336
quantity=1,
337
unit_price=200.00,
338
unit="service",
339
discount=10.0, # 10% discount
340
vat_value=default_vat
341
)
342
```
343
344
### Creating Quotes
345
346
```python
347
from creme.billing import get_quote_model
348
from creme.billing.models import QuoteStatus
349
350
QuoteModel = get_quote_model()
351
352
# Create quote
353
quote = QuoteModel.objects.create(
354
name="QUO-2023-001",
355
issuing_date=date.today(),
356
expiration_date=date.today() + timedelta(days=45),
357
status=QuoteStatus.objects.get(name="Draft")
358
)
359
360
# Convert accepted quote to invoice
361
if quote.status.name == "Accepted":
362
invoice = quote.convert_to_invoice()
363
invoice.save()
364
```
365
366
### Document Workflow
367
368
```python
369
# Quote -> Sales Order -> Invoice workflow
370
from creme.billing import get_salesorder_model
371
372
SalesOrderModel = get_salesorder_model()
373
374
# Step 1: Create and send quote
375
quote = QuoteModel.objects.create(
376
name="QUO-2023-002",
377
issuing_date=date.today()
378
)
379
quote.send_to_customer()
380
381
# Step 2: Convert accepted quote to sales order
382
if quote.status.name == "Accepted":
383
sales_order = quote.convert_to_sales_order()
384
sales_order.save()
385
386
# Step 3: Convert sales order to invoice when ready to bill
387
invoice = sales_order.convert_to_invoice()
388
invoice.save()
389
390
# Step 4: Generate PDF and send invoice
391
pdf_content = invoice.build_pdf()
392
invoice.send_email(attach_pdf=True)
393
```
394
395
### Credit Note Processing
396
397
```python
398
from creme.billing import get_creditnote_model
399
400
CreditNoteModel = get_creditnote_model()
401
402
# Create credit note for returned goods
403
credit_note = CreditNoteModel.objects.create(
404
name="CN-2023-001",
405
issuing_date=date.today(),
406
additional_info="Credit for returned merchandise"
407
)
408
409
# Add credit line
410
ServiceLine.objects.create(
411
related_document=credit_note,
412
on_the_fly_item="Product Return Credit",
413
quantity=1,
414
unit_price=-150.00, # Negative amount for credit
415
vat_value=default_vat
416
)
417
418
# Apply credit to original invoice
419
credit_note.apply_to_invoice(original_invoice)
420
```
421
422
### Payment Tracking
423
424
```python
425
from creme.billing.models import Payment
426
427
# Record payment
428
payment = Payment.objects.create(
429
invoice=invoice,
430
amount=invoice.get_total(),
431
payment_date=date.today(),
432
payment_method="Bank Transfer",
433
reference="TXN123456"
434
)
435
436
# Update invoice status
437
if payment.amount >= invoice.get_total():
438
paid_status = InvoiceStatus.objects.get(name="Paid")
439
invoice.status = paid_status
440
invoice.save()
441
```
442
443
### Financial Reporting
444
445
```python
446
from django.db.models import Sum, Q
447
from datetime import datetime
448
449
# Calculate monthly revenue
450
current_month = datetime.now().replace(day=1)
451
monthly_revenue = InvoiceModel.objects.filter(
452
issuing_date__gte=current_month,
453
status__name="Paid"
454
).aggregate(total=Sum('total_no_vat'))['total'] or 0
455
456
# Outstanding invoices
457
outstanding = InvoiceModel.objects.filter(
458
status__name__in=["Sent", "Overdue"]
459
).aggregate(total=Sum('total_no_vat'))['total'] or 0
460
461
# Pending quotes
462
pending_quotes = QuoteModel.objects.filter(
463
status__name="Sent",
464
expiration_date__gte=date.today()
465
).count()
466
467
# Generate aging report
468
from datetime import timedelta
469
today = date.today()
470
471
aging_buckets = {
472
'current': InvoiceModel.objects.filter(
473
status__name__in=["Sent"],
474
expiration_date__gte=today
475
).aggregate(Sum('total_no_vat')),
476
'1-30_days': InvoiceModel.objects.filter(
477
expiration_date__lt=today,
478
expiration_date__gte=today - timedelta(days=30)
479
).aggregate(Sum('total_no_vat')),
480
'31-60_days': InvoiceModel.objects.filter(
481
expiration_date__lt=today - timedelta(days=30),
482
expiration_date__gte=today - timedelta(days=60)
483
).aggregate(Sum('total_no_vat'))
484
}
485
```
486
487
### PDF Generation and Email
488
489
```python
490
# Generate PDF invoice
491
pdf_buffer = invoice.build_pdf()
492
493
# Custom PDF generation with template
494
from creme.billing.utils import generate_pdf_invoice
495
pdf_content = generate_pdf_invoice(
496
invoice=invoice,
497
template='custom_invoice_template.html',
498
logo_path='/path/to/company_logo.png'
499
)
500
501
# Email invoice to customer
502
invoice.send_email(
503
recipient_list=['customer@example.com'],
504
subject=f"Invoice {invoice.name}",
505
message="Please find attached your invoice.",
506
attach_pdf=True
507
)
508
```
509
510
## Integration Features
511
512
The billing system integrates with:
513
514
- **Contacts/Organizations**: Customer and supplier management
515
- **Products/Services**: Item catalogs and pricing
516
- **Activities**: Payment follow-up tasks
517
- **Documents**: File attachments and document management
518
- **Opportunities**: Quote generation from opportunities
519
- **Reports**: Financial analysis and business intelligence
520
- **Email System**: Automated invoice delivery
521
- **Workflows**: Approval processes and automation