#!/usr/bin/env python

""" 
   Copyright (C) 2003-2005 PimenTech SARL (http://www.pimentech.net)

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License as
   published by the Free Software Foundation; either version 2 of the
   License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the GNU
   General Public License for more details.

   You should have received a copy of the GNU General Public
   License along with this library; see the file COPYING.LIB.  If not,
   write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
   Boston, MA 02111-1307, USA.	
"""

from genpdf import *

class gendevis(genpdf):
	
	query_article = """
SELECT a.nom, a.description, a.code, tva.taux, ca.quantite, ca.declinaison, ca.remise, ca.montant_ht AS ca_ht, ca.montant_ttc AS ca_ttc
FROM article a, commande_article ca, devis d, tva, statut st
WHERE d.uid=%s AND d.uid=ca.ref_devis AND ca.ref_article=a.uid AND tva.uid=a.ref_tva AND ca.ref_statut=st.uid AND st.nom='valide'"""

	query_presta = """
SELECT cp.uid, cp.intitule AS prestation, cp.description, cp.remise, cp.montant_ht, cp.montant_ttc
FROM commande_prestation cp, devis d, statut st
WHERE d.uid=%s AND cp.ref_devis=d.uid AND cp.ref_statut=st.uid AND st.nom='valide'
ORDER BY cp.uid"""
		
	tokens={"ENTETE":"%# entete_from_genpdf", "INTITULE":"~", "CLIENT":"~", "ADRESSE_CLIENT":"~", "CP_CLIENT":"~", "VILLE_CLIENT":"~", "NUM_DEVIS":"~", "DESCRIPTION":"~", "DESCRIPTION_PRESTATION":"~", "ARTICLES":"~", "PRESTAS":"~", "PAIEMENT":"~", "PERIODE":"~", "ESCOMPTE":"~", "TOTAL_TVA":"~", "DETAIL_TVA":"~", "CHARGE":"0", "COMMENTAIRE":"~", "HAS_COMMENTAIRE":"0", "HAS_CLIENT_UETVA":"0", "CHARGE_COMMENTAIRE":"%# commentaire_from_genpdf", "GLOBAL_HT":"~", "GLOBAL_TTC":"~", "DATE_ACCEPTATION":"~", "DATE_EMISSION":"~", "FICHIER_LOGO":"~", "FICHIER_PIED":"~", "RAISON":"~", "ACCROCHE":"~", "MON_ADRESSE":"~", "MON_CP":"~", "MA_VILLE":"~", "MON_TEL":"~", "MON_FAX":"~", "MON_MAIL":"~", "SIRET":"~", "UE_TVA":"~", "CLIENT_UETVA":"~"}

	
	def __init__(self, uid, with_header, verbose, filedir):
		genpdf.__init__(self, uid, with_header, verbose, filedir)

	def getinfo_devis(self):
		
		req="""
SELECT d.id, d.commentaire, d.intitule, devise.nom AS devise, devise.symbole, d.date_accepte, d.date_emission, s.nom AS client, s.adresse1, s.cp, s.ville, s.logo, ms.logo,ms.pied_page,ms.raison,ms.adresse1 as mon_adresse,ms.cp as mon_cp,ms.ville as ma_ville,'TEL : '||ms.tel as mon_tel,'FAX : '||ms.fax as mon_fax,'EMAIL : '||ms.email as mon_mail,ms.siret,ms.ue_tva,ms.commentaire AS accroche
FROM devis d
LEFT JOIN view_mes_societes ms ON (d.ref_view_mes_societes=ms.uid)
LEFT JOIN devise ON (d.ref_devise=devise.uid),
view_client s
WHERE d.uid=%s AND d.ref_view_client=s.uid""" % self.UID
		self.curs.execute(req)
		if self.curs.rowcount!=1:
			self.DEBUG_INFO+=req
			print req
			raise "ERROR"
		else:
			res=self.curs.dictfetchone()
			if res['devise']=="Euro":
				devise=" \\euro"
			elif res['symbole']!='':
				devise=' '+res['symbole']
			elif res['devise']!='':
				devise=' '+res['devise']
			else:
				devise=' ?'
				
			(total_ht, total_ttc) = self.get_articles_prestas(devise)
			(remise_ht, charge_ht, remise_ttc, charge_ttc) = self.get_charges_remises(total_ht, total_ttc)
			
			if res['logo']:
				self.tokens['FICHIER_LOGO'] = self.FILEDIR + "/" + res['logo']
			if res['pied_page']:
				self.tokens['FICHIER_PIED'] = self.FILEDIR + "/" + res['pied_page']
				
			self.tokens['RAISON']=res['raison']
			self.tokens['MON_ADRESSE']=res['mon_adresse']
			self.tokens['MON_CP']=res['mon_cp']
			self.tokens['MA_VILLE']=res['ma_ville']
			self.tokens['MON_TEL']=res['mon_tel']
			self.tokens['MON_FAX']=res['mon_fax']
			self.tokens['MON_MAIL']=res['mon_mail']
			self.tokens['SIRET']=res['siret']
			self.tokens['UE_TVA']=res['ue_tva']
			

			self.tokens['ACCROCHE']=res['accroche']

			self.tokens['NUM_DEVIS']=res['id']
			if res['date_accepte']:
				self.tokens['DATE_ACCEPTATION']=res['date_accepte'].strftime('%d %B %Y')

			if res['date_emission']:
				self.tokens['DATE_EMISSION']=res['date_emission'].strftime('%d %B %Y')
			
			self.tokens['CLIENT']=res['client']
			self.tokens['CP_CLIENT']=res['cp']
			self.tokens['ADRESSE_CLIENT']=res['adresse1']
			self.tokens['VILLE_CLIENT']=res['ville']
			if res['intitule']:
				self.tokens['INTITULE']= res['intitule'].replace('&', '\\&')
			self.tokens['COMMENTAIRE'] = res['commentaire']
			if res['commentaire']:
				self.tokens['HAS_COMMENTAIRE'] = "1"
		
			self.tokens['GLOBAL_HT']= "Montant total HT & %s%s\\\\\n" % (euro_round_fr(total_ht-remise_ht+charge_ht), devise)
			if remise_ht != 0:
				self.tokens['GLOBAL_HT'] += "Dont Escompte & %s%s\\\\" % (euro_round_fr(remise_ht), devise)
			if charge_ht != 0:
				self.tokens['GLOBAL_HT'] += "Dont Charge Add. & %s%s\\\\" % (euro_round_fr(charge_ht), devise)
			self.tokens['GLOBAL_TTC']= "%s%s" % (euro_round_fr(total_ttc-remise_ttc+charge_ttc), devise)
			self.tokens['TOTAL_TVA']= "%s%s" % (euro_round_fr((total_ttc-remise_ttc+charge_ttc)-(total_ht-remise_ht+charge_ht)), devise)

			txt = ""
			for taux in add_tva.taux.keys():
				txt += "Total TVA à %s%% & %s \\euro\\\\\n" % (taux, euro_round_fr(add_tva.taux[taux] * float(taux) / 100))
				sys.stderr.write("Total tva à %s%% : %s\n" % (taux, euro_round_fr(add_tva.taux[taux] * float(taux) / 100)))
			self.tokens['DETAIL_TVA'] = txt

				
	def get_charges_remises(self, total_ht, total_ttc):
		"""Get info from table "charge_additionnelle" for facture and devis"""

		req="""SELECT ca.nom, ca.montant_ttc, ca.montant_ht, ca.absolu
		FROM charge_additionnelle ca, statut s
		WHERE ca.ref_statut=s.uid AND s.nom='valide' AND ca.ref_devis=%s
		ORDER BY ca.uid""" % self.UID

		calcul_remise_ht=0
		calcul_charge_ht=0
		calcul_remise_ttc=0
		calcul_charge_ttc=0

		self.curs.execute(req)
		if self.curs.rowcount==0:
			pass
		else:
			i=0
			self.tokens['CHARGE_COMMENTAIRE']= r"""
			\vspace*{0.5cm}
			{\bf \noindent Nota :}
			\begin{itemize}"""
			for i in range(self.curs.rowcount):
				res=self.curs.dictfetchone()
				if res['absolu']==1:
					taux = res['montant_ttc'] -  res['montant_ht']*100 / res['montant_ht']
					add_tva(res['montant_ht'], res['montant_ttc'])
					self.tokens['CHARGE_COMMENTAIRE']+= '\\item ' + res['nom']+ ' (%s HT) \n' % euro_round_fr(res['montant_ht'])
					if res['montant_ht']<0:
						calcul_remise_ht +=-res['montant_ht']
						calcul_remise_ttc +=-res['montant_ttc']
					else:
						calcul_charge_ht +=res['montant_ht']
						calcul_charge_ttc +=res['montant_ttc']
				else:
					add_tva(res['montant_ht'])
					self.tokens['CHARGE_COMMENTAIRE'] += '\\item ' + res['nom']+ ' (%s\\%%) \n' % euro_round_fr(res['montant_ht'])
					if res['montant_ht']<0:
						calcul_remise_ht += (-(total_ht-calcul_remise_ht+calcul_charge_ht)*(res['montant_ht']/100.0))
						calcul_remise_ttc += (-(total_ttc-calcul_remise_ttc+calcul_charge_ttc)*(res['montant_ht']/100.0))
					else:
						calcul_charge_ht += (total_ht-calcul_remise_ht+calcul_charge_ht)*(res['montant_ht']/100.0)
						calcul_charge_ttc += (total_ttc-calcul_remise_ttc+calcul_charge_ttc)*(res['montant_ht']/100.0)
						
			self.tokens['CHARGE_COMMENTAIRE'] += '\\end{itemize}\n'
		return calcul_remise_ht, calcul_charge_ht, calcul_remise_ttc, calcul_charge_ttc
	

def main():
	options=get_options()
	OUTFILE=options['OUTDIR']+"/devis"
	if options['TEMPLATE'] == '':
		options['TEMPLATE']='template_devis.tex'

	base=extract_base(options['DATABASE'])
	if not base:
		usage(get_options.__doc__)

	try:
		os.system('rm -f '+options['OUTDIR']+ '/pimengest2_debug')
		object=gendevis(options['UID'], options['WITH_ENTETE'], options['VERBOSE'], options['FILEDIR'])
		object.getConnection(base['base'], base['user'], base['pass'], base['host'], base['port'])
		object.getinfo_devis()
		object.replace_values(options['AFFICHAGE_TAB'], options['LATEXDIR'], options['TEMPLATE'])
	except 'ERROR':
		log(options['OUTDIR']+'/pimengest2_debug', '\n---\nCertainly not enougth information to generate the "devis". This is the query :\n---\n')
		log(options['OUTDIR']+'/pimengest2_debug', object.DEBUG_INFO)
		sys.exit(-1)
		
	if not check_output(options['OUTDIR']):
		os.makedirs(options['OUTDIR'])
		
	object.savetexfile(OUTFILE)
	if options['WITH_PDF']:
		print object.toPDF(options['OUTDIR'], OUTFILE)


if __name__ == '__main__':
	main()

