# app/views/booking.py
from flask import Blueprint, render_template, request, Response, current_app
from webapp.models.products import *
from webapp.models.facture import *
from webapp.models.user import *
from webapp import db
from datetime import datetime
from webapp.config import Config
from webapp.views.auth import admin_required
from escpos.printer import Dummy
import base64
from base64 import b64encode
from PIL import Image
import os


frontoffice = Blueprint("frontoffice", __name__)


@frontoffice.before_request
def make_session_permanent():
	session.permanent=True
	session.modified=True

@frontoffice.route("/")
def index():
	return redirect(url_for("frontoffice.panier"))


@frontoffice.route("/panier")
@login_required
def panier():
	current=current_user
	cart=[]
	if session.get("cart", None):
		cart=session.get("cart")
	all_articles=Article.query.all()
	ARTICLE={}

	for article in all_articles:
		ARTICLE[article.id]={
						"article_id":article.id,
						"article_code":article.code,
						"article_nom":article.nom,
						"prix":article.prix_vente_html,
						}
	return render_template("panier.html", all_articles=all_articles,current=current, cart=cart, ARTICLE=ARTICLE)

@frontoffice.route('/liste/article')
@login_required
def liste_articles():
    current=current_user
    all_articles=Article.query.all()
    form = ArticleForm()
    return render_template('liste_articles.html', current=current, all_articles=all_articles, form=form)

@frontoffice.route("/add/article", methods=["POST"])
@login_required
def add_article():
	current=current_user
	data=request.form.to_dict(flat=True)
	code=data["code"].strip().upper()
	nom=data["nom"].strip().upper()
	unite=data["unite"].strip().upper()
	prix_achat=Decimal(data["prix_achat"]) if data["prix_achat"]!="" else Decimal("0")
	prix_vente=Decimal(data["prix_vente"]) if data["prix_vente"]!="" else Decimal("0")
	query=Article.query.filter_by(code=code).first()
	if not query:
		new_article=Article(nom=nom, code=code, unite=unite, prix_achat=prix_achat, prix_vente=prix_vente)
		db.session.add(new_article)
		now=datetime.now()
		new_story=HistoriquePrix(
								date=now,
								article=new_article,
								motif='AJOUT',
								session=session["username"],
								prix_achat=prix_achat,
								prix_vente=prix_vente
								)
		db.session.add(new_story)
		db.session.commit()
	return redirect(url_for("frontoffice.liste_articles"))

@frontoffice.route("/edit/article", methods=["POST"])
@login_required
def edit_article():
	current=current_user
	now=datetime.now()
	data=request.form.to_dict(flat=True)
	code=data["code"].strip().upper()
	nom=data["nom"].strip().upper()
	unite=data["unite"].strip().upper()
	prix_achat=Decimal(data["prix_achat"]) if data["prix_achat"]!="" else Decimal("0")
	prix_vente=Decimal(data["prix_vente"]) if data["prix_vente"]!="" else Decimal("0")
	article=Article.query.filter_by(id=int(request.args["id"])).first()
	article.code=code
	article.nom=nom
	article.unite=unite
	if prix_achat+prix_vente!=article.prix_achat+article.prix_vente:
		print("Modification prix")
		article.prix_achat=prix_achat
		article.prix_vente=prix_vente
		new_story=HistoriquePrix(
								date=now,
								article=article,
								motif='MODIFICATION',
								session=session["username"],
								prix_achat=prix_achat,
								prix_vente=prix_vente
								)
		db.session.add(new_story)
	db.session.commit()
	return redirect(url_for("frontoffice.liste_articles"))

@frontoffice.route("/cart/update" , methods=["POST"])
@login_required
def cart_update():
	data = request.get_json()
	error=[]
	error_name=[]
	for index, d in enumerate(data):
		article=Article.query.filter_by(id=int(d["article_id"])).first()
		if not article:
			error.append(index)
			error_name.append({"name":d["name"], "stock":0})

	status=""
	if not error:
		status="OK"
	else:
		status="ERROR"
	for e in error:
		data.pop(e)
	session["cart"]=data
	print(data)
	return jsonify({"status": status, "error": error_name})


@frontoffice.route("/livraison/update" , methods=["POST"])
@login_required
def livraison_update():
	data = request.get_json()
	error=[]
	error_name=[]
	for index, d in enumerate(data):
		article=Article.query.filter_by(id=int(d["article_id"])).first()
		if not article:
			error.append(index)
			error_name.append({"name":d["name"], "stock":0})

	status=""
	if not error:
		status="OK"
	else:
		status="ERROR"
	for e in error:
		data.pop(e)
	session["livraison"]=data

	return jsonify({"status": status, "error": error_name})


@frontoffice.route("/commande/update" , methods=["POST"])
@login_required
def commande_update():

	data = request.get_json()
	error=[]
	error_name=[]
	for index, d in enumerate(data):
		article=Article.query.filter_by(id=int(d["article_id"])).first()
		if not article:
			error.append(index)
			error_name.append({"name":d["name"], "stock":0})

	status=""
	if not error:
		status="OK"
	else:
		status="ERROR"
	for e in error:
		data.pop(e)
	session["commande"]=data
	print("COMMANDE UPDATE:  ", session["commande"])
	return jsonify({"status": status, "error": error_name})

@frontoffice.route("/checkout/cart")
@login_required
def checkout():
	current=current_user
	data=session.get("cart",[])
	CHECKOUT={}
	TOTAL=Decimal(0)
	REMISE=Decimal(0)
	for cart in data:
		article=Article.query.filter_by(id=int(cart["article_id"])).first()
		quantity=int(cart["quantity"])
		total_remise=Decimal(cart["total_remise"])
		sous_total=Decimal(cart["sous_total"])
		REMISE+=total_remise
		TOTAL+=sous_total
		CHECKOUT[article]={"quantity":quantity,"subtotal":str(sous_total),"remise":str(total_remise),"prix_unit":article.prix_vente_html}
	all_client=Client.query.all()
	all_caisse=Caisse.query.all()
	return render_template("checkout.html",data=data, current=current,all_client=all_client,all_caisse=all_caisse, CHECKOUT=CHECKOUT, TOTAL=str(TOTAL), REMISE=str(REMISE))

def bigname(name):
	return name.strip().upper()

@frontoffice.route("/checkout/cart", methods=["POST"])
@login_required
def save_checkout():
	current=current_user
	data=session["cart"]
	info=request.form.to_dict(flat=True)
	client_id=int(info["client"])
	client=None
	if client_id==0:
		query=Client.query.filter_by(phone=bigname(info["phone"])).first()
		if query:
			client=query
		else:
			client=Client(
							nom=bigname(info["nom"]),
							phone=bigname(info["phone"]),
							code=NumClient.get_number(),
							address=bigname(info["address"]))
			db.session.add(client)
		info.pop("phone")
		info.pop("nom")
		info.pop("address")
	else:
		client=Client.query.filter_by(id=int(client_id)).first()
	date=datetime.strptime(info.pop("date"), "%Y-%m-%d")
	new_commande=CommandeClient(date=date,client=client, numero=NumFacture.get_number())
	net_payer=Decimal("0")
	total_remise=Decimal("0")
	for cart in data:
		net_payer+=Decimal(cart["sous_total"])
		total_remise+=Decimal(cart["total_remise"])
		article=Article.query.filter_by(id=int(cart["article_id"])).first()
		detail=DetailCommandeClient(
				commande_client=new_commande,
				article_id=int(cart["article_id"]),
				article_code=cart["code"],
				article_name=cart["nom"],
				prix_unit=article.prix_vente,
				quantite=int(cart["quantity"]),
				remise=Decimal(int(cart['total_remise'])/int(cart["quantity"]))
				)
		db.session.add(detail)
	new_commande.net_payer=net_payer
	new_commande.total_remise=total_remise
	client.credit+=net_payer
	new_balance=BalanceTiers(affectation="COMMANDE",date=date,client=client,credit=net_payer,solde=client.solde,commande_client=new_commande)
	db.session.add(new_commande)
	db.session.add(new_balance)
	session["cart"]=[]
	if info["montant"]!="0":
		new_reg=Reglement(date=date,commande_client=new_commande,montant=Decimal(info["montant"]),mode=info["mode"],numero_recu=NumRecu.get_number())
		db.session.add(new_reg)
		client.debit+=Decimal(info["montant"])
		caisse=Caisse.query.filter_by(id=info.pop("caisse")).first()
		new_recette=Recette(
							date=date,
							caisse=caisse,
							ref=new_reg.numero_recu,
							libelle="REGLEMENT",
							affectation=new_commande.numero,
							montant=Decimal(info["montant"])
							)
		db.session.add(new_recette)
		caisse.recette_val+=Decimal(info["montant"])
		journal=JournalCaisse(
								date=date,
								caisse=caisse,
								affectation="REGLEMENT",
								recette=new_recette,
								entree=Decimal(info["montant"]),
								solde=caisse.solde_val
							)
		debit_balance=BalanceTiers(affectation="REGLEMENT",date=date,client=client,debit=Decimal(info["montant"]),solde=client.solde,reglement=new_reg)
		db.session.add(journal)
		db.session.add(debit_balance)
	info.pop("mode")
	info.pop("montant")
	info.pop("client")
	for livraison, qte in info.items():
		if int(qte)!=0:
			article_id=int(livraison.split("_")[1])
			article_livre=Article.query.filter_by(id=article_id).first()
			article_livre.stock-=int(qte)
			new_livraison=Livraison(date=date,commande_client=new_commande,article=article_livre, quantite=int(qte))
			db.session.add(new_livraison)
	db.session.commit()

	return redirect(url_for("frontoffice.liste_commande"))

@frontoffice.route("/commande")
@login_required
def liste_commande():
	current=current_user
	all_commande=CommandeClient.query.order_by(db.desc(CommandeClient.id)).all()
	all_caisse=Caisse.query.all()
	return render_template("liste_commande.html",all_caisse=all_caisse, all_commande=all_commande, current=current)



@frontoffice.route("/commande/client")
@login_required
def liste_commande_client():
	current=current_user
	client=Client.query.filter_by(id=int(request.args["id"])).first()
	total_achat=Decimal(0)
	all_commande=CommandeClient.query.filter_by(client=client).order_by(db.desc(CommandeClient.id)).all()
	for commande in all_commande:
		total_achat+=commande.net_payer
	all_client=Client.query.order_by(db.desc(Client.code)).all()
	return render_template("liste_commande_client.html", all_client=all_client,client=client,all_commande=all_commande, current=current,total_achat=str(total_achat))

@frontoffice.route("/client")
@login_required
def liste_client():
	current=current_user
	all_client=Client.query.order_by(db.desc(Client.code)).all()

	return render_template("liste_client.html", current=current, all_client=all_client)



@frontoffice.route("/reglement/add", methods=["POST"])
@login_required
def add_reglement():
	current=current_user
	data=request.form.to_dict(flat=True)
	commande=CommandeClient.query.filter_by(id=int(request.args["id"])).first()
	date=datetime.strptime(data["date"],"%Y-%m-%d")
	caisse=Caisse.query.filter_by(id=int(data["caisse"])).first()

	new_reg=Reglement(date=date,commande_client=commande,montant=Decimal(data['montant']), mode=bigname(data['mode']),numero_recu=NumRecu.get_number())
	db.session.add(new_reg)
	new_recette=Recette(
						date=date,
						ref=new_reg.numero_recu,
						libelle="REGLEMENT",
						affectation=commande.numero,
						montant=Decimal(data["montant"]),
						caisse=caisse
						)
	db.session.add(new_reg)
	db.session.add(new_recette)
	caisse.recette_val+=Decimal(data["montant"])
	client=commande.client
	client.debit+=Decimal(data['montant'])
	journal=JournalCaisse(
								date=date,
								caisse=caisse,
								affectation="REGLEMENT",
								recette=new_recette,
								entree=Decimal(data["montant"]),
								solde=caisse.solde_val
							)
	debit_balance=BalanceTiers(affectation="REGLEMENT",date=date,client=client,debit=Decimal(data["montant"]),solde=client.solde,reglement=new_reg)
	db.session.add(journal)
	db.session.add(debit_balance)
	db.session.commit()
	return redirect(url_for("frontoffice.liste_commande"))


@frontoffice.route("/versement/new", methods=["POST"])
@login_required
def versement_new():
	current=current_user
	data=request.form.to_dict(flat=True)
	date=datetime.strptime(data["date"],"%Y-%m-%d")
	montant=Decimal(data["montant"])
	frais=Decimal(data["frais"])
	ref=data["ref"].strip().upper()
	new_versement=VersementFournisseur(date=date,montant=montant,frais=frais,ref=ref, fournisseur_id=int(data["fournisseur_id"]))
	db.session.add(new_versement)
	db.session.commit()
	return redirect(url_for("frontoffice.list_versement"))


@frontoffice.route('/json/commande')
@login_required
def detail_commande():
	commande=CommandeClient.query.filter_by(id=int(request.args["id"])).first()
	JSON={
			"commande_id":commande.id,
			"date":commande.date_html,
			"numero":commande.numero,
			"client_nom":commande.client.nom,
			"client_code":commande.client.code,
			"net_payer":commande.net_payer_str,
			"total_remise":commande.total_remise_str,
			"detail":[],
			"reglement":[],
			"reste":0
			}
	for detail in commande.detail_commande_client:
		JSON["detail"].append({
			"article_code":detail.article_code,
			"pu":detail.pu_html,
			"quantite":detail.quantite,
			"remise": detail.remise_html,
			"sous_total":str(detail.sous_total),
			"livre":detail.qty_livre()
			})
	reste=commande.net_payer
	for reg in commande.reglement:
		reste-=reg.montant
		JSON["reglement"].append({"date":reg.date_str,"mode":reg.mode,"montant":reg.montant_str})
	JSON["reste"]=str(reste)
	return jsonify(JSON)

@frontoffice.route('/json/impression')
@login_required
def impression_document():
	commande=CommandeClient.query.filter_by(id=int(request.args["id"])).first()
	livraison=commande.livraison
	reglement=commande.reglement
	JSON={
			"commande_id":commande.id,
			"numero":commande.numero,
			"reglement":[],
			"livraison":[]
			}
	total_liv=set()
	for liv in livraison:
		total_liv.add(liv.date_str)

	JSON["livraison"]=list(total_liv)
	for reg in reglement:
		JSON["reglement"].append({reg.date_str:reg.id})
	return jsonify(JSON)

@frontoffice.route('/json/livraison')
@login_required
def detail_livraison():
	livraison=LivraisonFournisseur.query.filter_by(id=int(request.args["id"])).first()
	JSON={
			"livraison_id":livraison.id,
			"date":livraison.date_html,
			"ref":livraison.ref,
			"net_payer":livraison.net_payer_str,
			"montant":livraison.montant_str,
			"detail":[],
			"reglement":[]
			}
	for detail in livraison.livraison_fournisseur_detail:
		JSON["detail"].append({
			"article_code":detail.article_code,
			"pu":detail.prix_achat_str,
			"quantite":detail.quantite,
			"sous_total":str(detail.sous_total_str)
			})
	for reg in livraison.reglement_fournisseur:
		JSON["reglement"].append({"date":reg.date_str, "montant_paye":reg.montant_str, "mode":reg.mode}) 
	return jsonify(JSON)


@frontoffice.route('/json/commande/fournisseur')
@login_required
def detail_commande_fournisseur():
	commande=CommandeFournisseur.query.filter_by(id=int(request.args["id"])).first()
	JSON={
			"commande_id":commande.id,
			"date":commande.date_html,
			"numero":commande.numero,
			"montant_commande":commande.montant_str,
			"detail":[],
			"livraison":[]
			}
	for detail in commande.detail_commande_fournisseur:
		JSON["detail"].append({
			"article_code":detail.article_code,
			"pu":detail.prix_achat_str,
			"quantite":detail.quantite,
			"sous_total":str(detail.sous_total_str)
			})
	
	livraisons=commande.livraison_fournisseur
	liv_total={}
	for livraison in livraisons:
		for detail in livraison.livraison_fournisseur_detail:
			if not detail.article_code in liv_total:
				liv_total[detail.article_code]=detail.quantite
			else:
				liv_total[detail.article_code]+=detail.quantite
	JSON["livraison"]=liv_total
	print(JSON)
	return jsonify(JSON)



@frontoffice.route("/poussin/add_reservation", methods=["POST"])
@login_required
def save_reservation():
	current=current_user
	info=request.form.to_dict(flat=True)
	client_id=int(info["client"])
	client=None
	montant=Decimal(info["avance"])
	if client_id==0:
		query=Client.query.filter_by(phone=bigname(info["phone"])).first()
		if query:
			client=query
		else:
			client=Client(nom=bigname(info["nom"]), phone=bigname(info["phone"]), code=NumClient.get_number())
			db.session.add(client)
	else:
		client=Client.query.filter_by(id=int(client_id)).first()

	new_reserve=ReseravationPoussin(
									client=client,
									avance=montant,
									date_reservation=datetime.strptime(info["date_reservation"], "%Y-%m-%d"),
									quantite_commande=int(info["quantite_commande"]),
									prix=Decimal(info["prix"])
									)
	db.session.add(new_reserve)
	client.debit+=montant
	new_reg=Reglement(montant=montant,mode=info["mode"],numero_recu=NumRecu.get_number())
	db.session.add(new_reg)
	caisse=Caisse.query.filter_by(id=info.pop("caisse_id")).first()
	new_recette=Recette(
						caisse=caisse,
						ref=new_reg.numero_recu,
						libelle="AVANCE POUSSIN",
						affectation=client.full_name,
						montant=montant
						)
	db.session.add(new_recette)
	caisse.recette_val+=montant
	journal=JournalCaisse(
						caisse=caisse,
						affectation="AVANCE POUSSIN",
						recette=new_recette,
						entree=montant,
						solde=caisse.solde_val
						)
	debit_balance=BalanceTiers(affectation="AVANCE POUSSIN",client=client,debit=montant,solde=client.solde,reglement=new_reg)
	db.session.add(journal)
	db.session.add(debit_balance)
	db.session.commit()
	return redirect(url_for("frontoffice.reservation_poussin"))

@frontoffice.route("/poussin/reservation")
@login_required
def reservation_poussin():
	current=current_user
	all_client=Client.query.order_by(db.desc(Client.code)).all()
	all_reservation=ReseravationPoussin.query.order_by(db.desc(ReseravationPoussin.date_reservation)).all()
	all_caisse=Caisse.query.all()
	return render_template("liste_reservation_poussin.html",all_caisse=all_caisse,all_client=all_client, current=current, all_reservation=all_reservation)

@frontoffice.route("/caisses")
@login_required
def caisses():
	current=current_user
	all_caisse=Caisse.query.all()
	return render_template("liste_caisse.html", current=current, all_caisse=all_caisse)

@frontoffice.route("/add/caisse", methods=["POST"])
@login_required
def add_caisse():
	current=current_user
	new_caisse=Caisse(name=request.form["name"])
	db.session.add(new_caisse)
	db.session.commit()
	return redirect(url_for("frontoffice.caisses"))


@frontoffice.route("/balance/client")
@login_required
def balance_client():
	current=current_user
	client=Client.query.filter_by(id=int(request.args["id"])).first()
	all_balance=BalanceTiers.query.filter_by(client=client).order_by(db.desc(BalanceTiers.id)).all()
	all_client=Client.query.order_by(db.desc(Client.code)).all()
	return render_template("balance_tiers.html", current=current, client=client, all_balance=all_balance, all_client=all_client)

@frontoffice.route("/balance/fournisseur")
@login_required
def balance_fournisseur():
	current=current_user
	fournisseur=Fournisseur.query.filter_by(id=int(request.args["id"])).first()
	all_balance=BalanceFournisseur.query.filter_by(fournisseur=fournisseur).order_by(db.desc(BalanceFournisseur.id)).all()
	
	return render_template("balance_fournisseur.html", current=current, fournisseur=fournisseur, all_balance=all_balance)

@frontoffice.route("/fournisseurs")
@login_required
def fournisseur():
	current=current_user
	fournisseur=Fournisseur.query.first()
	return render_template("fournisseur.html", current=current, fournisseur=fournisseur)

@frontoffice.route("/add/fournisseur", methods=["POST"])
@login_required
def add_fournisseur():
	current=current_user
	fournisseur=Fournisseur.query.first()
	if fournisseur:
		return "SEULEMENT UN FOURNISSEUR AUTORISE"
	else:
		db.session.add(Fournisseur(nom=request.form["name"].strip().upper()))
		db.session.commit()
		return redirect(url_for("frontoffice.fournisseur"))

@frontoffice.route("/fournisseur/livraison")
@login_required
def liste_livraison_fournisseur():
	current=current_user
	current_livraison=session.get("livraison",None)
	if current_livraison:
		return redirect(url_for("frontoffice.panier_fournisseur"))
	else:
		all_caisse=Caisse.query.all()
		all_livraison=LivraisonFournisseur.query.order_by(db.desc(LivraisonFournisseur.id)).all()
		return render_template("livraison_fournisseur.html", current=current,all_caisse=all_caisse, all_livraison=all_livraison)


@frontoffice.route("/fournisseur/commande")
@login_required
def liste_commande_fournisseur():
	current=current_user
	current_commande=session.get("commande",None)
	if current_commande:
		return redirect(url_for("frontoffice.panier_commande"))
	else:
		livraison=session.get("livraison",None)
		if not livraison:
			all_caisse=Caisse.query.all()
			all_commande=CommandeFournisseur.query.order_by(db.desc(CommandeFournisseur.id)).all()
			return render_template("commande_fournisseur.html", current=current,all_caisse=all_caisse, all_commande=all_commande)
		else:
			current_commande=session["cid"]
			return redirect(url_for("frontoffice.panier_fournisseur", cid=current_commande))


@frontoffice.route("/panier/fournisseur")
@login_required
def panier_fournisseur():
	current=current_user
	cid=request.args.get("cid",None)
	livraison=[]
	if session.get("livraison", None):
		livraison=session.get("livraison")
	if not cid:
		return redirect(url_for("frontoffice.liste_commande_fournisseur"))
	else:
		session["cid"]=int(cid)
		commande=CommandeFournisseur.query.filter_by(id=int(cid)).first()
		all_articles=Article.query.all()
		ARTICLE={}

		for article in all_articles:
			ARTICLE[article.id]={
							"article_id":article.id,
							"article_code":article.code,
							"article_nom":article.nom
							}
		return render_template("panier_fournisseur.html",commande=commande, all_articles=all_articles,current=current, livraison=livraison, ARTICLE=ARTICLE)


@frontoffice.route("/panier/commande")
@login_required
def panier_commande():
	current=current_user
	commande=[]
	if session.get("commande", None):
		commande=session.get("commande")
	all_articles=Article.query.all()
	ARTICLE={}

	for article in all_articles:
		ARTICLE[article.id]={
						"article_id":article.id,
						"article_code":article.code,
						"article_nom":article.nom
						}
	return render_template("panier_commande.html", all_articles=all_articles,current=current, commande=commande, ARTICLE=ARTICLE)


@frontoffice.route("/save/panier_commande", methods=["POST"])
@login_required
def save_commande_fournisseur():
	print("save panier commande")
	current=current_user
	data=request.form.to_dict(flat=True)
	commande=session.get("commande",None)
	fournisseur=Fournisseur.query.first()
	date=datetime.strptime(data["date"], "%Y-%m-%d")
	if not commande:
		return redirect(url_for("frontoffice.liste_commande_fournisseur"))
	else:
		new_commande=CommandeFournisseur(
										date=date,
										numero=NumCommande.get_number(),
										fournisseur=fournisseur,
										montant_commande=Decimal(data["montant"])
										)
		db.session.add(new_commande)
		for detail in commande:
			article=Article.query.filter_by(id=int(detail["article_id"])).first()
			new_detail=DetailCommandeFournisseur(
										commande_fournisseur=new_commande,
										article=article,
										article_code=article.code,
										article_name=article.nom,
										quantite=int(detail["quantity"])
										)
			db.session.add(new_detail)
		db.session.commit()
		session["commande"]=None
	return redirect(url_for("frontoffice.liste_commande_fournisseur"))




@frontoffice.route("/save/panier_fournisseur", methods=["POST"])
@login_required
def checkout_livraison():
	current=current_user
	data=request.form.to_dict(flat=True)
	livraison=session.get("livraison",None)
	cid=session.get("cid",None)
	commande=CommandeFournisseur.query.filter_by(id=int(cid)).first()
	fournisseur=Fournisseur.query.first()
	if not livraison:
		return redirect(url_for("frontoffice.liste_livraison_fournisseur"))
	else:
		new_livraison=LivraisonFournisseur(
						date=datetime.strptime(data["date"], "%Y-%m-%d"),
						fournisseur=fournisseur,
						net_payer=Decimal(data["net_payer"]),
						ref=data["ref"].strip(),
						commande_fournisseur=commande
						)
		montant=Decimal(0)
		for detail in livraison:
			article=Article.query.filter_by(id=int(detail["article_id"])).first()
			
			new_detail=LivraisonFournisseurDetail(
				livraison_fournisseur=new_livraison,
				article=article,
				article_code=article.code,
				article_name=article.nom,
				prix_achat_unit=Decimal(detail['prix_achat']),
				quantite=int(detail["quantity"])
				)
			article.stock+=int(detail["quantity"])
			montant+=Decimal(detail['sous_total'])
			db.session.add(new_detail)
			if Decimal(detail['prix_achat'])!=article.prix_achat:
				article.prix_achat=Decimal(detail['prix_achat'])

		new_livraison.montant=montant
		db.session.add(new_livraison)
		fournisseur.credit+=Decimal(data["net_payer"])
		new_balance=BalanceFournisseur(
					date=datetime.strptime(data["date"], "%Y-%m-%d"),
					affectation="ACHAT FOURNISSEUR",
					fournisseur=fournisseur,
					credit=Decimal(data["net_payer"]),
					solde=fournisseur.solde,
					livraison_fournisseur=new_livraison
					)
		db.session.add(new_balance)
		db.session.commit()
		session["livraison"]=[]
		session["cid"]=None
		return redirect(url_for("frontoffice.liste_livraison_fournisseur"))


@frontoffice.route("/journal/caisse")
@login_required
def journal_caisse():
	current=current_user
	caisse=Caisse.query.filter_by(id=int(request.args["cid"])).first()
	all_journal=JournalCaisse.query.filter_by(caisse=caisse).order_by(db.desc(JournalCaisse.id)).all()
	all_caisse=Caisse.query.all()
	return render_template("journal_caisse.html", current=current,all_caisse=all_caisse, caisse=caisse, all_journal=all_journal) 

@frontoffice.route("/depense/caisse")
@login_required
def depense_caisse():
	current=current_user
	caisse=Caisse.query.filter_by(id=int(request.args["cid"])).first()
	all_depense=SortieCaisse.query.filter_by(caisse=caisse).order_by(db.desc(SortieCaisse.id)).all()
	all_caisse=Caisse.query.all()
	return render_template("depense_caisse.html", current=current,all_caisse=all_caisse, caisse=caisse, all_depense=all_depense) 

@frontoffice.route("/recette/caisse")
@login_required
def recette_caisse():
	current=current_user
	caisse=Caisse.query.filter_by(id=int(request.args["cid"])).first()
	all_recette=Recette.query.filter_by(caisse=caisse).order_by(db.desc(Recette.id)).all()
	all_caisse=Caisse.query.all()
	return render_template("recette_caisse.html", current=current,all_caisse=all_caisse, caisse=caisse, all_recette=all_recette) 



@frontoffice.route("/gerant")
@admin_required
def gerant():
	current=current_user
	all_gerant=Gerant.query.all()
	return render_template("liste_gerant.html", current=current, all_gerant=all_gerant)


@frontoffice.route("/add/gerant", methods=["POST"])
@admin_required
def add_gerant():
	current=current_user
	new_gerant=Gerant(nom=request.form["name"])
	db.session.add(new_gerant)
	db.session.commit()
	return redirect(url_for("frontoffice.gerant"))


@frontoffice.route('/transfert')
@login_required
def transfert():
	current=current_user
	all_caisse=Caisse.query.all()
	all_transfert=Transfert.query.order_by(db.desc(Transfert.id)).all()
	return render_template("transfert.html",current=current, all_caisse=all_caisse, all_transfert=all_transfert)

@frontoffice.route('/add/transfert', methods=["POST"])
@login_required
def add_transfert():
	current=current_user
	data=request.form.to_dict(flat=True)
	date=datetime.strptime(data["date"], "%Y-%m-%d")
	caisse_in=int(data["caisse_in"])
	caisse_out=int(data["caisse_out"])
	montant=Decimal(data["montant"])
	new_transfert=Transfert.make_transfert(date,caisse_in,caisse_out,montant)
	return redirect(url_for("frontoffice.transfert"))



@frontoffice.route("/rawbt-receipt")
@login_required
def rawbt_receipt():
	now=datetime.now()
	logo_path = os.path.join(current_app.root_path, 'static', 'img', 'logofarm.png')
	commande=CommandeClient.query.filter_by(id=int(request.args["id"])).first()
	detail=commande.detail_commande_client
	dummy = Dummy()
	dummy.set(align="center")
	dummy.image(logo_path)
	dummy.text("******************************\n")
	dummy.set(width=2, height=2, bold=True)
	dummy.text("FARMSHOP ALAKAMISY FENOARIVO\n")
	dummy.set(width=1, height=1)
	dummy.text("Tél: 034 35 226 08\n")
	dummy.text("Tél: 038 32 545 63\n")
	dummy.text("******************************\n")
	dummy.text("FACTURE\n")
	dummy.set(align="left")
	dummy.text("Date: {}\n".format(commande.date_str))
	dummy.set(align="right",width=2, height=1, bold=True)
	dummy.text("FACTURE N°: {}\n".format(commande.numero))
	dummy.text("Client: {}\n".format(commande.client.nom))
	dummy.set(align="left",width=1, height=1, bold=False)
	dummy.text("________________________________\n")
	for d in detail:
		dummy.text("{}\n".format(d.article_name))
		dummy.text("{} --- {}{} x {}\n".format(d.article_code,d.quantite,d.article.unite,str(d.prix_unit)))
		dummy.set(align="right",width=1, height=1, bold=False)
		dummy.text("Rem {} ---- {}\n".format(d.remise_html,str(d.sous_total)))
		dummy.text("________________________________\n")
		dummy.set(align="left",width=1, height=1, bold=False)

	dummy.set(align="left",width=2, height=2, bold=False)
	dummy.text("Total remise: {} Ar\n".format(commande.total_remise_str))
	dummy.text("Total Net: {} Ar\n".format(commande.net_payer_str))
	dummy.text("________________________________\n")
	dummy.set(align="right",width=1, height=1, bold=False)
	dummy.text("{}\n".format(now.strftime("%d/%m/%Y")))
	dummy.cut()

	# Convert to base64
	escpos_data = dummy.output
	# print("ESCOBAR: ", escpos_data)
	base64_data = base64.b64encode(escpos_data).decode('ascii')

	# Create RawBT intent URL
	intent_url = f"intent:base64,{base64_data}#Intent;scheme=rawbt;package=ru.a402d.rawbtprinter;end;"

	return Response(
	    intent_url,
	    mimetype="text/plain"
	)


@frontoffice.route("/rawbt-reglement")
@login_required
def rawbt_reglement():
	now=datetime.now()
	logo_path = os.path.join(current_app.root_path, 'static', 'img', 'logofarm.png')
	reglement=Reglement.query.filter_by(id=int(request.args["id"])).first()
	commande=reglement.commande_client
	dummy = Dummy()
	dummy.set(align="center")
	dummy.image(logo_path)
	dummy.text("******************************\n")
	dummy.set(width=2, height=2, bold=True)
	dummy.text("FARMSHOP ALAKAMISY FENOARIVO\n")
	dummy.set(width=1, height=1)
	dummy.text("Tél: 034 35 226 08\n")
	dummy.text("Tél: 038 32 545 63\n")
	dummy.text("******************************\n")
	dummy.text("RECU DE PAIEMENT\n")
	dummy.set(align="left")
	dummy.text("Date: {}\n".format(reglement.date_str))
	dummy.set(align="right",width=2, height=1, bold=True)
	dummy.text("N°: {}\n".format(reglement.numero_recu))
	dummy.text("Client: {}\n".format(commande.client.nom))
	dummy.set(align="left",width=1, height=1, bold=False)
	dummy.text("________________________________\n")
	dummy.text("FACTURE : {}\n".format(commande.numero))
	dummy.text("MONTANT: {} Ar\n".format(commande.net_payer_str))
	dummy.text("________________________________\n")
	dummy.set(align="right",width=2, height=2, bold=False)
	dummy.text("PAYE: {} Ar\n".format(reglement.montant_str))
	dummy.text("MODE: {}\n".format(reglement.mode))
	dummy.text("________________________________\n")
	dummy.set(align="right",width=1, height=1, bold=False)
	dummy.text("{}\n".format(now.strftime("%d/%m/%Y")))
	dummy.cut()

	escpos_data = dummy.output

	base64_data = base64.b64encode(escpos_data).decode('ascii')

	# Create RawBT intent URL
	intent_url = f"intent:base64,{base64_data}#Intent;scheme=rawbt;package=ru.a402d.rawbtprinter;end;"

	return Response(
	    intent_url,
	    mimetype="text/plain"
	)


@frontoffice.route("/rawbt-livraison")
@login_required
def rawbt_livraison():
	now=datetime.now()
	logo_path = os.path.join(current_app.root_path, 'static', 'img', 'logofarm.png')
	commande=CommandeClient.query.filter_by(id=int(request.args["id"])).first()
	livraison=commande.livraison
	dummy = Dummy()
	dummy.set(align="center")
	dummy.image(logo_path)
	dummy.text("******************************\n")
	dummy.set(width=2, height=2, bold=True)
	dummy.text("FARMSHOP ALAKAMISY FENOARIVO\n")
	dummy.set(width=1, height=1)
	dummy.text("Tél: 034 35 226 08\n")
	dummy.text("Tél: 038 32 545 63\n")
	dummy.text("******************************\n")
	dummy.text("BON DE LIVRAISON\n")
	dummy.set(align="left")
	dummy.text("Date: {}\n".format(commande.date_str))
	dummy.set(align="right",width=2, height=1, bold=True)
	dummy.text("FACTURE N°: {}\n".format(commande.numero))
	dummy.text("Client: {}\n".format(commande.client.nom))
	dummy.set(align="left",width=1, height=1, bold=False)
	dummy.text("________________________________\n")

	dates=commande.date_livraison()
	for d in dates:
		dummy.text("{}\n".format(d.strftime("%d/%m/%Y")))
		dummy.set(align="right",width=1, height=1, bold=False)
		for detail in Livraison.query.filter_by(date=d, commande_client=commande).all():
			dummy.text("{} {}\n".format(detail.article.code,detail.article.nom))
			dummy.text("Qté livré --- {} {}\n".format(detail.quantite,detail.article.unite))
		dummy.text("________________________________\n")
	dummy.text("\n")	
	dummy.set(align="right",width=1, height=1, bold=False)
	dummy.text("{}\n".format(now.strftime("%d/%m/%Y")))
	dummy.cut()

	# Convert to base64
	escpos_data = dummy.output
	# print("ESCOBAR: ", escpos_data)
	base64_data = base64.b64encode(escpos_data).decode('ascii')

	# Create RawBT intent URL
	intent_url = f"intent:base64,{base64_data}#Intent;scheme=rawbt;package=ru.a402d.rawbtprinter;end;"

	return Response(
	    intent_url,
	    mimetype="text/plain"
	)


@frontoffice.route("/rawbt-caisse-out")
@login_required
def rawbt_caisse_out():
	now=datetime.now()
	logo_path = os.path.join(current_app.root_path, 'static', 'img', 'logofarm.png')
	caisse_out=SortieCaisse.query.filter_by(id=int(request.args["id"])).first()
	dummy = Dummy()
	dummy.set(align="center")
	dummy.image(logo_path)
	dummy.text("******************************\n")
	dummy.set(width=2, height=2, bold=True)
	dummy.text("FARMSHOP ALAKAMISY FENOARIVO\n")
	dummy.set(width=1, height=1)
	dummy.text("Tél: 034 35 226 08\n")
	dummy.text("Tél: 038 32 545 63\n")
	dummy.text("******************************\n")
	dummy.text("FICHE DE SORTIE DE CAISSE\n")
	dummy.set(align="left")
	dummy.text("Date: {}\n".format(caisse_out.date_str))
	dummy.set(align="right",width=2, height=1, bold=False)
	dummy.text("N°: {}\n".format(caisse_out.numero_fiche))
	dummy.text("Caisse: {}\n".format(caisse_out.caisse.name))
	dummy.text("\n")
	dummy.set(align="left",width=2, height=1, bold=False)
	dummy.text("Libelle: {}\n".format(caisse_out.libelle))
	dummy.text("affectation: {}\n".format(caisse_out.objet))
	dummy.text("Beneficiaire: {}\n".format(caisse_out.beneficiaire))
	dummy.set(align="right",width=2, height=2, bold=True)
	dummy.text("________________________________\n")
	dummy.text("Montant : {} MGA\n".format(caisse_out.montant))
	dummy.text("\n")
	dummy.set(align="center",width=1, height=1, bold=False)
	dummy.text("RESPONSABLE CAISSE \n")
	dummy.text("\n"*4)
	dummy.text("BENEFICIAIRE \n")
	dummy.text("\n"*4)
	dummy.text("________________________________\n")
	dummy.set(align="right",width=1, height=1, bold=False)
	dummy.text("Date impression: {}\n".format(now.strftime("%d/%m/%Y")))
	dummy.cut()

	# Convert to base64
	escpos_data = dummy.output
	# print("ESCOBAR: ", escpos_data)
	base64_data = base64.b64encode(escpos_data).decode('ascii')

	# Create RawBT intent URL
	intent_url = f"intent:base64,{base64_data}#Intent;scheme=rawbt;package=ru.a402d.rawbtprinter;end;"

	return Response(
	    intent_url,
	    mimetype="text/plain"
	)


@frontoffice.route("/fournisseur/versement")
@admin_required
def list_versement():
	current=current_user
	fournisseur=Fournisseur.query.first()
	all_versement=VersementFournisseur.query.filter_by(fournisseur=fournisseur).order_by(db.desc(VersementFournisseur.id)).all()
	all_caisse=Caisse.query.all()
	return render_template("versement_fournisseur.html", current=current,all_caisse=all_caisse, all_versement=all_versement, fournisseur=fournisseur)



@frontoffice.route("/caisse/sortie", methods=["POST"])
@login_required
def encaisse():
	current=current_user
	data=request.form.to_dict(flat=True)
	_type=request.args.get('type', None)
	versement_id=request.args.get("vid", None)
	caisse=Caisse.query.filter_by(id=int(data["caisse_id"])).first()
	montant=Decimal(data["montant"])
	numero_fiche=NumDepense.get_number()
	date_sortie=datetime.strptime(data["date"], "%Y-%m-%d")
	beneficiaire=data["beneficiaire"].strip().upper()
	libelle=data["libelle"].strip().upper()
	if _type=="fournisseur":
		#SortieCaisse, compte fournisseur +=debit, BalanceFrn , journalcaisse
		versement=VersementFournisseur.query.filter_by(id=int(versement_id)).first()
		total_versement=versement.montant+versement.frais
		
		if montant!=total_versement:
			return "MONTANT DOIT ETRE EGAL A {}".format(total_versement)
		else:
			fournisseur=versement.fournisseur
			
			caisse.depense_val+=montant
			versement.numero=numero_fiche
			versement.statut_encaissement="ENCAISSE"
			new_sortie=SortieCaisse(
							numero_fiche=numero_fiche,
							date_sortie=date_sortie,
							caisse=caisse,
							beneficiaire=beneficiaire,
							montant=montant,
							libelle=libelle,
							objet=versement.ref
							)
			db.session.add(new_sortie)
			versement.sortie_caisse=new_sortie
			fournisseur.debit+=versement.montant
			new_balance=BalanceFournisseur(
					date=date_sortie,
					affectation="VERSEMENT FOURNISSEUR",
					fournisseur=fournisseur,
					debit=versement.montant,
					solde=fournisseur.solde,
					versement_fournisseur=versement
					)
			db.session.add(new_balance)
			journal=JournalCaisse(
								date=date_sortie,
								caisse=caisse,
								affectation="VERSEMENT FOURNISSEUR",
								sortie_caisse=new_sortie,
								sortie=montant,
								solde=caisse.solde_val
							)
			db.session.add(journal)
			db.session.commit()
			return redirect(url_for("frontoffice.list_versement"))
	else:
		new_sortie=SortieCaisse(
							numero_fiche=numero_fiche,
							date_sortie=date_sortie,
							caisse=caisse,
							beneficiaire=beneficiaire,
							montant=montant,
							libelle=libelle,
							objet=data["objet"].strip().upper()
							)
		db.session.add(new_sortie)
		caisse.depense_val+=montant
		journal=JournalCaisse(
								date=date_sortie,
								caisse=caisse,
								affectation="DEPENSE",
								sortie_caisse=new_sortie,
								sortie=montant,
								solde=caisse.solde_val
							)
		db.session.add(journal)
		db.session.commit()
		return redirect(url_for("frontoffice.depense_caisse", cid=caisse.id))