Commit c7f65956 by François C.

Add callable function to retrieve product_template ids average sales

parent 7c83c96a
...@@ -70,6 +70,10 @@ class LaCagetteProducts(models.Model): ...@@ -70,6 +70,10 @@ class LaCagetteProducts(models.Model):
@api.model @api.model
def get_simple_list(self, data={}): def get_simple_list(self, data={}):
"""Retrieve products simple list.
@data: list of parameters (only_purchase_ok)
@return: list (with list key or error key)
"""
res = {} res = {}
try: try:
sql = """ sql = """
...@@ -101,3 +105,82 @@ class LaCagetteProducts(models.Model): ...@@ -101,3 +105,82 @@ class LaCagetteProducts(models.Model):
res['error'] = str(e) res['error'] = str(e)
return res return res
@api.model
def get_template_products_sales_average(self, params={}):
"""Retrieve products sales average.
@params: list of parameters ('ids', 'period', excluded_days)
@return: list (with list key or error key)
"""
res = {}
if 'ids' in params:
ids = list(filter(lambda x: isinstance(x, int), params['ids']))
if len(ids) > 0:
import datetime
today = datetime.date.today()
excluded_days = [0]
if 'excluded_days' in params:
excluded_days = params['excluded_days']
if 'to' in params:
dto = params['to']
else:
dto = today - datetime.timedelta(1)
dto = dto.strftime("%Y-%m-%d")
if 'from' in params:
dfrom = params['from']
else:
dfrom = today - datetime.timedelta(50)
dfrom = dfrom.strftime("%Y-%m-%d")
try:
sql = """
SELECT
TO_CHAR(create_date, 'YYYY-MM-DD') as day,
(SELECT product_tmpl_id FROM product_product WHERE id = pol.product_id) as tpl_id,
SUM(qty) as qtys, SUM(discount) as discounts
FROM pos_order_line pol
WHERE
qty != 0
AND
product_id
IN (
SELECT id FROM product_product
WHERE product_tmpl_id IN %s
)
AND
create_date > %s AND create_date < %s
GROUP BY day, tpl_id
"""
self.env.cr.execute(sql, [tuple(ids), dfrom, dto])
req_res = self.env.cr.dictfetchall()
sql_dates = """
SELECT date_trunc('day', dd):: date as ddate, extract(DOW FROM dd) as dow
FROM generate_series
( '""" + dfrom + """'::timestamp
, '""" + dto + """'::timestamp
, '1 day'::interval) dd
"""
self.env.cr.execute(sql_dates)
days = list(filter(lambda x: not (x['dow'] in excluded_days), self.env.cr.dictfetchall()))
res['list'] = []
products_sums = {}
for p in req_res:
pid = p['tpl_id']
if not (pid in products_sums):
products_sums[pid] = {'total_qty': p['qtys'], 'total_discount': p['discounts']}
else:
products_sums[pid]['total_qty'] += p['qtys']
products_sums[pid]['total_discount'] += p['discounts']
for pid, val in products_sums.items():
res['list'].append({'id': pid,
'average_qty': round(val['total_qty']/len(days),2),
'average_discount': round(val['total_discount']/len(days),2)})
except Exception as e:
res['error'] = str(e)
else:
res['error'] = "No valid ids found"
else:
res['error'] = "ids list key is missing"
return res
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment