Commit 1eced1bc by Damien Moulard

(WIP) Beginning of Sales Helper: display a supplier products

parent 32e8eb9b
Pipeline #937 passed with stage
in 20 seconds
......@@ -268,3 +268,15 @@ class Orders(models.Model):
coop_logger.error('Orders get_custom_barcode_labels_to_print(oids) : %s', str(e))
return labels_data
class CagetteSuppliers(models.Model):
@staticmethod
def get_suppliers():
api = OdooAPI()
f = ['id', 'name', 'display_name']
c = [['supplier', '=', 1], ['parent_id', '=', False]]
res = api.search_read('res.partner', c, f)
return res
\ No newline at end of file
#form_container {
margin-top: 30px;
}
#supplier_input {
width: 500px;
margin-right: 10px;
border-radius: 5px;
}
\ No newline at end of file
var suppliers_list = [],
products_table = null,
selected_suppliers = [],
products = [];
const datatable_base_columns = ['Produit']
function save_supplier_products(supplier, new_products) {
products = products.concat(new_products);
// TODO: Map supplier and products
// TODO: Concatenate same product in products list
}
function display_products() {
// Empty datatable if already exists
if (products_table) {
products_table.destroy();
}
/*
* TODO:
* - prepare data for datatable:
* for each product: 1 column for each supplier
* if product not related to the supplier: 'X' (clikable -> value = '')
* else: '' (render input)
* - dynamically add columns to datatables
* - remove "width: 100%" from table and allow vertical scrolling in case of many suppliers
* ...
*/
products_table = $('#products_table').DataTable({
data: products,
columns:[
{
data:"name",
title:"Produit"
}
],
order: [
[
0,
"asc"
]
],
dom: 'lrtip', // TODO: change DOM display?
iDisplayLength: 100,
language: {url : '/static/js/datatables/french.json'}
});
$('.main').show();
}
$(document).ready(function() {
$.ajaxSetup({ headers: { "X-CSRFToken": getCookie('csrftoken') } });
openModal();
// Get suppliers
$.ajax({
type: 'GET',
url: "/orders/get_suppliers",
dataType:"json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function(data) {
suppliers_list = data.res;
// Set up autocomplete on supplier input
$( "#supplier_input" ).autocomplete({
source: suppliers_list.map(a => a.display_name)
});
closeModal();
},
error: function(data) {
err = {msg: "erreur serveur lors de la récupération des fournisseurs", ctx: 'get_suppliers'};
if (typeof data.responseJSON != 'undefined' && typeof data.responseJSON.error != 'undefined') {
err.msg += ' : ' + data.responseJSON.error;
}
report_JS_error(err, 'orders');
closeModal();
alert('Erreur lors de la récupération des fournisseurs, rechargez la page plus tard');
}
});
$("#supplier_form").on("submit", function(e) {
e.preventDefault();
const user_input = $("#supplier_input").val();
// Check if user input is a valid supplier
let supplier = null;
for (const supplier_item of suppliers_list) {
if (user_input === supplier_item.display_name) {
supplier = supplier_item;
}
}
if (supplier != null) {
openModal();
selected_suppliers.push(supplier);
let url = "/orders/get_supplier_products";
url += "?sid=" + encodeURIComponent(supplier.id);
// Fetch supplier products
$.ajax({
type: 'GET',
url: url,
dataType:"json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function(data) {
save_supplier_products(supplier, data.res.products);
// TODO: display suppliers on page
display_products();
$("#supplier_input").val("")
closeModal();
},
error: function(data) {
err = {msg: "erreur serveur lors de la récupération des produits", ctx: 'get_supplier_products'};
if (typeof data.responseJSON != 'undefined' && typeof data.responseJSON.error != 'undefined') {
err.msg += ' : ' + data.responseJSON.error;
}
report_JS_error(err, 'orders');
closeModal();
alert('Erreur lors de la récupération des produits, réessayer plus tard.');
}
});
} else {
alert("Le fournisseur renseigné n'est pas valide.\n"
+ "Veuillez sélectionner un fournisseur dans la liste déroulante.")
}
})
});
......@@ -8,5 +8,8 @@ urlpatterns = [
url(r'^export/([0-9]+)', views.export_one),
url(r'^export/([a-z]+)', views.export_regex),
url(r'^get_pdf_labels$', views.get_pdf_labels),
url(r'^print_product_labels$', views.print_product_labels)
url(r'^print_product_labels$', views.print_product_labels),
url(r'^helper$', views.helper),
url(r'^get_suppliers$', views.get_suppliers),
url(r'^get_supplier_products$', views.get_supplier_products),
]
from outils.common_imports import *
from outils.for_view_imports import *
from orders.models import Order, Orders
from products.models import CagetteProduct
from orders.models import Order, Orders, CagetteSuppliers
from products.models import CagetteProduct, CagetteProducts
from openpyxl import Workbook
from openpyxl.writer.excel import save_virtual_workbook
......@@ -13,6 +13,38 @@ def as_text(value): return str(value) if value is not None else ""
def index(request):
return HttpResponse('Orders')
def helper(request):
context = {
'title': 'Aide à la commande',
}
template = loader.get_template('orders/helper.html')
return HttpResponse(template.render(context, request))
def get_suppliers(request):
""" Get suppliers list """
res = {}
try:
res = CagetteSuppliers.get_suppliers()
except Exception as e:
res["error"] = str(e)
return JsonResponse(res, status=500)
return JsonResponse({'res': res})
def get_supplier_products(request):
""" Get supplier products """
sid = request.GET.get('sid', '')
res = CagetteProducts.get_products_by_supplier(sid)
if 'error' in res:
return JsonResponse(res, status=500)
else:
return JsonResponse({'res': res})
def export_one(request, oid):
msg = ''
try:
......
......@@ -99,6 +99,7 @@ STATICFILES_DIRS = (
"website/static",
"shop/static",
"shelfs/static",
"orders/static",
# "tests/static"
)
......
......@@ -6,6 +6,7 @@ from outils.common import OdooAPI
import csv
import tempfile
import pymysql.cursors
import datetime
vcats = []
......@@ -387,6 +388,44 @@ class CagetteProducts(models.Model):
bc_map[bc] = bc
return bc_map
@staticmethod
def get_products_by_supplier(supplier_id):
api = OdooAPI()
res = {}
# todo : try with no result
try:
today = datetime.date.today().strftime("%Y-%m-%d")
print(today)
# Get products/supplier relation
f = ["product_tmpl_id", 'date_start', 'date_end']
c = [['name', '=', int(supplier_id)]]
psi = api.search_read('product.supplierinfo', c, f)
# Filter valid data
ptids = []
for p in psi:
if (p["product_tmpl_id"] is not False
and (p["date_start"] is False or p["date_start"] < today)
and (p["date_end"] is False or p["date_end"] < today)):
ptids.append(p["product_tmpl_id"][0])
# Get products templates
f = ["id", "state", "product_variant_ids", "name"]
c = [['id', 'in', ptids], ['purchase_ok', '=', True]]
products_t = api.search_read('product.template', c, f)
filtered_products_t = [p for p in products_t if p["state"] != "end" and p["state"] != "obsolete"]
# TODO get additional product data (product_variant_ids -> list of product.product)
res["products"] = filtered_products_t
except Exception as e:
print(str(e))
res["error"] = str(e)
return res
class OFF(models.Model):
"""OpenFoodFact restricted DB queries."""
......
......@@ -10,10 +10,6 @@ def index(request):
context = {'title': 'Export de ventes'}
template = loader.get_template('sales/index.html')
# m = CagetteSales()
# sales = m.get_sales()
# print(sales)
return HttpResponse(template.render(context, request))
def get_sales(request):
......
{% extends "base.html" %}
{% load static %}
{% block additionnal_css %}
<link rel="stylesheet" href="{% static 'css/datatables/jquery.dataTables.css' %}">
<link rel="stylesheet" href="{% static 'jquery-ui-1.12.1/jquery-ui.min.css' %}">
<link rel="stylesheet" href="{% static 'css/oders_helper_style.css' %}">
{% endblock %}
{% block additionnal_scripts %}
<script type="text/javascript" src="{% static 'jquery-ui-1.12.1/jquery-ui.min.js' %}?v="></script>
<script type="text/javascript" src="{% static 'js/datatables/jquery.dataTables.min.js' %}"></script>
{% endblock %}
{% block content %}
<div class="page_body">
<div class="header txtcenter">
<h1>Aide à la commande</h1>
</div>
<div class="txtcenter" id="form_container">
<form action="javascript:;" id="supplier_form">
<input type="text" name="supplier" id="supplier_input" placeholder="Rechercher un fournisseur par son nom">
<button type="submit" class='btn--primary'>Ajouter le fournisseur</button>
</form>
</div>
<div class="main" style="display:none;">
<div class="table_area">
<table id="products_table" class="display" cellspacing="0" width="100%"></table>
</div>
</div>
</div>
<script src="{% static "js/all_common.js" %}?v="></script>
<script type="text/javascript" src="{% static 'js/orders_helper.js' %}?v="></script>
{% endblock %}
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