This repository has been archived by the owner on Dec 30, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
stock_reporting_margin.py
667 lines (570 loc) · 22.7 KB
/
stock_reporting_margin.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
# This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
from decimal import Decimal
from itertools import tee, zip_longest
from sql import Literal, Null, With
from sql.aggregate import Max, Min, Sum
from sql.conditionals import Case, Coalesce
from sql.functions import Ceil, CurrentTimestamp, DateTrunc, Log, Power, Round
try:
import pygal
except ImportError:
pygal = None
from dateutil.relativedelta import relativedelta
from trytond.i18n import lazy_gettext
from trytond.model import ModelSQL, ModelView, fields
from trytond.modules.currency.fields import Monetary
from trytond.pool import Pool
from trytond.pyson import Eval, If
from trytond.tools import grouped_slice, reduce_ids
from trytond.transaction import Transaction
def pairwise(iterable):
a, b = tee(iterable)
next(b)
return zip_longest(a, b)
class Abstract(ModelSQL, ModelView):
company = fields.Many2One(
'company.company', lazy_gettext('stock.msg_stock_reporting_company'))
cost = Monetary(
lazy_gettext('stock.msg_stock_reporting_cost'),
currency='currency', digits='currency')
revenue = Monetary(
lazy_gettext('stock.msg_stock_reporting_revenue'),
currency='currency', digits='currency')
profit = Monetary(
lazy_gettext('stock.msg_stock_reporting_profit'),
currency='currency', digits='currency')
margin = fields.Numeric(
lazy_gettext('stock.msg_stock_reporting_margin'),
digits=(14, 4),
states={
'invisible': ~Eval('margin'),
})
margin_trend = fields.Function(fields.Char(
lazy_gettext('stock.msg_stock_reporting_margin_trend')),
'get_trend')
time_series = None
currency = fields.Many2One(
'currency.currency',
lazy_gettext('stock.msg_stock_reporting_currency'))
@classmethod
def table_query(cls):
from_item, tables, withs = cls._joins()
return from_item.select(*cls._columns(tables, withs),
where=cls._where(tables, withs),
group_by=cls._group_by(tables, withs),
with_=withs.values())
@classmethod
def _joins(cls):
pool = Pool()
Company = pool.get('company.company')
Currency = pool.get('currency.currency')
Move = pool.get('stock.move')
Location = pool.get('stock.location')
tables = {}
tables['move'] = move = Move.__table__()
tables['move.company'] = company = Company.__table__()
tables['move.company.currency'] = currency = Currency.__table__()
tables['move.from_location'] = from_location = Location.__table__()
tables['move.to_location'] = to_location = Location.__table__()
withs = {}
withs['currency_rate'] = currency_rate = With(
query=Currency.currency_rate_sql())
withs['currency_rate_company'] = currency_rate_company = With(
query=Currency.currency_rate_sql())
from_item = (move
.join(currency_rate, type_='LEFT',
condition=(move.currency == currency_rate.currency)
& (currency_rate.start_date <= move.effective_date)
& ((currency_rate.end_date == Null)
| (currency_rate.end_date > move.effective_date))
)
.join(company,
condition=move.company == company.id)
.join(currency,
condition=company.currency == currency.id)
.join(currency_rate_company,
condition=(company.currency == currency_rate_company.currency)
& (currency_rate_company.start_date <= move.effective_date)
& ((currency_rate_company.end_date == Null)
| (currency_rate_company.end_date > move.effective_date))
)
.join(from_location,
condition=(move.from_location == from_location.id))
.join(to_location,
condition=(move.to_location == to_location.id)))
return from_item, tables, withs
@classmethod
def _columns(cls, tables, withs):
move = tables['move']
from_location = tables['move.from_location']
to_location = tables['move.to_location']
currency = tables['move.company.currency']
sign = Case(
(from_location.type.in_(cls._to_location_types())
& to_location.type.in_(cls._from_location_types()),
-1),
else_=1)
cost = cls._column_cost(tables, withs, sign)
revenue = cls._column_revenue(tables, withs, sign)
profit = revenue - cost
margin = Case(
(revenue != 0, profit / revenue),
else_=Null)
return [
cls._column_id(tables, withs).as_('id'),
Literal(0).as_('create_uid'),
CurrentTimestamp().as_('create_date'),
cls.write_uid.sql_cast(Literal(Null)).as_('write_uid'),
cls.write_date.sql_cast(Literal(Null)).as_('write_date'),
move.company.as_('company'),
cls.cost.sql_cast(
Round(cost, currency.digits)).as_('cost'),
cls.revenue.sql_cast(
Round(revenue, currency.digits)).as_('revenue'),
cls.profit.sql_cast(
Round(profit, currency.digits)).as_('profit'),
cls.margin.sql_cast(
Round(margin, cls.margin.digits[1])).as_('margin'),
currency.id.as_('currency'),
]
@classmethod
def _column_id(cls, tables, withs):
move = tables['move']
return Min(move.id)
@classmethod
def _column_cost(cls, tables, withs, sign):
move = tables['move']
return Sum(
sign * cls.cost.sql_cast(move.internal_quantity)
* Coalesce(move.cost_price, 0))
@classmethod
def _column_revenue(cls, tables, withs, sign):
move = tables['move']
currency = withs['currency_rate']
currency_company = withs['currency_rate_company']
return Sum(
sign * cls.revenue.sql_cast(move.quantity)
* Coalesce(move.unit_price, 0)
* Coalesce(currency_company.rate / currency.rate, 0))
@classmethod
def _group_by(cls, tables, withs):
move = tables['move']
currency = tables['move.company.currency']
return [move.company, currency.id, currency.digits]
@classmethod
def _where(cls, tables, withs):
context = Transaction().context
move = tables['move']
from_location = tables['move.from_location']
to_location = tables['move.to_location']
where = move.company == context.get('company')
where &= ((
from_location.type.in_(cls._from_location_types())
& to_location.type.in_(cls._to_location_types()))
| (
from_location.type.in_(cls._to_location_types())
& to_location.type.in_(cls._from_location_types())))
where &= move.state == 'done'
from_date = context.get('from_date')
if from_date:
where &= move.effective_date >= from_date
to_date = context.get('to_date')
if to_date:
where &= move.effective_date <= to_date
return where
@classmethod
def _from_location_types(cls):
return ['storage', 'drop']
@classmethod
def _to_location_types(cls):
types = ['customer']
if Transaction().context.get('include_lost'):
types += ['lost_found']
return types
@property
def time_series_all(self):
delta = self._period_delta()
for ts, next_ts in pairwise(self.time_series or []):
yield ts
if delta and next_ts:
date = ts.date + delta
while date < next_ts.date:
yield None
date += delta
@classmethod
def _period_delta(cls):
context = Transaction().context
return {
'year': relativedelta(years=1),
'month': relativedelta(months=1),
'day': relativedelta(days=1),
}.get(context.get('period'))
def get_trend(self, name):
name = name[:-len('_trend')]
if pygal:
chart = pygal.Line()
chart.add('', [getattr(ts, name) or 0 if ts else 0
for ts in self.time_series_all])
return chart.render_sparktext()
@classmethod
def view_attributes(cls):
return super().view_attributes() + [
('/tree/field[@name="profit"]', 'visual',
If(Eval('profit', 0) < 0, 'danger', '')),
('/tree/field[@name="margin"]', 'visual',
If(Eval('margin', 0) < 0, 'danger', '')),
]
class AbstractTimeseries(Abstract):
date = fields.Date("Date")
@classmethod
def __setup__(cls):
super().__setup__()
cls._order = [('date', 'ASC')]
@classmethod
def _columns(cls, tables, withs):
return super()._columns(tables, withs) + [
cls._column_date(tables, withs).as_('date')]
@classmethod
def _column_date(cls, tables, withs):
context = Transaction().context
move = tables['move']
date = DateTrunc(context.get('period'), move.effective_date)
date = cls.date.sql_cast(date)
return date
@classmethod
def _group_by(cls, tables, withs):
return super()._group_by(tables, withs) + [
cls._column_date(tables, withs)]
class Context(ModelView):
"Stock Reporting Margin Context"
__name__ = 'stock.reporting.margin.context'
company = fields.Many2One('company.company', "Company", required=True)
from_date = fields.Date("From Date",
domain=[
If(Eval('to_date') & Eval('from_date'),
('from_date', '<=', Eval('to_date')),
()),
])
to_date = fields.Date("To Date",
domain=[
If(Eval('from_date') & Eval('to_date'),
('to_date', '>=', Eval('from_date')),
()),
])
period = fields.Selection([
('year', "Year"),
('month', "Month"),
('day', "Day"),
], "Period", required=True)
include_lost = fields.Boolean(
"Include Lost",
help="If checked, the cost of product moved "
"to a lost and found location is included.")
@classmethod
def default_company(cls):
return Transaction().context.get('company')
@classmethod
def default_from_date(cls):
pool = Pool()
Date = pool.get('ir.date')
context = Transaction().context
if 'from_date' in context:
return context['from_date']
return Date.today() - relativedelta(years=1)
@classmethod
def default_to_date(cls):
pool = Pool()
Date = pool.get('ir.date')
context = Transaction().context
if 'to_date' in context:
return context['to_date']
return Date.today()
@classmethod
def default_period(cls):
return Transaction().context.get('period', 'month')
@classmethod
def default_include_lost(cls):
return Transaction().context.get('include_lost', False)
class Main(Abstract, ModelView):
"Stock Reporting Margin"
__name__ = 'stock.reporting.margin.main'
time_series = fields.Function(fields.One2Many(
'stock.reporting.margin.main.time_series', None, "Time Series"),
'get_time_series')
def get_rec_name(self, name):
return ''
def get_time_series(self, name):
pool = Pool()
Timeseries = pool.get('stock.reporting.margin.main.time_series')
return [t.id for t in Timeseries.search([])]
class MainTimeseries(AbstractTimeseries, ModelView):
"Stock Reporting Margin"
__name__ = 'stock.reporting.margin.main.time_series'
class ProductMixin:
__slots__ = ()
product = fields.Many2One(
'product.product', "Product",
context={
'company': Eval('company', -1),
},
depends={'company'})
internal_quantity = fields.Float("Internal Quantity")
quantity = fields.Function(fields.Float(
"Quantity", digits='unit'), 'get_quantity')
unit = fields.Many2One('product.uom', "Unit")
@classmethod
def _joins(cls):
pool = Pool()
Product = pool.get('product.product')
Template = pool.get('product.template')
from_item, tables, withs = super()._joins()
if 'move.product' not in tables:
product = Product.__table__()
tables['move.product'] = product
move = tables['move']
from_item = (from_item
.join(product, condition=move.product == product.id))
if 'move.product.template' not in tables:
template = Template.__table__()
tables['move.product.template'] = template
product = tables['move.product']
from_item = (from_item
.join(template, condition=product.template == template.id))
return from_item, tables, withs
@classmethod
def _columns(cls, tables, withs):
move = tables['move']
from_location = tables['move.from_location']
to_location = tables['move.to_location']
template = tables['move.product.template']
sign = Case(
(from_location.type.in_(cls._to_location_types())
& to_location.type.in_(cls._from_location_types()),
-1),
else_=1)
return super()._columns(tables, withs) + [
move.product.as_('product'),
Sum(sign * move.internal_quantity).as_('internal_quantity'),
template.default_uom.as_('unit'),
]
@classmethod
def _group_by(cls, tables, withs):
move = tables['move']
template = tables['move.product.template']
return super()._group_by(tables, withs) + [
move.product, template.default_uom]
def get_rec_name(self, name):
return self.product.rec_name
def get_quantity(self, name):
return self.unit.round(self.internal_quantity)
class Product(ProductMixin, Abstract, ModelView):
"Stock Reporting Margin per Product"
__name__ = 'stock.reporting.margin.product'
time_series = fields.One2Many(
'stock.reporting.margin.product.time_series', 'product', "Time Series")
@classmethod
def __setup__(cls):
super().__setup__()
cls._order.insert(0, ('product', 'ASC'))
@classmethod
def _column_id(cls, tables, withs):
move = tables['move']
return move.product
class ProductTimeseries(ProductMixin, AbstractTimeseries, ModelView):
"Stock Reporting Margin per Product"
__name__ = 'stock.reporting.margin.product.time_series'
class CategoryMixin:
__slots__ = ()
category = fields.Many2One('product.category', "Category")
@classmethod
def _joins(cls):
pool = Pool()
Product = pool.get('product.product')
TemplateCategory = pool.get('product.template-product.category.all')
from_item, tables, withs = super()._joins()
if 'move.product' not in tables:
product = Product.__table__()
tables['move.product'] = product
move = tables['move']
from_item = (from_item
.join(product, condition=move.product == product.id))
if 'move.product.template_category' not in tables:
template_category = TemplateCategory.__table__()
tables['move.product.template_category'] = template_category
product = tables['move.product']
from_item = (from_item
.join(template_category,
condition=product.template == template_category.template))
return from_item, tables, withs
@classmethod
def _columns(cls, tables, withs):
template_category = tables['move.product.template_category']
return super()._columns(tables, withs) + [
template_category.category.as_('category')]
@classmethod
def _column_id(cls, tables, withs):
pool = Pool()
Category = pool.get('product.category')
category = Category.__table__()
move = tables['move']
template_category = tables['move.product.template_category']
# Get a stable number of category over time
# by using number one order bigger.
nb_category = category.select(
Power(10, (Ceil(Log(Max(category.id))) + Literal(1))))
return Min(move.id * nb_category + template_category.id)
@classmethod
def _group_by(cls, tables, withs):
template_category = tables['move.product.template_category']
return super()._group_by(tables, withs) + [template_category.category]
@classmethod
def _where(cls, tables, withs):
template_category = tables['move.product.template_category']
where = super()._where(tables, withs)
where &= template_category.category != Null
return where
def get_rec_name(self, name):
return self.category.rec_name if self.category else None
class Category(CategoryMixin, Abstract, ModelView):
"Stock Reporting Margin per Category"
__name__ = 'stock.reporting.margin.category'
time_series = fields.One2Many(
'stock.reporting.margin.category.time_series', 'category',
"Time Series")
@classmethod
def __setup__(cls):
super().__setup__()
cls._order.insert(0, ('category', 'ASC'))
@classmethod
def _column_id(cls, tables, withs):
template_category = tables['move.product.template_category']
return template_category.category
class CategoryTimeseries(CategoryMixin, AbstractTimeseries, ModelView):
"Stock Reporting Margin per Category"
__name__ = 'stock.reporting.margin.category.time_series'
class CategoryTree(ModelSQL, ModelView):
"Stock Reporting Margin per Category"
__name__ = 'stock.reporting.margin.category.tree'
name = fields.Function(fields.Char("Name"), 'get_name')
parent = fields.Many2One('stock.reporting.margin.category.tree', "Parent")
children = fields.One2Many(
'stock.reporting.margin.category.tree', 'parent', "Children")
cost = fields.Function(Monetary(
lazy_gettext('stock.msg_stock_reporting_cost'),
currency='currency', digits='currency'),
'get_total')
revenue = fields.Function(Monetary(
lazy_gettext('stock.msg_stock_reporting_revenue'),
currency='currency', digits='currency'),
'get_total')
profit = fields.Function(Monetary(
lazy_gettext('stock.msg_stock_reporting_profit'),
currency='currency', digits='currency'),
'get_total')
margin = fields.Function(Monetary(
lazy_gettext('stock.msg_stock_reporting_margin'),
digits=(14, 4)),
'get_margin')
currency = fields.Function(fields.Many2One(
'currency.currency',
lazy_gettext('stock.msg_stock_reporting_currency')),
'get_currency')
@classmethod
def __setup__(cls):
super().__setup__()
cls._order.insert(0, ('name', 'ASC'))
@classmethod
def table_query(cls):
pool = Pool()
Category = pool.get('product.category')
return Category.__table__()
@classmethod
def get_name(cls, categories, name):
pool = Pool()
Category = pool.get('product.category')
categories = Category.browse(categories)
return {c.id: c.name for c in categories}
@classmethod
def order_name(cls, tables):
pool = Pool()
Category = pool.get('product.category')
table, _ = tables[None]
if 'category' not in tables:
category = Category.__table__()
tables['category'] = {
None: (category, table.id == category.id),
}
return Category.name.convert_order(
'name', tables['category'], Category)
def time_series_all(self):
return []
@classmethod
def get_total(cls, categories, names):
pool = Pool()
ReportingCategory = pool.get('stock.reporting.margin.category')
table = cls.__table__()
reporting_category = ReportingCategory.__table__()
cursor = Transaction().connection.cursor()
categories = cls.search([
('parent', 'child_of', [c.id for c in categories]),
])
ids = [c.id for c in categories]
parents = {}
reporting_categories = []
for sub_ids in grouped_slice(ids):
sub_ids = list(sub_ids)
where = reduce_ids(table.id, sub_ids)
cursor.execute(*table.select(table.id, table.parent, where=where))
parents.update(cursor)
where = reduce_ids(reporting_category.id, sub_ids)
cursor.execute(
*reporting_category.select(reporting_category.id, where=where))
reporting_categories.extend(r for r, in cursor)
result = {}
reporting_categories = ReportingCategory.browse(reporting_categories)
for name in names:
values = dict.fromkeys(ids, 0)
values.update(
(c.id, getattr(c, name)) for c in reporting_categories)
result[name] = cls._sum_tree(categories, values, parents)
return result
@classmethod
def _sum_tree(cls, categories, values, parents):
result = values.copy()
categories = set((c.id for c in categories))
leafs = categories - set(parents.values())
while leafs:
for category in leafs:
categories.remove(category)
parent = parents.get(category)
if parent in result:
result[parent] += result[category]
next_leafs = set(categories)
for category in categories:
parent = parents.get(category)
if not parent:
continue
if parent in next_leafs and parent in categories:
next_leafs.remove(parent)
leafs = next_leafs
return result
def get_margin(self, name):
digits = self.__class__.margin.digits
if self.profit is not None and self.revenue:
return (self.profit / self.revenue).quantize(
Decimal(1) / 10 ** digits[1])
def get_currency(self, name):
pool = Pool()
Company = pool.get('company.company')
company = Transaction().context.get('company')
if company:
return Company(company).currency.id
@classmethod
def view_attributes(cls):
return super().view_attributes() + [
('/tree/field[@name="profit"]', 'visual',
If(Eval('profit', 0) < 0, 'danger', '')),
('/tree/field[@name="margin"]', 'visual',
If(Eval('margin', 0) < 0, 'danger', '')),
]