Commit 31e0ecb2 by François C.

Better save reception errors report logs

parent 86219535
Pipeline #1195 passed with stage
in 1 minute 21 seconds
...@@ -212,7 +212,7 @@ function validatePrices() { ...@@ -212,7 +212,7 @@ function validatePrices() {
var updates = { var updates = {
'group_amount_total' : order['amount_total'], 'group_amount_total' : order['amount_total'],
'update_type' : 'br_vaid', 'update_type' : 'br_valid',
'updated_products' : [], 'updated_products' : [],
'user_comments': "", 'user_comments': "",
'orders' : [order] 'orders' : [order]
......
...@@ -259,104 +259,110 @@ def save_error_report(request): ...@@ -259,104 +259,110 @@ def save_error_report(request):
save it to an excel file, save it to an excel file,
attach file to order in odoo attach file to order in odoo
""" """
if request.is_ajax(): if request.method == 'POST':
if request.method == 'POST': data = None
try:
myJson = request.body myJson = request.body
data = json.loads(myJson.decode()) data = json.loads(myJson.decode())
except Exception as e1:
coop_logger.error("Save reception report : Unable to load data %s (%s)", str(e1), str(myJson))
temp_files_name = [] if data and ('orders' in data):
orders_name = "" orders_name_elts = []
orders_partner = "" orders_partner = ""
group_ids = [] group_ids = []
for i, order in enumerate(data['orders']) :
# list of temp files: 1 report per order & group
data['orders'][i]['temp_file_name'] = "temp/" + order['name'] + "_rapport-reception_temp.xlsx"
group_ids.append(order['id']) try:
for i, order in enumerate(data['orders']) :
# list of temp files: 1 report per order & group
data['orders'][i]['temp_file_name'] = "temp/" + order['name'] + "_rapport-reception_temp.xlsx"
# Concatenate orders name group_ids.append(order['id'])
if orders_name != "" :
orders_name = orders_name + '-'
orders_name = orders_name + order['name']
# Concatenate orders partner orders_name_elts.append(order['name'])
if order['partner'] != orders_partner :
if orders_partner != "" :
orders_partner = orders_partner + ', '
orders_partner = orders_partner + order['partner'] + ' du ' + order['date_order']
# Concatenate orders partner
if order['partner'] != orders_partner:
if orders_partner != "":
orders_partner = orders_partner + ', '
orders_partner = orders_partner + order['partner'] + ' du ' + order['date_order']
# If group of orders
if len(data['orders']) > 1 :
temp_group_file_name = "temp/" + orders_name + "_rapport-reception_temp.xlsx"
# Add group in data['orders'] # If group of orders
group_order = { if len(data['orders']) > 1:
'name' : orders_name, orders_name = '-'.join(orders_name_elts)
'partner' : orders_partner, temp_group_file_name = "temp/" + orders_name + "_rapport-reception_temp.xlsx"
'date_order' : data['orders'][0]['date_order'],
'amount_total' : data['group_amount_total'],
'updated_products' : data['updated_products'],
'temp_file_name' : temp_group_file_name,
'group_ids' : group_ids
}
data['orders'].append(group_order) # Add group in data['orders']
group_order = {
'name': orders_name,
'partner': orders_partner,
'date_order': data['orders'][0]['date_order'],
'amount_total': data['group_amount_total'],
'updated_products': data['updated_products'],
'temp_file_name': temp_group_file_name,
'group_ids': group_ids
}
data['orders'].append(group_order)
except Exception as e2:
coop_logger.error("Save reception report : Error while create group_order %s", str(e2))
# Save qties & comments after step 1 # Save qties & comments after step 1
if data['update_type'] == 'qty_valid': if data['update_type'] == 'qty_valid':
for order in data['orders']: for order in data['orders']:
wb = Workbook()
ws = wb.active
ws.title = "Commande " + order['name']
ws.append(['type',
'nom_contenu',
'supplier_code',
'barcode',
'old_qty',
'product_qty',
'price_unit',
'supplier_shortage'])
# If in group add group name
if len(data['orders']) > 1 :
ws.append( ['group', orders_name] )
try: try:
if 'updated_products' in order: wb = Workbook()
for product in order['updated_products']: ws = wb.active
# Don't store products with same qties ws.title = "Commande " + order['name']
if product['old_qty'] != product['product_qty']:
if 'supplier_code' in product: ws.append(['type',
supplier_code = str(product['supplier_code']) 'nom_contenu',
else: 'supplier_code',
supplier_code = 'X' 'barcode',
'old_qty',
if 'supplier_shortage' in product: 'product_qty',
supplier_shortage = '/!\ Rupture fournisseur' 'price_unit',
else: 'supplier_shortage'])
supplier_shortage = ''
# If in group add group name
ws.append( ['produit', if len(data['orders']) > 1:
product['product_id'][1], ws.append(['group', orders_name])
supplier_code, try:
str(product['barcode']), if 'updated_products' in order:
product['old_qty'], for product in order['updated_products']:
product['product_qty'], # Don't store products with same qties
product['price_unit'], if product['old_qty'] != product['product_qty']:
supplier_shortage] ) if 'supplier_code' in product:
except Exception as exp: supplier_code = str(product['supplier_code'])
print("Error while updating products") else:
print(exp) supplier_code = 'X'
if ('user_comments' in data) and data['user_comments'] != "":
ws.append( ['commentaire', data['user_comments']] ) if 'supplier_shortage' in product:
else: supplier_shortage = '/!\ Rupture fournisseur'
ws.append( ['commentaire', 'Aucun commentaire.'] ) else:
supplier_shortage = ''
# Save file
wb.save(filename=order['temp_file_name']) ws.append(['produit',
product['product_id'][1],
supplier_code,
str(product['barcode']),
product['old_qty'],
product['product_qty'],
product['price_unit'],
supplier_shortage])
except Exception as exp:
coop_logger.error("Error while updating products in report : %s", str(exp))
if ('user_comments' in data) and data['user_comments'] != "":
ws.append( ['commentaire', data['user_comments']] )
else:
ws.append( ['commentaire', 'Aucun commentaire.'] )
# Save file
wb.save(filename=order['temp_file_name'])
except Exception as e3:
coop_logger.error("Save reception report : Error while create order Workbook %s", str(e3))
# Create report with data from steps 1 & 2 # Create report with data from steps 1 & 2
...@@ -385,13 +391,14 @@ def save_error_report(request): ...@@ -385,13 +391,14 @@ def save_error_report(request):
'supplier_shortage' : row[7] 'supplier_shortage' : row[7]
} }
elif row[0] == 'group': elif row[0] == 'group':
group_name = row[1] # group's orders name group_name = row[1] # group's orders name : Unused
elif row[0] == 'commentaire': elif row[0] == 'commentaire':
data_comment_s1 = row[1] # user comments data_comment_s1 = row[1] # user comments
# Clear step 1 temp file # Clear step 1 temp file
os.remove(order['temp_file_name']) os.remove(order['temp_file_name'])
except: except Exception as e4:
coop_logger.error("Save reception report : reloading first step xlsx file %s", str(e4))
data_comment_s1 = "Données de la première étape absentes !" data_comment_s1 = "Données de la première étape absentes !"
# Add data from step 2 # Add data from step 2
...@@ -450,140 +457,147 @@ def save_error_report(request): ...@@ -450,140 +457,147 @@ def save_error_report(request):
error_total_abs += abs(item['error_line']) error_total_abs += abs(item['error_line'])
data_full.append(item) data_full.append(item)
except Exception as exp: except Exception as e5:
coop_logger.error("Save reception report : Error while updating products %s", str(e5))
# no updated products, do nothing # no updated products, do nothing
print("Error while updating products")
print(exp)
# Add remaining products, the ones edited only in step 1 # Add remaining products, the ones edited only in step 1
for product in data_qties.values(): for product in data_qties.values():
item = { try:
'product_id': product['nom_contenu'], item = {
'product_supplier_code': product['supplier_code'], 'product_id': product['nom_contenu'],
'product_barcode': product['barcode'], 'product_supplier_code': product['supplier_code'],
'old_qty': float(product['old_qty']), 'product_barcode': product['barcode'],
'product_qty': float(product['product_qty']), 'old_qty': float(product['old_qty']),
'old_price_unit': float(product['price_unit']), 'product_qty': float(product['product_qty']),
'price_unit': '', 'old_price_unit': float(product['price_unit']),
'expected_amount':float(product['old_qty'])*float(product['price_unit']), 'price_unit': '',
'error_line': (float(product['old_qty'])-float(product['product_qty']))*float(product['price_unit']), 'expected_amount':float(product['old_qty'])*float(product['price_unit']),
'supplier_shortage': product['supplier_shortage'] 'error_line': (float(product['old_qty'])-float(product['product_qty']))*float(product['price_unit']),
} 'supplier_shortage': product['supplier_shortage']
}
error_total += item['error_line']
error_total_abs += abs(item['error_line']) error_total += item['error_line']
error_total_abs += abs(item['error_line'])
data_full.append(item)
data_full.append(item)
# Sort by error amount except Exception as e6:
def sortByError(e): coop_logger.error("Save reception report : Error while creating item from product %s (%s)", str(e6), str(e6))
return abs(e['error_line']) try:
data_full.sort(reverse=True, key=sortByError) # Sort by error amount
def sortByError(e):
# Create excel file return abs(e['error_line'])
wb = Workbook() data_full.sort(reverse=True, key=sortByError)
ws = wb.active
ws.title = "Commande " + order['name'] # Create excel file
# Group wb = Workbook()
if 'group_ids' in order : ws = wb.active
ws.append( ['Rapport de réception d\'un groupe de commandes'] ) ws.title = "Commande " + order['name']
ws.append( ['Fournisseur(s) : ', order['partner']] ) # Group
ws.append( ['Références des commandes du groupe : ', order['name']] ) if 'group_ids' in order :
else: ws.append( ['Rapport de réception d\'un groupe de commandes'] )
ws.append( ['Rapport de réception'] ) ws.append( ['Fournisseur(s) : ', order['partner']] )
ws.append( ['Fournisseur : ', order['partner']] ) ws.append( ['Références des commandes du groupe : ', order['name']] )
ws.append( ['Réf Commande : ', order['name']] ) else:
if len(data['orders']) > 1 : ws.append( ['Rapport de réception'] )
ws.append( ['Commande traitée en groupe. Groupe : ', orders_name] ) ws.append( ['Fournisseur : ', order['partner']] )
ws.append( ['Réf Commande : ', order['name']] )
ws.append( ['Date de la commande : ', order['date_order']] ) if len(data['orders']) > 1 :
ws.append( ['Date de la réception : ', time.strftime("%d/%m/%y")] ) ws.append( ['Commande traitée en groupe. Groupe : ', orders_name] )
ws.append( ['Montant total attendu (TTC) : ', str(round(order['amount_total'],2)) + ' €'] )
ws.append( [] ) ws.append( ['Date de la commande : ', order['date_order']] )
ws.append( ['Date de la réception : ', time.strftime("%d/%m/%y")] )
ws.append( ['Nom produit', ws.append( ['Montant total attendu (TTC) : ', str(round(order['amount_total'],2)) + ' €'] )
'Code Four.', ws.append( [] )
'Numéro de Code Barre',
'Qté commande', ws.append( ['Nom produit',
'Qté réception', 'Code Four.',
'Prix unit. initial', 'Numéro de Code Barre',
'Prix unit. MAJ', 'Qté commande',
'Prix total attendu', 'Qté réception',
"Montant erreur livraison (basé sur les différences de quantité)"] ) 'Prix unit. initial',
'Prix unit. MAJ',
if len(data_full) == 0: 'Prix total attendu',
ws.append( ['- Aucune modification -'] ) "Montant erreur livraison (basé sur les différences de quantité)"] )
else:
for product in data_full: if len(data_full) == 0:
ws.append( [product['product_id'], ws.append( ['- Aucune modification -'] )
product['product_supplier_code'], else:
str(product['product_barcode']), for product in data_full:
product['old_qty'], ws.append( [product['product_id'],
product['product_qty'], product['product_supplier_code'],
product['old_price_unit'], str(product['product_barcode']),
product['price_unit'], product['old_qty'],
round(product['expected_amount'], 2), product['product_qty'],
round(product['error_line'], 2), product['old_price_unit'],
product['supplier_shortage']] ) product['price_unit'],
ws.append( [] ) round(product['expected_amount'], 2),
ws.append( ['Montant total de l\'erreur :', '', '', '', '', '', '', '', round(error_total, 2)] ) round(product['error_line'], 2),
ws.append( ['Montant total en valeur absolue :', '', '', '', '', '', '', '', round(error_total_abs, 2)] ) product['supplier_shortage']] )
ws.append( [] )
ws.append( [] ) ws.append( ['Montant total de l\'erreur :', '', '', '', '', '', '', '', round(error_total, 2)] )
ws.append( [] ) ws.append( ['Montant total en valeur absolue :', '', '', '', '', '', '', '', round(error_total_abs, 2)] )
ws.append( ['Problèmes survenus durant le comptage :', data_comment_s1] ) ws.append( [] )
# Merge cells for comments ws.append( [] )
merge_begin = ws.max_row
merge_end = ws.max_row+3 ws.append( ['Problèmes survenus durant le comptage :', data_comment_s1] )
ws.append( [] ) # Merge cells for comments
ws.append( [] ) merge_begin = ws.max_row
ws.append( [] ) merge_end = ws.max_row+3
ws.merge_cells(start_row=merge_begin, start_column=1, end_row=merge_end, end_column=1) ws.append( [] )
ws.merge_cells(start_row=merge_begin, start_column=2, end_row=merge_end, end_column=7) ws.append( [] )
# Styling merged cells ws.append( [] )
top_left_cell = ws['A'+str(merge_begin)] ws.merge_cells(start_row=merge_begin, start_column=1, end_row=merge_end, end_column=1)
top_left_cell.alignment = Alignment(vertical="top") ws.merge_cells(start_row=merge_begin, start_column=2, end_row=merge_end, end_column=7)
top_left_cell = ws['B'+str(merge_begin)] # Styling merged cells
top_left_cell.alignment = Alignment(vertical="top") top_left_cell = ws['A'+str(merge_begin)]
top_left_cell.alignment = Alignment(vertical="top")
ws.append( ['Problèmes survenus durant la mise à jour des prix :', data_comment_s2] ) top_left_cell = ws['B'+str(merge_begin)]
merge_begin = ws.max_row top_left_cell.alignment = Alignment(vertical="top")
merge_end = ws.max_row+3
ws.append( [] ) ws.append( ['Problèmes survenus durant la mise à jour des prix :', data_comment_s2] )
ws.append( [] ) merge_begin = ws.max_row
ws.append( [] ) merge_end = ws.max_row+3
ws.merge_cells(start_row=merge_begin, start_column=1, end_row=merge_end, end_column=1) ws.append( [] )
ws.merge_cells(start_row=merge_begin, start_column=2, end_row=merge_end, end_column=7) ws.append( [] )
top_left_cell = ws['A'+str(merge_begin)] ws.append( [] )
top_left_cell.alignment = Alignment(vertical="top") ws.merge_cells(start_row=merge_begin, start_column=1, end_row=merge_end, end_column=1)
top_left_cell = ws['B'+str(merge_begin)] ws.merge_cells(start_row=merge_begin, start_column=2, end_row=merge_end, end_column=7)
top_left_cell.alignment = Alignment(vertical="top") top_left_cell = ws['A'+str(merge_begin)]
# "Auto fit" columns width to content top_left_cell.alignment = Alignment(vertical="top")
for column_cells in ws.columns: top_left_cell = ws['B'+str(merge_begin)]
length = max(len(as_text(cell.value)) for cell in column_cells) top_left_cell.alignment = Alignment(vertical="top")
# For other columns than the first, limit size # "Auto fit" columns width to content
if column_cells[3].column_letter != "A" and length > 20 : for column_cells in ws.columns:
length = 20 length = max(len(as_text(cell.value)) for cell in column_cells)
# For other columns than the first, limit size
ws.column_dimensions[column_cells[3].column_letter].width = length if column_cells[3].column_letter != "A" and length > 20 :
length = 20
ws.column_dimensions[column_cells[3].column_letter].width = length
except Exception as e7:
coop_logger.error("PO save report : error while creating final Workbook %s", str(e7))
# Save file # Save file
fileName = "temp/" + order['name'] + "_rapport-reception.xlsx" fileName = "temp/" + order['name'] + "_rapport-reception.xlsx"
try: try:
wb.save(filename=fileName) wb.save(filename=fileName)
except Exception as exp: #Attach file to order
print("Error while saving file %s"%fileName) if 'group_ids' in order: # group report
print(str(exp)) # Attach group report to each order
#Attach file to order for group_item_id in order['group_ids']:
if 'group_ids' in order : # group report m = CagetteReception(group_item_id)
# Attach group report to each order m.attach_file(fileName, False)
for group_item_id in order['group_ids'] : os.remove(fileName)
m = CagetteReception(group_item_id) else:
m.attach_file(fileName, False) m = CagetteReception(order['id'])
os.remove(fileName) m.attach_file(fileName)
else: except Exception as e8:
m = CagetteReception(order['id']) coop_logger.error("PO save report Error while saving file %s (%s)", fileName, str(e8))
m.attach_file(fileName) else:
coop_logger.error("Cant find 'orders' in data (%s)", str(data))
else:
coop_logger.info("Was waiting for a POST method (%s)", str(request.method))
return JsonResponse("ok", safe=False) return JsonResponse("ok", safe=False)
def reception_FAQ(request): def reception_FAQ(request):
......
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