* Copyright (C) 2004 Eric Seigne * Copyright (C) 2004-2010 Laurent Destailleur * Copyright (C) 2005 Marc Barilley / Ocebo * Copyright (C) 2005-2010 Regis Houssin * Copyright (C) 2006 Andre Cianfarani * Copyright (C) 2010 Juanjo Menent * * 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 program 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 program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /** * \file htdocs/compta/facture.php * \ingroup facture * \brief Page to cree=ate/see an invoice * \version $Id$ */ require('../main.inc.php'); require_once(DOL_DOCUMENT_ROOT."/core/class/html.formfile.class.php"); require_once(DOL_DOCUMENT_ROOT.'/includes/modules/facture/modules_facture.php'); require_once(DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'); require_once(DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'); require_once(DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'); require_once(DOL_DOCUMENT_ROOT."/lib/functions2.lib.php"); require_once(DOL_DOCUMENT_ROOT.'/lib/invoice.lib.php'); require_once(DOL_DOCUMENT_ROOT."/lib/date.lib.php"); if ($conf->projet->enabled) require_once(DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'); if ($conf->projet->enabled) require_once(DOL_DOCUMENT_ROOT.'/lib/project.lib.php'); $langs->load('bills'); $langs->load('companies'); $langs->load('products'); $langs->load('main'); $sall=isset($_GET['sall'])?trim($_GET['sall']):trim($_POST['sall']); $mesg=isset($_GET['mesg'])?$_GET['mesg']:''; $projectid=isset($_GET['projectid'])?$_GET['projectid']:0; // Security check $socid=isset($_GET['socid'])?$_GET['socid']:$_POST['socid']; $facid = isset($_GET["id"])?$_GET["id"]:(isset($_GET["ref"])?$_GET["ref"]:''); $fieldid = isset($_GET["ref"])?'facnumber':'rowid'; if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'facture', $facid,'','','fk_soc',$fieldid); // Nombre de ligne pour choix de produit/service predefinis $NBLINES=4; $usehm=$conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE; /******************************************************************************/ /* Actions */ /******************************************************************************/ // Action clone object if ($_REQUEST["action"] == 'confirm_clone' && $_REQUEST['confirm'] == 'yes') { if (1==0 && empty($_REQUEST["clone_content"]) && empty($_REQUEST["clone_receivers"])) { $mesg='
'.$langs->trans("NoCloneOptionsSpecified").'
'; } else { $object=new Facture($db); $result=$object->createFromClone($_REQUEST['facid']); if ($result > 0) { header("Location: ".$_SERVER['PHP_SELF'].'?facid='.$result); exit; } else { $mesg=$object->error; $_GET['action']=''; $_GET['id']=$_REQUEST['id']; } } } if ($_GET['action'] == 'reopen' && $user->rights->facture->creer) { $fac = new Facture($db); $result = $fac->fetch($_GET['facid']); if ($fac->statut == 2 || ($fac->statut == 3 && $fac->close_code != 'replaced')) { $result = $fac->set_unpaid($user); if ($result > 0) { Header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$_GET['facid']); exit; } else { $mesg='
'.$fac->error.'
'; } } } // Suppression de la facture if ($_REQUEST['action'] == 'confirm_delete' && $_REQUEST['confirm'] == 'yes' && $user->rights->facture->supprimer) { if ($user->rights->facture->supprimer) { $fac = new Facture($db); $result = $fac->fetch($_GET['facid']); $result = $fac->delete(); if ($result > 0) { Header('Location: '.$_SERVER["PHP_SELF"]); exit; } else { $mesg='
'.$fac->error.'
'; } } } /* * Supprime une ligne produit AVEC ou SANS confirmation */ if ($_REQUEST['action'] == 'confirm_deleteproductline' && $_REQUEST['confirm'] == 'yes') { if ($user->rights->facture->creer) { $fac = new Facture($db); $fac->fetch($_GET['facid']); $fac->fetch_client(); $result = $fac->deleteline($_GET['rowid'], $user); if ($result > 0) { // Define output language $outputlangs = $langs; $newlang=''; if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) $newlang=$_REQUEST['lang_id']; if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$fac->client->default_lang; if (! empty($newlang)) { $outputlangs = new Translate("",$conf); $outputlangs->setDefaultLang($newlang); } $result=facture_pdf_create($db, $fac->id, '', $fac->modelpdf, $outputlangs); if ($result > 0) { Header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$_GET['facid']); exit; } } else { $mesg='
'.$fac->error.'
'; $_GET['action']=''; } } } // Supprime affectation d'un avoir a la facture if ($_GET['action'] == 'unlinkdiscount') { if ($user->rights->facture->creer) { $discount=new DiscountAbsolute($db); $result=$discount->fetch($_GET["discountid"]); $discount->unlink_invoice(); } } // Validation if ($_GET['action'] == 'valid') { $facture = new Facture($db); $facture->fetch($_GET['facid']); // On verifie signe facture if ($facture->type == 2) { // Si avoir, le signe doit etre negatif if ($facture->total_ht >= 0) { $mesg='
'.$langs->trans("ErrorInvoiceAvoirMustBeNegative").'
'; $_GET['action']=''; } } else { // Si non avoir, le signe doit etre positif if ($facture->total_ht < 0) { $mesg='
'.$langs->trans("ErrorInvoiceOfThisTypeMustBePositive").'
'; $_GET['action']=''; } } } if ($_POST['action'] == 'classin') { $facture = new Facture($db); $facture->fetch($_GET['facid']); $facture->setProject($_POST['projectid']); } if ($_POST['action'] == 'setmode') { $facture = new Facture($db); $facture->fetch($_GET['facid']); $result=$facture->mode_reglement($_POST['mode_reglement_id']); if ($result < 0) dol_print_error($facture->db,$facture->error); } if ($_POST['action'] == 'setpaymentterm') { $facture = new Facture($db); $facture->fetch($_GET['facid']); $date_lim_reglement=dol_mktime(12,0,0,$_POST['paymenttermmonth'],$_POST['paymenttermday'],$_POST['paymenttermyear']); $result=$facture->cond_reglement($facture->cond_reglement_id,$date_lim_reglement); if ($result < 0) dol_print_error($facture->db,$facture->error); } if ($_POST['action'] == 'setinvoicedate') { $facture = new Facture($db); $facture->fetch($_GET['facid']); $facture->date=dol_mktime(12,0,0,$_POST['invoicedatemonth'],$_POST['invoicedateday'],$_POST['invoicedateyear']); $result=$facture->update($user); if ($result < 0) dol_print_error($facture->db,$facture->error); } if ($_POST['action'] == 'setconditions') { $facture = new Facture($db); $facture->fetch($_GET['facid']); $result=$facture->cond_reglement($_POST['cond_reglement_id']); if ($result < 0) dol_print_error($facture->db,$facture->error); } if ($_REQUEST['action'] == 'setremisepercent' && $user->rights->facture->creer) { $fac = new Facture($db); $fac->fetch($_REQUEST['facid']); $result = $fac->set_remise($user, $_POST['remise_percent']); $_GET['facid']=$_REQUEST['facid']; } if ($_POST['action'] == "setabsolutediscount" && $user->rights->facture->creer) { // POST[remise_id] ou POST[remise_id_for_payment] if (! empty($_POST["remise_id"])) { $fac = new Facture($db); $fac->id=$_GET['facid']; $ret=$fac->fetch($_GET['facid']); if ($ret > 0) { $result=$fac->insert_discount($_POST["remise_id"]); if ($result < 0) { $mesg='
'.$fac->error.'
'; } } else { dol_print_error($db,$fac->error); } } if (! empty($_POST["remise_id_for_payment"])) { require_once(DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'); $discount = new DiscountAbsolute($db); $discount->fetch($_POST["remise_id_for_payment"]); $result=$discount->link_to_invoice(0,$_GET['facid']); if ($result < 0) { $mesg='
'.$discount->error.'
'; } } } if ($_POST['action'] == 'set_ref_client') { $facture = new Facture($db); $facture->fetch($_GET['facid']); $facture->set_ref_client($_POST['ref_client']); } // Classify to validated if ($_REQUEST['action'] == 'confirm_valid' && $_REQUEST['confirm'] == 'yes' && $user->rights->facture->valider) { $fac = new Facture($db); $fac->fetch($_GET['facid']); $fac->fetch_client(); $result = $fac->validate($user); if ($result >= 0) { // Define output language $outputlangs = $langs; $newlang=''; if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) $newlang=$_REQUEST['lang_id']; if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$fac->client->default_lang; if (! empty($newlang)) { $outputlangs = new Translate("",$conf); $outputlangs->setDefaultLang($newlang); } facture_pdf_create($db, $fac->id, '', $fac->modelpdf, $outputlangs); } else { $mesg='
'.$fac->error.'
'; } } // Repasse la facture en mode brouillon (unvalidate) if ($_GET['action'] == 'modif' && $user->rights->facture->unvalidate) { $fac = new Facture($db); $fac->fetch($_GET['facid']); $fac->fetch_client(); // On verifie si la facture a des paiements $sql = 'SELECT pf.amount'; $sql.= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf'; $sql.= ' WHERE pf.fk_facture = '.$fac->id; $result = $db->query($sql); if ($result) { $i = 0; $num = $db->num_rows($result); while ($i < $num) { $objp = $db->fetch_object($result); $totalpaye += $objp->amount; $i++; } } else { dol_print_error($db,''); } $resteapayer = $fac->total_ttc - $totalpaye; // On verifie si les lignes de factures ont ete exportees en compta et/ou ventilees $ventilExportCompta = $fac->getVentilExportCompta(); // On verifie si aucun paiement n'a ete effectue if ($resteapayer == $fac->total_ttc && $fac->paye == 0 && $ventilExportCompta == 0) { $fac->set_draft($user); // Define output language $outputlangs = $langs; $newlang=''; if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) $newlang=$_REQUEST['lang_id']; if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$fac->client->default_lang; if (! empty($newlang)) { $outputlangs = new Translate("",$conf); $outputlangs->setDefaultLang($newlang); } facture_pdf_create($db, $fac->id, '', $fac->modelpdf, $outputlangs); } } // Classify "paid" if ($_REQUEST['action'] == 'confirm_paid' && $_REQUEST['confirm'] == 'yes' && $user->rights->facture->paiement) { $fac = new Facture($db); $fac->fetch($_GET['facid']); $result = $fac->set_paid($user); } // Classif "paid partialy" if ($_REQUEST['action'] == 'confirm_paid_partially' && $_REQUEST['confirm'] == 'yes' && $user->rights->facture->paiement) { $fac = new Facture($db); $fac->fetch($_GET['facid']); $close_code=$_POST["close_code"]; $close_note=$_POST["close_note"]; if ($close_code) { $result = $fac->set_paid($user,$close_code,$close_note); } else { $mesg='
'.$langs->trans("ErrorFieldRequired",$langs->trans("Reason")).'
'; } } // Classify "abandoned" if ($_REQUEST['action'] == 'confirm_canceled' && $_REQUEST['confirm'] == 'yes') { $fac = new Facture($db); $fac->fetch($_GET['facid']); $close_code=$_POST["close_code"]; $close_note=$_POST["close_note"]; if ($close_code) { $result = $fac->set_canceled($user,$close_code,$close_note); } else { $mesg='
'.$langs->trans("ErrorFieldRequired",$langs->trans("Reason")).'
'; } } // Convertir en reduc if ($_REQUEST['action'] == 'confirm_converttoreduc' && $_REQUEST['confirm'] == 'yes' && $user->rights->facture->creer) { $db->begin(); $fac = new Facture($db); $fac->fetch($_GET['facid']); $fac->fetch_client(); $fac->fetch_lines(); if (! $fac->paye) // protection against multiple submit { // Boucle sur chaque taux de tva $i=0; foreach($fac->lignes as $ligne) { $amount_ht[$ligne->tva_tx]+=$ligne->total_ht; $amount_tva[$ligne->tva_tx]+=$ligne->total_tva; $amount_ttc[$ligne->tva_tx]+=$ligne->total_ttc; $i++; } // Insert one discount by VAT rate category $discount = new DiscountAbsolute($db); if ($fac->type == 2) $discount->description='(CREDIT_NOTE)'; elseif ($fac->type == 3) $discount->description='(DEPOSIT)'; else { $this->error="CantConvertToReducAnInvoiceOfThisType"; return -1; } $discount->tva_tx=abs($fac->total_ttc); $discount->fk_soc=$fac->socid; $discount->fk_facture_source=$fac->id; $error=0; foreach($amount_ht as $tva_tx => $xxx) { $discount->amount_ht=abs($amount_ht[$tva_tx]); $discount->amount_tva=abs($amount_tva[$tva_tx]); $discount->amount_ttc=abs($amount_ttc[$tva_tx]); $discount->tva_tx=abs($tva_tx); $result=$discount->create($user); if ($result < 0) { $error++; break; } } if (! $error) { // Classe facture $result=$fac->set_paid($user); if ($result > 0) { //$mesg='OK'.$discount->id; $db->commit(); } else { $mesg='
'.$fac->error.'
'; $db->rollback(); } } else { $mesg='
'.$discount->error.'
'; $db->rollback(); } } } /* * Insert new invoice in database */ if ($_POST['action'] == 'add' && $user->rights->facture->creer) { $facture = new Facture($db); $facture->socid=$_POST['socid']; $db->begin(); // Replacement invoice if ($_POST['type'] == 1) { $datefacture = dol_mktime(12, 0 , 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']); if (empty($datefacture)) { $error=1; $mesg='
'.$langs->trans("ErrorFieldRequired",$langs->trans("Date")).'
'; } if (! ($_POST['fac_replacement'] > 0)) { $error=1; $mesg='
'.$langs->trans("ErrorFieldRequired",$langs->trans("ReplaceInvoice")).'
'; } if (! $error) { // This is a replacement invoice $result=$facture->fetch($_POST['fac_replacement']); $facture->fetch_client(); $facture->date = $datefacture; $facture->note_public = trim($_POST['note_public']); $facture->note = trim($_POST['note']); $facture->ref_client = $_POST['ref_client']; $facture->modelpdf = $_POST['model']; $facture->fk_project = $_POST['projectid']; $facture->cond_reglement_id = $_POST['cond_reglement_id']; $facture->mode_reglement_id = $_POST['mode_reglement_id']; $facture->remise_absolue = $_POST['remise_absolue']; $facture->remise_percent = $_POST['remise_percent']; // Proprietes particulieres a facture de remplacement $facture->fk_facture_source = $_POST['fac_replacement']; $facture->type = 1; $facid=$facture->createFromCurrent($user); } } // Credit note invoice if ($_POST['type'] == 2) { if (! $_POST['fac_avoir'] > 0) { $error=1; $mesg='
'.$langs->trans("ErrorFieldRequired",$langs->trans("CorrectInvoice")).'
'; } $datefacture = dol_mktime(12, 0 , 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']); if (empty($datefacture)) { $error=1; $mesg='
'.$langs->trans("ErrorFieldRequired",$langs->trans("Date")).'
'; } if (! $error) { // Si facture avoir $datefacture = dol_mktime(12, 0 , 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']); //$result=$facture->fetch($_POST['fac_avoir']); $facture->socid = $_POST['socid']; $facture->number = $_POST['facnumber']; $facture->date = $datefacture; $facture->note_public = trim($_POST['note_public']); $facture->note = trim($_POST['note']); $facture->ref_client = $_POST['ref_client']; $facture->modelpdf = $_POST['model']; $facture->fk_project = $_POST['projectid']; $facture->cond_reglement_id = 0; $facture->mode_reglement_id = $_POST['mode_reglement_id']; $facture->remise_absolue = $_POST['remise_absolue']; $facture->remise_percent = $_POST['remise_percent']; // Proprietes particulieres a facture avoir $facture->fk_facture_source = $_POST['fac_avoir']; $facture->type = 2; $facid = $facture->create($user); // Add predefined lines for ($i = 1; $i <= $NBLINES; $i++) { if ($_POST['idprod'.$i]) { $product=new Product($db); $product->fetch($_POST['idprod'.$i]); $startday=dol_mktime(12, 0 , 0, $_POST['date_start'.$i.'month'], $_POST['date_start'.$i.'day'], $_POST['date_start'.$i.'year']); $endday=dol_mktime(12, 0 , 0, $_POST['date_end'.$i.'month'], $_POST['date_end'.$i.'day'], $_POST['date_end'.$i.'year']); $result=$facture->addline($facid,$product->description,$product->price, $_POST['qty'.$i], $product->tva_tx, $product->localtax1_tx, $product->localtax2_tx, $_POST['idprod'.$i], $_POST['remise_percent'.$i], $startday, $endday, 0, 0, '', $product->price_base_type, $product->price_ttc, $product->type); } } } } // Standard invoice or Deposit invoice created from a predefined invoice if (($_POST['type'] == 0 || $_POST['type'] == 3) && $_POST['fac_rec'] > 0) { $datefacture = dol_mktime(12, 0 , 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']); if (empty($datefacture)) { $error=1; $mesg='
'.$langs->trans("ErrorFieldRequired",$langs->trans("Date")).'
'; } if (! $error) { $facture->socid = $_POST['socid']; $facture->type = $_POST['type']; $facture->number = $_POST['facnumber']; $facture->date = $datefacture; $facture->note_public = trim($_POST['note_public']); $facture->note = trim($_POST['note']); $facture->ref_client = $_POST['ref_client']; $facture->modelpdf = $_POST['model']; // Source facture $facture->fac_rec = $_POST['fac_rec']; $facid = $facture->create($user); } } // Standard or deposit or proforma invoice if (($_POST['type'] == 0 || $_POST['type'] == 3 || $_POST['type'] == 4) && $_POST['fac_rec'] <= 0) { $datefacture = dol_mktime(12, 0 , 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']); if (empty($datefacture)) { $error=1; $mesg='
'.$langs->trans("ErrorFieldRequired",$langs->trans("Date")).'
'; } if (! $error) { // Si facture standard $facture->socid = $_POST['socid']; $facture->type = $_POST['type']; $facture->number = $_POST['facnumber']; $facture->date = $datefacture; $facture->note_public = trim($_POST['note_public']); $facture->note = trim($_POST['note']); $facture->ref_client = $_POST['ref_client']; $facture->modelpdf = $_POST['model']; $facture->fk_project = $_POST['projectid']; $facture->cond_reglement_id = ($_POST['type'] == 3?1:$_POST['cond_reglement_id']); $facture->mode_reglement_id = $_POST['mode_reglement_id']; $facture->amount = $_POST['amount']; $facture->remise_absolue = $_POST['remise_absolue']; $facture->remise_percent = $_POST['remise_percent']; // If creation from other modules if ($_POST['origin'] && $_POST['originid']) { // Parse element/subelement (ex: project_task) $element = $subelement = $_POST['origin']; if (preg_match('/^([^_]+)_([^_]+)/i',$_POST['origin'],$regs)) { $element = $regs[1]; $subelement = $regs[2]; } // For compatibility if ($element == 'order') { $element = $subelement = 'commande'; } if ($element == 'propal') { $element = 'comm/propal'; $subelement = 'propal'; } if ($element == 'contract') { $element = $subelement = 'contrat'; } $facture->origin = $_POST['origin']; $facture->origin_id = $_POST['originid']; $facid = $facture->create($user); if ($facid > 0) { require_once(DOL_DOCUMENT_ROOT.'/'.$element.'/class/'.$subelement.'.class.php'); $classname = ucfirst($subelement); $object = new $classname($db); if ($object->fetch($_POST['originid'])) { // TODO mutualiser $lines = $object->lignes; if (empty($lines) && method_exists($object,'fetch_lignes')) $lines = $object->fetch_lignes(); if (empty($lines) && method_exists($object,'fetch_lines')) $lines = $object->fetch_lines(); for ($i = 0 ; $i < sizeof($lines) ; $i++) { $desc=($lines[$i]->desc?$lines[$i]->desc:$lines[$i]->libelle); $product_type=($lines[$i]->product_type?$lines[$i]->product_type:0); // Dates // TODO mutualiser $date_start=$lines[$i]->date_debut_prevue; if ($lines[$i]->date_debut_reel) $date_start=$lines[$i]->date_debut_reel; if ($lines[$i]->date_start) $date_start=$lines[$i]->date_start; $date_end=$lines[$i]->date_fin_prevue; if ($lines[$i]->date_fin_reel) $date_end=$lines[$i]->date_fin_reel; if ($lines[$i]->date_end) $date_end=$lines[$i]->date_end; $result = $facture->addline( $facid, $desc, $lines[$i]->subprice, $lines[$i]->qty, $lines[$i]->tva_tx, $lines[$i]->localtax1_tx, $lines[$i]->localtax2_tx, $lines[$i]->fk_product, $lines[$i]->remise_percent, $date_start, $date_end, 0, $lines[$i]->info_bits, $lines[$i]->fk_remise_except, 'HT', 0, $product_type ); if ($result < 0) { $error++; break; } } } else { $error++; } } else { $error++; } } // If some invoice's lines already known else { $facid = $facture->create($user); for ($i = 1; $i <= $NBLINES; $i++) { if ($_POST['idprod'.$i]) { $product=new Product($db); $product->fetch($_POST['idprod'.$i]); $startday=dol_mktime(12, 0 , 0, $_POST['date_start'.$i.'month'], $_POST['date_start'.$i.'day'], $_POST['date_start'.$i.'year']); $endday=dol_mktime(12, 0 , 0, $_POST['date_end'.$i.'month'], $_POST['date_end'.$i.'day'], $_POST['date_end'.$i.'year']); $result=$facture->addline($facid,$product->description,$product->price, $_POST['qty'.$i], $product->tva_tx, $product->localtax1_tx, $product->localtax2_tx, $_POST['idprod'.$i], $_POST['remise_percent'.$i], $startday, $endday, 0, 0, '', $product->price_base_type, $product->price_ttc, $product->type); } } } } } // Fin creation facture, on l'affiche if ($facid > 0 && ! $error) { $db->commit(); Header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$facid); exit; } else { $db->rollback(); $_GET["action"]='create'; $_GET["origin"]=$_POST["origin"]; $_GET["originid"]=$_POST["originid"]; if (! $mesg) $mesg='
'.$facture->error.'
'; } } // Add a new line if (($_POST['action'] == 'addline' || $_POST['action'] == 'addline_predef') && $user->rights->facture->creer) { $fac = new Facture($db); $result=0; if (empty($_POST['idprod']) && $_POST["type"] < 0) { $mesg='
'.$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("Type")).'
'; $result = -1 ; } if (empty($_POST['idprod']) && (! isset($_POST["pu"]) || $_POST["pu"]=='')) // Unit price can be 0 but not '' { $mesg='
'.$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("UnitPriceHT")).'
'; $result = -1 ; } if (empty($_POST['idprod']) && empty($_POST["np_desc"]) && empty($_POST["dp_desc"])) { $mesg='
'.$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("Description")).'
'; $result = -1 ; } if (! isset($_POST['qty']) || $_POST['qty']=='') { $mesg='
'.$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv('Qty')).'
'; $result = -1 ; } if ($result >= 0 && ( ($_POST['pu']!='' && ($_POST['np_desc'] || $_POST['dp_desc'])) || $_POST['idprod'] ) ) { $ret=$fac->fetch($_POST['facid']); if ($ret < 0) { dol_print_error($db,$fac->error); exit; } $ret=$fac->fetch_client(); $suffixe = $_POST['idprod'] ? '_predef' : ''; $date_start=dol_mktime($_POST['date_start'.$suffixe.'hour'],$_POST['date_start'.$suffixe.'min'],$_POST['date_start'.$suffixe.'sec'],$_POST['date_start'.$suffixe.'month'],$_POST['date_start'.$suffixe.'day'],$_POST['date_start'.$suffixe.'year']); $date_end=dol_mktime($_POST['date_end'.$suffixe.'hour'],$_POST['date_end'.$suffixe.'min'],$_POST['date_end'.$suffixe.'sec'],$_POST['date_end'.$suffixe.'month'],$_POST['date_end'.$suffixe.'day'],$_POST['date_end'.$suffixe.'year']); $price_base_type = 'HT'; // Ecrase $pu par celui du produit // Ecrase $desc par celui du produit // Ecrase $txtva par celui du produit // Ecrase $base_price_type par celui du produit if ($_POST['idprod']) { $prod = new Product($db, $_POST['idprod']); $prod->fetch($_POST['idprod']); $tva_tx = get_default_tva($mysoc,$fac->client,$prod->id); $tva_npr = get_default_npr($mysoc,$fac->client,$prod->id); // We define price for product if ($conf->global->PRODUIT_MULTIPRICES && $fac->client->price_level) { $pu_ht = $prod->multiprices[$fac->client->price_level]; $pu_ttc = $prod->multiprices_ttc[$fac->client->price_level]; $price_base_type = $prod->multiprices_base_type[$fac->client->price_level]; } else { $pu_ht = $prod->price; $pu_ttc = $prod->price_ttc; $price_base_type = $prod->price_base_type; } // On reevalue prix selon taux tva car taux tva transaction peut etre different // de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur). if ($tva_tx != $prod->tva_tx) { if ($price_base_type != 'HT') { $pu_ht = price2num($pu_ttc / (1 + ($tva_tx/100)), 'MU'); } else { $pu_ttc = price2num($pu_ht * (1 + ($tva_tx/100)), 'MU'); } } $desc = $prod->description; $desc.= $prod->description && $_POST['np_desc'] ? "\n" : ""; $desc.= $_POST['np_desc']; $type = $prod->type; } else { $pu_ht=$_POST['pu']; $tva_tx=str_replace('*','',$_POST['tva_tx']); $tva_npr=preg_match('/\*/',$_POST['tva_tx'])?1:0; $desc=$_POST['dp_desc']; $type=$_POST["type"]; } $localtax1_tx=get_localtax($tva_tx,1,$fac->client); $localtax2_tx=get_localtax($tva_tx,2,$fac->client); $info_bits=0; if ($tva_npr) $info_bits |= 0x01; if ($result >= 0) { if($prod->price_min && (price2num($pu_ht)*(1-price2num($_POST['remise_percent'])/100) < price2num($prod->price_min))) { $fac->error = $langs->trans("CantBeLessThanMinPrice",price2num($prod->price_min,'MU').' '.$langs->trans("Currency".$conf->monnaie)) ; $result = -1 ; } else { // Insert line $result = $fac->addline( $_POST['facid'], $desc, $pu_ht, $_POST['qty'], $tva_tx, $localtax1_tx, $localtax2_tx, $_POST['idprod'], $_POST['remise_percent'], $date_start, $date_end, 0, $info_bits, '', $price_base_type, $pu_ttc, $type ); } } } if ($result > 0) { // Define output language $outputlangs = $langs; $newlang=''; if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) $newlang=$_REQUEST['lang_id']; if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$fac->client->default_lang; if (! empty($newlang)) { $outputlangs = new Translate("",$conf); $outputlangs->setDefaultLang($newlang); } facture_pdf_create($db, $fac->id, '', $fac->modelpdf, $outputlangs); unset($_POST['qty']); unset($_POST['type']); unset($_POST['idprod']); unset($_POST['remmise_percent']); unset($_POST['dp_desc']); unset($_POST['np_desc']); unset($_POST['pu']); unset($_POST['tva_tx']); } else { if (empty($mesg)) $mesg='
'.$fac->error.'
'; } $_GET['facid']=$_POST['facid']; // Pour reaffichage de la fiche en cours d'edition } if ($_POST['action'] == 'updateligne' && $user->rights->facture->creer && $_POST['save'] == $langs->trans('Save')) { $fac = new Facture($db,'',$_POST['facid']); if (! $fac->fetch($_POST['facid']) > 0) dol_print_error($db); $fac->fetch_client(); // Clean parameters $date_start=''; $date_end=''; $date_start=dol_mktime($_POST['date_start'.$suffixe.'hour'],$_POST['date_start'.$suffixe.'min'],$_POST['date_start'.$suffixe.'sec'],$_POST['date_start'.$suffixe.'month'],$_POST['date_start'.$suffixe.'day'],$_POST['date_start'.$suffixe.'year']); $date_end=dol_mktime($_POST['date_end'.$suffixe.'hour'],$_POST['date_end'.$suffixe.'min'],$_POST['date_end'.$suffixe.'sec'],$_POST['date_end'.$suffixe.'month'],$_POST['date_end'.$suffixe.'day'],$_POST['date_end'.$suffixe.'year']); $description=dol_htmlcleanlastbr($_POST['desc']); // Define info_bits $info_bits=0; if (preg_match('/\*/',$_POST['tva_tx'])) $info_bits |= 0x01; // Define vat_rate $vat_rate=$_POST['tva_tx']; $vat_rate=str_replace('*','',$vat_rate); $localtax1_rate=get_localtax($vat_rate,1,$fac->client); $localtax2_rate=get_localtax($vat_rate,2,$fac->client); // Check parameters if (empty($_POST['productid']) && $_POST["type"] < 0) { $mesg = '
'.$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("Type")).'
'; $result = -1 ; } // Check minimum price if(! empty($_POST['productid'])) { $productid = $_POST['productid']; $product = new Product($db); $product->fetch($productid); $type=$product->type; } if($product->price_min && ($_POST['productid']!='') && (price2num($_POST['price'])*(1-price2num($_POST['remise_percent'])/100) < price2num($product->price_min))) { $mesg = '
'.$langs->trans("CantBeLessThanMinPrice",price2num($product->price_min,'MU').' '.$langs->trans("Currency".$conf->monnaie)).'
'; $result=-1; } // Define params if (! empty($_POST['productid'])) { $type=$product->type; } else { $type=$_POST["type"]; } // Update line if ($result >= 0) { $result = $fac->updateline($_POST['rowid'], $description, $_POST['price'], $_POST['qty'], $_POST['remise_percent'], $date_start, $date_end, $vat_rate, $localtax1_rate, $localtax2_rate, 'HT', $info_bits, $type ); // Define output language $outputlangs = $langs; $newlang=''; if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) $newlang=$_REQUEST['lang_id']; if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$fac->client->default_lang; if (! empty($newlang)) { $outputlangs = new Translate("",$conf); $outputlangs->setDefaultLang($newlang); } facture_pdf_create($db, $fac->id, '', $fac->modelpdf, $outputlangs); } $_GET['facid']=$_POST['facid']; // Pour reaffichage de la fiche en cours d'edition } if ($_POST['action'] == 'updateligne' && $user->rights->facture->creer && $_POST['cancel'] == $langs->trans('Cancel')) { Header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$_POST['facid']); // Pour reaffichage de la fiche en cours d'edition exit; } /* * Ordonnancement des lignes */ if ($_GET['action'] == 'up' && $user->rights->facture->creer) { $fac = new Facture($db,'',$_GET['facid']); $fac->fetch($_GET['facid']); $fac->fetch_client(); $fac->line_up($_GET['rowid']); // Define output language $outputlangs = $langs; $newlang=''; if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) $newlang=$_REQUEST['lang_id']; if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$fac->client->default_lang; if (! empty($newlang)) { $outputlangs = new Translate("",$conf); $outputlangs->setDefaultLang($newlang); } facture_pdf_create($db, $fac->id, '', $fac->modelpdf, $outputlangs); Header ('Location: '.$_SERVER["PHP_SELF"].'?facid='.$_GET["facid"].'#'.$_GET['rowid']); exit; } if ($_GET['action'] == 'down' && $user->rights->facture->creer) { $fac = new Facture($db,'',$_GET['facid']); $fac->fetch($_GET['facid']); $fac->fetch_client(); $fac->line_down($_GET['rowid']); // Define output language $outputlangs = $langs; $newlang=''; if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) $newlang=$_REQUEST['lang_id']; if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$fac->client->default_lang; if (! empty($newlang)) { $outputlangs = new Translate("",$conf); $outputlangs->setDefaultLang($newlang); } facture_pdf_create($db, $fac->id, '', $fac->modelpdf, $outputlangs); Header ('Location: '.$_SERVER["PHP_SELF"].'?facid='.$_GET["facid"].'#'.$_GET['rowid']); exit; } /* * Add file in email form */ if ($_POST['addfile']) { require_once(DOL_DOCUMENT_ROOT."/lib/files.lib.php"); // Set tmp user directory TODO Use a dedicated directory for temp mails files $vardir=$conf->user->dir_output."/".$user->id; $upload_dir = $vardir.'/temp/'; $mesg=dol_add_file_process($upload_dir,0,0); $_GET["action"]='presend'; $_POST["action"]='presend'; } /* * Remove file in email form */ if (! empty($_POST['removedfile'])) { require_once(DOL_DOCUMENT_ROOT."/lib/files.lib.php"); // Set tmp user directory $vardir=$conf->user->dir_output."/".$user->id; $upload_dir = $vardir.'/temp/'; $mesg=dol_remove_file_process($_POST['removedfile'],0); $_GET["action"]='presend'; $_POST["action"]='presend'; } /* * Send mail */ if (($_POST['action'] == 'send' || $_POST['action'] == 'relance') && ! $_POST['addfile'] && ! $_POST['removedfile'] && ! $_POST['cancel']) { $langs->load('mails'); $fac = new Facture($db,'',$_POST['facid']); $result=$fac->fetch($_POST['facid']); $result=$fac->fetch_thirdparty(); if ($result > 0) { $ref = dol_sanitizeFileName($fac->ref); $file = $conf->facture->dir_output . '/' . $ref . '/' . $ref . '.pdf'; if (is_readable($file)) { if ($_POST['sendto']) { // Le destinataire a ete fourni via le champ libre $sendto = $_POST['sendto']; $sendtoid = 0; } elseif ($_POST['receiver']) { // Le destinataire a ete fourni via la liste deroulante if ($_POST['receiver'] < 0) // Id du tiers { $sendto = $fac->client->email; $sendtoid = 0; } else // Id du contact { $sendto = $fac->client->contact_get_email($_POST['receiver']); $sendtoid = $_POST['receiver']; } } if (strlen($sendto)) { $langs->load("commercial"); $from = $_POST['fromname'] . ' <' . $_POST['frommail'] .'>'; $replyto = $_POST['replytoname']. ' <' . $_POST['replytomail'].'>'; $message = $_POST['message']; $sendtocc = $_POST['sendtocc']; $deliveryreceipt = $_POST['deliveryreceipt']; if ($_POST['action'] == 'send') { if (strlen($_POST['subject'])) $subject = $_POST['subject']; else $subject = $langs->transnoentities('Bill').' '.$fac->ref; $actiontypecode='AC_FAC'; $actionmsg=$langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto.".\n"; if ($message) { $actionmsg.=$langs->transnoentities('MailTopic').": ".$subject."\n"; $actionmsg.=$langs->transnoentities('TextUsedInTheMessageBody').":\n"; $actionmsg.=$message; } $actionmsg2=$langs->transnoentities('Action'.$actiontypecode); } if ($_POST['action'] == 'relance') { if (strlen($_POST['subject'])) $subject = $_POST['subject']; else $subject = $langs->transnoentities('Relance facture '.$fac->ref); $actiontypecode='AC_FAC'; $actionmsg=$langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto.".\n"; if ($message) { $actionmsg.=$langs->transnoentities('MailTopic').": ".$subject."\n"; $actionmsg.=$langs->transnoentities('TextUsedInTheMessageBody').":\n"; $actionmsg.=$message; } $actionmsg2=$langs->transnoentities('Action'.$actiontypecode); } // Create form object include_once(DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'); $formmail = new FormMail($db); $attachedfiles=$formmail->get_attached_files(); $filepath = $attachedfiles['paths']; $filename = $attachedfiles['names']; $mimetype = $attachedfiles['mimes']; // Send mail require_once(DOL_DOCUMENT_ROOT.'/lib/CMailFile.class.php'); $mailfile = new CMailFile($subject,$sendto,$from,$message,$filepath,$mimetype,$filename,$sendtocc,'',$deliveryreceipt,-1); if ($mailfile->error) { $mesg='
'.$mailfile->error.'
'; } else { $result=$mailfile->sendfile(); if ($result) { $mesg='
'.$langs->trans('MailSuccessfulySent',$from,$sendto).'.
'; $error=0; // Initialisation donnees $fac->sendtoid=$sendtoid; $fac->actiontypecode=$actiontypecode; $fac->actionmsg = $actionmsg; $fac->actionmsg2= $actionmsg2; $fac->facid=$fac->id; // Appel des triggers include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php"); $interface=new Interfaces($db); $result=$interface->run_triggers('BILL_SENTBYMAIL',$fac,$user,$langs,$conf); if ($result < 0) { $error++; $this->errors=$interface->errors; } // Fin appel triggers if ($error) { dol_print_error($db); } else { // Redirect here // This avoid sending mail twice if going out and then back to page Header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$fac->id.'&mesg='.urlencode($mesg)); exit; } } else { $langs->load("other"); $mesg='
'; if ($mailfile->error) { $mesg.=$langs->trans('ErrorFailedToSendMail',$from,$sendto); $mesg.='
'.$mailfile->error; } else { $mesg.='No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS'; } $mesg.='
'; } } } else { $langs->load("other"); $mesg='
'.$langs->trans('ErrorMailRecipientIsEmpty').'
'; dol_syslog('Recipient email is empty'); } } else { $langs->load("other"); $mesg='
'.$langs->trans('ErrorCantReadFile',$file).'
'; dol_syslog('Failed to read file: '.$file); } } else { $langs->load("other"); $mesg='
'.$langs->trans('ErrorFailedToReadEntity',$langs->trans("Invoice")).'
'; dol_syslog('Impossible de lire les donnees de la facture. Le fichier facture n\'a peut-etre pas ete genere.'); } $_GET['action'] = 'presend'; } /* * Generate document */ if ($_REQUEST['action'] == 'builddoc') // En get ou en post { $fac = new Facture($db, 0, $_GET['facid']); $fac->fetch($_GET['facid']); $fac->fetch_client(); if ($_REQUEST['model']) { $fac->setDocModel($user, $_REQUEST['model']); } // Define output language $outputlangs = $langs; $newlang=''; if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) $newlang=$_REQUEST['lang_id']; if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$fac->client->default_lang; if (! empty($newlang)) { $outputlangs = new Translate("",$conf); $outputlangs->setDefaultLang($newlang); } $result=facture_pdf_create($db, $fac->id, '', $fac->modelpdf, $outputlangs); if ($result <= 0) { dol_print_error($db,$result); exit; } else { Header ('Location: '.$_SERVER["PHP_SELF"].'?facid='.$fac->id.(empty($conf->global->MAIN_JUMP_TAG)?'':'#builddoc')); exit; } } /* * View */ llxHeader('',$langs->trans('Bill'),'EN:Customers_Invoices|FR:Factures_Clients|ES:Facturas_a_clientes'); $html = new Form($db); $formfile = new FormFile($db); /********************************************************************* * * Mode creation * **********************************************************************/ if ($_GET['action'] == 'create') { $facturestatic=new Facture($db); print_fiche_titre($langs->trans('NewBill')); if ($mesg) print $mesg; $soc = new Societe($db); if ($_GET['origin'] && $_GET['originid']) { // Parse element/subelement (ex: project_task) $element = $subelement = $_GET['origin']; if (preg_match('/^([^_]+)_([^_]+)/i',$_GET['origin'],$regs)) { $element = $regs[1]; $subelement = $regs[2]; } if ($element == 'project') { $projectid=$_GET['originid']; } else if (in_array($element,array('order','commande','propal','contrat','contract'))) { // For compatibility if ($element == 'order') { $element = $subelement = 'commande'; } if ($element == 'propal') { $element = 'comm/propal'; $subelement = 'propal'; } if ($element == 'contract') { $element = $subelement = 'contrat'; } require_once(DOL_DOCUMENT_ROOT.'/'.$element.'/class/'.$subelement.'.class.php'); $classname = ucfirst($subelement); $object = new $classname($db); $object->fetch($_GET['originid']); $object->fetch_client(); $projectid = (!empty($object->fk_project)?$object->fk_project:''); $ref_client = (!empty($object->ref_client)?$object->ref_client:''); $soc = $object->client; $cond_reglement_id = (!empty($object->cond_reglement_id)?$object->cond_reglement_id:(!empty($soc->cond_reglement_id)?$soc->cond_reglement_id:1)); $mode_reglement_id = (!empty($object->mode_reglement_id)?$object->mode_reglement_id:(!empty($soc->mode_reglement_id)?$soc->mode_reglement_id:0)); $remise_percent = (!empty($object->remise_percent)?$object->remise_percent:(!empty($soc->remise_percent)?$soc->remise_percent:0)); $remise_absolue = (!empty($object->remise_absolue)?$object->remise_absolue:(!empty($soc->remise_absolue)?$soc->remise_absolue:0)); $dateinvoice = empty($conf->global->MAIN_AUTOFILL_DATE)?-1:0; } } else { $res=$soc->fetch($socid); $cond_reglement_id = $soc->cond_reglement_id; $mode_reglement_id = $soc->mode_reglement_id; $remise_percent = $soc->remise_percent; $remise_absolue = 0; $dateinvoice = empty($conf->global->MAIN_AUTOFILL_DATE)?-1:0; } $absolute_discount=$soc->getAvailableDiscounts(); print '
'; print ''; print ''; print '' ."\n"; print ''; print ''; // Ref print ''; /* \todo L'info "Reference commande client" est une carac de la commande et non de la facture. Elle devrait donc etre stockee sur l'objet commande liee a la facture et non sur la facture. Pour ceux qui veulent l'utiliser au niveau de la facture, positionner la constante FAC_USE_CUSTOMER_ORDER_REF a 1. */ if ($conf->global->FAC_USE_CUSTOMER_ORDER_REF) { print ''; } // Factures predefinies if (empty($_GET['propalid']) && empty($_GET['commandeid']) && empty($_GET['contratid']) && empty($_GET['originid'])) { $sql = 'SELECT r.rowid, r.titre, r.total_ttc'; $sql.= ' FROM '.MAIN_DB_PREFIX.'facture_rec as r'; $sql.= ' WHERE r.fk_soc = '.$soc->id; $resql=$db->query($sql); if ($resql) { $num = $db->num_rows($resql); $i = 0; if ($num > 0) { print ''; } $db->free($resql); } else { dol_print_error($db); } } // Tiers print ''; print ''."\n"; // Type de facture $facids=$facturestatic->list_replacable_invoices($soc->id); if ($facids < 0) { dol_print_error($db,$facturestatic); exit; } $options=""; foreach ($facids as $facparam) { $options.=''; } $facids=$facturestatic->list_qualified_avoir_invoices($soc->id); if ($facids < 0) { dol_print_error($db,$facturestatic); exit; } $optionsav=""; foreach ($facids as $key => $value) { $newinvoice=new Facture($db); $newinvoice->fetch($key); $optionsav.=''; } print ''; // Discounts for third party print ''; // Date invoice print ''; // Payment term print ''; // Payment mode print ''; // Project if ($conf->projet->enabled) { $langs->load('projects'); print ''; } // Modele PDF print ''; print '"; // Note publique print ''; print ''; print ''; // Note privee if (! $user->societe_id) { print ''; print ''; print ''; } if (is_object($object)) { // TODO for compatibility if ($_GET['origin'] == 'contrat') { // Calcul contrat->price (HT), contrat->total (TTC), contrat->tva $object->remise_absolue=$remise_absolue; $object->remise_percent=$remise_percent; $object->update_price(); } print "\n"; print "\n"; print ''."\n"; print ''."\n"; print ''."\n"; print ''; print ''; print ''; print ''; print '"; if ($mysoc->pays_code=='ES') { if ($mysoc->localtax1_assuj=="1") //Localtax1 RE { print '"; } if ($mysoc->localtax2_assuj=="1") //Localtax2 IRPF { print '"; } } print '"; } else { // Show deprecated optional form to add product line here if ($conf->global->PRODUCT_SHOW_WHEN_CREATE) { print ''; } } // Bouton "Create Draft" print ''; print "
'.$langs->trans('Ref').''.$langs->trans('Draft').'
'.$langs->trans('RefCustomerOrder').''; print ''; print '
'.$langs->trans('CreateFromRepeatableInvoice').''; print '
'.$langs->trans('Company').''; print $soc->getNomUrl(1); print ''; print '
'.$langs->trans('Type').''; print ''."\n"; // Standard invoice print ''."\n"; // Deposit print ''."\n"; // Proforma if ($conf->global->FACTURE_USE_PROFORMAT) { print ''."\n"; } // Replacement print ''."\n"; // Credit note print ''."\n"; print '
'; print ''; print ''; $desc=$html->textwithpicto($langs->trans("InvoiceStandardAsk"),$langs->transnoentities("InvoiceStandardDesc"),1); print $desc; print '
'; print ''; print ''; $desc=$html->textwithpicto($langs->trans("InvoiceDeposit"),$langs->transnoentities("InvoiceDepositDesc"),1); print $desc; print '
'; print ''; print ''; $desc=$html->textwithpicto($langs->trans("InvoiceProForma"),$langs->transnoentities("InvoiceProFormaDesc"),1); print $desc; print '
'; print ''; print ''; $text=$langs->trans("InvoiceReplacementAsk").' '; $text.=''; $desc=$html->textwithpicto($text,$langs->transnoentities("InvoiceReplacementDesc"),1); print $desc; print '
'; print ''; print ''; $text=$langs->transnoentities("InvoiceAvoirAsk").' '; // $text.=''; $text.=''; $desc=$html->textwithpicto($text,$langs->transnoentities("InvoiceAvoirDesc"),1); //.' ('.$langs->trans("FeatureNotYetAvailable").')',$langs->transnoentities("InvoiceAvoirDesc"),1); print $desc; print '
'; print '
'.$langs->trans('Discounts').''; if ($soc->remise_client) print $langs->trans("CompanyHasRelativeDiscount",$soc->remise_client); else print $langs->trans("CompanyHasNoRelativeDiscount"); print '. '; if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->trans("Currency".$conf->monnaie)); else print $langs->trans("CompanyHasNoAbsoluteDiscount"); print '.'; print '
'.$langs->trans('Date').''; $html->select_date($dateinvoice,'','','','',"add",1,1); print '
'.$langs->trans('PaymentConditionsShort').''; $html->select_conditions_paiements(isset($_POST['cond_reglement_id'])?$_POST['cond_reglement_id']:$cond_reglement_id,'cond_reglement_id'); print '
'.$langs->trans('PaymentMode').''; $html->select_types_paiements(isset($_POST['mode_reglement_id'])?$_POST['mode_reglement_id']:$mode_reglement_id,'mode_reglement_id'); print '
'.$langs->trans('Project').''; select_projects($soc->id, $projectid, 'projectid'); print '
'.$langs->trans('Model').''; include_once(DOL_DOCUMENT_ROOT.'/includes/modules/facture/modules_facture.php'); $model=new ModelePDFFactures(); $liste=$model->liste_modeles($db); $html->select_array('model',$liste,$conf->global->FACTURE_ADDON_PDF); print "
'.$langs->trans('NotePublic').''; print '
'.$langs->trans('NotePrivate').''; print '
'.$langs->trans($classname).''.$object->getNomUrl(1).'
'.$langs->trans('TotalHT').''.price($object->total_ht).'
'.$langs->trans('TotalVAT').''.price($object->total_tva)."
'.$langs->transcountry("AmountLT1",$mysoc->pays_code).''.price($object->total_localtax1)."
'.$langs->transcountry("AmountLT2",$mysoc->pays_code).''.price($object->total_localtax2)."
'.$langs->trans('TotalTTC').''.price($object->total_ttc)."
'; // Zone de choix des produits predefinis a la creation print ''; print ''; print ''; print ''; print ''; print ''; if ($conf->service->enabled) { print ''; } print ''; for ($i = 1 ; $i <= $NBLINES ; $i++) { print ''; print ''; print ''; print ''; print ''; // Si le module service est actif, on propose des dates de debut et fin a la ligne if ($conf->service->enabled) { print ''; } print "\n"; } print '
'.$langs->trans('ProductsAndServices').''.$langs->trans('Qty').''.$langs->trans('ReductionShort').'     '.$langs->trans('ServiceLimitedDuration').'
'; // multiprix if($conf->global->PRODUIT_MULTIPRICES) $html->select_produits('','idprod'.$i,'',$conf->product->limit_size,$soc->price_level); else $html->select_produits('','idprod'.$i,'',$conf->product->limit_size); print '% '; print ''; print ''; print '
'; print $langs->trans('From').' '; print ''; print $html->select_date('','date_start'.$i,$usehm,$usehm,1,"add"); print '
'; print $langs->trans('to').' '; print ''; print $html->select_date('','date_end'.$i,$usehm,$usehm,1,"add"); print '
'; print '
'; print '
\n"; print "
\n"; // TODO deplacer dans la classe if ($_GET['origin'] == 'propal') { $title=$langs->trans('ProductsAndServices'); $sql = 'SELECT pt.rowid, pt.description, pt.fk_remise_except,'; $sql.= ' pt.qty, pt.tva_tx, pt.remise_percent, pt.subprice, pt.product_type, pt.info_bits,'; $sql.= ' p.label as product, p.ref, p.fk_product_type, p.rowid as prodid'; $sql.= ' FROM '.MAIN_DB_PREFIX.'propaldet as pt'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON pt.fk_product = p.rowid'; $sql.= ' WHERE pt.fk_propal = '.$object->id; $sql.= ' ORDER BY pt.rang ASC, pt.rowid'; } // TODO deplacer dans la classe if ($_GET['origin'] == 'commande') { $title=$langs->trans('Products'); $sql = 'SELECT pt.rowid, pt.description, pt.fk_remise_except,'; $sql.= ' pt.qty, pt.tva_tx, pt.remise_percent, pt.subprice, pt.product_type, pt.info_bits,'; $sql.= ' pt.date_start as date_debut_prevue, pt.date_end as date_fin_prevue,'; $sql.= ' p.label as product, p.ref, p.fk_product_type, p.rowid as prodid'; $sql.= ' FROM '.MAIN_DB_PREFIX.'commandedet as pt'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON pt.fk_product = p.rowid'; $sql.= ' WHERE pt.fk_commande = '.$object->id; $sql.= ' ORDER BY pt.rowid ASC'; } // TODO deplacer dans la classe if ($_GET['origin'] == 'contrat') { $title=$langs->trans('Services'); $sql = 'SELECT pt.rowid, pt.description,'; $sql.= ' pt.qty, pt.tva_tx, pt.remise_percent, pt.subprice, pt.info_bits,'; $sql.= ' pt.date_ouverture_prevue as date_debut_prevue, pt.date_ouverture as date_debut_reel,'; $sql.= ' pt.date_fin_validite as date_fin_prevue, pt.date_cloture as date_fin_reel,'; $sql.= ' p.label as product, p.ref, p.fk_product_type, p.rowid as prodid'; $sql.= ' FROM '.MAIN_DB_PREFIX.'contratdet as pt'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON pt.fk_product = p.rowid'; $sql.= ' WHERE pt.fk_contrat = '.$object->id; $sql.= ' ORDER BY pt.rowid ASC'; } if ($_GET['origin'] && $_GET['originid']) { print '
'; print_titre($title); print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; // Lignes $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); $i = 0; $var=True; while ($i < $num) { $objp = $db->fetch_object($resql); $var=!$var; $date_start=$objp->date_debut_prevue; if ($objp->date_debut_reel) $date_start=$objp->date_debut_reel; $date_end=$objp->date_fin_prevue; if ($objp->date_fin_reel) $date_end=$objp->date_fin_reel; print '\n"; print ''; print ''; print ''; print ''; print ''; print ''; $i++; } } else { dol_print_error($db); } print '
'.$langs->trans('Ref').''.$langs->trans('Description').''.$langs->trans('VAT').''.$langs->trans('PriceUHT').''.$langs->trans('Qty').''.$langs->trans('ReductionShort').'
'; if (($objp->info_bits & 2) == 2) { print ''; print img_object($langs->trans("ShowReduc"),'reduc').' '.$langs->trans("Discount"); print ''; } else if ($objp->prodid) { print ''; print ($objp->fk_product_type == 1 ? img_object($langs->trans(''),'service') : img_object($langs->trans(''),'product')); print ' '.$objp->ref.''; print $objp->product?' - '.$objp->product:''; // Dates if ($date_start || $date_end) { print_date_range($date_start,$date_end); } } else { print ($objp->product_type == -1 ? ' ' : ($objp->product_type == 1 ? img_object($langs->trans(''),'service') : img_object($langs->trans(''),'product'))); // Dates if ($date_start || $date_end) { print_date_range($date_start,$date_end); } } print "'; if ($objp->description) { if ($objp->description == '(CREDIT_NOTE)') { $discount=new DiscountAbsolute($db); $discount->fetch($objp->fk_remise_except); print $langs->transnoentities("DiscountFromCreditNote",$discount->getNomUrl(0)); } elseif ($obj->description == '(DEPOSIT)') { $discount=new DiscountAbsolute($db); $discount->fetch($objp->fk_remise_except); print $langs->transnoentities("DiscountFromDeposit",$discount->getNomUrl(0)); } else { print dol_trunc($objp->description,60); } } else { print ' '; } print ''.vatrate($objp->tva_tx).'%'.price($objp->subprice).''; print (($objp->info_bits & 2) != 2) ? $objp->qty : ' '; print ''; print (($objp->info_bits & 2) != 2) ? $objp->remise_percent.'%' : ' '; print '
'; } } else { /* * Show object in view mode */ $now=dol_now(); $id = $_REQUEST['facid']; $ref= $_REQUEST['ref']; if ($id > 0 || ! empty($ref)) { if ($mesg) print $mesg.'
'; $fac = new Facture($db); $result=$fac->fetch($id,$ref); if ($result > 0) { if ($user->societe_id>0 && $user->societe_id!=$fac->socid) accessforbidden('',0); $result=$fac->fetch_client(); $soc = new Societe($db, $fac->socid); $soc->fetch($fac->socid); $totalpaye = $fac->getSommePaiement(); $totalcreditnotes = $fac->getSumCreditNotesUsed(); $totaldeposits = $fac->getSumDepositsUsed(); //print "totalpaye=".$totalpaye." totalcreditnotes=".$totalcreditnotes." totaldeposts=".$totaldeposits; // We cal also use bcadd to avoid pb with floating points // For example print 239.2 - 229.3 - 9.9; does not return 0. //$resteapayer=bcadd($fac->total_ttc,$totalpaye,$conf->global->MAIN_MAX_DECIMALS_TOT); //$resteapayer=bcadd($resteapayer,$totalavoir,$conf->global->MAIN_MAX_DECIMALS_TOT); $resteapayer = price2num($fac->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits,'MT'); if ($fac->paye) $resteapayer=0; $resteapayeraffiche=$resteapayer; $absolute_discount=$soc->getAvailableDiscounts('','fk_facture_source IS NULL'); $absolute_creditnote=$soc->getAvailableDiscounts('','fk_facture_source IS NOT NULL'); $absolute_discount=price2num($absolute_discount,'MT'); $absolute_creditnote=price2num($absolute_creditnote,'MT'); $author = new User($db); if ($fac->user_author) { $author->fetch($fac->user_author); } $facidnext=$fac->getIdReplacingInvoice(); $head = facture_prepare_head($fac); dol_fiche_head($head, 'compta', $langs->trans('InvoiceCustomer'), 0, 'bill'); // Confirmation de la conversion de l'avoir en reduc if ($_GET['action'] == 'converttoreduc') { $text=$langs->trans('ConfirmConvertToReduc'); $ret=$html->form_confirm($_SERVER['PHP_SELF'].'?facid='.$fac->id,$langs->trans('ConvertToReduc'),$text,'confirm_converttoreduc','',"yes",2); if ($ret == 'html') print '
'; } // Confirmation de la suppression de la facture if ($_GET['action'] == 'delete') { $text=$langs->trans('ConfirmDeleteBill'); $ret=$html->form_confirm($_SERVER['PHP_SELF'].'?facid='.$fac->id,$langs->trans('DeleteBill'),$text,'confirm_delete','',0,2); if ($ret == 'html') print '
'; } // Confirmation de la validation if ($_GET['action'] == 'valid') { // on verifie si l'objet est en numerotation provisoire $facref = substr($fac->ref, 1, 4); if ($facref == 'PROV') { $savdate=$fac->date; if (! empty($conf->global->FAC_FORCE_DATE_VALIDATION)) { $fac->date=gmmktime(); $fac->date_lim_reglement=$fac->calculate_date_lim_reglement(); } $numref = $fac->getNextNumRef($soc); //$fac->date=$savdate; } else { $numref = $fac->ref; } $text=$langs->trans('ConfirmValidateBill',$numref); if ($conf->notification->enabled) { require_once(DOL_DOCUMENT_ROOT ."/core/class/notify.class.php"); $notify=new Notify($db); $text.='
'; $text.=$notify->confirmMessage('NOTIFY_VAL_FAC',$fac->socid); } $ret=$html->form_confirm($_SERVER["PHP_SELF"].'?facid='.$fac->id,$langs->trans('ValidateBill'),$text,'confirm_valid','',"yes",($conf->notification->enabled?0:2)); if ($ret == 'html') print '
'; } // Confirmation du classement paye if ($_GET['action'] == 'paid' && $resteapayer <= 0) { $ret=$html->form_confirm($_SERVER["PHP_SELF"].'?facid='.$fac->id,$langs->trans('ClassifyPaid'),$langs->trans('ConfirmClassifyPaidBill',$fac->ref),'confirm_paid','',"yes",1); if ($ret == 'html') print '
'; } if ($_GET['action'] == 'paid' && $resteapayer > 0) { // Code $i=0; $close[$i]['code']='discount_vat';$i++; $close[$i]['code']='badcustomer';$i++; // Help $i=0; $close[$i]['label']=$langs->trans("HelpEscompte").'

'.$langs->trans("ConfirmClassifyPaidPartiallyReasonDiscountVatDesc");$i++; $close[$i]['label']=$langs->trans("ConfirmClassifyPaidPartiallyReasonBadCustomerDesc");$i++; // Texte $i=0; $close[$i]['reason']=$html->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonDiscountVat",$resteapayer,$langs->trans("Currency".$conf->monnaie)),$close[$i]['label'],1);$i++; $close[$i]['reason']=$html->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadCustomer",$resteapayer,$langs->trans("Currency".$conf->monnaie)),$close[$i]['label'],1);$i++; // arrayreasons[code]=reason foreach($close as $key => $val) { $arrayreasons[$close[$key]['code']]=$close[$key]['reason']; } // Cree un tableau formulaire $formquestion=array( 'text' => $langs->trans("ConfirmClassifyPaidPartiallyQuestion"), array('type' => 'radio', 'name' => 'close_code', 'label' => $langs->trans("Reason"), 'values' => $arrayreasons), array('type' => 'text', 'name' => 'close_note', 'label' => $langs->trans("Comment"), 'value' => '', 'size' => '100') ); // Paiement incomplet. On demande si motif = escompte ou autre $ret=$html->form_confirm($_SERVER["PHP_SELF"].'?facid='.$fac->id,$langs->trans('ClassifyPaid'),$langs->trans('ConfirmClassifyPaidPartially',$fac->ref),'confirm_paid_partially',$formquestion,"yes"); if ($ret == 'html') print '
'; } // Confirmation du classement abandonne if ($_GET['action'] == 'canceled') { // S'il y a une facture de remplacement pas encore validee (etat brouillon), // on ne permet pas de classer abandonner la facture. if ($facidnext) { $facturereplacement=new Facture($db); $facturereplacement->fetch($facidnext); $statusreplacement=$facturereplacement->statut; } if ($facidnext && $statusreplacement == 0) { print '
'.$langs->trans("ErrorCantCancelIfReplacementInvoiceNotValidated").'
'; } else { // Code $close[1]['code']='badcustomer'; $close[2]['code']='abandon'; // Help $close[1]['label']=$langs->trans("ConfirmClassifyPaidPartiallyReasonBadCustomerDesc"); $close[2]['label']=$langs->trans("ConfirmClassifyAbandonReasonOtherDesc"); // Texte $close[1]['reason']=$html->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadCustomer",$fac->ref),$close[1]['label'],1); $close[2]['reason']=$html->textwithpicto($langs->transnoentities("ConfirmClassifyAbandonReasonOther"),$close[2]['label'],1); // arrayreasons $arrayreasons[$close[1]['code']]=$close[1]['reason']; $arrayreasons[$close[2]['code']]=$close[2]['reason']; // Cree un tableau formulaire $formquestion=array( 'text' => $langs->trans("ConfirmCancelBillQuestion"), array('type' => 'radio', 'name' => 'close_code', 'label' => $langs->trans("Reason"), 'values' => $arrayreasons), array('type' => 'text', 'name' => 'close_note', 'label' => $langs->trans("Comment"), 'value' => '', 'size' => '100') ); $ret=$html->form_confirm($_SERVER['PHP_SELF'].'?facid='.$fac->id,$langs->trans('CancelBill'),$langs->trans('ConfirmCancelBill',$fac->ref),'confirm_canceled',$formquestion,"yes"); if ($ret == 'html') print '
'; } } // Confirmation de la suppression d'une ligne produit if ($_GET['action'] == 'delete_product_line') { $ret=$html->form_confirm($_SERVER["PHP_SELF"].'?facid='.$fac->id.'&rowid='.$_GET["rowid"], $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteproductline', '', 'no', 1); if ($ret == 'html') print '
'; } // Clone confirmation if ($_GET["action"] == 'clone') { // Create an array for form $formquestion=array( //'text' => $langs->trans("ConfirmClone"), //array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1) ); // Paiement incomplet. On demande si motif = escompte ou autre $ret=$html->form_confirm($_SERVER["PHP_SELF"].'?facid='.$fac->id,$langs->trans('CloneInvoice'),$langs->trans('ConfirmCloneInvoice',$fac->ref),'confirm_clone',$formquestion,'yes',1); if ($ret == 'html') print '
'; } // Invoice content print ''; // Ref print ''; print ''; // Ref client /* \todo L'info "Reference commande client" est une carac de la commande et non de la facture. Elle devrait donc etre stockee sur l'objet commande lie a la facture et non sur la facture. Pour ceux qui utilisent ainsi, positionner la constante FAC_USE_CUSTOMER_ORDER_REF a 1. */ if ($conf->global->FAC_USE_CUSTOMER_ORDER_REF) { print ''; print ''; } // Third party print ''; print ''; print ''; // Type print ''; // Discounts print ''; // Date invoice print ''; /* * List of payments */ $nbrows=8; if ($conf->global->FAC_USE_CUSTOMER_ORDER_REF) $nbrows++; if ($conf->projet->enabled) $nbrows++; //Local taxes if ($mysoc->pays_code=='ES') { if($mysoc->localtax1_assuj=="1") $nbrows++; if($mysoc->localtax2_assuj=="1") $nbrows++; } print ''; // Date payment term print ''; // Conditions de reglement print ''; // Mode de reglement print ''; // Lit lignes de facture pour determiner montant // On s'en sert pas mais ca sert pour debuggage /* $sql = 'SELECT l.price as price, l.qty, l.rowid, l.tva_tx,'; $sql .= ' l.remise_percent, l.subprice'; $sql .= ' FROM '.MAIN_DB_PREFIX.'facturedet as l '; $sql .= ' WHERE l.fk_facture = '.$fac->id; $resql = $db->query($sql); if ($resql) { $num_lignes = $db->num_rows($resql); $i=0; $total_lignes_ht=0; $total_lignes_vat=0; $total_lignes_ttc=0; while ($i < $num_lignes) { $obj=$db->fetch_object($resql); $ligne_ht=($obj->price*$obj->qty); $ligne_vat=($ligne_ht*$obj->tva_tx/100); $ligne_ttc=($ligne_ht+$ligne_vat); $total_lignes_ht+=$ligne_ht; $total_lignes_vat+=$ligne_vat; $total_lignes_ttc+=$ligne_ttc; $i++; } } */ // Montants print ''; print ''; print ''; print ''; print ''; // Amount Local Taxes if ($mysoc->pays_code=='ES') { if ($mysoc->localtax1_assuj=="1") //Localtax1 RE { print ''; print ''; print ''; } if ($mysoc->localtax2_assuj=="1") //Localtax2 IRPF { print ''; print ''; print ''; } } print ''; print ''; // Statut print ''; print ''; // Project if ($conf->projet->enabled) { $langs->load('projects'); print ''; print ''; print ''; } print '
'.$langs->trans('Ref').''; $morehtmlref=''; $discount=new DiscountAbsolute($db); $result=$discount->fetch(0,$fac->id); if ($result > 0) { $morehtmlref=' ('.$langs->trans("CreditNoteConvertedIntoDiscount",$discount->getNomUrl(1,'discount')).')'; } if ($result < 0) { dol_print_error('',$discount->error); } print $html->showrefnav($fac,'ref','',1,'facnumber','ref',$morehtmlref); print '
'; print ''; if ($_GET['action'] != 'RefCustomerOrder' && $fac->brouillon) print ''; print '
'; print $langs->trans('RefCustomerOrder').''; print ''.img_edit($langs->trans('Modify')).'
'; print '
'; if ($user->rights->facture->creer && $_GET['action'] == 'RefCustomerOrder') { print '
'; print ''; print ''; print ''; print ' '; print '
'; } else { print $fac->ref_client; } print '
'.$langs->trans('Company').''.$soc->getNomUrl(1,'compta'); print '   ('.$langs->trans('OtherBills').')
'.$langs->trans('Type').''; print $fac->getLibType(); if ($fac->type == 1) { $facreplaced=new Facture($db); $facreplaced->fetch($fac->fk_facture_source); print ' ('.$langs->transnoentities("ReplaceInvoice",$facreplaced->getNomUrl(1)).')'; } if ($fac->type == 2) { $facusing=new Facture($db); $facusing->fetch($fac->fk_facture_source); print ' ('.$langs->transnoentities("CorrectInvoice",$facusing->getNomUrl(1)).')'; } $facidavoir=$fac->getListIdAvoirFromInvoice(); if (sizeof($facidavoir) > 0) { print ' ('.$langs->transnoentities("InvoiceHasAvoir"); $i=0; foreach($facidavoir as $id) { if ($i==0) print ' '; else print ','; $facavoir=new Facture($db); $facavoir->fetch($id); print $facavoir->getNomUrl(1); } print ')'; } if ($facidnext > 0) { $facthatreplace=new Facture($db); $facthatreplace->fetch($facidnext); print ' ('.$langs->transnoentities("ReplacedByInvoice",$facthatreplace->getNomUrl(1)).')'; } print '
'.$langs->trans('Discounts').''; if ($soc->remise_client) print $langs->trans("CompanyHasRelativeDiscount",$soc->remise_client); else print $langs->trans("CompanyHasNoRelativeDiscount"); print '. '; if ($absolute_discount > 0) { if ($fac->statut > 0 || $fac->type == 2 || $fac->type == 3) { if ($fac->statut == 0) { print $langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->transnoentities("Currency".$conf->monnaie)).'. '; } else { if ($fac->statut < 1 || $fac->type == 2 || $fac->type == 3) { $text=$langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->transnoentities("Currency".$conf->monnaie)); print '
'.$text.'.
'; } else { $text=$langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->transnoentities("Currency".$conf->monnaie)); $text2=$langs->trans("AbsoluteDiscountUse"); print $html->textwithpicto($text,$text2); } } } else { // Remise dispo de type non avoir $filter='fk_facture_source IS NULL'; print '
'; $html->form_remise_dispo($_SERVER["PHP_SELF"].'?facid='.$fac->id,0,'remise_id',$soc->id,$absolute_discount,$filter,$resteapayer); } } if ($absolute_creditnote > 0) { // If validated, we show link "add credit note to payment" if ($fac->statut != 1 || $fac->type == 2 || $fac->type == 3) { if ($fac->statut == 0 && $fac->type != 3) { $text=$langs->trans("CompanyHasCreditNote",price($absolute_creditnote),$langs->transnoentities("Currency".$conf->monnaie)); print $html->textwithpicto($text,$langs->trans("CreditNoteDepositUse")); } else print $langs->trans("CompanyHasCreditNote",price($absolute_creditnote),$langs->transnoentities("Currency".$conf->monnaie)).'.'; } else { // Remise dispo de type avoir $filter='fk_facture_source IS NOT NULL'; if (! $absolute_discount) print '
'; $html->form_remise_dispo($_SERVER["PHP_SELF"].'?facid='.$fac->id,0,'remise_id_for_payment',$soc->id,$absolute_creditnote,$filter,$resteapayer); } } if (! $absolute_discount && ! $absolute_creditnote) print $langs->trans("CompanyHasNoAbsoluteDiscount").'.'; print '
'; print ''; if ($fac->type != 2 && $_GET['action'] != 'editinvoicedate' && $fac->brouillon && $user->rights->facture->creer) print ''; print '
'; print $langs->trans('Date'); print 'id.'">'.img_edit($langs->trans('SetDate'),1).'
'; print '
'; if ($fac->type != 2) { if ($_GET['action'] == 'editinvoicedate') { $html->form_date($_SERVER['PHP_SELF'].'?facid='.$fac->id,$fac->date,'invoicedate'); } else { print dol_print_date($fac->date,'daytext'); } } else { print dol_print_date($fac->date,'daytext'); } print ''; print ''; // List of payments already done print ''; print ''; print ''; print ''; print ''; print ''; $var=true; // Payments already done (from deposits) /* $depositamount=0; $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,"; $sql.= " re.description, re.fk_facture_source, re.fk_facture_source"; $sql.= " FROM ".MAIN_DB_PREFIX ."societe_remise_except as re"; $sql.= " WHERE fk_facture = ".$fac->id; $resql=$db->query($sql); if ($resql) { $numdeposits = $db->num_rows($resql); $i = 0; $invoice=new Facture($db); // Loop on each deposit applied while ($i < $numdeposits) { $objinvoice = $db->fetch_object($resql); $invoice->fetch($objinvoice->fk_facture_source); if ($invoice->type != 3) continue; // only deposits // For each deposits, get payments $sql = 'SELECT datep as dp, pf.amount,'; $sql.= ' c.libelle as paiement_type, p.num_paiement, p.rowid'; $sql.= ' FROM '.MAIN_DB_PREFIX.'paiement as p, '.MAIN_DB_PREFIX.'c_paiement as c, '.MAIN_DB_PREFIX.'paiement_facture as pf'; $sql.= ' WHERE pf.fk_facture = '.$invoice->id.' AND p.fk_paiement = c.id AND pf.fk_paiement = p.rowid'; $sql.= ' ORDER BY dp, tms'; $resqlpayment = $db->query($sql); if ($resqlpayment) { $numpayments = $db->num_rows($resqlpayment); $j = 0; while ($j < $numpayments) { $objpayment = $db->fetch_object($resqlpayement); $var=!$var; print ''; print ''; print ''; // Remove deposit invoice print ''; print ''; $j++; $depositamount += $obj->amount; } } $i++; } } else { dol_print_error($db); } */ // Payments already done (from payment on this invoice) $sql = 'SELECT p.datep as dp, p.num_paiement, p.rowid,'; $sql.= ' c.code as payment_code, c.libelle as payment_label,'; $sql.= ' pf.amount'; $sql.= ' FROM '.MAIN_DB_PREFIX.'paiement as p, '.MAIN_DB_PREFIX.'c_paiement as c, '.MAIN_DB_PREFIX.'paiement_facture as pf'; $sql.= ' WHERE pf.fk_facture = '.$fac->id.' AND p.fk_paiement = c.id AND pf.fk_paiement = p.rowid'; $sql.= ' ORDER BY dp, tms'; $result = $db->query($sql); if ($result) { $num = $db->num_rows($result); $i = 0; if ($fac->type != 2) { while ($i < $num) { $objp = $db->fetch_object($result); $var=!$var; print ''; $label=($langs->trans("PaymentType".$objp->payment_code)!=("PaymentType".$objp->payment_code))?$langs->trans("PaymentType".$objp->payment_code):$objp->payment_label; print ''; print ''; print ''; print ''; $i++; } } $db->free($result); } else { dol_print_error($db); } if ($fac->type != 2) { // Total already paid print ''; $resteapayeraffiche=$resteapayer; // Loop on each credit note or deposit amount applied $creditnoteamount=0; $depositamount=0; $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,"; $sql.= " re.description, re.fk_facture_source, re.fk_facture_source"; $sql.= " FROM ".MAIN_DB_PREFIX ."societe_remise_except as re"; $sql.= " WHERE fk_facture = ".$fac->id; $resql=$db->query($sql); if ($resql) { $num = $db->num_rows($resql); $i = 0; $invoice=new Facture($db); while ($i < $num) { $obj = $db->fetch_object($resql); $invoice->fetch($obj->fk_facture_source); print ''; print ''; print ''; $i++; if ($invoice->type == 2) $creditnoteamount += $obj->amount_ttc; if ($invoice->type == 3) $depositamount += $obj->amount_ttc; } } else { dol_print_error($db); } // Paye partiellement 'escompte' if (($fac->statut == 2 || $fac->statut == 3) && $fac->close_code == 'discount_vat') { print ''; $resteapayeraffiche=0; } // Paye partiellement ou Abandon 'badcustomer' if (($fac->statut == 2 || $fac->statut == 3) && $fac->close_code == 'badcustomer') { print ''; //$resteapayeraffiche=0; } // Paye partiellement ou Abandon 'product_returned' if (($fac->statut == 2 || $fac->statut == 3) && $fac->close_code == 'product_returned') { print ''; $resteapayeraffiche=0; } // Paye partiellement ou Abandon 'abandon' if (($fac->statut == 2 || $fac->statut == 3) && $fac->close_code == 'abandon') { print ''; $resteapayeraffiche=0; } // Billed print ''; // Remainder to pay print ''; print ''; print ''; } else { // Sold credit note print ''; print ''; } print '
'.($fac->type == 2 ? $langs->trans("PaymentsBack") : $langs->trans('Payments')).''.$langs->trans('Type').''.$langs->trans('Amount').' 
'; print ''.img_object($langs->trans('ShowPayment'),'payment').' '; print dol_print_date($db->jdate($objpayment->dp),'day').''; print ' ('.$langs->trans("Deposit").' '; print $invoice->getNomUrl(0).')'; print ''.$objpayment->paiement_type.' '.$objpayement->num_paiement.''.price($objpayment->amount).''; print 'rowid.'">'.img_delete().''; print '
'; print ''.img_object($langs->trans('ShowPayment'),'payment').' '; print dol_print_date($db->jdate($objp->dp),'day').''.$label.' '.$objp->num_paiement.''.price($objp->amount).' 
'; if ($fac->type != 3) print $langs->trans('AlreadyPaidNoCreditNotesNoDeposits'); else print $langs->trans('AlreadyPaid'); print ' :'.price($totalpaye).' 
'; if ($invoice->type == 2) print $langs->trans("CreditNote").' '; if ($invoice->type == 3) print $langs->trans("Deposit").' '; print $invoice->getNomUrl(0); print ' :'.price($obj->amount_ttc).''; print 'rowid.'">'.img_delete().''; print '
'; print $html->textwithpicto($langs->trans("Escompte").':',$langs->trans("HelpEscompte"),-1); print ''.price($fac->total_ttc - $creditnoteamount - $depositamount - $totalpaye).' 
'; print $html->textwithpicto($langs->trans("Abandoned").':',$langs->trans("HelpAbandonBadCustomer"),-1); print ''.price($fac->total_ttc - $creditnoteamount - $depositamount - $totalpaye).' 
'; print $html->textwithpicto($langs->trans("ProductReturned").':',$langs->trans("HelpAbandonProductReturned"),-1); print ''.price($fac->total_ttc - $creditnoteamount - $depositamount - $totalpaye).' 
'; $text=$langs->trans("HelpAbandonOther"); if ($fac->close_note) $text.='

'.$langs->trans("Reason").':'.$fac->close_note; print $html->textwithpicto($langs->trans("Abandoned").':',$text,-1); print '
'.price($fac->total_ttc - $creditnoteamount - $depositamount - $totalpaye).' 
'.$langs->trans("Billed").' :'.price($fac->total_ttc).' 
'; if ($resteapayeraffiche >= 0) print $langs->trans('RemainderToPay'); else print $langs->trans('ExcessReceived'); print ' :'.price($resteapayeraffiche).' 
'.$langs->trans('TotalTTCToYourCredit').' :'.price(abs($fac->total_ttc)).' 
'; print '
'; print ''; if ($fac->type != 2 && $_GET['action'] != 'editpaymentterm' && $fac->brouillon && $user->rights->facture->creer) print ''; print '
'; print $langs->trans('DateMaxPayment'); print 'id.'">'.img_edit($langs->trans('SetDate'),1).'
'; print '
'; if ($fac->type != 2) { if ($_GET['action'] == 'editpaymentterm') { $html->form_date($_SERVER['PHP_SELF'].'?facid='.$fac->id,$fac->date_lim_reglement,'paymentterm'); } else { print dol_print_date($fac->date_lim_reglement,'daytext'); if ($fac->date_lim_reglement < ($now - $conf->facture->client->warning_delay) && ! $fac->paye && $fac->statut == 1 && ! $fac->am) print img_warning($langs->trans('Late')); } } else { print ' '; } print '
'; print ''; if ($fac->type != 2 && $_GET['action'] != 'editconditions' && $fac->brouillon && $user->rights->facture->creer) print ''; print '
'; print $langs->trans('PaymentConditionsShort'); print 'id.'">'.img_edit($langs->trans('SetConditions'),1).'
'; print '
'; if ($fac->type != 2) { if ($_GET['action'] == 'editconditions') { $html->form_conditions_reglement($_SERVER['PHP_SELF'].'?facid='.$fac->id,$fac->cond_reglement_id,'cond_reglement_id'); } else { $html->form_conditions_reglement($_SERVER['PHP_SELF'].'?facid='.$fac->id,$fac->cond_reglement_id,'none'); } } else { print ' '; } print '
'; print ''; if ($_GET['action'] != 'editmode' && $fac->brouillon && $user->rights->facture->creer) print ''; print '
'; print $langs->trans('PaymentMode'); print 'id.'">'.img_edit($langs->trans('SetMode'),1).'
'; print '
'; if ($_GET['action'] == 'editmode') { $html->form_modes_reglement($_SERVER['PHP_SELF'].'?facid='.$fac->id,$fac->mode_reglement_id,'mode_reglement_id'); } else { $html->form_modes_reglement($_SERVER['PHP_SELF'].'?facid='.$fac->id,$fac->mode_reglement_id,'none'); } print '
'.$langs->trans('AmountHT').''.price($fac->total_ht).''.$langs->trans('Currency'.$conf->monnaie).'
'.$langs->trans('AmountVAT').''.price($fac->total_tva).''.$langs->trans('Currency'.$conf->monnaie).'
'.$langs->transcountry("AmountLT1",$mysoc->pays_code).''.price($fac->total_localtax1).''.$langs->trans("Currency".$conf->monnaie).'
'.$langs->transcountry("AmountLT2",$mysoc->pays_code).''.price($fac->total_localtax2).''.$langs->trans("Currency".$conf->monnaie).'
'.$langs->trans('AmountTTC').''.price($fac->total_ttc).''.$langs->trans('Currency'.$conf->monnaie).'
'.$langs->trans('Status').''.($fac->getLibStatut(4,$totalpaye)).'
'; print ''; if ($_GET['action'] != 'classin') { print ''; } print '
'; print $langs->trans('Project'); print 'id.'">'; print img_edit($langs->trans('SetProject'),1); print '
'; print '
'; if ($_GET['action'] == 'classin') { $html->form_project($_SERVER['PHP_SELF'].'?facid='.$fac->id,$fac->socid,$fac->fk_project,'projectid'); } else { $html->form_project($_SERVER['PHP_SELF'].'?facid='.$fac->id,$fac->socid,$fac->fk_project,'none'); } print '

'; /* * Inoice lines */ $sql = 'SELECT l.fk_product, l.product_type, l.description, l.qty, l.rowid, l.tva_tx,'; $sql.= ' l.fk_remise_except,'; $sql.= ' l.remise_percent, l.subprice, l.info_bits,'; $sql.= ' l.total_ht, l.total_tva, l.total_ttc,'; $sql.= ' l.date_start,'; $sql.= ' l.date_end,'; $sql.= ' l.product_type,'; $sql.= ' p.ref as product_ref, p.fk_product_type, p.label as product_label,'; $sql.= ' p.description as product_desc'; $sql.= ' FROM '.MAIN_DB_PREFIX.'facturedet as l'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product p ON l.fk_product=p.rowid'; $sql.= ' WHERE l.fk_facture = '.$fac->id; $sql.= ' ORDER BY l.rang ASC, l.rowid'; $resql = $db->query($sql); if ($resql) { $num_lignes = $db->num_rows($resql); $i = 0; $total = 0; $product_static=new Product($db); print ''; if ($num_lignes) { print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print "\n"; } $var=true; while ($i < $num_lignes) { $objp = $db->fetch_object($resql); $var=!$var; // Show product and description $type=$objp->product_type?$objp->product_type:$objp->fk_product_type; // Try to enhance type detection using date_start and date_end for free lines where type // was not saved. if (! empty($objp->date_start)) $type=1; if (! empty($objp->date_end)) $type=1; // Show line if ($_GET['action'] != 'editline' || $_GET['rowid'] != $objp->rowid) { print ''; if ($objp->fk_product > 0) { print ''; } else { print '\n"; } // VAT print ''; // Unit price print '\n"; print ''; // Remise percent (negative or positive) if (!empty($objp->remise_percent)) { print '\n"; } else { print ''; } // Montant total HT print '\n"; // Icone d'edition et suppression if ($fac->statut == 0 && $user->rights->facture->creer) { print ''; print ''; if ($num_lignes > 1) { print ''; } } else { print ''; } print ''; } // Ligne en mode update if ($_GET['action'] == 'editline' && $user->rights->facture->creer && $_GET['rowid'] == $objp->rowid) { print 'rowid.'" method="post">'; print ''; print ''; print ''; print ''; print ''; print ''; // VAT print ''; // Unit price print ''; print ''; print ''; print ''; print '' . "\n"; if ($conf->service->enabled) { print ''; print ''; print ''; } print "\n"; } $total = $total + ($objp->qty * $objp->price); $i++; } $db->free($resql); } else { dol_print_error($db); } /* * Form to add new line */ if ($fac->statut == 0 && $user->rights->facture->creer && $_GET['action'] <> 'valid' && $_GET['action'] <> 'editline') { // Free zone form print ''; print ''; print ''; print ''; print ''; print ''; print ''; print "\n"; // Add free products/services form print ''; print ''; print ''; print ''; $var=true; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; if ($conf->service->enabled) { print ''; print ''; print ''; } print ''; // Predefined services/products form if ($conf->product->enabled || $conf->service->enabled) { print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; $var=! $var; print ''; print ''; print ''; print ''; print ''; print ''; if ($conf->service->enabled) { print ''; print ''; print ''; } print ''; } } print "
'.$langs->trans('Description').''.$langs->trans('VAT').''.$langs->trans('PriceUHT').''.$langs->trans('Qty').''.$langs->trans('ReductionShort').''.$langs->trans('TotalHTShort').' 
'; print ''; // ancre pour retourner sur la ligne // Show product and description $product_static->type=$objp->fk_product_type; $product_static->id=$objp->fk_product; $product_static->ref=$objp->product_ref; $product_static->libelle=$objp->product_label; $text=$product_static->getNomUrl(1); $text.= ' - '.$objp->product_label; $description=($conf->global->PRODUIT_DESC_IN_FORM?'':dol_htmlentitiesbr($objp->description)); print $html->textwithtooltip($text,$description,3,'','',$i); // Show range print_date_range($db->jdate($objp->date_start),$db->jdate($objp->date_end)); // Add description in form if ($conf->global->PRODUIT_DESC_IN_FORM) print ($objp->description && $objp->description!=$objp->product_label)?'
'.dol_htmlentitiesbr($objp->description):''; print '
'; print ''; // ancre pour retourner sur la ligne if (($objp->info_bits & 2) == 2) { print ''; print img_object($langs->trans("ShowReduc"),'reduc').' '.$langs->trans("Discount"); print ''; if ($objp->description) { if ($objp->description == '(CREDIT_NOTE)') { $discount=new DiscountAbsolute($db); $discount->fetch($objp->fk_remise_except); print ' - '.$langs->transnoentities("DiscountFromCreditNote",$discount->getNomUrl(0)); } elseif ($objp->description == '(DEPOSIT)') { $discount=new DiscountAbsolute($db); $discount->fetch($objp->fk_remise_except); print ' - '.$langs->transnoentities("DiscountFromDeposit",$discount->getNomUrl(0)); } else { print ' - '.nl2br($objp->description); } } } else { if ($type==1) $text = img_object($langs->trans('Service'),'service'); else $text = img_object($langs->trans('Product'),'product'); print $text.' '.nl2br($objp->description); // Show range print_date_range($db->jdate($objp->date_start),$db->jdate($objp->date_end)); } print "'.vatrate($objp->tva_tx,'%',$objp->info_bits).''.price($objp->subprice)."'; if (($objp->info_bits & 2) != 2) { print $objp->qty; } else print ' '; print ''.dol_print_reduction($objp->remise_percent,$langs)." '.price($objp->total_ht)."'; if (($objp->info_bits & 2) == 2) { // Ligne remise predefinie, on permet pas modif } else { print 'rowid.'#'.$objp->rowid.'">'; print img_edit(); print ''; } print ''; print 'rowid.'">'; print img_delete(); print ''; if ($i > 0) { print 'rowid.'">'; print img_up(); print ''; } if ($i < $num_lignes-1) { print 'rowid.'">'; print img_down(); print ''; } print ' 
'; print ''; // ancre pour retourner sur la ligne // Show product and description if ($objp->fk_product > 0) { print ''; $product_static->type=$objp->fk_product_type; $product_static->id=$objp->fk_product; $product_static->ref=$objp->product_ref; $product_static->libelle=$objp->product_label; $text=$product_static->getNomUrl(1); $text.= ' - '.$objp->product_label; print $text; print '
'; } else { print $html->select_type_of_lines($objp->product_type,'type',1); if ($conf->product->enabled && $conf->service->enabled) print '
'; } // Description - Editor wysiwyg if ($conf->fckeditor->enabled && $conf->global->FCKEDITOR_ENABLE_DETAILS) { require_once(DOL_DOCUMENT_ROOT."/lib/doleditor.class.php"); $doleditor=new DolEditor('desc',$objp->description,164,'dolibarr_details'); $doleditor->Create(); } else { $nbrows=ROWS_2; if (! empty($conf->global->MAIN_INPUT_DESC_HEIGHT)) $nbrows=$conf->global->MAIN_INPUT_DESC_HEIGHT; print ''; } print '
'; print $html->select_tva('tva_tx',$objp->tva_tx,$mysoc,$soc,'',$objp->info_bits); print ''; if (($objp->info_bits & 2) != 2) { print ''; } else print ' '; print ''; if (($objp->info_bits & 2) != 2) { print '%'; } else print ' '; print ''; print '
'.$langs->trans('ServiceLimitedDuration').' '.$langs->trans('From').' '; print $html->select_date($db->jdate($objp->date_start),'date_start',$usehm,$usehm,$objp->date_start?0:1,"updateligne"); print ' '.$langs->trans('to').' '; print $html->select_date($db->jdate($objp->date_end),'date_end',$usehm,$usehm,$objp->date_end?0:1,"updateligne"); print '
'; print ''; // ancre print $langs->trans('AddNewLine').' - '.$langs->trans("FreeZone").''.$langs->trans('VAT').''.$langs->trans('PriceUHT').''.$langs->trans('Qty').''.$langs->trans('ReductionShort').' 
'; print $html->select_type_of_lines(isset($_POST["type"])?$_POST["type"]:-1,'type',1); if (($conf->product->enabled && $conf->service->enabled) || (empty($conf->product->enabled) && empty($conf->service->enabled))) print '
'; // Editor wysiwyg if ($conf->fckeditor->enabled && $conf->global->FCKEDITOR_ENABLE_DETAILS) { require_once(DOL_DOCUMENT_ROOT."/lib/doleditor.class.php"); $doleditor=new DolEditor('dp_desc',$_POST["dp_desc"],100,'dolibarr_details'); $doleditor->Create(); } else { $nbrows=ROWS_2; if (! empty($conf->global->MAIN_INPUT_DESC_HEIGHT)) $nbrows=$conf->global->MAIN_INPUT_DESC_HEIGHT; print ''; } print '
'; if($soc->tva_assuj == "0") print '0'; else $html->select_tva('tva_tx',$conf->defaulttx,$mysoc,$soc); print '%
'.$langs->trans('ServiceLimitedDuration').' '.$langs->trans('From').' '; print $html->select_date('','date_start',$usehm,$usehm,1,"addline"); print ' '.$langs->trans('to').' '; print $html->select_date('','date_end',$usehm,$usehm,1,"addline"); print '
'; print $langs->trans("AddNewLine").' - '; if ($conf->service->enabled) { print $langs->trans('RecordedProductsAndServices'); } else { print $langs->trans('RecordedProducts'); } print ''.$langs->trans('Qty').''.$langs->trans('ReductionShort').' 
'; // multiprix if($conf->global->PRODUIT_MULTIPRICES) { $html->select_produits((! empty($_POST['idprod'])?$_POST['idprod']:''),'idprod','',$conf->product->limit_size,$soc->price_level); } else { $html->select_produits((! empty($_POST['idprod'])?$_POST['idprod']:''),'idprod','',$conf->product->limit_size); } if (! $conf->global->PRODUIT_USE_SEARCH_TO_SELECT) print '
'; // Editor wysiwyg if ($conf->fckeditor->enabled && $conf->global->FCKEDITOR_ENABLE_DETAILS) { require_once(DOL_DOCUMENT_ROOT."/lib/doleditor.class.php"); $doleditor=new DolEditor('np_desc',$_POST["np_desc"],100,'dolibarr_details'); $doleditor->Create(); } else { $nbrows=ROWS_2; if (! empty($conf->global->MAIN_INPUT_DESC_HEIGHT)) $nbrows=$conf->global->MAIN_INPUT_DESC_HEIGHT; print ''; } print '
%
'.$langs->trans('ServiceLimitedDuration').' '.$langs->trans('From').' '; print $html->select_date('','date_start_predef',$usehm,$usehm,1,"addline_predef"); print ' '.$langs->trans('to').' '; print $html->select_date('','date_end_predef',$usehm,$usehm,1,"addline_predef"); print '
\n"; print "\n"; /* * Boutons actions */ if ($_GET['action'] != 'prerelance' && $_GET['action'] != 'presend') { if ($user->societe_id == 0 && $_GET['action'] <> 'valid' && $_GET['action'] <> 'editline') { print '
'; // Editer une facture deja validee, sans paiement effectue et pas exporte en compta if ($fac->statut == 1) { // On verifie si les lignes de factures ont ete exportees en compta et/ou ventilees $ventilExportCompta = $fac->getVentilExportCompta(); if ($resteapayer == $fac->total_ttc && $fac->paye == 0 && $ventilExportCompta == 0) { if (! $facidnext) { if ($user->rights->facture->unvalidate) { print ''.$langs->trans('Modify').''; } else { print ''.$langs->trans('Modify').''; } } else { print ''.$langs->trans('Modify').''; } } } // Reopen a standard paid invoice if (($fac->type == 0 || $fac->type == 1) && ($fac->statut == 2 || $fac->statut == 3)) // A paid invoice (partially or completely) { if (! $facidnext && $fac->close_code != 'replaced') // Not replaced by another invoice { print ''.$langs->trans('ReOpen').''; } else { print ''.$langs->trans('ReOpen').''; } } // Validate if ($fac->statut == 0 && $num_lignes > 0 && ( (($fac->type == 0 || $fac->type == 1 || $fac->type == 3 || $fac->type == 4) && $fac->total_ttc >= 0) || ($fac->type == 2 && $fac->total_ttc <= 0)) ) { if ($user->rights->facture->valider) { print ''.$langs->trans('Validate').''; } } // Send by mail if (($fac->statut == 1 || $fac->statut == 2) && $user->rights->facture->envoyer) { if ($facidnext) { print ''.$langs->trans('SendByMail').''; } else { print ''.$langs->trans('SendByMail').''; } } if ($conf->global->FACTURE_SHOW_SEND_REMINDER) // For backward compatibility { if (($fac->statut == 1 || $fac->statut == 2) && $resteapayer > 0 && $user->rights->facture->envoyer) { if ($facidnext) { print ''.$langs->trans('SendRemindByMail').''; } else { print ''.$langs->trans('SendRemindByMail').''; } } } // Create payment if ($fac->type != 2 && $fac->statut == 1 && $fac->paye == 0 && $user->rights->facture->paiement) { if ($facidnext) { print ''.$langs->trans('DoPayment').''; } else { if ($resteapayer == 0) { print ''.$langs->trans('DoPayment').''; } else { print ''.$langs->trans('DoPayment').''; } } } // Reverse back money or convert to reduction if ($fac->type == 2 || $fac->type == 3) { // For credit note only if ($fac->type == 2 && $fac->statut == 1 && $fac->paye == 0 && $user->rights->facture->paiement) { print ''.$langs->trans('DoPaymentBack').''; } // For credit note if ($fac->type == 2 && $fac->statut == 1 && $fac->paye == 0 && $user->rights->facture->creer && $fac->getSommePaiement() == 0) { print ''.$langs->trans('ConvertToReduc').''; } // For deposit invoice if ($fac->type == 3 && $fac->statut == 1 && $resteapayer == 0 && $user->rights->facture->creer) { print ''.$langs->trans('ConvertToReduc').''; } } // Classify paid (if not deposit and not credit note. Such invoice are "converted") if ($fac->statut == 1 && $fac->paye == 0 && $user->rights->facture->paiement && (($fac->type != 2 && $fac->type != 3 && $resteapayer <= 0) || ($fac->type == 2 && $resteapayer >= 0)) ) { print ''.$langs->trans('ClassifyPaid').''; } // Classify 'closed not completely paid' (possible si validee et pas encore classee payee) if ($fac->statut == 1 && $fac->paye == 0 && $resteapayer > 0 && $user->rights->facture->paiement) { if ($totalpaye > 0 || $totalcreditnotes > 0) { // If one payment or one credit note was linked to this invoice print ''.$langs->trans('ClassifyPaidPartially').''; } else { if ($facidnext) { print ''.$langs->trans('ClassifyCanceled').''; } else { print ''.$langs->trans('ClassifyCanceled').''; } } } // Clone if (($fac->type == 0 || $fac->type == 3 || $fac->type == 4) && $user->rights->facture->creer) { print ''.$langs->trans("ToClone").''; } // Clone as predefined if (($fac->type == 0 || $fac->type == 3 || $fac->type == 4) && $fac->statut == 0 && $user->rights->facture->creer) { if (! $facidnext) { print ''.$langs->trans("ChangeIntoRepeatableInvoice").''; } } // Delete if ($fac->is_erasable() && $user->rights->facture->supprimer && $_GET['action'] != 'delete') { if ($facidnext) { print ''.$langs->trans('Delete').''; } elseif ($fac->getSommePaiement()) { print ''.$langs->trans('Delete').''; } else { print ''.$langs->trans('Delete').''; } } print '
'; } } if ($_GET['action'] != 'prerelance' && $_GET['action'] != 'presend') { print '
'; print ''; // ancre /* * Documents generes */ $filename=dol_sanitizeFileName($fac->ref); $filedir=$conf->facture->dir_output . '/' . dol_sanitizeFileName($fac->ref); $urlsource=$_SERVER['PHP_SELF'].'?facid='.$fac->id; $genallowed=$user->rights->facture->creer; $delallowed=$user->rights->facture->supprimer; $var=true; print '
'; $somethingshown=$formfile->show_documents('facture',$filename,$filedir,$urlsource,$genallowed,$delallowed,$fac->modelpdf,1,0,0,28,0,'','','',$soc->default_lang); /* * Linked object block */ $fac->load_object_linked($fac->id,$fac->element); foreach($fac->linked_object as $object => $objectid) { if($conf->$object->enabled && $object != $fac->element) { $somethingshown=$fac->showLinkedObjectBlock($object,$objectid,$somethingshown); } } print '
'; print '
'; // List of actions on element include_once(DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'); $formactions=new FormActions($db); $somethingshown=$formactions->showactions($fac,'invoice',$socid); print '
'; } else { /* * Affiche formulaire mail */ // By default if $_GET['action']=='presend' $titreform='SendBillByMail'; $topicmail='SendBillRef'; $action='send'; $modelmail='facture_send'; if ($_GET['action'] == 'prerelance') // For backward compatibility { $titrefrom='SendReminderBillByMail'; $topicmail='SendReminderBillRef'; $action='relance'; $modelmail='facture_relance'; } $ref = dol_sanitizeFileName($fac->ref); $file = $conf->facture->dir_output . '/' . $ref . '/' . $ref . '.pdf'; // Construit PDF si non existant if (! is_readable($file)) { // Define output language $outputlangs = $langs; $newlang=''; if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) $newlang=$_REQUEST['lang_id']; if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$fac->client->default_lang; if (! empty($newlang)) { $outputlangs = new Translate("",$conf); $outputlangs->setDefaultLang($newlang); } $result=facture_pdf_create($db, $fac->id, '', $_REQUEST['model'], $outputlangs); if ($result <= 0) { dol_print_error($db,$result); exit; } } print '
'; print_titre($langs->trans($titre)); // Cree l'objet formulaire mail include_once(DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'); $formmail = new FormMail($db); $formmail->fromtype = 'user'; $formmail->fromid = $user->id; $formmail->fromname = $user->getFullName($langs); $formmail->frommail = $user->email; $formmail->withfrom=1; $formmail->withto=empty($_POST["sendto"])?1:$_POST["sendto"]; $formmail->withtosocid=$soc->id; $formmail->withtocc=1; $formmail->withtoccsocid=0; $formmail->withtoccc=$conf->global->MAIN_EMAIL_USECCC; $formmail->withtocccsocid=0; $formmail->withtopic=$langs->transnoentities($topicmail,'__FACREF__'); $formmail->withfile=2; $formmail->withbody=1; $formmail->withdeliveryreceipt=1; $formmail->withcancel=1; // Tableau des substitutions $formmail->substit['__FACREF__']=$fac->ref; // Tableau des parametres complementaires du post $formmail->param['action']=$action; $formmail->param['models']=$modelmail; $formmail->param['facid']=$fac->id; $formmail->param['returnurl']=$_SERVER["PHP_SELF"].'?id='.$fac->id; // Init list of files if (! empty($_REQUEST["mode"]) && $_REQUEST["mode"]=='init') { $formmail->clear_attached_files(); $formmail->add_attached_files($file,$ref.'.pdf','application/pdf'); } $formmail->show_form(); print '
'; } } else { dol_print_error($db,$fac->error); } } else { /*************************************************************************** * * * Mode Liste * * * ***************************************************************************/ $now=gmmktime(); $page =$_GET['page']; $sortorder=$_GET['sortorder']; $sortfield=$_GET['sortfield']; $month =$_GET['month']; $year =$_GET['year']; $limit = $conf->liste_limit; $offset = $limit * $page ; if (! $sortorder) $sortorder='DESC'; if (! $sortfield) $sortfield='f.datef'; $facturestatic=new Facture($db); if ($page == -1) $page = 0 ; $sql = 'SELECT '; $sql.= ' f.rowid as facid, f.facnumber, f.type, f.increment, f.total, f.total_ttc,'; $sql.= ' f.datef as df, f.date_lim_reglement as datelimite,'; $sql.= ' f.paye as paye, f.fk_statut,'; $sql.= ' s.nom, s.rowid as socid'; if (! $sall) $sql.= ' ,SUM(pf.amount) as am'; // To be able to sort on status $sql.= ' FROM '.MAIN_DB_PREFIX.'societe as s'; if (!$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; $sql.= ', '.MAIN_DB_PREFIX.'facture as f'; if ($sall) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'facturedet as fd ON fd.fk_facture = f.rowid'; if (! $sall) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiement_facture as pf ON pf.fk_facture = f.rowid'; $sql.= ' WHERE f.fk_soc = s.rowid'; $sql.= " AND f.entity = ".$conf->entity; if (!$user->rights->societe->client->voir && !$socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; if ($socid) $sql.= ' AND s.rowid = '.$socid; if ($_GET['filtre']) { $filtrearr = explode(',', $_GET['filtre']); foreach ($filtrearr as $fil) { $filt = explode(':', $fil); $sql .= ' AND ' . trim($filt[0]) . ' = ' . trim($filt[1]); } } if ($_GET['search_ref']) { $sql.= ' AND f.facnumber LIKE \'%'.addslashes(trim($_GET['search_ref'])).'%\''; } if ($_GET['search_societe']) { $sql.= ' AND s.nom LIKE \'%'.addslashes(trim($_GET['search_societe'])).'%\''; } if ($_GET['search_montant_ht']) { $sql.= ' AND f.total = \''.addslashes(trim($_GET['search_montant_ht'])).'\''; } if ($_GET['search_montant_ttc']) { $sql.= ' AND f.total_ttc = \''.addslashes(trim($_GET['search_montant_ttc'])).'\''; } if ($month > 0) { if ($year > 0) $sql.= " AND f.datef BETWEEN '".$db->idate(dol_get_first_day($year,$month,false))."' AND '".$db->idate(dol_get_last_day($year,$month,false))."'"; else $sql.= " AND date_format(f.datef, '%m') = '$month'"; } else if ($year > 0) { $sql.= " AND f.datef BETWEEN '".$db->idate(dol_get_first_day($year,1,false))."' AND '".$db->idate(dol_get_last_day($year,12,false))."'"; } if ($_POST['sf_ref']) { $sql.= ' AND f.facnumber LIKE \'%'.addslashes(trim($_POST['sf_ref'])) . '%\''; } if ($sall) { $sql.= ' AND (s.nom LIKE \'%'.addslashes($sall).'%\' OR f.facnumber LIKE \'%'.addslashes($sall).'%\' OR f.note LIKE \'%'.addslashes($sall).'%\' OR fd.description LIKE \'%'.addslashes($sall).'%\')'; } if (! $sall) { $sql.= ' GROUP BY f.rowid, f.facnumber, f.type, f.increment, f.total, f.total_ttc,'; $sql.= ' f.datef, f.date_lim_reglement,'; $sql.= ' f.paye, f.fk_statut,'; $sql.= ' s.nom, s.rowid'; } $sql.= ' ORDER BY '; $listfield=explode(',',$sortfield); foreach ($listfield as $key => $value) $sql.= $listfield[$key].' '.$sortorder.','; $sql.= ' f.rowid DESC '; $sql.= $db->plimit($limit+1,$offset); $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); if ($socid) { $soc = new Societe($db); $soc->fetch($socid); } $param='&socid='.$socid; if ($month) $param.='&month='.$month; if ($year) $param.='&year=' .$year; print_barre_liste($langs->trans('BillsCustomers').' '.($socid?' '.$soc->nom:''),$page,'facture.php',$param,$sortfield,$sortorder,'',$num); $i = 0; print '
'."\n"; print ''; print ''; print_liste_field_titre($langs->trans('Ref'),$_SERVER['PHP_SELF'],'f.facnumber','',$param,'',$sortfield,$sortorder); print_liste_field_titre($langs->trans('Date'),$_SERVER['PHP_SELF'],'f.datef','',$param,'align="center"',$sortfield,$sortorder); print_liste_field_titre($langs->trans("DateDue"),$_SERVER['PHP_SELF'],"f.date_lim_reglement","&socid=$socid","",'align="center"',$sortfield,$sortorder); print_liste_field_titre($langs->trans('Company'),$_SERVER['PHP_SELF'],'s.nom','',$param,'',$sortfield,$sortorder); print_liste_field_titre($langs->trans('AmountHT'),$_SERVER['PHP_SELF'],'f.total','',$param,'align="right"',$sortfield,$sortorder); print_liste_field_titre($langs->trans('AmountTTC'),$_SERVER['PHP_SELF'],'f.total_ttc','',$param,'align="right"',$sortfield,$sortorder); print_liste_field_titre($langs->trans('Received'),$_SERVER['PHP_SELF'],'am','',$param,'align="right"',$sortfield,$sortorder); print_liste_field_titre($langs->trans('Status'),$_SERVER['PHP_SELF'],'fk_statut,paye,am','',$param,'align="right"',$sortfield,$sortorder); //print ''; print ''; // Lignes des champs de filtre print ''; print ''; print ''; print ''; print ''; print '\n"; if ($num > 0) { $var=True; $total=0; $totalrecu=0; while ($i < min($num,$limit)) { $objp = $db->fetch_object($resql); $var=!$var; $datelimit=$db->jdate($objp->datelimite); print ''; print '\n"; // Date print ''; // Date limit print ''; print ''; print ''; print ''; print ''; // Affiche statut de la facture print '"; //print ""; print "\n"; $total+=$objp->total; $total_ttc+=$objp->total_ttc; $totalrecu+=$paiement; $i++; } if (($offset + $num) <= $limit) { // Print total print ''; print ''; print ''; print ''; print ''; print ''; print ''; } } print "
 
'; print ''; print ''; print ''; //print ' '.$langs->trans('Year').': '; $max_year = date("Y"); $syear = $year; //if ($syear == '') $syear = date("Y"); $html->select_year($syear,'year',1, '', $max_year); print ' '; print ''; print ''; print ''; print ''; print ''; print ''; print ' '; print ''; print "
'; $facturestatic->id=$objp->facid; $facturestatic->ref=$objp->facnumber; $facturestatic->type=$objp->type; $paiement = $facturestatic->getSommePaiement(); print ''; print ''; print ''; print '
'; print $facturestatic->getNomUrl(1); print $objp->increment; print ''; $filename=dol_sanitizeFileName($objp->facnumber); $filedir=$conf->facture->dir_output . '/' . dol_sanitizeFileName($objp->facnumber); $urlsource=$_SERVER['PHP_SELF'].'?facid='.$objp->facid; $formfile->show_documents('facture',$filename,$filedir,$urlsource,'','','',1,'',1); print '
'; print "
'; print dol_print_date($db->jdate($objp->df),'day'); print ''.dol_print_date($datelimit,'day'); if ($datelimit < ($now - $conf->facture->client->warning_delay) && ! $objp->paye && $objp->fk_statut == 1 && ! $paiement) { print img_warning($langs->trans('Late')); } print ''.img_object($langs->trans('ShowCompany'),'company').' '.dol_trunc($objp->nom,48).''.price($objp->total).''.price($objp->total_ttc).''.price($paiement).''; print $facturestatic->LibStatut($objp->paye,$objp->fk_statut,5,$paiement,$objp->type); print " 
'.$langs->trans('Total').''.price($total).''.price($total_ttc).''.price($totalrecu).' 
\n"; print "
\n"; $db->free($resql); } else { dol_print_error($db); } } } $db->close(); llxFooter('$Date$ - $Revision$'); ?>