';
print '';
@@ -529,7 +559,7 @@ if ($id > 0)
}
print '';
-
+ print '
';
$boxstat = '';
@@ -538,7 +568,7 @@ if ($id > 0)
// Lien recap
$boxstat.='
';
- $boxstat.='
';
+ $boxstat.='';
$boxstat.='';
if (! empty($conf->propal->enabled))
@@ -630,8 +660,6 @@ if ($id > 0)
*/
if (! empty($conf->propal->enabled) && $user->rights->propal->lire)
{
- $propal_static = new Propal($db);
-
$sql = "SELECT s.nom, s.rowid, p.rowid as propalid, p.fk_statut, p.total_ht";
$sql.= ", p.tva as total_tva";
$sql.= ", p.total as total_ttc";
@@ -646,12 +674,13 @@ if ($id > 0)
$resql=$db->query($sql);
if ($resql)
{
- $var=true;
- $num = $db->num_rows($resql);
+ $propal_static = new Propal($db);
+ $num = $db->num_rows($resql);
if ($num > 0)
{
- print '';
+ print '';
+ print '
';
print '';
print '";
+ if ($num > 0)
+ {
+ print "
";
+ print '
';
+ }
}
else
{
@@ -697,8 +730,6 @@ if ($id > 0)
*/
if (! empty($conf->commande->enabled) && $user->rights->commande->lire)
{
- $commande_static=new Commande($db);
-
$sql = "SELECT s.nom, s.rowid";
$sql.= ", c.rowid as cid, c.total_ht";
$sql.= ", c.tva as total_tva";
@@ -714,14 +745,14 @@ if ($id > 0)
$resql=$db->query($sql);
if ($resql)
{
- $var=true;
- $num = $db->num_rows($resql);
+ $commande_static=new Commande($db);
+ $num = $db->num_rows($resql);
if ($num > 0)
{
// Check if there are orders billable
$sql2 = 'SELECT s.nom, s.rowid as socid, s.client, c.rowid, c.ref, c.total_ht, c.ref_client,';
- $sql2.= ' c.date_valid, c.date_commande, c.date_livraison, c.fk_statut, c.facture as facturee';
+ $sql2.= ' c.date_valid, c.date_commande, c.date_livraison, c.fk_statut, c.facture as billed';
$sql2.= ' FROM '.MAIN_DB_PREFIX.'societe as s';
$sql2.= ', '.MAIN_DB_PREFIX.'commande as c';
$sql2.= ' WHERE c.fk_soc = s.rowid';
@@ -733,6 +764,7 @@ if ($id > 0)
$orders2invoice = $db->num_rows($resql2);
$db->free($resql2);
+ print '';
print '
';
print '';
@@ -749,14 +781,16 @@ if ($id > 0)
{
$objp = $db->fetch_object($resql);
+ $commande_static->id = $objp->cid;
+ $commande_static->ref = $objp->ref;
+ $commande_static->ref_client=$objp->ref_client;
+ $commande_static->total_ht = $objp->total_ht;
+ $commande_static->total_tva = $objp->total_tva;
+ $commande_static->total_ttc = $objp->total_ttc;
+ $commande_static->billed = $objp->billed;
+
print ' ';
print '';
- $commande_static->id = $objp->cid;
- $commande_static->ref = $objp->ref;
- $commande_static->ref_client=$objp->ref_client;
- $commande_static->total_ht = $objp->total_ht;
- $commande_static->total_tva = $objp->total_tva;
- $commande_static->total_ttc = $objp->total_ttc;
print $commande_static->getNomUrl(1);
print ' '.dol_print_date($db->jdate($objp->dc),'day')." \n";
print ''.price($objp->total_ht).' ';
@@ -765,7 +799,11 @@ if ($id > 0)
}
$db->free($resql);
- if ($num >0) print "
";
+ if ($num >0)
+ {
+ print "
";
+ print '';
+ }
}
else
{
@@ -776,9 +814,8 @@ if ($id > 0)
/*
* Last shipments
*/
- if (! empty($conf->expedition->enabled) && $user->rights->expedition->lire) {
- $sendingstatic = new Expedition($db);
-
+ if (! empty($conf->expedition->enabled) && $user->rights->expedition->lire)
+ {
$sql = 'SELECT e.rowid as id';
$sql.= ', e.ref';
$sql.= ', e.date_creation';
@@ -797,12 +834,14 @@ if ($id > 0)
$sql.= " ORDER BY e.date_creation DESC";
$resql = $db->query($sql);
- if ($resql) {
- $var = true;
- $num = $db->num_rows($resql);
- $i = 0;
+ if ($resql)
+ {
+ $sendingstatic = new Expedition($db);
+
+ $num = $db->num_rows($resql);
if ($num > 0) {
- print '';
+ print '';
+ print '
';
print '';
print ''.$langs->trans("LastSendings",($num<=$MAXLIST?"":$MAXLIST)).' '.$langs->trans("AllSendings").' '.$num.' ';
@@ -811,12 +850,16 @@ if ($id > 0)
print ' ';
}
- while ($i < $num && $i < $MAXLIST) {
+ $i = 0;
+ while ($i < $num && $i < $MAXLIST)
+ {
$objp = $db->fetch_object($resql);
- print '';
- print '';
+
$sendingstatic->id = $objp->id;
$sendingstatic->ref = $objp->ref;
+
+ print ' ';
+ print '';
print $sendingstatic->getNomUrl(1);
print ' ';
if ($objp->date_creation > 0) {
@@ -832,7 +875,10 @@ if ($id > 0)
$db->free($resql);
if ($num > 0)
+ {
print "
";
+ print '';
+ }
} else {
dol_print_error($db);
}
@@ -843,9 +889,7 @@ if ($id > 0)
*/
if (! empty($conf->contrat->enabled) && $user->rights->contrat->lire)
{
- $contratstatic=new Contrat($db);
-
- $sql = "SELECT s.nom, s.rowid, c.rowid as id, c.ref as ref, c.statut, c.datec as dc, c.date_contrat as dcon, c.ref_supplier as refsup";
+ $sql = "SELECT s.nom, s.rowid, c.rowid as id, c.ref as ref, c.statut, c.datec as dc, c.date_contrat as dcon, c.ref_customer as refcus, c.ref_supplier as refsup";
$sql.= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."contrat as c";
$sql.= " WHERE c.fk_soc = s.rowid ";
$sql.= " AND s.rowid = ".$object->id;
@@ -855,11 +899,13 @@ if ($id > 0)
$resql=$db->query($sql);
if ($resql)
{
- $var=true;
+ $contrat=new Contrat($db);
+
$num = $db->num_rows($resql);
- if ($num >0 )
+ if ($num >0)
{
- print '';
+ print '';
+ print '
';
print '';
print ''.$langs->trans("LastContracts",($num<=$MAXLIST?"":$MAXLIST)).' ';
@@ -868,25 +914,27 @@ if ($id > 0)
print '
';
print ' ';
}
+
$i = 0;
while ($i < $num && $i < $MAXLIST)
{
- $contrat=new Contrat($db);
-
$objp = $db->fetch_object($resql);
+ $contrat->id=$objp->id;
+ $contrat->ref=$objp->ref?$objp->ref:$objp->id;
+ $contrat->ref_customer=$objp->refcus;
+ $contrat->ref_supplier=$objp->refsup;
+ $contrat->fetch_lines();
+
print '';
print '';
- $contrat->id=$objp->id;
- $contrat->ref=$objp->ref?$objp->ref:$objp->id;
print $contrat->getNomUrl(1,12);
print " \n";
print ''.dol_trunc($objp->refsup,12)." \n";
print ''.dol_print_date($db->jdate($objp->dc),'day')." \n";
print ''.dol_print_date($db->jdate($objp->dcon),'day')." \n";
print ' ';
- print '';
- $contrat->fetch_lines();
+ print ' ';
print $contrat->getLibStatut(4);
print " \n";
print ' ';
@@ -894,7 +942,11 @@ if ($id > 0)
}
$db->free($resql);
- if ($num > 0) print "
";
+ if ($num > 0)
+ {
+ print "
";
+ print '';
+ }
}
else
{
@@ -914,24 +966,24 @@ if ($id > 0)
$sql.= " AND f.entity = ".$conf->entity;
$sql.= " ORDER BY f.tms DESC";
- $fichinter_static=new Fichinter($db);
-
$resql=$db->query($sql);
if ($resql)
{
- $var=true;
+ $fichinter_static=new Fichinter($db);
+
$num = $db->num_rows($resql);
if ($num > 0)
{
- print '';
+ print '';
+ print '
';
print '';
print ' ';
print ' ';
-
}
+
$i = 0;
while ($i < $num && $i < $MAXLIST)
{
@@ -951,7 +1003,11 @@ if ($id > 0)
}
$db->free($resql);
- if ($num > 0) print "
";
+ if ($num > 0)
+ {
+ print "
";
+ print '';
+ }
}
else
{
@@ -964,14 +1020,12 @@ if ($id > 0)
*/
if (! empty($conf->facture->enabled) && $user->rights->facture->lire)
{
- $invoicetemplate = new FactureRec($db);
-
$sql = 'SELECT f.rowid as id, f.titre as ref, f.amount';
$sql.= ', f.total as total_ht';
$sql.= ', f.tva as total_tva';
$sql.= ', f.total_ttc';
$sql.= ', f.datec as dc';
- $sql.= ', f.date_last_gen';
+ $sql.= ', f.date_last_gen, f.date_when';
$sql.= ', f.frequency';
$sql.= ', f.unit_frequency';
$sql.= ', f.suspended as suspended';
@@ -988,11 +1042,12 @@ if ($id > 0)
$resql=$db->query($sql);
if ($resql)
{
- $var=true;
+ $invoicetemplate = new FactureRec($db);
+
$num = $db->num_rows($resql);
- $i = 0;
if ($num > 0)
{
+ print '';
print '
';
print '';
@@ -1001,12 +1056,11 @@ if ($id > 0)
print ' ';
}
+ $i = 0;
while ($i < $num && $i < $MAXLIST)
{
$objp = $db->fetch_object($resql);
- print '';
- print '';
$invoicetemplate->id = $objp->id;
$invoicetemplate->ref = $objp->ref;
$invoicetemplate->suspended = $objp->suspended;
@@ -1015,6 +1069,11 @@ if ($id > 0)
$invoicetemplate->total_ht = $objp->total_ht;
$invoicetemplate->total_tva = $objp->total_tva;
$invoicetemplate->total_ttc = $objp->total_ttc;
+ $invoicetemplate->date_last_gen = $objp->date_last_gen;
+ $invoicetemplate->date_when = $objp->date_when;
+
+ print ' ';
+ print '';
print $invoicetemplate->getNomUrl(1);
print ' ';
if ($objp->frequency && $objp->date_last_gen > 0)
@@ -1052,7 +1111,11 @@ if ($id > 0)
}
$db->free($resql);
- if ($num > 0) print "
";
+ if ($num > 0)
+ {
+ print "
";
+ print '
';
+ }
}
else
{
@@ -1065,8 +1128,6 @@ if ($id > 0)
*/
if (! empty($conf->facture->enabled) && $user->rights->facture->lire)
{
- $facturestatic = new Facture($db);
-
$sql = 'SELECT f.rowid as facid, f.facnumber, f.type, f.amount';
$sql.= ', f.total as total_ht';
$sql.= ', f.tva as total_tva';
@@ -1086,12 +1147,13 @@ if ($id > 0)
$resql=$db->query($sql);
if ($resql)
{
- $var=true;
+ $facturestatic = new Facture($db);
+
$num = $db->num_rows($resql);
- $i = 0;
if ($num > 0)
{
- print '';
+ print '';
+ print '
';
print '';
print ''.$langs->trans("LastCustomersBills",($num<=$MAXLIST?"":$MAXLIST)).' '.$langs->trans("AllBills").' '.$num.' ';
@@ -1100,18 +1162,20 @@ if ($id > 0)
print ' ';
}
+ $i = 0;
while ($i < $num && $i < $MAXLIST)
{
$objp = $db->fetch_object($resql);
- print '';
- print '';
$facturestatic->id = $objp->facid;
$facturestatic->ref = $objp->facnumber;
$facturestatic->type = $objp->type;
- $facturestatic->total_ht = $objp->total_ht;
- $facturestatic->total_tva = $objp->total_tva;
- $facturestatic->total_ttc = $objp->total_ttc;
+ $facturestatic->total_ht = $objp->total_ht;
+ $facturestatic->total_tva = $objp->total_tva;
+ $facturestatic->total_ttc = $objp->total_ttc;
+
+ print ' ';
+ print '';
print $facturestatic->getNomUrl(1);
print ' ';
if ($objp->df > 0)
@@ -1139,7 +1203,11 @@ if ($id > 0)
}
$db->free($resql);
- if ($num > 0) print "
";
+ if ($num > 0)
+ {
+ print "
";
+ print '
';
+ }
}
else
{
@@ -1272,7 +1340,8 @@ if ($id > 0)
}
else
{
- dol_print_error($db,'Bad value for socid parameter');
+ $langs->load("errors");
+ print $langs->trans('ErrorRecordNotFound');
}
// End of page
diff --git a/htdocs/comm/contact.php b/htdocs/comm/contact.php
index 5c160bfab16..aa8dae43140 100644
--- a/htdocs/comm/contact.php
+++ b/htdocs/comm/contact.php
@@ -26,6 +26,7 @@
require '../main.inc.php';
+// Load translation files required by the page
$langs->load("companies");
$sortfield=GETPOST('sortfield', 'alpha');
@@ -34,7 +35,7 @@ $page=GETPOST('page', 'int');
if (! $sortorder) $sortorder="ASC";
if (! $sortfield) $sortfield="p.name";
if ($page < 0) { $page = 0; }
-$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit;
+$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit;
$offset = $limit * $page ;
$type=GETPOST('type', 'alpha');
@@ -78,7 +79,7 @@ if (! $user->rights->societe->client->voir && ! $socid) $sql .= " ".MAIN_DB_PREF
$sql.= " ".MAIN_DB_PREFIX."socpeople as p";
$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = p.fk_soc";
$sql.= " WHERE s.fk_stcomm = st.id";
-$sql.= " AND p.entity IN (".getEntity('societe').")";
+$sql.= " AND p.entity IN (".getEntity('socpeople').")";
if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
if ($type == "c") $sql.= " AND s.client IN (1, 3)";
if ($type == "p") $sql.= " AND s.client IN (2, 3)";
@@ -144,14 +145,11 @@ if ($resql)
print ' ';
print "\n";
- $var=True;
$i = 0;
while ($i < min($num,$limit))
{
$obj = $db->fetch_object($resql);
-
-
print '';
print ''.img_object($langs->trans("ShowContact"),"contact");
print ' '.$obj->name.' ';
diff --git a/htdocs/comm/index.php b/htdocs/comm/index.php
index 91004c86f67..e90a821b5e3 100644
--- a/htdocs/comm/index.php
+++ b/htdocs/comm/index.php
@@ -37,8 +37,8 @@ if (! empty($conf->fournisseur->enabled)) require_once DOL_DOCUMENT_ROOT.'/fourn
if (! $user->rights->societe->lire) accessforbidden();
-$langs->load("commercial");
-$langs->load("propal");
+// Load translation files required by the page
+$langs->loadLangs(array("commercial", "propal"));
$action=GETPOST('action', 'alpha');
$bid=GETPOST('bid', 'int');
@@ -161,7 +161,6 @@ if (! empty($conf->propal->enabled) && $user->rights->propal->lire)
print ' ';
print ''.$langs->trans("ProposalsDraft").($num?' '.$num.' ':'').' ';
- $var=true;
if ($num > 0)
{
$i = 0;
@@ -228,7 +227,7 @@ if (! empty($conf->supplier_proposal->enabled) && $user->rights->supplier_propos
if (! $user->rights->societe->client->voir && ! $socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
$sql.= " WHERE p.fk_statut = 0";
$sql.= " AND p.fk_soc = s.rowid";
- $sql.= " AND p.entity IN (".getEntity('propal').")";
+ $sql.= " AND p.entity IN (".getEntity('supplier_proposal').")";
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;
@@ -243,7 +242,6 @@ if (! empty($conf->supplier_proposal->enabled) && $user->rights->supplier_propos
print '';
print ''.$langs->trans("SupplierProposalsDraft").($num?' '.$num.' ':'').' ';
- $var=true;
if ($num > 0)
{
$i = 0;
@@ -266,7 +264,7 @@ if (! empty($conf->supplier_proposal->enabled) && $user->rights->supplier_propos
$companystatic->code_client = $obj->code_client;
$companystatic->code_fournisseur = $obj->code_fournisseur;
$companystatic->canvas=$obj->canvas;
- print $companystatic->getNomUrl(1,'customer',16);
+ print $companystatic->getNomUrl(1,'supplier',16);
print '';
print ''.price($obj->total_ht).' ';
$i++;
@@ -274,13 +272,11 @@ if (! empty($conf->supplier_proposal->enabled) && $user->rights->supplier_propos
}
if ($total>0)
{
-
print ''.$langs->trans("Total").' '.price($total)." ";
}
}
else
{
-
print ''.$langs->trans("NoProposal").' ';
}
print "
";
@@ -323,7 +319,6 @@ if (! empty($conf->commande->enabled) && $user->rights->commande->lire)
print '';
print ''.$langs->trans("DraftOrders").($num?' '.$num.' ':'').' ';
- $var = true;
if ($num > 0)
{
$i = 0;
@@ -349,7 +344,12 @@ if (! empty($conf->commande->enabled) && $user->rights->commande->lire)
$companystatic->canvas=$obj->canvas;
print $companystatic->getNomUrl(1,'customer',16);
print '';
- print ''.price($obj->total_ttc).' ';
+ if(! empty($conf->global->MAIN_DASHBOARD_USE_TOTAL_HT)) {
+ print ''.price($obj->total_ht).' ';
+ }
+ else {
+ print ''.price($obj->total_ttc).' ';
+ }
$i++;
$total += $obj->total_ttc;
}
@@ -406,7 +406,6 @@ if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->commande
print '';
print ''.$langs->trans("DraftSuppliersOrders").($num?' '.$num.' ':'').' ';
- $var = true;
if ($num > 0)
{
$i = 0;
@@ -432,7 +431,12 @@ if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->commande
$companystatic->canvas=$obj->canvas;
print $companystatic->getNomUrl(1,'supplier',16);
print '';
- print ''.price($obj->total_ttc).' ';
+ if(! empty($conf->global->MAIN_DASHBOARD_USE_TOTAL_HT)) {
+ print ''.price($obj->total_ht).' ';
+ }
+ else {
+ print ''.price($obj->total_ttc).' ';
+ }
$i++;
$total += $obj->total_ttc;
}
@@ -518,7 +522,6 @@ if (! empty($conf->societe->enabled) && $user->rights->societe->lire)
print '';
$i++;
-
}
$db->free($resql);
@@ -676,8 +679,8 @@ if (! empty($conf->propal->enabled) && $user->rights->propal->lire)
{
$langs->load("propal");
- $sql = "SELECT s.nom as name, s.rowid, p.rowid as propalid, p.total as total_ttc, p.total_ht, p.tva as total_tva, p.ref, p.ref_client, p.fk_statut, p.datep as dp, p.fin_validite as dfv";
- $sql.= ", s.code_client";
+ $sql = "SELECT s.nom as name, s.rowid, s.code_client";
+ $sql.= ", p.rowid as propalid, p.entity, p.total as total_ttc, p.total_ht, p.tva as total_tva, p.ref, p.ref_client, p.fk_statut, p.datep as dp, p.fin_validite as dfv";
$sql.= " FROM ".MAIN_DB_PREFIX."societe as s";
$sql.= ", ".MAIN_DB_PREFIX."propal as p";
if (! $user->rights->societe->client->voir && ! $socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
@@ -726,7 +729,7 @@ if (! empty($conf->propal->enabled) && $user->rights->propal->lire)
print '';
print '';
$filename=dol_sanitizeFileName($obj->ref);
- $filedir=$conf->propal->dir_output . '/' . dol_sanitizeFileName($obj->ref);
+ $filedir=$conf->propal->multidir_output[$obj->entity] . '/' . dol_sanitizeFileName($obj->ref);
$urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->propalid;
print $formfile->getDocumentsLink($propalstatic->element, $filename, $filedir);
print '
';
@@ -744,7 +747,12 @@ if (! empty($conf->propal->enabled) && $user->rights->propal->lire)
print ' ';
print '';
print dol_print_date($db->jdate($obj->dp),'day').' '."\n";
- print ''.price($obj->total_ttc).' ';
+ if(! empty($conf->global->MAIN_DASHBOARD_USE_TOTAL_HT)) {
+ print ''.price($obj->total_ht).' ';
+ }
+ else {
+ print ''.price($obj->total_ttc).' ';
+ }
print ''.$propalstatic->LibStatut($obj->fk_statut,3).' '."\n";
print ' '."\n";
$i++;
@@ -843,7 +851,12 @@ if (! empty($conf->commande->enabled) && $user->rights->commande->lire)
print '';
print '';
print dol_print_date($db->jdate($obj->dp),'day').' '."\n";
- print ''.price($obj->total_ttc).' ';
+ if(! empty($conf->global->MAIN_DASHBOARD_USE_TOTAL_HT)) {
+ print ''.price($obj->total_ht).' ';
+ }
+ else {
+ print ''.price($obj->total_ttc).' ';
+ }
print ''.$orderstatic->LibStatut($obj->fk_statut,$obj->billed,3).' '."\n";
print ''."\n";
$i++;
diff --git a/htdocs/comm/mailing/advtargetemailing.php b/htdocs/comm/mailing/advtargetemailing.php
index cfafdaa725b..1c886e2ba2c 100644
--- a/htdocs/comm/mailing/advtargetemailing.php
+++ b/htdocs/comm/mailing/advtargetemailing.php
@@ -34,9 +34,8 @@ require_once DOL_DOCUMENT_ROOT . '/core/modules/mailings/advthirdparties.modules
require_once DOL_DOCUMENT_ROOT . '/core/class/html.formcompany.class.php';
require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php';
-// Translations
-$langs->load("mails");
-$langs->load("companies");
+// Load translation files required by the page
+$langs->loadLangs(array('mails', 'companies'));
if (! empty($conf->categorie->enabled)) {
$langs->load("categories");
}
@@ -73,13 +72,13 @@ if (GETPOST('button_removefilter_x','alpha')) {
$search_prenom = '';
$search_email = '';
}
-
$array_query = array ();
-
$object = new Mailing($db);
$advTarget = new AdvanceTargetingMailing($db);
+
if (empty($template_id)) {
- $advTarget->fk_mailing = $id;
+ $advTarget->fk_element = $id;
+ $advTarget->type_element = 'mailing';
$result = $advTarget->fetch_by_mailing();
} else {
$result = $advTarget->fetch($template_id);
@@ -223,7 +222,7 @@ if ($action == 'add') {
} else {
$advTarget->contact_lines = array ();
}
-
+
if ((count($advTarget->thirdparty_lines) > 0) || (count($advTarget->contact_lines) > 0)) {
// Add targets into database
$obj = new mailing_advthirdparties($db);
@@ -237,6 +236,7 @@ if ($action == 'add') {
if (! empty($template_id)) {
$query_temlate_id = '&template_id=' . $template_id;
}
+ setEventMessages($langs->trans("XTargetsAdded",$result), null, 'mesgs');
header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id . $query_temlate_id);
exit();
}
@@ -356,6 +356,7 @@ if ($action == 'savefilter' || $action == 'createfilter') {
setEventMessage($advTarget->error, 'errors');
}
} elseif ($action == 'savefilter') {
+
$result = $advTarget->update($user);
if ($result < 0) {
setEventMessage($advTarget->error, 'errors');
@@ -409,36 +410,7 @@ if ($_POST["button_removefilter"]) {
llxHeader('', $langs->trans("MailAdvTargetRecipients"));
-print '';
$form = new Form($db);
$formadvtargetemaling = new FormAdvTargetEmailing($db);
@@ -490,489 +462,11 @@ if ($object->fetch($id) >= 0) {
// Show email selectors
if ($object->statut == 0 && $user->rights->mailing->creer) {
- print_fiche_titre($langs->trans("AdvTgtTitle"));
-
- print '' . "\n";
- print '
' . "\n";
- print '
' . "\n";
-
- print '';
- print ' ';
+
+ include DOL_DOCUMENT_ROOT . '/core/tpl/advtarget.tpl.php';
+
}
}
llxFooter();
-$db->close();
\ No newline at end of file
+$db->close();
diff --git a/htdocs/comm/mailing/card.php b/htdocs/comm/mailing/card.php
index db19e943b4b..97746ad9d82 100644
--- a/htdocs/comm/mailing/card.php
+++ b/htdocs/comm/mailing/card.php
@@ -35,6 +35,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
+// Load translation files required by the page
$langs->load("mails");
if (! $user->rights->mailing->lire || (empty($conf->global->EXTERNAL_USERS_ARE_AUTHORIZED) && $user->societe_id > 0)) accessforbidden();
@@ -244,7 +245,7 @@ if (empty($reshook))
$substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN . 'contractline' . $obj->source_id, 2);
}
}
- /* For backward compatibility */
+ /* For backward compatibility, deprecated */
if (! empty($conf->paypal->enabled) && ! empty($conf->global->PAYPAL_SECURITY_TOKEN))
{
$substitutionarray['__SECUREKEYPAYPAL__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2);
@@ -754,7 +755,7 @@ if ($action == 'create')
$parameters=array();
$reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;
- if (empty($reshook) && ! empty($extrafields->attribute_label))
+ if (empty($reshook))
{
print $object->showOptionals($extrafields,'edit');
}
@@ -967,7 +968,7 @@ else
* Boutons d'action
*/
- if (GETPOST('cancel','alpha') || $confirm=='no' || $action == '' || in_array($action,array('settodraft', 'valid','delete','sendall','clone')))
+ if (GETPOST('cancel','alpha') || $confirm=='no' || $action == '' || in_array($action,array('settodraft','valid','delete','sendall','clone','test')))
{
print "\n\n\n";
@@ -1071,7 +1072,9 @@ else
print '
';
print load_fiche_titre($langs->trans("TestMailing"));
- // Create l'objet formulaire mail
+ dol_fiche_head(null, '', '', -1);
+
+ // Create l'objet formulaire mail
include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
$formmail = new FormMail($db);
$formmail->fromname = $object->email_from;
@@ -1099,6 +1102,10 @@ else
print $formmail->get_form();
print '
';
+
+ dol_fiche_end();
+
+ print dol_set_focus('#sendto');
}
@@ -1114,7 +1121,7 @@ else
dol_fiche_head('', '', '', -1);
- print '
';
+ print '';
// Subject
print ''.$langs->trans("MailTopic").' '.$object->sujet.' ';
@@ -1229,7 +1236,7 @@ else
$parameters=array();
$reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;
- if (empty($reshook) && ! empty($extrafields->attribute_label))
+ if (empty($reshook))
{
print $object->showOptionals($extrafields,'edit');
}
@@ -1260,7 +1267,7 @@ else
dol_fiche_head(null, '', '', -1);
- print '';
+ print '';
// Subject
print ''.$langs->trans("MailTopic").' ';
diff --git a/htdocs/comm/mailing/cibles.php b/htdocs/comm/mailing/cibles.php
index 57af9f5c601..08ed54d2fc3 100644
--- a/htdocs/comm/mailing/cibles.php
+++ b/htdocs/comm/mailing/cibles.php
@@ -32,6 +32,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/emailing.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
+// Load translation files required by the page
$langs->load("mails");
// Security check
@@ -75,8 +76,6 @@ if ($action == 'add')
$module=GETPOST("module");
$result=-1;
- $var=true;
-
foreach ($modulesdir as $dir)
{
// Load modules attributes in arrays (name, numero, orders) from dir directory
@@ -260,7 +259,7 @@ if ($object->fetch($id) >= 0)
print load_fiche_titre($langs->trans("ToAddRecipientsChooseHere"), ($user->admin?info_admin($langs->trans("YouCanAddYourOwnPredefindedListHere"),1):''), 'title_generic');
//print '';
- print '';
+ print '
';
//print '
';
print '';
@@ -277,8 +276,6 @@ if ($object->fetch($id) >= 0)
clearstatcache();
- $var = true;
-
foreach ($modulesdir as $dir)
{
$modulenames=array();
@@ -306,6 +303,8 @@ if ($object->fetch($id) >= 0)
// Sort $modulenames
sort($modulenames);
+ $var = true;
+
// Loop on each submodule
foreach($modulenames as $modulename)
{
@@ -331,7 +330,7 @@ if ($object->fetch($id) >= 0)
// Si le module mailing est qualifie
if ($qualified)
{
- $var = !$var;
+ $var = ! $var;
if ($allowaddtarget)
{
@@ -425,7 +424,13 @@ if ($object->fetch($id) >= 0)
{
$result = $db->query($sql);
$nbtotalofrecords = $db->num_rows($result);
+ if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0
+ {
+ $page = 0;
+ $offset = 0;
+ }
}
+
//$nbtotalofrecords=$object->nbemail; // nbemail is a denormalized field storing nb of targets
$sql .= $db->plimit($limit+1, $offset);
@@ -555,7 +560,7 @@ if ($object->fetch($id) >= 0)
include_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
$objectstatic=new Adherent($db);
$objectstatic->fetch($obj->source_id);
- print $objectstatic->getNomUrl(2);
+ print $objectstatic->getNomUrl(1);
}
else if ($obj->source_type == 'user')
{
@@ -563,14 +568,21 @@ if ($object->fetch($id) >= 0)
$objectstatic=new User($db);
$objectstatic->fetch($obj->source_id);
$objectstatic->id=$obj->source_id;
- print $objectstatic->getNomUrl(2);
+ print $objectstatic->getNomUrl(1);
}
else if ($obj->source_type == 'thirdparty')
{
include_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
$objectstatic=new Societe($db);
$objectstatic->fetch($obj->source_id);
- print $objectstatic->getNomUrl(2);
+ print $objectstatic->getNomUrl(1);
+ }
+ else if ($obj->source_type == 'contact')
+ {
+ include_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
+ $objectstatic=new Contact($db);
+ $objectstatic->fetch($obj->source_id);
+ print $objectstatic->getNomUrl(1);
}
else
{
diff --git a/htdocs/comm/mailing/class/advtargetemailing.class.php b/htdocs/comm/mailing/class/advtargetemailing.class.php
index 70efeccead3..50d9faf0637 100644
--- a/htdocs/comm/mailing/class/advtargetemailing.class.php
+++ b/htdocs/comm/mailing/class/advtargetemailing.class.php
@@ -39,7 +39,8 @@ class AdvanceTargetingMailing extends CommonObject
var $name;
var $entity;
- var $fk_mailing;
+ var $fk_element;
+ var $type_element;
var $filtervalue;
var $fk_user_author;
var $datec='';
@@ -92,7 +93,9 @@ class AdvanceTargetingMailing extends CommonObject
$error=0;
// Clean parameters
- if (isset($this->fk_mailing)) $this->fk_mailing=trim($this->fk_mailing);
+ if (isset($this->fk_element)) $this->fk_element=trim($this->fk_element);
+ if (isset($this->type_element)) $this->type_element=trim($this->type_element);
+
if (isset($this->name)) $this->name=trim($this->name);
if (isset($this->filtervalue)) $this->filtervalue=trim($this->filtervalue);
if (isset($this->fk_user_author)) $this->fk_user_author=trim($this->fk_user_author);
@@ -108,7 +111,8 @@ class AdvanceTargetingMailing extends CommonObject
$sql.= "name,";
$sql.= "entity,";
- $sql.= "fk_mailing,";
+ $sql.= "fk_element,";
+ $sql.= "type_element,";
$sql.= "filtervalue,";
$sql.= "fk_user_author,";
$sql.= "datec,";
@@ -119,7 +123,8 @@ class AdvanceTargetingMailing extends CommonObject
$sql.= " ".(! isset($this->name)?'NULL':"'".$this->db->escape($this->name)."'").",";
$sql.= " ".$conf->entity.",";
- $sql.= " ".(! isset($this->fk_mailing)?'NULL':"'".$this->db->escape($this->fk_mailing)."'").",";
+ $sql.= " ".(! isset($this->fk_element)?'NULL':"'".$this->db->escape($this->fk_element)."'").",";
+ $sql.= " ".(! isset($this->type_element)?'NULL':"'".$this->db->escape($this->type_element)."'").",";
$sql.= " ".(! isset($this->filtervalue)?'NULL':"'".$this->db->escape($this->filtervalue)."'").",";
$sql.= " ".$user->id.",";
$sql.= " '".$this->db->idate(dol_now())."',";
@@ -184,7 +189,8 @@ class AdvanceTargetingMailing extends CommonObject
$sql.= " t.name,";
$sql.= " t.entity,";
- $sql.= " t.fk_mailing,";
+ $sql.= " t.fk_element,";
+ $sql.= " t.type_element,";
$sql.= " t.filtervalue,";
$sql.= " t.fk_user_author,";
$sql.= " t.datec,";
@@ -206,7 +212,8 @@ class AdvanceTargetingMailing extends CommonObject
$this->name = $obj->name;
$this->entity = $obj->entity;
- $this->fk_mailing = $obj->fk_mailing;
+ $this->fk_element = $obj->fk_element;
+ $this->type_element = $obj->type_element;
$this->filtervalue = $obj->filtervalue;
$this->fk_user_author = $obj->fk_user_author;
$this->datec = $this->db->jdate($obj->datec);
@@ -240,7 +247,8 @@ class AdvanceTargetingMailing extends CommonObject
$sql.= " t.name,";
$sql.= " t.entity,";
- $sql.= " t.fk_mailing,";
+ $sql.= " t.fk_element,";
+ $sql.= " t.type_element,";
$sql.= " t.filtervalue,";
$sql.= " t.fk_user_author,";
$sql.= " t.datec,";
@@ -249,9 +257,9 @@ class AdvanceTargetingMailing extends CommonObject
$sql.= " FROM ".MAIN_DB_PREFIX."advtargetemailing as t";
if (!empty($id)) {
- $sql.= " WHERE t.fk_mailing = ".$id;
+ $sql.= " WHERE t.fk_element = ".$id." AND type_element='mailing'";
}else {
- $sql.= " WHERE t.fk_mailing = ".$this->fk_mailing;
+ $sql.= " WHERE t.fk_element = ".$this->fk_element." AND type_element='mailing'";
}
dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG);
@@ -266,7 +274,74 @@ class AdvanceTargetingMailing extends CommonObject
$this->name = $obj->name;
$this->entity = $obj->entity;
- $this->fk_mailing = $obj->fk_mailing;
+ $this->fk_element = $obj->fk_element;
+ $this->type_element = $obj->type_element;
+ $this->filtervalue = $obj->filtervalue;
+ $this->fk_user_author = $obj->fk_user_author;
+ $this->datec = $this->db->jdate($obj->datec);
+ $this->fk_user_mod = $obj->fk_user_mod;
+ $this->tms = $this->db->jdate($obj->tms);
+
+ }
+ $this->db->free($resql);
+
+ return 1;
+ }
+ else
+ {
+ $this->error="Error ".$this->db->lasterror();
+ dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
+ return -1;
+ }
+ }
+
+
+
+
+ /**
+ * Load object in memory from the database
+ *
+ * @param int $id Id object
+ * @param string $type_element Type target
+ * @return int <0 if KO, >0 if OK
+ */
+ function fetch_by_element($id=0, $type_element='mailing')
+ {
+ global $langs;
+ $sql = "SELECT";
+ $sql.= " t.rowid,";
+
+ $sql.= " t.name,";
+ $sql.= " t.entity,";
+ $sql.= " t.fk_element,";
+ $sql.= " t.type_element,";
+ $sql.= " t.filtervalue,";
+ $sql.= " t.fk_user_author,";
+ $sql.= " t.datec,";
+ $sql.= " t.fk_user_mod,";
+ $sql.= " t.tms";
+
+ $sql.= " FROM ".MAIN_DB_PREFIX."advtargetemailing as t";
+ if (!empty($id)) {
+ $sql.= " WHERE t.fk_element = ".$id." AND type_element='$type_element'";
+ }else {
+ $sql.= " WHERE t.fk_element = ".$this->fk_element." AND type_element='$type_element'";
+ }
+
+ dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG);
+ $resql=$this->db->query($sql);
+ if ($resql)
+ {
+ if ($this->db->num_rows($resql))
+ {
+ $obj = $this->db->fetch_object($resql);
+
+ $this->id = $obj->rowid;
+
+ $this->name = $obj->name;
+ $this->entity = $obj->entity;
+ $this->fk_element = $obj->fk_element;
+ $this->type_element = $obj->type_element;
$this->filtervalue = $obj->filtervalue;
$this->fk_user_author = $obj->fk_user_author;
$this->datec = $this->db->jdate($obj->datec);
@@ -299,7 +374,8 @@ class AdvanceTargetingMailing extends CommonObject
$error=0;
// Clean parameters
- if (isset($this->fk_mailing)) $this->fk_mailing=trim($this->fk_mailing);
+ if (isset($this->fk_element)) $this->fk_element=trim($this->fk_element);
+ if (isset($this->type_element)) $this->type_element=trim($this->type_element);
if (isset($this->name)) $this->name=trim($this->name);
if (isset($this->filtervalue)) $this->filtervalue=trim($this->filtervalue);
if (isset($this->fk_user_author)) $this->fk_user_author=trim($this->fk_user_author);
@@ -315,14 +391,14 @@ class AdvanceTargetingMailing extends CommonObject
$sql.= " name=".(isset($this->name)?"'".$this->db->escape($this->name)."'":"''").",";
$sql.= " entity=".$conf->entity.",";
- $sql.= " fk_mailing=".(isset($this->fk_mailing)?$this->fk_mailing:"null").",";
+ $sql.= " fk_element=".(isset($this->fk_element)?$this->fk_element:"null").",";
+ $sql.= " type_element=".(isset($this->type_element)?"'".$this->db->escape($this->type_element)."'":"null").",";
$sql.= " filtervalue=".(isset($this->filtervalue)?"'".$this->db->escape($this->filtervalue)."'":"null").",";
$sql.= " fk_user_mod=".$user->id;
$sql.= " WHERE rowid=".$this->id;
$this->db->begin();
-
dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG);
$resql = $this->db->query($sql);
if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
@@ -432,7 +508,7 @@ class AdvanceTargetingMailing extends CommonObject
global $langs,$conf;
if (!empty($arrayquery)) {
- $result=$this->fetch_by_mailing($this->fk_mailing);
+ $result=$this->fetch_by_mailing($this->fk_element);
$this->filtervalue=json_encode($arrayquery);
if ($result<0) {
return -1;
diff --git a/htdocs/comm/mailing/class/html.formadvtargetemailing.class.php b/htdocs/comm/mailing/class/html.formadvtargetemailing.class.php
index c7f425f8f7a..7408bb27d37 100644
--- a/htdocs/comm/mailing/class/html.formadvtargetemailing.class.php
+++ b/htdocs/comm/mailing/class/html.formadvtargetemailing.class.php
@@ -409,21 +409,22 @@ class FormAdvTargetEmailing extends Form
}
/**
- * selectAdvtargetemailingTemplate
+ * Return a combo list to select emailing target selector
*
- * @param string $htmlname control name
- * @param integer $selected defaut selected
- * @param integer $showempty empty lines
- *
- * @return string HTML combo
+ * @param string $htmlname control name
+ * @param integer $selected defaut selected
+ * @param integer $showempty empty lines
+ * @param string $type_element Type element. Example: 'mailing'
+ * @return string HTML combo
*/
- public function selectAdvtargetemailingTemplate($htmlname='template_id',$selected=0,$showempty=0) {
+ public function selectAdvtargetemailingTemplate($htmlname='template_id', $selected=0, $showempty=0, $type_element='mailing') {
global $conf, $user, $langs;
$out = '';
- $sql = "SELECT c.rowid, c.name, c.fk_mailing";
+ $sql = "SELECT c.rowid, c.name, c.fk_element";
$sql .= " FROM " . MAIN_DB_PREFIX . "advtargetemailing as c";
+ $sql .= " WHERE type_element='$type_element'";
$sql .= " ORDER BY c.name";
dol_syslog ( get_class ( $this ) . "::".__METHOD__, LOG_DEBUG );
@@ -441,7 +442,7 @@ class FormAdvTargetEmailing extends Form
$obj = $this->db->fetch_object ( $resql );
$label = $obj->name;
if (empty($label)) {
- $label=$obj->fk_mailing;
+ $label=$obj->fk_element;
}
if ($selected > 0 && $selected == $obj->rowid) {
diff --git a/htdocs/comm/mailing/index.php b/htdocs/comm/mailing/index.php
index 52eacf6c115..17693a1a73c 100644
--- a/htdocs/comm/mailing/index.php
+++ b/htdocs/comm/mailing/index.php
@@ -27,8 +27,8 @@ require '../../main.inc.php';
require_once DOL_DOCUMENT_ROOT .'/comm/mailing/class/mailing.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
-$langs->load("commercial");
-$langs->load("orders");
+// Load translation files required by the page
+$langs->loadLangs(array('commercial', 'orders'));
// Security check
@@ -52,7 +52,6 @@ print '
';
//if (! empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is useless due to the global search combo
//{
// Recherche emails
- $var=false;
print '
\n";
//}
@@ -74,7 +73,6 @@ print '
'.$langs->trans("TargetsStatistic
$dir=DOL_DOCUMENT_ROOT."/core/modules/mailings";
$handle=opendir($dir);
-$var=True;
if (is_resource($handle))
{
while (($file = readdir($handle))!==false)
@@ -106,8 +104,6 @@ if (is_resource($handle))
// Si le module mailing est qualifi�
if ($qualified)
{
- $var = !$var;
-
foreach ($mailmodule->getSqlArrayForStats() as $sql)
{
print ' ';
@@ -169,14 +165,12 @@ if ($result)
$num = $db->num_rows($result);
if ($num > 0)
- {
- $var = true;
+ {
$i = 0;
- while ($i < $num )
+ while ($i < $num )
{
$obj = $db->fetch_object($result);
-
print ' ';
print ''.img_object($langs->trans("ShowEMail"),"email").' '.$obj->rowid.' ';
diff --git a/htdocs/comm/mailing/info.php b/htdocs/comm/mailing/info.php
index ddb0d4a8fc6..b4f2eaeb6f3 100644
--- a/htdocs/comm/mailing/info.php
+++ b/htdocs/comm/mailing/info.php
@@ -29,6 +29,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/emailing.lib.php';
$id=GETPOST('id');
+// Load translation files required by the page
$langs->load("mails");
// Security check
diff --git a/htdocs/comm/mailing/list.php b/htdocs/comm/mailing/list.php
index f2491b09336..87a390d4006 100644
--- a/htdocs/comm/mailing/list.php
+++ b/htdocs/comm/mailing/list.php
@@ -25,6 +25,7 @@
require '../../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/comm/mailing/class/mailing.class.php';
+// Load translation files required by the page
$langs->load("mails");
// Security check
@@ -32,7 +33,7 @@ $result=restrictedArea($user,'mailing');
$sortfield = GETPOST("sortfield",'alpha');
$sortorder = GETPOST("sortorder",'alpha');
-$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit;
+$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit;
$page = GETPOST("page",'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1
$offset = $limit * $page;
@@ -103,12 +104,19 @@ if ($result)
$title=$langs->trans("ListOfEMailings");
if ($filteremail) $title.=' ('.$langs->trans("SentTo",$filteremail).')';
- print_barre_liste($title, $page, $_SERVER["PHP_SELF"],"",$sortfield,$sortorder,"",$num);
+
+ $newcardbutton='';
+ if ($user->rights->mailing->creer)
+ {
+ $newcardbutton=''.$langs->trans('NewMailing').' ';
+ $newcardbutton.= ' ';
+ $newcardbutton.= ' ';
+ }
$i = 0;
- $param = "&sall=".urlencode($sall);
- if ($filteremail) $param.='&filteremail='.urlencode($filteremail);
+ $param = "&sall=".urlencode($sall);
+ if ($filteremail) $param.='&filteremail='.urlencode($filteremail);
print ' ';
}
+ $tmparray=$object->getTotalWeightVolume();
+ $totalWeight=$tmparray['weight'];
+ $totalVolume=$tmparray['volume'];
+ if ($totalWeight) {
+ print '
' . $langs->trans("CalculatedWeight") . ' ';
+ print '';
+ print showDimensionInBestUnit($totalWeight, 0, "weight", $langs, isset($conf->global->MAIN_WEIGHT_DEFAULT_ROUND)?$conf->global->MAIN_WEIGHT_DEFAULT_ROUND:-1, isset($conf->global->MAIN_WEIGHT_DEFAULT_UNIT)?$conf->global->MAIN_WEIGHT_DEFAULT_UNIT:'no');
+ print ' ';
+ }
+ if ($totalVolume) {
+ print '
' . $langs->trans("CalculatedVolume") . ' ';
+ print '';
+ print showDimensionInBestUnit($totalVolume, 0, "volume", $langs, isset($conf->global->MAIN_VOLUME_DEFAULT_ROUND)?$conf->global->MAIN_VOLUME_DEFAULT_ROUND:-1, isset($conf->global->MAIN_VOLUME_DEFAULT_UNIT)?$conf->global->MAIN_VOLUME_DEFAULT_UNIT:'no');
+ print ' ';
+ }
+
// Incoterms
if (!empty($conf->incoterm->enabled))
{
@@ -2135,7 +2171,7 @@ if ($action == 'create')
print '
';
print $langs->trans('IncotermLabel');
print ' ';
- if ($user->rights->propal->creer) print ''.img_edit().' ';
+ if ($usercancreate) print ''.img_edit().' ';
else print ' ';
print '
';
print '';
@@ -2264,7 +2300,7 @@ if ($action == 'create')
$ret = $object->printObjectLines($action, $mysoc, $soc, $lineid, 1);
// Form to add new line
- if ($object->statut == Propal::STATUS_DRAFT && $user->rights->propal->creer)
+ if ($object->statut == Propal::STATUS_DRAFT && $usercancreate && $action != 'selectlines')
{
if ($action != 'editline')
{
@@ -2299,8 +2335,7 @@ if ($action == 'create')
// Validate
if ($object->statut == Propal::STATUS_DRAFT && $object->total_ttc >= 0 && count($object->lines) > 0)
{
- if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->creer))
- || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->propal_advance->validate)))
+ if ($usercanvalidate)
{
print '
';
}
@@ -2313,34 +2348,34 @@ if ($action == 'create')
print '
';
}*/
// Edit
- if ($object->statut == Propal::STATUS_VALIDATED && $user->rights->propal->creer) {
+ if ($object->statut == Propal::STATUS_VALIDATED && $usercancreate) {
print '
';
}
// ReOpen
- if (($object->statut == Propal::STATUS_SIGNED || $object->statut == Propal::STATUS_NOTSIGNED || $object->statut == Propal::STATUS_BILLED) && $user->rights->propal->cloturer) {
+ if (($object->statut == Propal::STATUS_SIGNED || $object->statut == Propal::STATUS_NOTSIGNED || $object->statut == Propal::STATUS_BILLED) && $usercanclose) {
print '
';
}
// Send
if ($object->statut == Propal::STATUS_VALIDATED || $object->statut == Propal::STATUS_SIGNED) {
- if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->propal->propal_advance->send) {
- print '
';
+ if ($usercansend) {
+ print '
';
} else
- print '
';
+ print '
';
}
// Create an order
if (! empty($conf->commande->enabled) && $object->statut == Propal::STATUS_SIGNED) {
- if ($user->rights->commande->creer) {
+ if ($usercancreateorder) {
print '
';
}
}
// Create an intervention
if (! empty($conf->service->enabled) && ! empty($conf->ficheinter->enabled) && $object->statut == Propal::STATUS_SIGNED) {
- if ($user->rights->ficheinter->creer) {
+ if ($usercancreateintervention) {
$langs->load("interventions");
print '
';
}
@@ -2350,7 +2385,7 @@ if ($action == 'create')
if ($conf->contrat->enabled && $object->statut == Propal::STATUS_SIGNED) {
$langs->load("contracts");
- if ($user->rights->contrat->creer) {
+ if ($usercancreatecontract) {
print '
';
}
}
@@ -2358,7 +2393,7 @@ if ($action == 'create')
// Create an invoice and classify billed
if ($object->statut == Propal::STATUS_SIGNED)
{
- if (! empty($conf->facture->enabled) && $user->rights->facture->creer)
+ if (! empty($conf->facture->enabled) && $usercancreateinvoice)
{
print '
';
}
@@ -2371,18 +2406,18 @@ if ($action == 'create')
}
// Set accepted/refused
- if ($object->statut == Propal::STATUS_VALIDATED && $user->rights->propal->cloturer) {
+ if ($object->statut == Propal::STATUS_VALIDATED && $usercanclose) {
print '
';
}
// Clone
- if ($user->rights->propal->creer) {
+ if ($usercancreate) {
print '
';
}
// Delete
- if ($user->rights->propal->supprimer) {
+ if ($usercandelete) {
print '
';
}
@@ -2403,10 +2438,10 @@ if ($action == 'create')
* Documents generes
*/
$filename = dol_sanitizeFileName($object->ref);
- $filedir = $conf->propal->dir_output . "/" . dol_sanitizeFileName($object->ref);
+ $filedir = $conf->propal->multidir_output[$object->entity] . "/" . dol_sanitizeFileName($object->ref);
$urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id;
- $genallowed = $user->rights->propal->lire;
- $delallowed = $user->rights->propal->creer;
+ $genallowed = $usercanread;
+ $delallowed = $usercancreate;
print $formfile->showdocuments('propal', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', 0, '', $soc->default_lang, '', $object);
@@ -2444,7 +2479,7 @@ if ($action == 'create')
// Presend form
$modelmail='propal_send';
$defaulttopic='SendPropalRef';
- $diroutput = $conf->propal->dir_output;
+ $diroutput = $conf->propal->multidir_output[$object->entity];
$trackid = 'pro'.$object->id;
include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php';
diff --git a/htdocs/comm/propal/class/api_proposals.class.php b/htdocs/comm/propal/class/api_proposals.class.php
index 63b26373f60..39857d88365 100644
--- a/htdocs/comm/propal/class/api_proposals.class.php
+++ b/htdocs/comm/propal/class/api_proposals.class.php
@@ -77,6 +77,9 @@ class Proposals extends DolibarrApi
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
+ // Add external contacts ids
+ $this->propal->contacts_ids = $this->propal->liste_contact(-1,'external',1);
+
$this->propal->fetchObjectLinked();
return $this->_cleanObjectDatas($this->propal);
}
@@ -156,6 +159,8 @@ class Proposals extends DolibarrApi
$obj = $db->fetch_object($result);
$proposal_static = new Propal($db);
if($proposal_static->fetch($obj->rowid)) {
+ // Add external contacts ids
+ $proposal_static->contacts_ids = $proposal_static->liste_contact(-1,'external',1);
$obj_ret[] = $this->_cleanObjectDatas($proposal_static);
}
$i++;
@@ -176,7 +181,7 @@ class Proposals extends DolibarrApi
* @param array $request_data Request data
* @return int ID of proposal
*/
- function post($request_data = NULL)
+ function post($request_data = null)
{
if(! DolibarrApiAccess::$user->rights->propal->creer) {
throw new RestException(401, "Insuffisant rights");
@@ -241,7 +246,7 @@ class Proposals extends DolibarrApi
*
* @return int
*/
- function postLine($id, $request_data = NULL)
+ function postLine($id, $request_data = null)
{
if(! DolibarrApiAccess::$user->rights->propal->creer) {
throw new RestException(401);
@@ -307,7 +312,7 @@ class Proposals extends DolibarrApi
*
* @return object
*/
- function putLine($id, $lineid, $request_data = NULL)
+ function putLine($id, $lineid, $request_data = null)
{
if(! DolibarrApiAccess::$user->rights->propal->creer) {
throw new RestException(401);
@@ -410,7 +415,7 @@ class Proposals extends DolibarrApi
*
* @return int
*/
- function put($id, $request_data = NULL) {
+ function put($id, $request_data = null) {
if(! DolibarrApiAccess::$user->rights->propal->creer) {
throw new RestException(401);
}
@@ -708,7 +713,7 @@ class Proposals extends DolibarrApi
$object = parent::_cleanObjectDatas($object);
- unset($object->note);
+ unset($object->note);
unset($object->name);
unset($object->lastname);
unset($object->firstname);
diff --git a/htdocs/comm/propal/class/propal.class.php b/htdocs/comm/propal/class/propal.class.php
index a9782d21dac..cf7610a218e 100644
--- a/htdocs/comm/propal/class/propal.class.php
+++ b/htdocs/comm/propal/class/propal.class.php
@@ -12,6 +12,7 @@
* Copyright (C) 2012 Cedric Salvador
* Copyright (C) 2013 Florian Henry
* Copyright (C) 2014-2015 Marcos García
+ * Copyright (C) 2018 Nicolas ZABOURI
*
* 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
@@ -142,9 +143,9 @@ class Propal extends CommonObject
public $cond_reglement_code;
public $mode_reglement_code;
- public $remise;
- public $remise_percent;
- public $remise_absolue;
+ public $remise = 0;
+ public $remise_percent = 0;
+ public $remise_absolue = 0;
public $fk_address;
public $address_type;
public $address;
@@ -198,6 +199,7 @@ class Propal extends CommonObject
*/
const STATUS_BILLED = 4; // Todo rename into STATUS_CLOSE ?
+
/**
* Constructor
*
@@ -210,26 +212,13 @@ class Propal extends CommonObject
global $conf,$langs;
$this->db = $db;
+
$this->socid = $socid;
$this->id = $propalid;
+
$this->products = array();
- $this->remise = 0;
- $this->remise_percent = 0;
- $this->remise_absolue = 0;
$this->duree_validite=$conf->global->PROPALE_VALIDITY_DURATION;
-
- $langs->load("propal");
- $this->labelstatut[0]=(! empty($conf->global->PROPAL_STATUS_DRAFT_LABEL) ? $conf->global->PROPAL_STATUS_DRAFT_LABEL : $langs->trans("PropalStatusDraft"));
- $this->labelstatut[1]=(! empty($conf->global->PROPAL_STATUS_VALIDATED_LABEL) ? $conf->global->PROPAL_STATUS_VALIDATED_LABEL : $langs->trans("PropalStatusValidated"));
- $this->labelstatut[2]=(! empty($conf->global->PROPAL_STATUS_SIGNED_LABEL) ? $conf->global->PROPAL_STATUS_SIGNED_LABEL : $langs->trans("PropalStatusSigned"));
- $this->labelstatut[3]=(! empty($conf->global->PROPAL_STATUS_NOTSIGNED_LABEL) ? $conf->global->PROPAL_STATUS_NOTSIGNED_LABEL : $langs->trans("PropalStatusNotSigned"));
- $this->labelstatut[4]=(! empty($conf->global->PROPAL_STATUS_BILLED_LABEL) ? $conf->global->PROPAL_STATUS_BILLED_LABEL : $langs->trans("PropalStatusBilled"));
- $this->labelstatut_short[0]=(! empty($conf->global->PROPAL_STATUS_DRAFTSHORT_LABEL) ? $conf->global->PROPAL_STATUS_DRAFTSHORT_LABEL : $langs->trans("PropalStatusDraftShort"));
- $this->labelstatut_short[1]=(! empty($conf->global->PROPAL_STATUS_VALIDATEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_VALIDATEDSHORT_LABEL : $langs->trans("Opened"));
- $this->labelstatut_short[2]=(! empty($conf->global->PROPAL_STATUS_SIGNEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_SIGNEDSHORT_LABEL : $langs->trans("PropalStatusSignedShort"));
- $this->labelstatut_short[3]=(! empty($conf->global->PROPAL_STATUS_NOTSIGNEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_NOTSIGNEDSHORT_LABEL : $langs->trans("PropalStatusNotSignedShort"));
- $this->labelstatut_short[4]=(! empty($conf->global->PROPAL_STATUS_BILLEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_BILLEDSHORT_LABEL : $langs->trans("PropalStatusBilledShort"));
}
@@ -1116,12 +1105,8 @@ class Propal extends CommonObject
{
$action='update';
- // Actions on extra fields (by external module or standard code)
- // TODO le hook fait double emploi avec le trigger !!
- $hookmanager->initHooks(array('propaldao'));
- $parameters=array('socid'=>$this->id);
- $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
- if (empty($reshook))
+ // Actions on extra fields
+ if (! $error)
{
if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
{
@@ -1132,9 +1117,8 @@ class Propal extends CommonObject
}
}
}
- else if ($reshook < 0) $error++;
- if (! $notrigger)
+ if (! $error && ! $notrigger)
{
// Call trigger
$result=$this->call_trigger('PROPAL_CREATE',$user);
@@ -1212,7 +1196,7 @@ class Propal extends CommonObject
// get extrafields so they will be clone
foreach($this->lines as $line)
- $line->fetch_optionals($line->rowid);
+ $line->fetch_optionals();
// Load dest object
$clonedObj = clone $this;
@@ -1291,11 +1275,6 @@ class Propal extends CommonObject
$reshook=$hookmanager->executeHooks('createFrom',$parameters,$clonedObj,$action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) $error++;
}
-
- // Call trigger
- $result=$clonedObj->call_trigger('PROPAL_CLONE',$user);
- if ($result < 0) { $error++; }
- // End call triggers
}
unset($this->context['createfromclone']);
@@ -1350,16 +1329,19 @@ class Propal extends CommonObject
$sql.= ", dr.code as demand_reason_code, dr.label as demand_reason";
$sql.= ", cr.code as cond_reglement_code, cr.libelle as cond_reglement, cr.libelle_facture as cond_reglement_libelle_doc";
$sql.= ", cp.code as mode_reglement_code, cp.libelle as mode_reglement";
- $sql.= " FROM ".MAIN_DB_PREFIX."c_propalst as c, ".MAIN_DB_PREFIX."propal as p";
+ $sql.= " FROM ".MAIN_DB_PREFIX."propal as p";
+ $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_propalst as c ON p.fk_statut = c.id';
$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as cp ON p.fk_mode_reglement = cp.id AND cp.entity IN ('.getEntity('c_paiement').')';
$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON p.fk_cond_reglement = cr.rowid AND cr.entity IN ('.getEntity('c_payment_term').')';
$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_availability as ca ON p.fk_availability = ca.rowid';
$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON p.fk_input_reason = dr.rowid';
$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON p.fk_incoterms = i.rowid';
- $sql.= " WHERE p.fk_statut = c.id";
- $sql.= " AND p.entity IN (".getEntity('propal').")";
- if ($ref) $sql.= " AND p.ref='".$ref."'";
- else $sql.= " AND p.rowid=".$rowid;
+
+ if ($ref) {
+ $sql.= " WHERE p.entity IN (".getEntity('propal').")"; // Dont't use entity if you use rowid
+ $sql.= " AND p.ref='".$this->db->escape($ref)."'";
+ }
+ else $sql.= " WHERE p.rowid=".$rowid;
dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
$resql=$this->db->query($sql);
@@ -1444,12 +1426,9 @@ class Propal extends CommonObject
$this->brouillon = 1;
}
- // Retreive all extrafield for invoice
+ // Retreive all extrafield
// fetch optionals attributes and labels
- require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
- $extrafields=new ExtraFields($this->db);
- $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true);
- $this->fetch_optionals($this->id,$extralabels);
+ $this->fetch_optionals();
$this->db->free($resql);
@@ -1486,6 +1465,8 @@ class Propal extends CommonObject
*/
function update(User $user, $notrigger=0)
{
+ global $conf;
+
$error=0;
// Clean parameters
@@ -1534,17 +1515,23 @@ class Propal extends CommonObject
$error++; $this->errors[]="Error ".$this->db->lasterror();
}
- if (! $error)
+ if (! $error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options)>0)
{
- if (! $notrigger)
+ $result=$this->insertExtraFields();
+ if ($result < 0)
{
- // Call trigger
- $result=$this->call_trigger('PROPAL_MODIFY', $user);
- if ($result < 0) $error++;
- // End call triggers
+ $error++;
}
}
+ if (! $error && ! $notrigger)
+ {
+ // Call trigger
+ $result=$this->call_trigger('PROPAL_MODIFY', $user);
+ if ($result < 0) $error++;
+ // End call triggers
+ }
+
// Commit or rollback
if ($error)
{
@@ -1670,7 +1657,7 @@ class Propal extends CommonObject
$this->db->free($result);
- return 1;
+ return $num;
}
else
{
@@ -1761,8 +1748,8 @@ class Propal extends CommonObject
// to not lose the linked files
$oldref = dol_sanitizeFileName($this->ref);
$newref = dol_sanitizeFileName($num);
- $dirsource = $conf->propal->dir_output.'/'.$oldref;
- $dirdest = $conf->propal->dir_output.'/'.$newref;
+ $dirsource = $conf->propal->multidir_output[$this->entity].'/'.$oldref;
+ $dirdest = $conf->propal->multidir_output[$this->entity].'/'.$newref;
if (file_exists($dirsource))
{
@@ -1771,7 +1758,7 @@ class Propal extends CommonObject
{
dol_syslog("Rename ok");
// Rename docs starting with $oldref with $newref
- $listoffiles=dol_dir_list($conf->propal->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/'));
+ $listoffiles=dol_dir_list($dirdest, 'files', 1, '^'.preg_quote($oldref,'/'));
foreach($listoffiles as $fileentry)
{
$dirsource=$fileentry['name'];
@@ -2540,21 +2527,6 @@ class Propal extends CommonObject
}
}
- /**
- * Class invoiced the Propal
- *
- * @return int <0 si ko, >0 si ok
- * @deprecated
- * @see classifyBilled()
- */
- function classer_facturee()
- {
- global $user;
- dol_syslog(__METHOD__ . " is deprecated", LOG_WARNING);
-
- return $this->classifyBilled($user);
- }
-
/**
* Set draft status
*
@@ -2827,9 +2799,9 @@ class Propal extends CommonObject
{
// We remove directory
$ref = dol_sanitizeFileName($this->ref);
- if ($conf->propal->dir_output && !empty($this->ref))
+ if ($conf->propal->multidir_output[$this->entity] && !empty($this->ref))
{
- $dir = $conf->propal->dir_output . "/" . $ref ;
+ $dir = $conf->propal->multidir_output[$this->entity] . "/" . $ref ;
$file = $dir . "/" . $ref . ".pdf";
if (file_exists($file))
{
@@ -3123,10 +3095,26 @@ class Propal extends CommonObject
* @param int $mode 0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto, 6=Long label + Picto
* @return string Label
*/
- function LibStatut($statut,$mode=1)
+ function LibStatut($statut,$mode=1)
{
- global $langs;
- $langs->load("propal");
+ global $conf;
+
+ // Init/load array of translation of status
+ if (empty($this->labelstatut) || empty($this->labelstatut_short))
+ {
+ global $langs;
+ $langs->load("propal");
+ $this->labelstatut[0]=$langs->trans("PropalStatusDraft");
+ $this->labelstatut[1]=$langs->trans("PropalStatusValidated");
+ $this->labelstatut[2]=$langs->trans("PropalStatusSigned");
+ $this->labelstatut[3]=$langs->trans("PropalStatusNotSigned");
+ $this->labelstatut[4]=$langs->trans("PropalStatusBilled");
+ $this->labelstatut_short[0]=$langs->trans("PropalStatusDraftShort");
+ $this->labelstatut_short[1]=$langs->trans("Opened");
+ $this->labelstatut_short[2]=$langs->trans("PropalStatusSignedShort");
+ $this->labelstatut_short[3]=$langs->trans("PropalStatusNotSignedShort");
+ $this->labelstatut_short[4]=$langs->trans("PropalStatusBilledShort");
+ }
$statuttrans='';
if ($statut==self::STATUS_DRAFT) $statuttrans='statut0';
@@ -3372,12 +3360,19 @@ class Propal extends CommonObject
global $conf,$langs;
$langs->load("propal");
- if (! empty($conf->global->PROPALE_ADDON))
+ $constant = 'PROPALE_ADDON_'.$this->entity;
+
+ if (! empty($conf->global->$constant)) {
+ $classname = $conf->global->$constant; // for multicompany proposal sharing
+ } else {
+ $classname = $conf->global->PROPALE_ADDON;
+ }
+
+ if (! empty($classname))
{
$mybool=false;
- $file = $conf->global->PROPALE_ADDON.".php";
- $classname = $conf->global->PROPALE_ADDON;
+ $file = $classname.".php";
// Include file with class
$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
@@ -3605,9 +3600,10 @@ class Propal extends CommonObject
* @param int $hidedetails Hide details of lines
* @param int $hidedesc Hide description
* @param int $hideref Hide ref
+ * @param null|array $moreparams Array to provide more information
* @return int 0 if KO, 1 if OK
*/
- public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0)
+ public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
{
global $conf,$langs;
@@ -3626,7 +3622,7 @@ class Propal extends CommonObject
$modelpath = "core/modules/propale/doc/";
- return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
+ return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref,$moreparams);
}
/**
@@ -3846,6 +3842,8 @@ class PropaleLigne extends CommonObjectLine
$this->multicurrency_total_tva = $objp->multicurrency_total_tva;
$this->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
+ $this->fetch_optionals();
+
$this->db->free($result);
return 1;
@@ -3980,7 +3978,7 @@ class PropaleLigne extends CommonObjectLine
}
}
- if (! $notrigger)
+ if (! $error && ! $notrigger)
{
// Call trigger
$result=$this->call_trigger('LINEPROPAL_INSERT',$user);
@@ -4163,7 +4161,7 @@ class PropaleLigne extends CommonObjectLine
}
}
- if (! $notrigger)
+ if (! $error && ! $notrigger)
{
// Call trigger
$result=$this->call_trigger('LINEPROPAL_UPDATE',$user);
diff --git a/htdocs/comm/propal/contact.php b/htdocs/comm/propal/contact.php
index 01e851769a7..5e21f493c64 100644
--- a/htdocs/comm/propal/contact.php
+++ b/htdocs/comm/propal/contact.php
@@ -32,10 +32,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
-$langs->load("facture");
-$langs->load("orders");
-$langs->load("sendings");
-$langs->load("companies");
+// Load translation files required by the page
+$langs->loadLangs(array('facture', 'orders', 'sendings', 'companies'));
$id=GETPOST('id','int');
$ref= GETPOST('ref','alpha');
@@ -164,7 +162,7 @@ if ($object->id > 0)
$morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1);
$morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1);
// Thirdparty
- $morehtmlref.=' '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1);
+ $morehtmlref.=' '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1,'customer');
// Project
if (! empty($conf->projet->enabled))
{
diff --git a/htdocs/comm/propal/document.php b/htdocs/comm/propal/document.php
index ba373c78f44..1c8d494214d 100644
--- a/htdocs/comm/propal/document.php
+++ b/htdocs/comm/propal/document.php
@@ -36,9 +36,8 @@ if (! empty($conf->projet->enabled)) {
require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
}
-$langs->load('compta');
-$langs->load('other');
-$langs->load('companies');
+// Load translation files required by the page
+$langs->loadLangs(array('compta', 'other', 'companies'));
$action = GETPOST('action','alpha');
$confirm = GETPOST('confirm','alpha');
@@ -75,7 +74,7 @@ $object->fetch($id,$ref);
if ($object->id > 0)
{
$object->fetch_thirdparty();
- $upload_dir = $conf->propal->dir_output.'/'.dol_sanitizeFileName($object->ref);
+ $upload_dir = $conf->propal->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->ref);
include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php';
}
@@ -90,7 +89,7 @@ $form = new Form($db);
if ($object->id > 0)
{
- $upload_dir = $conf->propal->dir_output.'/'.dol_sanitizeFileName($object->ref);
+ $upload_dir = $conf->propal->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->ref);
$head = propal_prepare_head($object);
dol_fiche_head($head, 'document', $langs->trans('Proposal'), -1, 'propal');
@@ -114,7 +113,7 @@ if ($object->id > 0)
$morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1);
$morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1);
// Thirdparty
- $morehtmlref.=' '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1);
+ $morehtmlref.=' '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1,'customer');
// Project
if (! empty($conf->projet->enabled))
{
@@ -160,7 +159,7 @@ if ($object->id > 0)
// Files infos
print ''.$langs->trans("NbOfAttachedFiles").' '.count($filearray).' ';
- print ''.$langs->trans("TotalSizeOfAttachedFiles").' '.$totalsize.' '.$langs->trans("bytes").' ';
+ print ''.$langs->trans("TotalSizeOfAttachedFiles").' '.dol_print_size($totalsize,1,1).' ';
print "
\n";
diff --git a/htdocs/comm/propal/index.php b/htdocs/comm/propal/index.php
index a313ab299f0..0dbe2fb855e 100644
--- a/htdocs/comm/propal/index.php
+++ b/htdocs/comm/propal/index.php
@@ -27,8 +27,8 @@ require '../../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
require_once DOL_DOCUMENT_ROOT .'/comm/propal/class/propal.class.php';
-$langs->load("propal");
-$langs->load("companies");
+// Load translation files required by the page
+$langs->loadLangs(array('propal', 'companies'));
// Security check
$socid=GETPOST('socid','int');
@@ -216,7 +216,7 @@ $max=5;
* Last modified proposals
*/
-$sql = "SELECT c.rowid, c.ref, c.fk_statut, s.nom as socname, s.rowid as socid, s.canvas, s.client,";
+$sql = "SELECT c.rowid, c.entity, c.ref, c.fk_statut, s.nom as socname, s.rowid as socid, s.canvas, s.client,";
$sql.= " date_cloture as datec";
$sql.= " FROM ".MAIN_DB_PREFIX."propal as c";
$sql.= ", ".MAIN_DB_PREFIX."societe as s";
@@ -262,7 +262,7 @@ if ($resql)
print '';
$filename=dol_sanitizeFileName($obj->ref);
- $filedir=$conf->propal->dir_output . '/' . dol_sanitizeFileName($obj->ref);
+ $filedir=$conf->propal->multidir_output[$obj->entity] . '/' . dol_sanitizeFileName($obj->ref);
$urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid;
print $formfile->getDocumentsLink($propalstatic->element, $filename, $filedir);
print '
';
@@ -296,7 +296,8 @@ if (! empty($conf->propal->enabled) && $user->rights->propale->lire)
$now=dol_now();
- $sql = "SELECT s.nom as socname, s.rowid as socid, s.canvas, s.client, p.rowid as propalid, p.total as total_ttc, p.total_ht, p.ref, p.fk_statut, p.datep as dp, p.fin_validite as dfv";
+ $sql = "SELECT s.nom as socname, s.rowid as socid, s.canvas, s.client";
+ $sql.= ", p.rowid as propalid, p.entity, p.total as total_ttc, p.total_ht, p.ref, p.fk_statut, p.datep as dp, p.fin_validite as dfv";
$sql.= " FROM ".MAIN_DB_PREFIX."societe as s";
$sql.= ", ".MAIN_DB_PREFIX."propal as p";
if (!$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
@@ -341,7 +342,7 @@ if (! empty($conf->propal->enabled) && $user->rights->propale->lire)
print '';
print '';
$filename=dol_sanitizeFileName($obj->ref);
- $filedir=$conf->propal->dir_output . '/' . dol_sanitizeFileName($obj->ref);
+ $filedir=$conf->propal->multidir_output[$obj->entity] . '/' . dol_sanitizeFileName($obj->ref);
$urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->propalid;
print $formfile->getDocumentsLink($propalstatic->element, $filename, $filedir);
print '
';
diff --git a/htdocs/comm/propal/info.php b/htdocs/comm/propal/info.php
index 67cc8210402..317c9902d52 100644
--- a/htdocs/comm/propal/info.php
+++ b/htdocs/comm/propal/info.php
@@ -32,8 +32,8 @@ if (! empty($conf->projet->enabled)) {
require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
}
-$langs->load('propal');
-$langs->load('compta');
+// Load translation files required by the page
+$langs->loadLangs(array('propal', 'compta'));
$id=GETPOST('id','int');
$ref=GETPOST('ref','alpha');
diff --git a/htdocs/comm/propal/list.php b/htdocs/comm/propal/list.php
index eb16e54bbbb..a40a6e25b97 100644
--- a/htdocs/comm/propal/list.php
+++ b/htdocs/comm/propal/list.php
@@ -10,8 +10,9 @@
* Copyright (C) 2012 Christophe Battarel
* Copyright (C) 2013 Cédric Salvador
* Copyright (C) 2015 Jean-François Ferry
- * Copyright (C) 2016 Ferran Marcet
+ * Copyright (C) 2016-2018 Ferran Marcet
* Copyright (C) 2017 Charlene Benke
+ * Copyright (C) 2018 Nicolas ZABOURI
*
* 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
@@ -43,7 +44,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
-$langs->loadLangs(array('companies','propal','compta','bills','orders','products'));
+// Load translation files required by the page
+$langs->loadLangs(array('companies','propal','compta','bills','orders','products','deliveries'));
$socid=GETPOST('socid','int');
@@ -52,6 +54,7 @@ $massaction=GETPOST('massaction','alpha');
$show_files=GETPOST('show_files','int');
$confirm=GETPOST('confirm','alpha');
$toselect = GETPOST('toselect', 'array');
+$contextpage=GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'proposallist';
$search_user=GETPOST('search_user','int');
$search_sale=GETPOST('search_sale','int');
@@ -74,6 +77,14 @@ $search_type_thirdparty=GETPOST("search_type_thirdparty",'int');
$search_day=GETPOST("search_day","int");
$search_month=GETPOST("search_month","int");
$search_year=GETPOST("search_year","int");
+$search_dayfin=GETPOST("search_dayfin","int");
+$search_month_end=GETPOST("search_month_end","int");
+$search_yearfin=GETPOST("search_yearfin","int");
+$search_daydelivery=GETPOST("search_daydelivery","int");
+$search_monthdelivery=GETPOST("search_monthdelivery","int");
+$search_yeardelivery=GETPOST("search_yeardelivery","int");
+$search_availability=GETPOST('search_availability','int');
+$search_categ_cus=trim(GETPOST("search_categ_cus",'int'));
$search_btn=GETPOST('button_search','alpha');
$search_remove_btn=GETPOST('button_removefilter','alpha');
@@ -85,7 +96,7 @@ $sall=trim((GETPOST('search_all', 'alphanohtml')!='')?GETPOST('search_all', 'alp
$mesg=(GETPOST("msg") ? GETPOST("msg") : GETPOST("mesg"));
-$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit;
+$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit;
$sortfield = GETPOST("sortfield",'alpha');
$sortorder = GETPOST("sortorder",'alpha');
$page = GETPOST("page",'int');
@@ -96,9 +107,6 @@ $pagenext = $page + 1;
if (! $sortfield) $sortfield='p.ref';
if (! $sortorder) $sortorder='DESC';
-// Initialize technical object to manage context to save list fields
-$contextpage=GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'proposallist';
-
// Security check
$module='propal';
$dbtable='';
@@ -112,9 +120,10 @@ if (! empty($socid))
}
$result = restrictedArea($user, $module, $objectid, $dbtable);
-$diroutputmassaction=$conf->propal->dir_output . '/temp/massgeneration/'.$user->id;
+$diroutputmassaction=$conf->propal->multidir_output[$conf->entity] . '/temp/massgeneration/'.$user->id;
// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
+$object = new Propal($db);
$hookmanager->initHooks(array('propallist'));
$extrafields = new ExtraFields($db);
@@ -146,6 +155,8 @@ $arrayfields=array(
'typent.code'=>array('label'=>$langs->trans("ThirdPartyType"), 'checked'=>$checkedtypetiers),
'p.date'=>array('label'=>$langs->trans("Date"), 'checked'=>1),
'p.fin_validite'=>array('label'=>$langs->trans("DateEnd"), 'checked'=>1),
+ 'p.date_livraison'=>array('label'=>$langs->trans("DeliveryDate"), 'checked'=>0),
+ 'ava.rowid'=>array('label'=>$langs->trans("AvailabilityPeriod"), 'checked'=>0),
'p.total_ht'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1),
'p.total_vat'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>0),
'p.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>0),
@@ -203,10 +214,19 @@ if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x',
$search_year='';
$search_month='';
$search_day='';
+ $search_yearfin='';
+ $search_month_end='';
+ $search_dayfin='';
+ $search_yeardelivery='';
+ $search_monthdelivery='';
+ $search_daydelivery='';
+ $search_availability='';
$viewstatut='';
$object_statut='';
$toselect='';
$search_array_options=array();
+ $search_categ_cus=0;
+
}
if ($object_statut != '') $viewstatut=$object_statut;
@@ -216,7 +236,8 @@ if (empty($reshook))
$objectlabel='Proposals';
$permtoread = $user->rights->propal->lire;
$permtodelete = $user->rights->propal->supprimer;
- $uploaddir = $conf->propal->dir_output;
+ $permtoclose = $user->rights->propal->cloturer;
+ $uploaddir = $conf->propal->multidir_output[$conf->entity];
include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';
}
@@ -243,12 +264,15 @@ $sql = 'SELECT';
if ($sall || $search_product_category > 0) $sql = 'SELECT DISTINCT';
$sql.= ' s.rowid as socid, s.nom as name, s.email, s.town, s.zip, s.fk_pays, s.client, s.code_client, ';
$sql.= " typent.code as typent_code,";
+$sql.= " ava.rowid as availability,";
$sql.= " state.code_departement as state_code, state.nom as state_name,";
-$sql.= ' p.rowid, p.note_private, p.total_ht, p.tva as total_vat, p.total as total_ttc, p.localtax1, p.localtax2, p.ref, p.ref_client, p.fk_statut, p.fk_user_author, p.datep as dp, p.fin_validite as dfv,';
+$sql.= ' p.rowid, p.entity, p.note_private, p.total_ht, p.tva as total_vat, p.total as total_ttc, p.localtax1, p.localtax2, p.ref, p.ref_client, p.fk_statut, p.fk_user_author, p.datep as dp, p.fin_validite as dfv,p.date_livraison as ddelivery,';
$sql.= ' p.datec as date_creation, p.tms as date_update,';
$sql.= " pr.rowid as project_id, pr.ref as project_ref,";
if (! $user->rights->societe->client->voir && ! $socid) $sql .= " sc.fk_soc, sc.fk_user,";
$sql.= ' u.login';
+if ($search_categ_cus) $sql .= ", cc.fk_categorie, cc.fk_soc";
+
// Add fields from extrafields
foreach ($extrafields->attribute_label as $key => $val) $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key.' as options_'.$key : '');
// Add fields from hooks
@@ -259,12 +283,15 @@ $sql.= ' FROM '.MAIN_DB_PREFIX.'societe as s';
$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as country on (country.rowid = s.fk_pays)";
$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_typent as typent on (typent.id = s.fk_typent)";
$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as state on (state.rowid = s.fk_departement)";
+if (! empty($search_categ_cus)) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_societe as cc ON s.rowid = cc.fk_soc"; // We'll need this table joined to the select in order to filter by categ
+
$sql.= ', '.MAIN_DB_PREFIX.'propal as p';
if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."propal_extrafields as ef on (p.rowid = ef.fk_object)";
if ($sall || $search_product_category > 0) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'propaldet as pd ON p.rowid=pd.fk_propal';
if ($search_product_category > 0) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=pd.fk_product';
$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'user as u ON p.fk_user_author = u.rowid';
$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."projet as pr ON pr.rowid = p.fk_projet";
+$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_availability as ava on (ava.rowid = p.fk_availability)";
// We'll need this table joined to the select in order to filter by sale
if ($search_sale > 0 || (! $user->rights->societe->client->voir && ! $socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
if ($search_user > 0)
@@ -285,7 +312,8 @@ if ($search_country) $sql .= " AND s.fk_pays IN (".$db->escape($search_country).
if ($search_type_thirdparty) $sql .= " AND s.fk_typent IN (".$db->escape($search_type_thirdparty).')';
if ($search_ref) $sql .= natural_search('p.ref', $search_ref);
if ($search_refcustomer) $sql .= natural_search('p.ref_client', $search_refcustomer);
-if ($search_refproject) $sql .= natural_search('pr.ref', $search_refproject);
+if ($search_refproject) $sql .= natural_search('pr.ref', $search_refproject);
+if ($search_availability) $sql .= " AND p.fk_availability IN (".$db->escape($search_availability).')';
if ($search_societe) $sql .= natural_search('s.nom', $search_societe);
if ($search_login) $sql .= natural_search("u.login", $search_login);
@@ -295,6 +323,9 @@ if ($search_montant_ttc != '') $sql.= natural_search("p.total", $search_montant_
if ($sall) {
$sql .= natural_search(array_keys($fieldstosearchall), $sall);
}
+if ($search_categ_cus > 0) $sql.= " AND cc.fk_categorie = ".$db->escape($search_categ_cus);
+if ($search_categ_cus == -2) $sql.= " AND cc.fk_categorie IS NULL";
+
if ($search_product_category > 0) $sql.=" AND cp.fk_categorie = ".$db->escape($search_product_category);
if ($socid > 0) $sql.= ' AND s.rowid = '.$socid;
if ($viewstatut != '' && $viewstatut != '-1')
@@ -314,6 +345,32 @@ else if ($search_year > 0)
{
$sql.= " AND p.datep BETWEEN '".$db->idate(dol_get_first_day($search_year,1,false))."' AND '".$db->idate(dol_get_last_day($search_year,12,false))."'";
}
+if ($search_month_end > 0)
+{
+ if ($search_yearfin > 0 && empty($search_dayfin))
+ $sql.= " AND p.fin_validite BETWEEN '".$db->idate(dol_get_first_day($search_yearfin,$search_month_end,false))."' AND '".$db->idate(dol_get_last_day($search_yearfin,$search_month_end,false))."'";
+ else if ($search_yearfin > 0 && ! empty($search_dayfin))
+ $sql.= " AND p.fin_validite BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $search_month_end, $search_dayfin, $search_yearfin))."' AND '".$db->idate(dol_mktime(23, 59, 59, $search_month_end, $search_dayfin, $search_yearfin))."'";
+ else
+ $sql.= " AND date_format(p.fin_validite, '%m') = '".$db->escape($search_month_end)."'";
+}
+else if ($search_yearfin > 0)
+{
+ $sql.= " AND p.fin_validite BETWEEN '".$db->idate(dol_get_first_day($search_yearfin,1,false))."' AND '".$db->idate(dol_get_last_day($search_yearfin,12,false))."'";
+}
+if ($search_monthdelivery > 0)
+{
+ if ($search_yeardelivery > 0 && empty($search_daydelivery))
+ $sql.= " AND p.date_livraison BETWEEN '".$db->idate(dol_get_first_day($search_yeardelivery,$search_monthdelivery,false))."' AND '".$db->idate(dol_get_last_day($search_yeardelivery,$search_monthdelivery,false))."'";
+ else if ($search_yeardelivery > 0 && ! empty($search_daydelivery))
+ $sql.= " AND p.date_livraison BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $search_monthdelivery, $search_daydelivery, $search_yeardelivery))."' AND '".$db->idate(dol_mktime(23, 59, 59, $search_monthdelivery, $search_daydelivery, $search_yeardelivery))."'";
+ else
+ $sql.= " AND date_format(p.date_livraison, '%m') = '".$db->escape($search_monthdelivery)."'";
+}
+else if ($search_yeardelivery > 0)
+{
+ $sql.= " AND p.date_livraison BETWEEN '".$db->idate(dol_get_first_day($search_yeardelivery,1,false))."' AND '".$db->idate(dol_get_last_day($search_yeardelivery,12,false))."'";
+}
if ($search_sale > 0) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$db->escape($search_sale);
if ($search_user > 0)
{
@@ -336,6 +393,12 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
{
$result = $db->query($sql);
$nbtotalofrecords = $db->num_rows($result);
+
+ if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0
+ {
+ $page = 0;
+ $offset = 0;
+ }
}
$sql.= $db->plimit($limit+1, $offset);
@@ -371,7 +434,7 @@ if ($resql)
if ($search_year) $param.='&search_year='.urlencode($search_year);
if ($search_ref) $param.='&search_ref='.urlencode($search_ref);
if ($search_refcustomer) $param.='&search_refcustomer='.urlencode($search_refcustomer);
- if ($search_refprojet) $param.='&search_refprojet='.urlencode($search_refprojet);
+ if ($search_refproject) $param.='&search_refproject='.urlencode($search_refproject);
if ($search_societe) $param.='&search_societe='.urlencode($search_societe);
if ($search_user > 0) $param.='&search_user='.urlencode($search_user);
if ($search_sale > 0) $param.='&search_sale='.urlencode($search_sale);
@@ -381,7 +444,8 @@ if ($resql)
if ($search_zip) $param.='&search_zip='.urlencode($search_zip);
if ($socid > 0) $param.='&socid='.urlencode($socid);
if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss);
- if ($search_product_category != '') $param.='&search_product_category='.$search_product_category;
+ if ($search_categ_cus > 0) $param.='&search_categ_cus='.urlencode($search_categ_cus);
+ if ($search_product_category != '') $param.='&search_product_category='.$search_product_category;
// Add $param from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
@@ -392,9 +456,18 @@ if ($resql)
'builddoc'=>$langs->trans("PDFMerge"),
);
if ($user->rights->propal->supprimer) $arrayofmassactions['predelete']=$langs->trans("Delete");
- if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array();
+ if ($user->rights->propal->cloturer) $arrayofmassactions['closed']=$langs->trans("Closed");
+ if (in_array($massaction, array('presend','predelete','closed'))) $arrayofmassactions=array();
$massactionbutton=$form->selectMassAction('', $arrayofmassactions);
+ $newcardbutton='';
+ if ($user->rights->propal->creer)
+ {
+ $newcardbutton=''.$langs->trans('NewPropal').' ';
+ $newcardbutton.= ' ';
+ $newcardbutton.= ' ';
+ }
+
// Lignes des champs de filtre
print '';
if ($optioncss != '') print ' ';
@@ -406,7 +479,7 @@ if ($resql)
print ' ';
print ' ';
- print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_commercial.png', 0, '', '', $limit);
+ print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_commercial.png', 0, $newcardbutton, '', $limit);
$topicmail="SendPropalRef";
$modelmail="proposal_send";
@@ -417,7 +490,7 @@ if ($resql)
if ($sall)
{
foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val);
- print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall);
+ print ''.$langs->trans("FilterOnInto", $all) . join(', ',$fieldstosearchall).'
';
}
$i = 0;
@@ -451,6 +524,14 @@ if ($resql)
$moreforfilter.=$form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1);
$moreforfilter.='';
}
+ if (! empty($conf->categorie->enabled))
+ {
+ require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
+ $moreforfilter.='';
+ $moreforfilter.=$langs->trans('CustomersProspectsCategoriesShort').': ';
+ $moreforfilter.=$formother->select_categories('customer',$search_categ_cus,'search_categ_cus',1);
+ $moreforfilter.='
';
+ }
$parameters=array();
$reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook
if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint;
@@ -465,7 +546,7 @@ if ($resql)
$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage;
$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields
- if ($massactionbutton) $selectedfields.=$form->showCheckAddButtons('checkforselect', 1);
+ $selectedfields.=(count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : '');
print '';
print '
'."\n";
@@ -474,25 +555,25 @@ if ($resql)
if (! empty($arrayfields['p.ref']['checked']))
{
print '';
- print ' ';
+ print ' ';
print ' ';
}
if (! empty($arrayfields['p.ref_client']['checked']))
{
print '';
- print ' ';
+ print ' ';
print ' ';
}
if (! empty($arrayfields['pr.ref']['checked']))
{
print '';
- print ' ';
+ print ' ';
print ' ';
}
if (! empty($arrayfields['s.nom']['checked']))
{
print '';
- print ' ';
+ print ' ';
print ' ';
}
if (! empty($arrayfields['s.town']['checked'])) print ' ';
@@ -516,15 +597,16 @@ if ($resql)
{
print '';
print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT));
+ print ajax_combobox('search_type_thirdparty');
print ' ';
}
// Date
if (! empty($arrayfields['p.date']['checked']))
{
- print '';
+ print ' ';
//print $langs->trans('Month').': ';
- if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ' ';
- print ' ';
+ if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ' ';
+ print ' ';
//print ' '.$langs->trans('Year').': ';
$formother->select_year($search_year,'search_year',1, 20, 5);
print ' ';
@@ -532,34 +614,59 @@ if ($resql)
// Date end
if (! empty($arrayfields['p.fin_validite']['checked']))
{
- print ' ';
+ print '';
+ //print $langs->trans('Month').': ';
+ if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ' ';
+ print ' ';
+ //print ' '.$langs->trans('Year').': ';
+ $formother->select_year($search_yearfin,'search_yearfin',1, 20, 5);
+ print ' ';
+ }
+ // Date delivery
+ if (! empty($arrayfields['p.date_livraison']['checked']))
+ {
+ print '';
+ //print $langs->trans('Month').': ';
+ if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ' ';
+ print ' ';
+ //print ' '.$langs->trans('Year').': ';
+ $formother->select_year($search_yeardelivery,'search_yeardelivery',1, 20, 5);
+ print ' ';
+ }
+ // Availability
+ if (! empty($arrayfields['ava.rowid']['checked']))
+ {
+ print '';
+ print $form->selectAvailabilityDelay($search_availability, 'search_availability', '', 1);
+ print ajax_combobox('search_availability');
+ print ' ';
}
if (! empty($arrayfields['p.total_ht']['checked']))
{
// Amount
print '';
- print ' ';
+ print ' ';
print ' ';
}
if (! empty($arrayfields['p.total_vat']['checked']))
{
// Amount
print '';
- print ' ';
+ print ' ';
print ' ';
}
if (! empty($arrayfields['p.total_ttc']['checked']))
{
// Amount
print '';
- print ' ';
+ print ' ';
print ' ';
}
if (! empty($arrayfields['u.login']['checked']))
{
// Author
print '';
- print ' ';
+ print ' ';
print ' ';
}
// Extra fields
@@ -610,6 +717,8 @@ if ($resql)
if (! empty($arrayfields['typent.code']['checked'])) print_liste_field_titre($arrayfields['typent.code']['label'],$_SERVER["PHP_SELF"],"typent.code","",$param,'align="center"',$sortfield,$sortorder);
if (! empty($arrayfields['p.date']['checked'])) print_liste_field_titre($arrayfields['p.date']['label'],$_SERVER["PHP_SELF"],'p.datep','',$param, 'align="center"',$sortfield,$sortorder);
if (! empty($arrayfields['p.fin_validite']['checked'])) print_liste_field_titre($arrayfields['p.fin_validite']['label'],$_SERVER["PHP_SELF"],'dfv','',$param, 'align="center"',$sortfield,$sortorder);
+ if (! empty($arrayfields['p.date_livraison']['checked'])) print_liste_field_titre($arrayfields['p.date_livraison']['label'],$_SERVER["PHP_SELF"],'ddelivery','',$param, 'align="center"',$sortfield,$sortorder);
+ if (! empty($arrayfields['ava.rowid']['checked'])) print_liste_field_titre($arrayfields['ava.rowid']['label'],$_SERVER["PHP_SELF"],'availability','',$param, '',$sortfield,$sortorder);
if (! empty($arrayfields['p.total_ht']['checked'])) print_liste_field_titre($arrayfields['p.total_ht']['label'],$_SERVER["PHP_SELF"],'p.total_ht','',$param, 'align="right"',$sortfield,$sortorder);
if (! empty($arrayfields['p.total_vat']['checked'])) print_liste_field_titre($arrayfields['p.total_vat']['label'],$_SERVER["PHP_SELF"],'p.tva','',$param, 'align="right"',$sortfield,$sortorder);
if (! empty($arrayfields['p.total_ttc']['checked'])) print_liste_field_titre($arrayfields['p.total_ttc']['label'],$_SERVER["PHP_SELF"],'p.total','',$param, 'align="right"',$sortfield,$sortorder);
@@ -666,7 +775,7 @@ if ($resql)
// Other picto tool
print '';
$filename=dol_sanitizeFileName($obj->ref);
- $filedir=$conf->propal->dir_output . '/' . dol_sanitizeFileName($obj->ref);
+ $filedir=$conf->propal->multidir_output[$obj->entity] . '/' . dol_sanitizeFileName($obj->ref);
$urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid;
print $formfile->getDocumentsLink($objectstatic->element, $filename, $filedir);
print '
';
@@ -775,6 +884,28 @@ if ($resql)
}
if (! $i) $totalarray['nbfield']++;
}
+ // Date delivery
+ if (! empty($arrayfields['p.date_livraison']['checked']))
+ {
+ if ($obj->ddelivery)
+ {
+ print '
'.dol_print_date($db->jdate($obj->ddelivery),'day');
+ print ' ';
+ }
+ else
+ {
+ print '
';
+ }
+ if (! $i) $totalarray['nbfield']++;
+ }
+ // Availability
+ if (! empty($arrayfields['ava.rowid']['checked']))
+ {
+ print '
';
+ $form->form_availability('', $obj->availability, 'none', 1);
+ print ' ';
+ if (! $i) $totalarray['nbfield']++;
+ }
// Amount HT
if (! empty($arrayfields['p.total_ht']['checked']))
@@ -895,25 +1026,18 @@ if ($resql)
print ''."\n";
- if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files)
- {
- /*
- * Show list of available documents
- */
- $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder;
- $urlsource.=str_replace('&','&',$param);
+ $hidegeneratedfilelistifempty=1;
+ if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty=0;
- $filedir=$diroutputmassaction;
- $genallowed=$user->rights->propal->lire;
- $delallowed=$user->rights->propal->creer;
+ // Show list of available documents
+ $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder;
+ $urlsource.=str_replace('&','&',$param);
- print $formfile->showdocuments('massfilesarea_proposals','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,'','');
- }
- else
- {
- print '
'.$langs->trans("ShowTempMassFilesArea").' ';
- }
+ $filedir=$diroutputmassaction;
+ $genallowed=$user->rights->propal->lire;
+ $delallowed=$user->rights->propal->creer;
+ print $formfile->showdocuments('massfilesarea_proposals','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,'','','',null,$hidegeneratedfilelistifempty);
}
else
{
diff --git a/htdocs/comm/propal/note.php b/htdocs/comm/propal/note.php
index 17e53b89948..607cff245d9 100644
--- a/htdocs/comm/propal/note.php
+++ b/htdocs/comm/propal/note.php
@@ -33,10 +33,8 @@ if (! empty($conf->projet->enabled)) {
require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
}
-$langs->load('propal');
-$langs->load('compta');
-$langs->load('bills');
-$langs->load("companies");
+// Load translation files required by the page
+$langs->loadLangs(array('propal', 'compta', 'bills', 'companies'));
$id = GETPOST('id','int');
$ref=GETPOST('ref','alpha');
diff --git a/htdocs/comm/propal/stats/index.php b/htdocs/comm/propal/stats/index.php
index 273862f68bf..ac6b42c45d8 100644
--- a/htdocs/comm/propal/stats/index.php
+++ b/htdocs/comm/propal/stats/index.php
@@ -54,11 +54,8 @@ $year = GETPOST('year')>0?GETPOST('year'):$nowyear;
$startyear=$year-1;
$endyear=$year;
-$langs->load('orders');
-$langs->load('companies');
-$langs->load('other');
-$langs->load('suppliers');
-$langs->load('supplier_proposal');
+// Load translation files required by the page
+$langs->loadLangs(array('orders', 'companies', 'other', 'suppliers', 'supplier_proposal'));
/*
@@ -329,7 +326,7 @@ print '
';
// Show graphs
-print '
';
+print '';
if ($mesg) { print $mesg; }
else {
print $px1->show();
diff --git a/htdocs/comm/propal/tpl/linkedobjectblock.tpl.php b/htdocs/comm/propal/tpl/linkedobjectblock.tpl.php
index cc8c6fe0547..cd49ca863e6 100644
--- a/htdocs/comm/propal/tpl/linkedobjectblock.tpl.php
+++ b/htdocs/comm/propal/tpl/linkedobjectblock.tpl.php
@@ -41,29 +41,36 @@ global $user;
$langs = $GLOBALS['langs'];
$linkedObjectBlock = $GLOBALS['linkedObjectBlock'];
+// Load translation files required by the page
$langs->load("propal");
$total=0; $ilink=0;
-$var=true;
foreach($linkedObjectBlock as $key => $objectlink)
{
$ilink++;
- $trclass=($var?'pair':'impair');
+ $trclass='oddeven';
if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass.=' liste_sub_total';
?>
-
- trans("Proposal"); ?>
- getNomUrl(1); ?>
- ref_client; ?>
- date,'day'); ?>
- " data-element="element; ?>" data-id="id; ?>" >
+ trans("Proposal"); ?>
+ global->MAIN_ENABLE_IMPORT_LINKED_OBJECT_LINES)
+ {
+ $url = DOL_URL_ROOT.'/comm/propal/card.php?id='.$objectlink->id;
+ print ' ';
+ }
+ ?>
+
+ getNomUrl(1); ?>
+ ref_client; ?>
+ date,'day'); ?>
+ rights->propale->lire) {
$total = $total + $objectlink->total_ht;
echo price($objectlink->total_ht);
} ?>
- getLibStatut(3); ?>
- id.'&action=dellink&dellinkid='.$key; ?>">transnoentitiesnoconv("RemoveLink")); ?>
+ getLibStatut(3); ?>
+ id.'&action=dellink&dellinkid='.$key; ?>">transnoentitiesnoconv("RemoveLink"), 'unlink'); ?>
load("propal");
@@ -88,8 +89,6 @@ if ($resql)
$i = 0;
if ($num > 0 )
{
- $var=true;
-
print '';
print '';
print ''.$langs->trans("ProspectsByStatus").' ';
@@ -126,8 +125,6 @@ if (! empty($conf->propal->enabled) && $user->rights->propale->lire)
$resql=$db->query($sql);
if ($resql)
{
- $var=true;
-
$total=0;
$num = $db->num_rows($resql);
$i = 0;
@@ -197,8 +194,6 @@ if (! empty($conf->propal->enabled) && $user->rights->propale->lire)
$i = 0;
if ($num > 0)
{
- $var=true;
-
print '';
print ''.$langs->trans("ProposalsOpened").' ';
@@ -223,7 +218,8 @@ if (! empty($conf->propal->enabled) && $user->rights->propale->lire)
$i++;
$total += $obj->price;
}
- if ($total>0) {
+ if ($total>0)
+ {
print ''.$langs->trans("Total")." ".price($total)." ";
}
print "
";
@@ -255,8 +251,6 @@ if ($resql)
$i = 0;
if ($num > 0 )
{
- $var=true;
-
print '';
print ''.$langs->trans("ProspectToContact").' ';
diff --git a/htdocs/comm/prospect/recap-prospect.php b/htdocs/comm/prospect/recap-prospect.php
index fe0fdc55b58..50127d719c8 100644
--- a/htdocs/comm/prospect/recap-prospect.php
+++ b/htdocs/comm/prospect/recap-prospect.php
@@ -26,8 +26,8 @@ require '../../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
-$langs->load("companies");
-$langs->load('other');
+// Load translation files required by the page
+$langs->loadLangs(array('companies', 'other'));
if (! empty($conf->facture->enabled)) $langs->load("bills");
// Security check
diff --git a/htdocs/comm/recap-client.php b/htdocs/comm/recap-client.php
index 71add817dc5..6cd41c6c658 100644
--- a/htdocs/comm/recap-client.php
+++ b/htdocs/comm/recap-client.php
@@ -26,6 +26,7 @@ require '../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
+// Load translation files required by the page
$langs->load("companies");
if (! empty($conf->facture->enabled)) $langs->load("bills");
diff --git a/htdocs/comm/remise.php b/htdocs/comm/remise.php
index 1ad4612d879..6f3287b8831 100644
--- a/htdocs/comm/remise.php
+++ b/htdocs/comm/remise.php
@@ -26,13 +26,12 @@ require '../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
-$langs->load("companies");
-$langs->load("orders");
-$langs->load("bills");
+// Load translation files required by the page
+$langs->loadLangs(array('companies', 'orders', 'bills'));
$id=GETPOST("id",'int');
-$socid = GETPOST('id','int');
+$socid = GETPOST('id','int')?GETPOST('id','int'):GETPOST('socid','int');
// Security check
if ($user->societe_id > 0)
{
@@ -56,7 +55,14 @@ if (GETPOST('action','aZ09') == 'setremise')
{
$object = new Societe($db);
$object->fetch($id);
- $result=$object->set_remise_client(price2num(GETPOST("remise")),GETPOST("note"),$user);
+
+ $discount_type = GETPOST('discount_type', 'int');
+
+ if(! empty($discount_type)) {
+ $result=$object->set_remise_supplier(price2num(GETPOST("remise")),GETPOST("note"),$user);
+ } else {
+ $result=$object->set_remise_client(price2num(GETPOST("remise")),GETPOST("note"),$user);
+ }
if ($result > 0)
{
@@ -100,34 +106,73 @@ if ($socid > 0)
$head = societe_prepare_head($object);
-
+ $isCustomer = $object->client == 1 || $object->client == 3;
+ $isSupplier = $object->fournisseur == 1;
print '';
print ' ';
print ' ';
print ' ';
- dol_fiche_head($head, 'relativediscount', $langs->trans("ThirdParty"), 0, 'company');
+ dol_fiche_head($head, 'relativediscount', $langs->trans("ThirdParty"), -1, 'company');
dol_banner_tab($object, 'socid', '', ($user->societe_id?0:1), 'rowid', 'nom');
print '';
print '
';
+
+ if(! $isCustomer && ! $isSupplier) {
+ print '
'.$langs->trans('ThirdpartyIsNeitherCustomerNorClientSoCannotHaveDiscounts').'
';
+
+ dol_fiche_end();
+
+ print '';
+
+ llxFooter();
+ $db->close();
+ exit;
+ }
+
print '
';
- // Discount
- print '';
- print $langs->trans("CustomerRelativeDiscount").' '.price2num($object->remise_percent)."% ";
+ if($isCustomer) {
+ // Customer discount
+ print '';
+ print $langs->trans("CustomerRelativeDiscount").' '.price2num($object->remise_percent)."% ";
+ }
+
+ if($isSupplier) {
+ // Supplier discount
+ print '';
+ print $langs->trans("SupplierRelativeDiscount").' '.price2num($object->remise_supplier_percent)."% ";
+ }
+
print '
';
print '
';
print load_fiche_titre($langs->trans("NewRelativeDiscount"),'','');
print '
';
-
+
+ if($isCustomer && ! $isSupplier) {
+ print '
';
+ }
+
+ if(! $isCustomer && $isSupplier) {
+ print '
';
+ }
+
print '
';
+ if($isCustomer && $isSupplier) {
+ // Discount type
+ print ''.$langs->trans('DiscountType').' ';
+ print ' '.$langs->trans('Customer').' ';
+ print ' '.$langs->trans('Supplier').' ';
+ print ' ';
+ }
+
// New value
print '';
print $langs->trans("NewValue").' % ';
@@ -155,57 +200,128 @@ if ($socid > 0)
print ' ';
+ if($isCustomer) {
+ if($isSupplier) {
+ print '';
+ print '
';
+ print load_fiche_titre($langs->trans("CustomerDiscounts"), '', '');
+ }
- /*
- * List log of all percent discounts
- */
- $sql = "SELECT rc.rowid, rc.remise_client as remise_percent, rc.note, rc.datec as dc,";
- $sql.= " u.login, u.rowid as user_id";
- $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise as rc, ".MAIN_DB_PREFIX."user as u";
- $sql.= " WHERE rc.fk_soc = " . $object->id;
- $sql.= " AND rc.entity = " . $conf->entity;
- $sql.= " AND u.rowid = rc.fk_user_author";
- $sql.= " ORDER BY rc.datec DESC";
+ /*
+ * List log of all customer percent discounts
+ */
+ $sql = "SELECT rc.rowid, rc.remise_client as remise_percent, rc.note, rc.datec as dc,";
+ $sql.= " u.login, u.rowid as user_id";
+ $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise as rc, ".MAIN_DB_PREFIX."user as u";
+ $sql.= " WHERE rc.fk_soc = " . $object->id;
+ $sql.= " AND rc.entity = " . $conf->entity;
+ $sql.= " AND u.rowid = rc.fk_user_author";
+ $sql.= " ORDER BY rc.datec DESC";
- $resql=$db->query($sql);
- if ($resql)
- {
- print '
';
- $tag = !$tag;
- print '';
- print ''.$langs->trans("Date").' ';
- print ''.$langs->trans("CustomerRelativeDiscountShort").' ';
- print ''.$langs->trans("NoteReason").' ';
- print ''.$langs->trans("User").' ';
- print ' ';
- $num = $db->num_rows($resql);
- if ($num > 0)
- {
- $i = 0;
- while ($i < $num)
- {
- $obj = $db->fetch_object($resql);
- print '';
- print ''.dol_print_date($db->jdate($obj->dc),"dayhour").' ';
- print ''.price2num($obj->remise_percent).'% ';
- print ''.$obj->note.' ';
- print ''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.' ';
- print ' ';
- $i++;
- }
+ $resql=$db->query($sql);
+ if ($resql)
+ {
+ print '';
+ $tag = !$tag;
+ print '';
+ print ''.$langs->trans("Date").' ';
+ print ''.$langs->trans("CustomerRelativeDiscountShort").' ';
+ print ''.$langs->trans("NoteReason").' ';
+ print ''.$langs->trans("User").' ';
+ print ' ';
+ $num = $db->num_rows($resql);
+ if ($num > 0)
+ {
+ $i = 0;
+ while ($i < $num)
+ {
+ $obj = $db->fetch_object($resql);
+ print '';
+ print ''.dol_print_date($db->jdate($obj->dc),"dayhour").' ';
+ print ''.price2num($obj->remise_percent).'% ';
+ print ''.$obj->note.' ';
+ print ''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.' ';
+ print ' ';
+ $i++;
+ }
+ }
+ else
+ {
+ print ''.$langs->trans("None").' ';
+ }
+ $db->free($resql);
+ print "
";
}
else
{
- print ''.$langs->trans("None").' ';
- }
- $db->free($resql);
- print "
";
- }
- else
- {
- dol_print_error($db);
+ dol_print_error($db);
+ }
}
+ if($isSupplier) {
+ if($isCustomer) {
+ print '
'; // class="fichehalfleft"
+ print '
';
+ print '
';
+ print load_fiche_titre($langs->trans("SupplierDiscounts"), '', '');
+ }
+
+ /*
+ * List log of all supplier percent discounts
+ */
+ $sql = "SELECT rc.rowid, rc.remise_supplier as remise_percent, rc.note, rc.datec as dc,";
+ $sql.= " u.login, u.rowid as user_id";
+ $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise_supplier as rc, ".MAIN_DB_PREFIX."user as u";
+ $sql.= " WHERE rc.fk_soc = " . $object->id;
+ $sql.= " AND rc.entity = " . $conf->entity;
+ $sql.= " AND u.rowid = rc.fk_user_author";
+ $sql.= " ORDER BY rc.datec DESC";
+
+ $resql=$db->query($sql);
+ if ($resql)
+ {
+ print '
';
+ $tag = !$tag;
+ print '';
+ print ''.$langs->trans("Date").' ';
+ print ''.$langs->trans("CustomerRelativeDiscountShort").' ';
+ print ''.$langs->trans("NoteReason").' ';
+ print ''.$langs->trans("User").' ';
+ print ' ';
+ $num = $db->num_rows($resql);
+ if ($num > 0)
+ {
+ $i = 0;
+ while ($i < $num)
+ {
+ $obj = $db->fetch_object($resql);
+ print '';
+ print ''.dol_print_date($db->jdate($obj->dc),"dayhour").' ';
+ print ''.price2num($obj->remise_percent).'% ';
+ print ''.$obj->note.' ';
+ print ''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.' ';
+ print ' ';
+ $i++;
+ }
+ }
+ else
+ {
+ print ''.$langs->trans("None").' ';
+ }
+ $db->free($resql);
+ print "
";
+ }
+ else
+ {
+ dol_print_error($db);
+ }
+
+ if($isCustomer) {
+ print '
'; // class="ficheaddleft"
+ print '
'; // class="fichehalfright"
+ print '
'; // class="fichecenter"
+ }
+ }
}
llxFooter();
diff --git a/htdocs/comm/remx.php b/htdocs/comm/remx.php
index 0127b8f15be..3eec109e6b3 100644
--- a/htdocs/comm/remx.php
+++ b/htdocs/comm/remx.php
@@ -26,11 +26,11 @@
require '../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
+require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
-$langs->load("orders");
-$langs->load("bills");
-$langs->load("companies");
+// Load translation files required by the page
+$langs->loadLangs(array('orders', 'bills', 'companies'));
$id=GETPOST('id','int');
@@ -92,6 +92,12 @@ if ($action == 'confirm_split' && GETPOST("confirm") == 'yes')
$newdiscount2->fk_facture=$discount->fk_facture;
$newdiscount1->fk_facture_line=$discount->fk_facture_line;
$newdiscount2->fk_facture_line=$discount->fk_facture_line;
+ $newdiscount1->fk_invoice_supplier_source=$discount->fk_invoice_supplier_source;
+ $newdiscount2->fk_invoice_supplier_source=$discount->fk_invoice_supplier_source;
+ $newdiscount1->fk_invoice_supplier=$discount->fk_invoice_supplier;
+ $newdiscount2->fk_invoice_supplier=$discount->fk_invoice_supplier;
+ $newdiscount1->fk_invoice_supplier_line=$discount->fk_invoice_supplier_line;
+ $newdiscount2->fk_invoice_supplier_line=$discount->fk_invoice_supplier_line;
if ($discount->description == '(CREDIT_NOTE)' || $discount->description == '(DEPOSIT)')
{
$newdiscount1->description=$discount->description;
@@ -106,6 +112,8 @@ if ($action == 'confirm_split' && GETPOST("confirm") == 'yes')
$newdiscount2->fk_user=$discount->fk_user;
$newdiscount1->fk_soc=$discount->fk_soc;
$newdiscount2->fk_soc=$discount->fk_soc;
+ $newdiscount1->discount_type=$discount->discount_type;
+ $newdiscount2->discount_type=$discount->discount_type;
$newdiscount1->datec=$discount->datec;
$newdiscount2->datec=$discount->datec;
$newdiscount1->tva_tx=$discount->tva_tx;
@@ -143,6 +151,7 @@ if ($action == 'setremise' && $user->rights->societe->creer)
$amount_ht=GETPOST('amount_ht');
$desc=GETPOST('desc','alpha');
$tva_tx=GETPOST('tva_tx','alpha');
+ $discount_type=! empty($_POST['discount_type'])?GETPOST('discount_type','alpha'):0;
if (price2num($amount_ht) > 0)
{
@@ -157,7 +166,7 @@ if ($action == 'setremise' && $user->rights->societe->creer)
{
$soc = new Societe($db);
$soc->fetch($id);
- $discountid=$soc->set_remise_except($amount_ht,$user,$desc,$tva_tx);
+ $discountid=$soc->set_remise_except($amount_ht,$user,$desc,$tva_tx,$discount_type);
if ($discountid > 0)
{
@@ -215,6 +224,7 @@ if (GETPOST('action','aZ09') == 'confirm_remove' && GETPOST("confirm")=='yes')
$form=new Form($db);
$facturestatic=new Facture($db);
+$facturefournstatic=new FactureFournisseur($db);
llxHeader('',$langs->trans("GlobalDiscount"));
@@ -224,12 +234,14 @@ if ($socid > 0)
$object = new Societe($db);
$object->fetch($socid);
+ $isCustomer = $object->client == 1 || $object->client == 3;
+ $isSupplier = $object->fournisseur == 1;
+
/*
* Display tabs
*/
$head = societe_prepare_head($object);
-
print 'id.'">';
print ' ';
print ' ';
@@ -242,36 +254,85 @@ if ($socid > 0)
print '';
print '
';
+
+ if(! $isCustomer && ! $isSupplier) {
+ print '
'.$langs->trans('ThirdpartyIsNeitherCustomerNorClientSoCannotHaveDiscounts').'
';
+
+ dol_fiche_end();
+
+ print '';
+
+ llxFooter();
+ $db->close();
+ exit;
+ }
+
+
print '
';
- // Calcul avoirs en cours
- $remise_all=$remise_user=0;
- $sql = "SELECT SUM(rc.amount_ht) as amount, rc.fk_user";
- $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise_except as rc";
- $sql.= " WHERE rc.fk_soc = " . $object->id;
- $sql.= " AND rc.entity = " . $conf->entity;
- $sql.= " AND (fk_facture_line IS NULL AND fk_facture IS NULL)";
- $sql.= " GROUP BY rc.fk_user";
- $resql=$db->query($sql);
- if ($resql)
- {
- $obj = $db->fetch_object($resql);
- $remise_all+=$obj->amount;
- if ($obj->fk_user == $user->id) $remise_user+=$obj->amount;
- }
- else
- {
- dol_print_error($db);
+ if($isCustomer) { // Calcul avoirs client en cours
+ $remise_all=$remise_user=0;
+ $sql = "SELECT SUM(rc.amount_ht) as amount, rc.fk_user";
+ $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise_except as rc";
+ $sql.= " WHERE rc.fk_soc = " . $object->id;
+ $sql.= " AND rc.entity = " . $conf->entity;
+ $sql.= " AND discount_type = 0"; // Exclude supplier discounts
+ $sql.= " AND (fk_facture_line IS NULL AND fk_facture IS NULL)";
+ $sql.= " GROUP BY rc.fk_user";
+ $resql=$db->query($sql);
+ if ($resql)
+ {
+ $obj = $db->fetch_object($resql);
+ $remise_all+=$obj->amount;
+ if ($obj->fk_user == $user->id) $remise_user+=$obj->amount;
+ }
+ else
+ {
+ dol_print_error($db);
+ }
+
+ print ''.$langs->trans("CustomerAbsoluteDiscountAllUsers").' ';
+ print ''.$remise_all.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").' ';
+
+ if (! empty($user->fk_soc)) // No need to show this for external users
+ {
+ print ''.$langs->trans("CustomerAbsoluteDiscountMy").' ';
+ print ''.$remise_user.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").' ';
+ }
}
- print ''.$langs->trans("CustomerAbsoluteDiscountAllUsers").' ';
- print ''.$remise_all.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").' ';
-
- if (! empty($user->fk_soc)) // No need to show this for external users
- {
- print ''.$langs->trans("CustomerAbsoluteDiscountMy").' ';
- print ''.$remise_user.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").' ';
+ if($isSupplier) {
+ // Calcul avoirs fournisseur en cours
+ $remise_all=$remise_user=0;
+ $sql = "SELECT SUM(rc.amount_ht) as amount, rc.fk_user";
+ $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise_except as rc";
+ $sql.= " WHERE rc.fk_soc = " . $object->id;
+ $sql.= " AND rc.entity = " . $conf->entity;
+ $sql.= " AND discount_type = 1"; // Exclude customer discounts
+ $sql.= " AND (fk_invoice_supplier_line IS NULL AND fk_invoice_supplier IS NULL)";
+ $sql.= " GROUP BY rc.fk_user";
+ $resql=$db->query($sql);
+ if ($resql)
+ {
+ $obj = $db->fetch_object($resql);
+ $remise_all+=$obj->amount;
+ if ($obj->fk_user == $user->id) $remise_user+=$obj->amount;
+ }
+ else
+ {
+ dol_print_error($db);
+ }
+
+ print ''.$langs->trans("SupplierAbsoluteDiscountAllUsers").' ';
+ print ''.$remise_all.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").' ';
+
+ if (! empty($user->fk_soc)) // No need to show this for external users
+ {
+ print ''.$langs->trans("SupplierAbsoluteDiscountMy").' ';
+ print ''.$remise_user.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").' ';
+ }
}
+
print '
';
print '
';
@@ -283,7 +344,22 @@ if ($socid > 0)
print load_fiche_titre($langs->trans("NewGlobalDiscount"),'','');
print '
';
+
+ if($isCustomer && ! $isSupplier) {
+ print ' ';
+ }
+
+ if(! $isCustomer && $isSupplier) {
+ print ' ';
+ }
+
print '';
+ if($isCustomer && $isSupplier) {
+ print ''.$langs->trans('DiscountType').' ';
+ print ' '.$langs->trans('Customer').' ';
+ print ' '.$langs->trans('Supplier').' ';
+ print ' ';
+ }
print ''.$langs->trans("AmountHT").' ';
print ' ';
print ' '.$langs->trans("Currency".$conf->currency).' ';
@@ -321,132 +397,287 @@ if ($socid > 0)
print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&remid='.GETPOST('remid'), $langs->trans('RemoveDiscount'), $langs->trans('ConfirmRemoveDiscount'), 'confirm_remove', '', 0, 1);
}
+
/*
- * Liste remises fixes restant en cours (= liees a aucune facture ni ligne de facture)
+ * Liste remises fixes client restant en cours (= liees a aucune facture ni ligne de facture)
*/
- $sql = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,";
- $sql.= " rc.datec as dc, rc.description,";
- $sql.= " rc.fk_facture_source,";
- $sql.= " u.login, u.rowid as user_id,";
- $sql.= " fa.facnumber as ref, fa.type as type";
- $sql.= " FROM ".MAIN_DB_PREFIX."user as u, ".MAIN_DB_PREFIX."societe_remise_except as rc";
- $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fa ON rc.fk_facture_source = fa.rowid";
- $sql.= " WHERE rc.fk_soc = " . $object->id;
- $sql.= " AND rc.entity = " . $conf->entity;
- $sql.= " AND u.rowid = rc.fk_user";
- $sql.= " AND (rc.fk_facture_line IS NULL AND rc.fk_facture IS NULL)";
- $sql.= " ORDER BY rc.datec DESC";
+
+ print load_fiche_titre($langs->trans("DiscountStillRemaining"));
- $resql=$db->query($sql);
- if ($resql)
- {
- print load_fiche_titre($langs->trans("DiscountStillRemaining"));
- print '';
- print '';
- print ''.$langs->trans("Date").' '; // Need 120+ for format with AM/PM
- print ''.$langs->trans("ReasonDiscount").' ';
- print ''.$langs->trans("ConsumedBy").' ';
- print ''.$langs->trans("AmountHT").' ';
- print ''.$langs->trans("VATRate").' ';
- print ''.$langs->trans("AmountTTC").' ';
- print ''.$langs->trans("DiscountOfferedBy").' ';
- print ' ';
- print ' ';
+ if($isCustomer) {
+ if($isSupplier) {
+ print '';
+ print '
';
+ print load_fiche_titre($langs->trans("CustomerDiscounts"), '', '');
+ }
- $showconfirminfo=array();
-
- $i = 0;
- $num = $db->num_rows($resql);
- if ($num > 0)
+ $sql = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,";
+ $sql.= " rc.datec as dc, rc.description,";
+ $sql.= " rc.fk_facture_source,";
+ $sql.= " u.login, u.rowid as user_id,";
+ $sql.= " fa.facnumber as ref, fa.type as type";
+ $sql.= " FROM ".MAIN_DB_PREFIX."user as u, ".MAIN_DB_PREFIX."societe_remise_except as rc";
+ $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fa ON rc.fk_facture_source = fa.rowid";
+ $sql.= " WHERE rc.fk_soc = " . $object->id;
+ $sql.= " AND rc.entity = " . $conf->entity;
+ $sql.= " AND u.rowid = rc.fk_user";
+ $sql.= " AND rc.discount_type = 0"; // Eliminate supplier discounts
+ $sql.= " AND (rc.fk_facture_line IS NULL AND rc.fk_facture IS NULL)";
+ $sql.= " ORDER BY rc.datec DESC";
+
+ $resql=$db->query($sql);
+ if ($resql)
{
- while ($i < $num)
- {
- $obj = $db->fetch_object($resql);
-
- print '
';
- print ''.dol_print_date($db->jdate($obj->dc),'dayhour').' ';
- if (preg_match('/\(CREDIT_NOTE\)/',$obj->description))
- {
- print '';
- $facturestatic->id=$obj->fk_facture_source;
- $facturestatic->ref=$obj->ref;
- $facturestatic->type=$obj->type;
- print preg_replace('/\(CREDIT_NOTE\)/',$langs->trans("CreditNote"),$obj->description).' '.$facturestatic->getNomURl(1);
- print ' ';
- }
- elseif (preg_match('/\(DEPOSIT\)/',$obj->description))
- {
- print '';
- $facturestatic->id=$obj->fk_facture_source;
- $facturestatic->ref=$obj->ref;
- $facturestatic->type=$obj->type;
- print preg_replace('/\(DEPOSIT\)/',$langs->trans("InvoiceDeposit"),$obj->description).' '.$facturestatic->getNomURl(1);
- print ' ';
- }
- elseif (preg_match('/\(EXCESS RECEIVED\)/',$obj->description))
- {
- print '';
- $facturestatic->id=$obj->fk_facture_source;
- $facturestatic->ref=$obj->ref;
- $facturestatic->type=$obj->type;
- print preg_replace('/\(EXCESS RECEIVED\)/',$langs->trans("ExcessReceived"),$obj->description).' '.$facturestatic->getNomURl(1);
- print ' ';
- }
- else
- {
- print '';
- print $obj->description;
- print ' ';
- }
- print ''.$langs->trans("NotConsumed").' ';
- print ''.price($obj->amount_ht).' ';
- print ''.price2num($obj->tva_tx,'MU').'% ';
- print ''.price($obj->amount_ttc).' ';
- print '';
- print ''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.' ';
- print ' ';
- if ($user->rights->societe->creer || $user->rights->facture->creer)
- {
- print '';
- print 'id.'&action=split&remid='.$obj->rowid.($backtopage?'&backtopage='.urlencode($backtopage):'').'">'.img_split($langs->trans("SplitDiscount")).' ';
- print ' ';
- print 'id.'&action=remove&remid='.$obj->rowid.($backtopage?'&backtopage='.urlencode($backtopage):'').'">'.img_delete($langs->trans("RemoveDiscount")).' ';
- print ' ';
- }
- else print ' ';
- print ' ';
-
- if ($_GET["action"]=='split' && GETPOST('remid') == $obj->rowid)
- {
- $showconfirminfo['rowid']=$obj->rowid;
- $showconfirminfo['amount_ttc']=$obj->amount_ttc;
- }
- $i++;
- }
+ print '
';
+ print '';
+ print ''.$langs->trans("Date").' '; // Need 120+ for format with AM/PM
+ print ''.$langs->trans("ReasonDiscount").' ';
+ print ''.$langs->trans("ConsumedBy").' ';
+ print ''.$langs->trans("AmountHT").' ';
+ print ''.$langs->trans("VATRate").' ';
+ print ''.$langs->trans("AmountTTC").' ';
+ print ''.$langs->trans("DiscountOfferedBy").' ';
+ print ' ';
+ print ' ';
+
+ $showconfirminfo=array();
+
+ $i = 0;
+ $num = $db->num_rows($resql);
+ if ($num > 0)
+ {
+ while ($i < $num)
+ {
+ $obj = $db->fetch_object($resql);
+
+ print '';
+ print ''.dol_print_date($db->jdate($obj->dc),'dayhour').' ';
+ if (preg_match('/\(CREDIT_NOTE\)/',$obj->description))
+ {
+ print '';
+ $facturestatic->id=$obj->fk_facture_source;
+ $facturestatic->ref=$obj->ref;
+ $facturestatic->type=$obj->type;
+ print preg_replace('/\(CREDIT_NOTE\)/',$langs->trans("CreditNote"),$obj->description).' '.$facturestatic->getNomURl(1);
+ print ' ';
+ }
+ elseif (preg_match('/\(DEPOSIT\)/',$obj->description))
+ {
+ print '';
+ $facturestatic->id=$obj->fk_facture_source;
+ $facturestatic->ref=$obj->ref;
+ $facturestatic->type=$obj->type;
+ print preg_replace('/\(DEPOSIT\)/',$langs->trans("InvoiceDeposit"),$obj->description).' '.$facturestatic->getNomURl(1);
+ print ' ';
+ }
+ elseif (preg_match('/\(EXCESS RECEIVED\)/',$obj->description))
+ {
+ print '';
+ $facturestatic->id=$obj->fk_facture_source;
+ $facturestatic->ref=$obj->ref;
+ $facturestatic->type=$obj->type;
+ print preg_replace('/\(EXCESS RECEIVED\)/',$langs->trans("ExcessReceived"),$obj->description).' '.$facturestatic->getNomURl(1);
+ print ' ';
+ }
+ else
+ {
+ print '';
+ print $obj->description;
+ print ' ';
+ }
+ print ''.$langs->trans("NotConsumed").' ';
+ print ''.price($obj->amount_ht).' ';
+ print ''.price2num($obj->tva_tx,'MU').'% ';
+ print ''.price($obj->amount_ttc).' ';
+ print '';
+ print ''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.' ';
+ print ' ';
+ if ($user->rights->societe->creer || $user->rights->facture->creer)
+ {
+ print '';
+ print 'id.'&action=split&remid='.$obj->rowid.($backtopage?'&backtopage='.urlencode($backtopage):'').'">'.img_split($langs->trans("SplitDiscount")).' ';
+ print ' ';
+ print 'id.'&action=remove&remid='.$obj->rowid.($backtopage?'&backtopage='.urlencode($backtopage):'').'">'.img_delete($langs->trans("RemoveDiscount")).' ';
+ print ' ';
+ }
+ else print ' ';
+ print ' ';
+
+ if ($_GET["action"]=='split' && GETPOST('remid') == $obj->rowid)
+ {
+ $showconfirminfo['rowid']=$obj->rowid;
+ $showconfirminfo['amount_ttc']=$obj->amount_ttc;
+ }
+ $i++;
+ }
+ }
+ else
+ {
+ print ''.$langs->trans("None").' ';
+ }
+ $db->free($resql);
+ print "
";
+
+ if (count($showconfirminfo))
+ {
+ $amount1=price2num($showconfirminfo['amount_ttc']/2,'MT');
+ $amount2=($showconfirminfo['amount_ttc']-$amount1);
+ $formquestion=array(
+ 'text' => $langs->trans('TypeAmountOfEachNewDiscount'),
+ array('type' => 'text', 'name' => 'amount_ttc_1', 'label' => $langs->trans("AmountTTC").' 1', 'value' => $amount1, 'size' => '5'),
+ array('type' => 'text', 'name' => 'amount_ttc_2', 'label' => $langs->trans("AmountTTC").' 2', 'value' => $amount2, 'size' => '5')
+ );
+ $langs->load("dict");
+ print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&remid='.$showconfirminfo['rowid'].($backtopage?'&backtopage='.urlencode($backtopage):''), $langs->trans('SplitDiscount'), $langs->trans('ConfirmSplitDiscount',price($showconfirminfo['amount_ttc']),$langs->transnoentities("Currency".$conf->currency)), 'confirm_split', $formquestion, 0, 0);
+ }
}
else
{
- print '
'.$langs->trans("None").' ';
- }
- $db->free($resql);
- print "
";
-
- if (count($showconfirminfo))
- {
- $amount1=price2num($showconfirminfo['amount_ttc']/2,'MT');
- $amount2=($showconfirminfo['amount_ttc']-$amount1);
- $formquestion=array(
- 'text' => $langs->trans('TypeAmountOfEachNewDiscount'),
- array('type' => 'text', 'name' => 'amount_ttc_1', 'label' => $langs->trans("AmountTTC").' 1', 'value' => $amount1, 'size' => '5'),
- array('type' => 'text', 'name' => 'amount_ttc_2', 'label' => $langs->trans("AmountTTC").' 2', 'value' => $amount2, 'size' => '5')
- );
- $langs->load("dict");
- print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&remid='.$showconfirminfo['rowid'].($backtopage?'&backtopage='.urlencode($backtopage):''), $langs->trans('SplitDiscount'), $langs->trans('ConfirmSplitDiscount',price($showconfirminfo['amount_ttc']),$langs->transnoentities("Currency".$conf->currency)), 'confirm_split', $formquestion, 0, 0);
+ dol_print_error($db);
}
}
- else
- {
- dol_print_error($db);
+
+ if($isSupplier) {
+ if($isCustomer) {
+ print ''; // class="fichehalfleft"
+ print '';
+ print '
';
+ print load_fiche_titre($langs->trans("SupplierDiscounts"), '', '');
+ }
+
+ /*
+ * Liste remises fixes fournisseur restant en cours (= liees a aucune facture ni ligne de facture)
+ */
+ $sql = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,";
+ $sql.= " rc.datec as dc, rc.description,";
+ $sql.= " rc.fk_invoice_supplier_source,";
+ $sql.= " u.login, u.rowid as user_id,";
+ $sql.= " fa.ref, fa.type as type";
+ $sql.= " FROM ".MAIN_DB_PREFIX."user as u, ".MAIN_DB_PREFIX."societe_remise_except as rc";
+ $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture_fourn as fa ON rc.fk_invoice_supplier_source = fa.rowid";
+ $sql.= " WHERE rc.fk_soc = " . $object->id;
+ $sql.= " AND rc.entity = " . $conf->entity;
+ $sql.= " AND u.rowid = rc.fk_user";
+ $sql.= " AND rc.discount_type = 1"; // Eliminate customer discounts
+ $sql.= " AND (rc.fk_invoice_supplier IS NULL AND rc.fk_invoice_supplier_line IS NULL)";
+ $sql.= " ORDER BY rc.datec DESC";
+
+ $resql=$db->query($sql);
+ if ($resql)
+ {
+ print '
';
+ print '';
+ print ''.$langs->trans("Date").' '; // Need 120+ for format with AM/PM
+ print ''.$langs->trans("ReasonDiscount").' ';
+ print ''.$langs->trans("ConsumedBy").' ';
+ print ''.$langs->trans("AmountHT").' ';
+ print ''.$langs->trans("VATRate").' ';
+ print ''.$langs->trans("AmountTTC").' ';
+ print ''.$langs->trans("DiscountOfferedBy").' ';
+ print ' ';
+ print ' ';
+
+ $showconfirminfo=array();
+
+ $i = 0;
+ $num = $db->num_rows($resql);
+ if ($num > 0)
+ {
+ while ($i < $num)
+ {
+ $obj = $db->fetch_object($resql);
+
+ print '';
+ print ''.dol_print_date($db->jdate($obj->dc),'dayhour').' ';
+ if (preg_match('/\(CREDIT_NOTE\)/',$obj->description))
+ {
+ print '';
+ $facturefournstatic->id=$obj->fk_invoice_supplier_source;
+ $facturefournstatic->ref=$obj->ref;
+ $facturefournstatic->type=$obj->type;
+ print preg_replace('/\(CREDIT_NOTE\)/',$langs->trans("CreditNote"),$obj->description).' '.$facturefournstatic->getNomURl(1);
+ print ' ';
+ }
+ elseif (preg_match('/\(DEPOSIT\)/',$obj->description))
+ {
+ print '';
+ $facturefournstatic->id=$obj->fk_invoice_supplier_source;
+ $facturefournstatic->ref=$obj->ref;
+ $facturefournstatic->type=$obj->type;
+ print preg_replace('/\(DEPOSIT\)/',$langs->trans("InvoiceDeposit"),$obj->description).' '.$facturefournstatic->getNomURl(1);
+ print ' ';
+ }
+ elseif (preg_match('/\(EXCESS PAID\)/',$obj->description))
+ {
+ print '';
+ $facturefournstatic->id=$obj->fk_invoice_supplier_source;
+ $facturefournstatic->ref=$obj->ref;
+ $facturefournstatic->type=$obj->type;
+ print preg_replace('/\(EXCESS PAID\)/',$langs->trans("ExcessPaid"),$obj->description).' '.$facturefournstatic->getNomURl(1);
+ print ' ';
+ }
+ else
+ {
+ print '';
+ print $obj->description;
+ print ' ';
+ }
+ print ''.$langs->trans("NotConsumed").' ';
+ print ''.price($obj->amount_ht).' ';
+ print ''.price2num($obj->tva_tx,'MU').'% ';
+ print ''.price($obj->amount_ttc).' ';
+ print '';
+ print ''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.' ';
+ print ' ';
+ if ($user->rights->societe->creer || $user->rights->facture->creer)
+ {
+ print '';
+ print 'id.'&action=split&remid='.$obj->rowid.($backtopage?'&backtopage='.urlencode($backtopage):'').'">'.img_split($langs->trans("SplitDiscount")).' ';
+ print ' ';
+ print 'id.'&action=remove&remid='.$obj->rowid.($backtopage?'&backtopage='.urlencode($backtopage):'').'">'.img_delete($langs->trans("RemoveDiscount")).' ';
+ print ' ';
+ }
+ else print ' ';
+ print ' ';
+
+ if ($_GET["action"]=='split' && GETPOST('remid') == $obj->rowid)
+ {
+ $showconfirminfo['rowid']=$obj->rowid;
+ $showconfirminfo['amount_ttc']=$obj->amount_ttc;
+ }
+ $i++;
+ }
+ }
+ else
+ {
+ print ''.$langs->trans("None").' ';
+ }
+ $db->free($resql);
+ print "
";
+
+ if (count($showconfirminfo))
+ {
+ $amount1=price2num($showconfirminfo['amount_ttc']/2,'MT');
+ $amount2=($showconfirminfo['amount_ttc']-$amount1);
+ $formquestion=array(
+ 'text' => $langs->trans('TypeAmountOfEachNewDiscount'),
+ array('type' => 'text', 'name' => 'amount_ttc_1', 'label' => $langs->trans("AmountTTC").' 1', 'value' => $amount1, 'size' => '5'),
+ array('type' => 'text', 'name' => 'amount_ttc_2', 'label' => $langs->trans("AmountTTC").' 2', 'value' => $amount2, 'size' => '5')
+ );
+ $langs->load("dict");
+ print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&remid='.$showconfirminfo['rowid'].($backtopage?'&backtopage='.urlencode($backtopage):''), $langs->trans('SplitDiscount'), $langs->trans('ConfirmSplitDiscount',price($showconfirminfo['amount_ttc']),$langs->transnoentities("Currency".$conf->currency)), 'confirm_split', $formquestion, 0, 0);
+ }
+ }
+ else
+ {
+ dol_print_error($db);
+ }
+
+ if($isCustomer) {
+ print '
'; // class="ficheaddleft"
+ print '
'; // class="fichehalfright"
+ print ''; // class="fichecenter"
+ }
}
print ' ';
@@ -454,150 +685,317 @@ if ($socid > 0)
/*
* List discount consumed (=liees a une ligne de facture ou facture)
*/
+
+ print load_fiche_titre($langs->trans("DiscountAlreadyCounted"));
- // Remises liees a lignes de factures
- $sql = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,";
- $sql.= " rc.datec as dc, rc.description, rc.fk_facture_line, rc.fk_facture,";
- $sql.= " rc.fk_facture_source,";
- $sql.= " u.login, u.rowid as user_id,";
- $sql.= " f.rowid, f.facnumber,";
- $sql.= " fa.facnumber as ref, fa.type as type";
- $sql.= " FROM ".MAIN_DB_PREFIX."facture as f";
- $sql.= " , ".MAIN_DB_PREFIX."user as u";
- $sql.= " , ".MAIN_DB_PREFIX."facturedet as fc";
- $sql.= " , ".MAIN_DB_PREFIX."societe_remise_except as rc";
- $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fa ON rc.fk_facture_source = fa.rowid";
- $sql.= " WHERE rc.fk_soc =". $object->id;
- $sql.= " AND rc.fk_facture_line = fc.rowid";
- $sql.= " AND fc.fk_facture = f.rowid";
- $sql.= " AND rc.fk_user = u.rowid";
- $sql.= " ORDER BY dc DESC";
- //$sql.= " UNION ";
- // Remises liees a factures
- $sql2 = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,";
- $sql2.= " rc.datec as dc, rc.description, rc.fk_facture_line, rc.fk_facture,";
- $sql2.= " rc.fk_facture_source,";
- $sql2.= " u.login, u.rowid as user_id,";
- $sql2.= " f.rowid, f.facnumber,";
- $sql2.= " fa.facnumber as ref, fa.type as type";
- $sql2.= " FROM ".MAIN_DB_PREFIX."facture as f";
- $sql2.= " , ".MAIN_DB_PREFIX."user as u";
- $sql2.= " , ".MAIN_DB_PREFIX."societe_remise_except as rc";
- $sql2.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fa ON rc.fk_facture_source = fa.rowid";
- $sql2.= " WHERE rc.fk_soc =". $object->id;
- $sql2.= " AND rc.fk_facture = f.rowid";
- $sql2.= " AND rc.fk_user = u.rowid";
-
- $sql2.= " ORDER BY dc DESC";
-
- $resql=$db->query($sql);
- $resql2=null;
- if ($resql) $resql2=$db->query($sql2);
- if ($resql2)
- {
- print load_fiche_titre($langs->trans("DiscountAlreadyCounted"));
- print '';
- print '';
- print ''.$langs->trans("Date").' '; // Need 120+ for format with AM/PM
- print ''.$langs->trans("ReasonDiscount").' ';
- print ''.$langs->trans("ConsumedBy").' ';
- print ''.$langs->trans("AmountHT").' ';
- print ''.$langs->trans("VATRate").' ';
- print ''.$langs->trans("AmountTTC").' ';
- print ''.$langs->trans("Author").' ';
- print ' ';
- print ' ';
-
- $tab_sqlobj=array();
- $tab_sqlobjOrder=array();
- $num = $db->num_rows($resql);
- if ($num > 0)
- {
- for ($i = 0;$i < $num; $i++)
- {
- $sqlobj = $db->fetch_object($resql);
- $tab_sqlobj[] = $sqlobj;
- $tab_sqlobjOrder[]=$db->jdate($sqlobj->dc);
- }
+ if($isCustomer) {
+ if($isSupplier) {
+ print '';
+ print '
';
+ print load_fiche_titre($langs->trans("CustomerDiscounts"), '', '');
}
- $db->free($resql);
- $num = $db->num_rows($resql2);
- for ($i = 0;$i < $num;$i++)
+ // Remises liees a lignes de factures
+ $sql = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,";
+ $sql.= " rc.datec as dc, rc.description, rc.fk_facture_line, rc.fk_facture,";
+ $sql.= " rc.fk_facture_source,";
+ $sql.= " u.login, u.rowid as user_id,";
+ $sql.= " f.rowid, f.facnumber,";
+ $sql.= " fa.facnumber as ref, fa.type as type";
+ $sql.= " FROM ".MAIN_DB_PREFIX."facture as f";
+ $sql.= " , ".MAIN_DB_PREFIX."user as u";
+ $sql.= " , ".MAIN_DB_PREFIX."facturedet as fc";
+ $sql.= " , ".MAIN_DB_PREFIX."societe_remise_except as rc";
+ $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fa ON rc.fk_facture_source = fa.rowid";
+ $sql.= " WHERE rc.fk_soc =". $object->id;
+ $sql.= " AND rc.fk_facture_line = fc.rowid";
+ $sql.= " AND fc.fk_facture = f.rowid";
+ $sql.= " AND rc.fk_user = u.rowid";
+ $sql.= " AND rc.discount_type = 0"; // Eliminate supplier discounts
+ $sql.= " ORDER BY dc DESC";
+ //$sql.= " UNION ";
+ // Remises liees a factures
+ $sql2 = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,";
+ $sql2.= " rc.datec as dc, rc.description, rc.fk_facture_line, rc.fk_facture,";
+ $sql2.= " rc.fk_facture_source,";
+ $sql2.= " u.login, u.rowid as user_id,";
+ $sql2.= " f.rowid, f.facnumber,";
+ $sql2.= " fa.facnumber as ref, fa.type as type";
+ $sql2.= " FROM ".MAIN_DB_PREFIX."facture as f";
+ $sql2.= " , ".MAIN_DB_PREFIX."user as u";
+ $sql2.= " , ".MAIN_DB_PREFIX."societe_remise_except as rc";
+ $sql2.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fa ON rc.fk_facture_source = fa.rowid";
+ $sql2.= " WHERE rc.fk_soc =". $object->id;
+ $sql2.= " AND rc.fk_facture = f.rowid";
+ $sql2.= " AND rc.fk_user = u.rowid";
+ $sql2.= " AND rc.discount_type = 0"; // Eliminate supplier discounts
+ $sql2.= " ORDER BY dc DESC";
+
+ $resql=$db->query($sql);
+ $resql2=null;
+ if ($resql) $resql2=$db->query($sql2);
+ if ($resql2)
{
- $sqlobj = $db->fetch_object($resql2);
- $tab_sqlobj[] = $sqlobj;
- $tab_sqlobjOrder[]= $db->jdate($sqlobj->dc);
- }
- $db->free($resql2);
- array_multisort($tab_sqlobjOrder,SORT_DESC,$tab_sqlobj);
-
- $num = count($tab_sqlobj);
- if ($num > 0)
- {
- $i = 0 ;
- while ($i < $num )
- {
- $obj = array_shift($tab_sqlobj);
- print '
';
- print ''.dol_print_date($db->jdate($obj->dc),'dayhour').' ';
- if (preg_match('/\(CREDIT_NOTE\)/',$obj->description))
- {
- print '';
- $facturestatic->id=$obj->fk_facture_source;
- $facturestatic->ref=$obj->ref;
- $facturestatic->type=$obj->type;
- print preg_replace('/\(CREDIT_NOTE\)/',$langs->trans("CreditNote"),$obj->description).' '.$facturestatic->getNomURl(1);
- print ' ';
- }
- elseif (preg_match('/\(DEPOSIT\)/',$obj->description))
- {
- print '';
- $facturestatic->id=$obj->fk_facture_source;
- $facturestatic->ref=$obj->ref;
- $facturestatic->type=$obj->type;
- print preg_replace('/\(DEPOSIT\)/',$langs->trans("InvoiceDeposit"),$obj->description).' '.$facturestatic->getNomURl(1);
- print ' ';
- }
- elseif (preg_match('/\(EXCESS RECEIVED\)/',$obj->description))
- {
- print '';
- $facturestatic->id=$obj->fk_facture_source;
- $facturestatic->ref=$obj->ref;
- $facturestatic->type=$obj->type;
- print preg_replace('/\(EXCESS RECEIVED\)/',$langs->trans("Invoice"),$obj->description).' '.$facturestatic->getNomURl(1);
- print ' ';
- }
- else
- {
- print '';
- print $obj->description;
- print ' ';
- }
- print ''.img_object($langs->trans("ShowBill"),'bill').' '.$obj->facnumber.' ';
- print ''.price($obj->amount_ht).' ';
- print ''.price2num($obj->tva_tx,'MU').'% ';
- print ''.price($obj->amount_ttc).' ';
- print '';
- print ''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.' ';
- print ' ';
- print ' ';
- print ' ';
- $i++;
- }
+ print '
';
+ print '';
+ print ''.$langs->trans("Date").' '; // Need 120+ for format with AM/PM
+ print ''.$langs->trans("ReasonDiscount").' ';
+ print ''.$langs->trans("ConsumedBy").' ';
+ print ''.$langs->trans("AmountHT").' ';
+ print ''.$langs->trans("VATRate").' ';
+ print ''.$langs->trans("AmountTTC").' ';
+ print ''.$langs->trans("Author").' ';
+ print ' ';
+ print ' ';
+
+ $tab_sqlobj=array();
+ $tab_sqlobjOrder=array();
+ $num = $db->num_rows($resql);
+ if ($num > 0)
+ {
+ for ($i = 0;$i < $num; $i++)
+ {
+ $sqlobj = $db->fetch_object($resql);
+ $tab_sqlobj[] = $sqlobj;
+ $tab_sqlobjOrder[]=$db->jdate($sqlobj->dc);
+ }
+ }
+ $db->free($resql);
+
+ $num = $db->num_rows($resql2);
+ for ($i = 0;$i < $num;$i++)
+ {
+ $sqlobj = $db->fetch_object($resql2);
+ $tab_sqlobj[] = $sqlobj;
+ $tab_sqlobjOrder[]= $db->jdate($sqlobj->dc);
+ }
+ $db->free($resql2);
+ array_multisort($tab_sqlobjOrder,SORT_DESC,$tab_sqlobj);
+
+ $num = count($tab_sqlobj);
+ if ($num > 0)
+ {
+ $i = 0 ;
+ while ($i < $num )
+ {
+ $obj = array_shift($tab_sqlobj);
+ print '';
+ print ''.dol_print_date($db->jdate($obj->dc),'dayhour').' ';
+ if (preg_match('/\(CREDIT_NOTE\)/',$obj->description))
+ {
+ print '';
+ $facturestatic->id=$obj->fk_facture_source;
+ $facturestatic->ref=$obj->ref;
+ $facturestatic->type=$obj->type;
+ print preg_replace('/\(CREDIT_NOTE\)/',$langs->trans("CreditNote"),$obj->description).' '.$facturestatic->getNomURl(1);
+ print ' ';
+ }
+ elseif (preg_match('/\(DEPOSIT\)/',$obj->description))
+ {
+ print '';
+ $facturestatic->id=$obj->fk_facture_source;
+ $facturestatic->ref=$obj->ref;
+ $facturestatic->type=$obj->type;
+ print preg_replace('/\(DEPOSIT\)/',$langs->trans("InvoiceDeposit"),$obj->description).' '.$facturestatic->getNomURl(1);
+ print ' ';
+ }
+ elseif (preg_match('/\(EXCESS RECEIVED\)/',$obj->description))
+ {
+ print '';
+ $facturestatic->id=$obj->fk_facture_source;
+ $facturestatic->ref=$obj->ref;
+ $facturestatic->type=$obj->type;
+ print preg_replace('/\(EXCESS RECEIVED\)/',$langs->trans("Invoice"),$obj->description).' '.$facturestatic->getNomURl(1);
+ print ' ';
+ }
+ else
+ {
+ print '';
+ print $obj->description;
+ print ' ';
+ }
+ print ''.img_object($langs->trans("ShowBill"),'bill').' '.$obj->facnumber.' ';
+ print ''.price($obj->amount_ht).' ';
+ print ''.price2num($obj->tva_tx,'MU').'% ';
+ print ''.price($obj->amount_ttc).' ';
+ print '';
+ print ''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.' ';
+ print ' ';
+ print ' ';
+ print ' ';
+ $i++;
+ }
+ }
+ else
+ {
+ print ''.$langs->trans("None").' ';
+ }
+
+ print "
";
}
else
{
- print '
'.$langs->trans("None").' ';
+ dol_print_error($db);
+ }
+ }
+
+ if($isSupplier) {
+ if($isCustomer) {
+ print '
'; // class="fichehalfleft"
+ print '
';
+ print '
';
+ print load_fiche_titre($langs->trans("SupplierDiscounts"), '', '');
}
- print "
";
- }
- else
- {
- dol_print_error($db);
- }
+ // Remises liees a lignes de factures
+ $sql = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,";
+ $sql.= " rc.datec as dc, rc.description, rc.fk_invoice_supplier_line, rc.fk_invoice_supplier,";
+ $sql.= " rc.fk_invoice_supplier_source,";
+ $sql.= " u.login, u.rowid as user_id,";
+ $sql.= " f.rowid, f.ref as facnumber,";
+ $sql.= " fa.ref, fa.type as type";
+ $sql.= " FROM ".MAIN_DB_PREFIX."facture_fourn as f";
+ $sql.= " , ".MAIN_DB_PREFIX."user as u";
+ $sql.= " , ".MAIN_DB_PREFIX."facture_fourn_det as fc";
+ $sql.= " , ".MAIN_DB_PREFIX."societe_remise_except as rc";
+ $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture_fourn as fa ON rc.fk_invoice_supplier_source = fa.rowid";
+ $sql.= " WHERE rc.fk_soc =". $object->id;
+ $sql.= " AND rc.fk_invoice_supplier_line = fc.rowid";
+ $sql.= " AND fc.fk_facture_fourn = f.rowid";
+ $sql.= " AND rc.fk_user = u.rowid";
+ $sql.= " AND rc.discount_type = 1"; // Eliminate customer discounts
+ $sql.= " ORDER BY dc DESC";
+ //$sql.= " UNION ";
+ // Remises liees a factures
+ $sql2 = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,";
+ $sql2.= " rc.datec as dc, rc.description, rc.fk_invoice_supplier_line, rc.fk_invoice_supplier,";
+ $sql2.= " rc.fk_invoice_supplier_source,";
+ $sql2.= " u.login, u.rowid as user_id,";
+ $sql2.= " f.rowid, f.ref as facnumber,";
+ $sql2.= " fa.ref, fa.type as type";
+ $sql2.= " FROM ".MAIN_DB_PREFIX."facture_fourn as f";
+ $sql2.= " , ".MAIN_DB_PREFIX."user as u";
+ $sql2.= " , ".MAIN_DB_PREFIX."societe_remise_except as rc";
+ $sql2.= " LEFT JOIN ".MAIN_DB_PREFIX."facture_fourn as fa ON rc.fk_invoice_supplier_source = fa.rowid";
+ $sql2.= " WHERE rc.fk_soc =". $object->id;
+ $sql2.= " AND rc.fk_invoice_supplier = f.rowid";
+ $sql2.= " AND rc.fk_user = u.rowid";
+ $sql2.= " AND rc.discount_type = 1"; // Eliminate customer discounts
+ $sql2.= " ORDER BY dc DESC";
+
+ $resql=$db->query($sql);
+ $resql2=null;
+ if ($resql) $resql2=$db->query($sql2);
+ if ($resql2)
+ {
+ print '';
+ print '';
+ print ''.$langs->trans("Date").' '; // Need 120+ for format with AM/PM
+ print ''.$langs->trans("ReasonDiscount").' ';
+ print ''.$langs->trans("ConsumedBy").' ';
+ print ''.$langs->trans("AmountHT").' ';
+ print ''.$langs->trans("VATRate").' ';
+ print ''.$langs->trans("AmountTTC").' ';
+ print ''.$langs->trans("Author").' ';
+ print ' ';
+ print ' ';
+
+ $tab_sqlobj=array();
+ $tab_sqlobjOrder=array();
+ $num = $db->num_rows($resql);
+ if ($num > 0)
+ {
+ for ($i = 0;$i < $num; $i++)
+ {
+ $sqlobj = $db->fetch_object($resql);
+ $tab_sqlobj[] = $sqlobj;
+ $tab_sqlobjOrder[]=$db->jdate($sqlobj->dc);
+ }
+ }
+ $db->free($resql);
+
+ $num = $db->num_rows($resql2);
+ for ($i = 0;$i < $num;$i++)
+ {
+ $sqlobj = $db->fetch_object($resql2);
+ $tab_sqlobj[] = $sqlobj;
+ $tab_sqlobjOrder[]= $db->jdate($sqlobj->dc);
+ }
+ $db->free($resql2);
+ array_multisort($tab_sqlobjOrder,SORT_DESC,$tab_sqlobj);
+
+ $num = count($tab_sqlobj);
+ if ($num > 0)
+ {
+ $i = 0 ;
+ while ($i < $num )
+ {
+ $obj = array_shift($tab_sqlobj);
+ print '';
+ print ''.dol_print_date($db->jdate($obj->dc),'dayhour').' ';
+ if (preg_match('/\(CREDIT_NOTE\)/',$obj->description))
+ {
+ print '';
+ $facturefournstatic->id=$obj->fk_invoice_supplier_source;
+ $facturefournstatic->ref=$obj->ref;
+ $facturefournstatic->type=$obj->type;
+ print preg_replace('/\(CREDIT_NOTE\)/',$langs->trans("CreditNote"),$obj->description).' '.$facturefournstatic->getNomURl(1);
+ print ' ';
+ }
+ elseif (preg_match('/\(DEPOSIT\)/',$obj->description))
+ {
+ print '';
+ $facturefournstatic->id=$obj->fk_invoice_supplier_source;
+ $facturefournstatic->ref=$obj->ref;
+ $facturefournstatic->type=$obj->type;
+ print preg_replace('/\(DEPOSIT\)/',$langs->trans("InvoiceDeposit"),$obj->description).' '.$facturefournstatic->getNomURl(1);
+ print ' ';
+ }
+ elseif (preg_match('/\(EXCESS PAID\)/',$obj->description))
+ {
+ print '';
+ $facturefournstatic->id=$obj->fk_invoice_supplier_source;
+ $facturefournstatic->ref=$obj->ref;
+ $facturefournstatic->type=$obj->type;
+ print preg_replace('/\(EXCESS PAID\)/',$langs->trans("Invoice"),$obj->description).' '.$facturefournstatic->getNomURl(1);
+ print ' ';
+ }
+ else
+ {
+ print '';
+ print $obj->description;
+ print ' ';
+ }
+ print ''.img_object($langs->trans("ShowBill"),'bill').' '.$obj->facnumber.' ';
+ print ''.price($obj->amount_ht).' ';
+ print ''.price2num($obj->tva_tx,'MU').'% ';
+ print ''.price($obj->amount_ttc).' ';
+ print '';
+ print ''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.' ';
+ print ' ';
+ print ' ';
+ print ' ';
+ $i++;
+ }
+ }
+ else
+ {
+ print ''.$langs->trans("None").' ';
+ }
+
+ print "
";
+ }
+ else
+ {
+ dol_print_error($db);
+ }
+ if($isCustomer) {
+ print ''; // class="ficheaddleft"
+ print ''; // class="fichehalfright"
+ print ''; // class="fichecenter"
+ }
+ }
}
llxFooter();
diff --git a/htdocs/commande/card.php b/htdocs/commande/card.php
index 27fc1821a03..0fe49cf9f12 100644
--- a/htdocs/commande/card.php
+++ b/htdocs/commande/card.php
@@ -56,15 +56,8 @@ if (!empty($conf->variants->enabled)) {
require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php';
}
-$langs->load('orders');
-$langs->load('sendings');
-$langs->load('companies');
-$langs->load('bills');
-$langs->load('propal');
-$langs->load('deliveries');
-$langs->load('sendings');
-$langs->load('products');
-$langs->load('other');
+// Load translation files required by the page
+$langs->loadLangs(array('orders','sendings','companies','bills','propal','deliveries','products','other'));
if (!empty($conf->incoterm->enabled)) $langs->load('incoterm');
if (! empty($conf->margin->enabled)) $langs->load('margins');
if (! empty($conf->productbatch->enabled)) $langs->load("productbatch");
@@ -366,8 +359,7 @@ if (empty($reshook))
}
// Extrafields
- if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && method_exists($lines[$i], 'fetch_optionals')) // For avoid conflicts if
- // trigger used
+ if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && method_exists($lines[$i], 'fetch_optionals')) // For avoid conflicts if trigger used
{
$lines[$i]->fetch_optionals($lines[$i]->rowid);
$array_options = $lines[$i]->array_options;
@@ -376,7 +368,12 @@ if (empty($reshook))
$tva_tx = $lines[$i]->tva_tx;
if (! empty($lines[$i]->vat_src_code) && ! preg_match('/\(/', $tva_tx)) $tva_tx .= ' ('.$lines[$i]->vat_src_code.')';
- $result = $object->addline($desc, $lines[$i]->subprice, $lines[$i]->qty, $tva_tx, $lines[$i]->localtax1_tx, $lines[$i]->localtax2_tx, $lines[$i]->fk_product, $lines[$i]->remise_percent, $lines[$i]->info_bits, $lines[$i]->fk_remise_except, 'HT', 0, $date_start, $date_end, $product_type, $lines[$i]->rang, $lines[$i]->special_code, $fk_parent_line, $lines[$i]->fk_fournprice, $lines[$i]->pa_ht, $label, $array_options, $lines[$i]->fk_unit, $object->origin, $lines[$i]->rowid);
+ $result = $object->addline(
+ $desc, $lines[$i]->subprice, $lines[$i]->qty, $tva_tx, $lines[$i]->localtax1_tx, $lines[$i]->localtax2_tx, $lines[$i]->fk_product,
+ $lines[$i]->remise_percent, $lines[$i]->info_bits, $lines[$i]->fk_remise_except, 'HT', 0, $date_start, $date_end, $product_type,
+ $lines[$i]->rang, $lines[$i]->special_code, $fk_parent_line, $lines[$i]->fk_fournprice, $lines[$i]->pa_ht, $label, $array_options,
+ $lines[$i]->fk_unit, $object->origin, $lines[$i]->rowid
+ );
if ($result < 0) {
$error++;
@@ -806,7 +803,27 @@ if (empty($reshook))
// If price per quantity and customer
elseif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))
{
- // TODO Same than PRODUIT_CUSTOMER_PRICES_BY_QTY but using $object->thirdparty->price_level
+ if ($prod->prices_by_qty[$object->thirdparty->price_level]) // yes, this product has some prices per quantity
+ {
+ // Search the correct price into loaded array product_price_by_qty using id of array retrieved into POST['pqp'].
+ $pqp = GETPOST('pbq','int');
+ // Search price into product_price_by_qty from $prod->id
+ foreach($prod->prices_by_qty_list[$object->thirdparty->price_level] as $priceforthequantityarray)
+ {
+ if ($priceforthequantityarray['rowid'] != $pqp) continue;
+ // We found the price
+ if ($priceforthequantityarray['price_base_type'] == 'HT')
+ {
+ $pu_ht = $priceforthequantityarray['unitprice'];
+ }
+ else
+ {
+ $pu_ttc = $priceforthequantityarray['unitprice'];
+ }
+ // Note: the remise_percent or price by qty is used to set data on form, so we will use value from POST.
+ break;
+ }
+ }
}
$tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $tva_tx));
@@ -1027,8 +1044,8 @@ if (empty($reshook))
$type = $product->type;
$price_min = $product->price_min;
- if (! empty($conf->global->PRODUIT_MULTIPRICES) && ! empty($object->thirdparty->price_level))
- $price_min = $product->multiprices_min [$object->thirdparty->price_level];
+ if ((! empty($conf->global->PRODUIT_MULTIPRICES) || ! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && ! empty($object->thirdparty->price_level))
+ $price_min = $product->multiprices_min[$object->thirdparty->price_level];
$label = ((GETPOST('update_label') && GETPOST('product_label')) ? GETPOST('product_label') : '');
@@ -1269,31 +1286,25 @@ if (empty($reshook))
if ($action == 'update_extras')
{
+ $object->oldcopy = dol_clone($object);
+
// Fill array 'array_options' with data from update form
$extralabels = $extrafields->fetch_name_optionals_label($object->table_element);
- $ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute'));
+ $ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute','none'));
if ($ret < 0) $error++;
if (! $error)
{
- // Actions on extra fields (by external module or standard code)
- $hookmanager->initHooks(array('orderdao'));
- $parameters = array('id' => $object->id);
- $reshook = $hookmanager->executeHooks('insertExtraFields', $parameters, $object, $action); // Note that $action and $object may have been modified by
- // some hooks
- if (empty($reshook)) {
- $result = $object->insertExtraFields();
- if ($result < 0)
- {
- setEventMessages($object->error, $object->errors, 'errors');
- $error++;
- }
- } else if ($reshook < 0)
+ // Actions on extra fields
+ $result = $object->insertExtraFields('ORDER_MODIFY');
+ if ($result < 0)
+ {
+ setEventMessages($object->error, $object->errors, 'errors');
$error++;
+ }
}
- if ($error)
- $action = 'edit_extras';
+ if ($error) $action = 'edit_extras';
}
if ($action == 'set_thirdparty' && $user->rights->commande->creer)
@@ -1448,7 +1459,7 @@ if ($action == 'create' && $user->rights->commande->creer)
$ref_client = (! empty($objectsrc->ref_client) ? $objectsrc->ref_client : '');
$soc = $objectsrc->thirdparty;
- $cond_reglement_id = (!empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(!empty($soc->cond_reglement_id)?$soc->cond_reglement_id:1));
+ $cond_reglement_id = (!empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(!empty($soc->cond_reglement_id)?$soc->cond_reglement_id:0)); // TODO maybe add default value option
$mode_reglement_id = (!empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(!empty($soc->mode_reglement_id)?$soc->mode_reglement_id:0));
$fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0));
$availability_id = (!empty($objectsrc->availability_id)?$objectsrc->availability_id:(!empty($soc->availability_id)?$soc->availability_id:0));
@@ -1554,17 +1565,14 @@ if ($action == 'create' && $user->rights->commande->creer)
// Ligne info remises tiers
print '' . $langs->trans('Discounts') . ' ';
- if ($soc->remise_percent)
- print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent);
- else
- print $langs->trans("CompanyHasNoRelativeDiscount");
- print '. ';
+
$absolute_discount = $soc->getAvailableDiscounts();
- if ($absolute_discount)
- print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->trans("Currency" . $conf->currency));
- else
- print $langs->trans("CompanyHasNoAbsoluteDiscount");
- print '.';
+
+ $thirdparty = $soc;
+ $discount_type = 0;
+ $backtopage = urlencode($_SERVER["PHP_SELF"] . '?socid=' . $thirdparty->id . '&action=' . $action . '&origin=' . GETPOST('origin') . '&originid=' . GETPOST('originid'));
+ include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php';
+
print ' ';
}
// Date
@@ -1661,7 +1669,7 @@ if ($action == 'create' && $user->rights->commande->creer)
$parameters = array('objectsrc' => $objectsrc, 'socid'=>$socid);
$reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by
print $hookmanager->resPrint;
- if (empty($reshook) && ! empty($extrafields->attribute_label)) {
+ if (empty($reshook)) {
print $object->showOptionals($extrafields, 'edit');
}
@@ -1802,7 +1810,7 @@ if ($action == 'create' && $user->rights->commande->creer)
$author = new User($db);
$author->fetch($object->user_author_id);
- $res = $object->fetch_optionals($object->id, $extralabels);
+ $res = $object->fetch_optionals();
$head = commande_prepare_head($object);
dol_fiche_head($head, 'order', $langs->trans("CustomerOrder"), -1, 'order');
@@ -1954,7 +1962,6 @@ if ($action == 'create' && $user->rights->commande->creer)
// array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value'
// => 1),
array('type' => 'other','name' => 'socid','label' => $langs->trans("SelectThirdParty"),'value' => $form->select_company(GETPOST('socid', 'int'), 'socid', '(s.client=1 OR s.client=3)')));
- // Paiement incomplet. On demande si motif = escompte ou autre
$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('CloneOrder'), $langs->trans('ConfirmCloneOrder', $object->ref), 'confirm_clone', $formquestion, 'yes', 1);
}
@@ -1990,17 +1997,17 @@ if ($action == 'create' && $user->rights->commande->creer)
{
if ($action != 'classify')
$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : ';
- if ($action == 'classify') {
- //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
- $morehtmlref.='';
- $morehtmlref.=' ';
- $morehtmlref.=' ';
- $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
- $morehtmlref.=' ';
- $morehtmlref.=' ';
- } else {
- $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
- }
+ if ($action == 'classify') {
+ //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
+ $morehtmlref.='';
+ $morehtmlref.=' ';
+ $morehtmlref.=' ';
+ $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
+ $morehtmlref.=' ';
+ $morehtmlref.=' ';
+ } else {
+ $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
+ }
} else {
if (! empty($object->fk_project)) {
$proj = new Project($db);
@@ -2039,12 +2046,11 @@ if ($action == 'create' && $user->rights->commande->creer)
// Relative and absolute discounts
if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
- $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final
- // invoice
+ $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
$filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
} else {
- $filterabsolutediscount = "fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND description LIKE '(DEPOSIT)%')";
- $filtercreditnote = "fk_facture_source IS NOT NULL AND description NOT LIKE '(DEPOSIT)%'";
+ $filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')";
+ $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')";
}
$addrelativediscount = 'id . '">' . $langs->trans("EditRelativeDiscounts") . ' ';
@@ -2052,29 +2058,17 @@ if ($action == 'create' && $user->rights->commande->creer)
$addcreditnote = 'id . '">' . $langs->trans("AddCreditNote") . ' ';
print '' . $langs->trans('Discounts') . ' ';
- if ($soc->remise_percent)
- print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent);
- else
- print $langs->trans("CompanyHasNoRelativeDiscount");
- print '. ';
- $absolute_discount = $soc->getAvailableDiscounts('', 'fk_facture_source IS NULL');
- $absolute_creditnote = $soc->getAvailableDiscounts('', 'fk_facture_source IS NOT NULL');
+
+ $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount);
+ $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote);
$absolute_discount = price2num($absolute_discount, 'MT');
$absolute_creditnote = price2num($absolute_creditnote, 'MT');
- if ($absolute_discount) {
- if ($object->statut > Commande::STATUS_DRAFT) {
- print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency));
- } else {
- // Remise dispo de type remise fixe (not credit note)
- print ' ';
- $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?id=' . $object->id, 0, 'remise_id', $soc->id, $absolute_discount, $filterabsolutediscount, 0, '', 1);
- }
- }
- if ($absolute_creditnote) {
- print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)) . '. ';
- }
- if (! $absolute_discount && ! $absolute_creditnote)
- print $langs->trans("CompanyHasNoAbsoluteDiscount") . '.';
+
+ $thirdparty = $soc;
+ $discount_type = 0;
+ $backtopage = urlencode($_SERVER["PHP_SELF"] . '?id=' . $object->id);
+ include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php';
+
print ' ';
// Date
@@ -2301,12 +2295,15 @@ if ($action == 'create' && $user->rights->commande->creer)
$tmparray=$object->getTotalWeightVolume();
$totalWeight=$tmparray['weight'];
$totalVolume=$tmparray['volume'];
- if ($totalWeight || $totalVolume)
+ if ($totalWeight)
{
print ''.$langs->trans("CalculatedWeight").' ';
print '';
print showDimensionInBestUnit($totalWeight, 0, "weight", $langs, isset($conf->global->MAIN_WEIGHT_DEFAULT_ROUND)?$conf->global->MAIN_WEIGHT_DEFAULT_ROUND:-1, isset($conf->global->MAIN_WEIGHT_DEFAULT_UNIT)?$conf->global->MAIN_WEIGHT_DEFAULT_UNIT:'no');
print ' ';
+ }
+ if ($totalVolume)
+ {
print ''.$langs->trans("CalculatedVolume").' ';
print '';
print showDimensionInBestUnit($totalVolume, 0, "volume", $langs, isset($conf->global->MAIN_VOLUME_DEFAULT_ROUND)?$conf->global->MAIN_VOLUME_DEFAULT_ROUND:-1, isset($conf->global->MAIN_VOLUME_DEFAULT_UNIT)?$conf->global->MAIN_VOLUME_DEFAULT_UNIT:'no');
@@ -2389,8 +2386,12 @@ if ($action == 'create' && $user->rights->commande->creer)
}
// Total HT
+ $alert = '';
+ if($object->total_ht < $object->thirdparty->order_min_amount) {
+ $alert = ' ' . img_warning($langs->trans('OrderMinAmount').': '.price($object->thirdparty->order_min_amount));
+ }
print ' ' . $langs->trans('AmountHT') . ' ';
- print '' . price($object->total_ht, 1, '', 1, - 1, - 1, $conf->currency) . ' ';
+ print '' . price($object->total_ht, 1, '', 1, - 1, - 1, $conf->currency) . $alert . ' ';
// Total VAT
print '' . $langs->trans('AmountVAT') . ' ' . price($object->total_tva, 1, '', 1, - 1, - 1, $conf->currency) . ' ';
@@ -2467,7 +2468,7 @@ if ($action == 'create' && $user->rights->commande->creer)
/*
* Form to add new line
*/
- if ($object->statut == Commande::STATUS_DRAFT && $user->rights->commande->creer)
+ if ($object->statut == Commande::STATUS_DRAFT && $user->rights->commande->creer && $action != 'selectlines')
{
if ($action != 'editline')
{
@@ -2498,9 +2499,9 @@ if ($action == 'create' && $user->rights->commande->creer)
// Send
if ($object->statut > Commande::STATUS_DRAFT) {
if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->commande->order_advance->send)) {
- print '';
+ print '';
} else
- print '';
+ print '';
}
// Valid
@@ -2639,9 +2640,8 @@ if ($action == 'create' && $user->rights->commande->creer)
$somethingshown = $form->showLinkedObjectBlock($object, $linktoelem);
// Show online payment link
- //$useonlinepayment = (! empty($conf->paypal->enabled) || ! empty($conf->stripe->enabled) || ! empty($conf->paybox->enabled));
- $useonlinepayment = $conf->global->ORDER_SHOW_ONLINE_PAYMENT_ON_ORDER;
-
+ $useonlinepayment = (! empty($conf->paypal->enabled) || ! empty($conf->stripe->enabled) || ! empty($conf->paybox->enabled));
+ if (! empty($conf->global->ORDER_HIDE_ONLINE_PAYMENT_ON_ORDER)) $useonlinepayment = 0;
if ($object->statut != Commande::STATUS_DRAFT && $useonlinepayment)
{
print ' ';
diff --git a/htdocs/commande/class/api_orders.class.php b/htdocs/commande/class/api_orders.class.php
index cbd505a41b8..e52da47e11b 100644
--- a/htdocs/commande/class/api_orders.class.php
+++ b/htdocs/commande/class/api_orders.class.php
@@ -76,9 +76,11 @@ class Orders extends DolibarrApi
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
- $this->commande->fetchObjectLinked();
+ // Add external contacts ids
+ $this->commande->contacts_ids = $this->commande->liste_contact(-1,'external',1);
+ $this->commande->fetchObjectLinked();
return $this->_cleanObjectDatas($this->commande);
- }
+ }
@@ -159,6 +161,8 @@ class Orders extends DolibarrApi
$obj = $db->fetch_object($result);
$commande_static = new Commande($db);
if($commande_static->fetch($obj->rowid)) {
+ // Add external contacts ids
+ $commande_static->contacts_ids = $commande_static->liste_contact(-1,'external',1);
$obj_ret[] = $this->_cleanObjectDatas($commande_static);
}
$i++;
@@ -179,7 +183,7 @@ class Orders extends DolibarrApi
* @param array $request_data Request data
* @return int ID of order
*/
- function post($request_data = NULL)
+ function post($request_data = null)
{
if(! DolibarrApiAccess::$user->rights->commande->creer) {
throw new RestException(401, "Insuffisant rights");
@@ -245,7 +249,7 @@ class Orders extends DolibarrApi
*
* @return int
*/
- function postLine($id, $request_data = NULL) {
+ function postLine($id, $request_data = null) {
if(! DolibarrApiAccess::$user->rights->commande->creer) {
throw new RestException(401);
}
@@ -308,7 +312,7 @@ class Orders extends DolibarrApi
*
* @return object
*/
- function putLine($id, $lineid, $request_data = NULL) {
+ function putLine($id, $lineid, $request_data = null) {
if(! DolibarrApiAccess::$user->rights->commande->creer) {
throw new RestException(401);
}
@@ -402,7 +406,7 @@ class Orders extends DolibarrApi
*
* @return int
*/
- function put($id, $request_data = NULL) {
+ function put($id, $request_data = null) {
if (! DolibarrApiAccess::$user->rights->commande->creer) {
throw new RestException(401);
}
diff --git a/htdocs/commande/class/commande.class.php b/htdocs/commande/class/commande.class.php
index 9007490d421..ecd2be95d7a 100644
--- a/htdocs/commande/class/commande.class.php
+++ b/htdocs/commande/class/commande.class.php
@@ -10,6 +10,7 @@
* Copyright (C) 2013 Florian Henry
* Copyright (C) 2014-2015 Marcos García
* Copyright (C) 2016-2017 Ferran Marcet
+ * Copyright (C) 2018 Nicolas ZABOURI
*
* 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
@@ -79,10 +80,9 @@ class Commande extends CommonOrder
*/
public $statut;
/**
- * @deprecated
- * @see billed
+ * Billed
+ * @var int
*/
- public $facturee;
public $billed; // billed or not
public $brouillon;
@@ -545,7 +545,6 @@ class Commande extends CommonOrder
{
$this->statut = self::STATUS_VALIDATED;
$this->billed = 0;
- $this->facturee = 0; // deprecated
$this->db->commit();
return 1;
@@ -825,7 +824,7 @@ class Commande extends CommonOrder
$line = $this->lines[$i];
// Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
- //if (! is_object($line)) $line=json_decode(json_encode($line), FALSE); // convert recursively array into object.
+ //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
if (! is_object($line)) $line = (object) $line;
// Reset fk_parent_line for no child products and special product
@@ -1024,7 +1023,7 @@ class Commande extends CommonOrder
// get lines so they will be clone
foreach($this->lines as $line)
- $line->fetch_optionals($line->rowid);
+ $line->fetch_optionals();
// Load source object
$objFrom = clone $this;
@@ -1073,11 +1072,6 @@ class Commande extends CommonOrder
$reshook=$hookmanager->executeHooks('createFrom',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) $error++;
}
-
- // Call trigger
- $result=$this->call_trigger('ORDER_CLONE',$user);
- if ($result < 0) $error++;
- // End call triggers
}
unset($this->context['createfromclone']);
@@ -1150,7 +1144,7 @@ class Commande extends CommonOrder
$line->marque_tx = $marginInfos[2];
// get extrafields from original line
- $object->lines[$i]->fetch_optionals($object->lines[$i]->rowid);
+ $object->lines[$i]->fetch_optionals();
foreach($object->lines[$i]->array_options as $options_key => $value)
$line->array_options[$options_key] = $value;
@@ -1264,7 +1258,10 @@ class Commande extends CommonOrder
{
global $mysoc, $conf, $langs, $user;
- dol_syslog(get_class($this)."::addline commandeid=$this->id, desc=$desc, pu_ht=$pu_ht, qty=$qty, txtva=$txtva, fk_product=$fk_product, remise_percent=$remise_percent, info_bits=$info_bits, fk_remise_except=$fk_remise_except, price_base_type=$price_base_type, pu_ttc=$pu_ttc, date_start=$date_start, date_end=$date_end, type=$type special_code=$special_code, fk_unit=$fk_unit, origin=$origin, origin_id=$origin_id, pu_ht_devise=$pu_ht_devise", LOG_DEBUG);
+ $logtext = "::addline commandeid=$this->id, desc=$desc, pu_ht=$pu_ht, qty=$qty, txtva=$txtva, fk_product=$fk_product, remise_percent=$remise_percent";
+ $logtext.= ", info_bits=$info_bits, fk_remise_except=$fk_remise_except, price_base_type=$price_base_type, pu_ttc=$pu_ttc, date_start=$date_start";
+ $logtext.= ", date_end=$date_end, type=$type special_code=$special_code, fk_unit=$fk_unit, origin=$origin, origin_id=$origin_id, pu_ht_devise=$pu_ht_devise";
+ dol_syslog(get_class($this).$logtext, LOG_DEBUG);
include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
@@ -1538,8 +1535,8 @@ class Commande extends CommonOrder
{
$prod = new Product($this->db);
$prod->fetch($idproduct);
- $prod -> get_sousproduits_arbo ();
- $prods_arbo = $prod->get_each_prod();
+ $prod -> get_sousproduits_arbo();
+ $prods_arbo = $prod->get_arbo_each_prod();
if(count($prods_arbo) > 0)
{
foreach($prods_arbo as $key => $value)
@@ -1589,13 +1586,15 @@ class Commande extends CommonOrder
$sql.= ', ca.code as availability_code, ca.label as availability_label';
$sql.= ', dr.code as demand_reason_code';
$sql.= ' FROM '.MAIN_DB_PREFIX.'commande as c';
- $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON c.fk_cond_reglement = cr.rowid AND cr.entity IN ('.getEntity('c_payment_term').')';
- $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON c.fk_mode_reglement = p.id AND p.entity IN ('.getEntity('c_paiement').')';
+ $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON c.fk_cond_reglement = cr.rowid';
+ $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON c.fk_mode_reglement = p.id';
$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_availability as ca ON c.fk_availability = ca.rowid';
$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON c.fk_input_reason = ca.rowid';
$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON c.fk_incoterms = i.rowid';
- $sql.= " WHERE c.entity IN (".getEntity('commande').")";
- if ($id) $sql.= " AND c.rowid=".$id;
+
+ if ($id) $sql.= " WHERE c.rowid=".$id;
+ else $sql.= " WHERE c.entity IN (".getEntity('commande').")"; // Dont't use entity if you use rowid
+
if ($ref) $sql.= " AND c.ref='".$this->db->escape($ref)."'";
if ($ref_ext) $sql.= " AND c.ref_ext='".$this->db->escape($ref_ext)."'";
if ($ref_int) $sql.= " AND c.ref_int='".$this->db->escape($ref_int)."'";
@@ -1630,7 +1629,6 @@ class Commande extends CommonOrder
$this->remise_percent = $obj->remise_percent;
$this->remise_absolue = $obj->remise_absolue;
$this->source = $obj->source;
- $this->facturee = $obj->billed; // deprecated
$this->billed = $obj->billed;
$this->note = $obj->note_private; // deprecated
$this->note_private = $obj->note_private;
@@ -1675,12 +1673,9 @@ class Commande extends CommonOrder
if ($this->statut == self::STATUS_DRAFT) $this->brouillon = 1;
- // Retrieve all extrafields for invoice
+ // Retreive all extrafield
// fetch optionals attributes and labels
- require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
- $extrafields=new ExtraFields($this->db);
- $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true);
- $this->fetch_optionals($this->id,$extralabels);
+ $this->fetch_optionals();
$this->db->free($result);
@@ -2710,7 +2705,6 @@ class Commande extends CommonOrder
if (! $error)
{
$this->oldcopy= clone $this;
- $this->facturee=1; // deprecated
$this->billed=1;
}
@@ -2746,21 +2740,6 @@ class Commande extends CommonOrder
}
}
- /**
- * Classify the order as invoiced
- *
- * @return int <0 if ko, >0 if ok
- * @deprecated
- * @see classifyBilled()
- */
- function classer_facturee()
- {
- global $user;
- dol_syslog(__METHOD__ . " is deprecated", LOG_WARNING);
-
- return $this->classifyBilled($user);
- }
-
/**
* Classify the order as not invoiced
*
@@ -2782,7 +2761,6 @@ class Commande extends CommonOrder
if (! $error)
{
$this->oldcopy= clone $this;
- $this->facturee=1; // deprecated
$this->billed=1;
}
@@ -2793,7 +2771,6 @@ class Commande extends CommonOrder
if (! $error)
{
- $this->facturee=0; // deprecated
$this->billed=0;
$this->db->commit();
@@ -3090,17 +3067,23 @@ class Commande extends CommonOrder
$error++; $this->errors[]="Error ".$this->db->lasterror();
}
- if (! $error)
+ if (! $error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options)>0)
{
- if (! $notrigger)
+ $result=$this->insertExtraFields();
+ if ($result < 0)
{
- // Call trigger
- $result=$this->call_trigger('ORDER_MODIFY', $user);
- if ($result < 0) $error++;
- // End call triggers
+ $error++;
}
}
+ if (! $error && ! $notrigger)
+ {
+ // Call trigger
+ $result=$this->call_trigger('ORDER_MODIFY', $user);
+ if ($result < 0) $error++;
+ // End call triggers
+ }
+
// Commit or rollback
if ($error)
{
@@ -3329,7 +3312,6 @@ class Commande extends CommonOrder
*/
function getLibStatut($mode)
{
- if ($this->facturee && empty($this->billed)) $this->billed=$this->facturee; // For backward compatibility
return $this->LibStatut($this->statut, $this->billed, $mode);
}
@@ -3704,9 +3686,10 @@ class Commande extends CommonOrder
* @param int $hidedetails Hide details of lines
* @param int $hidedesc Hide description
* @param int $hideref Hide ref
+ * @param null|array $moreparams Array to provide more information
* @return int 0 if KO, 1 if OK
*/
- public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0)
+ public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
{
global $conf,$langs;
@@ -3725,7 +3708,7 @@ class Commande extends CommonOrder
$modelpath = "core/modules/commande/doc/";
- return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
+ return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
}
@@ -4240,7 +4223,7 @@ class OrderLine extends CommonOrderLine
}
}
- if (! $notrigger)
+ if (! $error && ! $notrigger)
{
// Call trigger
$result=$this->call_trigger('LINEORDER_UPDATE',$user);
diff --git a/htdocs/commande/contact.php b/htdocs/commande/contact.php
index 0eb4ed2cd63..7669239134a 100644
--- a/htdocs/commande/contact.php
+++ b/htdocs/commande/contact.php
@@ -32,9 +32,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
-$langs->load("orders");
-$langs->load("sendings");
-$langs->load("companies");
+// Load translation files required by the page
+$langs->loadLangs(array('orders', 'sendings', 'companies'));
$id=GETPOST('id','int');
$ref=GETPOST('ref','alpha');
diff --git a/htdocs/commande/customer.php b/htdocs/commande/customer.php
index 205efc3ad91..9263ceb3f45 100644
--- a/htdocs/commande/customer.php
+++ b/htdocs/commande/customer.php
@@ -42,8 +42,8 @@ if ($user->societe_id > 0)
if (! $user->rights->facture->creer)
accessforbidden();
-$langs->load("companies");
-$langs->load("orders");
+// Load translation files required by the page
+$langs->loadLangs(array("companies", "orders"));
$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit;
$sortfield = GETPOST("sortfield",'alpha');
@@ -102,6 +102,12 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
{
$result = $db->query($sql);
$nbtotalofrecords = $db->num_rows($result);
+
+ if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0
+ {
+ $page = 0;
+ $offset = 0;
+ }
}
$sql.= $db->plimit($limit + 1, $offset);
@@ -149,14 +155,10 @@ if ($resql)
print "\n";
- $var=true;
-
while ($i < min($num,$limit))
{
$obj = $db->fetch_object($resql);
-
-
print '';
print '';
diff --git a/htdocs/commande/document.php b/htdocs/commande/document.php
index ee688bed307..ffebbaa260a 100644
--- a/htdocs/commande/document.php
+++ b/htdocs/commande/document.php
@@ -36,9 +36,8 @@ if (! empty($conf->projet->enabled)) {
require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
}
-
-$langs->load('companies');
-$langs->load('other');
+// Load translation files required by the page
+$langs->loadLangs(array('companies', 'other'));
$action = GETPOST('action','aZ09');
$confirm = GETPOST('confirm');
@@ -69,6 +68,7 @@ $object = new Commande($db);
/*
* Actions
*/
+
if ($object->fetch($id))
{
$object->fetch_thirdparty();
@@ -163,7 +163,7 @@ if ($id > 0 || ! empty($ref))
print '';
print ''.$langs->trans("NbOfAttachedFiles").' '.count($filearray).' ';
- print ''.$langs->trans("TotalSizeOfAttachedFiles").' '.$totalsize.' '.$langs->trans("bytes").' ';
+ print ''.$langs->trans("TotalSizeOfAttachedFiles").' '.dol_print_size($totalsize,1,1).' ';
print "
\n";
diff --git a/htdocs/commande/index.php b/htdocs/commande/index.php
index feacdd70b07..5cfb87c7a25 100644
--- a/htdocs/commande/index.php
+++ b/htdocs/commande/index.php
@@ -31,8 +31,8 @@ require_once DOL_DOCUMENT_ROOT .'/commande/class/commande.class.php';
if (!$user->rights->commande->lire) accessforbidden();
-$langs->load("orders");
-$langs->load("bills");
+// Load translation files required by the page
+$langs->loadLangs(array('orders', 'bills'));
// Security check
$socid=GETPOST('socid','int');
diff --git a/htdocs/commande/info.php b/htdocs/commande/info.php
index 518ab856474..4bac4a3a447 100644
--- a/htdocs/commande/info.php
+++ b/htdocs/commande/info.php
@@ -33,8 +33,8 @@ if (! empty($conf->projet->enabled)) {
if (!$user->rights->commande->lire) accessforbidden();
-$langs->load("orders");
-$langs->load("sendings");
+// Load translation files required by the page
+$langs->loadLangs(array('orders', 'sendings'));
$socid=0;
$comid = GETPOST("id",'int');
diff --git a/htdocs/commande/list.php b/htdocs/commande/list.php
index 04ef69b2638..3734ab18a93 100644
--- a/htdocs/commande/list.php
+++ b/htdocs/commande/list.php
@@ -44,6 +44,7 @@ require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
+// Load translation files required by the page
$langs->loadLangs(array("orders",'sendings','deliveries','companies','compta','bills'));
$action=GETPOST('action','aZ09');
@@ -51,6 +52,7 @@ $massaction=GETPOST('massaction','alpha');
$show_files=GETPOST('show_files','int');
$confirm=GETPOST('confirm','alpha');
$toselect = GETPOST('toselect', 'array');
+$contextpage=GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'orderlist';
$search_orderyear=GETPOST("search_orderyear","int");
$search_ordermonth=GETPOST("search_ordermonth","int");
@@ -72,6 +74,7 @@ $socid=GETPOST('socid','int');
$search_user=GETPOST('search_user','int');
$search_sale=GETPOST('search_sale','int');
$search_total_ht=GETPOST('search_total_ht','alpha');
+$search_categ_cus=trim(GETPOST("search_categ_cus",'int'));
$optioncss = GETPOST('optioncss','alpha');
$billed = GETPOST('billed','int');
$viewstatut=GETPOST('viewstatut');
@@ -98,11 +101,9 @@ $pagenext = $page + 1;
if (! $sortfield) $sortfield='c.ref';
if (! $sortorder) $sortorder='DESC';
-// Initialize technical object to manage context to save list fields
-$contextpage=GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'orderlist';
-
// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
-$hookmanager->initHooks(array($contextpage));
+$object = new Commande($db);
+$hookmanager->initHooks(array('orderlist'));
$extrafields = new ExtraFields($db);
// fetch optionals attributes and labels
@@ -197,6 +198,7 @@ if (empty($reshook))
$billed='';
$toselect='';
$search_array_options=array();
+ $search_categ_cus=0;
}
if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')
|| GETPOST('button_search_x','alpha') || GETPOST('button_search.x','alpha') || GETPOST('button_search','alpha'))
@@ -212,6 +214,7 @@ if (empty($reshook))
$uploaddir = $conf->commande->dir_output;
$trigger_name='ORDER_SENTBYMAIL';
include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';
+
}
@@ -241,6 +244,8 @@ $sql.= ' c.rowid, c.ref, c.total_ht, c.tva as total_tva, c.total_ttc, c.ref_clie
$sql.= ' c.date_valid, c.date_commande, c.note_private, c.date_livraison as date_delivery, c.fk_statut, c.facture as billed,';
$sql.= ' c.date_creation as date_creation, c.tms as date_update,';
$sql.= " p.rowid as project_id, p.ref as project_ref";
+if ($search_categ_cus) $sql .= ", cc.fk_categorie, cc.fk_soc";
+
// Add fields from extrafields
foreach ($extrafields->attribute_label as $key => $val) $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key.' as options_'.$key : '');
// Add fields from hooks
@@ -251,6 +256,7 @@ $sql.= ' FROM '.MAIN_DB_PREFIX.'societe as s';
$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as country on (country.rowid = s.fk_pays)";
$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_typent as typent on (typent.id = s.fk_typent)";
$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as state on (state.rowid = s.fk_departement)";
+if (! empty($search_categ_cus)) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_societe as cc ON s.rowid = cc.fk_soc"; // We'll need this table joined to the select in order to filter by categ
$sql.= ', '.MAIN_DB_PREFIX.'commande as c';
if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."commande_extrafields as ef on (c.rowid = ef.fk_object)";
if ($sall || $search_product_category > 0) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'commandedet as pd ON c.rowid=pd.fk_commande';
@@ -331,6 +337,8 @@ if ($search_sale > 0) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$sear
if ($search_user > 0) $sql.= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='commande' AND tc.source='internal' AND ec.element_id = c.rowid AND ec.fk_socpeople = ".$search_user;
if ($search_total_ht != '') $sql.= natural_search('c.total_ht', $search_total_ht, 1);
if ($search_project_ref != '') $sql.= natural_search("p.ref",$search_project_ref);
+if ($search_categ_cus > 0) $sql.= " AND cc.fk_categorie = ".$db->escape($search_categ_cus);
+if ($search_categ_cus == -2) $sql.= " AND cc.fk_categorie IS NULL";
// Add where from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
// Add where from hooks
@@ -346,6 +354,12 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
{
$result = $db->query($sql);
$nbtotalofrecords = $db->num_rows($result);
+
+ if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0
+ {
+ $page = 0;
+ $offset = 0;
+ }
}
$sql.= $db->plimit($limit + 1,$offset);
@@ -408,12 +422,13 @@ if ($resql)
if ($search_total_vat != '') $param.='&search_total_vat='.urlencode($search_total_vat);
if ($search_total_ttc != '') $param.='&search_total_ttc='.urlencode($search_total_ttc);
if ($search_project_ref >= 0) $param.="&search_project_ref=".urlencode($search_project_ref);
- if ($search_town != '') $param .= '&search_town='.urlencode($search_town);
- if ($search_zip != '') $param .= '&search_zip='.urlencode($search_zip);
- if ($search_state != '') $param .= '&search_state='.urlencode($search_state);
- if ($search_country != '') $param .= '&search_country='.urlencode($search_country);
- if ($search_type_thirdparty != '') $param .= '&search_type_thirdparty='.urlencode($search_type_thirdparty);
- if ($search_product_category != '') $param .= '&search_product_category='.urlencode($search_product_category);
+ if ($search_town != '') $param.='&search_town='.urlencode($search_town);
+ if ($search_zip != '') $param.='&search_zip='.urlencode($search_zip);
+ if ($search_state != '') $param.='&search_state='.urlencode($search_state);
+ if ($search_country != '') $param.='&search_country='.urlencode($search_country);
+ if ($search_type_thirdparty != '') $param.='&search_type_thirdparty='.urlencode($search_type_thirdparty);
+ if ($search_product_category != '') $param.='&search_product_category='.urlencode($search_product_category);
+ if ($search_categ_cus > 0) $param.='&search_categ_cus='.urlencode($search_categ_cus);
if ($show_files) $param.='&show_files=' .urlencode($show_files);
if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss);
if ($billed != '') $param.='&billed='.urlencode($billed);
@@ -425,12 +440,22 @@ if ($resql)
$arrayofmassactions = array(
'presend'=>$langs->trans("SendByMail"),
'builddoc'=>$langs->trans("PDFMerge"),
+ 'cancelorders'=>$langs->trans("Cancel"),
+
);
if($user->rights->facture->creer) $arrayofmassactions['createbills']=$langs->trans("CreateInvoiceForThisCustomer");
if ($user->rights->commande->supprimer) $arrayofmassactions['predelete']=$langs->trans("Delete");
if (in_array($massaction, array('presend','predelete','createbills'))) $arrayofmassactions=array();
$massactionbutton=$form->selectMassAction('', $arrayofmassactions);
+ $newcardbutton='';
+ if ($contextpage == 'orderlist' && $user->rights->commande->creer)
+ {
+ $newcardbutton=''.$langs->trans('NewOrder').' ';
+ $newcardbutton.= ' ';
+ $newcardbutton.= ' ';
+ }
+
// Lines of title fields
print '';
if ($optioncss != '') print ' ';
@@ -443,7 +468,7 @@ if ($resql)
print ' ';
print ' ';
- print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_commercial.png', 0, '', '', $limit);
+ print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_commercial.png', 0, $newcardbutton, '', $limit);
$topicmail="SendOrderRef";
$modelmail="order_send";
@@ -487,7 +512,7 @@ if ($resql)
{
print $form->selectyesno('valdate_invoices', 0, 1);
}
- if (! empty($conf->global->WORKFLOW_INVOICE_AMOUNT_CLASSIFY_BILLED_ORDER)) print ' '.$langs->trans("IfValidateInvoiceIsNoOrderStayUnbilled").' ';
+ if (! empty($conf->workflow->enabled) && ! empty($conf->global->WORKFLOW_INVOICE_AMOUNT_CLASSIFY_BILLED_ORDER)) print ' '.$langs->trans("IfValidateInvoiceIsNoOrderStayUnbilled").' ';
else print ' '.$langs->trans("OptionToSetOrderBilledNotEnabled").' ';
print ' ';
print ' ';
@@ -504,7 +529,7 @@ if ($resql)
if ($sall)
{
foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val);
- print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall);
+ print ''.$langs->trans("FilterOnInto", $all) . join(', ',$fieldstosearchall).'
';
}
$moreforfilter='';
@@ -536,6 +561,14 @@ if ($resql)
$moreforfilter.=$form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1);
$moreforfilter.='';
}
+ if (! empty($conf->categorie->enabled))
+ {
+ require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
+ $moreforfilter.='';
+ $moreforfilter.=$langs->trans('CustomersProspectsCategoriesShort').': ';
+ $moreforfilter.=$formother->select_categories('customer',$search_categ_cus,'search_categ_cus',1);
+ $moreforfilter.='
';
+ }
$parameters=array();
$reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook
if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint;
@@ -610,17 +643,17 @@ if ($resql)
// Date order
if (! empty($arrayfields['c.date_commande']['checked']))
{
- print '';
- if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ' ';
- print ' ';
+ print ' ';
+ if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ' ';
+ print ' ';
$formother->select_year($search_orderyear?$search_orderyear:-1,'search_orderyear',1, 20, 5);
print ' ';
}
if (! empty($arrayfields['c.date_delivery']['checked']))
{
- print '';
- if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ' ';
- print ' ';
+ print ' ';
+ if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ' ';
+ print ' ';
$formother->select_year($search_deliveryyear?$search_deliveryyear:-1,'search_deliveryyear',1, 20, 5);
print ' ';
}
@@ -1112,25 +1145,18 @@ if ($resql)
print ''."\n";
- if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files)
- {
- /*
- * Show list of available documents
- */
- $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder;
- $urlsource.=str_replace('&','&',$param);
+ $hidegeneratedfilelistifempty=1;
+ if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty=0;
- $filedir=$diroutputmassaction;
- $genallowed=$user->rights->commande->lire;
- $delallowed=$user->rights->commande->creer;
+ // Show list of available documents
+ $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder;
+ $urlsource.=str_replace('&','&',$param);
- print $formfile->showdocuments('massfilesarea_orders','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,'');
- }
- else
- {
- print ''.$langs->trans("ShowTempMassFilesArea").' ';
- }
+ $filedir=$diroutputmassaction;
+ $genallowed=$user->rights->commande->lire;
+ $delallowed=$user->rights->commande->creer;
+ print $formfile->showdocuments('massfilesarea_orders','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,'','','',null,$hidegeneratedfilelistifempty);
}
else
{
diff --git a/htdocs/commande/note.php b/htdocs/commande/note.php
index 6598805490d..6cff3bfb3bc 100644
--- a/htdocs/commande/note.php
+++ b/htdocs/commande/note.php
@@ -32,10 +32,8 @@ if (! empty($conf->projet->enabled)) {
require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
}
-
-$langs->load("companies");
-$langs->load("bills");
-$langs->load("orders");
+// Load translation files required by the page
+$langs->loadLangs(array('companies', 'bills', 'orders'));
$id = GETPOST('id','int');
$ref=GETPOST('ref','alpha');
diff --git a/htdocs/commande/orderstoinvoice.php b/htdocs/commande/orderstoinvoice.php
index 77c533b88b8..03d379270b1 100644
--- a/htdocs/commande/orderstoinvoice.php
+++ b/htdocs/commande/orderstoinvoice.php
@@ -39,9 +39,8 @@ if (! empty($conf->projet->enabled)) {
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
}
-$langs->load('orders');
-$langs->load('deliveries');
-$langs->load('companies');
+// Load translation files required by the page
+$langs->loadLangs(array("orders", "deliveries", "companies"));
if (! $user->rights->facture->creer)
accessforbidden();
@@ -480,7 +479,7 @@ if ($action == 'create' && !$error)
$parameters=array('objectsrc' => $objectsrc, 'idsrc' => $listoforders);
$reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;
- if (empty($reshook) && ! empty($extrafields->attribute_label))
+ if (empty($reshook))
{
$object=new Facture($db);
print $object->showOptionals($extrafields,'edit');
@@ -553,7 +552,7 @@ if (($action != 'create' && $action != 'add') || ($action == 'create' && $error)
rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
@@ -655,7 +654,7 @@ if (($action != 'create' && $action != 'add') || ($action == 'create' && $error)
print '';
print '';
- $var=true;
+
$generic_commande = new Commande($db);
while ($i < $num)
@@ -703,7 +702,7 @@ if (($action != 'create' && $action != 'add') || ($action == 'create' && $error)
print '';
// Statut
- print ''.$generic_commande->LibStatut($objp->fk_statut,$objp->facturee,5).' ';
+ print ''.$generic_commande->LibStatut($objp->fk_statut,$objp->billed,5).' ';
// Checkbox
print '';
diff --git a/htdocs/commande/stats/index.php b/htdocs/commande/stats/index.php
index b1baf7332a1..8f259808357 100644
--- a/htdocs/commande/stats/index.php
+++ b/htdocs/commande/stats/index.php
@@ -55,10 +55,8 @@ $year = GETPOST('year')>0?GETPOST('year'):$nowyear;
$startyear=$year-1;
$endyear=$year;
-$langs->load('orders');
-$langs->load('companies');
-$langs->load('other');
-$langs->load('suppliers');
+// Load translation files required by the page
+$langs->loadLangs(array('orders', 'companies', 'other', 'suppliers'));
/*
@@ -354,7 +352,7 @@ print '';
// Show graphs
-print '
';
+print '';
if ($mesg) { print $mesg; }
else {
print $px1->show();
diff --git a/htdocs/commande/tpl/linkedobjectblock.tpl.php b/htdocs/commande/tpl/linkedobjectblock.tpl.php
index 39479ba220b..758a37eddb8 100644
--- a/htdocs/commande/tpl/linkedobjectblock.tpl.php
+++ b/htdocs/commande/tpl/linkedobjectblock.tpl.php
@@ -36,34 +36,36 @@ global $noMoreLinkedObjectBlockAfter;
$langs = $GLOBALS['langs'];
$linkedObjectBlock = $GLOBALS['linkedObjectBlock'];
+// Load translation files required by the page
$langs->load("orders");
$total=0; $ilink=0;
-$var=true;
foreach($linkedObjectBlock as $key => $objectlink)
{
$ilink++;
- $trclass=($var?'pair':'impair');
+ $trclass='oddeven';
if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass.=' liste_sub_total';
?>
-
- trans("CustomerOrder"); ?>
- getNomUrl(1); ?>
- ref_client; ?>
- date,'day'); ?>
- " >
+ trans("CustomerOrder"); ?>
+ global->MAIN_ENABLE_IMPORT_LINKED_OBJECT_LINES) print '
+
+ getNomUrl(1); ?>
+ ref_client; ?>
+ date,'day'); ?>
+ rights->commande->lire) {
$total = $total + $objectlink->total_ht;
echo price($objectlink->total_ht);
} ?>
- getLibStatut(3); ?>
-
+ getLibStatut(3); ?>
+
element != 'shipping') {
?>
- id.'&action=dellink&dellinkid='.$key; ?>">transnoentitiesnoconv("RemoveLink")); ?>
+ id.'&action=dellink&dellinkid='.$key; ?>">transnoentitiesnoconv("RemoveLink"), 'unlink'); ?>
@@ -87,4 +89,4 @@ if (count($linkedObjectBlock) > 1)
}
?>
-
\ No newline at end of file
+
diff --git a/htdocs/compta/ajaxpayment.php b/htdocs/compta/ajaxpayment.php
index 27a167bc576..5e83b3032c1 100644
--- a/htdocs/compta/ajaxpayment.php
+++ b/htdocs/compta/ajaxpayment.php
@@ -20,16 +20,11 @@
* \brief File to return Ajax response on payment breakdown process
*/
-//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1');
-//if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1');
if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1');
-//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1');
if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK','1');
if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1');
if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); // If there is no menu to show
if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); // If we don't need to load the html.form.class.php
-//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1');
-//if (! defined("NOLOGIN")) define("NOLOGIN",'1'); // If this page is public (can be called outside logged session)
require '../main.inc.php';
@@ -66,7 +61,7 @@ foreach ($remains as $key => $value)
}
// Treatment
-$result = $amountPayment != '' ? ($amountPayment - array_sum($amounts)) : ($amountPayment + array_sum($amounts)); // Remaining amountPayment
+$result = ($amountPayment != '') ? ($amountPayment - array_sum($amounts)) : array_sum($amounts); // Remaining amountPayment
$toJsonArray = array();
$totalRemaining = price2num(array_sum($remains));
$toJsonArray['label'] = $amountPayment == '' ? '' : $langs->transnoentities('RemainingAmountPayment');
diff --git a/htdocs/compta/bank/annuel.php b/htdocs/compta/bank/annuel.php
index 3eee68bcb24..a786cf5ca28 100644
--- a/htdocs/compta/bank/annuel.php
+++ b/htdocs/compta/bank/annuel.php
@@ -29,8 +29,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php';
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php';
-$langs->load("banks");
-$langs->load("categories");
+// Load translation files required by the page
+$langs->loadLangs(array('banks', 'categories'));
$WIDTH=DolGraph::getDefaultGraphSizeForStats('width',380); // Large for one graph in a smarpthone.
$HEIGHT=DolGraph::getDefaultGraphSizeForStats('height',160);
@@ -200,7 +200,6 @@ for ($annee = $year_start ; $annee <= $year_end ; $annee++)
}
print ' ';
-$var=true;
for ($mois = 1 ; $mois < 13 ; $mois++)
{
diff --git a/htdocs/compta/bank/bankentries_list.php b/htdocs/compta/bank/bankentries_list.php
index f85e2a664fb..ec41a28327f 100644
--- a/htdocs/compta/bank/bankentries_list.php
+++ b/htdocs/compta/bank/bankentries_list.php
@@ -1,12 +1,13 @@
- * Copyright (C) 2004-2016 Laurent Destailleur
+ * Copyright (C) 2004-2018 Laurent Destailleur
* Copyright (C) 2005-2010 Regis Houssin
* Copyright (C) 2012 Vinícius Nogueira
* Copyright (C) 2014 Florian Henry
* Copyright (C) 2015 Jean-François Ferry
* Copyright (C) 2016 Juanjo Menent
* Copyright (C) 2017 Alexandre Spangaro
+ * Copyright (C) 2018 Ferran Marcet
*
* 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
@@ -47,6 +48,7 @@ require_once DOL_DOCUMENT_ROOT.'/expensereport/class/paymentexpensereport.class.
require_once DOL_DOCUMENT_ROOT.'/loan/class/loan.class.php';
require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php';
+// Load translation files required by the page
$langs->loadLangs(array("banks","bills","categories","companies","margins","salaries","loan","donations","trips","members","compta","accountancy"));
$id = GETPOST('id','int');
@@ -54,6 +56,7 @@ $ref = GETPOST('ref','alpha');
$action=GETPOST('action','alpha');
$cancel=GETPOST('cancel','alpha');
$confirm=GETPOST('confirm','alpha');
+$contextpage='banktransactionlist'.(empty($object->ref)?'':'-'.$object->id);
// Security check
$fieldvalue = (! empty($id) ? $id : (! empty($ref) ? $ref :''));
@@ -90,7 +93,7 @@ $num_releve=GETPOST("num_releve","alpha");
$cat=GETPOST("cat");
if (empty($dateop)) $dateop=-1;
-$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit;
+$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit;
$sortfield = GETPOST("sortfield",'alpha');
$sortorder = GETPOST("sortorder",'alpha');
$page = GETPOST("page",'int');
@@ -100,7 +103,7 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined,
$offset = $limit * $page;
$pageprev = $page - 1;
$pagenext = $page + 1;
-if (! $sortorder) $sortorder='ASC';
+if (! $sortorder) $sortorder='desc,desc,desc';
if (! $sortfield) $sortfield='b.datev,b.dateo,b.rowid';
$mode_balance_ok=false;
@@ -110,7 +113,6 @@ if (($sortfield == 'b.datev' || $sortfield == 'b.datev,b.dateo,b.rowid'))
$sortfield = 'b.datev,b.dateo,b.rowid';
if ($id > 0 || ! empty($ref) || $search_account > 0) $mode_balance_ok = true;
}
-if (strtolower($sortorder) == 'desc') $mode_balance_ok = false;
$object = new Account($db);
if ($id > 0 || ! empty($ref))
@@ -120,10 +122,6 @@ if ($id > 0 || ! empty($ref))
}
-// Initialize technical object to manage context to save list fields
-$contextpage='banktransactionlist'.(empty($object->ref)?'':'-'.$object->id);
-//var_dump($contextpage);
-
// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
$hookmanager->initHooks(array('banktransactionlist', $contextpage));
$extrafields = new ExtraFields($db);
@@ -430,9 +428,9 @@ if ($id > 0 || ! empty($ref))
if ($user->rights->banque->consolidate) {
$newparam = $param;
$newparam = preg_replace('/search_conciliated=\d+/i','',$newparam);
- $buttonreconcile = ''.$langs->trans("Conciliate").' ';
+ $buttonreconcile = ''.$langs->trans("Conciliate").' ';
} else {
- $buttonreconcile = ''.$langs->trans("Conciliate").' ';
+ $buttonreconcile = ''.$langs->trans("Conciliate").' ';
}
}
}
@@ -446,7 +444,7 @@ $sql = "SELECT b.rowid, b.dateo as do, b.datev as dv, b.amount, b.label, b.rappr
$sql.= " b.fk_account, b.fk_type,";
$sql.= " ba.rowid as bankid, ba.ref as bankref,";
$sql.= " bu.url_id,";
-$sql.= " s.nom, s.name_alias, s.client, s.fournisseur, s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur";
+$sql.= " s.nom, s.name_alias, s.client, s.fournisseur, s.email, s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur";
// Add fields from extrafields
foreach ($extrafields->attribute_label as $key => $val) $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key.' as options_'.$key : '');
// Add fields from hooks
@@ -527,8 +525,8 @@ if (! empty($debit)) $mode_balance_ok=false;
if (! empty($credit)) $mode_balance_ok=false;
if (! empty($thirdparty)) $mode_balance_ok=false;
-$sql.= $db->plimit($limit+1,$offset);
-
+$sql.= $db->plimit($limit+1, $offset);
+//print $sql;
dol_syslog('compta/bank/bankentries_list.php', LOG_DEBUG);
$resql = $db->query($sql);
if ($resql)
@@ -672,7 +670,7 @@ if ($resql)
print '';
print ' ';
print '';
- $form->select_types_paiements((GETPOST('operation')?GETPOST('operation'):($object->courant == Account::TYPE_CASH ? 'LIQ' : '')),'operation','1,2',2,1);
+ $form->select_types_paiements((GETPOST('operation')?GETPOST('operation'):($object->courant == Account::TYPE_CASH ? 'LIQ' : '')), 'operation', '1,2', 2, 1);
print ' ';
print '';
print ' ';
@@ -725,7 +723,7 @@ if ($resql)
// Title
$bankcateg=new BankCateg($db);
- $addbutton = '';
+ $newcardbutton = '';
if ($action != 'addline' && $action != 'reconcile')
{
if (empty($conf->global->BANK_DISABLE_DIRECT_INPUT))
@@ -733,27 +731,37 @@ if ($resql)
if (! empty($conf->global->BANK_USE_VARIOUS_PAYMENT)) // If direct entries is done using miscellaneous payments
{
if ($user->rights->banque->modifier) {
- $addbutton = ''.$langs->trans("AddBankRecord").' ';
+ $newcardbutton = ''.$langs->trans("AddBankRecord").' ';
+ $newcardbutton.= ' ';
+ $newcardbutton.= ' ';
} else {
- $addbutton = ''.$langs->trans("AddBankRecord").' ';
+ $newcardbutton = ''.$langs->trans("AddBankRecord");
+ $newcardbutton.= ' ';
+ $newcardbutton.= ' ';
}
}
else // If direct entries is not done using miscellaneous payments
{
if ($user->rights->banque->modifier) {
- $addbutton = ''.$langs->trans("AddBankRecord").' ';
+ $newcardbutton = ''.$langs->trans("AddBankRecord");
+ $newcardbutton.= ' ';
+ $newcardbutton.= ' ';
} else {
- $addbutton = ''.$langs->trans("AddBankRecord").' ';
+ $newcardbutton = ''.$langs->trans("AddBankRecord");
+ $newcardbutton.= ' ';
+ $newcardbutton.= ' ';
}
}
}
else
{
- $addbutton = ''.$langs->trans("AddBankRecord").' ';
+ $newcardbutton = ''.$langs->trans("AddBankRecord");
+ $newcardbutton.= ' ';
+ $newcardbutton.= ' ';
}
}
- $morehtml='';
+ $morehtml='
';
$morehtml.= '
'.$langs->trans("Page")." "; // ' Page ';
$morehtml.='
';
$morehtml.='/'.$nbtotalofpages.' ';
@@ -764,7 +772,7 @@ if ($resql)
$morehtml.=$buttonreconcile;
}
- $morehtml.=$addbutton;
+ $morehtml.=$newcardbutton;
$picto='title_bank';
if ($id > 0 || ! empty($ref)) $picto='';
@@ -851,7 +859,7 @@ if ($resql)
if (! empty($arrayfields['type']['checked']))
{
print '
';
- $form->select_types_paiements(empty($search_type)?'':$search_type, 'search_type', '', 2, 0, 1, 0, 1, 'maxwidth100');
+ $form->select_types_paiements(empty($search_type)?'':$search_type, 'search_type', '', 2, 1, 1, 0, 1, 'maxwidth100');
print ' ';
}
if (! empty($arrayfields['b.num_chq']['checked']))
@@ -904,7 +912,7 @@ if ($resql)
if (! empty($arrayfields['b.conciliated']['checked']))
{
print '
';
- print $form->selectyesno('search_conciliated', $search_conciliated, 1, False, 1);
+ print $form->selectyesno('search_conciliated', $search_conciliated, 1, false, 1);
print ' ';
}
print '
';
@@ -934,14 +942,15 @@ if ($resql)
// Extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
// Hook fields
- $parameters=array('arrayfields'=>$arrayfields);
+ $parameters=array('arrayfields'=>$arrayfields,'param'=>$param,'sortfield'=>$sortfield,'sortorder'=>$sortorder);
$reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;
print_liste_field_titre('', $_SERVER["PHP_SELF"],"",'','','align="right"',$sortfield,$sortorder,'maxwidthsearch ');
print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch ');
print "\n";
- $balance = 0; // For balance
+ $balance = 0; // For balance
+ $balancebefore = 0; // For balance
$balancecalculated = false;
$posconciliatecol = 0;
@@ -965,7 +974,7 @@ if ($resql)
// Loop on each record before
$sign = 1;
$i = 0;
- $sqlforbalance='SELECT SUM(b.amount) as balance';
+ $sqlforbalance='SELECT SUM(b.amount) as previoustotal';
$sqlforbalance.= " FROM ";
$sqlforbalance.= " ".MAIN_DB_PREFIX."bank_account as ba,";
$sqlforbalance.= " ".MAIN_DB_PREFIX."bank as b";
@@ -980,7 +989,16 @@ if ($resql)
$objforbalance = $db->fetch_object($resqlforbalance);
if ($objforbalance)
{
- $balance = $objforbalance->balance;
+ // If sort is desc,desc,desc then total of previous date + amount is the balancebefore of the previous line before the line to show
+ if ($sortfield == 'b.datev,b.dateo,b.rowid' && $sortorder == 'desc,desc,desc')
+ {
+ $balancebefore = $objforbalance->previoustotal + ($sign * $objp->amount);
+ }
+ // If sort is asc,asc,asc then total of previous date is balance of line before the next line to show
+ else
+ {
+ $balance = $objforbalance->previoustotal;
+ }
}
}
else dol_print_error($db);
@@ -1028,6 +1046,7 @@ if ($resql)
print ' ';
print ' ';
}
+
if (! empty($arrayfields['balancebefore']['checked']))
{
print '
';
@@ -1042,6 +1061,12 @@ if ($resql)
}
print ' ';
+ print ' ';
+ print ' ';
print ' ';
print '
';
print ' ';
@@ -1049,7 +1074,17 @@ if ($resql)
}
}
- $balance = price2num($balance + ($sign * $objp->amount),'MT');
+
+ if ($sortfield == 'b.datev,b.dateo,b.rowid' && $sortorder == 'desc,desc,desc')
+ {
+ $balance = price2num($balancebefore, 'MT'); // balance = balancebefore of previous line (sort is desc)
+ $balancebefore = price2num($balancebefore - ($sign * $objp->amount),'MT');
+ }
+ else
+ {
+ $balancebefore = price2num($balance, 'MT'); // balancebefore = balance of previous line (sort is asc)
+ $balance = price2num($balance + ($sign * $objp->amount),'MT');
+ }
if (empty($cachebankaccount[$objp->bankid]))
{
@@ -1269,6 +1304,7 @@ if ($resql)
$companystatic->name=$objp->nom;
$companystatic->name_alias=$objp->name_alias;
$companystatic->client=$objp->client;
+ $companystatic->email=$objp->email;
$companystatic->fournisseur=$objp->fournisseur;
$companystatic->code_client=$objp->code_client;
$companystatic->code_fournisseur=$objp->code_fournisseur;
@@ -1326,7 +1362,6 @@ if ($resql)
{
if ($mode_balance_ok)
{
- $balancebefore = price2num($balance - ($sign * $objp->amount),'MT');
if ($balancebefore >= 0)
{
print '
'.price($balancebefore).' ';
@@ -1388,14 +1423,14 @@ if ($resql)
if (! empty($arrayfields['b.conciliated']['checked']))
{
- print '
';
+ print ' ';
print $objp->conciliated?$langs->trans("Yes"):$langs->trans("No");
print ' ';
if (! $i) $totalarray['nbfield']++;
}
// Action edit/delete
- print '
';
+ print ' ';
// Transaction reconciliated or edit link
if ($objp->conciliated && $bankaccount->canBeConciliated() > 0) // If line not conciliated and account can be conciliated
{
diff --git a/htdocs/compta/bank/bilan.php b/htdocs/compta/bank/bilan.php
index 22f7c8c9e79..5e5194d55c8 100644
--- a/htdocs/compta/bank/bilan.php
+++ b/htdocs/compta/bank/bilan.php
@@ -25,8 +25,8 @@
require('../../main.inc.php');
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
-$langs->load("banks");
-$langs->load("categories");
+// Load translation files required by the page
+$langs->loadLangs(array('banks', 'categories'));
if (!$user->rights->banque->lire)
accessforbidden();
diff --git a/htdocs/compta/bank/budget.php b/htdocs/compta/bank/budget.php
index 15aae28c1d1..280cd9bdbc0 100644
--- a/htdocs/compta/bank/budget.php
+++ b/htdocs/compta/bank/budget.php
@@ -27,8 +27,8 @@
require('../../main.inc.php');
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
-$langs->load("banks");
-$langs->load("categories");
+// Load translation files required by the page
+$langs->loadLangs(array('banks', 'categories'));
// Security check
if ($user->societe_id) $socid=$user->societe_id;
@@ -70,7 +70,6 @@ if ($result)
$num = $db->num_rows($result);
$i = 0; $total = 0; $totalnb = 0;
- $var=true;
while ($i < $num)
{
$objp = $db->fetch_object($result);
diff --git a/htdocs/compta/bank/card.php b/htdocs/compta/bank/card.php
index 38add1141f7..db497733863 100644
--- a/htdocs/compta/bank/card.php
+++ b/htdocs/compta/bank/card.php
@@ -39,6 +39,7 @@ if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT . '/core
if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingaccount.class.php';
if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingjournal.class.php';
+// Load translation files required by the page
$langs->loadLangs(array("banks","bills","categories","companies","compta"));
$action = GETPOST('action','aZ09');
@@ -413,7 +414,7 @@ if ($action == 'create')
$parameters=array();
$reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;
- if (empty($reshook) && ! empty($extrafields->attribute_label))
+ if (empty($reshook))
{
print $object->showOptionals($extrafields,'edit',$parameters);
}
@@ -803,15 +804,15 @@ else
print ' ';
print ' '."\n\n";
- dol_fiche_head('');
+ dol_fiche_head(array(), 0, '', 0);
- print '
';
+ //print '
';
print '';
// Ref
print ''.$langs->trans("Ref").' ';
- print ' ref).'"> ';
+ print ' ref).'"> ';
// Label
print ''.$langs->trans("Label").' ';
@@ -914,7 +915,7 @@ else
$parameters=array();
$reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;
- if (empty($reshook) && ! empty($extrafields->attribute_label))
+ if (empty($reshook))
{
print $object->showOptionals($extrafields,'edit');
}
diff --git a/htdocs/compta/bank/categ.php b/htdocs/compta/bank/categ.php
index 83e1f15ef36..be029fcb2f5 100644
--- a/htdocs/compta/bank/categ.php
+++ b/htdocs/compta/bank/categ.php
@@ -30,8 +30,8 @@ require('../../main.inc.php');
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/bankcateg.class.php';
-$langs->load("banks");
-$langs->load("categories");
+// Load translation files required by the page
+$langs->loadLangs(array('banks', 'categories'));
$action=GETPOST('action','aZ09');
@@ -101,11 +101,10 @@ if ($result)
$num = $db->num_rows($result);
$i = 0; $total = 0;
- $var=True;
while ($i < $num)
{
$objp = $db->fetch_object($result);
-
+
print '';
print ''.$objp->rowid.' ';
if (GETPOST('action','aZ09') == 'edit' && GETPOST("categid")== $objp->rowid)
@@ -136,7 +135,7 @@ if ($result)
*/
if ($action != 'edit')
{
-
+
print ' ';
print ' ';
print ' ';
diff --git a/htdocs/compta/bank/class/account.class.php b/htdocs/compta/bank/class/account.class.php
index 8afcf967874..7228214e51c 100644
--- a/htdocs/compta/bank/class/account.class.php
+++ b/htdocs/compta/bank/class/account.class.php
@@ -395,9 +395,10 @@ class Account extends CommonObject
* @param string $emetteur Name of cheque writer
* @param string $banque Bank of cheque writer
* @param string $accountancycode When we record a free bank entry, we must provide accounting account if accountancy module is on.
+ * @param int $datev Date value
* @return int Rowid of added entry, <0 if KO
*/
- function addline($date, $oper, $label, $amount, $num_chq, $categorie, User $user, $emetteur='',$banque='', $accountancycode='')
+ function addline($date, $oper, $label, $amount, $num_chq, $categorie, User $user, $emetteur='',$banque='', $accountancycode='', $datev=null)
{
// Deprecatîon warning
if (is_numeric($oper)) {
@@ -447,7 +448,7 @@ class Account extends CommonObject
$this->db->begin();
- $datev = $date;
+ if (is_null($datev) || empty($datev)) $datev = $date;
$accline = new AccountLine($this->db);
$accline->datec = $now;
@@ -505,10 +506,12 @@ class Account extends CommonObject
* @param int $notrigger 1=Disable triggers
* @return int < 0 if KO, > 0 if OK
*/
- function create(User $user = null, $notrigger=0)
+ function create(User $user, $notrigger=0)
{
global $langs,$conf, $hookmanager;
+ $error=0;
+
// Clean parameters
if (! $this->min_allowed) $this->min_allowed=0;
if (! $this->min_desired) $this->min_desired=0;
@@ -668,7 +671,7 @@ class Account extends CommonObject
* @param int $notrigger 1=Disable triggers
* @return int <0 if KO, >0 if OK
*/
- function update(User $user = null, $notrigger = 0)
+ function update(User $user, $notrigger = 0)
{
global $langs,$conf, $hookmanager;
@@ -913,12 +916,9 @@ class Account extends CommonObject
$this->date_creation = $this->db->jdate($obj->date_creation);
$this->date_update = $this->db->jdate($obj->date_update);
- // Retreive all extrafield for thirdparty
+ // Retreive all extrafield
// fetch optionals attributes and labels
- require_once(DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php');
- $extrafields=new ExtraFields($this->db);
- $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true);
- $this->fetch_optionals($this->id,$extralabels);
+ $this->fetch_optionals();
return 1;
}
@@ -1138,6 +1138,8 @@ class Account extends CommonObject
*/
function solde($option=0)
{
+ $solde=0;
+
$sql = "SELECT sum(amount) as amount";
$sql.= " FROM ".MAIN_DB_PREFIX."bank";
$sql.= " WHERE fk_account = ".$this->id;
@@ -1152,8 +1154,13 @@ class Account extends CommonObject
$solde = $obj->amount;
}
$this->db->free($resql);
- return $solde;
+ } else {
+ $this->errors[]=$this->db->lasterror;
+ return -1;
}
+
+ return $solde;
+
}
/**
@@ -1596,7 +1603,7 @@ class Account extends CommonObject
$this->code_banque = '123';
$this->code_guichet = '456';
$this->number = 'ABC12345';
- $this->cle_rib = 50;
+ $this->cle_rib = '50';
$this->bic = 'AA12';
$this->iban = 'FR999999999';
$this->domiciliation = 'My bank address';
@@ -1907,7 +1914,7 @@ class AccountLine extends CommonObject
*/
function update_conciliation(User $user, $cat)
{
- global $conf;
+ global $conf,$langs;
$this->db->begin();
@@ -2135,9 +2142,10 @@ class AccountLine extends CommonObject
* @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto
* @param int $maxlen Longueur max libelle
* @param string $option Option ('showall')
+ * @param int $notooltip 1=Disable tooltip
* @return string Chaine avec URL
*/
- function getNomUrl($withpicto=0,$maxlen=0,$option='')
+ function getNomUrl($withpicto=0,$maxlen=0,$option='',$notooltip=0)
{
global $langs;
diff --git a/htdocs/compta/bank/document.php b/htdocs/compta/bank/document.php
index 2fca317d1c4..33e74dc3691 100644
--- a/htdocs/compta/bank/document.php
+++ b/htdocs/compta/bank/document.php
@@ -25,17 +25,14 @@
* \brief Page de gestion des documents attaches a un compte bancaire
*/
require('../../main.inc.php');
-require_once(DOL_DOCUMENT_ROOT . "/core/lib/bank.lib.php");
-require_once(DOL_DOCUMENT_ROOT . "/core/lib/files.lib.php");
-require_once(DOL_DOCUMENT_ROOT . "/core/lib/images.lib.php");
-require_once(DOL_DOCUMENT_ROOT . "/core/class/html.formfile.class.php");
+require_once DOL_DOCUMENT_ROOT . "/core/lib/bank.lib.php";
+require_once DOL_DOCUMENT_ROOT . "/core/lib/files.lib.php";
+require_once DOL_DOCUMENT_ROOT . "/core/lib/images.lib.php";
+require_once DOL_DOCUMENT_ROOT . "/core/class/html.formfile.class.php";
require_once DOL_DOCUMENT_ROOT . '/compta/bank/class/account.class.php';
-$langs->load("banks");
-
-
-$langs->load('companies');
-$langs->load('other');
+// Load translation files required by the page
+$langs->loadLangs(array('banks', 'companies', 'other'));
$id = (GETPOST('id', 'int') ? GETPOST('id', 'int') : GETPOST('account', 'int'));
$ref = GETPOST('ref', 'alpha');
@@ -127,7 +124,7 @@ if ($id > 0 || !empty($ref)) {
print '';
print '' . $langs->trans("NbOfAttachedFiles") . ' ' . count($filearray) . ' ';
- print '' . $langs->trans("TotalSizeOfAttachedFiles") . ' ' . $totalsize . ' ' . $langs->trans("bytes") . ' ';
+ print '' . $langs->trans("TotalSizeOfAttachedFiles") . ' ' .dol_print_size($totalsize,1,1).' ';
print "
\n";
print '';
diff --git a/htdocs/compta/bank/graph.php b/htdocs/compta/bank/graph.php
index a813a71eeca..b829002a990 100644
--- a/htdocs/compta/bank/graph.php
+++ b/htdocs/compta/bank/graph.php
@@ -28,8 +28,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php';
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php';
-$langs->load("banks");
-$langs->load("categories");
+// Load translation files required by the page
+$langs->loadLangs(array('banks', 'categories'));
$WIDTH=DolGraph::getDefaultGraphSizeForStats('width',768);
$HEIGHT=DolGraph::getDefaultGraphSizeForStats('height',200);
diff --git a/htdocs/compta/bank/info.php b/htdocs/compta/bank/info.php
index 832ec95dcd2..ab43b9374aa 100644
--- a/htdocs/compta/bank/info.php
+++ b/htdocs/compta/bank/info.php
@@ -26,9 +26,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
-$langs->load("banks");
-$langs->load("categories");
-$langs->load("companies");
+// Load translation files required by the page
+$langs->loadLangs(array('banks', 'categories', 'companies'));
$id = GETPOST("rowid");
diff --git a/htdocs/compta/bank/ligne.php b/htdocs/compta/bank/ligne.php
index 5cb97be90bb..e006f78c6e7 100644
--- a/htdocs/compta/bank/ligne.php
+++ b/htdocs/compta/bank/ligne.php
@@ -32,10 +32,8 @@ require('../../main.inc.php');
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
-$langs->load("banks");
-$langs->load("categories");
-$langs->load("compta");
-$langs->load("bills");
+// Load translation files required by the page
+$langs->loadLangs(array('banks', 'categories', 'compta', 'bills'));
if (! empty($conf->adherent->enabled)) $langs->load("members");
if (! empty($conf->don->enabled)) $langs->load("donations");
if (! empty($conf->loan->enabled)) $langs->load("loan");
@@ -62,6 +60,7 @@ if (! $user->rights->banque->lire && ! $user->rights->banque->consolidate) acces
/*
* Actions
*/
+
if ($cancel)
{
if ($backtopage)
@@ -108,10 +107,23 @@ if ($user->rights->banque->modifier && $action == "update")
{
$error=0;
- $ac = new Account($db);
- $ac->fetch($id);
+ $acline = new AccountLine($db);
+ $acline->fetch($rowid);
- if ($ac->courant == Account::TYPE_CASH && $_POST['value'] != 'LIQ')
+ $acsource = new Account($db);
+ $acsource->fetch($id);
+
+ $actarget = new Account($db);
+ if (GETPOST('accountid','int') > 0 && ! $acline->rappro && ! $acline->getVentilExportCompta()) // We ask to change bank account
+ {
+ $actarget->fetch(GETPOST('accountid','int'));
+ }
+ else
+ {
+ $actarget->fetch($id);
+ }
+
+ if ($actarget->courant == Account::TYPE_CASH && GETPOST('value','alpha') != 'LIQ')
{
setEventMessages($langs->trans("ErrorCashAccountAcceptsOnlyCashMoney"), null, 'errors');
$error++;
@@ -119,16 +131,6 @@ if ($user->rights->banque->modifier && $action == "update")
if (! $error)
{
- // Avant de modifier la date ou le montant, on controle si ce n'est pas encore rapproche
- $conciliated=0;
- $sql = "SELECT b.rappro FROM ".MAIN_DB_PREFIX."bank as b WHERE rowid=".$rowid;
- $result = $db->query($sql);
- if ($result)
- {
- $objp = $db->fetch_object($result);
- $conciliated=$objp->rappro;
- }
-
$db->begin();
$amount = price2num($_POST['amount']);
@@ -142,15 +144,15 @@ if ($user->rights->banque->modifier && $action == "update")
if (isset($_POST['banque'])) $sql.=" banque='".$db->escape($_POST["banque"])."',";
if (isset($_POST['emetteur'])) $sql.=" emetteur='".$db->escape($_POST["emetteur"])."',";
// Blocked when conciliated
- if (! $conciliated)
+ if (! $acline->rappro)
{
if (isset($_POST['label'])) $sql.=" label='".$db->escape($_POST["label"])."',";
if (isset($_POST['amount'])) $sql.=" amount='".$amount."',";
if (isset($_POST['dateomonth'])) $sql.=" dateo = '".$db->idate($dateop)."',";
if (isset($_POST['datevmonth'])) $sql.=" datev = '".$db->idate($dateval)."',";
}
- $sql.= " fk_account = ".$id;
- $sql.= " WHERE rowid = ".$rowid;
+ $sql.= " fk_account = ".$actarget->id;
+ $sql.= " WHERE rowid = ".$acline->id;
$result = $db->query($sql);
if (! $result)
@@ -282,7 +284,7 @@ if ($result)
$account = $acct->id;
$bankline = new AccountLine($db);
- $bankline->fetch($rowid,$ref);
+ $bankline->fetch($rowid, $ref);
$links=$acct->get_url($rowid);
$bankline->load_previous_next_ref('','rowid');
@@ -311,21 +313,19 @@ if ($result)
print '
';
print '';
- // Ref
- /*
- print ''.$langs->trans("Ref")." ";
- print '';
- print $form->showrefnav($bankline, 'rowid', $linkback, 1, 'rowid', 'rowid');
- print ' ';
- print ' ';
- */
-
$i++;
// Bank account
print ''.$langs->trans("Account").' ';
print '';
- print $acct->getNomUrl(1,'transactions','reflabel');
+ if (! $objp->rappro && ! $bankline->getVentilExportCompta())
+ {
+ print $form->select_comptes($acct->id, 'accountid', 0, '', 0);
+ }
+ else
+ {
+ print $acct->getNomUrl(1,'transactions','reflabel');
+ }
print ' ';
print ' ';
diff --git a/htdocs/compta/bank/list.php b/htdocs/compta/bank/list.php
index 6a39416342e..e52e285742c 100644
--- a/htdocs/compta/bank/list.php
+++ b/htdocs/compta/bank/list.php
@@ -1,8 +1,11 @@
* Copyright (C) 2004-2016 Laurent Destailleur
* Copyright (C) 2005-2012 Regis Houssin
* Copyright (C) 2015 Jean-François Ferry
+ * Copyright (C) 2018 Ferran Marcet
*
* 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
@@ -32,16 +35,15 @@ require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingaccount.class.php';
if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingjournal.class.php';
-$langs->load("banks");
-$langs->load("categories");
-$langs->load("accountancy");
-$langs->load("compta");
+// Load translation files required by the page
+$langs->loadLangs(array('banks', 'categories', 'accountancy', 'compta'));
$action=GETPOST('action','alpha');
$massaction=GETPOST('massaction','alpha');
$show_files=GETPOST('show_files','int');
$confirm=GETPOST('confirm','alpha');
$toselect = GETPOST('toselect', 'array');
+$contextpage= GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'bankaccountlist'; // To manage different context of search
$search_ref=GETPOST('search_ref','alpha');
$search_label=GETPOST('search_label','alpha');
@@ -51,7 +53,8 @@ $optioncss = GETPOST('optioncss','alpha');
// Security check
if ($user->societe_id) $socid=$user->societe_id;
-$result=restrictedArea($user,'banque');
+if (! empty($user->rights->accounting->chartofaccount)) $allowed=1; // Dictionary with list of banks accounting account allowed to manager of chart account
+if (! $allowed) $result=restrictedArea($user,'banque');
$diroutputmassaction=$conf->bank->dir_output . '/temp/massgeneration/'.$user->id;
@@ -66,11 +69,9 @@ $pagenext = $page + 1;
if (! $sortfield) $sortfield='b.label';
if (! $sortorder) $sortorder='ASC';
-// Initialize technical object to manage context to save list fields
-$contextpage='bankaccountlist';
-
// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
-$hookmanager->initHooks(array($contextpage));
+$object = new Account($db);
+$hookmanager->initHooks(array('bankaccountlist'));
$extrafields = new ExtraFields($db);
// fetch optionals attributes and labels
@@ -228,7 +229,9 @@ $massactionbutton=$form->selectMassAction('', $arrayofmassactions);
$newcardbutton='';
if ($user->rights->banque->configurer)
{
- $newcardbutton.=''.$langs->trans("NewFinancialAccount").' ';
+ $newcardbutton.=''.$langs->trans("NewFinancialAccount").' ';
+ $newcardbutton.= ' ';
+ $newcardbutton.= ' ';
}
@@ -254,7 +257,7 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';
if ($sall)
{
foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val);
- print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall);
+ print ''.$langs->trans("FilterOnInto", $all) . join(', ',$fieldstosearchall).'
';
}
$moreforfilter='';
@@ -387,7 +390,7 @@ if (! empty($arrayfields['toreconcile']['checked'])) print_liste_field_titr
// Extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
// Hook fields
-$parameters=array('arrayfields'=>$arrayfields);
+$parameters=array('arrayfields'=>$arrayfields,'param'=>$param,'sortfield'=>$sortfield,'sortorder'=>$sortorder);
$reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;
if (! empty($arrayfields['b.datec']['checked'])) print_liste_field_titre($arrayfields['b.datec']['label'],$_SERVER["PHP_SELF"],"b.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder);
@@ -399,7 +402,7 @@ print "\n";
$total = array(); $found = 0; $i=0; $lastcurrencycode='';
-$var=true;
+
foreach ($accounts as $key=>$type)
{
if ($i >= $limit) break;
@@ -409,7 +412,6 @@ foreach ($accounts as $key=>$type)
$obj = new Account($db);
$obj->fetch($key);
- $var = !$var;
$solde = $obj->solde(1);
if (! empty($lastcurrencycode) && $lastcurrencycode != $obj->currency_code)
@@ -551,7 +553,7 @@ foreach ($accounts as $key=>$type)
if (! empty($arrayfields['balance']['checked']))
{
print '';
- print ''.price($solde, 0, $langs, 0, 0, -1, $obj->currency_code).' ';
+ print ''.price($solde, 0, $langs, 0, -1, -1, $obj->currency_code).' ';
print ' ';
if (! $i) $totalarray['nbfield']++;
if (! $i) $totalarray['totalbalancefield']=$totalarray['nbfield'];
diff --git a/htdocs/compta/bank/releve.php b/htdocs/compta/bank/releve.php
index a1e69cdc651..1d9d5526700 100644
--- a/htdocs/compta/bank/releve.php
+++ b/htdocs/compta/bank/releve.php
@@ -41,6 +41,7 @@ require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/functions.lib.php';
+// Load translation files required by the page
$langs->loadLangs(array("banks","categories","companies","bills","trips"));
$action=GETPOST('action', 'alpha');
@@ -72,7 +73,7 @@ if ($user->rights->banque->consolidate && $action == 'dvprev' && ! empty($dvid))
}
-$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit;
+$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit;
$sortfield = GETPOST("sortfield",'alpha');
$sortorder = GETPOST("sortorder",'alpha');
$page = GETPOST("page",'int');
@@ -395,7 +396,6 @@ if (empty($numref))
$result = $db->query($sql);
if ($result)
{
- $var=True;
$numrows = $db->num_rows($result);
$i = 0;
@@ -534,11 +534,10 @@ else
$title=$langs->trans("AccountStatement").' '.$numref.' - '.$langs->trans("BankAccount").' '.$object->getNomUrl(1, 'receipts');
print load_fiche_titre($title, $mesprevnext, 'title_bank.png');
//print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, 0, $nbtotalofrecords, 'title_bank.png', 0, '', '', 0, 1);
- print ' ';
print "";
print ' ';
- print " ";
+ print ' ';
print '';
print '
';
@@ -573,7 +572,6 @@ else
$result = $db->query($sql);
if ($result)
{
- $var=False;
$numrows = $db->num_rows($result);
$i = 0;
@@ -753,7 +751,7 @@ else
while ($ii < $numc)
{
$objc = $db->fetch_object($resc);
- print " - $objc->label ";
+ print " - ".$objc->label." ";
$ii++;
}
}
@@ -776,7 +774,7 @@ else
print ' '.price($objp->amount)." \n";
}
- print ''.price($total)." \n";
+ print ''.price(price2num($total, 'MT'))." \n";
if ($user->rights->banque->modifier || $user->rights->banque->consolidate)
{
@@ -798,8 +796,9 @@ else
print "\n".''.$langs->trans("Total")." : ".price($totald)." ".price($totalc)." ";
// Line Balance
- print "\n ".$langs->trans("EndBankBalance")." : ";
- print ''.price($total)." ";
+ print "\n";
+ print " ".$langs->trans("EndBankBalance")." : ";
+ print ''.price(price2num($total, 'MT'))." ";
print " \n";
print "
";
print "
";
diff --git a/htdocs/compta/bank/transfer.php b/htdocs/compta/bank/transfer.php
index e50d4822da7..765001e75a5 100644
--- a/htdocs/compta/bank/transfer.php
+++ b/htdocs/compta/bank/transfer.php
@@ -30,6 +30,7 @@ require('../../main.inc.php');
require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php';
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
+// Load translation files required by the page
$langs->loadLangs(array("banks", "categories", "multicurrency"));
if (! $user->rights->banque->transfer)
diff --git a/htdocs/compta/bank/treso.php b/htdocs/compta/bank/treso.php
index 136e352ff00..0fb8880ce87 100644
--- a/htdocs/compta/bank/treso.php
+++ b/htdocs/compta/bank/treso.php
@@ -33,10 +33,8 @@ require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
-$langs->load("banks");
-$langs->load("categories");
-$langs->load("bills");
-$langs->load("companies");
+// Load translation files required by the page
+$langs->loadLangs(array('banks', 'categories', 'bills', 'companies'));
// Security check
if (isset($_GET["account"]) || isset($_GET["ref"]))
@@ -117,8 +115,6 @@ if ($_REQUEST["account"] || $_REQUEST["ref"])
print ''.$langs->trans("BankBalance").' ';
print '';
- $var=true;
-
// Current balance
print '';
diff --git a/htdocs/compta/bank/various_payment/card.php b/htdocs/compta/bank/various_payment/card.php
index 2828963d889..1b4d7579892 100644
--- a/htdocs/compta/bank/various_payment/card.php
+++ b/htdocs/compta/bank/various_payment/card.php
@@ -35,6 +35,7 @@ if (! empty($conf->projet->enabled))
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
}
+// Load translation files required by the page
$langs->loadLangs(array("compta", "banks", "bills", "users", "accountancy"));
// Get parameters
diff --git a/htdocs/compta/bank/various_payment/document.php b/htdocs/compta/bank/various_payment/document.php
index ff304676686..cf596860a4b 100644
--- a/htdocs/compta/bank/various_payment/document.php
+++ b/htdocs/compta/bank/various_payment/document.php
@@ -28,6 +28,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php';
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/paymentvarious.class.php';
+// Load translation files required by the page
$langs->loadLangs(array("compta", "banks", "bills", "users", "accountancy"));
$id = GETPOST('id','int');
diff --git a/htdocs/compta/bank/various_payment/index.php b/htdocs/compta/bank/various_payment/index.php
index d52cbeb7595..6535e0c0082 100644
--- a/htdocs/compta/bank/various_payment/index.php
+++ b/htdocs/compta/bank/various_payment/index.php
@@ -29,6 +29,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php';
require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php';
require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php';
+// Load translation files required by the page
$langs->loadLangs(array("compta","banks","bills","accountancy"));
// Security check
@@ -38,7 +39,7 @@ $result = restrictedArea($user, 'banque', '', '', '');
$optioncss = GETPOST('optioncss','alpha');
-$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit;
+$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit;
$search_ref = GETPOST('search_ref','int');
$search_user = GETPOST('search_user','alpha');
$search_label = GETPOST('search_label','alpha');
@@ -102,7 +103,7 @@ $sql = "SELECT v.rowid, v.sens, v.amount, v.label, v.datep as datep, v.datev as
$sql.= " ba.rowid as bid, ba.ref as bref, ba.number as bnumber, ba.account_number as bank_account_number, ba.fk_accountancy_journal as accountancy_journal, ba.label as blabel,";
$sql.= " pst.code as payment_code";
$sql.= " FROM ".MAIN_DB_PREFIX."payment_various as v";
-$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pst ON v.fk_typepayment = pst.id AND pst.entity IN (" . getEntity('c_paiement').")";
+$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pst ON v.fk_typepayment = pst.id";
$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON v.fk_bank = b.rowid";
$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid";
$sql.= " WHERE v.entity IN (".getEntity('payment_various').")";
@@ -137,7 +138,6 @@ if ($result)
$num = $db->num_rows($result);
$i = 0;
$total = 0 ;
- $var=true;
$param='';
if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage);
@@ -153,6 +153,14 @@ if ($result)
if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss);
+ $newcardbutton='';
+ if ($user->rights->banque->modifier)
+ {
+ $newcardbutton=''.$langs->trans('MenuNewVariousPayment').' ';
+ $newcardbutton.= ' ';
+ $newcardbutton.= ' ';
+ }
+
print '';
if ($optioncss != '') print ' ';
@@ -163,7 +171,7 @@ if ($result)
print ' ';
print ' ';
- print_barre_liste($langs->trans("VariousPayments"),$page,$_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,'',$num, $totalnboflines, 'title_accountancy.png', 0, '', '', $limit);
+ print_barre_liste($langs->trans("VariousPayments"),$page,$_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,'',$num, $totalnboflines, 'title_accountancy.png', 0, $newcardbutton, '', $limit);
print '';
print '
'."\n";
@@ -187,7 +195,7 @@ if ($result)
// Type
print '';
- $form->select_types_paiements($typeid,'typeid','',0,0,1,16);
+ $form->select_types_paiements($typeid,'typeid','',0,1,1,16);
print ' ';
// Account
diff --git a/htdocs/compta/bank/various_payment/info.php b/htdocs/compta/bank/various_payment/info.php
index f6c7dc063f7..bb66871d6c0 100644
--- a/htdocs/compta/bank/various_payment/info.php
+++ b/htdocs/compta/bank/various_payment/info.php
@@ -26,6 +26,7 @@ require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/paymentvarious.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
+// Load translation files required by the page
$langs->loadLangs(array("compta", "banks", "bills", "users", "accountancy"));
$id=GETPOST('id','int');
diff --git a/htdocs/compta/charges/index.php b/htdocs/compta/charges/index.php
index 6e765cdacb0..6d369b696b9 100644
--- a/htdocs/compta/charges/index.php
+++ b/htdocs/compta/charges/index.php
@@ -34,8 +34,8 @@ require_once DOL_DOCUMENT_ROOT.'/compta/salaries/class/paymentsalary.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
-$langs->load("compta");
-$langs->load("bills");
+// Load translation files required by the page
+$langs->loadLangs(array('compta', 'bills'));
// Security check
if ($user->societe_id) $socid=$user->societe_id;
@@ -48,7 +48,7 @@ if (! $year && $mode != 'sconly') { $year=date("Y", time()); }
$search_account = GETPOST('search_account','int');
-$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit;
+$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit;
$sortfield = GETPOST("sortfield",'alpha');
$sortorder = GETPOST("sortorder",'alpha');
$page = GETPOST("page",'int');
@@ -139,7 +139,7 @@ if (! empty($conf->tax->enabled) && $user->rights->tax->charges->lire)
$sql.= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c,";
$sql.= " ".MAIN_DB_PREFIX."chargesociales as cs";
$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiementcharge as pc ON pc.fk_charge = cs.rowid";
- $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON pc.fk_typepaiement = pct.id AND pct.entity IN (".getEntity('c_paiement').")";
+ $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON pc.fk_typepaiement = pct.id";
$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON pc.fk_bank = b.rowid";
$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid";
$sql.= " WHERE cs.fk_type = c.id";
@@ -166,12 +166,10 @@ if (! empty($conf->tax->enabled) && $user->rights->tax->charges->lire)
$total = 0;
$totalnb = 0;
$totalpaye = 0;
- $var=true;
while ($i < min($num, $limit))
{
$obj = $db->fetch_object($resql);
- $var = !$var;
print '';
// Date
$date=$obj->periode;
@@ -260,7 +258,7 @@ if (! empty($conf->tax->enabled) && $user->rights->tax->charges->lire)
$sql.= " FROM ".MAIN_DB_PREFIX."tva as pv";
$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON pv.fk_bank = b.rowid";
$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid";
- $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON pv.fk_typepayment = pct.id AND pct.entity IN (".getEntity('c_paiement').")";
+ $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON pv.fk_typepayment = pct.id";
$sql.= " WHERE pv.entity IN (".getEntity("tax").")";
if ($year > 0)
{
@@ -417,14 +415,13 @@ while($j<$numlt)
print_liste_field_titre("DatePayment",$_SERVER["PHP_SELF"],"pv.datep","",$param,'align="center"',$sortfield,$sortorder);
print_liste_field_titre("PayedByThisPayment",$_SERVER["PHP_SELF"],"pv.amount","",$param,'align="right"',$sortfield,$sortorder);
print " \n";
- $var=1;
+
while ($i < $num)
{
$obj = $db->fetch_object($result);
$total = $total + $obj->amount;
-
print '';
print ''.dol_print_date($db->jdate($obj->dm),'day').' '."\n";
@@ -474,7 +471,7 @@ if (! empty($conf->salaries->enabled) && $user->rights->salaries->read)
$sql.= " FROM ".MAIN_DB_PREFIX."payment_salary as s";
$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON s.fk_bank = b.rowid";
$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid";
- $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON s.fk_typepayment = pct.id AND pct.entity IN (".getEntity('c_paiement').")";
+ $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON s.fk_typepayment = pct.id";
$sql.= " , ".MAIN_DB_PREFIX."user as u";
$sql.= " WHERE s.entity IN (".getEntity('user').")";
$sql.= " AND u.rowid = s.fk_user";
@@ -501,7 +498,7 @@ if (! empty($conf->salaries->enabled) && $user->rights->salaries->read)
if (! empty($conf->banque->enabled)) print_liste_field_titre("Account",$_SERVER["PHP_SELF"],"ba.label","",$param,"",$sortfield,$sortorder);
print_liste_field_titre("PayedByThisPayment",$_SERVER["PHP_SELF"],"s.amount","",$param,'align="right"',$sortfield,$sortorder);
print " \n";
- $var=1;
+
while ($i < $num)
{
$obj = $db->fetch_object($result);
diff --git a/htdocs/compta/clients.php b/htdocs/compta/clients.php
index c65a7a670ae..ceb9324961e 100644
--- a/htdocs/compta/clients.php
+++ b/htdocs/compta/clients.php
@@ -39,7 +39,7 @@ if ($user->societe_id > 0)
if (! $user->rights->facture->lire)
accessforbidden();
-
+// Load translation files required by the page
$langs->load("companies");
$mode=GETPOST("mode");
@@ -172,14 +172,10 @@ if ($resql)
print '';
print "\n";
- $var=true;
-
while ($i < min($num,$conf->liste_limit))
{
$obj = $db->fetch_object($resql);
-
-
print '';
print '';
$thirdpartystatic->id=$obj->rowid;
diff --git a/htdocs/compta/deplacement/card.php b/htdocs/compta/deplacement/card.php
index 979ef5960e0..05d509e268d 100644
--- a/htdocs/compta/deplacement/card.php
+++ b/htdocs/compta/deplacement/card.php
@@ -33,6 +33,7 @@ if (! empty($conf->projet->enabled))
require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
}
+// Load translation files required by the page
$langs->load("trips");
diff --git a/htdocs/compta/deplacement/document.php b/htdocs/compta/deplacement/document.php
index 1f3974ce041..59d92140c86 100644
--- a/htdocs/compta/deplacement/document.php
+++ b/htdocs/compta/deplacement/document.php
@@ -34,10 +34,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/trip.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
-$langs->load("other");
-$langs->load("trips");
-$langs->load("companies");
-$langs->load("interventions");
+// Load translation files required by the page
+$langs->loadLangs(array('other', 'trips', 'companies', 'interventions'));
$id = GETPOST('id','int');
$ref = GETPOST('ref', 'alpha');
@@ -115,7 +113,7 @@ if ($object->id)
//print " ".$langs->trans("Company")." ".$object->client->getNomUrl(1)." ";
print ''.$langs->trans("NbOfAttachedFiles").' '.count($filearray).' ';
- print ''.$langs->trans("TotalSizeOfAttachedFiles").' '.$totalsize.' '.$langs->trans("bytes").' ';
+ print ''.$langs->trans("TotalSizeOfAttachedFiles").' '.dol_print_size($totalsize,1,1).' ';
print '
';
print '
';
diff --git a/htdocs/compta/deplacement/index.php b/htdocs/compta/deplacement/index.php
index 2cd3823bacd..a390023e280 100644
--- a/htdocs/compta/deplacement/index.php
+++ b/htdocs/compta/deplacement/index.php
@@ -27,9 +27,8 @@ require '../../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/deplacement/class/deplacement.class.php';
-$langs->load("companies");
-$langs->load("users");
-$langs->load("trips");
+// Load translation files required by the page
+$langs->loadLangs(array('companies', 'users', 'trips'));
// Security check
$socid = GETPOST('socid','int');
@@ -45,7 +44,7 @@ $pageprev = $page - 1;
$pagenext = $page + 1;
if (! $sortorder) $sortorder="DESC";
if (! $sortfield) $sortfield="d.dated";
-$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit;
+$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit;
/*
diff --git a/htdocs/compta/deplacement/info.php b/htdocs/compta/deplacement/info.php
index 1e0279263e3..6a62484323f 100644
--- a/htdocs/compta/deplacement/info.php
+++ b/htdocs/compta/deplacement/info.php
@@ -27,6 +27,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/trip.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
require_once DOL_DOCUMENT_ROOT.'/compta/deplacement/class/deplacement.class.php';
+// Load translation files required by the page
$langs->load("trips");
// Security check
diff --git a/htdocs/compta/deplacement/list.php b/htdocs/compta/deplacement/list.php
index 807ddfee700..bdbdad0a712 100644
--- a/htdocs/compta/deplacement/list.php
+++ b/htdocs/compta/deplacement/list.php
@@ -30,9 +30,8 @@ require_once DOL_DOCUMENT_ROOT.'/compta/deplacement/class/deplacement.class.php'
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
-$langs->load("companies");
-$langs->load("users");
-$langs->load("trips");
+// Load translation files required by the page
+$langs->loadLangs(array('companies', 'users', 'trips'));
// Security check
$socid = GETPOST('socid','int');
@@ -46,7 +45,7 @@ $search_company=GETPOST('search_company','alpha');
$sortfield = GETPOST("sortfield",'alpha');
$sortorder = GETPOST("sortorder",'alpha');
$page = GETPOST("page",'int');
-$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit;
+$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit;
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1
$offset = $limit * $page;
$pageprev = $page - 1;
@@ -170,7 +169,6 @@ if ($resql)
print '';
print " \n";
- $var=true;
while ($i < min($num,$limit))
{
$obj = $db->fetch_object($resql);
@@ -178,7 +176,6 @@ if ($resql)
$soc = new Societe($db);
if ($obj->socid) $soc->fetch($obj->socid);
-
print '';
// Id
print ''.img_object($langs->trans("ShowTrip"),"trip").' '.$obj->rowid.' ';
diff --git a/htdocs/compta/deplacement/stats/index.php b/htdocs/compta/deplacement/stats/index.php
index 36bc107d672..cf652948a6e 100644
--- a/htdocs/compta/deplacement/stats/index.php
+++ b/htdocs/compta/deplacement/stats/index.php
@@ -27,8 +27,8 @@ require '../../../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/deplacement/class/deplacementstats.class.php';
-$langs->load("trips");
-$langs->load("companies");
+// Load translation files required by the page
+$langs->loadLangs(array('trips', 'companies'));
$WIDTH=DolGraph::getDefaultGraphSizeForStats('width');
$HEIGHT=DolGraph::getDefaultGraphSizeForStats('height');
@@ -294,7 +294,7 @@ print '';
// Show graphs
-print '
';
+print '';
if ($mesg) { print $mesg; }
else {
print $px1->show();
diff --git a/htdocs/compta/facture/admin/facture_cust_extrafields.php b/htdocs/compta/facture/admin/facture_cust_extrafields.php
index 7e6b069b0d9..2c676e399de 100644
--- a/htdocs/compta/facture/admin/facture_cust_extrafields.php
+++ b/htdocs/compta/facture/admin/facture_cust_extrafields.php
@@ -29,9 +29,8 @@ require '../../../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/invoice.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
-$langs->load("companies");
-$langs->load("admin");
-$langs->load("bills");
+// Load translation files required by the page
+$langs->loadLangs(array('companies', 'admin', 'bills'));
$extrafields = new ExtraFields($db);
$form = new Form($db);
diff --git a/htdocs/compta/facture/admin/facture_rec_cust_extrafields.php b/htdocs/compta/facture/admin/facture_rec_cust_extrafields.php
index 76284e7fe73..18aa3c99442 100644
--- a/htdocs/compta/facture/admin/facture_rec_cust_extrafields.php
+++ b/htdocs/compta/facture/admin/facture_rec_cust_extrafields.php
@@ -30,9 +30,8 @@ require '../../../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/invoice.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
-$langs->load("companies");
-$langs->load("admin");
-$langs->load("bills");
+// Load translation files required by the page
+$langs->loadLangs(array('companies', 'admin', 'bills'));
$extrafields = new ExtraFields($db);
$form = new Form($db);
diff --git a/htdocs/compta/facture/admin/facturedet_cust_extrafields.php b/htdocs/compta/facture/admin/facturedet_cust_extrafields.php
index d42139e4ec0..2b90ae7fe05 100644
--- a/htdocs/compta/facture/admin/facturedet_cust_extrafields.php
+++ b/htdocs/compta/facture/admin/facturedet_cust_extrafields.php
@@ -30,9 +30,8 @@ require '../../../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/invoice.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
-$langs->load("companies");
-$langs->load("admin");
-$langs->load("bills");
+// Load translation files required by the page
+$langs->loadLangs(array('companies', 'admin', 'bills'));
$extrafields = new ExtraFields($db);
$form = new Form($db);
diff --git a/htdocs/compta/facture/admin/facturedet_rec_cust_extrafields.php b/htdocs/compta/facture/admin/facturedet_rec_cust_extrafields.php
index cc33b8dc026..97f8b78b195 100644
--- a/htdocs/compta/facture/admin/facturedet_rec_cust_extrafields.php
+++ b/htdocs/compta/facture/admin/facturedet_rec_cust_extrafields.php
@@ -30,9 +30,8 @@ require '../../../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/invoice.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
-$langs->load("companies");
-$langs->load("admin");
-$langs->load("bills");
+// Load translation files required by the page
+$langs->loadlangs(array('companies', 'admin', 'bills'));
$extrafields = new ExtraFields($db);
$form = new Form($db);
diff --git a/htdocs/compta/facture/card.php b/htdocs/compta/facture/card.php
index 1d22d21d574..20d279c5113 100644
--- a/htdocs/compta/facture/card.php
+++ b/htdocs/compta/facture/card.php
@@ -64,6 +64,7 @@ if (! empty($conf->accounting->enabled)) {
require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingjournal.class.php';
}
+// Load translation files required by the page
$langs->loadLangs(array('bills','companies','compta','products','banks','main','withdrawals'));
if (! empty($conf->incoterm->enabled)) $langs->load('incoterm');
if (! empty($conf->margin->enabled)) $langs->load('margins');
@@ -556,7 +557,7 @@ if (empty($reshook))
|| (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->unvalidate)))
)
{
- $idwarehouse = GETPOST('idwarehouse');
+ $idwarehouse = GETPOST('idwarehouse','int');
$object->fetch($id);
$object->fetch_thirdparty();
@@ -643,8 +644,8 @@ if (empty($reshook))
else if ($action == 'confirm_paid_partially' && $confirm == 'yes' && $user->rights->facture->paiement)
{
$object->fetch($id);
- $close_code = $_POST["close_code"];
- $close_note = $_POST["close_note"];
+ $close_code = GETPOST("close_code",'none');
+ $close_note = GETPOST("close_note",'none');
if ($close_code) {
$result = $object->set_paid($user, $close_code, $close_note);
if ($result<0) setEventMessages($object->error, $object->errors, 'errors');
@@ -654,8 +655,8 @@ if (empty($reshook))
} // Classify "abandoned"
else if ($action == 'confirm_canceled' && $confirm == 'yes') {
$object->fetch($id);
- $close_code = $_POST["close_code"];
- $close_note = $_POST["close_note"];
+ $close_code = GETPOST("close_code",'none');
+ $close_note = GETPOST("close_note",'none');
if ($close_code) {
$result = $object->set_canceled($user, $close_code, $close_note);
if ($result<0) setEventMessages($object->error, $object->errors, 'errors');
@@ -719,7 +720,7 @@ if (empty($reshook))
$sql = 'SELECT SUM(pf.amount) as total_paiements';
$sql.= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'paiement as p';
- $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id AND c.entity IN (' . getEntity('c_paiement') . ')';
+ $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id';
$sql.= ' WHERE pf.fk_facture = '.$object->id;
$sql.= ' AND pf.fk_paiement = p.rowid';
$sql.= ' AND p.entity IN (' . getEntity('facture').')';
@@ -916,12 +917,21 @@ if (empty($reshook))
$object->fk_facture_source = $sourceinvoice > 0 ? $sourceinvoice : '';
$object->type = Facture::TYPE_CREDIT_NOTE;
+ $facture_source = new Facture($db); // fetch origin object
+ if ($facture_source->fetch($object->fk_facture_source)>0)
+ {
+ if ($facture_source->type == Facture::TYPE_SITUATION)
+ {
+ $object->situation_counter = $facture_source->situation_counter;
+ $object->situation_cycle_ref = $facture_source->situation_cycle_ref;
+ $facture_source->fetchPreviousNextSituationInvoice();
+ }
+ }
$id = $object->create($user);
if (GETPOST('invoiceAvoirWithLines', 'int')==1 && $id>0)
{
- $facture_source = new Facture($db); // fetch origin object
- if ($facture_source->fetch($object->fk_facture_source)>0)
+ if (!empty($facture_source->lines))
{
$fk_parent_line = 0;
@@ -938,6 +948,61 @@ if (empty($reshook))
$fk_parent_line = 0;
}
+
+
+
+ if($facture_source->type == Facture::TYPE_SITUATION)
+ {
+
+ if(!empty($facture_source->tab_previous_situation_invoice))
+ {
+ // search the last invoice in cycle
+ $lineIndex = count($facture_source->tab_previous_situation_invoice) - 1;
+ $searchPreviousInvoice = true;
+ while( $searchPreviousInvoice )
+ {
+ if($facture_source->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_SITUATION || $lineIndex < 1)
+ {
+ $searchPreviousInvoice=false; // find, exit;
+ break;
+ }
+ else
+ {
+ $lineIndex--; // go to previous invoice in cycle
+ }
+ }
+
+
+ $maxPrevSituationPercent = 0;
+ foreach($facture_source->tab_previous_situation_invoice[$lineIndex]->lines as $prevLine)
+ {
+ if($prevLine->id == $line->fk_prev_id)
+ {
+ $maxPrevSituationPercent = max($maxPrevSituationPercent,$prevLine->situation_percent);
+
+ //$line->subprice = $line->subprice - $prevLine->subprice;
+ $line->total_ht = $line->total_ht - $prevLine->total_ht;
+ $line->total_tva = $line->total_tva - $prevLine->total_tva;
+ $line->total_ttc = $line->total_ttc - $prevLine->total_ttc;
+ $line->total_localtax1 = $line->total_localtax1 - $prevLine->total_localtax1;
+ $line->total_localtax2 = $line->total_localtax2 - $prevLine->total_localtax2;
+
+ $line->multicurrency_subprice = $line->multicurrency_subprice - $prevLine->multicurrency_subprice;
+ $line->multicurrency_total_ht = $line->multicurrency_total_ht - $prevLine->multicurrency_total_ht;
+ $line->multicurrency_total_tva = $line->multicurrency_total_tva - $prevLine->multicurrency_total_tva;
+ $line->multicurrency_total_ttc = $line->multicurrency_total_ttc - $prevLine->multicurrency_total_ttc;
+
+
+ }
+ }
+
+ // prorata
+ $line->situation_percent = $maxPrevSituationPercent - $line->situation_percent;
+
+
+ }
+ }
+
$line->fk_facture = $object->id;
$line->fk_parent_line = $fk_parent_line;
@@ -971,7 +1036,6 @@ if (empty($reshook))
if(GETPOST('invoiceAvoirWithPaymentRestAmount', 'int')==1 && $id>0)
{
- $facture_source = new Facture($db); // fetch origin object if not previously defined
if ($facture_source->fetch($object->fk_facture_source)>0)
{
$totalpaye = $facture_source->getSommePaiement();
@@ -982,6 +1046,18 @@ if (empty($reshook))
$object->addline($langs->trans('invoiceAvoirLineWithPaymentRestAmount'),$remain_to_pay,1,0,0,0,0,0,'','','TTC');
}
}
+
+ // Add link between credit note and origin
+ if(! empty($object->fk_facture_source)) {
+ $facture_source->fetch($object->fk_facture_source);
+ $facture_source->fetchObjectLinked();
+
+ if(! empty($facture_source->linkedObjectsIds)) {
+ foreach($facture_source->linkedObjectsIds as $sourcetype => $TIds) {
+ $object->add_object_linked($sourcetype, current($TIds));
+ }
+ }
+ }
}
}
@@ -1214,7 +1290,7 @@ if (empty($reshook))
{
$arraylist = array('amount' => 'FixAmount','variable' => 'VarAmount');
$descline = $langs->trans('Deposit');
- $descline.= ' - '.$langs->trans($arraylist[$typeamount]);
+ //$descline.= ' - '.$langs->trans($arraylist[$typeamount]);
if ($typeamount=='amount') {
$descline.= ' ('. price($valuedeposit, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).')';
} elseif ($typeamount=='variable') {
@@ -1341,7 +1417,13 @@ if (empty($reshook))
$localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty);
$localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty);
- $result = $object->addline($desc, $lines[$i]->subprice, $lines[$i]->qty, $tva_tx, $localtax1_tx, $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, $lines[$i]->rang, $lines[$i]->special_code, $object->origin, $lines[$i]->rowid, $fk_parent_line, $lines[$i]->fk_fournprice, $lines[$i]->pa_ht, $label, $array_options, $lines[$i]->situation_percent, $lines[$i]->fk_prev_id, $lines[$i]->fk_unit);
+ $result = $object->addline(
+ $desc, $lines[$i]->subprice, $lines[$i]->qty, $tva_tx, $localtax1_tx, $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, $lines[$i]->rang, $lines[$i]->special_code, $object->origin, $lines[$i]->rowid,
+ $fk_parent_line, $lines[$i]->fk_fournprice, $lines[$i]->pa_ht, $label, $array_options,
+ $lines[$i]->situation_percent, $lines[$i]->fk_prev_id, $lines[$i]->fk_unit
+ );
if ($result > 0) {
$lineid = $result;
@@ -1421,6 +1503,7 @@ if (empty($reshook))
}
}
+ // Situation invoices
if (GETPOST('type') == Facture::TYPE_SITUATION && (!empty($_POST['situations'])))
{
$datefacture = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']);
@@ -1472,16 +1555,16 @@ if (empty($reshook))
$object->fetch_thirdparty();
$object->date = $datefacture;
$object->date_pointoftax = $date_pointoftax;
- $object->note_public = trim($_POST['note_public']);
- $object->note = trim($_POST['note']);
- $object->ref_client = $_POST['ref_client'];
- $object->ref_int = $_POST['ref_int'];
- $object->modelpdf = $_POST['model'];
- $object->fk_project = $_POST['projectid'];
- $object->cond_reglement_id = $_POST['cond_reglement_id'];
- $object->mode_reglement_id = $_POST['mode_reglement_id'];
- $object->remise_absolue = $_POST['remise_absolue'];
- $object->remise_percent = $_POST['remise_percent'];
+ $object->note_public = trim(GETPOST('note_public','none'));
+ $object->note = trim(GETPOST('note','none'));
+ $object->ref_client = GETPOST('ref_client','alpha');
+ $object->ref_int = GETPOST('ref_int','alpha');
+ $object->modelpdf = GETPOST('model','alpha');
+ $object->fk_project = GETPOST('projectid','int');
+ $object->cond_reglement_id = GETPOST('cond_reglement_id','int');
+ $object->mode_reglement_id = GETPOST('mode_reglement_id','int');
+ $object->remise_absolue = GETPOST('remise_absolue','int');
+ $object->remise_percent = GETPOST('remise_percent','int');
// Proprietes particulieres a facture de remplacement
@@ -1550,14 +1633,14 @@ if (empty($reshook))
// Set if we used free entry or predefined product
$predef='';
- $product_desc=(GETPOST('dp_desc')?GETPOST('dp_desc'):'');
+ $product_desc=(GETPOST('dp_desc','none')?GETPOST('dp_desc','none'):'');
$price_ht = GETPOST('price_ht');
$price_ht_devise = GETPOST('multicurrency_price_ht');
$prod_entry_mode = GETPOST('prod_entry_mode','alpha');
if ($prod_entry_mode == 'free')
{
$idprod=0;
- $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0);
+ $tva_tx = (GETPOST('tva_tx','alpha') ? GETPOST('tva_tx','alpha') : 0);
}
else
{
@@ -1734,7 +1817,28 @@ if (empty($reshook))
// If price per quantity and customer
elseif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))
{
- // TODO Same than PRODUIT_CUSTOMER_PRICES_BY_QTY but using $object->thirdparty->price_level
+ if ($prod->prices_by_qty[$object->thirdparty->price_level]) // yes, this product has some prices per quantity
+ {
+ // Search the correct price into loaded array product_price_by_qty using id of array retrieved into POST['pqp'].
+ $pqp = GETPOST('pbq','int');
+
+ // Search price into product_price_by_qty from $prod->id
+ foreach($prod->prices_by_qty_list[$object->thirdparty->price_level] as $priceforthequantityarray)
+ {
+ if ($priceforthequantityarray['rowid'] != $pqp) continue;
+ // We found the price
+ if ($priceforthequantityarray['price_base_type'] == 'HT')
+ {
+ $pu_ht = $priceforthequantityarray['unitprice'];
+ }
+ else
+ {
+ $pu_ttc = $priceforthequantityarray['unitprice'];
+ }
+ // Note: the remise_percent or price by qty is used to set data on form, so we will use value from POST.
+ break;
+ }
+ }
}
$tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $tva_tx));
@@ -1965,7 +2069,25 @@ if (empty($reshook))
$line->fetch(GETPOST('lineid'));
$percent = $line->get_prev_progress($object->id);
- if (GETPOST('progress') < $percent)
+ if($object->type == Facture::TYPE_CREDIT_NOTE && $object->situation_cycle_ref>0)
+ {
+ // in case of situation credit note
+ if(GETPOST('progress') >= 0 )
+ {
+ $mesg = $langs->trans("CantBeNullOrPositive");
+ setEventMessages($mesg, null, 'warnings');
+ $error++;
+ $result = -1;
+ }
+ elseif (GETPOST('progress') < $line->situation_percent) // TODO : use a modified $line->get_prev_progress($object->id) result
+ {
+ $mesg = $langs->trans("CantBeLessThanMinPercent");
+ setEventMessages($mesg, null, 'warnings');
+ $error++;
+ $result = -1;
+ }
+ }
+ elseif (GETPOST('progress') < $percent)
{
$mesg = '' . $langs->trans("CantBeLessThanMinPercent") . '
';
setEventMessages($mesg, null, 'warnings');
@@ -1983,7 +2105,7 @@ if (empty($reshook))
$type = $product->type;
$price_min = $product->price_min;
- if (! empty($conf->global->PRODUIT_MULTIPRICES) && ! empty($object->thirdparty->price_level))
+ if ((! empty($conf->global->PRODUIT_MULTIPRICES) || ! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && ! empty($object->thirdparty->price_level))
$price_min = $product->multiprices_min [$object->thirdparty->price_level];
$label = ((GETPOST('update_label') && GETPOST('product_label')) ? GETPOST('product_label') : '');
@@ -2111,6 +2233,208 @@ if (empty($reshook))
exit();
}
+ // Outing situation invoice from cycle
+ elseif ($action == 'confirm_situationout' && $confirm == 'yes' && $user->rights->facture->creer)
+ {
+ $object->fetch($id,'', '','', true);
+
+ if ($object->statut == Facture::STATUS_VALIDATED
+ && $object->type == Facture::TYPE_SITUATION
+ && $user->rights->facture->creer
+ && !$objectidnext
+ && $object->is_last_in_cycle()
+ && ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer))
+ || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->unvalidate)))
+ )
+ {
+ $outingError = 0;
+ $newCycle = $object->newCycle(); // we need to keep the "situation behavior" so we place it on a new situation cycle
+ if($newCycle > 1)
+ {
+ // Search credit notes
+ $lastCycle = $object->situation_cycle_ref;
+ $lastSituationCounter = $object->situation_counter;
+ $linkedCreditNotesList = array();
+
+ if (count($object->tab_next_situation_invoice) > 0) {
+ foreach ($object->tab_next_situation_invoice as $next_invoice) {
+ if($next_invoice->type == Facture::TYPE_CREDIT_NOTE
+ && $next_invoice->situation_counter == $object->situation_counter
+ && $next_invoice->fk_facture_source == $object->id
+ )
+ {
+ $linkedCreditNotesList[] = $next_invoice->id ;
+ }
+ }
+ }
+
+ $object->situation_cycle_ref = $newCycle;
+ $object->situation_counter = 1;
+ $object->situation_final = 0;
+ if($object->update($user) > 0)
+ {
+ $errors = 0;
+ if(count($linkedCreditNotesList) > 0)
+ {
+ // now, credit note must follow
+ $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture ';
+ $sql.= ' SET situation_cycle_ref='.$newCycle;
+ $sql.= ' , situation_final=0';
+ $sql.= ' , situation_counter='.$object->situation_counter;
+ $sql.= ' WHERE rowid IN ('.implode(',',$linkedCreditNotesList).')';
+
+ $resql=$db->query($sql);
+ if (!$resql) $errors++;
+
+ // Change each progression persent on each lines
+ foreach($object->lines as $line)
+ {
+
+ // no traitement for special product
+ if ($line->product_type == 9 ) continue;
+
+
+ if(!empty($object->tab_previous_situation_invoice))
+ {
+ // search the last invoice in cycle
+ $lineIndex = count($object->tab_previous_situation_invoice) - 1;
+ $searchPreviousInvoice = true;
+ while( $searchPreviousInvoice )
+ {
+ if($object->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_SITUATION || $lineIndex < 1)
+ {
+ $searchPreviousInvoice=false; // find, exit;
+ break;
+ }
+ else
+ {
+ $lineIndex--; // go to previous invoice in cycle
+ }
+ }
+
+
+ $maxPrevSituationPercent = 0;
+ foreach($object->tab_previous_situation_invoice[$lineIndex]->lines as $prevLine)
+ {
+ if($prevLine->id == $line->fk_prev_id)
+ {
+ $maxPrevSituationPercent = max($maxPrevSituationPercent,$prevLine->situation_percent);
+ }
+ }
+
+
+ $line->situation_percent = $line->situation_percent - $maxPrevSituationPercent;
+
+ if($line->update()<0) $errors++;
+
+ }
+ }
+ }
+
+ if (!$errors)
+ {
+ setEventMessages($langs->trans('Updated'), '', 'mesgs');
+ header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
+ }
+ else
+ {
+ setEventMessages($langs->trans('ErrorOutingSituationInvoiceCreditNote'), array(), 'errors');
+ }
+ }
+ else
+ {
+ setEventMessages($langs->trans('ErrorOutingSituationInvoiceOnUpdate'), array(), 'errors');
+ }
+ }
+ else
+ {
+ setEventMessages($langs->trans('ErrorFindNextSituationInvoice'), array(), 'errors');
+ }
+ }
+ }
+
+ // add lines from objectlinked
+ elseif($action == 'import_lines_from_object'
+ && $user->rights->facture->creer
+ && $object->statut == Facture::STATUS_DRAFT
+ && ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA || $object->type == Facture::TYPE_SITUATION))
+ {
+ $fromElement = GETPOST('fromelement');
+ $fromElementid = GETPOST('fromelementid');
+ $importLines = GETPOST('line_checkbox');
+
+ if(!empty($importLines) && is_array($importLines) && !empty($fromElement) && ctype_alpha($fromElement) && !empty($fromElementid))
+ {
+ if($fromElement == 'commande')
+ {
+ dol_include_once('/'.$fromElement.'/class/'.$fromElement.'.class.php');
+ $lineClassName = 'OrderLine';
+ }
+ elseif($fromElement == 'propal')
+ {
+ dol_include_once('/comm/'.$fromElement.'/class/'.$fromElement.'.class.php');
+ $lineClassName = 'PropaleLigne';
+ }
+ $nextRang = count($object->lines) + 1;
+ $importCount = 0;
+ $error = 0;
+ foreach($importLines as $lineId)
+ {
+ $lineId = intval($lineId);
+ $originLine = new $lineClassName($db);
+ if(intval($fromElementid) > 0 && $originLine->fetch( $lineId ) > 0)
+ {
+ $originLine->fetch_optionals($lineId);
+ $desc = $originLine->desc;
+ $pu_ht = $originLine->subprice;
+ $qty = $originLine->qty;
+ $txtva = $originLine->tva_tx;
+ $txlocaltax1 = $originLine->localtax1_tx;
+ $txlocaltax2 = $originLine->localtax2_tx;
+ $fk_product = $originLine->fk_product;
+ $remise_percent = $originLine->remise_percent;
+ $date_start = $originLine->date_start;
+ $date_end = $originLine->date_end;
+ $ventil = 0;
+ $info_bits = $originLine->info_bits;
+ $fk_remise_except = $originLine->fk_remise_except;
+ $price_base_type='HT';
+ $pu_ttc=0;
+ $type = $originLine->product_type;
+ $rang=$nextRang++;
+ $special_code = $originLine->special_code;
+ $origin = $originLine->element;
+ $origin_id = $originLine->id;
+ $fk_parent_line=0;
+ $fk_fournprice=$originLine->fk_fournprice;
+ $pa_ht = $originLine->pa_ht;
+ $label = $originLine->label;
+ $array_options = $originLine->array_options;
+ $situation_percent = 100;
+ $fk_prev_id = '';
+ $fk_unit = $originLine->fk_unit;
+ $pu_ht_devise = $originLine->multicurrency_subprice;
+
+ $res = $object->addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $ventil, $info_bits, $fk_remise_except, $price_base_type, $pu_ttc, $type, $rang, $special_code, $origin, $origin_id, $fk_parent_line, $fk_fournprice, $pa_ht, $label, $array_options, $situation_percent, $fk_prev_id, $fk_unit,$pu_ht_devise);
+
+ if($res > 0){
+ $importCount++;
+ }else{
+ $error++;
+ }
+ }
+ else{
+ $error++;
+ }
+ }
+
+ if($error)
+ {
+ setEventMessage($langs->trans('ErrorsOnXLines',$error), 'errors');
+ }
+ }
+ }
+
// Actions when printing a doc from card
include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
@@ -2129,27 +2453,22 @@ if (empty($reshook))
if ($action == 'update_extras') {
+ $object->oldcopy = dol_clone($object);
+
// Fill array 'array_options' with data from add form
$extralabels = $extrafields->fetch_name_optionals_label($object->table_element);
- $ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute'));
+ $ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute','none'));
if ($ret < 0) $error++;
- if (! $error) {
- // Actions on extra fields (by external module or standard code)
- // TODO le hook fait double emploi avec le trigger !!
- $hookmanager->initHooks(array('invoicedao'));
- $parameters = array('id' => $object->id);
- $reshook = $hookmanager->executeHooks('insertExtraFields', $parameters, $object, $action); // Note that $action and $object may have been modified by
- // some hooks
- if (empty($reshook)) {
- $result = $object->insertExtraFields();
- if ($result < 0)
- {
- setEventMessages($object->error, $object->errors, 'errors');
- $error++;
- }
- } else if ($reshook < 0)
- $error ++;
+ if (! $error)
+ {
+ // Actions on extra fields
+ $result = $object->insertExtraFields('BILL_MODIFY');
+ if ($result < 0)
+ {
+ setEventMessages($object->error, $object->errors, 'errors');
+ $error++;
+ }
}
if ($error)
@@ -2554,7 +2873,7 @@ if ($action == 'create')
if (($origin == 'propal') || ($origin == 'commande'))
{
print ' ';
- $arraylist = array('amount' => 'FixAmount','variable' => 'VarAmount');
+ $arraylist = array('amount' => $langs->transnoentitiesnoconv('FixAmount'), 'variable' => $langs->transnoentitiesnoconv('VarAmountOneLine', $langs->transnoentitiesnoconv('Deposit')));
print $form->selectarray('typedeposit', $arraylist, GETPOST('typedeposit'), 0, 0, 0, '', 1);
print ' ';
print '' . $langs->trans('Value') . ': ';
@@ -2714,19 +3033,12 @@ if ($action == 'create')
{
// Discounts for third party
print ' ' . $langs->trans('Discounts') . ' ';
- if ($soc->remise_percent)
- print $langs->trans("CompanyHasRelativeDiscount", 'id . '&action=' . $action . '&origin=' . GETPOST('origin') . '&originid=' . GETPOST('originid')) . '">' . $soc->remise_percent . ' ');
- else
- print $langs->trans("CompanyHasNoRelativeDiscount");
- print ' id . '&action=' . $action . '&origin=' . GETPOST('origin') . '&originid=' . GETPOST('originid')) . '">(' . $langs->trans("EditRelativeDiscount") . ') ';
- print '. ';
- print ' ';
- if ($absolute_discount)
- print $langs->trans("CompanyHasAbsoluteDiscount", 'id . '&action=' . $action . '&origin=' . GETPOST('origin') . '&originid=' . GETPOST('originid')) . '">' . price($absolute_discount) . ' ', $langs->trans("Currency" . $conf->currency));
- else
- print $langs->trans("CompanyHasNoAbsoluteDiscount");
- print ' id . '&action=' . $action . '&origin=' . GETPOST('origin') . '&originid=' . GETPOST('originid')) . '">(' . $langs->trans("EditGlobalDiscounts") . ') ';
- print '.';
+
+ $thirdparty = $soc;
+ $discount_type = 0;
+ $backtopage = urlencode($_SERVER["PHP_SELF"] . '?socid=' . $thirdparty->id . '&action=' . $action . '&origin=' . GETPOST('origin') . '&originid=' . GETPOST('originid'));
+ include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php';
+
print ' ';
}
@@ -2796,7 +3108,7 @@ if ($action == 'create')
$parameters = array('objectsrc' => $objectsrc,'colspan' => ' colspan="2"', 'cols'=>2);
$reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;
- if (empty($reshook) && ! empty($extrafields->attribute_label)) {
+ if (empty($reshook)) {
print $object->showOptionals($extrafields, 'edit');
}
@@ -2888,7 +3200,7 @@ if ($action == 'create')
print ' ';
print ' ';
- switch ($classname) {
+ switch (get_class($objectsrc)) {
case 'Propal':
$newclassname = 'CommercialProposal';
break;
@@ -2905,7 +3217,7 @@ if ($action == 'create')
$newclassname = 'Intervention';
break;
default:
- $newclassname = $classname;
+ $newclassname = get_class($objectsrc);
}
print '' . $langs->trans($newclassname) . ' ' . $objectsrc->getNomUrl(1);
@@ -3015,7 +3327,7 @@ else if ($id > 0 || ! empty($ref))
$filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
$filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
} else {
- $filterabsolutediscount = "fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%'))";
+ $filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')";
$filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')";
}
@@ -3074,7 +3386,25 @@ else if ($id > 0 || ! empty($ref))
);
$formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $langs->trans('DeleteBill'), $text, 'confirm_delete', $formquestion, "yes", 1);
} else {
- $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $langs->trans('DeleteBill'), $text, 'confirm_delete', '', '', 1);
+ $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $langs->trans('DeleteBill'), $text, 'confirm_delete', '', 'no', 1);
+ }
+ }
+
+ // Confirmation to remove invoice from cycle
+ if ($action == 'situationout') {
+ $text = $langs->trans('ConfirmRemoveSituationFromCycle', $object->ref);
+ $label = $langs->trans("ConfirmOuting");
+ $formquestion = array();
+ // remove situation from cycle
+ if ($object->statut == Facture::STATUS_VALIDATED
+ && $user->rights->facture->creer
+ && !$objectidnext
+ && $object->is_last_in_cycle()
+ && ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer))
+ || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->unvalidate)))
+ )
+ {
+ $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $label, $text, 'confirm_situationout', $formquestion, "yes", 1);
}
}
@@ -3185,31 +3515,31 @@ else if ($id > 0 || ! empty($ref))
if ($action == 'paid' && $resteapayer > 0) {
// Code
$i = 0;
- $close [$i] ['code'] = 'discount_vat'; // escompte
+ $close [$i]['code'] = 'discount_vat'; // escompte
$i ++;
- $close [$i] ['code'] = 'badcustomer';
+ $close [$i]['code'] = 'badcustomer';
$i ++;
// Help
$i = 0;
- $close [$i] ['label'] = $langs->trans("HelpEscompte") . ' ' . $langs->trans("ConfirmClassifyPaidPartiallyReasonDiscountVatDesc");
+ $close [$i]['label'] = $langs->trans("HelpEscompte") . ' ' . $langs->trans("ConfirmClassifyPaidPartiallyReasonDiscountVatDesc");
$i ++;
- $close [$i] ['label'] = $langs->trans("ConfirmClassifyPaidPartiallyReasonBadCustomerDesc");
+ $close [$i]['label'] = $langs->trans("ConfirmClassifyPaidPartiallyReasonBadCustomerDesc");
$i ++;
// Texte
$i = 0;
- $close [$i] ['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonDiscount", $resteapayer, $langs->trans("Currency" . $conf->currency)), $close [$i] ['label'], 1);
+ $close [$i]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonDiscount", $resteapayer, $langs->trans("Currency" . $conf->currency)), $close[$i]['label'], 1);
$i ++;
- $close [$i] ['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadCustomer", $resteapayer, $langs->trans("Currency" . $conf->currency)), $close [$i] ['label'], 1);
+ $close [$i]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadCustomer", $resteapayer, $langs->trans("Currency" . $conf->currency)), $close[$i]['label'], 1);
$i ++;
// arrayreasons[code]=reason
foreach ($close as $key => $val) {
- $arrayreasons [$close [$key] ['code']] = $close [$key] ['reason'];
+ $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'));
+ $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' => '','morecss' => 'minwidth300'));
// Paiement incomplet. On demande si motif = escompte ou autre
- $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?facid=' . $object->id, $langs->trans('ClassifyPaid'), $langs->trans('ConfirmClassifyPaidPartially', $object->ref), 'confirm_paid_partially', $formquestion, "yes");
+ $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?facid=' . $object->id, $langs->trans('ClassifyPaid'), $langs->trans('ConfirmClassifyPaidPartially', $object->ref), 'confirm_paid_partially', $formquestion, "yes", 1, 310);
}
// Confirmation du classement abandonne
@@ -3238,16 +3568,16 @@ else if ($id > 0 || ! empty($ref))
$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'));
+ $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' => '','morecss' => 'minwidth300'));
- $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $langs->trans('CancelBill'), $langs->trans('ConfirmCancelBill', $object->ref), 'confirm_canceled', $formquestion, "yes");
+ $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $langs->trans('CancelBill'), $langs->trans('ConfirmCancelBill', $object->ref), 'confirm_canceled', $formquestion, "yes", 1, 250);
}
}
if ($action == 'deletepaiement')
{
$payment_id = GETPOST('paiement_id');
- $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&paiement_id='.$payment_id, $langs->trans('DeletePayment'), $langs->trans('ConfirmDeletePayment'), 'confirm_delete_paiement', '', 0, 1);
+ $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&paiement_id='.$payment_id, $langs->trans('DeletePayment'), $langs->trans('ConfirmDeletePayment'), 'confirm_delete_paiement', '', 'no', 1);
}
@@ -3288,7 +3618,7 @@ else if ($id > 0 || ! empty($ref))
$morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->facture->creer, 'string', '', 0, 1);
$morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->facture->creer, 'string', '', null, null, '', 1);
// Thirdparty
- $morehtmlref.=' '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1);
+ $morehtmlref.=' '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1,'customer');
if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref.=' ('.$langs->trans("OtherBills").' )';
// Project
if (! empty($conf->projet->enabled))
@@ -3373,90 +3703,20 @@ else if ($id > 0 || ! empty($ref))
$discount = new DiscountAbsolute($db);
$result = $discount->fetch(0, $object->id);
if ($result > 0){
- print '. '.$langs->trans("CreditNoteConvertedIntoDiscount", $object->getLibType(), $discount->getNomUrl(1, 'discount')).' ';
+ print '. '.$langs->trans("CreditNoteConvertedIntoDiscount", $object->getLibType(1), $discount->getNomUrl(1, 'discount')).' ';
}
}
print ' ';
// Relative and absolute discounts
- $addrelativediscount = 'id . '">' . $langs->trans("EditRelativeDiscounts") . ' ';
- $addabsolutediscount = 'id . '">' . $langs->trans("EditGlobalDiscounts") . ' ';
- $addcreditnote = 'id . '">' . $langs->trans("AddCreditNote") . ' ';
- $viewabsolutediscount = 'id . '">' . $langs->trans("ViewAvailableGlobalDiscounts") . ' ';
-
print '' . $langs->trans('Discounts');
- print ' ';
- if ($soc->remise_percent)
- print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent);
- else
- print $langs->trans("CompanyHasNoRelativeDiscount");
- // print ' ('.$addrelativediscount.')';
- // Is there is commercial discount or down payment available ?
- if ($absolute_discount > 0) {
- print '. ';
- if ($object->statut > 0 || $object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT) {
- if ($object->statut == 0) {
- print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency));
- print '. ';
- } else {
- if ($object->statut < 1 || $object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT) {
- $text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency));
- print ' ' . $text . '. ';
- } else {
- $text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency));
- $text2 = $langs->trans("AbsoluteDiscountUse");
- print $form->textwithpicto($text, $text2);
- }
- }
- } else {
- // Discount available of type fixed amount (not credit note)
- print ' ';
- $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, GETPOST('discountid'), 'remise_id', $soc->id, $absolute_discount, $filterabsolutediscount, $resteapayer, ' (' . $addabsolutediscount . ')');
- }
- } else {
- if ($absolute_creditnote > 0) // If not, link will be added later
- {
- if ($object->statut == Facture::STATUS_DRAFT && $object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_DEPOSIT)
- print ' (' . $addabsolutediscount . ') ';
- else
- print '. ';
- } else
- print '. ';
- }
- // Is there credit notes availables ?
- if ($absolute_creditnote > 0)
- {
- // If validated, we show link "add credit note to payment"
- if ($object->statut != Facture::STATUS_VALIDATED || $object->type == Facture::TYPE_CREDIT_NOTE) {
- if ($object->statut == 0 && $object->type != Facture::TYPE_DEPOSIT) {
- $text = $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency));
- print $form->textwithpicto($text, $langs->trans("CreditNoteDepositUse"));
- } else {
- print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)) . '.';
- }
- } else { // We can add a credit note on a down payment or standard invoice or situation invoice
- // There is credit notes discounts available
- if (! $absolute_discount) print ' ';
- // $form->form_remise_dispo($_SERVER["PHP_SELF"].'?facid='.$object->id, 0, 'remise_id_for_payment', $soc->id, $absolute_creditnote, $filtercreditnote, $resteapayer);
- $more=' ('.$addcreditnote. (($addcreditnote && $viewabsolutediscount) ? ' - ' : '') . $viewabsolutediscount . ')';
- $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, 0, 'remise_id_for_payment', $soc->id, $absolute_creditnote, $filtercreditnote, 0, $more); // We allow credit note even if amount is higher
- }
- }
- if (! $absolute_discount && ! $absolute_creditnote) {
- print $langs->trans("CompanyHasNoAbsoluteDiscount");
- if ($object->statut == Facture::STATUS_DRAFT && $object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_DEPOSIT)
- print ' (' . $addabsolutediscount . ') ';
- else
- print '. ';
- }
- // if ($object->statut == 0 && $object->type != 2 && $object->type != 3)
- // {
- // if (! $absolute_discount && ! $absolute_creditnote) print ' ';
- // print ' - ';
- // print $addabsolutediscount;
- // print ' - '.$addcreditnote; // We disbale link to credit note
- // }
+ print ' ';
+ $thirdparty = $soc;
+ $discount_type = 0;
+ $backtopage = urlencode($_SERVER["PHP_SELF"] . '?facid=' . $object->id);
+ include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php';
+
print ' ';
// Date invoice
@@ -3629,54 +3889,10 @@ else if ($id > 0 || ! empty($ref))
print "";
print '';
- // Situations
- if (! empty($conf->global->INVOICE_USE_SITUATION))
- {
- if ($object->type == 5 && ($object->situation_counter > 1))
- {
- $prevsits = $object->get_prev_sits();
- print '';
- print $langs->trans('SituationAmount');
- print ' ';
- print $prevsits[0]->situation_counter;
- $cprevsits = count($prevsits);
- for ($i = 1; $i < $cprevsits; $i++) {
- print ' + ';
- print $prevsits[$i]->situation_counter;
- }
- print ' + ';
- print $object->situation_counter;
- print ' ';
- print '';
- $prevsits_total_amount = 0;
- foreach ($prevsits as $situation) {
- $prevsits_total_amount += $situation->total_ht;
- }
- $prevsits_total_amount += $object->total_ht;
-
- print price($prevsits_total_amount, 0, $langs, 1, -1, -1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency) );
-
- print ' ';
-
- // Previous situation(s) deduction(s)
- for ($i = 0; $i < $cprevsits; $i++) {
- print '';
- print '';
- print $langs->trans('SituationDeduction');
- print ' ';
- print $prevsits[$i]->situation_counter;
- print ' ';
-
- print '';
- print '- ' . price($prevsits[$i]->total_ht, 0, $langs, 1, -1, -1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency) );
- print ' ';
- }
- }
- }
// Incoterms
if (!empty($conf->incoterm->enabled))
@@ -3812,8 +4028,6 @@ else if ($id > 0 || ! empty($ref))
print '
';
- // List of previous situation invoices
-
$sign = 1;
if ($object->type == Facture::TYPE_CREDIT_NOTE) $sign = - 1;
$nbrows = 8;
@@ -3835,88 +4049,129 @@ else if ($id > 0 || ! empty($ref))
if (! empty($conf->incoterm->enabled))
$nbrows += 1;
- if ($object->type == Facture::TYPE_SITUATION && ! empty($conf->global->INVOICE_USE_SITUATION))
+ // List of previous situation invoices
+ if (($object->situation_cycle_ref > 0) && ! empty($conf->global->INVOICE_USE_SITUATION))
{
- if (count($object->tab_previous_situation_invoice) > 0 || count($object->tab_next_situation_invoice) > 0)
- print '';
- if (count($object->tab_previous_situation_invoice) > 0) {
- // List of previous invoices
- print '';
- print '' . $langs->trans('ListOfPreviousSituationInvoices') . ' ';
- print ' ';
- if (! empty($conf->banque->enabled)) print ' ';
- print '' . $langs->trans('AmountHT') . ' ';
- print '' . $langs->trans('AmountTTC') . ' ';
- print ' ';
- print ' ';
+ print '';
- $total_prev_ht = $total_prev_ttc = 0;
- foreach ($object->tab_previous_situation_invoice as $prev_invoice) {
- $totalpaye = $prev_invoice->getSommePaiement();
- $total_prev_ht += $prev_invoice->total_ht;
- $total_prev_ttc += $prev_invoice->total_ttc;
- print '';
- print '' . $prev_invoice->getNomUrl(1) . ' ';
- print ' ';
- if (! empty($conf->banque->enabled)) print ' ';
- print '' . price($prev_invoice->total_ht) . ' ';
- print '' . price($prev_invoice->total_ttc) . ' ';
- print '' . $prev_invoice->getLibStatut(3, $totalpaye) . ' ';
- print ' ';
- }
+ print '';
+ print '' . $langs->trans('ListOfSituationInvoices') . ' ';
+ print ' ';
+ print '' . $langs->trans('Situation') . ' ';
+ if (! empty($conf->banque->enabled)) print ' ';
+ print '' . $langs->trans('AmountHT') . ' ';
+ print '' . $langs->trans('AmountTTC') . ' ';
+ print ' ';
+ print ' ';
- print '';
- print ' ';
- print ' ';
- if (! empty($conf->banque->enabled)) print ' ';
- print '' . price($total_prev_ht) . ' ';
- print '' . price($total_prev_ttc) . ' ';
- print ' ';
- print ' ';
- }
- if (count($object->tab_next_situation_invoice) > 0) {
- // List of next invoices
- print '';
- print '' . $langs->trans('ListOfNextSituationInvoices') . ' ';
- print ' ';
- if (! empty($conf->banque->enabled)) print ' ';
- print '' . $langs->trans('AmountHT') . ' ';
- print '' . $langs->trans('AmountTTC') . ' ';
- print ' ';
- print ' ';
+ $total_prev_ht = $total_prev_ttc = 0;
+ $total_global_ht = $total_global_ttc = 0;
- $total_next_ht = $total_next_ttc = 0;
+ if (count($object->tab_previous_situation_invoice) > 0) {
+ // List of previous invoices
- foreach ($object->tab_next_situation_invoice as $next_invoice) {
- $totalpaye = $next_invoice->getSommePaiement();
- $total_next_ht += $next_invoice->total_ht;
- $total_next_ttc += $next_invoice->total_ttc;
- print '';
- print '' . $next_invoice->getNomUrl(1) . ' ';
- print ' ';
- if (! empty($conf->banque->enabled)) print ' ';
- print '' . price($next_invoice->total_ht) . ' ';
- print '' . price($next_invoice->total_ttc) . ' ';
- print '' . $next_invoice->getLibStatut(3, $totalpaye) . ' ';
- print ' ';
+ $current_situation_counter = array();
+ foreach ($object->tab_previous_situation_invoice as $prev_invoice) {
+ $totalpaye = $prev_invoice->getSommePaiement();
+ $total_prev_ht += $prev_invoice->total_ht;
+ $total_prev_ttc += $prev_invoice->total_ttc;
+ $current_situation_counter[] = (($prev_invoice->type == Facture::TYPE_CREDIT_NOTE)?-1:1) * $prev_invoice->situation_counter;
+ print '';
+ print '' . $prev_invoice->getNomUrl(1) . ' ';
+ print ' ';
+ print ''.(($prev_invoice->type == Facture::TYPE_CREDIT_NOTE)?$langs->trans('situationInvoiceShortcode_AS'):$langs->trans('situationInvoiceShortcode_S')) . $prev_invoice->situation_counter.' ';
+ if (! empty($conf->banque->enabled)) print ' ';
+ print '' . price($prev_invoice->total_ht) . ' ';
+ print '' . price($prev_invoice->total_ttc) . ' ';
+ print '' . $prev_invoice->getLibStatut(3, $totalpaye) . ' ';
+ print ' ';
+ }
+ }
- }
- print '';
- print ' ';
- if (! empty($conf->banque->enabled)) print ' ';
+ $total_global_ht += $total_prev_ht ;
+ $total_global_ttc += $total_prev_ttc ;
+ $total_global_ht += $object->total_ht;
+ $total_global_ttc += $object->total_ttc;
+ $current_situation_counter[] = (($object->type == Facture::TYPE_CREDIT_NOTE)?-1:1) * $object->situation_counter;
+ print ' ';
+ print '' . $object->getNomUrl(1) . ' ';
+ print ' ';
+ print ''.(($object->type == Facture::TYPE_CREDIT_NOTE)?$langs->trans('situationInvoiceShortcode_AS'):$langs->trans('situationInvoiceShortcode_S')) . $object->situation_counter.' ';
+ if (! empty($conf->banque->enabled)) print ' ';
+ print '' . price($object->total_ht) . ' ';
+ print '' . price($object->total_ttc) . ' ';
+ print '' . $object->getLibStatut(3, $object->getSommePaiement()) . ' ';
+ print ' ';
- print '' . price($total_next_ht) . ' ';
- print '' . price($total_next_ttc) . ' ';
- print ' ';
- print '';
- }
- if (count($object->tab_previous_situation_invoice) > 0 || count($object->tab_next_situation_invoice) > 0)
- print '
';
+ print '';
+ print '' . $langs->trans('CurrentSituationTotal') . ' ';
+ print '';
+ $i =0;
+ foreach ($current_situation_counter as $sit)
+ {
+ $curSign = $sit>0?'+':'-';
+ $curType = $sit>0?$langs->trans('situationInvoiceShortcode_S'):$langs->trans('situationInvoiceShortcode_AS');
+ if($i>0) print ' '.$curSign.' ';
+ print $curType . abs($sit);
+ $i++;
+ }
+ print ' ';
+ if (! empty($conf->banque->enabled)) print ' ';
+ print '' . price($total_global_ht) . ' ';
+ print '' . price($total_global_ttc) . ' ';
+ print ' ';
+ print ' ';
+
+
+ if (count($object->tab_next_situation_invoice) > 0) {
+ // List of next invoices
+ /*print '';
+ print '' . $langs->trans('ListOfNextSituationInvoices') . ' ';
+ print ' ';
+ print ' ';
+ if (! empty($conf->banque->enabled)) print ' ';
+ print '' . $langs->trans('AmountHT') . ' ';
+ print '' . $langs->trans('AmountTTC') . ' ';
+ print ' ';
+ print ' ';*/
+
+ $total_next_ht = $total_next_ttc = 0;
+
+ foreach ($object->tab_next_situation_invoice as $next_invoice) {
+ $totalpaye = $next_invoice->getSommePaiement();
+ $total_next_ht += $next_invoice->total_ht;
+ $total_next_ttc += $next_invoice->total_ttc;
+
+ print '';
+ print '' . $next_invoice->getNomUrl(1) . ' ';
+ print ' ';
+ print ''.(($next_invoice->type == Facture::TYPE_CREDIT_NOTE)?$langs->trans('situationInvoiceShortcode_AS'):$langs->trans('situationInvoiceShortcode_S')) . $next_invoice->situation_counter.' ';
+ if (! empty($conf->banque->enabled)) print ' ';
+ print '' . price($next_invoice->total_ht) . ' ';
+ print '' . price($next_invoice->total_ttc) . ' ';
+ print '' . $next_invoice->getLibStatut(3, $totalpaye) . ' ';
+ print ' ';
+
+ }
+
+ $total_global_ht += $total_next_ht;
+ $total_global_ttc += $total_next_ttc;
+
+ print '';
+ print ' ';
+ if (! empty($conf->banque->enabled)) print ' ';
+ print '' . price($total_global_ht) . ' ';
+ print '' . price($total_global_ttc) . ' ';
+ print ' ';
+ print ' ';
+ }
+
+ print '
';
}
@@ -4068,7 +4323,7 @@ else if ($id > 0 || ! empty($ref))
print $form->textwithpicto($langs->trans("Discount") . ':', $langs->trans("HelpEscompte"), - 1);
print ' ' . price(price2num($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye, 'MT')) . ' ';
$resteapayeraffiche = 0;
- $cssforamountpaymentcomplete = '';
+ $cssforamountpaymentcomplete = 'amountpaymentneutral';
}
// Paye partiellement ou Abandon 'badcustomer'
if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'badcustomer') {
@@ -4076,7 +4331,7 @@ else if ($id > 0 || ! empty($ref))
print $form->textwithpicto($langs->trans("Abandoned") . ':', $langs->trans("HelpAbandonBadCustomer"), - 1);
print '' . price(price2num($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye, 'MT')) . ' ';
// $resteapayeraffiche=0;
- $cssforamountpaymentcomplete = '';
+ $cssforamountpaymentcomplete = 'amountpaymentneutral';
}
// Paye partiellement ou Abandon 'product_returned'
if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'product_returned') {
@@ -4084,7 +4339,7 @@ else if ($id > 0 || ! empty($ref))
print $form->textwithpicto($langs->trans("ProductReturned") . ':', $langs->trans("HelpAbandonProductReturned"), - 1);
print '' . price(price2num($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye, 'MT')) . ' ';
$resteapayeraffiche = 0;
- $cssforamountpaymentcomplete = '';
+ $cssforamountpaymentcomplete = 'amountpaymentneutral';
}
// Paye partiellement ou Abandon 'abandon'
if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'abandon') {
@@ -4095,7 +4350,7 @@ else if ($id > 0 || ! empty($ref))
print $form->textwithpicto($langs->trans("Abandoned") . ':', $text, - 1);
print '' . price(price2num($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye, 'MT')) . ' ';
$resteapayeraffiche = 0;
- $cssforamountpaymentcomplete = '';
+ $cssforamountpaymentcomplete = 'amountpaymentneutral';
}
// Billed
@@ -4113,7 +4368,7 @@ else if ($id > 0 || ! empty($ref))
}
else // Credit note
{
- $cssforamountpaymentcomplete='';
+ $cssforamountpaymentcomplete='amountpaymentneutral';
// Total already paid back
print '';
@@ -4128,7 +4383,7 @@ else if ($id > 0 || ! empty($ref))
if ($resteapayeraffiche <= 0)
print $langs->trans('RemainderToPayBack');
else
- print $langs->trans('ExcessPaydBack');
+ print $langs->trans('ExcessPaid');
print ' : ';
print '' . price($sign * $resteapayeraffiche) . ' ';
print ' ';
@@ -4248,7 +4503,7 @@ else if ($id > 0 || ! empty($ref))
// Form to add new line
if ($object->statut == 0 && $user->rights->facture->creer && $action != 'valid' && $action != 'editline' && ($object->is_first() || !$object->situation_cycle_ref))
{
- if ($action != 'editline')
+ if ($action != 'editline' && $action != 'selectlines')
{
// Add free products/services
$object->formAddObjectLine(1, $mysoc, $soc);
@@ -4290,7 +4545,7 @@ else if ($id > 0 || ! empty($ref))
if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer))
|| (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->unvalidate)))
{
- print '';
+ print '';
} else {
print '' . $langs->trans('Modify') . '
';
}
@@ -4319,7 +4574,7 @@ else if ($id > 0 || ! empty($ref))
{
if (! $objectidnext && $object->close_code != 'replaced') // Not replaced by another invoice
{
- print '';
+ print '';
} else {
print '' . $langs->trans('ReOpen') . '
';
}
@@ -4330,19 +4585,19 @@ else if ($id > 0 || ! empty($ref))
if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer))
|| (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->validate)))
{
- print '';
+ print '';
}
}
// Send by mail
if (($object->statut == Facture::STATUS_VALIDATED || $object->statut == Facture::STATUS_CLOSED) || ! empty($conf->global->FACTURE_SENDBYEMAIL_FOR_ALL_STATUS)) {
if ($objectidnext) {
- print '' . $langs->trans('SendByMail') . '
';
+ print '' . $langs->trans('SendMail') . '
';
} else {
if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->facture->invoice_advance->send) {
- print '';
+ print '';
} else
- print '';
+ print '';
}
}
@@ -4402,16 +4657,16 @@ else if ($id > 0 || ! empty($ref))
// For standard invoice with excess received
if ($object->type == Facture::TYPE_STANDARD && empty($object->paye) && ($object->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits) < 0 && $user->rights->facture->creer && empty($discount->id))
{
- print '';
+ print '';
}
// For credit note
if ($object->type == Facture::TYPE_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0 && $user->rights->facture->creer && $object->getSommePaiement() == 0) {
- print '';
+ print '';
}
// For deposit invoice
if ($object->type == Facture::TYPE_DEPOSIT && $user->rights->facture->creer && $object->statut > 0 && empty($discount->id))
{
- print '';
+ print '';
}
}
@@ -4420,7 +4675,7 @@ else if ($id > 0 || ! empty($ref))
|| ($object->type == Facture::TYPE_DEPOSIT && $object->paye == 0 && $object->total_ttc > 0 && $resteapayer == 0 && $user->rights->facture->paiement && empty($discount->id))
)
{
- print '';
+ print '';
}
// Classify 'closed not completely paid' (possible si validee et pas encore classee payee)
@@ -4430,7 +4685,7 @@ else if ($id > 0 || ! empty($ref))
if ($totalpaye > 0 || $totalcreditnotes > 0)
{
// If one payment or one credit note was linked to this invoice
- print '';
+ print '';
}
else
{
@@ -4442,7 +4697,7 @@ else if ($id > 0 || ! empty($ref))
}
else
{
- print '';
+ print '';
}
}
}
@@ -4451,7 +4706,7 @@ else if ($id > 0 || ! empty($ref))
// Clone
if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA) && $user->rights->facture->creer)
{
- print '';
+ print '';
}
// Clone as predefined / Create template
@@ -4472,6 +4727,45 @@ else if ($id > 0 || ! empty($ref))
}
}
+ // For situation invoice with excess received
+ if ($object->statut > Facture::STATUS_DRAFT
+ && ($object->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits) > 0
+ && $user->rights->facture->creer
+ && !$objectidnext
+ && $object->is_last_in_cycle()
+ && $conf->global->INVOICE_USE_SITUATION_CREDIT_NOTE
+ )
+ {
+ if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer))
+ || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->unvalidate)))
+ {
+ print '';
+ } else {
+ print '' . $langs->trans("CreateCreditNote") . '
';
+ }
+ }
+
+ // remove situation from cycle
+ if ($object->statut > Facture::STATUS_DRAFT
+ && $object->type == Facture::TYPE_SITUATION
+ && $user->rights->facture->creer
+ && !$objectidnext
+ && $object->situation_counter > 1
+ && $object->is_last_in_cycle()
+ && ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer))
+ || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->unvalidate)))
+ )
+ {
+ if(($object->total_ttc - $totalcreditnotes ) == 0 )
+ {
+ print '';
+ }
+ else
+ {
+ print '';
+ }
+ }
+
// Create next situation invoice
if ($user->rights->facture->creer && ($object->type == 5) && ($object->statut == 1 || $object->statut == 2)) {
if ($object->is_last_in_cycle() && $object->situation_final != 1) {
@@ -4510,7 +4804,7 @@ else if ($id > 0 || ! empty($ref))
}
else
{
- print '';
+ print '';
}
} else {
print '';
@@ -4540,7 +4834,15 @@ else if ($id > 0 || ! empty($ref))
// Show links to link elements
$linktoelem = $form->showLinkToObjectBlock($object, null, array('invoice'));
- $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem);
+
+ $compatibleImportElementsList = false;
+ if($user->rights->facture->creer
+ && $object->statut == Facture::STATUS_DRAFT
+ && ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA || $object->type == Facture::TYPE_SITUATION) )
+ {
+ $compatibleImportElementsList = array('commande','propal'); // import from linked elements
+ }
+ $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem,$compatibleImportElementsList);
// Show online payment link
diff --git a/htdocs/compta/facture/class/api_invoices.class.php b/htdocs/compta/facture/class/api_invoices.class.php
index a114829d43c..7012b0ef800 100644
--- a/htdocs/compta/facture/class/api_invoices.class.php
+++ b/htdocs/compta/facture/class/api_invoices.class.php
@@ -81,6 +81,9 @@ class Invoices extends DolibarrApi
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
+ // Add external contacts ids
+ $this->invoice->contacts_ids = $this->invoice->liste_contact(-1,'external',1);
+
$this->invoice->fetchObjectLinked();
return $this->_cleanObjectDatas($this->invoice);
}
@@ -176,6 +179,9 @@ class Invoices extends DolibarrApi
$invoice_static->totaldeposits = $invoice_static->getSumDepositsUsed();
$invoice_static->remaintopay = price2num($invoice_static->total_ttc - $invoice_static->totalpaid - $invoice_static->totalcreditnotes - $invoice_static->totaldeposits, 'MT');
+ // Add external contacts ids
+ $invoice_static->contacts_ids = $invoice_static->liste_contact(-1,'external',1);
+
$obj_ret[] = $this->_cleanObjectDatas($invoice_static);
}
$i++;
@@ -196,7 +202,7 @@ class Invoices extends DolibarrApi
* @param array $request_data Request datas
* @return int ID of invoice
*/
- function post($request_data = NULL)
+ function post($request_data = null)
{
if(! DolibarrApiAccess::$user->rights->facture->creer) {
throw new RestException(401, "Insuffisant rights");
@@ -313,7 +319,7 @@ class Invoices extends DolibarrApi
* @throws 401
* @throws 404
*/
- function putLine($id, $lineid, $request_data = NULL) {
+ function putLine($id, $lineid, $request_data = null) {
if(! DolibarrApiAccess::$user->rights->facture->creer) {
throw new RestException(401);
}
@@ -414,7 +420,7 @@ class Invoices extends DolibarrApi
* @param array $request_data Datas
* @return int
*/
- function put($id, $request_data = NULL)
+ function put($id, $request_data = null)
{
if(! DolibarrApiAccess::$user->rights->facture->creer) {
throw new RestException(401);
@@ -485,7 +491,13 @@ class Invoices extends DolibarrApi
/**
* Add a line to a given invoice
*
- * Exemple of POST query : { "desc": "Desc", "subprice": "1.00000000", "qty": "1", "tva_tx": "20.000", "localtax1_tx": "0.000", "localtax2_tx": "0.000", "fk_product": "1", "remise_percent": "0", "date_start": "", "date_end": "", "fk_code_ventilation": 0, "info_bits": "0", "fk_remise_except": null, "product_type": "1", "rang": "-1", "special_code": "0", "fk_parent_line": null, "fk_fournprice": null, "pa_ht": "0.00000000", "label": "", "array_options": [], "situation_percent": "100", "fk_prev_id": null, "fk_unit": null }
+ * Exemple of POST query :
+ * {
+ * "desc": "Desc", "subprice": "1.00000000", "qty": "1", "tva_tx": "20.000", "localtax1_tx": "0.000", "localtax2_tx": "0.000",
+ * "fk_product": "1", "remise_percent": "0", "date_start": "", "date_end": "", "fk_code_ventilation": 0, "info_bits": "0",
+ * "fk_remise_except": null, "product_type": "1", "rang": "-1", "special_code": "0", "fk_parent_line": null, "fk_fournprice": null,
+ * "pa_ht": "0.00000000", "label": "", "array_options": [], "situation_percent": "100", "fk_prev_id": null, "fk_unit": null
+ * }
*
* @param int $id Id of invoice
* @param array $request_data InvoiceLine data
@@ -499,7 +511,7 @@ class Invoices extends DolibarrApi
* @throws 404
* @throws 400
*/
- function postLine($id, $request_data = NULL) {
+ function postLine($id, $request_data = null) {
if(! DolibarrApiAccess::$user->rights->facture->creer) {
throw new RestException(401);
}
@@ -562,6 +574,59 @@ class Invoices extends DolibarrApi
return $updateRes;
}
+ /**
+ * Adds a contact to an invoice
+ *
+ * @param int $id Order ID
+ * @param int $fk_socpeople Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link
+ * @param string $type_contact Type of contact (code). Must a code found into table llx_c_type_contact. For example: BILLING
+ * @param string $source external=Contact extern (llx_socpeople), internal=Contact intern (llx_user)
+ * @param int $notrigger Disable all triggers
+ *
+ * @url POST {id}/contacts
+ *
+ * @return array
+ *
+ * @throws 200
+ * @throws 304
+ * @throws 401
+ * @throws 404
+ * @throws 500
+ *
+ */
+ function addContact($id, $fk_socpeople, $type_contact, $source, $notrigger=0)
+ {
+ if(! DolibarrApiAccess::$user->rights->facture->creer) {
+ throw new RestException(401);
+ }
+ $result = $this->invoice->fetch($id);
+ if( ! $result ) {
+ throw new RestException(404, 'Invoice not found');
+ }
+
+ if( ! DolibarrApi::_checkAccessToResource('facture',$this->invoice->id)) {
+ throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
+ }
+
+ $result = $this->invoice->add_contact($fk_socpeople,$type_contact,$source,$notrigger);
+ if ($result < 0) {
+ throw new RestException(500, 'Error : '.$this->invoice->error);
+ }
+
+ $result = $this->invoice->fetch($id);
+ if( ! $result ) {
+ throw new RestException(404, 'Invoice not found');
+ }
+
+ if( ! DolibarrApi::_checkAccessToResource('facture',$this->invoice->id)) {
+ throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
+ }
+
+ return $this->_cleanObjectDatas($this->invoice);
+ }
+
+
+
/**
* Sets an invoice as draft
*
@@ -899,14 +964,13 @@ class Invoices extends DolibarrApi
return $result;
}
- /**
- * Add payment line to a specific invoice
- *
- * The model schema is defined by the PaymentData class.
+
+ /**
+ * Add payment line to a specific invoice with the remain to pay as amount.
*
* @param int $id Id of invoice
- * @param string $datepaye {@from body} Payment date {@type timestamp}
- * @param int $paiementid {@from body} Payment mode Id {@min 1}
+ * @param string $datepaye {@from body} Payment date {@type timestamp}
+ * @param int $paiementid {@from body} Payment mode Id {@min 1}
* @param string $closepaidinvoices {@from body} Close paid invoices {@choice yes,no}
* @param int $accountid {@from body} Account Id {@min 1}
* @param string $num_paiement {@from body} Payment number (optional)
@@ -922,63 +986,194 @@ class Invoices extends DolibarrApi
* @throws 404
*/
function addPayment($id, $datepaye, $paiementid, $closepaidinvoices, $accountid, $num_paiement='', $comment='', $chqemetteur='', $chqbank='') {
+ global $conf;
+
+ require_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php';
+
+ if(! DolibarrApiAccess::$user->rights->facture->creer) {
+ throw new RestException(403);
+ }
+ if(empty($id)) {
+ throw new RestException(400, 'Invoice ID is mandatory');
+ }
+
+ if( ! DolibarrApi::_checkAccessToResource('facture',$id)) {
+ throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
+ }
+
+ if (! empty($conf->banque->enabled)) {
+ if(empty($accountid)) {
+ throw new RestException(400, 'Account ID is mandatory');
+ }
+ }
+
+ if(empty($paiementid)) {
+ throw new RestException(400, 'Paiement ID or Paiement Code is mandatory');
+ }
+
+
+ $result = $this->invoice->fetch($id);
+ if( ! $result ) {
+ throw new RestException(404, 'Invoice not found');
+ }
+
+ // Calculate amount to pay
+ $totalpaye = $this->invoice->getSommePaiement();
+ $totalcreditnotes = $this->invoice->getSumCreditNotesUsed();
+ $totaldeposits = $this->invoice->getSumDepositsUsed();
+ $resteapayer = price2num($this->invoice->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits, 'MT');
+
+ $this->db->begin();
+
+ $amounts = array();
+ $multicurrency_amounts = array();
+
+ // Clean parameters amount if payment is for a credit note
+ if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
+ $resteapayer = price2num($resteapayer,'MT');
+ $amounts[$id] = -$resteapayer;
+ // Multicurrency
+ $newvalue = price2num($this->invoice->multicurrency_total_ttc,'MT');
+ $multicurrency_amounts[$id] = -$newvalue;
+ } else {
+ $resteapayer = price2num($resteapayer,'MT');
+ $amounts[$id] = $resteapayer;
+ // Multicurrency
+ $newvalue = price2num($this->invoice->multicurrency_total_ttc,'MT');
+ $multicurrency_amounts[$id] = $newvalue;
+ }
+
+
+ // Creation of payment line
+ $paiement = new Paiement($this->db);
+ $paiement->datepaye = $datepaye;
+ $paiement->amounts = $amounts; // Array with all payments dispatching with invoice id
+ $paiement->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
+ $paiement->paiementid = $paiementid;
+ $paiement->paiementcode = dol_getIdFromCode($this->db,$paiementid,'c_paiement','id','code',1);
+ $paiement->num_paiement = $num_paiement;
+ $paiement->note = $comment;
+
+ $paiement_id = $paiement->create(DolibarrApiAccess::$user, ($closepaidinvoices=='yes'?1:0)); // This include closing invoices
+ if ($paiement_id < 0)
+ {
+ $this->db->rollback();
+ throw new RestException(400, 'Payment error : '.$paiement->error);
+ }
+
+ if (! empty($conf->banque->enabled)) {
+ $label='(CustomerInvoicePayment)';
+
+ if($paiement->paiementcode == 'CHQ' && empty($chqemetteur)) {
+ throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paiement->paiementcode);
+ }
+ if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) $label='(CustomerInvoicePaymentBack)'; // Refund of a credit note
+ $result=$paiement->addPaymentToBank(DolibarrApiAccess::$user,'payment',$label,$accountid,$chqemetteur,$chqbank);
+ if ($result < 0)
+ {
+ $this->db->rollback();
+ throw new RestException(400, 'Add payment to bank error : '.$paiement->error);
+ }
+ }
+
+ $this->db->commit();
+
+ return $paiement_id;
+ }
+
+ /**
+ * Add a payment to pay partially or completely one or several invoices.
+ * Warning: Take care that all invoices are owned by the same customer.
+ * Example of value for parameter arrayofamounts: {"1": "99.99", "2": "10"}
+ *
+ * @param array $arrayofamounts {@from body} Array with id of invoices with amount to pay for each invoice
+ * @param string $datepaye {@from body} Payment date {@type timestamp}
+ * @param int $paiementid {@from body} Payment mode Id {@min 1}
+ * @param string $closepaidinvoices {@from body} Close paid invoices {@choice yes,no}
+ * @param int $accountid {@from body} Account Id {@min 1}
+ * @param string $num_paiement {@from body} Payment number (optional)
+ * @param string $comment {@from body} Note (optional)
+ * @param string $chqemetteur {@from body} Payment issuer (mandatory if paiementcode = 'CHQ')
+ * @param string $chqbank {@from body} Issuer bank name (optional)
+ *
+ * @url POST /paymentsdistributed
+ *
+ * @return int Payment ID
+ * @throws 400
+ * @throws 401
+ * @throws 403
+ * @throws 404
+ */
+ function addPaymentDistributed($arrayofamounts, $datepaye, $paiementid, $closepaidinvoices, $accountid, $num_paiement='', $comment='', $chqemetteur='', $chqbank='')
+ {
global $conf;
require_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php';
if(! DolibarrApiAccess::$user->rights->facture->creer) {
- throw new RestException(401);
+ throw new RestException(403);
}
- if(empty($id)) {
- throw new RestException(400, 'Invoice ID is mandatory');
- }
-
- if( ! DolibarrApi::_checkAccessToResource('facture',$id)) {
- throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
+ foreach($arrayofamounts as $id => $amount) {
+ if(empty($id)) {
+ throw new RestException(400, 'Invoice ID is mandatory. Fill the invoice id and amount into arrayofamounts parameter. For example: {"1": "99.99", "2": "10"}');
+ }
+ if( ! DolibarrApi::_checkAccessToResource('facture',$id)) {
+ throw new RestException(403, 'Access not allowed on invoice ID '.$id.' for login '.DolibarrApiAccess::$user->login);
+ }
}
if (! empty($conf->banque->enabled)) {
- if(empty($accountid)) {
- throw new RestException(400, 'Account ID is mandatory');
- }
+ if(empty($accountid)) {
+ throw new RestException(400, 'Account ID is mandatory');
+ }
}
-
if(empty($paiementid)) {
- throw new RestException(400, 'Paiement ID or Paiement Code is mandatory');
+ throw new RestException(400, 'Paiement ID or Paiement Code is mandatory');
}
-
- $result = $this->invoice->fetch($id);
- if( ! $result ) {
- throw new RestException(404, 'Invoice not found');
- }
-
- // Calculate amount to pay
- $totalpaye = $this->invoice->getSommePaiement();
- $totalcreditnotes = $this->invoice->getSumCreditNotesUsed();
- $totaldeposits = $this->invoice->getSumDepositsUsed();
- $resteapayer = price2num($this->invoice->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits, 'MT');
-
$this->db->begin();
$amounts = array();
$multicurrency_amounts = array();
- // Clean parameters amount if payment is for a credit note
- if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
- $resteapayer = price2num($resteapayer,'MT');
- $amounts[$id] = -$resteapayer;
- // Multicurrency
- $newvalue = price2num($this->invoice->multicurrency_total_ttc,'MT');
- $multicurrency_amounts[$id] = -$newvalue;
- } else {
- $resteapayer = price2num($resteapayer,'MT');
- $amounts[$id] = $resteapayer;
- // Multicurrency
- $newvalue = price2num($this->invoice->multicurrency_total_ttc,'MT');
- $multicurrency_amounts[$id] = $newvalue;
- }
+ // Loop on each invoice to pay
+ foreach($arrayofamounts as $id => $amount)
+ {
+ $result = $this->invoice->fetch($id);
+ if( ! $result ) {
+ $this->db->rollback();
+ throw new RestException(404, 'Invoice ID '.$id.' not found');
+ }
+ // Calculate amount to pay
+ $totalpaye = $this->invoice->getSommePaiement();
+ $totalcreditnotes = $this->invoice->getSumCreditNotesUsed();
+ $totaldeposits = $this->invoice->getSumDepositsUsed();
+ $resteapayer = price2num($this->invoice->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits, 'MT');
+ if ($amount != 'remain')
+ {
+ if ($amount > $resteapayer)
+ {
+ $this->db->rollback();
+ throw new RestException(400, 'Payment amount on invoice ID '.$id.' ('.$amount.') is higher than remain to pay ('.$resteapayer.')');
+ }
+ $resteapayer = $amount;
+ }
+ // Clean parameters amount if payment is for a credit note
+ if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
+ $resteapayer = price2num($resteapayer,'MT');
+ $amounts[$id] = -$resteapayer;
+ // Multicurrency
+ $newvalue = price2num($this->invoice->multicurrency_total_ttc,'MT');
+ $multicurrency_amounts[$id] = -$newvalue;
+ } else {
+ $resteapayer = price2num($resteapayer,'MT');
+ $amounts[$id] = $resteapayer;
+ // Multicurrency
+ $newvalue = price2num($this->invoice->multicurrency_total_ttc,'MT');
+ $multicurrency_amounts[$id] = $newvalue;
+ }
+ }
// Creation of payment line
$paiement = new Paiement($this->db);
@@ -989,17 +1184,14 @@ class Invoices extends DolibarrApi
$paiement->paiementcode = dol_getIdFromCode($this->db,$paiementid,'c_paiement','id','code',1);
$paiement->num_paiement = $num_paiement;
$paiement->note = $comment;
-
$paiement_id = $paiement->create(DolibarrApiAccess::$user, ($closepaidinvoices=='yes'?1:0)); // This include closing invoices
if ($paiement_id < 0)
{
$this->db->rollback();
throw new RestException(400, 'Payment error : '.$paiement->error);
}
-
if (! empty($conf->banque->enabled)) {
$label='(CustomerInvoicePayment)';
-
if($paiement->paiementcode == 'CHQ' && empty($chqemetteur)) {
throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paiement->paiementcode);
}
@@ -1011,7 +1203,9 @@ class Invoices extends DolibarrApi
throw new RestException(400, 'Add payment to bank error : '.$paiement->error);
}
}
+
$this->db->commit();
+
return $paiement_id;
}
diff --git a/htdocs/compta/facture/class/facture-rec.class.php b/htdocs/compta/facture/class/facture-rec.class.php
index 799fd25c5ae..a82f06ad851 100644
--- a/htdocs/compta/facture/class/facture-rec.class.php
+++ b/htdocs/compta/facture/class/facture-rec.class.php
@@ -68,6 +68,13 @@ class FactureRec extends CommonInvoice
var $usenewprice=0;
+ var $suspended; // status
+
+ const STATUS_NOTSUSPENDED = 0;
+ const STATUS_SUSPENDED = 1;
+
+
+
/**
* Constructor
*
@@ -95,12 +102,13 @@ class FactureRec extends CommonInvoice
// Clean parameters
$this->titre=trim($this->titre);
$this->usenewprice=empty($this->usenewprice)?0:$this->usenewprice;
+ if (empty($this->suspended)) $this->suspended=0;
// No frequency defined then no next date to execution
if (empty($this->frequency))
{
$this->frequency=0;
- $this->date_when=NULL;
+ $this->date_when=null;
}
@@ -147,6 +155,7 @@ class FactureRec extends CommonInvoice
$sql.= ", fk_multicurrency";
$sql.= ", multicurrency_code";
$sql.= ", multicurrency_tx";
+ $sql.= ", suspended";
$sql.= ") VALUES (";
$sql.= "'".$this->db->escape($this->titre)."'";
$sql.= ", ".$facsrc->socid;
@@ -167,13 +176,14 @@ class FactureRec extends CommonInvoice
$sql.= ", '".$this->db->escape($this->unit_frequency)."'";
$sql.= ", ".(!empty($this->date_when)?"'".$this->db->idate($this->date_when)."'":'NULL');
$sql.= ", ".(!empty($this->date_last_gen)?"'".$this->db->idate($this->date_last_gen)."'":'NULL');
- $sql.= ", ".$this->nb_gen_done;
- $sql.= ", ".$this->nb_gen_max;
- $sql.= ", ".$this->auto_validate;
- $sql.= ", ".$this->generate_pdf;
- $sql.= ", ".$facsrc->fk_multicurrency;
- $sql.= ", '".$facsrc->multicurrency_code."'";
- $sql.= ", ".$facsrc->multicurrency_tx;
+ $sql.= ", ".$this->db->escape($this->nb_gen_done);
+ $sql.= ", ".$this->db->escape($this->nb_gen_max);
+ $sql.= ", ".$this->db->escape($this->auto_validate);
+ $sql.= ", ".$this->db->escape($this->generate_pdf);
+ $sql.= ", ".$this->db->escape($facsrc->fk_multicurrency);
+ $sql.= ", '".$this->db->escape($facsrc->multicurrency_code)."'";
+ $sql.= ", ".$this->db->escape($facsrc->multicurrency_tx);
+ $sql.= ", ".$this->db->escape($this->suspended);
$sql.= ")";
if ($this->db->query($sql))
@@ -304,8 +314,8 @@ class FactureRec extends CommonInvoice
$sql.= ', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
//$sql.= ', el.fk_source';
$sql.= ' FROM '.MAIN_DB_PREFIX.'facture_rec as f';
- $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid AND c.entity IN ('.getEntity('c_payment_term').')';
- $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id AND p.entity IN ('.getEntity('c_paiement').')';
+ $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid';
+ $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id';
//$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON el.fk_target = f.rowid AND el.targettype = 'facture'";
$sql.= ' WHERE f.entity IN ('.getEntity('facture').')';
if ($rowid) $sql.= ' AND f.rowid='.$rowid;
@@ -381,12 +391,9 @@ class FactureRec extends CommonInvoice
if ($this->statut == self::STATUS_DRAFT) $this->brouillon = 1;
- // Retreive all extrafield for thirdparty
+ // Retreive all extrafield
// fetch optionals attributes and labels
- require_once(DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php');
- $extrafields=new ExtraFields($this->db);
- $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true);
- $this->fetch_optionals($this->id,$extralabels);
+ $this->fetch_optionals();
/*
* Lines
@@ -442,7 +449,7 @@ class FactureRec extends CommonInvoice
$sql = 'SELECT l.rowid, l.fk_product, l.product_type, l.label as custom_label, l.description, l.product_type, l.price, l.qty, l.vat_src_code, l.tva_tx, ';
$sql.= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise, l.remise_percent, l.subprice,';
- $sql.= ' l.info_bits, l.total_ht, l.total_tva, l.total_ttc,';
+ $sql.= ' l.info_bits, l.date_start_fill, l.date_end_fill, l.total_ht, l.total_tva, l.total_ttc,';
//$sql.= ' l.situation_percent, l.fk_prev_id,';
//$sql.= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise_percent, l.fk_remise_except, l.subprice,';
$sql.= ' l.rang, l.special_code,';
@@ -468,7 +475,6 @@ class FactureRec extends CommonInvoice
$line->id = $objp->rowid;
$line->rowid = $objp->rowid;
- $line->label = $objp->custom_label; // Label line
$line->desc = $objp->description; // Description line
$line->description = $objp->description; // Description line
$line->product_type = $objp->product_type; // Type of line
@@ -481,6 +487,8 @@ class FactureRec extends CommonInvoice
$line->qty = $objp->qty;
$line->subprice = $objp->subprice;
+ $line->label = $objp->custom_label; // @deprecated
+
$line->vat_src_code = $objp->vat_src_code;
$line->tva_tx = $objp->tva_tx;
$line->localtax1_tx = $objp->localtax1_tx;
@@ -490,6 +498,8 @@ class FactureRec extends CommonInvoice
$line->remise_percent = $objp->remise_percent;
$line->fk_remise_except = $objp->fk_remise_except;
$line->fk_product = $objp->fk_product;
+ $line->date_start_fill = $objp->date_start_fill;
+ $line->date_end_fill = $objp->date_end_fill;
$line->info_bits = $objp->info_bits;
$line->total_ht = $objp->total_ht;
$line->total_tva = $objp->total_tva;
@@ -504,7 +514,7 @@ class FactureRec extends CommonInvoice
$line->price = $objp->price;
$line->remise = $objp->remise;
- $extralabelsline = $line->fetch_optionals($line->id,$extrafieldsline);
+ $extralabelsline = $line->fetch_optionals($line->id);
// Multicurrency
$line->fk_multicurrency = $objp->fk_multicurrency;
@@ -605,15 +615,17 @@ class FactureRec extends CommonInvoice
* @param string $label Label of the line
* @param string $fk_unit Unit
* @param double $pu_ht_devise Unit price in currency
+ * @param int $date_start_fill 1=Flag to fill start date when generating invoice
+ * @param int $date_end_fill 1=Flag to fill end date when generating invoice
* @return int <0 if KO, Id of line if OK
*/
- function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $price_base_type='HT', $info_bits=0, $fk_remise_except='', $pu_ttc=0, $type=0, $rang=-1, $special_code=0, $label='', $fk_unit=null, $pu_ht_devise=0)
+ function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $price_base_type='HT', $info_bits=0, $fk_remise_except='', $pu_ttc=0, $type=0, $rang=-1, $special_code=0, $label='', $fk_unit=null, $pu_ht_devise=0, $date_start_fill=0, $date_end_fill=0)
{
global $mysoc;
$facid=$this->id;
- dol_syslog(get_class($this)."::addline facid=$facid,desc=$desc,pu_ht=$pu_ht,qty=$qty,txtva=$txtva,txlocaltax1=$txlocaltax1,txlocaltax2=$txlocaltax2,fk_product=$fk_product,remise_percent=$remise_percent,info_bits=$info_bits,fk_remise_except=$fk_remise_except,price_base_type=$price_base_type,pu_ttc=$pu_ttc,type=$type,fk_unit=$fk_unit,pu_ht_devise=$pu_ht_devise", LOG_DEBUG);
+ dol_syslog(get_class($this)."::addline facid=$facid,desc=$desc,pu_ht=$pu_ht,qty=$qty,txtva=$txtva,txlocaltax1=$txlocaltax1,txlocaltax2=$txlocaltax2,fk_product=$fk_product,remise_percent=$remise_percent,info_bits=$info_bits,fk_remise_except=$fk_remise_except,price_base_type=$price_base_type,pu_ttc=$pu_ttc,type=$type,fk_unit=$fk_unit,pu_ht_devise=$pu_ht_devise,date_start_fill=$date_start_fill,date_end_fill=$date_end_fill", LOG_DEBUG);
include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
// Check parameters
@@ -703,6 +715,8 @@ class FactureRec extends CommonInvoice
$sql.= ", total_localtax1";
$sql.= ", total_localtax2";
$sql.= ", total_ttc";
+ $sql.= ", date_start_fill";
+ $sql.= ", date_end_fill";
$sql.= ", info_bits";
$sql.= ", rang";
$sql.= ", special_code";
@@ -730,6 +744,8 @@ class FactureRec extends CommonInvoice
$sql.= ", ".price2num($total_localtax1);
$sql.= ", ".price2num($total_localtax2);
$sql.= ", ".price2num($total_ttc);
+ $sql.= ", ".(int) $date_start_fill;
+ $sql.= ", ".(int) $date_end_fill;
$sql.= ", ".$info_bits;
$sql.= ", ".$rang;
$sql.= ", ".$special_code;
@@ -781,9 +797,11 @@ class FactureRec extends CommonInvoice
* @param string $fk_unit Unit
* @param double $pu_ht_devise Unit price in currency
* @param int $notrigger disable line update trigger
+ * @param int $date_start_fill 1=Flag to fill start date when generating invoice
+ * @param int $date_end_fill 1=Flag to fill end date when generating invoice
* @return int <0 if KO, Id of line if OK
*/
- function updateline($rowid, $desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $price_base_type='HT', $info_bits=0, $fk_remise_except='', $pu_ttc=0, $type=0, $rang=-1, $special_code=0, $label='', $fk_unit=null, $pu_ht_devise = 0, $notrigger=0)
+ function updateline($rowid, $desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $price_base_type='HT', $info_bits=0, $fk_remise_except='', $pu_ttc=0, $type=0, $rang=-1, $special_code=0, $label='', $fk_unit=null, $pu_ht_devise = 0, $notrigger=0, $date_start_fill=0, $date_end_fill=0)
{
global $mysoc;
@@ -886,6 +904,8 @@ class FactureRec extends CommonInvoice
$sql.= ", total_localtax1='".price2num($total_localtax1)."'";
$sql.= ", total_localtax2='".price2num($total_localtax2)."'";
$sql.= ", total_ttc='".price2num($total_ttc)."'";
+ $sql.= ", date_start_fill=".((int) $date_start_fill);
+ $sql.= ", date_end_fill=".((int) $date_end_fill);
$sql.= ", info_bits=".$info_bits;
$sql.= ", rang=".$rang;
$sql.= ", special_code=".$special_code;
@@ -951,15 +971,20 @@ class FactureRec extends CommonInvoice
* Create all recurrents invoices (for all entities if multicompany is used).
* A result may also be provided into this->output.
*
- * WARNING: This method change context $conf->entity to be in correct context for each recurring invoice found.
+ * WARNING: This method change temporarly context $conf->entity to be in correct context for each recurring invoice found.
*
- * @return int 0 if OK, < 0 if KO (this function is used also by cron so only 0 is OK)
+ * @param int $restictoninvoiceid 0=All qualified template invoices found. > 0 = restrict action on invoice ID
+ * @param int $forcevalidation 1=Force validation of invoice whatever is template auto_validate flag.
+ * @return int 0 if OK, < 0 if KO (this function is used also by cron so only 0 is OK)
*/
- function createRecurringInvoices()
+ function createRecurringInvoices($restictoninvoiceid=0, $forcevalidation=0)
{
global $conf, $langs, $db, $user;
+ $error=0;
+
$langs->load("bills");
+ $langs->load('main');
$nb_create=0;
@@ -967,13 +992,15 @@ class FactureRec extends CommonInvoice
$tmparray=dol_getdate($now);
$today = dol_mktime(23,59,59,$tmparray['mon'],$tmparray['mday'],$tmparray['year']); // Today is last second of current day
- dol_syslog("createRecurringInvoices");
+ dol_syslog("createRecurringInvoices restictoninvoiceid=".$restictoninvoiceid." forcevalidation=".$forcevalidation);
+
$sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'facture_rec';
$sql.= ' WHERE frequency > 0'; // A recurring invoice is an invoice with a frequency
$sql.= " AND (date_when IS NULL OR date_when <= '".$db->idate($today)."')";
$sql.= ' AND (nb_gen_done < nb_gen_max OR nb_gen_max = 0)';
$sql.= ' AND suspended = 0';
$sql.= ' AND entity = '.$conf->entity; // MUST STAY = $conf->entity here
+ if ($restictoninvoiceid > 0) $sql.=' AND rowid = '.$restictoninvoiceid;
$sql.= $db->order('entity', 'ASC');
//print $sql;exit;
@@ -990,11 +1017,13 @@ class FactureRec extends CommonInvoice
while ($i < $num) // Loop on each template invoice. If $num = 0, test is false at first pass.
{
- $line = $db->fetch_object($resql);
+ $line = $db->fetch_object($resql);
$db->begin();
- $facturerec = new FactureRec($db);
+ $invoiceidgenerated = 0;
+
+ $facturerec = new FactureRec($db);
$facturerec->fetch($line->rowid);
if ($facturerec->id > 0)
@@ -1004,8 +1033,6 @@ class FactureRec extends CommonInvoice
dol_syslog("createRecurringInvoices Process invoice template id=".$facturerec->id.", ref=".$facturerec->ref.", entity=".$facturerec->entity);
- $error=0;
-
$facture = new Facture($db);
$facture->fac_rec = $facturerec->id; // We will create $facture from this recurring invoice
$facture->fk_fac_rec_source = $facturerec->id; // We will create $facture from this recurring invoice
@@ -1022,7 +1049,7 @@ class FactureRec extends CommonInvoice
$this->error = $facture->error;
$error++;
}
- if (! $error && $facturerec->auto_validate)
+ if (! $error && ($facturerec->auto_validate || $forcevalidation))
{
$result = $facture->validate($user);
if ($result <= 0)
@@ -1034,6 +1061,8 @@ class FactureRec extends CommonInvoice
}
if (! $error && $facturerec->generate_pdf)
{
+ // We refresh the object in order to have all necessary data (like date_lim_reglement)
+ $facture->fetch($facture->id);
$result = $facture->generateDocument($facturerec->modelpdf, $langs);
if ($result <= 0)
{
@@ -1092,7 +1121,21 @@ class FactureRec extends CommonInvoice
global $langs;
$result='';
- $label=$langs->trans("ShowInvoice").': '.$this->ref;
+
+ $label = '' . $langs->trans("ShowInvoice") . ' ';
+ if (! empty($this->ref))
+ $label .= ''.$langs->trans('Ref') . ': ' . $this->ref;
+ if (! empty($this->date_last_gen))
+ $label .= ''.$langs->trans('DateLastGeneration') . ': ' . dol_print_date($this->date_last_gen, 'dayhour');
+ if ($this->frequency > 0)
+ {
+ if (! empty($this->date_when))
+ {
+ $label .= ''.$langs->trans('NextDateToExecution') . ': ';
+ $label .= (empty($this->suspended)?'':''). dol_print_date($this->date_when, 'day').(empty($this->suspended)?'':' '); // No hour for this property
+ if (! empty($this->suspended)) $label .= ' ('.$langs->trans("Disabled").')';
+ }
+ }
$url = DOL_URL_ROOT.'/compta/facture/fiche-rec.php?facid='.$this->id;
@@ -1151,49 +1194,69 @@ class FactureRec extends CommonInvoice
$prefix='';
if ($recur)
{
- if ($status == 1) return $langs->trans('Disabled'); // credit note
+ if ($status == self::STATUS_SUSPENDED) return $langs->trans('Disabled');
else return $langs->trans('Active');
}
- else return $langs->trans("Draft");
+ else
+ {
+ if ($status == self::STATUS_SUSPENDED) return $langs->trans('Disabled');
+ else return $langs->trans("Draft");
+ }
}
if ($mode == 1)
{
$prefix='Short';
if ($recur)
{
- if ($status == 1) return $langs->trans('Disabled');
+ if ($status == self::STATUS_SUSPENDED) return $langs->trans('Disabled');
else return $langs->trans('Active');
}
- else return $langs->trans("Draft");
+ else
+ {
+ if ($status == self::STATUS_SUSPENDED) return $langs->trans('Disabled');
+ else return $langs->trans("Draft");
+ }
}
if ($mode == 2)
{
if ($recur)
{
- if ($status == 1) return img_picto($langs->trans('Disabled'),'statut6').' '.$langs->trans('Disabled');
+ if ($status == self::STATUS_SUSPENDED) return img_picto($langs->trans('Disabled'),'statut6').' '.$langs->trans('Disabled');
else return img_picto($langs->trans('Active'),'statut4').' '.$langs->trans('Active');
}
- else return img_picto($langs->trans('Draft'),'statut0').' '.$langs->trans('Draft');
+ else
+ {
+ if ($status == self::STATUS_SUSPENDED) return img_picto($langs->trans('Disabled'),'statut6').' '.$langs->trans('Disabled');
+ else return img_picto($langs->trans('Draft'),'statut0').' '.$langs->trans('Draft');
+ }
}
if ($mode == 3)
{
if ($recur)
{
$prefix='Short';
- if ($status == 1) return img_picto($langs->trans('Disabled'),'statut6');
+ if ($status == self::STATUS_SUSPENDED) return img_picto($langs->trans('Disabled'),'statut6');
else return img_picto($langs->trans('Active'),'statut4');
}
- else return img_picto($langs->trans('Draft'),'statut0');
+ else
+ {
+ if ($status == self::STATUS_SUSPENDED) return img_picto($langs->trans('Disabled'),'statut6');
+ else return img_picto($langs->trans('Draft'),'statut0');
+ }
}
if ($mode == 4)
{
$prefix='';
if ($recur)
{
- if ($status == 1) return img_picto($langs->trans('Disabled'),'statut6').' '.$langs->trans('Disabled');
+ if ($status == self::STATUS_SUSPENDED) return img_picto($langs->trans('Disabled'),'statut6').' '.$langs->trans('Disabled');
else return img_picto($langs->trans('Active'),'statut4').' '.$langs->trans('Active');
}
- else return img_picto($langs->trans('Draft'),'statut0').' '.$langs->trans('Draft');
+ else
+ {
+ if ($status == self::STATUS_SUSPENDED) return img_picto($langs->trans('Disabled'),'statut6').' '.$langs->trans('Disabled');
+ else return img_picto($langs->trans('Draft'),'statut0').' '.$langs->trans('Draft');
+ }
}
if ($mode == 5 || $mode == 6)
{
@@ -1201,10 +1264,14 @@ class FactureRec extends CommonInvoice
if ($mode == 5) $prefix='Short';
if ($recur)
{
- if ($status == 1) return ''.$langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut6');
+ if ($status == self::STATUS_SUSPENDED) return ''.$langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut6');
else return ''.$langs->trans('Active').' '.img_picto($langs->trans('Active'),'statut4');
}
- else return $langs->trans('Draft').' '.img_picto($langs->trans('Active'),'statut0');
+ else
+ {
+ if ($status == self::STATUS_SUSPENDED) return ''.$langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut6');
+ else return $langs->trans('Draft').' '.img_picto($langs->trans('Active'),'statut0');
+ }
}
}
@@ -1471,7 +1538,7 @@ class FactureRec extends CommonInvoice
}
/**
- * Update the auto validate invoice
+ * Update the auto validate flag of invoice
*
* @param int $validate 0 to create in draft, 1 to create and validate invoice
* @return int <0 if KO, >0 if OK
@@ -1575,6 +1642,10 @@ class FactureLigneRec extends CommonInvoiceLine
public $element='facturedetrec';
public $table_element='facturedet_rec';
+ var $date_start_fill;
+ var $date_end_fill;
+
+
/**
* Delete line in database
*
@@ -1629,7 +1700,7 @@ class FactureLigneRec extends CommonInvoiceLine
{
$sql = 'SELECT l.rowid, l.fk_facture ,l.fk_product, l.product_type, l.label as custom_label, l.description, l.product_type, l.price, l.qty, l.vat_src_code, l.tva_tx,';
$sql.= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise, l.remise_percent, l.subprice,';
- $sql.= ' l.info_bits, l.total_ht, l.total_tva, l.total_ttc,';
+ $sql.= ' l.date_start_fill, l.date_end_fill, l.info_bits, l.total_ht, l.total_tva, l.total_ttc,';
$sql.= ' l.rang, l.special_code,';
$sql.= ' l.fk_unit, l.fk_contract_line,';
$sql.= ' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc';
@@ -1669,6 +1740,8 @@ class FactureLigneRec extends CommonInvoiceLine
$this->remise_percent = $objp->remise_percent;
$this->fk_remise_except = $objp->fk_remise_except;
$this->fk_product = $objp->fk_product;
+ $this->date_start_fill = $objp->date_start_fill;
+ $this->date_end_fill = $objp->date_end_fill;
$this->info_bits = $objp->info_bits;
$this->total_ht = $objp->total_ht;
$this->total_tva = $objp->total_tva;
@@ -1694,22 +1767,17 @@ class FactureLigneRec extends CommonInvoiceLine
/**
* Update a line to invoice_rec.
*
+ * @param User $user User
+ * @param int $notrigger No trigger
* @return int <0 if KO, Id of line if OK
*/
- function update()
+ function update(User $user, $notrigger=0)
{
- global $user;
+ global $conf;
include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
- if ($fk_product)
- {
- $product=new Product($this->db);
- $result=$product->fetch($fk_product);
- $product_type=$product->type;
- }
-
- $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet_rec SET ";
+ $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet_rec SET";
$sql.= " fk_facture = ".$this->fk_facture;
$sql.= ", label=".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null");
$sql.= ", description='".$this->db->escape($this->desc)."'";
@@ -1725,16 +1793,21 @@ class FactureLigneRec extends CommonInvoiceLine
$sql.= ", product_type=".$this->product_type;
$sql.= ", remise_percent='".price2num($this->remise_percent)."'";
$sql.= ", subprice='".price2num($this->subprice)."'";
- $sql.= ", total_ht='".price2num($this->total_ht)."'";
- $sql.= ", total_tva='".price2num($this->total_tva)."'";
- $sql.= ", total_localtax1='".price2num($this->total_localtax1)."'";
- $sql.= ", total_localtax2='".price2num($this->total_localtax2)."'";
- $sql.= ", total_ttc='".price2num($this->total_ttc)."'";
+ $sql.= ", info_bits='".price2num($this->info_bits)."'";
+ $sql.= ", date_start_fill=".(int) $this->date_start_fill;
+ $sql.= ", date_end_fill=".(int) $this->date_end_fill;
+ if (empty($this->skip_update_total))
+ {
+ $sql.= ", total_ht=".price2num($this->total_ht);
+ $sql.= ", total_tva=".price2num($this->total_tva);
+ $sql.= ", total_localtax1=".price2num($this->total_localtax1);
+ $sql.= ", total_localtax2=".price2num($this->total_localtax2);
+ $sql.= ", total_ttc=".price2num($this->total_ttc);
+ }
$sql.= ", rang=".$this->rang;
$sql.= ", special_code=".$this->special_code;
$sql.= ", fk_unit=".($this->fk_unit ?"'".$this->db->escape($this->fk_unit )."'":"null");
$sql.= ", fk_contract_line=".($this->fk_contract_line?$this->fk_contract_line:"null");
-
$sql.= " WHERE rowid = ".$this->id;
dol_syslog(get_class($this)."::updateline", LOG_DEBUG);
@@ -1750,10 +1823,10 @@ class FactureLigneRec extends CommonInvoiceLine
}
}
- if (! $notrigger)
+ if (! $error && ! $notrigger)
{
// Call trigger
- $result=$this->call_trigger('LINEBILL_REC_UPDATE',$user);
+ $result=$this->call_trigger('LINEBILL_REC_UPDATE', $user);
if ($result < 0)
{
$this->db->rollback();
@@ -1766,7 +1839,7 @@ class FactureLigneRec extends CommonInvoiceLine
}
else
{
- $this->error=$this->db->error();
+ $this->error=$this->db->lasterror();
$this->db->rollback();
return -2;
}
diff --git a/htdocs/compta/facture/class/facture.class.php b/htdocs/compta/facture/class/facture.class.php
index bc7a14c0c45..2329b1caeb0 100644
--- a/htdocs/compta/facture/class/facture.class.php
+++ b/htdocs/compta/facture/class/facture.class.php
@@ -13,8 +13,9 @@
* Copyright (C) 2012 Cédric Salvador
* Copyright (C) 2012-2014 Raphaël Doursenaud
* Copyright (C) 2013 Cedric Gross
- * Copyright (C) 2013 Florian Henry
- * Copyright (C) 2016 Ferran Marcet
+ * Copyright (C) 2013 Florian Henry
+ * Copyright (C) 2016 Ferran Marcet
+ * Copyright (C) 2018 Alexandre Spangaro
* Copyright (C) 2018 Nicolas ZABOURI
*
* This program is free software; you can redistribute it and/or modify
@@ -44,6 +45,9 @@ require_once DOL_DOCUMENT_ROOT.'/societe/class/client.class.php';
require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php';
require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
+if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php';
+if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php';
+
/**
* Class to manage invoices
*/
@@ -141,7 +145,7 @@ class Facture extends CommonInvoice
public $situation_counter;
/**
- * @var bool Final situation flag
+ * @var int Final situation flag
*/
public $situation_final;
@@ -240,7 +244,7 @@ class Facture extends CommonInvoice
* @param int $forceduedate 1=Do not recalculate due date from payment condition but force it with value
* @return int <0 if KO, >0 if OK
*/
- function create($user,$notrigger=0,$forceduedate=0)
+ function create(User $user, $notrigger=0, $forceduedate=0)
{
global $langs,$conf,$mysoc,$hookmanager;
$error=0;
@@ -266,13 +270,13 @@ class Facture extends CommonInvoice
$this->multicurrency_tx = 1;
}
- dol_syslog(get_class($this)."::create user=".$user->id);
+ dol_syslog(get_class($this)."::create user=".$user->id." date=".$this->date);
// Check parameters
- if (empty($this->date) || empty($user->id))
+ if (empty($this->date))
{
- $this->error="ErrorBadParameter";
- dol_syslog(get_class($this)."::create Try to create an invoice with an empty parameter (user, date, ...)", LOG_ERR);
+ $this->error="Try to create an invoice with an empty parameter (date)";
+ dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
return -3;
}
$soc = new Societe($this->db);
@@ -288,6 +292,10 @@ class Facture extends CommonInvoice
$this->db->begin();
+ $originaldatewhen=null;
+ $nextdatewhen=null;
+ $previousdaynextdatewhen=null;
+
// Create invoice from a template invoice
if ($this->fac_rec > 0)
{
@@ -298,19 +306,22 @@ class Facture extends CommonInvoice
$result=$_facrec->fetch($this->fac_rec);
$result=$_facrec->fetchObjectLinked(); // This load $_facrec->linkedObjectsIds
+ // Define some dates
$originaldatewhen = $_facrec->date_when;
+ $nextdatewhen=dol_time_plus_duree($originaldatewhen, $_facrec->frequency, $_facrec->unit_frequency);
+ $previousdaynextdatewhen=dol_time_plus_duree($nextdatewhen, -1, 'd');
$this->socid = $_facrec->socid; // Invoice created on same thirdparty than template
$this->entity = $_facrec->entity; // Invoice created in same entity than template
// Fields coming from GUI (priority on template). TODO Value of template should be used as default value on GUI so we can use here always value from GUI
- $this->fk_project = GETPOST('projectid','int') > 0 ? GETPOST('projectid','int') : $_facrec->fk_project;
+ $this->fk_project = GETPOST('projectid','int') > 0 ? ((int) GETPOST('projectid','int')) : $_facrec->fk_project;
$this->note_public = GETPOST('note_public','none') ? GETPOST('note_public','none') : $_facrec->note_public;
$this->note_private = GETPOST('note_private','none') ? GETPOST('note_private','none') : $_facrec->note_private;
- $this->modelpdf = GETPOST('model') ? GETPOST('model') : $_facrec->modelpdf;
- $this->cond_reglement_id = GETPOST('cond_reglement_id') > 0 ? GETPOST('cond_reglement_id') : $_facrec->cond_reglement_id;
- $this->mode_reglement_id = GETPOST('mode_reglement_id') > 0 ? GETPOST('mode_reglement_id') : $_facrec->mode_reglement_id;
- $this->fk_account = GETPOST('fk_account') > 0 ? GETPOST('fk_account') : $_facrec->fk_account;
+ $this->modelpdf = GETPOST('model','alpha') ? GETPOST('model','apha') : $_facrec->modelpdf;
+ $this->cond_reglement_id = GETPOST('cond_reglement_id','int') > 0 ? ((int) GETPOST('cond_reglement_id','int')) : $_facrec->cond_reglement_id;
+ $this->mode_reglement_id = GETPOST('mode_reglement_id','int') > 0 ? ((int) GETPOST('mode_reglement_id','int')) : $_facrec->mode_reglement_id;
+ $this->fk_account = GETPOST('fk_account') > 0 ? ((int) GETPOST('fk_account')) : $_facrec->fk_account;
// Set here to have this defined for substitution into notes, should be recalculated after adding lines to get same result
$this->total_ht = $_facrec->total_ht;
@@ -375,7 +386,8 @@ class Facture extends CommonInvoice
$substitutionarray['__INVOICE_NEXT_YEAR__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'y'), '%Y');
// Only for tempalte invoice
$substitutionarray['__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = dol_print_date($originaldatewhen, 'dayhour');
- $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = dol_print_date(dol_time_plus_duree($originaldatewhen, $_facrec->frequency, $_facrec->unit_frequency), 'dayhour');
+ $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = dol_print_date($nextdatewhen, 'dayhour');
+ $substitutionarray['__INVOICE_PREVIOUS_DATE_NEXT_INVOICE_AFTER_GEN__'] = dol_print_date($previousdaynextdatewhen, 'dayhour');
//var_dump($substitutionarray);exit;
@@ -495,6 +507,7 @@ class Facture extends CommonInvoice
}
}
+ // Propagate contacts
if (! $error && $this->id && ! empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && ! empty($this->origin) && ! empty($this->origin_id)) // Get contact from origin object
{
$originforcontact = $this->origin;
@@ -532,11 +545,10 @@ class Facture extends CommonInvoice
else dol_print_error($resqlcontact);
}
-
/*
- * Insert lines of invoices into database
+ * Insert lines of invoices, if not from template invoice, into database
*/
- if (count($this->lines) && is_object($this->lines[0])) // If this->lines is array of InvoiceLines (preferred mode)
+ if (! $error && empty($this->fac_rec) && count($this->lines) && is_object($this->lines[0])) // If this->lines is array of InvoiceLines (preferred mode)
{
$fk_parent_line = 0;
@@ -546,9 +558,18 @@ class Facture extends CommonInvoice
$newinvoiceline=$this->lines[$i];
$newinvoiceline->fk_facture=$this->id;
- // TODO This seems not used. Here we put origin 'facture' but after, we put an id of object !
- $newinvoiceline->origin = $this->element;
- $newinvoiceline->origin_id = $this->lines[$i]->id;
+ $newinvoiceline->origin = $this->lines[$i]->element;
+ $newinvoiceline->origin_id = $this->lines[$i]->id;
+
+ // Auto set date of service ?
+ if ($this->lines[$i]->date_start_fill == 1 && $originaldatewhen) // $originaldatewhen is defined when generating from recurring invoice only
+ {
+ $newinvoiceline->date_start = $originaldatewhen;
+ }
+ if ($this->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) // $previousdaynextdatewhen is defined when generating from recurring invoice only
+ {
+ $newinvoiceline->date_end = $previousdaynextdatewhen;
+ }
if ($result >= 0)
{
@@ -582,7 +603,7 @@ class Facture extends CommonInvoice
}
}
}
- else // If this->lines is an array of invoice line arrays
+ elseif (! $error && empty($this->fac_rec)) // If this->lines is an array of invoice line arrays
{
$fk_parent_line = 0;
@@ -593,7 +614,7 @@ class Facture extends CommonInvoice
$line = $this->lines[$i];
// Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
- //if (! is_object($line)) $line=json_decode(json_encode($line), FALSE); // convert recursively array into object.
+ //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
if (! is_object($line)) $line = (object) $line;
if ($result >= 0)
@@ -690,7 +711,9 @@ class Facture extends CommonInvoice
$localtax2_tx,
$_facrec->lines[$i]->fk_product,
$_facrec->lines[$i]->remise_percent,
- '','',0,
+ ($_facrec->lines[$i]->date_start_fill == 1 && $originaldatewhen)?$originaldatewhen:'',
+ ($_facrec->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen)?$previousdaynextdatewhen:'',
+ 0,
$tva_npr,
'',
'HT',
@@ -728,35 +751,20 @@ class Facture extends CommonInvoice
{
$action='create';
- // Actions on extra fields (by external module or standard code)
- // TODO le hook fait double emploi avec le trigger !!
- /*
- $hookmanager->initHooks(array('invoicedao'));
- $parameters=array('invoiceid'=>$this->id);
- $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
- if (empty($reshook))
- {
- if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
- {*/
+ // Actions on extra fields
if (! $error)
{
$result=$this->insertExtraFields();
if ($result < 0) $error++;
}
- /*}
- }
- else if ($reshook < 0) $error++;*/
- if (! $error)
- {
- if (! $notrigger)
- {
- // Call trigger
- $result=$this->call_trigger('BILL_CREATE',$user);
- if ($result < 0) $error++;
- // End call triggers
- }
- }
+ if (! $error && ! $notrigger)
+ {
+ // Call trigger
+ $result=$this->call_trigger('BILL_CREATE',$user);
+ if ($result < 0) $error++;
+ // End call triggers
+ }
if (! $error)
{
@@ -806,14 +814,17 @@ class Facture extends CommonInvoice
// Charge facture source
$facture=new Facture($this->db);
- $this->fetch_optionals();
- if(!empty($this->array_options)){
- $facture->array_options = $this->array_options;
- }
+ // Retreive all extrafield
+ // fetch optionals attributes and labels
+ $this->fetch_optionals();
- foreach($this->lines as &$line){
+ if(!empty($this->array_options)){
+ $facture->array_options = $this->array_options;
+ }
+
+ foreach($this->lines as &$line){
$line->fetch_optionals();//fetch extrafields
- }
+ }
$facture->fk_facture_source = $this->fk_facture_source;
$facture->type = $this->type;
@@ -864,7 +875,7 @@ class Facture extends CommonInvoice
}
elseif ($this->type == self::TYPE_SITUATION && !empty($conf->global->INVOICE_USE_SITUATION))
{
- $this->fetchObjectLinked('', '', $object->id, 'facture');
+ $this->fetchObjectLinked('', '', $facture->id, 'facture');
foreach ($this->linkedObjectsIds as $typeObject => $Tfk_object)
{
@@ -974,11 +985,6 @@ class Facture extends CommonInvoice
$reshook=$hookmanager->executeHooks('createFrom',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) $error++;
}
-
- // Call trigger
- $result=$this->call_trigger('BILL_CLONE',$user);
- if ($result < 0) $error++;
- // End call triggers
}
unset($this->context['createfromclone']);
@@ -1049,7 +1055,7 @@ class Facture extends CommonInvoice
$line->pa_ht = $marginInfos[0];
// get extrafields from original line
- $object->lines[$i]->fetch_optionals($object->lines[$i]->rowid);
+ $object->lines[$i]->fetch_optionals();
foreach($object->lines[$i]->array_options as $options_key => $value)
$line->array_options[$options_key] = $value;
@@ -1146,7 +1152,7 @@ class Facture extends CommonInvoice
{
global $langs, $conf, $user, $form;
- if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips
+ if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips
$result='';
@@ -1265,11 +1271,13 @@ class Facture extends CommonInvoice
$sql.= ', f.fk_incoterms, f.location_incoterms';
$sql.= ", i.libelle as libelle_incoterms";
$sql.= ' FROM '.MAIN_DB_PREFIX.'facture as f';
- $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid AND c.entity IN (' . getEntity('c_payment_term').')';
- $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id AND p.entity IN ('.getEntity('c_paiement').')';
+ $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid';
+ $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id';
$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON f.fk_incoterms = i.rowid';
- $sql.= ' WHERE f.entity IN ('.getEntity('facture').')';
- if ($rowid) $sql.= " AND f.rowid=".$rowid;
+
+ if ($rowid) $sql.= " WHERE f.rowid=".$rowid;
+ else $sql.= ' WHERE f.entity IN ('.getEntity('facture').')'; // Dont't use entity if you use rowid
+
if ($ref) $sql.= " AND f.facnumber='".$this->db->escape($ref)."'";
if ($ref_ext) $sql.= " AND f.ref_ext='".$this->db->escape($ref_ext)."'";
if ($ref_int) $sql.= " AND f.ref_int='".$this->db->escape($ref_int)."'";
@@ -1344,23 +1352,20 @@ class Facture extends CommonInvoice
$this->multicurrency_total_tva = $obj->multicurrency_total_tva;
$this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
- if ($this->type == self::TYPE_SITUATION && $fetch_situation)
+ if (($this->type == self::TYPE_SITUATION || ($this->type == self::TYPE_CREDIT_NOTE && $this->situation_cycle_ref > 0)) && $fetch_situation)
{
$this->fetchPreviousNextSituationInvoice();
}
if ($this->statut == self::STATUS_DRAFT) $this->brouillon = 1;
- // Retrieve all extrafield for invoice
+ // Retreive all extrafield
// fetch optionals attributes and labels
- require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
- $extrafields=new ExtraFields($this->db);
- $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true);
- $this->fetch_optionals($this->id,$extralabels);
+ $this->fetch_optionals();
/*
* Lines
- */
+ */
$this->lines = array();
@@ -1469,6 +1474,9 @@ class Facture extends CommonInvoice
$line->fk_prev_id = $objp->fk_prev_id;
$line->fk_unit = $objp->fk_unit;
+ // Accountancy
+ $line->fk_accounting_account = $objp->fk_code_ventilation;
+
// Multicurrency
$line->fk_multicurrency = $objp->fk_multicurrency;
$line->multicurrency_code = $objp->multicurrency_code;
@@ -1516,8 +1524,16 @@ class Facture extends CommonInvoice
$invoice = new Facture($this->db);
if ($invoice->fetch($objp->rowid) > 0)
{
- if ($objp->situation_counter < $this->situation_counter) $this->tab_previous_situation_invoice[] = $invoice;
- else $this->tab_next_situation_invoice[] = $invoice;
+ if ($objp->situation_counter < $this->situation_counter
+ || ($objp->situation_counter == $this->situation_counter && $objp->rowid < $this->id) // This case appear when there are credit notes
+ )
+ {
+ $this->tab_previous_situation_invoice[] = $invoice;
+ }
+ else
+ {
+ $this->tab_next_situation_invoice[] = $invoice;
+ }
}
}
}
@@ -1531,8 +1547,10 @@ class Facture extends CommonInvoice
* @param int $notrigger 0=launch triggers after, 1=disable triggers
* @return int <0 if KO, >0 if OK
*/
- function update($user=null, $notrigger=0)
+ function update(User $user, $notrigger=0)
{
+ global $conf;
+
$error=0;
// Clean parameters
@@ -1547,36 +1565,24 @@ class Facture extends CommonInvoice
if (isset($this->note_public)) $this->note_public=trim($this->note_public);
if (isset($this->modelpdf)) $this->modelpdf=trim($this->modelpdf);
if (isset($this->import_key)) $this->import_key=trim($this->import_key);
- if (empty($this->situation_cycle_ref)) {
- $this->situation_cycle_ref = 'null';
- }
-
- if (empty($this->situation_counter)) {
- $this->situation_counter = 'null';
- }
-
- if (empty($this->situation_final)) {
- $this->situation_final = '0';
- }
// Check parameters
// Put here code to add control on parameters values
// Update request
$sql = "UPDATE ".MAIN_DB_PREFIX."facture SET";
-
$sql.= " facnumber=".(isset($this->ref)?"'".$this->db->escape($this->ref)."'":"null").",";
- $sql.= " type=".(isset($this->type)?$this->type:"null").",";
+ $sql.= " type=".(isset($this->type)?$this->db->escape($this->type):"null").",";
$sql.= " ref_client=".(isset($this->ref_client)?"'".$this->db->escape($this->ref_client)."'":"null").",";
$sql.= " increment=".(isset($this->increment)?"'".$this->db->escape($this->increment)."'":"null").",";
- $sql.= " fk_soc=".(isset($this->socid)?$this->socid:"null").",";
+ $sql.= " fk_soc=".(isset($this->socid)?$this->db->escape($this->socid):"null").",";
$sql.= " datec=".(strval($this->date_creation)!='' ? "'".$this->db->idate($this->date_creation)."'" : 'null').",";
$sql.= " datef=".(strval($this->date)!='' ? "'".$this->db->idate($this->date)."'" : 'null').",";
$sql.= " date_pointoftax=".(strval($this->date_pointoftax)!='' ? "'".$this->db->idate($this->date_pointoftax)."'" : 'null').",";
$sql.= " date_valid=".(strval($this->date_validation)!='' ? "'".$this->db->idate($this->date_validation)."'" : 'null').",";
- $sql.= " paye=".(isset($this->paye)?$this->paye:"null").",";
- $sql.= " remise_percent=".(isset($this->remise_percent)?$this->remise_percent:"null").",";
- $sql.= " remise_absolue=".(isset($this->remise_absolue)?$this->remise_absolue:"null").",";
+ $sql.= " paye=".(isset($this->paye)?$this->db->escape($this->paye):"null").",";
+ $sql.= " remise_percent=".(isset($this->remise_percent)?$this->db->escape($this->remise_percent):"null").",";
+ $sql.= " remise_absolue=".(isset($this->remise_absolue)?$this->db->escape($this->remise_absolue):"null").",";
$sql.= " close_code=".(isset($this->close_code)?"'".$this->db->escape($this->close_code)."'":"null").",";
$sql.= " close_note=".(isset($this->close_note)?"'".$this->db->escape($this->close_note)."'":"null").",";
$sql.= " tva=".(isset($this->total_tva)?$this->total_tva:"null").",";
@@ -1584,23 +1590,22 @@ class Facture extends CommonInvoice
$sql.= " localtax2=".(isset($this->total_localtax2)?$this->total_localtax2:"null").",";
$sql.= " total=".(isset($this->total_ht)?$this->total_ht:"null").",";
$sql.= " total_ttc=".(isset($this->total_ttc)?$this->total_ttc:"null").",";
- $sql.= " revenuestamp=".((isset($this->revenuestamp) && $this->revenuestamp != '')?$this->revenuestamp:"null").",";
- $sql.= " fk_statut=".(isset($this->statut)?$this->statut:"null").",";
- $sql.= " fk_user_author=".(isset($this->user_author)?$this->user_author:"null").",";
- $sql.= " fk_user_valid=".(isset($this->fk_user_valid)?$this->fk_user_valid:"null").",";
- $sql.= " fk_facture_source=".(isset($this->fk_facture_source)?$this->fk_facture_source:"null").",";
- $sql.= " fk_projet=".(isset($this->fk_project)?$this->fk_project:"null").",";
- $sql.= " fk_cond_reglement=".(isset($this->cond_reglement_id)?$this->cond_reglement_id:"null").",";
- $sql.= " fk_mode_reglement=".(isset($this->mode_reglement_id)?$this->mode_reglement_id:"null").",";
+ $sql.= " revenuestamp=".((isset($this->revenuestamp) && $this->revenuestamp != '')?$this->db->escape($this->revenuestamp):"null").",";
+ $sql.= " fk_statut=".(isset($this->statut)?$this->db->escape($this->statut):"null").",";
+ $sql.= " fk_user_author=".(isset($this->user_author)?$this->db->escape($this->user_author):"null").",";
+ $sql.= " fk_user_valid=".(isset($this->fk_user_valid)?$this->db->escape($this->fk_user_valid):"null").",";
+ $sql.= " fk_facture_source=".(isset($this->fk_facture_source)?$this->db->escape($this->fk_facture_source):"null").",";
+ $sql.= " fk_projet=".(isset($this->fk_project)?$this->db->escape($this->fk_project):"null").",";
+ $sql.= " fk_cond_reglement=".(isset($this->cond_reglement_id)?$this->db->escape($this->cond_reglement_id):"null").",";
+ $sql.= " fk_mode_reglement=".(isset($this->mode_reglement_id)?$this->db->escape($this->mode_reglement_id):"null").",";
$sql.= " date_lim_reglement=".(strval($this->date_lim_reglement)!='' ? "'".$this->db->idate($this->date_lim_reglement)."'" : 'null').",";
$sql.= " note_private=".(isset($this->note_private)?"'".$this->db->escape($this->note_private)."'":"null").",";
$sql.= " note_public=".(isset($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null").",";
$sql.= " model_pdf=".(isset($this->modelpdf)?"'".$this->db->escape($this->modelpdf)."'":"null").",";
- $sql.= " import_key=".(isset($this->import_key)?"'".$this->db->escape($this->import_key)."'":"null");
- $sql.= ", situation_cycle_ref=".$this->situation_cycle_ref;
- $sql.= ", situation_counter=".$this->situation_counter;
- $sql.= ", situation_final=".$this->situation_final;
-
+ $sql.= " import_key=".(isset($this->import_key)?"'".$this->db->escape($this->import_key)."'":"null").",";
+ $sql.= " situation_cycle_ref=".(empty($this->situation_cycle_ref)?"null":$this->db->escape($this->situation_cycle_ref)).",";
+ $sql.= " situation_counter=".(empty($this->situation_counter)?"null":$this->db->escape($this->situation_counter)).",";
+ $sql.= " situation_final=".(empty($this->situation_counter)?"0":$this->db->escape($this->situation_counter));
$sql.= " WHERE rowid=".$this->id;
$this->db->begin();
@@ -1611,17 +1616,23 @@ class Facture extends CommonInvoice
$error++; $this->errors[]="Error ".$this->db->lasterror();
}
- if (! $error)
+ if (! $error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options)>0)
{
- if (! $notrigger)
+ $result=$this->insertExtraFields();
+ if ($result < 0)
{
- // Call trigger
- $result=$this->call_trigger('BILL_MODIFY',$user);
- if ($result < 0) $error++;
- // End call triggers
+ $error++;
}
}
+ if (! $error && ! $notrigger)
+ {
+ // Call trigger
+ $result=$this->call_trigger('BILL_MODIFY',$user);
+ if ($result < 0) $error++;
+ // End call triggers
+ }
+
// Commit or rollback
if ($error)
{
@@ -1822,9 +1833,9 @@ class Facture extends CommonInvoice
dol_syslog(get_class($this)."::delete rowid=".$rowid.", ref=".$this->ref.", thirdparty=".$this->thirdparty->name, LOG_DEBUG);
// Test to avoid invoice deletion (allowed if draft)
- $test = $this->is_erasable();
+ $result = $this->is_erasable();
- if ($test <= 0) return 0;
+ if ($result <= 0) return 0;
$error=0;
@@ -1992,6 +2003,7 @@ class Facture extends CommonInvoice
$this->db->begin();
dol_syslog(get_class($this)."::set_paid rowid=".$this->id, LOG_DEBUG);
+
$sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET';
$sql.= ' fk_statut='.self::STATUS_CLOSED;
if (! $close_code) $sql.= ', paye=1';
@@ -1999,7 +2011,6 @@ class Facture extends CommonInvoice
if ($close_note) $sql.= ", close_note='".$this->db->escape($close_note)."'";
$sql.= ' WHERE rowid = '.$this->id;
- dol_syslog(get_class($this)."::set_paid", LOG_DEBUG);
$resql = $this->db->query($sql);
if ($resql)
{
@@ -2254,7 +2265,7 @@ class Facture extends CommonInvoice
// Validate
$sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
- $sql.= " SET facnumber='".$num."', fk_statut = ".self::STATUS_VALIDATED.", fk_user_valid = ".$user->id.", date_valid = '".$this->db->idate($now)."'";
+ $sql.= " SET facnumber='".$num."', fk_statut = ".self::STATUS_VALIDATED.", fk_user_valid = ".($user->id > 0 ? $user->id : "null").", date_valid = '".$this->db->idate($now)."'";
if (! empty($conf->global->FAC_FORCE_DATE_VALIDATION)) // If option enabled, we force invoice date
{
$sql.= ", datef='".$this->db->idate($this->date)."'";
@@ -2371,7 +2382,7 @@ class Facture extends CommonInvoice
if (!empty($conf->global->INVOICE_USE_SITUATION))
{
- $final = True;
+ $final = true;
$nboflines = count($this->lines);
while (($i < $nboflines) && $final) {
$final = ($this->lines[$i]->situation_percent == 100);
@@ -2545,8 +2556,8 @@ class Facture extends CommonInvoice
* @param double $txlocaltax2 Local tax 2 rate (deprecated, use instead txtva with code inside)
* @param int $fk_product Id of predefined product/service
* @param double $remise_percent Percent of discount on line
- * @param int $date_start Date start of service
- * @param int $date_end Date end of service
+ * @param int $date_start Date start of service
+ * @param int $date_end Date end of service
* @param int $ventil Code of dispatching into accountancy
* @param int $info_bits Bits de type de lignes
* @param int $fk_remise_except Id discount used
@@ -2568,11 +2579,12 @@ class Facture extends CommonInvoice
* @param double $pu_ht_devise Unit price in currency
* @return int <0 if KO, Id of line if OK
*/
- function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $date_start='', $date_end='', $ventil=0, $info_bits=0, $fk_remise_except='', $price_base_type='HT', $pu_ttc=0, $type=self::TYPE_STANDARD, $rang=-1, $special_code=0, $origin='', $origin_id=0, $fk_parent_line=0, $fk_fournprice=null, $pa_ht=0, $label='', $array_options=0, $situation_percent=100, $fk_prev_id='', $fk_unit = null, $pu_ht_devise = 0)
+ function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $date_start='', $date_end='', $ventil=0, $info_bits=0, $fk_remise_except='', $price_base_type='HT', $pu_ttc=0, $type=self::TYPE_STANDARD, $rang=-1, $special_code=0, $origin='', $origin_id=0, $fk_parent_line=0, $fk_fournprice=null, $pa_ht=0, $label='', $array_options=0, $situation_percent=100, $fk_prev_id=0, $fk_unit = null, $pu_ht_devise = 0)
{
// Deprecation warning
if ($label) {
dol_syslog(__METHOD__ . ": using line label is deprecated", LOG_WARNING);
+ //var_dump(debug_backtrace(false));exit;
}
global $mysoc, $conf, $langs;
@@ -2739,14 +2751,15 @@ class Facture extends CommonInvoice
// Mise a jour informations denormalisees au niveau de la facture meme
$result=$this->update_price(1,'auto',0,$mysoc); // The addline method is designed to add line from user input so total calculation with update_price must be done using 'auto' mode.
+
if ($result > 0)
{
$this->db->commit();
- return $this->line->rowid;
+ return $this->line->id;
}
else
{
- $this->error=$this->db->error();
+ $this->error=$this->db->lasterror();
$this->db->rollback();
return -1;
}
@@ -3075,7 +3088,7 @@ class Facture extends CommonInvoice
// For triggers
$result = $line->fetch($rowid);
- if (! ($result > 0)) dol_print_error($db, $line->error, $line->errors);
+ if (! ($result > 0)) dol_print_error($this->db, $line->error, $line->errors);
if ($line->delete($user) > 0)
{
@@ -3231,7 +3244,6 @@ class Facture extends CommonInvoice
}
}
-
/**
* Return next reference of customer invoice not already used (or last reference)
* according to numbering module defined into constant FACTURE_ADDON
@@ -3502,6 +3514,7 @@ class Facture extends CommonInvoice
$return = array();
+
$sql = "SELECT f.rowid as rowid, f.facnumber, f.fk_statut, f.type, f.paye, pf.fk_paiement";
$sql.= " FROM ".MAIN_DB_PREFIX."facture as f";
$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
@@ -3513,6 +3526,23 @@ class Facture extends CommonInvoice
// $sql.= " OR f.close_code IS NOT NULL)"; // Classee payee partiellement
$sql.= " AND ff.type IS NULL"; // Renvoi vrai si pas facture de remplacement
$sql.= " AND f.type != ".self::TYPE_CREDIT_NOTE; // Type non 2 si facture non avoir
+
+ if($conf->global->INVOICE_USE_SITUATION_CREDIT_NOTE){
+ // Select the last situation invoice
+ $sqlSit = 'SELECT MAX(fs.rowid)';
+ $sqlSit.= " FROM ".MAIN_DB_PREFIX."facture as fs";
+ $sqlSit.= " WHERE fs.entity = ".$conf->entity;
+ $sqlSit.= " AND fs.type = ".self::TYPE_SITUATION;
+ $sqlSit.= " AND fs.fk_statut in (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")";
+ $sqlSit.= " GROUP BY fs.situation_cycle_ref";
+ $sqlSit.= " ORDER BY fs.situation_counter";
+ $sql.= " AND ( f.type != ".self::TYPE_SITUATION . " OR f.rowid IN (".$sqlSit.") )"; // Type non 5 si facture non avoir
+ }
+ else
+ {
+ $sql.= " AND f.type != ".self::TYPE_SITUATION ; // Type non 5 si facture non avoir
+ }
+
if ($socid > 0) $sql.=" AND f.fk_soc = ".$socid;
$sql.= " ORDER BY f.facnumber";
@@ -4395,7 +4425,7 @@ class FactureLigne extends CommonInvoiceLine
if (empty($this->subprice)) $this->subprice=0;
if (empty($this->special_code)) $this->special_code=0;
if (empty($this->fk_parent_line)) $this->fk_parent_line=0;
- if (empty($this->fk_prev_id)) $this->fk_prev_id = 'null';
+ if (empty($this->fk_prev_id)) $this->fk_prev_id = 0;
if (! isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') $this->situation_percent = 100;
if (empty($this->pa_ht)) $this->pa_ht=0;
@@ -4478,7 +4508,7 @@ class FactureLigne extends CommonInvoiceLine
$sql.= " ".price2num($this->total_localtax1).",";
$sql.= " ".price2num($this->total_localtax2);
$sql.= ", " . $this->situation_percent;
- $sql.= ", " . $this->fk_prev_id;
+ $sql.= ", " . (!empty($this->fk_prev_id)?$this->fk_prev_id:"null");
$sql.= ", ".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
$sql.= ", ".$user->id;
$sql.= ", ".$user->id;
@@ -4494,11 +4524,11 @@ class FactureLigne extends CommonInvoiceLine
$resql=$this->db->query($sql);
if ($resql)
{
- $this->rowid=$this->db->last_insert_id(MAIN_DB_PREFIX.'facturedet');
+ $this->id=$this->db->last_insert_id(MAIN_DB_PREFIX.'facturedet');
+ $this->rowid=$this->id; // For backward compatibility
if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
{
- $this->id=$this->rowid;
$result=$this->insertExtraFields();
if ($result < 0)
{
@@ -4570,12 +4600,12 @@ class FactureLigne extends CommonInvoiceLine
}
$this->db->commit();
- return $this->rowid;
+ return $this->id;
}
else
{
- $this->error=$this->db->error();
+ $this->error=$this->db->lasterror();
$this->db->rollback();
return -2;
}
@@ -4658,11 +4688,11 @@ class FactureLigne extends CommonInvoiceLine
$sql.= ", special_code='".$this->db->escape($this->special_code)."'";
if (empty($this->skip_update_total))
{
- $sql.= ", total_ht=".price2num($this->total_ht)."";
- $sql.= ", total_tva=".price2num($this->total_tva)."";
- $sql.= ", total_ttc=".price2num($this->total_ttc)."";
- $sql.= ", total_localtax1=".price2num($this->total_localtax1)."";
- $sql.= ", total_localtax2=".price2num($this->total_localtax2)."";
+ $sql.= ", total_ht=".price2num($this->total_ht);
+ $sql.= ", total_tva=".price2num($this->total_tva);
+ $sql.= ", total_ttc=".price2num($this->total_ttc);
+ $sql.= ", total_localtax1=".price2num($this->total_localtax1);
+ $sql.= ", total_localtax2=".price2num($this->total_localtax2);
}
$sql.= ", fk_product_fournisseur_price=".(! empty($this->fk_fournprice)?"'".$this->db->escape($this->fk_fournprice)."'":"null");
$sql.= ", buy_price_ht='".price2num($this->pa_ht)."'";
@@ -4694,7 +4724,7 @@ class FactureLigne extends CommonInvoiceLine
}
}
- if (! $notrigger)
+ if (! $error && ! $notrigger)
{
// Call trigger
$result=$this->call_trigger('LINEBILL_UPDATE',$user);
@@ -4755,6 +4785,7 @@ class FactureLigne extends CommonInvoiceLine
/**
* Mise a jour en base des champs total_xxx de ligne de facture
+ * TODO What is goal of this method ?
*
* @return int <0 if KO, >0 if OK
*/
diff --git a/htdocs/compta/facture/class/paymentterm.class.php b/htdocs/compta/facture/class/paymentterm.class.php
index bc13b0d5876..3697a61672b 100644
--- a/htdocs/compta/facture/class/paymentterm.class.php
+++ b/htdocs/compta/facture/class/paymentterm.class.php
@@ -57,7 +57,6 @@ class PaymentTerm // extends CommonObject
function __construct($db)
{
$this->db = $db;
- return 1;
}
@@ -90,7 +89,6 @@ class PaymentTerm // extends CommonObject
// Insert request
$sql = "INSERT INTO ".MAIN_DB_PREFIX."c_payment_term(";
- $sql.= "rowid,";
$sql.= "entity,";
$sql.= "code,";
$sql.= "sortorder,";
@@ -101,7 +99,6 @@ class PaymentTerm // extends CommonObject
$sql.= "nbjour,";
$sql.= "decalage";
$sql.= ") VALUES (";
- $sql.= " ".(! isset($this->rowid)?'NULL':"'".$this->db->escape($this->rowid)."'").",";
$sql.= " ".(! isset($this->entity)?getEntity('c_payment_term'):"'".$this->db->escape($this->entity)."'").",";
$sql.= " ".(! isset($this->code)?'NULL':"'".$this->db->escape($this->code)."'").",";
$sql.= " ".(! isset($this->sortorder)?'NULL':"'".$this->db->escape($this->sortorder)."'").",";
@@ -181,7 +178,6 @@ class PaymentTerm // extends CommonObject
$sql.= " FROM ".MAIN_DB_PREFIX."c_payment_term as t";
$sql.= " WHERE t.rowid = ".$id;
- $sql.= " AND t.entity = " . getEntity('c_payment_term');
dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
$resql=$this->db->query($sql);
@@ -221,36 +217,36 @@ class PaymentTerm // extends CommonObject
*
* @return int <0 if KO, >0 if OK
*/
- function getDefaultId()
- {
- global $langs;
+ function getDefaultId()
+ {
+ global $langs;
- $ret=0;
+ $ret=0;
- $sql = "SELECT";
+ $sql = "SELECT";
$sql.= " t.rowid";
- $sql.= " FROM ".MAIN_DB_PREFIX."c_payment_term as t";
- $sql.= " WHERE t.code = 'RECEP'";
- $sql.= " AND t.entity = " . getEntity('c_payment_term');
+ $sql.= " FROM ".MAIN_DB_PREFIX."c_payment_term as t";
+ $sql.= " WHERE t.code = 'RECEP'";
+ $sql.= " AND t.entity IN (".getEntity('c_payment_term').")";
- dol_syslog(get_class($this)."::getDefaultId", LOG_DEBUG);
- $resql=$this->db->query($sql);
- if ($resql)
- {
- if ($this->db->num_rows($resql))
- {
- $obj = $this->db->fetch_object($resql);
- if ($obj) $ret=$obj->rowid;
- }
- $this->db->free($resql);
- return $ret;
- }
- else
- {
- $this->error="Error ".$this->db->lasterror();
- return -1;
- }
- }
+ dol_syslog(get_class($this)."::getDefaultId", LOG_DEBUG);
+ $resql=$this->db->query($sql);
+ if ($resql)
+ {
+ if ($this->db->num_rows($resql))
+ {
+ $obj = $this->db->fetch_object($resql);
+ if ($obj) $ret=$obj->rowid;
+ }
+ $this->db->free($resql);
+ return $ret;
+ }
+ else
+ {
+ $this->error="Error ".$this->db->lasterror();
+ return -1;
+ }
+ }
/**
@@ -293,7 +289,6 @@ class PaymentTerm // extends CommonObject
$sql.= " nbjour=".(isset($this->nbjour)?$this->nbjour:"null").",";
$sql.= " decalage=".(isset($this->decalage)?$this->decalage:"null")."";
$sql.= " WHERE rowid = " . $this->id;
- $sql.= " AND entity = " . getEntity('c_payment_term');
$this->db->begin();
@@ -336,11 +331,11 @@ class PaymentTerm // extends CommonObject
}
- /**
+ /**
* Delete object in database
*
- * @param User $user User that delete
- * @param int $notrigger 0=launch triggers after, 1=disable triggers
+ * @param User $user User that delete
+ * @param int $notrigger 0=launch triggers after, 1=disable triggers
* @return int <0 if KO, >0 if OK
*/
function delete($user, $notrigger=0)
@@ -350,7 +345,6 @@ class PaymentTerm // extends CommonObject
$sql = "DELETE FROM ".MAIN_DB_PREFIX."c_payment_term";
$sql.= " WHERE rowid = " . $this->id;
- $sql.= " AND t.entity = " . getEntity('c_payment_term');
$this->db->begin();
diff --git a/htdocs/compta/facture/contact.php b/htdocs/compta/facture/contact.php
index 2c95366f9a9..af872a174ca 100644
--- a/htdocs/compta/facture/contact.php
+++ b/htdocs/compta/facture/contact.php
@@ -35,8 +35,8 @@ if (! empty($conf->projet->enabled)) {
require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
}
-$langs->load("bills");
-$langs->load("companies");
+// Load translation files required by the page
+$langs->loadLangs(array('bills', 'companies'));
$id = (GETPOST('id')?GETPOST('id','int'):GETPOST('facid','int')); // For backward compatibility
$ref = GETPOST('ref','alpha');
@@ -155,7 +155,7 @@ if ($id > 0 || ! empty($ref))
$morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1);
$morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1);
// Thirdparty
- $morehtmlref.=' '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1);
+ $morehtmlref.=' '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1,'customer');
// Project
if (! empty($conf->projet->enabled))
{
diff --git a/htdocs/compta/facture/document.php b/htdocs/compta/facture/document.php
index 8b76f9b167f..828c77f1178 100644
--- a/htdocs/compta/facture/document.php
+++ b/htdocs/compta/facture/document.php
@@ -38,11 +38,8 @@ if (! empty($conf->projet->enabled)) {
require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
}
-$langs->load('propal');
-$langs->load('compta');
-$langs->load('other');
-$langs->load("bills");
-$langs->load('companies');
+// Load translation files required by the page
+$langs->loadLangs(array('propal', 'compta', 'other', 'bills', 'companies'));
$id=(GETPOST('id','int')?GETPOST('id','int'):GETPOST('facid','int')); // For backward compatibility
@@ -125,7 +122,7 @@ if ($id > 0 || ! empty($ref))
$morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1);
$morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1);
// Thirdparty
- $morehtmlref.=' '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1);
+ $morehtmlref.=' '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1,'customer');
// Project
if (! empty($conf->projet->enabled))
{
@@ -171,7 +168,7 @@ if ($id > 0 || ! empty($ref))
print '';
print ''.$langs->trans("NbOfAttachedFiles").' '.count($filearray).' ';
- print ''.$langs->trans("TotalSizeOfAttachedFiles").' '.$totalsize.' '.$langs->trans("bytes").' ';
+ print ''.$langs->trans("TotalSizeOfAttachedFiles").' '.dol_print_size($totalsize,1,1).' ';
print "
\n";
print "\n";
diff --git a/htdocs/compta/facture/fiche-rec.php b/htdocs/compta/facture/fiche-rec.php
index 4519fd24f6a..fb70da42665 100644
--- a/htdocs/compta/facture/fiche-rec.php
+++ b/htdocs/compta/facture/fiche-rec.php
@@ -43,7 +43,8 @@ require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
require_once DOL_DOCUMENT_ROOT . '/core/lib/invoice.lib.php';
require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php';
-$langs->loadLangs(array('bills','compta','admin','other','products'));
+// Load translation files required by the page
+$langs->loadLangs(array('bills', 'compta', 'admin', 'other', 'products'));
$action = GETPOST('action','alpha');
$massaction = GETPOST('massaction','alpha');
@@ -63,24 +64,10 @@ if ($action == "create" || $action == "add") $objecttype = '';
$result = restrictedArea($user, 'facture', $id, $objecttype);
$projectid = GETPOST('projectid','int');
-$search_ref=GETPOST('search_ref');
-$search_societe=GETPOST('search_societe');
-$search_montant_ht=GETPOST('search_montant_ht');
-$search_montant_vat=GETPOST('search_montant_vat');
-$search_montant_ttc=GETPOST('search_montant_ttc');
-$search_payment_mode=GETPOST('search_payment_mode');
-$search_payment_term=GETPOST('search_payment_term');
-$day=GETPOST('day');
-$year=GETPOST('year');
-$month=GETPOST('month');
-$day_date_when=GETPOST('day_date_when');
$year_date_when=GETPOST('year_date_when');
$month_date_when=GETPOST('month_date_when');
-$search_recurring=GETPOST('search_recurring','int');
-$search_frequency=GETPOST('search_frequency','alpha');
-$search_unit_frequency=GETPOST('search_unit_frequency','alpha');
-$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit;
+$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit;
$sortfield = GETPOST("sortfield",'alpha');
$sortorder = GETPOST("sortorder",'alpha');
$page = GETPOST("page",'int');
@@ -141,28 +128,6 @@ if (empty($reshook))
include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once
- // Do we click on purge search criteria ?
- if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All test are required to be compatible with all browsers
- {
- $search_ref='';
- $search_societe='';
- $search_montant_ht='';
- $search_montant_vat='';
- $search_montant_ttc='';
- $search_montant_mode='';
- $search_montant_term='';
- $day='';
- $year='';
- $month='';
- $day_date_when='';
- $year_date_when='';
- $month_date_when='';
- $search_recurring='';
- $search_frequency='';
- $search_unit_frequency='';
- $search_array_options=array();
- }
-
// Mass actions
/*$objectclass='MyObject';
$objectlabel='MyObject';
@@ -443,13 +408,16 @@ if (empty($reshook))
}
else if ($action == 'update_extras')
{
+ $object->oldcopy = dol_clone($object);
+
// Fill array 'array_options' with data from update form
$extralabels = $extrafields->fetch_name_optionals_label($object->table_element);
- $ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute'));
+ $ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute','none'));
if ($ret < 0) $error++;
- if (! $error) {
- $result = $object->insertExtraFields();
+ if (! $error)
+ {
+ $result = $object->insertExtraFields('BILLREC_MODIFY');
if ($result < 0)
{
setEventMessages($object->error, $object->errors, 'errors');
@@ -681,6 +649,9 @@ if (empty($reshook))
$fk_unit= GETPOST('units', 'alpha');
}
+ $date_start_fill = GETPOST('date_start_fill','int');
+ $date_end_fill = GETPOST('date_end_fill','int');
+
// Margin
$fournprice = price2num(GETPOST('fournprice' . $predef) ? GETPOST('fournprice' . $predef) : '');
$buyingprice = price2num(GETPOST('buying_price' . $predef) != '' ? GETPOST('buying_price' . $predef) : ''); // If buying_price is '0', we must keep this value
@@ -701,7 +672,7 @@ if (empty($reshook))
else
{
// Insert line
- $result = $object->addline($desc, $pu_ht, $qty, $tva_tx,$localtax1_tx, $localtax2_tx, $idprod, $remise_percent, $price_base_type, $info_bits, '', $pu_ttc, $type, - 1, $special_code, $label, $fk_unit);
+ $result = $object->addline($desc, $pu_ht, $qty, $tva_tx,$localtax1_tx, $localtax2_tx, $idprod, $remise_percent, $price_base_type, $info_bits, '', $pu_ttc, $type, - 1, $special_code, $label, $fk_unit, 0, $date_start_fill, $date_end_fill);
if ($result > 0)
{
@@ -757,6 +728,9 @@ if (empty($reshook))
unset($_POST['date_endmonth']);
unset($_POST['date_endyear']);
+ unset($_POST['date_start_fill']);
+ unset($_POST['date_end_fill']);
+
unset($_POST['situations']);
unset($_POST['progress']);
}
@@ -878,6 +852,9 @@ if (empty($reshook))
$error ++;
}
+ $date_start_fill = GETPOST('date_start_fill','int');
+ $date_end_fill = GETPOST('date_end_fill','int');
+
// Update line
if (! $error)
{
@@ -900,7 +877,10 @@ if (empty($reshook))
$special_code,
$label,
GETPOST('units'),
- $pu_ht_devise
+ $pu_ht_devise,
+ 0,
+ $date_start_fill,
+ $date_end_fill
);
if ($result >= 0)
@@ -1184,7 +1164,7 @@ if ($action == 'create')
$disableedit=1;
$disablemove=1;
$disableremove=1;
- $ret = $object->printObjectLines('', $mysoc, $object->thirdparty, $lineid, 0); // No date selector for template invoice
+ $object->printObjectLines('', $mysoc, $object->thirdparty, $lineid, 0); // No date selector for template invoice
}
print "
\n";
@@ -1533,7 +1513,7 @@ else
//var_dump(dol_print_date($object->date_when+60, 'dayhour').' - '.dol_print_date($now, 'dayhour'));
if (! $object->isMaxNbGenReached())
{
- if ($action != 'editdate_when' && $object->frequency > 0 && $object->date_when && $object->date_when < $now) print img_warning($langs->trans("Late"));
+ if (! $object->suspended && $action != 'editdate_when' && $object->frequency > 0 && $object->date_when && $object->date_when < $now) print img_warning($langs->trans("Late"));
}
else
{
diff --git a/htdocs/compta/facture/info.php b/htdocs/compta/facture/info.php
index 00272fee9b3..8964b85203b 100644
--- a/htdocs/compta/facture/info.php
+++ b/htdocs/compta/facture/info.php
@@ -32,8 +32,8 @@ if (! empty($conf->projet->enabled)) {
require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
}
-$langs->load("companies");
-$langs->load("bills");
+// Load translation files required by the page
+$langs->loadLangs(array('companies', 'bills'));
$id = GETPOST("facid","int");
$ref=GETPOST("ref",'alpha');
@@ -69,7 +69,7 @@ $morehtmlref='
';
$morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1);
$morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1);
// Thirdparty
-$morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1);
+$morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1,'customer');
// Project
if (! empty($conf->projet->enabled))
{
diff --git a/htdocs/compta/facture/invoicetemplate_list.php b/htdocs/compta/facture/invoicetemplate_list.php
index 306106d4889..b7b985dd73c 100644
--- a/htdocs/compta/facture/invoicetemplate_list.php
+++ b/htdocs/compta/facture/invoicetemplate_list.php
@@ -42,10 +42,8 @@ require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
require_once DOL_DOCUMENT_ROOT . '/core/lib/invoice.lib.php';
require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php';
-$langs->load('bills');
-$langs->load('compta');
-$langs->load('admin');
-$langs->load('other');
+// Load translation files required by the page
+$langs->loadLangs(array('bills', 'compta', 'admin', 'other'));
$action = GETPOST('action','alpha');
$massaction = GETPOST('massaction','alpha');
@@ -83,7 +81,7 @@ $search_frequency=GETPOST('search_frequency','alpha');
$search_unit_frequency=GETPOST('search_unit_frequency','alpha');
$search_status=GETPOST('search_status','int');
-$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit;
+$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit;
$sortfield = GETPOST("sortfield",'alpha');
$sortorder = GETPOST("sortorder",'alpha');
$page = GETPOST("page",'int');
@@ -273,14 +271,20 @@ else if ($search_year_date_when > 0)
$sql.= " AND f.date_when BETWEEN '".$db->idate(dol_get_first_day($search_year_date_when,1,false))."' AND '".$db->idate(dol_get_last_day($search_year_date_when,12,false))."'";
}
+$sql.= $db->order($sortfield, $sortorder);
+
$nbtotalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
{
$result = $db->query($sql);
$nbtotalofrecords = $db->num_rows($result);
+ if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0
+ {
+ $page = 0;
+ $offset = 0;
+ }
}
-$sql.= $db->order($sortfield, $sortorder);
$sql.= $db->plimit($limit+1,$offset);
$resql = $db->query($sql);
@@ -419,19 +423,19 @@ if ($resql)
// Date invoice
if (! empty($arrayfields['f.date_last_gen']['checked']))
{
- print '
';
- if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ' ';
- print ' ';
- $formother->select_year($search_year?$search_year:-1,'search_year',1, 20, 5);
+ print ' ';
+ if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ' ';
+ print ' ';
+ $formother->select_year($search_year?$search_year:-1,'search_year',1, 20, 5, 0, 0, '', 'witdhauto valignmiddle');
print ' ';
}
// Date next generation
if (! empty($arrayfields['f.date_when']['checked']))
{
- print '
';
- if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ' ';
- print ' ';
- $formother->select_year($search_year_date_when?$search_year_date_when:-1,'search_year_date_when',1, 20, 5);
+ print ' ';
+ if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ' ';
+ print ' ';
+ $formother->select_year($search_year_date_when?$search_year_date_when:-1,'search_year_date_when',1, 20, 5, 0, 0, '', 'witdhauto valignmiddle');
print ' ';
}
// Extra fields
@@ -599,15 +603,17 @@ if ($resql)
if (! empty($arrayfields['f.date_when']['checked']))
{
print '
';
+ print '';
print ($objp->frequency ? ($invoicerectmp->isMaxNbGenReached()?'':'').dol_print_date($db->jdate($objp->date_when),'day').($invoicerectmp->isMaxNbGenReached()?' ':'') : ''.$langs->trans('NA').' ');
if (! $invoicerectmp->isMaxNbGenReached())
{
- if ($objp->frequency > 0 && $db->jdate($objp->date_when) && $db->jdate($objp->date_when) < $now) print img_warning($langs->trans("Late"));
+ if (! $objp->suspended && $objp->frequency > 0 && $db->jdate($objp->date_when) && $db->jdate($objp->date_when) < $now) print img_warning($langs->trans("Late"));
}
else
{
print img_info($langs->trans("MaxNumberOfGenerationReached"));
}
+ print '
';
print ' ';
if (! $i) $totalarray['nbfield']++;
}
@@ -647,7 +653,7 @@ if ($resql)
}
else
{
- print $langs->trans("DateIsNotEnough");
+ print $form->textwithpicto('', $langs->trans("DateIsNotEnough"));
}
}
else
diff --git a/htdocs/compta/facture/list.php b/htdocs/compta/facture/list.php
index b813ed7c6da..6c39c0cd0a9 100644
--- a/htdocs/compta/facture/list.php
+++ b/htdocs/compta/facture/list.php
@@ -49,10 +49,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
if (! empty($conf->commande->enabled)) require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
-
-$langs->load('bills');
-$langs->load('companies');
-$langs->load('products');
+// Load translation files required by the page
+$langs->loadLangs(array('bills', 'companies', 'products'));
$sall=trim((GETPOST('search_all', 'alphanohtml')!='')?GETPOST('search_all', 'alphanohtml'):GETPOST('sall', 'alphanohtml'));
$projectid=(GETPOST('projectid')?GETPOST('projectid','int'):0);
@@ -66,6 +64,7 @@ $massaction=GETPOST('massaction','alpha');
$show_files=GETPOST('show_files','int');
$confirm=GETPOST('confirm','alpha');
$toselect = GETPOST('toselect', 'array');
+$contextpage=GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'invoicelist';
$lineid=GETPOST('lineid','int');
$userid=GETPOST('userid','int');
@@ -80,7 +79,7 @@ $search_montant_vat=GETPOST('search_montant_vat','alpha');
$search_montant_localtax1=GETPOST('search_montant_localtax1','alpha');
$search_montant_localtax2=GETPOST('search_montant_localtax2','alpha');
$search_montant_ttc=GETPOST('search_montant_ttc','alpha');
-$search_status=GETPOST('search_status','int');
+$search_status=GETPOST('search_status','intcomma');
$search_paymentmode=GETPOST('search_paymentmode','int');
$search_town=GETPOST('search_town','alpha');
$search_zip=GETPOST('search_zip','alpha');
@@ -95,30 +94,28 @@ $search_year = GETPOST('search_year','int');
$search_day_lim = GETPOST('search_day_lim','int');
$search_month_lim = GETPOST('search_month_lim','int');
$search_year_lim = GETPOST('search_year_lim','int');
+$search_categ_cus=trim(GETPOST("search_categ_cus",'int'));
$search_btn=GETPOST('button_search','alpha');
$search_remove_btn=GETPOST('button_removefilter','alpha');
-$option = GETPOST('option');
+$option = GETPOST('search_option');
if ($option == 'late') {
$search_status = '1';
}
$filtre = GETPOST('filtre','alpha');
-$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit;
+$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit;
$sortfield = GETPOST("sortfield",'alpha');
$sortorder = GETPOST("sortorder",'alpha');
$page = GETPOST("page",'int');
if (empty($page) || $page == -1 || !empty($search_btn) || !empty($search_remove_btn) || (empty($toselect) && $massaction === '0')) { $page = 0; } // If $page is not defined, or '' or -1
$offset = $limit * $page;
-if (! $sortorder && ! empty($conf->global->INVOICE_DEFAULT_UNPAYED_SORT_ORDER) && $search_status == 1) $sortorder=$conf->global->INVOICE_DEFAULT_UNPAYED_SORT_ORDER;
+if (! $sortorder && ! empty($conf->global->INVOICE_DEFAULT_UNPAYED_SORT_ORDER) && $search_status == '1') $sortorder=$conf->global->INVOICE_DEFAULT_UNPAYED_SORT_ORDER;
if (! $sortorder) $sortorder='DESC';
if (! $sortfield) $sortfield='f.datef';
$pageprev = $page - 1;
$pagenext = $page + 1;
-// Initialize technical object to manage context to save list fields
-$contextpage=GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'invoicelist';
-
// Security check
$fieldid = (! empty($ref)?'facnumber':'rowid');
if (! empty($user->societe_id)) $socid=$user->societe_id;
@@ -131,6 +128,7 @@ $object=new Facture($db);
$now=dol_now();
// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
+$object = new Facture($db);
$hookmanager->initHooks(array('invoicelist'));
$extrafields = new ExtraFields($db);
@@ -231,6 +229,8 @@ if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter','a
$search_month_lim='';
$toselect='';
$search_array_options=array();
+ $search_categ_cus=0;
+
}
if (empty($reshook))
@@ -278,7 +278,7 @@ if ($massaction == 'withdrawrequest')
$error++;
setEventMessages($objecttmp->ref.' '.$langs->trans("AmountMustBePositive"), $objecttmp->errors, 'errors');
}
- if(!($objecttmp->statut > Facture::STATUS_DRAFT)){
+ if (!($objecttmp->statut > Facture::STATUS_DRAFT)){
$error++;
setEventMessages($objecttmp->ref.' '.$langs->trans("Draft"), $objecttmp->errors, 'errors');
}
@@ -300,11 +300,11 @@ if ($massaction == 'withdrawrequest')
$numprlv = $db->num_rows($result_sql);
}
- if($numprlv>0){
+ if ($numprlv>0){
$error++;
setEventMessages($objecttmp->ref.' '.$langs->trans("RequestAlreadyDone"), $objecttmp->errors, 'errors');
}
- if(!empty($objecttmp->mode_reglement_id ) && $objecttmp->mode_reglement_id != 3){
+ if (!empty($objecttmp->mode_reglement_code ) && $objecttmp->mode_reglement_code != 'PRE'){
$error++;
setEventMessages($objecttmp->ref.' '.$langs->trans("BadPaymentMethod"), $objecttmp->errors, 'errors');
}
@@ -368,10 +368,12 @@ $sql.= ' s.rowid as socid, s.nom as name, s.email, s.town, s.zip, s.fk_pays, s.c
$sql.= " typent.code as typent_code,";
$sql.= " state.code_departement as state_code, state.nom as state_name,";
$sql.= " country.code as country_code,";
-$sql.= " p.rowid as project_id, p.ref as project_ref";
+$sql.= " p.rowid as project_id, p.ref as project_ref, p.title as project_label";
// We need dynamount_payed to be able to sort on status (value is surely wrong because we can count several lines several times due to other left join or link with contacts. But what we need is just 0 or > 0)
// TODO Better solution to be able to sort on already payed or remain to pay is to store amount_payed in a denormalized field.
if (! $sall) $sql.= ', SUM(pf.amount) as dynamount_payed';
+if ($search_categ_cus) $sql .= ", cc.fk_categorie, cc.fk_soc";
+
// Add fields from extrafields
foreach ($extrafields->attribute_label as $key => $val) $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key.' as options_'.$key : '');
// Add fields from hooks
@@ -382,6 +384,8 @@ $sql.= ' FROM '.MAIN_DB_PREFIX.'societe as s';
$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as country on (country.rowid = s.fk_pays)";
$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_typent as typent on (typent.id = s.fk_typent)";
$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as state on (state.rowid = s.fk_departement)";
+if (! empty($search_categ_cus)) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_societe as cc ON s.rowid = cc.fk_soc"; // We'll need this table joined to the select in order to filter by categ
+
$sql.= ', '.MAIN_DB_PREFIX.'facture as f';
if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture_extrafields as ef on (f.rowid = ef.fk_object)";
if (! $sall) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiement_facture as pf ON pf.fk_facture = f.rowid';
@@ -438,12 +442,21 @@ if ($search_montant_vat != '') $sql.= natural_search('f.tva', $search_montant_va
if ($search_montant_localtax1 != '') $sql.= natural_search('f.localtax1', $search_montant_localtax1, 1);
if ($search_montant_localtax2 != '') $sql.= natural_search('f.localtax2', $search_montant_localtax2, 1);
if ($search_montant_ttc != '') $sql.= natural_search('f.total_ttc', $search_montant_ttc, 1);
-if ($search_status != '' && $search_status >= 0)
+if ($search_categ_cus > 0) $sql.= " AND cc.fk_categorie = ".$db->escape($search_categ_cus);
+if ($search_categ_cus == -2) $sql.= " AND cc.fk_categorie IS NULL";
+if ($search_status != '-1' && $search_status != '')
{
- if ($search_status == '0') $sql.=" AND f.fk_statut = 0"; // draft
- if ($search_status == '1') $sql.=" AND f.fk_statut = 1"; // unpayed
- if ($search_status == '2') $sql.=" AND f.fk_statut = 2"; // payed Not that some corrupted data may contains f.fk_statut = 1 AND f.paye = 1 (it means payed too but should not happend. If yes, reopen and reclassify billed)
- if ($search_status == '3') $sql.=" AND f.fk_statut = 3"; // abandonned
+ if (is_numeric($search_status) && $search_status >= 0)
+ {
+ if ($search_status == '0') $sql.=" AND f.fk_statut = 0"; // draft
+ if ($search_status == '1') $sql.=" AND f.fk_statut = 1"; // unpayed
+ if ($search_status == '2') $sql.=" AND f.fk_statut = 2"; // payed Not that some corrupted data may contains f.fk_statut = 1 AND f.paye = 1 (it means payed too but should not happend. If yes, reopen and reclassify billed)
+ if ($search_status == '3') $sql.=" AND f.fk_statut = 3"; // abandonned
+ }
+ else
+ {
+ $sql.= " AND f.fk_statut IN (".$search_status.")"; // When search_status is '1,2' for example
+ }
}
if ($search_paymentmode > 0) $sql .= " AND f.fk_mode_reglement = ".$db->escape($search_paymentmode);
if ($search_month > 0)
@@ -453,7 +466,7 @@ if ($search_month > 0)
else if ($search_year > 0 && ! empty($search_day))
$sql.= " AND f.datef BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $search_month, $search_day, $search_year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $search_month, $search_day, $serch_year))."'";
else
- $sql.= " AND date_format(f.datef, '%m') = '".$month."'";
+ $sql.= " AND date_format(f.datef, '%m') = '".$search_month."'";
}
else if ($search_year > 0)
{
@@ -510,7 +523,8 @@ else
$sql.= ' ORDER BY ';
$listfield=explode(',',$sortfield);
-foreach ($listfield as $key => $value) $sql.= $listfield[$key].' '.$sortorder.',';
+$listorder=explode(',',$sortorder);
+foreach ($listfield as $key => $value) $sql.= $listfield[$key].' '.($listorder[$key]?$listorder[$key]:'DESC').',';
$sql.= ' f.rowid DESC ';
$nbtotalofrecords = '';
@@ -518,6 +532,11 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
{
$result = $db->query($sql);
$nbtotalofrecords = $db->num_rows($result);
+ if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0
+ {
+ $page = 0;
+ $offset = 0;
+ }
}
$sql.= $db->plimit($limit+1,$offset);
@@ -538,8 +557,8 @@ if ($resql)
}
$param='&socid='.$socid;
- if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage;
- if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit;
+ if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage);
+ if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit);
if ($sall) $param.='&sall='.urlencode($sall);
if ($search_day) $param.='&search_day='.urlencode($search_day);
if ($search_month) $param.='&search_month='.urlencode($search_month);
@@ -563,9 +582,11 @@ if ($resql)
if ($search_montant_ttc != '') $param.='&search_montant_ttc='.urlencode($search_montant_ttc);
if ($search_status != '') $param.='&search_status='.urlencode($search_status);
if ($search_paymentmode > 0) $param.='search_paymentmode='.urlencode($search_paymentmode);
- if ($show_files) $param.='&show_files=' .urlencode($show_files);
- if ($option) $param.="&option=".urlencode($option);
+ if ($show_files) $param.='&show_files='.urlencode($show_files);
+ if ($option) $param.="&search_option=".urlencode($option);
if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss);
+ if ($search_categ_cus > 0) $param.='&search_categ_cus='.urlencode($search_categ_cus);
+
// Add $param from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
@@ -574,26 +595,29 @@ if ($resql)
'presend'=>$langs->trans("SendByMail"),
'builddoc'=>$langs->trans("PDFMerge"),
);
- if ($conf->prelevement->enabled)
- {
- $langs->load("withdrawals");
- $arrayofmassactions['withdrawrequest']=$langs->trans("MakeWithdrawRequest");
+ if ($conf->prelevement->enabled) {
+ $langs->load("withdrawals");
+ $arrayofmassactions['withdrawrequest'] = $langs->trans("MakeWithdrawRequest");
}
- if ($user->rights->facture->supprimer)
- {
- //if (! empty($conf->global->STOCK_CALCULATE_ON_BILL) || empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED))
- if (empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED))
- {
- // mass deletion never possible on invoices on such situation
+ if ($user->rights->facture->supprimer) {
+ if (!empty($conf->global->INVOICE_CAN_REMOVE_DRAFT_ONLY)) {
+ $arrayofmassactions['predeletedraft'] = $langs->trans("Deletedraft");
}
- else
- {
- $arrayofmassactions['predelete']=$langs->trans("Delete");
- }
- }
- if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array();
+ elseif (!empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED)) { // mass deletion never possible on invoices on such situation
+ $arrayofmassactions['predelete'] = $langs->trans("Delete");
+ }
+ }
+ if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array();
$massactionbutton=$form->selectMassAction('', $arrayofmassactions);
+ $newcardbutton='';
+ if($user->rights->facture->creer)
+ {
+ $newcardbutton='
'.$langs->trans('NewBill').' ';
+ $newcardbutton.= ' ';
+ $newcardbutton.= '';
+ }
+
$i = 0;
print '
'."\n";
@@ -607,7 +631,7 @@ if ($resql)
print ' ';
print ' ';
- print_barre_liste($langs->trans('BillsCustomers').' '.($socid?' '.$soc->name:''), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_accountancy.png', 0, '', '', $limit);
+ print_barre_liste($langs->trans('BillsCustomers').' '.($socid?' '.$soc->name:''), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_accountancy.png', 0, $newcardbutton, '', $limit);
$topicmail="SendBillRef";
$modelmail="facture_send";
@@ -618,7 +642,7 @@ if ($resql)
if ($sall)
{
foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val);
- print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall);
+ print ''.$langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall).'
';
}
// If the user can view prospects other than his'
@@ -649,6 +673,14 @@ if ($resql)
$moreforfilter.=$form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1);
$moreforfilter.=' ';
}
+ if (! empty($conf->categorie->enabled))
+ {
+ require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
+ $moreforfilter.='
';
+ $moreforfilter.=$langs->trans('CustomersProspectsCategoriesShort').': ';
+ $moreforfilter.=$formother->select_categories('customer',$search_categ_cus,'search_categ_cus',1);
+ $moreforfilter.='
';
+ }
$parameters=array();
$reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook
if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint;
@@ -706,19 +738,19 @@ if ($resql)
if (! empty($arrayfields['f.date']['checked']))
{
print '
';
- if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ' ';
- print ' ';
- $formother->select_year($search_year?$search_year:-1,'search_year',1, 20, 5, 0, 0, '', 'width75');
+ if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ' ';
+ print ' ';
+ $formother->select_year($search_year?$search_year:-1,'search_year',1, 20, 5, 0, 0, '', 'widthauto valignmiddle');
print ' ';
}
// Date due
if (! empty($arrayfields['f.date_lim_reglement']['checked']))
{
print '
';
- if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ' ';
- print ' ';
- $formother->select_year($search_year_lim?$search_year_lim:-1,'search_year_lim',1, 20, 5, 0, 0, '', 'width75');
- print ' '.$langs->trans("Late");
+ if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ' ';
+ print ' ';
+ $formother->select_year($search_year_lim?$search_year_lim:-1,'search_year_lim',1, 20, 5, 0, 0, '', 'widthauto valignmiddle');
+ print ' '.$langs->trans("Late");
print ' ';
}
// Project
@@ -760,7 +792,7 @@ if ($resql)
if (! empty($arrayfields['f.fk_mode_reglement']['checked']))
{
print '
';
- $form->select_types_paiements($search_paymentmode, 'search_paymentmode', '', 0, 0, 1, 10);
+ $form->select_types_paiements($search_paymentmode, 'search_paymentmode', '', 0, 1, 1, 10);
print ' ';
}
if (! empty($arrayfields['f.total_ht']['checked']))
@@ -779,14 +811,14 @@ if ($resql)
}
if (! empty($arrayfields['f.total_localtax1']['checked']))
{
- // Amount
+ // Localtax1
print '
';
print ' ';
print ' ';
}
if (! empty($arrayfields['f.total_localtax2']['checked']))
{
- // Amount
+ // Localtax2
print '
';
print ' ';
print ' ';
@@ -831,7 +863,7 @@ if ($resql)
if (! empty($arrayfields['f.fk_statut']['checked']))
{
print '
';
- $liststatus=array('0'=>$langs->trans("BillShortStatusDraft"), '1'=>$langs->trans("BillShortStatusNotPaid"), '2'=>$langs->trans("BillShortStatusPaid"), '3'=>$langs->trans("BillShortStatusCanceled"));
+ $liststatus=array('0'=>$langs->trans("BillShortStatusDraft"), '1'=>$langs->trans("BillShortStatusNotPaid"), '2'=>$langs->trans("BillShortStatusPaid"), '1,2'=>$langs->trans("BillShortStatusNotPaid").'+'.$langs->trans("BillShortStatusPaid"), '3'=>$langs->trans("BillShortStatusCanceled"));
print $form->selectarray('search_status', $liststatus, $search_status, 1);
print ' ';
}
@@ -871,7 +903,7 @@ if ($resql)
print $hookmanager->resPrint;
if (! empty($arrayfields['f.datec']['checked'])) print_liste_field_titre($arrayfields['f.datec']['label'],$_SERVER["PHP_SELF"],"f.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder);
if (! empty($arrayfields['f.tms']['checked'])) print_liste_field_titre($arrayfields['f.tms']['label'],$_SERVER["PHP_SELF"],"f.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder);
- if (! empty($arrayfields['f.fk_statut']['checked'])) print_liste_field_titre($arrayfields['f.fk_statut']['label'],$_SERVER["PHP_SELF"],"fk_statut,paye,type,dynamount_payed","",$param,'align="right"',$sortfield,$sortorder);
+ if (! empty($arrayfields['f.fk_statut']['checked'])) print_liste_field_titre($arrayfields['f.fk_statut']['label'],$_SERVER["PHP_SELF"],"f.fk_statut,f.paye,f.type,dynamount_payed","",$param,'align="right"',$sortfield,$sortorder);
print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch ');
print "
\n";
@@ -983,6 +1015,7 @@ if ($resql)
{
$projectstatic->id=$obj->project_id;
$projectstatic->ref=$obj->project_ref;
+ $projectstatic->title=$obj->project_label;
print $projectstatic->getNomUrl(1);
}
print '';
@@ -1196,22 +1229,18 @@ if ($resql)
print " \n";
- if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files)
- {
- // Show list of available documents
- $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder;
- $urlsource.=str_replace('&','&',$param);
+ $hidegeneratedfilelistifempty=1;
+ if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty=0;
- $filedir=$diroutputmassaction;
- $genallowed=$user->rights->facture->lire;
- $delallowed=$user->rights->facture->creer;
+ // Show list of available documents
+ $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder;
+ $urlsource.=str_replace('&','&',$param);
- print $formfile->showdocuments('massfilesarea_invoices','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,'');
- }
- else
- {
- print ''.$langs->trans("ShowTempMassFilesArea").' ';
- }
+ $filedir=$diroutputmassaction;
+ $genallowed=$user->rights->facture->lire;
+ $delallowed=$user->rights->facture->creer;
+
+ print $formfile->showdocuments('massfilesarea_invoices','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,'','','',null,$hidegeneratedfilelistifempty);
}
else
{
diff --git a/htdocs/compta/facture/note.php b/htdocs/compta/facture/note.php
index 755ac413743..58fc26030b7 100644
--- a/htdocs/compta/facture/note.php
+++ b/htdocs/compta/facture/note.php
@@ -33,8 +33,8 @@ if (! empty($conf->projet->enabled)) {
require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
}
-$langs->load("companies");
-$langs->load("bills");
+// Load translation files required by the page
+$langs->loadLangs(array('companies', 'bills'));
$id=(GETPOST('id','int')?GETPOST('id','int'):GETPOST('facid','int')); // For backward compatibility
$ref=GETPOST('ref','alpha');
@@ -92,7 +92,7 @@ if ($id > 0 || ! empty($ref))
$morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1);
$morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1);
// Thirdparty
- $morehtmlref.=' '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1);
+ $morehtmlref.=' '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1,'customer');
// Project
if (! empty($conf->projet->enabled))
{
diff --git a/htdocs/compta/facture/prelevement.php b/htdocs/compta/facture/prelevement.php
index 989e742afee..ecde973bd3b 100644
--- a/htdocs/compta/facture/prelevement.php
+++ b/htdocs/compta/facture/prelevement.php
@@ -37,10 +37,8 @@ if (! empty($conf->projet->enabled)) {
if (!$user->rights->facture->lire) accessforbidden();
-$langs->load("bills");
-$langs->load("banks");
-$langs->load("withdrawals");
-$langs->load('companies');
+// Load translation files required by the page
+$langs->loadLangs(array('bills', 'banks', 'withdrawals', 'companies'));
$id=(GETPOST('id','int')?GETPOST('id','int'):GETPOST('facid','int')); // For backward compatibility
$ref=GETPOST('ref','alpha');
@@ -140,8 +138,16 @@ if ($object->id > 0)
if ($object->paye) $resteapayer=0;
$resteapayeraffiche=$resteapayer;
- $absolute_discount=$object->thirdparty->getAvailableDiscounts('','fk_facture_source IS NULL');
- $absolute_creditnote=$object->thirdparty->getAvailableDiscounts('','fk_facture_source IS NOT NULL');
+ if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
+ $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
+ $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
+ } else {
+ $filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')";
+ $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')";
+ }
+
+ $absolute_discount=$object->thirdparty->getAvailableDiscounts('',$filterabsolutediscount);
+ $absolute_creditnote=$object->thirdparty->getAvailableDiscounts('',$filtercreditnote);
$absolute_discount=price2num($absolute_discount,'MT');
$absolute_creditnote=price2num($absolute_creditnote,'MT');
@@ -253,61 +259,13 @@ if ($object->id > 0)
// Discounts
print ''.$langs->trans('Discounts').' ';
- if ($object->thirdparty->remise_percent) print $langs->trans("CompanyHasRelativeDiscount",$object->thirdparty->remise_percent);
- else print $langs->trans("CompanyHasNoRelativeDiscount");
- print '. ';
- if ($absolute_discount > 0)
- {
- if ($object->statut > Facture::STATUS_DRAFT || $object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT)
- {
- if ($object->statut == Facture::STATUS_DRAFT)
- {
- print $langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->transnoentities("Currency".$conf->currency)).'. ';
- }
- else
- {
- if ($object->statut < Facture::STATUS_VALIDATED || $object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT)
- {
- $text=$langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->transnoentities("Currency".$conf->currency));
- print ' '.$text.'. ';
- }
- else
- {
- $text=$langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->transnoentities("Currency".$conf->currency));
- $text2=$langs->trans("AbsoluteDiscountUse");
- print $form->textwithpicto($text,$text2);
- }
- }
- }
- else
- {
- // Remise dispo de type non avoir
- $filter='fk_facture_source IS NULL';
- print ' ';
- $form->form_remise_dispo($_SERVER["PHP_SELF"].'?id='.$object->id,0,'remise_id',$object->thirdparty->id,$absolute_discount,$filter,$resteapayer,'',1);
- }
- }
- if ($absolute_creditnote > 0)
- {
- // If validated, we show link "add credit note to payment"
- if ($object->statut != Facture::STATUS_VALIDATED || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_CREDIT_NOTE)
- {
- if ($object->statut == Facture::STATUS_DRAFT && $object->type != Facture::TYPE_DEPOSIT)
- {
- $text=$langs->trans("CompanyHasCreditNote",price($absolute_creditnote),$langs->transnoentities("Currency".$conf->currency));
- print $form->textwithpicto($text,$langs->trans("CreditNoteDepositUse"));
- }
- else print $langs->trans("CompanyHasCreditNote",price($absolute_creditnote),$langs->transnoentities("Currency".$conf->currency)).'.';
- }
- else
- {
- // Remise dispo de type avoir
- $filter='fk_facture_source IS NOT NULL';
- if (! $absolute_discount) print ' ';
- $form->form_remise_dispo($_SERVER["PHP_SELF"].'?id='.$object->id,0,'remise_id_for_payment',$object->thirdparty->id,$absolute_creditnote,$filter,$resteapayer,'',1);
- }
- }
- if (! $absolute_discount && ! $absolute_creditnote) print $langs->trans("CompanyHasNoAbsoluteDiscount").'.';
+
+ $thirdparty = $object->thirdparty;
+ $discount_type = 0;
+ $backtopage = urlencode($_SERVER["PHP_SELF"] . '?facid=' . $object->id);
+ $cannotApplyDiscount = 1;
+ include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php';
+
print ' ';
// Date invoice
diff --git a/htdocs/compta/facture/stats/index.php b/htdocs/compta/facture/stats/index.php
index d85255fbf4e..0416e04f7b0 100644
--- a/htdocs/compta/facture/stats/index.php
+++ b/htdocs/compta/facture/stats/index.php
@@ -3,7 +3,7 @@
* Copyright (c) 2004-2012 Laurent Destailleur
* Copyright (C) 2012 Marcos García
* Copyright (C) 2013 Juanjo Menent
- * Copyright (C) 2015 Jean-François Ferry
+ * Copyright (C) 2015 Jean-François Ferry
*
* 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
@@ -57,10 +57,8 @@ $endyear=$year;
/*
* View
*/
-
-$langs->load('bills');
-$langs->load('companies');
-$langs->load('other');
+// Load translation files required by the page
+$langs->loadLangs(array('bills', 'companies', 'other'));
$form=new Form($db);
@@ -331,7 +329,7 @@ print '';
// Show graphs
-print '
';
+print '';
if ($mesg) { print $mesg; }
else {
print $px1->show();
diff --git a/htdocs/compta/facture/tpl/linkedobjectblock.tpl.php b/htdocs/compta/facture/tpl/linkedobjectblock.tpl.php
index ca3ec7c89c0..1a55771b963 100644
--- a/htdocs/compta/facture/tpl/linkedobjectblock.tpl.php
+++ b/htdocs/compta/facture/tpl/linkedobjectblock.tpl.php
@@ -39,20 +39,19 @@ $linkedObjectBlock = $GLOBALS['linkedObjectBlock'];
$langs->load("bills");
$total=0; $ilink=0;
-$var=true;
foreach($linkedObjectBlock as $key => $objectlink)
{
$ilink++;
- $trclass=($var?'pair':'impair');
+ $trclass='oddeven';
if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass.=' liste_sub_total';
?>
-
- trans("CustomerInvoice"); ?>
- getNomUrl(1); ?>
- ref_client; ?>
- date,'day'); ?>
- " data-element="element; ?>" data-id="id; ?>" >
+ trans("CustomerInvoice"); ?>
+ getNomUrl(1); ?>
+ ref_client; ?>
+ date,'day'); ?>
+ rights->facture->lire) {
$sign = 1;
if ($object->type == Facture::TYPE_CREDIT_NOTE) $sign = -1;
@@ -66,8 +65,8 @@ foreach($linkedObjectBlock as $key => $objectlink)
echo ''.price($objectlink->total_ht).' ';
}
} ?>
- getLibStatut(3); ?>
- id.'&action=dellink&dellinkid='.$key; ?>">transnoentitiesnoconv("RemoveLink")); ?>
+ getLibStatut(3); ?>
+ id.'&action=dellink&dellinkid='.$key; ?>">transnoentitiesnoconv("RemoveLink"), 'unlink'); ?>
1)
}
?>
-
\ No newline at end of file
+
diff --git a/htdocs/compta/facture/tpl/linkedobjectblockForRec.tpl.php b/htdocs/compta/facture/tpl/linkedobjectblockForRec.tpl.php
index e0f132e2ad5..5f224bc2026 100644
--- a/htdocs/compta/facture/tpl/linkedobjectblockForRec.tpl.php
+++ b/htdocs/compta/facture/tpl/linkedobjectblockForRec.tpl.php
@@ -39,15 +39,14 @@ $linkedObjectBlock = $GLOBALS['linkedObjectBlock'];
$langs->load("bills");
$total=0; $ilink=0;
-$var=true;
foreach($linkedObjectBlock as $key => $objectlink)
{
$ilink++;
- $trclass=($var?'pair':'impair');
+ $trclass='oddeven';
if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass.=' liste_sub_total';
?>
- >
+
trans("RepeatableInvoice"); ?>
getNomUrl(1); ?>
@@ -62,7 +61,7 @@ foreach($linkedObjectBlock as $key => $objectlink)
print $objectlink->getLibStatut(3);
?>
- id.'&action=dellink&dellinkid='.$key; ?>">transnoentitiesnoconv("RemoveLink")); ?>
+ id.'&action=dellink&dellinkid='.$key; ?>">transnoentitiesnoconv("RemoveLink"), 'unlink'); ?>
tax->enabled))
//if (!$user->rights->compta->general->lire)
// accessforbidden();
-$langs->load("compta");
-$langs->load("bills");
+// Load translation files required by the page
+$langs->loadLangs(array('compta', 'bills'));
if (! empty($conf->commande->enabled))
$langs->load("orders");
@@ -199,7 +199,7 @@ if (! empty($conf->facture->enabled) && $user->rights->facture->lire)
print $facturestatic->getNomUrl(1,'');
print '';
print '';
- print $companystatic->getNomUrl(1,'',16);
+ print $companystatic->getNomUrl(1,'customer',16);
print ' ';
print ''.price($obj->total_ttc).' ';
print '';
@@ -234,7 +234,8 @@ if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture-
$sql.= ", s.nom as name";
$sql.= ", s.rowid as socid, s.email";
$sql.= ", s.code_fournisseur, s.code_compta_fournisseur";
- $sql.= " FROM ".MAIN_DB_PREFIX."facture_fourn as f, ".MAIN_DB_PREFIX."societe as s";
+ $sql.= ", cc.rowid as country_id, cc.code as country_code";
+ $sql.= " FROM ".MAIN_DB_PREFIX."facture_fourn as f, ".MAIN_DB_PREFIX."societe as s LEFT JOIN ".MAIN_DB_PREFIX."c_country as cc ON cc.rowid = s.fk_pays";
if (!$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
$sql.= " WHERE s.rowid = f.fk_soc AND f.fk_statut = 0";
$sql.= " AND f.entity = ".$conf->entity;
@@ -274,6 +275,8 @@ if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture-
$companystatic->id=$obj->socid;
$companystatic->name=$obj->name;
$companystatic->email=$obj->email;
+ $companystatic->country_id=$obj->country_id;
+ $companystatic->country_code=$obj->country_code;
$companystatic->fournisseur = 1;
$companystatic->code_client = $obj->code_client;
$companystatic->code_fournisseur = $obj->code_fournisseur;
@@ -313,7 +316,7 @@ if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture-
print '';
-// Last modified customer invoices
+// Latest modified customer invoices
if (! empty($conf->facture->enabled) && $user->rights->facture->lire)
{
$langs->load("boxes");
@@ -323,9 +326,10 @@ if (! empty($conf->facture->enabled) && $user->rights->facture->lire)
$sql.= ", f.date_lim_reglement as datelimite";
$sql.= ", s.nom as name";
$sql.= ", s.rowid as socid";
- $sql.= ", s.code_client, s.code_compta";
- $sql.= ", sum(pf.amount) as am";
- $sql.= " FROM ".MAIN_DB_PREFIX."societe as s,".MAIN_DB_PREFIX."facture as f";
+ $sql.= ", s.code_client, s.code_compta, s.email";
+ $sql.= ", cc.rowid as country_id, cc.code as country_code";
+ $sql.= ", sum(pf.amount) as am";
+ $sql.= " FROM ".MAIN_DB_PREFIX."societe as s LEFT JOIN ".MAIN_DB_PREFIX."c_country as cc ON cc.rowid = s.fk_pays, ".MAIN_DB_PREFIX."facture as f";
$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf on f.rowid=pf.fk_facture";
if (!$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
$sql.= " WHERE s.rowid = f.fk_soc";
@@ -338,7 +342,8 @@ if (! empty($conf->facture->enabled) && $user->rights->facture->lire)
$sql.=$hookmanager->resPrint;
$sql.= " GROUP BY f.rowid, f.facnumber, f.fk_statut, f.type, f.total, f.tva, f.total_ttc, f.paye, f.tms, f.date_lim_reglement,";
- $sql.= " s.nom, s.rowid, s.code_client, s.code_compta";
+ $sql.= " s.nom, s.rowid, s.code_client, s.code_compta, s.email,";
+ $sql.= " cc.rowid, cc.code";
$sql.= " ORDER BY f.tms DESC ";
$sql.= $db->plimit($max, 0);
@@ -374,6 +379,10 @@ if (! empty($conf->facture->enabled) && $user->rights->facture->lire)
$thirdpartystatic->id=$obj->socid;
$thirdpartystatic->name=$obj->name;
+ $thirdpartystatic->email=$obj->email;
+ $thirdpartystatic->country_id=$obj->country_id;
+ $thirdpartystatic->country_code=$obj->country_code;
+ $thirdpartystatic->email=$obj->email;
$thirdpartystatic->client=1;
$thirdpartystatic->code_client = $obj->code_client;
//$thirdpartystatic->code_fournisseur = $obj->code_fournisseur;
@@ -567,10 +576,8 @@ if (! empty($conf->don->enabled) && $user->rights->societe->lire)
print '';
if ($num)
{
- $var = true;
$total_ttc = $totalam = $total = 0;
- $var=true;
while ($i < $num && $i < $max)
{
$objp = $db->fetch_object($result);
@@ -631,7 +638,6 @@ if (! empty($conf->tax->enabled) && $user->rights->tax->charges->lire)
$resql = $db->query($sql);
if ( $resql )
{
- $var = false;
$num = $db->num_rows($resql);
print '
';
@@ -663,7 +669,6 @@ if (! empty($conf->tax->enabled) && $user->rights->tax->charges->lire)
print ''.$chargestatic->getLibStatut(3).' ';
print '';
$tot_ttc+=$obj->amount;
- $var = !$var;
$i++;
}
@@ -699,8 +704,9 @@ if (! empty($conf->facture->enabled) && ! empty($conf->commande->enabled) && $us
$sql.= ", s.nom as name, s.email";
$sql.= ", s.rowid as socid";
$sql.= ", s.code_client, s.code_compta";
- $sql.= ", c.rowid, c.ref, c.facture, c.fk_statut, c.total_ht, c.tva as total_tva, c.total_ttc";
- $sql.= " FROM ".MAIN_DB_PREFIX."societe as s";
+ $sql.= ", c.rowid, c.ref, c.facture, c.fk_statut, c.total_ht, c.tva as total_tva, c.total_ttc,";
+ $sql.= " cc.rowid as country_id, cc.code as country_code";
+ $sql.= " FROM ".MAIN_DB_PREFIX."societe as s LEFT JOIN ".MAIN_DB_PREFIX."c_country as cc ON cc.rowid = s.fk_pays";
if (!$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
$sql.= ", ".MAIN_DB_PREFIX."commande as c";
$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON el.fk_source = c.rowid AND el.sourcetype = 'commande'";
@@ -716,12 +722,11 @@ if (! empty($conf->facture->enabled) && ! empty($conf->commande->enabled) && $us
$reshook=$hookmanager->executeHooks('printFieldListWhereCustomerOrderToBill',$parameters);
$sql.=$hookmanager->resPrint;
- $sql.= " GROUP BY s.nom, s.rowid, s.email, s.code_client, s.code_compta, c.rowid, c.ref, c.facture, c.fk_statut, c.tva, c.total_ht, c.total_ttc";
+ $sql.= " GROUP BY s.nom, s.email, s.rowid, s.code_client, s.code_compta, c.rowid, c.ref, c.facture, c.fk_statut, c.total_ht, c.tva, c.total_ttc, cc.rowid, cc.code";
$resql = $db->query($sql);
if ( $resql )
{
- $var=false;
$num = $db->num_rows($resql);
if ($num)
@@ -745,6 +750,8 @@ if (! empty($conf->facture->enabled) && ! empty($conf->commande->enabled) && $us
$societestatic->id=$obj->socid;
$societestatic->name=$obj->name;
$societestatic->email=$obj->email;
+ $societestatic->country_id=$obj->country_id;
+ $societestatic->country_code=$obj->country_code;
$societestatic->client=1;
$societestatic->code_client = $obj->code_client;
//$societestatic->code_fournisseur = $obj->code_fournisseur;
@@ -817,8 +824,9 @@ if (! empty($conf->facture->enabled) && $user->rights->facture->lire)
$sql.= ", s.nom as name";
$sql.= ", s.rowid as socid, s.email";
$sql.= ", s.code_client, s.code_compta";
- $sql.= ", sum(pf.amount) as am";
- $sql.= " FROM ".MAIN_DB_PREFIX."societe as s,".MAIN_DB_PREFIX."facture as f";
+ $sql.= ", cc.rowid as country_id, cc.code as country_code";
+ $sql.= ", sum(pf.amount) as am";
+ $sql.= " FROM ".MAIN_DB_PREFIX."societe as s LEFT JOIN ".MAIN_DB_PREFIX."c_country as cc ON cc.rowid = s.fk_pays,".MAIN_DB_PREFIX."facture as f";
$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf on f.rowid=pf.fk_facture";
if (!$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
$sql.= " WHERE s.rowid = f.fk_soc AND f.paye = 0 AND f.fk_statut = 1";
@@ -831,13 +839,12 @@ if (! empty($conf->facture->enabled) && $user->rights->facture->lire)
$sql.=$hookmanager->resPrint;
$sql.= " GROUP BY f.rowid, f.facnumber, f.fk_statut, f.datef, f.type, f.total, f.tva, f.total_ttc, f.paye, f.tms, f.date_lim_reglement,";
- $sql.= " s.nom, s.rowid, s.email, s.code_client, s.code_compta";
+ $sql.= " s.nom, s.rowid, s.email, s.code_client, s.code_compta, cc.rowid, cc.code";
$sql.= " ORDER BY f.datef ASC, f.facnumber ASC";
$resql = $db->query($sql);
if ($resql)
{
- $var=false;
$num = $db->num_rows($resql);
$i = 0;
@@ -870,6 +877,8 @@ if (! empty($conf->facture->enabled) && $user->rights->facture->lire)
$societestatic->id=$obj->socid;
$societestatic->name=$obj->name;
$societestatic->email=$obj->email;
+ $societestatic->country_id=$obj->country_id;
+ $societestatic->country_code=$obj->country_code;
$societestatic->client=1;
$societestatic->code_client = $obj->code_client;
$societestatic->code_fournisseur = $obj->code_fournisseur;
@@ -971,7 +980,6 @@ if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture-
$resql=$db->query($sql);
if ($resql)
{
- $var=false;
$num = $db->num_rows($resql);
print '';
@@ -1022,7 +1030,6 @@ if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture-
$total_ttc += $obj->total_ttc;
$totalam += $obj->am;
$i++;
- $var = !$var;
}
print '
'.$langs->trans("Total").' ('.$langs->trans("RemainderToPay").': '.price($total_ttc-$totalam).') ';
@@ -1056,7 +1063,6 @@ if ($resql)
print '';
print ''.$langs->trans("TasksToDo").'';
print " \n";
- $var = true;
$i = 0;
while ($i < $db->num_rows($resql))
{
diff --git a/htdocs/compta/journal/purchasesjournal.php b/htdocs/compta/journal/purchasesjournal.php
index 5934ca71afb..2bc754ccf11 100644
--- a/htdocs/compta/journal/purchasesjournal.php
+++ b/htdocs/compta/journal/purchasesjournal.php
@@ -33,9 +33,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.class.php';
-$langs->load("companies");
-$langs->load("other");
-$langs->load("compta");
+// Load translation files required by the page
+$langs->loadlangs(array('companies', 'other', 'compta'));
$date_startmonth=GETPOST('date_startmonth');
$date_startday=GETPOST('date_startday');
diff --git a/htdocs/compta/journal/sellsjournal.php b/htdocs/compta/journal/sellsjournal.php
index f4b027b5016..24b36cf76c0 100644
--- a/htdocs/compta/journal/sellsjournal.php
+++ b/htdocs/compta/journal/sellsjournal.php
@@ -35,10 +35,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
require_once DOL_DOCUMENT_ROOT.'/societe/class/client.class.php';
-
-$langs->load("companies");
-$langs->load("other");
-$langs->load("compta");
+// Load translation files required by the page
+$langs->loadLangs(array('companies', 'other', 'compta'));
$date_startmonth=GETPOST('date_startmonth');
$date_startday=GETPOST('date_startday');
diff --git a/htdocs/compta/localtax/card.php b/htdocs/compta/localtax/card.php
index f3dfbf05a05..e8a84fcc9e1 100644
--- a/htdocs/compta/localtax/card.php
+++ b/htdocs/compta/localtax/card.php
@@ -25,10 +25,10 @@
require '../../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/compta/localtax/class/localtax.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/vat.lib.php';
-$langs->load("compta");
-$langs->load("banks");
-$langs->load("bills");
+// Load translation files required by the page
+$langs->loadLangs(array('compta', 'banks', 'bills'));
$id=GETPOST("id",'int');
$action=GETPOST("action","alpha");
@@ -38,11 +38,11 @@ if (empty($refund)) $refund=0;
$lttype=GETPOST('localTaxType', 'int');
// Security check
-$socid = isset($_GET["socid"])?$_GET["socid"]:'';
+$socid = GETPOST('socid','int');
if ($user->societe_id) $socid=$user->societe_id;
$result = restrictedArea($user, 'tax', '', '', 'charges');
-$localtax = new Localtax($db);
+$object = new Localtax($db);
// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
$hookmanager->initHooks(array('localtaxvatcard','globalcard'));
@@ -52,9 +52,9 @@ $hookmanager->initHooks(array('localtaxvatcard','globalcard'));
* Actions
*/
-//add payment of localtax
-if($_POST["cancel"] == $langs->trans("Cancel")){
- header("Location: reglement.php?localTaxType=".$lttype);
+if ($_POST["cancel"] == $langs->trans("Cancel") && ! $id)
+{
+ header("Location: list.php?localTaxType=".$lttype);
exit;
}
@@ -66,25 +66,25 @@ if ($action == 'add' && $_POST["cancel"] <> $langs->trans("Cancel"))
$datev=dol_mktime(12,0,0, $_POST["datevmonth"], $_POST["datevday"], $_POST["datevyear"]);
$datep=dol_mktime(12,0,0, $_POST["datepmonth"], $_POST["datepday"], $_POST["datepyear"]);
- $localtax->accountid=GETPOST("accountid");
- $localtax->paymenttype=GETPOST("paiementtype");
- $localtax->datev=$datev;
- $localtax->datep=$datep;
- $localtax->amount=price2num(GETPOST("amount"));
- $localtax->label=GETPOST("label");
- $localtax->ltt=$lttype;
+ $object->accountid=GETPOST("accountid");
+ $object->paymenttype=GETPOST("paiementtype");
+ $object->datev=$datev;
+ $object->datep=$datep;
+ $object->amount=price2num(GETPOST("amount"));
+ $object->label=GETPOST("label");
+ $object->ltt=$lttype;
- $ret=$localtax->addPayment($user);
+ $ret=$object->addPayment($user);
if ($ret > 0)
{
$db->commit();
- header("Location: reglement.php?localTaxType=".$lttype);
+ header("Location: list.php?localTaxType=".$lttype);
exit;
}
else
{
$db->rollback();
- setEventMessages($localtax->error, $localtax->errors, 'errors');
+ setEventMessages($object->error, $object->errors, 'errors');
$_GET["action"]="create";
}
}
@@ -92,39 +92,39 @@ if ($action == 'add' && $_POST["cancel"] <> $langs->trans("Cancel"))
//delete payment of localtax
if ($action == 'delete')
{
- $result=$localtax->fetch($id);
+ $result=$object->fetch($id);
- if ($localtax->rappro == 0)
+ if ($object->rappro == 0)
{
$db->begin();
- $ret=$localtax->delete($user);
+ $ret=$object->delete($user);
if ($ret > 0)
{
- if ($localtax->fk_bank)
+ if ($object->fk_bank)
{
$accountline=new AccountLine($db);
- $result=$accountline->fetch($localtax->fk_bank);
+ $result=$accountline->fetch($object->fk_bank);
if ($result > 0) $result=$accountline->delete($user); // $result may be 0 if not found (when bank entry was deleted manually and fk_bank point to nothing)
}
if ($result >= 0)
{
$db->commit();
- header("Location: ".DOL_URL_ROOT.'/compta/localtax/reglement.php?localTaxType='.$localtax->ltt);
+ header("Location: ".DOL_URL_ROOT.'/compta/localtax/list.php?localTaxType='.$object->ltt);
exit;
}
else
{
- $localtax->error=$accountline->error;
+ $object->error=$accountline->error;
$db->rollback();
- setEventMessages($localtax->error, $localtax->errors, 'errors');
+ setEventMessages($object->error, $object->errors, 'errors');
}
}
else
{
$db->rollback();
- setEventMessages($localtax->error, $localtax->errors, 'errors');
+ setEventMessages($object->error, $object->errors, 'errors');
}
}
else
@@ -136,17 +136,12 @@ if ($action == 'delete')
/*
-* View
-*/
-
-llxHeader();
-
-$form = new Form($db);
+ * View
+ */
if ($id)
{
- $vatpayment = new Localtax($db);
- $result = $vatpayment->fetch($id);
+ $result = $object->fetch($id);
if ($result <= 0)
{
dol_print_error($db);
@@ -154,6 +149,13 @@ if ($id)
}
}
+$form = new Form($db);
+
+$title=$langs->trans("LT".$object->ltt) . " - " . $langs->trans("Card");
+$help_url='';
+llxHeader("",$title,$helpurl);
+
+
if ($action == 'create')
{
@@ -173,7 +175,7 @@ if ($action == 'create')
print $form->select_date($datep,"datep",'','','','add',1,1);
print '';
- print ''.$langs->trans("DateValue").' ';
+ print ' '.$form->textwithpicto($langs->trans("PeriodEndDate"), $langs->trans("LastDayTaxIsRelatedTo")).' ';
print $form->select_date($datev,"datev",'','','','add',1,1);
print ' ';
@@ -218,47 +220,48 @@ if ($action == 'create')
}
-/* ************************************************************************** */
-/* */
-/* Barre d'action */
-/* */
-/* ************************************************************************** */
-
+// View mode
if ($id)
{
$h = 0;
- $head[$h][0] = DOL_URL_ROOT.'/compta/localtax/card.php?id='.$vatpayment->id;
+ $head[$h][0] = DOL_URL_ROOT.'/compta/localtax/card.php?id='.$object->id;
$head[$h][1] = $langs->trans('Card');
$head[$h][2] = 'card';
$h++;
- dol_fiche_head($head, 'card', $langs->trans("VATPayment"), 0, 'payment');
+ dol_fiche_head($head, 'card', $langs->transcountry("LT".$object->ltt, $mysoc->country_code), -1, 'payment');
+ $linkback = ''.$langs->trans("BackToList").' ';
+
+ dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', $morehtmlref, '', 0, '', '');
+
+ print '';
+ print '
';
print '
';
print "";
- print ''.$langs->trans("Ref").' ';
- print $vatpayment->ref;
+ print ' '.$langs->trans("Ref").' ';
+ print $object->ref;
print ' ';
print "";
print ''.$langs->trans("DatePayment").' ';
- print dol_print_date($vatpayment->datep,'day');
+ print dol_print_date($object->datep,'day');
print ' ';
- print ''.$langs->trans("DateValue").' ';
- print dol_print_date($vatpayment->datev,'day');
+ print ' '.$form->textwithpicto($langs->trans("PeriodEndDate"), $langs->trans("LastDayTaxIsRelatedTo")).' ';
+ print dol_print_date($object->datev,'day');
print ' ';
- print ''.$langs->trans("Amount").' '.price($vatpayment->amount).' ';
+ print ''.$langs->trans("Amount").' '.price($object->amount).' ';
if (! empty($conf->banque->enabled))
{
- if ($vatpayment->fk_account > 0)
+ if ($object->fk_account > 0)
{
$bankline=new AccountLine($db);
- $bankline->fetch($vatpayment->fk_bank);
+ $bankline->fetch($object->fk_bank);
print '';
print ''.$langs->trans('BankTransactionLine').' ';
@@ -271,22 +274,28 @@ if ($id)
// Other attributes
$parameters=array();
- $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$vatpayment,$action); // Note that $action and $object may have been modified by hook
+ $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;
print '
';
- dol_fiche_end();
+ print '
';
+
+ dol_fiche_end();
/*
- * Boutons d'actions
- */
+ * Action buttons
+ */
print "";
}
diff --git a/htdocs/compta/localtax/class/localtax.class.php b/htdocs/compta/localtax/class/localtax.class.php
index 570942590c2..a75de537724 100644
--- a/htdocs/compta/localtax/class/localtax.class.php
+++ b/htdocs/compta/localtax/class/localtax.class.php
@@ -29,7 +29,11 @@ require_once DOL_DOCUMENT_ROOT .'/core/class/commonobject.class.php';
*/
class Localtax extends CommonObject
{
- var $ltt;
+ public $element='localtax'; //!< Id that identify managed objects
+ public $table_element='localtax'; //!< Name of table without prefix where object is stored
+ public $picto='payment';
+
+ var $ltt;
var $tms;
var $datep;
var $datev;
@@ -132,7 +136,7 @@ class Localtax extends CommonObject
* @param int $notrigger 0=no, 1=yes (no update trigger)
* @return int <0 if KO, >0 if OK
*/
- function update($user=null, $notrigger=0)
+ function update(User $user, $notrigger=0)
{
global $conf, $langs;
@@ -149,8 +153,8 @@ class Localtax extends CommonObject
$this->db->begin();
// Update request
- $sql = "UPDATE ".MAIN_DB_PREFIX."localtax SET";
- $sql.= " localtaxtype=".$this->ltt.",";
+ $sql = "UPDATE ".MAIN_DB_PREFIX."localtax SET";
+ $sql.= " localtaxtype=".$this->ltt.",";
$sql.= " tms='".$this->db->idate($this->tms)."',";
$sql.= " datep='".$this->db->idate($this->datep)."',";
$sql.= " datev='".$this->db->idate($this->datev)."',";
@@ -160,7 +164,7 @@ class Localtax extends CommonObject
$sql.= " fk_bank=".$this->fk_bank.",";
$sql.= " fk_user_creat=".$this->fk_user_creat.",";
$sql.= " fk_user_modif=".$this->fk_user_modif;
- $sql.= " WHERE rowid=".$this->id;
+ $sql.= " WHERE rowid=".$this->id;
dol_syslog(get_class($this)."::update", LOG_DEBUG);
$resql = $this->db->query($sql);
@@ -255,12 +259,12 @@ class Localtax extends CommonObject
}
- /**
- * Delete object in database
- *
- * @param User $user User that delete
- * @return int <0 if KO, >0 if OK
- */
+ /**
+ * Delete object in database
+ *
+ * @param User $user User that delete
+ * @return int <0 if KO, >0 if OK
+ */
function delete($user)
{
// Call trigger
@@ -285,11 +289,11 @@ class Localtax extends CommonObject
/**
- * Initialise an instance with random values.
- * Used to build previews or test instances.
- * id must be 0 if object instance is a specimen.
- *
- * @return void
+ * Initialise an instance with random values.
+ * Used to build previews or test instances.
+ * id must be 0 if object instance is a specimen.
+ *
+ * @return void
*/
function initAsSpecimen()
{
@@ -607,4 +611,29 @@ class Localtax extends CommonObject
return $result;
}
+ /**
+ * Retourne le libelle du statut d'une facture (brouillon, validee, abandonnee, payee)
+ *
+ * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
+ * @return string Libelle
+ */
+ function getLibStatut($mode=0)
+ {
+ return $this->LibStatut($this->statut,$mode);
+ }
+
+ /**
+ * Renvoi le libelle d'un statut donne
+ *
+ * @param int $status Statut
+ * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
+ * @return string Libelle du statut
+ */
+ function LibStatut($status,$mode=0)
+ {
+ global $langs; // TODO Renvoyer le libelle anglais et faire traduction a affichage
+
+ return '';
+ }
+
}
diff --git a/htdocs/compta/localtax/clients.php b/htdocs/compta/localtax/clients.php
index 70d52c3d9d3..9502ff46d2d 100644
--- a/htdocs/compta/localtax/clients.php
+++ b/htdocs/compta/localtax/clients.php
@@ -26,17 +26,16 @@ require '../../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/tax.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/localtax/class/localtax.class.php';
-$langs->load("bills");
-$langs->load("compta");
-$langs->load("companies");
-$langs->load("products");
+// Load translation files required by the page
+$langs->loadLangs(array("other","compta","banks","bills","companies","product","trips","admin"));
$local=GETPOST('localTaxType', 'int');
// Date range
-$year=GETPOST("year");
+$year=GETPOST("year","int");
if (empty($year))
{
$year_current = strftime("%Y",dol_now());
@@ -45,43 +44,48 @@ if (empty($year))
$year_current = $year;
$year_start = $year;
}
-$date_start=dol_mktime(0,0,0,$_REQUEST["date_startmonth"],$_REQUEST["date_startday"],$_REQUEST["date_startyear"]);
-$date_end=dol_mktime(23,59,59,$_REQUEST["date_endmonth"],$_REQUEST["date_endday"],$_REQUEST["date_endyear"]);
+$date_start=dol_mktime(0,0,0,GETPOST("date_startmonth"),GETPOST("date_startday"),GETPOST("date_startyear"));
+$date_end=dol_mktime(23,59,59,GETPOST("date_endmonth"),GETPOST("date_endday"),GETPOST("date_endyear"));
// Quarter
if (empty($date_start) || empty($date_end)) // We define date_start and date_end
{
$q=GETPOST("q");
if (empty($q))
{
- if (isset($_REQUEST["month"])) { $date_start=dol_get_first_day($year_start,$_REQUEST["month"],false); $date_end=dol_get_last_day($year_start,$_REQUEST["month"],false); }
+ if (GETPOST("month")) { $date_start=dol_get_first_day($year_start,GETPOST("month"),false); $date_end=dol_get_last_day($year_start,GETPOST("month"),false); }
else
{
- $month_current = strftime("%m",dol_now());
- if ($month_current >= 10) $q=4;
- elseif ($month_current >= 7) $q=3;
- elseif ($month_current >= 4) $q=2;
- else $q=1;
+ $date_start=dol_get_first_day($year_start,empty($conf->global->SOCIETE_FISCAL_MONTH_START)?1:$conf->global->SOCIETE_FISCAL_MONTH_START,false);
+ if (empty($conf->global->MAIN_INFO_VAT_RETURN) || $conf->global->MAIN_INFO_VAT_RETURN == 2) $date_end=dol_time_plus_duree($date_start, 3, 'm') - 1;
+ else if ($conf->global->MAIN_INFO_VAT_RETURN == 3) $date_end=dol_time_plus_duree($date_start, 1, 'y') - 1;
+ else if ($conf->global->MAIN_INFO_VAT_RETURN == 1) $date_end=dol_time_plus_duree($date_start, 1, 'm') - 1;
}
}
- if ($q==1) { $date_start=dol_get_first_day($year_start,1,false); $date_end=dol_get_last_day($year_start,3,false); }
- if ($q==2) { $date_start=dol_get_first_day($year_start,4,false); $date_end=dol_get_last_day($year_start,6,false); }
- if ($q==3) { $date_start=dol_get_first_day($year_start,7,false); $date_end=dol_get_last_day($year_start,9,false); }
- if ($q==4) { $date_start=dol_get_first_day($year_start,10,false); $date_end=dol_get_last_day($year_start,12,false); }
+ else
+ {
+ if ($q==1) { $date_start=dol_get_first_day($year_start,1,false); $date_end=dol_get_last_day($year_start,3,false); }
+ if ($q==2) { $date_start=dol_get_first_day($year_start,4,false); $date_end=dol_get_last_day($year_start,6,false); }
+ if ($q==3) { $date_start=dol_get_first_day($year_start,7,false); $date_end=dol_get_last_day($year_start,9,false); }
+ if ($q==4) { $date_start=dol_get_first_day($year_start,10,false); $date_end=dol_get_last_day($year_start,12,false); }
+ }
}
-$min = GETPOST("min");
+$min = price2num(GETPOST("min","alpha"));
if (empty($min)) $min = 0;
// Define modetax (0 or 1)
-// 0=normal, 1=option vat for services is on debit
+// 0=normal, 1=option vat for services is on debit, 2=option on payments for products
$modetax = $conf->global->TAX_MODE;
-if (isset($_REQUEST["modetax"])) $modetax=$_REQUEST["modetax"];
+if (GETPOSTISSET("modetax")) $modetax=GETPOST("modetax",'int');
+if (empty($modetax)) $modetax=0;
// Security check
$socid = GETPOST('socid','int');
if ($user->societe_id) $socid=$user->societe_id;
$result = restrictedArea($user, 'tax', '', '', 'charges');
+
+
/*
* View
*/
@@ -98,6 +102,9 @@ foreach($listofparams as $param)
llxHeader('','','','',0,0,'','',$morequerystring);
+
+$name=$langs->transcountry($local==1?"LT1ReportByCustomers":"LT2ReportByCustomers", $mysoc->country_code);
+
$fsearch.=' ';
$fsearch.=' ';
$fsearch.=' ';
@@ -108,7 +115,6 @@ $calc=$conf->global->MAIN_INFO_LOCALTAX_CALC.$local;
// Affiche en-tete du rapport
if ($calc==0 || $calc==1) // Calculate on invoice for goods and services
{
- $nom=$langs->transcountry($local==1?"LT1ReportByCustomersInInputOutputMode":"LT2ReportByCustomersInInputOutputMode",$mysoc->country_code);
$calcmode=$calc==0?$langs->trans("CalcModeLT".$local):$langs->trans("CalcModeLT".$local."Rec");
$calcmode.=' ('.$langs->trans("TaxModuleSetupToModifyRulesLT",DOL_URL_ROOT.'/admin/company.php').')';
$period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1);
@@ -126,7 +132,6 @@ if ($calc==0 || $calc==1) // Calculate on invoice for goods and services
}
if ($calc==2) // Invoice for goods, payment for services
{
- $nom=$langs->transcountry($local==1?"LT1ReportByCustomersInInputOutputMode":"LT2ReportByCustomersInInputOutputMode",$mysoc->country_code);
$calcmode=$langs->trans("CalcModeLT2Debt");
$calcmode.=' ('.$langs->trans("TaxModuleSetupToModifyRulesLT",DOL_URL_ROOT.'/admin/company.php').')';
$period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1);
@@ -160,7 +165,7 @@ if($calc ==0 || $calc == 2)
print "".$vatcust." ";
print "\n";
- $coll_list = vat_by_thirdparty($db,0,$date_start,$date_end,$modetax,'sell');
+ $coll_list = tax_by_thirdparty('localtax'.$local, $db, 0, $date_start, $date_end, $modetax, 'sell');
$action = "tvaclient";
$object = &$coll_list;
@@ -176,12 +181,11 @@ if($calc ==0 || $calc == 2)
if (is_array($coll_list))
{
- $var=true;
$total = 0; $totalamount = 0;
$i = 1;
foreach($coll_list as $coll)
{
- if(($min == 0 or ($min > 0 && $coll->amount > $min)) && ($local==1?$coll->localtax1:$coll->localtax2) !=0)
+ if(($min == 0 || ($min > 0 && $coll->amount > $min)) && ($local==1?$coll->localtax1:$coll->localtax2) !=0)
{
$intra = str_replace($find,$replace,$coll->tva_intra);
@@ -244,19 +248,18 @@ if($calc ==0 || $calc == 1){
$company_static=new Societe($db);
- $coll_list = vat_by_thirdparty($db,0,$date_start,$date_end,$modetax,'buy');
+ $coll_list = tax_by_thirdparty('localtax'.$local, $db, 0, $date_start, $date_end,$modetax, 'buy');
$parameters["direction"] = 'buy';
$parameters["type"] = 'localtax'.$local;
$reshook=$hookmanager->executeHooks('addVatLine',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks
if (is_array($coll_list))
{
- $var=true;
$total = 0; $totalamount = 0;
$i = 1;
foreach($coll_list as $coll)
{
- if(($min == 0 or ($min > 0 && $coll->amount > $min)) && ($local==1?$coll->localtax1:$coll->localtax2) != 0)
+ if(($min == 0 || ($min > 0 && $coll->amount > $min)) && ($local==1?$coll->localtax1:$coll->localtax2) != 0)
{
$intra = str_replace($find,$replace,$coll->tva_intra);
diff --git a/htdocs/compta/localtax/index.php b/htdocs/compta/localtax/index.php
index 6286bfaa4e4..c62034ee65c 100644
--- a/htdocs/compta/localtax/index.php
+++ b/htdocs/compta/localtax/index.php
@@ -1,6 +1,7 @@
* Copyright (C) 2014 Ferran Marcet
+ * Copyright (C) 2018 Laurent Destailleur
*
* 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
@@ -22,48 +23,71 @@
* \brief Index page of IRPF reports
*/
require '../../main.inc.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/tax.lib.php';
-require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php';
+require_once DOL_DOCUMENT_ROOT.'/compta/localtax/class/localtax.class.php';
-$langs->load("other");
-$langs->load("compta");
-$langs->load("banks");
-$langs->load("bills");
+// Load translation files required by the page
+$langs->loadLangs(array("other","compta","banks","bills","companies","product","trips","admin"));
$localTaxType=GETPOST('localTaxType', 'int');
+// Date range
$year=GETPOST("year","int");
-if ($year == 0)
+if (empty($year))
{
- $year_current = strftime("%Y",time());
- $year_start = $year_current;
+ $year_current = strftime("%Y",dol_now());
+ $year_start = $year_current;
} else {
- $year_current = $year;
- $year_start = $year;
+ $year_current = $year;
+ $year_start = $year;
+}
+$date_start=dol_mktime(0,0,0,GETPOST("date_startmonth"),GETPOST("date_startday"),GETPOST("date_startyear"));
+$date_end=dol_mktime(23,59,59,GETPOST("date_endmonth"),GETPOST("date_endday"),GETPOST("date_endyear"));
+if (empty($date_start) || empty($date_end)) // We define date_start and date_end
+{
+ $q=GETPOST("q","int");
+ if (empty($q))
+ {
+ if (GETPOST("month","int")) { $date_start=dol_get_first_day($year_start,GETPOST("month","int"),false); $date_end=dol_get_last_day($year_start,GETPOST("month","int"),false); }
+ else
+ {
+ $date_start=dol_get_first_day($year_start, $conf->global->SOCIETE_FISCAL_MONTH_START,false);
+ $date_end=dol_time_plus_duree($date_start, 1, 'y') - 1;
+ }
+ }
+ else
+ {
+ if ($q==1) { $date_start=dol_get_first_day($year_start,1,false); $date_end=dol_get_last_day($year_start,3,false); }
+ if ($q==2) { $date_start=dol_get_first_day($year_start,4,false); $date_end=dol_get_last_day($year_start,6,false); }
+ if ($q==3) { $date_start=dol_get_first_day($year_start,7,false); $date_end=dol_get_last_day($year_start,9,false); }
+ if ($q==4) { $date_start=dol_get_first_day($year_start,10,false); $date_end=dol_get_last_day($year_start,12,false); }
+ }
}
+// Define modetax (0 or 1)
+// 0=normal, 1=option vat for services is on debit, 2=option on payments for products
+$modetax = $conf->global->TAX_MODE;
+if (GETPOSTISSET("modetax")) $modetax=GETPOST("modetax",'int');
+if (empty($modetax)) $modetax=0;
+
// Security check
-$socid = isset($_GET["socid"])?$_GET["socid"]:'';
-if ($user->societe_id)
- $socid=$user->societe_id;
+$socid = GETPOST('socid','int');
+if ($user->societe_id) $socid=$user->societe_id;
$result = restrictedArea($user, 'tax', '', '', 'charges');
-// Define modetax (0 or 1)
-// 0=normal, 1=option vat for services is on debit
-$modetax = $conf->global->TAX_MODE;
-if (isset($_GET["modetax"]))
- $modetax=$_GET["modetax"];
/**
* print function
*
- * @param DoliDB $db Database
- * @param string $sql sql
- * @param string $date date
- * @return void
+ * @param DoliDB $db Database handler
+ * @param string $sql SQL Request
+ * @param string $date Date
+ * @return void
*/
-function pt ($db, $sql, $date)
+function pt($db, $sql, $date)
{
global $conf, $bc,$langs;
@@ -73,29 +97,92 @@ function pt ($db, $sql, $date)
$i = 0;
$total = 0;
print '';
+
print '';
- print ''.$date.' ';
- print ''.$langs->trans("Amount").' ';
- print ' '."\n";
+ print ''.$date.' ';
+ print ''.$langs->trans("ClaimedForThisPeriod").' ';
+ print ''.$langs->trans("PaidDuringThisPeriod").' ';
print " \n";
- $var=True;
+
+ $totalclaimed = 0;
+ $totalpaid = 0;
+ $amountclaimed = 0;
+ $amountpaid = 0;
+ $previousmonth = '';
+ $previousmode = '';
+ $mode = '';
+
while ($i < $num) {
$obj = $db->fetch_object($result);
+ $mode = $obj->mode;
- print '';
- print ''.$obj->dm." \n";
- $total = $total + $obj->mm;
+ //print $obj->dm.' '.$obj->mode.' '.$previousmonth.' '.$previousmode;
+ if ($obj->mode == 'claimed' && ! empty($previousmode))
+ {
+ print ' ';
+ print ''.$obj->dm." \n";
+ print ''.price($amountclaimed)." \n";
+ print ''.price($amountpaid)." \n";
+ print " \n";
- print ''.price($obj->mm)." \n";
- print "\n";
+ $amountclaimed = 0;
+ $amountpaid = 0;
+ }
+
+ if ($obj->mode == 'claimed')
+ {
+ $amountclaimed = $obj->mm;
+ $totalclaimed = $totalclaimed + $amountclaimed;
+ }
+ if ($obj->mode == 'paid')
+ {
+ $amountpaid = $obj->mm;
+ $totalpaid = $totalpaid + $amountpaid;
+ }
+
+ if ($obj->mode == 'paid')
+ {
+ print '';
+ print ''.$obj->dm." \n";
+ print ''.price($amountclaimed)." \n";
+ print ''.price($amountpaid)." \n";
+ print " \n";
+ $amountclaimed = 0;
+ $amountpaid = 0;
+ $previousmode = '';
+ $previousmonth = '';
+ }
+ else
+ {
+ $previousmode = $obj->mode;
+ $previousmonth = $obj->dm;
+ }
$i++;
}
- print ''.$langs->trans("Total")." : ".price($total)." ";
+
+ if ($mode == 'claimed' && ! empty($previousmode))
+ {
+ print '';
+ print ''.$previousmonth." \n";
+ print ''.price($amountclaimed)." \n";
+ print ''.price($amountpaid)." \n";
+ print " \n";
+
+ $amountclaimed = 0;
+ $amountpaid = 0;
+ }
+
+ print '';
+ print ''.$langs->trans("Total").' ';
+ print ''.price($totalclaimed).' ';
+ print ''.price($totalpaid).' ';
+ print " ";
print "
";
$db->free($result);
- } else {
+ }
+ else {
dol_print_error($db);
}
}
@@ -105,7 +192,9 @@ function pt ($db, $sql, $date)
* View
*/
-llxHeader();
+$form=new Form($db);
+$company_static=new Societe($db);
+$tva = new Tva($db);
if($localTaxType==1) {
$LT='LT1';
@@ -123,24 +212,37 @@ if($localTaxType==1) {
$CalcLT= $conf->global->MAIN_INFO_LOCALTAX_CALC2;
}
+$fsearch.=' ';
+$description = $fsearch;
-$textprevyear="".img_previous()." ";
-$textnextyear=" ".img_next()." ";
+// Show report header
+$name = $langs->trans("ReportByMonth");
+$description .= $langs->trans($LT);
+$calcmode = $langs->trans("LTReportBuildWithOptionDefinedInModule").' ';
+$calcmode.= '('.$langs->trans("TaxModuleSetupToModifyRulesLT",DOL_URL_ROOT.'/admin/company.php').') ';
+
+//if (! empty($conf->global->MAIN_MODULE_ACCOUNTING)) $description.=' '.$langs->trans("ThisIsAnEstimatedValue");
+
+$period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1);
+
+$builddate=dol_now();
+
+
+llxHeader('', $name);
+
+//$textprevyear="".img_previous()." ";
+//$textnextyear=" ".img_next()." ";
+//print load_fiche_titre($langs->transcountry($LT,$mysoc->country_code),"$textprevyear ".$langs->trans("Year")." $year_start $textnextyear", 'title_accountancy.png');
+
+report_header($name,'',$period,$periodlink,$description,$builddate,$exportlink,array(),$calcmode);
+//report_header($name,'',$textprevyear.$langs->trans("Year")." ".$year_start.$textnextyear,'',$description,$builddate,$exportlink,array(),$calcmode);
-print load_fiche_titre($langs->transcountry($LT,$mysoc->country_code),"$textprevyear ".$langs->trans("Year")." $year_start $textnextyear", 'title_accountancy.png');
-print $langs->trans("LTReportBuildWithOptionDefinedInModule").' ';
-print '('.$langs->trans("TaxModuleSetupToModifyRulesLT",DOL_URL_ROOT.'/admin/company.php').') ';
print ' ';
-print '';
-print '';
-print load_fiche_titre($langs->transcountry($LTSummary,$mysoc->country_code), '', '');
-print ' ';
-print load_fiche_titre($langs->transcountry($LTPaid,$mysoc->country_code), '', '');
-print ' ';
+print '';
-print '
';
+print load_fiche_titre($langs->transcountry($LTSummary,$mysoc->country_code), '', '');
print '';
print '';
@@ -155,22 +257,156 @@ if($CalcLT==1) {
if($CalcLT==2) {
print "".$langs->transcountry($LTCustomer,$mysoc->country_code)." ";
}
-
print "".$langs->trans("TotalToPay")." ";
print " \n";
print " \n";
-$y = $year_current ;
+$tmp=dol_getdate($date_start);
+$y = $tmp['year'];
+$m = $tmp['mon'];
+$tmp=dol_getdate($date_end);
+$yend = $tmp['year'];
+$mend = $tmp['mon'];
-$var=True;
$total=0; $subtotalcoll=0; $subtotalpaye=0; $subtotal=0;
-$i=0;
-for ($m = 1 ; $m < 13 ; $m++ ) {
- $coll_listsell = tax_by_date('vat', $db, $y, 0, 0, 0, $modetax, 'sell', $m);
- $coll_listbuy = tax_by_date('vat', $db, $y, 0, 0, 0, $modetax, 'buy', $m);
+$i=0; $mcursor=0;
+while ((($y < $yend) || ($y == $yend && $m < $mend)) && $mcursor < 1000) // $mcursor is to avoid too large loop
+{
+ //$m = $conf->global->SOCIETE_FISCAL_MONTH_START + ($mcursor % 12);
+ if ($m == 13) $y++;
+ if ($m > 12) $m -= 12;
+ $mcursor++;
+
+ // Get array with details of each line
+ $x_coll = tax_by_rate(($localTaxType==1?'localtax1':'localtax2'), $db, $y, 0, 0, 0, $modetax, 'sell', $m);
+ $x_paye = tax_by_rate(($localTaxType==1?'localtax1':'localtax2'), $db, $y, 0, 0, 0, $modetax, 'buy', $m);
+
+ $x_both = array();
+ //now, from these two arrays, get another array with one rate per line
+ foreach(array_keys($x_coll) as $my_coll_rate)
+ {
+ $x_both[$my_coll_rate]['coll']['totalht'] = $x_coll[$my_coll_rate]['totalht'];
+ $x_both[$my_coll_rate]['coll']['vat'] = $x_coll[$my_coll_rate]['vat'];
+ $x_both[$my_coll_rate]['coll']['localtax1'] = $x_coll[$my_coll_rate]['localtax1'];
+ $x_both[$my_coll_rate]['coll']['localtax2'] = $x_coll[$my_coll_rate]['localtax2'];
+ $x_both[$my_coll_rate]['paye']['totalht'] = 0;
+ $x_both[$my_coll_rate]['paye']['vat'] = 0;
+ $x_both[$my_coll_rate]['paye']['localtax1'] = 0;
+ $x_both[$my_coll_rate]['paye']['localtax2'] = 0;
+ $x_both[$my_coll_rate]['coll']['links'] = '';
+ $x_both[$my_coll_rate]['coll']['detail'] = array();
+ foreach($x_coll[$my_coll_rate]['facid'] as $id=>$dummy) {
+ //$invoice_customer->id=$x_coll[$my_coll_rate]['facid'][$id];
+ //$invoice_customer->ref=$x_coll[$my_coll_rate]['facnum'][$id];
+ //$invoice_customer->type=$x_coll[$my_coll_rate]['type'][$id];
+ //$company_static->fetch($x_coll[$my_coll_rate]['company_id'][$id]);
+ $x_both[$my_coll_rate]['coll']['detail'][] = array(
+ 'id' =>$x_coll[$my_coll_rate]['facid'][$id],
+ 'descr' =>$x_coll[$my_coll_rate]['descr'][$id],
+ 'pid' =>$x_coll[$my_coll_rate]['pid'][$id],
+ 'pref' =>$x_coll[$my_coll_rate]['pref'][$id],
+ 'ptype' =>$x_coll[$my_coll_rate]['ptype'][$id],
+ 'payment_id'=>$x_coll[$my_coll_rate]['payment_id'][$id],
+ 'payment_amount'=>$x_coll[$my_coll_rate]['payment_amount'][$id],
+ 'ftotal_ttc'=>$x_coll[$my_coll_rate]['ftotal_ttc'][$id],
+ 'dtotal_ttc'=>$x_coll[$my_coll_rate]['dtotal_ttc'][$id],
+ 'dtype' =>$x_coll[$my_coll_rate]['dtype'][$id],
+ 'datef' =>$x_coll[$my_coll_rate]['datef'][$id],
+ 'datep' =>$x_coll[$my_coll_rate]['datep'][$id],
+ //'company_link'=>$company_static->getNomUrl(1,'',20),
+ 'ddate_start'=>$x_coll[$my_coll_rate]['ddate_start'][$id],
+ 'ddate_end' =>$x_coll[$my_coll_rate]['ddate_end'][$id],
+
+ 'totalht' =>$x_coll[$my_coll_rate]['totalht_list'][$id],
+ 'vat' =>$x_coll[$my_coll_rate]['vat_list'][$id],
+ 'localtax1' =>$x_coll[$my_coll_rate]['localtax1_list'][$id],
+ 'localtax2' =>$x_coll[$my_coll_rate]['localtax2_list'][$id],
+ //'link' =>$invoice_customer->getNomUrl(1,'',12)
+ );
+ }
+ }
+
+ // tva paid
+ foreach (array_keys($x_paye) as $my_paye_rate) {
+ $x_both[$my_paye_rate]['paye']['totalht'] = $x_paye[$my_paye_rate]['totalht'];
+ $x_both[$my_paye_rate]['paye']['vat'] = $x_paye[$my_paye_rate]['vat'];
+ $x_both[$my_paye_rate]['paye']['localtax1'] = $x_paye[$my_paye_rate]['localtax1'];
+ $x_both[$my_paye_rate]['paye']['localtax2'] = $x_paye[$my_paye_rate]['localtax2'];
+ if (!isset($x_both[$my_paye_rate]['coll']['totalht'])) {
+ $x_both[$my_paye_rate]['coll']['totalht'] = 0;
+ $x_both[$my_paye_rate]['coll']['vat'] = 0;
+ $x_both[$my_paye_rate]['coll']['localtax1'] = 0;
+ $x_both[$my_paye_rate]['coll']['localtax2'] = 0;
+ }
+ $x_both[$my_paye_rate]['paye']['links'] = '';
+ $x_both[$my_paye_rate]['paye']['detail'] = array();
+
+ foreach ($x_paye[$my_paye_rate]['facid'] as $id=>$dummy)
+ {
+ // ExpenseReport
+ if ($x_paye[$my_paye_rate]['ptype'][$id] == 'ExpenseReportPayment')
+ {
+ //$expensereport->id=$x_paye[$my_paye_rate]['facid'][$id];
+ //$expensereport->ref=$x_paye[$my_paye_rate]['facnum'][$id];
+ //$expensereport->type=$x_paye[$my_paye_rate]['type'][$id];
+
+ $x_both[$my_paye_rate]['paye']['detail'][] = array(
+ 'id' =>$x_paye[$my_paye_rate]['facid'][$id],
+ 'descr' =>$x_paye[$my_paye_rate]['descr'][$id],
+ 'pid' =>$x_paye[$my_paye_rate]['pid'][$id],
+ 'pref' =>$x_paye[$my_paye_rate]['pref'][$id],
+ 'ptype' =>$x_paye[$my_paye_rate]['ptype'][$id],
+ 'payment_id' =>$x_paye[$my_paye_rate]['payment_id'][$id],
+ 'payment_amount' =>$x_paye[$my_paye_rate]['payment_amount'][$id],
+ 'ftotal_ttc' =>price2num($x_paye[$my_paye_rate]['ftotal_ttc'][$id]),
+ 'dtotal_ttc' =>price2num($x_paye[$my_paye_rate]['dtotal_ttc'][$id]),
+ 'dtype' =>$x_paye[$my_paye_rate]['dtype'][$id],
+ 'ddate_start' =>$x_paye[$my_paye_rate]['ddate_start'][$id],
+ 'ddate_end' =>$x_paye[$my_paye_rate]['ddate_end'][$id],
+
+ 'totalht' =>price2num($x_paye[$my_paye_rate]['totalht_list'][$id]),
+ 'vat' =>$x_paye[$my_paye_rate]['vat_list'][$id],
+ 'localtax1' =>$x_paye[$my_paye_rate]['localtax1_list'][$id],
+ 'localtax2' =>$x_paye[$my_paye_rate]['localtax2_list'][$id],
+ //'link' =>$expensereport->getNomUrl(1)
+ );
+ }
+ else
+ {
+ //$invoice_supplier->id=$x_paye[$my_paye_rate]['facid'][$id];
+ //$invoice_supplier->ref=$x_paye[$my_paye_rate]['facnum'][$id];
+ //$invoice_supplier->type=$x_paye[$my_paye_rate]['type'][$id];
+ //$company_static->fetch($x_paye[$my_paye_rate]['company_id'][$id]);
+ $x_both[$my_paye_rate]['paye']['detail'][] = array(
+ 'id' =>$x_paye[$my_paye_rate]['facid'][$id],
+ 'descr' =>$x_paye[$my_paye_rate]['descr'][$id],
+ 'pid' =>$x_paye[$my_paye_rate]['pid'][$id],
+ 'pref' =>$x_paye[$my_paye_rate]['pref'][$id],
+ 'ptype' =>$x_paye[$my_paye_rate]['ptype'][$id],
+ 'payment_id'=>$x_paye[$my_paye_rate]['payment_id'][$id],
+ 'payment_amount'=>$x_paye[$my_paye_rate]['payment_amount'][$id],
+ 'ftotal_ttc'=>price2num($x_paye[$my_paye_rate]['ftotal_ttc'][$id]),
+ 'dtotal_ttc'=>price2num($x_paye[$my_paye_rate]['dtotal_ttc'][$id]),
+ 'dtype' =>$x_paye[$my_paye_rate]['dtype'][$id],
+ 'datef' =>$x_paye[$my_paye_rate]['datef'][$id],
+ 'datep' =>$x_paye[$my_paye_rate]['datep'][$id],
+ //'company_link'=>$company_static->getNomUrl(1,'',20),
+ 'ddate_start'=>$x_paye[$my_paye_rate]['ddate_start'][$id],
+ 'ddate_end' =>$x_paye[$my_paye_rate]['ddate_end'][$id],
+
+ 'totalht' =>price2num($x_paye[$my_paye_rate]['totalht_list'][$id]),
+ 'vat' =>$x_paye[$my_paye_rate]['vat_list'][$id],
+ 'localtax1' =>$x_paye[$my_paye_rate]['localtax1_list'][$id],
+ 'localtax2' =>$x_paye[$my_paye_rate]['localtax2_list'][$id],
+ //'link' =>$invoice_supplier->getNomUrl(1,'',12)
+ );
+ }
+ }
+ }
+ //now we have an array (x_both) indexed by rates for coll and paye
$action = "tva";
- $object = array(&$coll_listsell, &$coll_listbuy);
+ $object = array(&$x_coll, &$x_paye, &$x_both);
$parameters["mode"] = $modetax;
$parameters["year"] = $y;
$parameters["month"] = $m;
@@ -180,112 +416,176 @@ for ($m = 1 ; $m < 13 ; $m++ ) {
$hookmanager->initHooks(array('externalbalance'));
$reshook=$hookmanager->executeHooks('addVatLine',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks
- if (! is_array($coll_listbuy) && $coll_listbuy == -1) {
+ if (! is_array($x_coll) && $coll_listbuy == -1)
+ {
$langs->load("errors");
print ''.$langs->trans("ErrorNoAccountancyModuleLoaded").' ';
break;
}
- if (! is_array($coll_listbuy) && $coll_listbuy == -2) {
+ if (! is_array($x_paye) && $coll_listbuy == -2)
+ {
print ''.$langs->trans("FeatureNotYetAvailable").' ';
break;
}
print '';
- print ''.dol_print_date(dol_mktime(0,0,0,$m,1,$y),"%b %Y").' ';
- if($CalcLT==0) {
- $x_coll = 0;
- foreach($coll_listsell as $vatrate=>$val) {
- $x_coll+=$val[$localTaxType==1?'localtax1':'localtax2'];
- }
- $subtotalcoll = $subtotalcoll + $x_coll;
- print "".price($x_coll)." ";
+ print ''.dol_print_date(dol_mktime(0,0,0,$m,1,$y),"%b %Y").' ';
- $x_paye = 0;
- foreach($coll_listbuy as $vatrate=>$val) {
- $x_paye+=$val[$localTaxType==1?'localtax1':'localtax2'];
- }
- $subtotalpaye = $subtotalpaye + $x_paye;
- print "".price($x_paye)." ";
- } elseif($CalcLT==1) {
- $x_paye = 0;
- foreach($coll_listbuy as $vatrate=>$val) {
- $x_paye+=$val[$localTaxType==1?'localtax1':'localtax2'];
+ $x_coll_sum = 0;
+ foreach (array_keys($x_coll) as $rate)
+ {
+ $subtot_coll_total_ht = 0;
+ $subtot_coll_vat = 0;
+
+ foreach ($x_both[$rate]['coll']['detail'] as $index => $fields)
+ {
+ // Payment
+ $ratiopaymentinvoice=1;
+ if ($modetax != 1)
+ {
+ // Define type
+ // We MUST use dtype (type in line). We can use something else, only if dtype is really unknown.
+ $type=(isset($fields['dtype'])?$fields['dtype']:$fields['ptype']);
+ // Try to enhance type detection using date_start and date_end for free lines where type
+ // was not saved.
+ if (!empty($fields['ddate_start'])) {
+ $type=1;
+ }
+ if (!empty($fields['ddate_end'])) {
+ $type=1;
+ }
+
+ if (($type == 0 && $conf->global->TAX_MODE_SELL_PRODUCT == 'invoice')
+ || ($type == 1 && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice'))
+ {
+ //print $langs->trans("NA");
+ } else {
+ if (isset($fields['payment_amount']) && price2num($fields['ftotal_ttc'])) {
+ $ratiopaymentinvoice=($fields['payment_amount']/$fields['ftotal_ttc']);
+ }
+ }
+ }
+ //var_dump('type='.$type.' '.$fields['totalht'].' '.$ratiopaymentinvoice);
+ $temp_ht=$fields['totalht']*$ratiopaymentinvoice;
+ $temp_vat=$fields['localtax'.$localTaxType]*$ratiopaymentinvoice;
+ $subtot_coll_total_ht += $temp_ht;
+ $subtot_coll_vat += $temp_vat;
+ $x_coll_sum += $temp_vat;
}
- $subtotalpaye = $subtotalpaye + $x_paye;
- print "".price($x_paye)." ";
- } elseif($CalcLT==2) {
- $x_coll = 0;
- foreach($coll_listsell as $vatrate=>$val) {
- $x_coll+=$val[$localTaxType==1?'localtax1':'localtax2'];
+ }
+ print "".price(price2num($x_coll_sum,'MT'))." ";
+
+ $x_paye_sum = 0;
+ foreach (array_keys($x_paye) as $rate)
+ {
+ $subtot_paye_total_ht = 0;
+ $subtot_paye_vat = 0;
+
+ foreach ($x_both[$rate]['paye']['detail'] as $index => $fields)
+ {
+ // Payment
+ $ratiopaymentinvoice=1;
+ if ($modetax != 1)
+ {
+ // Define type
+ // We MUST use dtype (type in line). We can use something else, only if dtype is really unknown.
+ $type=(isset($fields['dtype'])?$fields['dtype']:$fields['ptype']);
+ // Try to enhance type detection using date_start and date_end for free lines where type
+ // was not saved.
+ if (!empty($fields['ddate_start'])) {
+ $type=1;
+ }
+ if (!empty($fields['ddate_end'])) {
+ $type=1;
+ }
+
+ if (($type == 0 && $conf->global->TAX_MODE_SELL_PRODUCT == 'invoice')
+ || ($type == 1 && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice'))
+ {
+ //print $langs->trans("NA");
+ } else {
+ if (isset($fields['payment_amount']) && price2num($fields['ftotal_ttc'])) {
+ $ratiopaymentinvoice=($fields['payment_amount']/$fields['ftotal_ttc']);
+ }
+ }
+ }
+ //var_dump('type='.$type.' '.$fields['totalht'].' '.$ratiopaymentinvoice);
+ $temp_ht=$fields['totalht']*$ratiopaymentinvoice;
+ $temp_vat=$fields['localtax'.$localTaxType]*$ratiopaymentinvoice;
+ $subtot_paye_total_ht += $temp_ht;
+ $subtot_paye_vat += $temp_vat;
+ $x_paye_sum += $temp_vat;
}
- $subtotalcoll = $subtotalcoll + $x_coll;
- print "".price($x_coll)." ";
-
}
+ print "".price(price2num($x_paye_sum,'MT'))." ";
- if($CalcLT==0) {
- $diff= $x_coll - $x_paye;
- } elseif($CalcLT==1) {
- $diff= $x_paye;
- } elseif($CalcLT==2) {
- $diff= $x_coll;
- }
+ $subtotalcoll = $subtotalcoll + $x_coll_sum;
+ $subtotalpaye = $subtotalpaye + $x_paye_sum;
+ $diff = $x_coll_sum - $x_paye_sum;
$total = $total + $diff;
- $subtotal = $subtotal + $diff;
+ $subtotal = price2num($subtotal + $diff, 'MT');
- print "".price($diff)." \n";
+ print "".price(price2num($diff,'MT'))." \n";
print " \n";
print " \n";
- $i++;
- if ($i > 2) {
- print '';
- print ''.$langs->trans("SubTotal").': ';
- if($CalcLT==0) {
- print ''.price($subtotalcoll).' ';
- print ''.price($subtotalpaye).' ';
- print ''.price($subtotal).' ';
- } elseif($CalcLT==1) {
- print ''.price($subtotalpaye).' ';
- print ''.price($subtotal).' ';
- } elseif($CalcLT==2) {
- print ''.price($subtotalcoll).' ';
- print ''.price($subtotal).' ';
- }
- print ' ';
- $i = 0;
- $subtotalcoll=0; $subtotalpaye=0; $subtotal=0;
+ $i++; $m++;
+ if ($i > 2)
+ {
+ print '';
+ print ''.$langs->trans("SubTotal").' : ';
+ print ''.price(price2num($subtotalcoll,'MT')).' ';
+ print ''.price(price2num($subtotalpaye,'MT')).' ';
+ print ''.price(price2num($subtotal,'MT')).' ';
+ print ' ';
+ $i = 0;
+ $subtotalcoll=0; $subtotalpaye=0; $subtotal=0;
}
}
-print ''.$langs->trans("TotalToPay").': '.price($total).' ';
+print ''.$langs->trans("TotalToPay").': '.price(price2num($total, 'MT')).' ';
print " \n";
print ' ';
print '
';
-print ' ';
+
+print '';
+
+
/*
* Payed
*/
-$sql = "SELECT SUM(amount) as mm, date_format(f.datev,'%Y-%m') as dm";
+print load_fiche_titre($langs->transcountry($LTPaid,$mysoc->country_code), '', '');
+
+$sql='';
+
+$sql.= "SELECT SUM(amount) as mm, date_format(f.datev,'%Y-%m') as dm, 'claimed' as mode";
$sql.= " FROM ".MAIN_DB_PREFIX."localtax as f";
$sql.= " WHERE f.entity = ".$conf->entity;
-$sql.= " AND f.datev >= '".$db->idate(dol_get_first_day($y,1,false))."'";
-$sql.= " AND f.datev <= '".$db->idate(dol_get_last_day($y,12,false))."'";
+$sql.= " AND (f.datev >= '".$db->idate($date_start)."' AND f.datev <= '".$db->idate($date_end)."')";
$sql.= " AND localtaxtype=".$localTaxType;
$sql.= " GROUP BY dm";
-$sql.= " ORDER BY dm ASC";
-pt($db, $sql,$langs->trans("Year")." $y");
+$sql.= " UNION ";
-print '
';
+$sql.= "SELECT SUM(amount) as mm, date_format(f.datep,'%Y-%m') as dm, 'paid' as mode";
+$sql.= " FROM ".MAIN_DB_PREFIX."localtax as f";
+$sql.= " WHERE f.entity = ".$conf->entity;
+$sql.= " AND (f.datep >= '".$db->idate($date_start)."' AND f.datep <= '".$db->idate($date_end)."')";
+$sql.= " AND localtaxtype=".$localTaxType;
+$sql.= " GROUP BY dm";
-print '';
-print '
';
+$sql.= " ORDER BY dm ASC, mode ASC";
+//print $sql;
+
+pt($db, $sql, $langs->trans("Month"));
+
+
+print '';
llxFooter();
$db->close();
diff --git a/htdocs/compta/localtax/reglement.php b/htdocs/compta/localtax/list.php
similarity index 72%
rename from htdocs/compta/localtax/reglement.php
rename to htdocs/compta/localtax/list.php
index 54183ef72b9..0e32a249f17 100644
--- a/htdocs/compta/localtax/reglement.php
+++ b/htdocs/compta/localtax/list.php
@@ -16,7 +16,7 @@
*/
/**
- * \file htdocs/compta/localtax/reglement.php
+ * \file htdocs/compta/localtax/list.php
* \ingroup tax
* \brief List of IRPF payments
*/
@@ -24,15 +24,16 @@
require '../../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/compta/localtax/class/localtax.class.php';
-$langs->load("compta");
+// Load translation files required by the page
$langs->load("compta");
// Security check
-$socid = isset($_GET["socid"])?$_GET["socid"]:'';
+$socid = GETPOST('socid','int');
if ($user->societe_id) $socid=$user->societe_id;
$result = restrictedArea($user, 'tax', '', '', 'charges');
$ltt=GETPOST("localTaxType");
+
/*
* View
*/
@@ -41,12 +42,20 @@ llxHeader();
$localtax_static = new Localtax($db);
-print load_fiche_titre($langs->transcountry($ltt==2?"LT2Payments":"LT1Payments",$mysoc->country_code));
+$newcardbutton='';
+if ($user->rights->tax->charges->creer)
+{
+ $newcardbutton=''.$langs->trans('NewLocalTaxPayment', ($ltt+1)).' ';
+ $newcardbutton.= ' ';
+ $newcardbutton.= ' ';
+}
-$sql = "SELECT rowid, amount, label, f.datev as dm";
+print load_fiche_titre($langs->transcountry($ltt==2?"LT2Payments":"LT1Payments",$mysoc->country_code), $newcardbutton);
+
+$sql = "SELECT rowid, amount, label, f.datev, f.datep";
$sql.= " FROM ".MAIN_DB_PREFIX."localtax as f ";
$sql.= " WHERE f.entity = ".$conf->entity." AND localtaxtype=".$db->escape($ltt);
-$sql.= " ORDER BY dm DESC";
+$sql.= " ORDER BY datev DESC";
$result = $db->query($sql);
if ($result)
@@ -59,6 +68,7 @@ if ($result)
print '';
print ''.$langs->trans("Ref").' ';
print "".$langs->trans("Label")." ";
+ print "".$langs->trans("PeriodEndDate")." ";
print ''.$langs->trans("DatePayment").' ';
print "".$langs->trans("PayedByThisPayment")." ";
print " \n";
@@ -66,14 +76,15 @@ if ($result)
while ($i < $num)
{
$obj = $db->fetch_object($result);
-
+
print '
';
$localtax_static->id=$obj->rowid;
$localtax_static->ref=$obj->rowid;
print "".$localtax_static->getNomUrl(1)." \n";
print "".dol_trunc($obj->label,40)." \n";
- print ''.dol_print_date($db->jdate($obj->dm),'day')." \n";
+ print ''.dol_print_date($db->jdate($obj->datev),'day')." \n";
+ print ''.dol_print_date($db->jdate($obj->datep),'day')." \n";
$total = $total + $obj->amount;
print "".price($obj->amount)." ";
@@ -81,8 +92,8 @@ if ($result)
$i++;
}
- print ' '.$langs->trans("Total").' ';
- print "".price($total)." ";
+ print '
'.$langs->trans("Total").' ';
+ print ''.price($total).' ';
print "
";
$db->free($result);
diff --git a/htdocs/compta/localtax/quadri_detail.php b/htdocs/compta/localtax/quadri_detail.php
index 5e18c786c18..31729693f37 100644
--- a/htdocs/compta/localtax/quadri_detail.php
+++ b/htdocs/compta/localtax/quadri_detail.php
@@ -22,8 +22,7 @@
/**
* \file htdocs/compta/tva/quadri_detail.php
* \ingroup tax
- * \brief Trimestrial page - detailed version
- * TODO Deal with recurrent invoices as well
+ * \brief Local tax by rate
*/
global $mysoc;
@@ -31,21 +30,22 @@ require '../../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/tax.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/localtax/class/localtax.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php';
+require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
+require_once DOL_DOCUMENT_ROOT.'/expensereport/class/paymentexpensereport.class.php';
-$langs->load("bills");
-$langs->load("compta");
-$langs->load("companies");
-$langs->load("products");
+// Load translation files required by the page
+$langs->loadLangs(array("other","compta","banks","bills","companies","product","trips","admin"));
$local=GETPOST('localTaxType', 'int');
// Date range
-$year=GETPOST("year");
+$year=GETPOST("year","int");
if (empty($year))
{
$year_current = strftime("%Y",dol_now());
@@ -54,38 +54,41 @@ if (empty($year))
$year_current = $year;
$year_start = $year;
}
-
-$date_start = dol_mktime( 0, 0, 0, GETPOST( "date_startmonth" ), GETPOST( "date_startday" ), GETPOST( "date_startyear" ) );
-$date_end = dol_mktime( 23, 59, 59, GETPOST( "date_endmonth" ), GETPOST( "date_endday" ), GETPOST( "date_endyear" ) );
+$date_start=dol_mktime(0,0,0,GETPOST("date_startmonth"),GETPOST("date_startday"),GETPOST("date_startyear"));
+$date_end=dol_mktime(23,59,59,GETPOST("date_endmonth"),GETPOST("date_endday"),GETPOST("date_endyear"));
// Quarter
if (empty($date_start) || empty($date_end)) // We define date_start and date_end
{
- $q=GETPOST("q");
+ $q=GETPOST("q","int");
if (empty($q))
{
- if (isset($_REQUEST["month"])) { $date_start=dol_get_first_day($year_start,$_REQUEST["month"],false); $date_end=dol_get_last_day($year_start,$_REQUEST["month"],false); }
+ if (GETPOST("month","int")) { $date_start=dol_get_first_day($year_start,GETPOST("month","int"),false); $date_end=dol_get_last_day($year_start,GETPOST("month","int"),false); }
else
{
- $month_current = strftime("%m",dol_now());
- if ($month_current >= 10) $q=4;
- elseif ($month_current >= 7) $q=3;
- elseif ($month_current >= 4) $q=2;
- else $q=1;
+ $date_start=dol_get_first_day($year_start,empty($conf->global->SOCIETE_FISCAL_MONTH_START)?1:$conf->global->SOCIETE_FISCAL_MONTH_START,false);
+ if (empty($conf->global->MAIN_INFO_VAT_RETURN) || $conf->global->MAIN_INFO_VAT_RETURN == 2) $date_end=dol_time_plus_duree($date_start, 3, 'm') - 1;
+ else if ($conf->global->MAIN_INFO_VAT_RETURN == 3) $date_end=dol_time_plus_duree($date_start, 1, 'y') - 1;
+ else if ($conf->global->MAIN_INFO_VAT_RETURN == 1) $date_end=dol_time_plus_duree($date_start, 1, 'm') - 1;
}
}
- if ($q==1) { $date_start=dol_get_first_day($year_start,1,false); $date_end=dol_get_last_day($year_start,3,false); }
- if ($q==2) { $date_start=dol_get_first_day($year_start,4,false); $date_end=dol_get_last_day($year_start,6,false); }
- if ($q==3) { $date_start=dol_get_first_day($year_start,7,false); $date_end=dol_get_last_day($year_start,9,false); }
- if ($q==4) { $date_start=dol_get_first_day($year_start,10,false); $date_end=dol_get_last_day($year_start,12,false); }
+ else
+ {
+ if ($q==1) { $date_start=dol_get_first_day($year_start,1,false); $date_end=dol_get_last_day($year_start,3,false); }
+ if ($q==2) { $date_start=dol_get_first_day($year_start,4,false); $date_end=dol_get_last_day($year_start,6,false); }
+ if ($q==3) { $date_start=dol_get_first_day($year_start,7,false); $date_end=dol_get_last_day($year_start,9,false); }
+ if ($q==4) { $date_start=dol_get_first_day($year_start,10,false); $date_end=dol_get_last_day($year_start,12,false); }
+ }
}
-$min = GETPOST("min");
+$min = price2num(GETPOST("min","alpha"));
if (empty($min)) $min = 0;
// Define modetax (0 or 1)
-// 0=normal, 1=option vat for services is on debit
-$modetax = $conf->global->TAX_MODE;
-if (isset($_REQUEST["modetax"])) $modetax=$_REQUEST["modetax"];
+// 0=normal, 1=option vat for services is on debit, 2=option on payments for products
+//$modetax = $conf->global->TAX_MODE;
+$calc=$conf->global->MAIN_INFO_LOCALTAX_CALC.$local;
+$modetax=$conf->global->$calc;
+if (GETPOSTISSET("modetax")) $modetax=GETPOST("modetax",'int');
if (empty($modetax)) $modetax=0;
// Security check
@@ -93,122 +96,123 @@ $socid = GETPOST('socid','int');
if ($user->societe_id) $socid=$user->societe_id;
$result = restrictedArea($user, 'tax', '', '', 'charges');
-/**
+
+
+/*
* View
*/
+
+$form=new Form($db);
+$company_static=new Societe($db);
+$invoice_customer=new Facture($db);
+$invoice_supplier=new FactureFournisseur($db);
+$expensereport=new ExpenseReport($db);
+$product_static=new Product($db);
+$payment_static=new Paiement($db);
+$paymentfourn_static=new PaiementFourn($db);
+$paymentexpensereport_static=new PaymentExpenseReport($db);
+
$morequerystring='';
$listofparams=array('date_startmonth','date_startyear','date_startday','date_endmonth','date_endyear','date_endday');
-foreach($listofparams as $param)
+foreach ($listofparams as $param)
{
if (GETPOST($param)!='') $morequerystring.=($morequerystring?'&':'').$param.'='.GETPOST($param);
}
-llxHeader('','','','',0,0,'','',$morequerystring);
-
-$form=new Form($db);
-
-$company_static=new Societe($db);
-$invoice_customer=new Facture($db);
-$invoice_supplier=new FactureFournisseur($db);
-$product_static=new Product($db);
-$payment_static=new Paiement($db);
-$paymentfourn_static=new PaiementFourn($db);
+llxHeader('',$langs->trans("LocalTaxReport"),'','',0,0,'','',$morequerystring);
$fsearch.='
';
$fsearch.='
';
$fsearch.='
';
-$calc=$conf->global->MAIN_INFO_LOCALTAX_CALC.$local;
-
-if ($conf->global->$calc==0 || $conf->global->$calc==1) // Calculate on invoice for goods and services
-{
- $nom=$langs->trans($local==1?"LT1ReportByQuartersInDueDebtMode":"LT2ReportByQuartersInDueDebtMode");
- $calcmode=$calc==0?$langs->trans("CalcModeLT".$local):$langs->trans("CalcModeLT".$local."Rec");
- $calcmode.='
('.$langs->trans("TaxModuleSetupToModifyRulesLT",DOL_URL_ROOT.'/admin/company.php').')';
- $period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1);
- $prevyear=$year_start; $prevquarter=$q;
- if ($prevquarter > 1) $prevquarter--;
- else { $prevquarter=4; $prevyear--; }
- $nextyear=$year_start; $nextquarter=$q;
- if ($nextquarter < 4) $nextquarter++;
- else { $nextquarter=1; $nextyear++; }
-
- if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $description.='
'.$langs->trans("DepositsAreNotIncluded");
- else $description.='
'.$langs->trans("DepositsAreIncluded");
- $description.=$fsearch;
- $builddate=dol_now();
-
- $elementcust=$langs->trans("CustomersInvoices");
- $productcust=$langs->trans("ProductOrService");
- $amountcust=$langs->trans("AmountHT");
- $vatcust=$langs->trans("VATReceived");
- if ($mysoc->tva_assuj) $vatcust.=' ('.$langs->trans("ToPay").')';
- $elementsup=$langs->trans("SuppliersInvoices");
- $productsup=$langs->trans("ProductOrService");
- $amountsup=$langs->trans("AmountHT");
- $vatsup=$langs->trans("VATPaid");
- if ($mysoc->tva_assuj) $vatsup.=' ('.$langs->trans("ToGetBack").')';
+$name=$langs->transcountry($local==1?"LT1ReportByQuarters":"LT2ReportByQuarters", $mysoc->country_code);
+$calcmode='';
+if ($modetax == 0) $calcmode=$langs->trans('OptionVATDefault');
+if ($modetax == 1) $calcmode=$langs->trans('OptionVATDebitOption');
+if ($modetax == 2) $calcmode=$langs->trans('OptionPaymentForProductAndServices');
+$calcmode.='
('.$langs->trans("TaxModuleSetupToModifyRules",DOL_URL_ROOT.'/admin/taxes.php').')';
+// Set period
+$period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1);
+$prevyear=$year_start; $prevquarter=$q;
+if ($prevquarter > 1) {
+ $prevquarter--;
+} else {
+ $prevquarter=4; $prevyear--;
}
-if ($conf->global->$calc==2) // Invoice for goods, payment for services
-{
- $nom=$langs->trans($local==1?"LT1ReportByQuartersInInputOutputMode":"LT2ReportByQuartersInInputOutputMode");
- $calcmode=$calc==0?$langs->trans("CalcModeLT".$local):$langs->trans("CalcModeLT".$local."Rec");
- $calcmode.='
('.$langs->trans("TaxModuleSetupToModifyRulesLT",DOL_URL_ROOT.'/admin/company.php').')';
- $period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1);
- $prevyear=$year_start; $prevquarter=$q;
- if ($prevquarter > 1) $prevquarter--;
- else { $prevquarter=4; $prevyear--; }
- $nextyear=$year_start; $nextquarter=$q;
- if ($nextquarter < 4) $nextquarter++;
- else { $nextquarter=1; $nextyear++; }
- if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $description.=' '.$langs->trans("DepositsAreNotIncluded");
- else $description.=' '.$langs->trans("DepositsAreIncluded");
- $description.=$fsearch;
- $builddate=dol_now();
-
- $elementcust=$langs->trans("CustomersInvoices");
- $productcust=$langs->trans("ProductOrService");
- $amountcust=$langs->trans("AmountHT");
- $vatcust=$langs->trans("VATReceived");
- if ($mysoc->tva_assuj) $vatcust.=' ('.$langs->trans("ToPay").')';
- $elementsup=$langs->trans("SuppliersInvoices");
- $productsup=$langs->trans("ProductOrService");
- $amountsup=$langs->trans("AmountHT");
- $vatsup=$langs->trans("VATPaid");
- if ($mysoc->tva_assuj) $vatsup.=' ('.$langs->trans("ToGetBack").')';
+$nextyear=$year_start; $nextquarter=$q;
+if ($nextquarter < 4) {
+ $nextquarter++;
+} else {
+ $nextquarter=1; $nextyear++;
}
+$description.=$fsearch;
+$builddate=dol_now();
+
+/*if ($conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') $description.=$langs->trans("RulesVATDueProducts");
+if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment') $description.=$langs->trans("RulesVATInProducts");
+if ($conf->global->TAX_MODE_SELL_SERVICE == 'invoice') $description.='
'.$langs->trans("RulesVATDueServices");
+if ($conf->global->TAX_MODE_SELL_SERVICE == 'payment') $description.='
'.$langs->trans("RulesVATInServices");
+if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
+ $description.='
'.$langs->trans("DepositsAreNotIncluded");
+}
+*/
+if (! empty($conf->global->MAIN_MODULE_ACCOUNTING)) $description.='
'.$langs->trans("ThisIsAnEstimatedValue");
+
+// Customers invoices
+$elementcust=$langs->trans("CustomersInvoices");
+$productcust=$langs->trans("ProductOrService");
+$amountcust=$langs->trans("AmountHT");
+$vatcust=$langs->trans("VATReceived");
+$namecust=$langs->trans("Name");
+if ($mysoc->tva_assuj) {
+ $vatcust.=' ('.$langs->trans("ToPay").')';
+}
+
+// Suppliers invoices
+$elementsup=$langs->trans("SuppliersInvoices");
+$productsup=$productcust;
+$amountsup=$amountcust;
+$vatsup=$langs->trans("VATPaid");
+$namesup=$namecust;
+if ($mysoc->tva_assuj) {
+ $vatsup.=' ('.$langs->trans("ToGetBack").')';
+}
+
+
report_header($name,'',$period,$periodlink,$description,$builddate,$exportlink,array(),$calcmode);
if($local==1){
$vatcust=$langs->transcountry("LocalTax1", $mysoc->country_code);
$vatsup=$langs->transcountry("LocalTax1", $mysoc->country_code);
+ $vatexpensereport=$langs->transcountry("LocalTax1", $mysoc->country_code);
}else{
$vatcust=$langs->transcountry("LocalTax2", $mysoc->country_code);
$vatsup=$langs->transcountry("LocalTax2", $mysoc->country_code);
+ $vatexpensereport=$langs->transcountry("LocalTax2", $mysoc->country_code);
}
// VAT Received and paid
+echo '
';
$y = $year_current;
$total = 0;
$i=0;
+$columns = 5;
// Load arrays of datas
-$x_coll = tax_by_date('localtax' . $local, $db, 0, 0, $date_start, $date_end, $modetax, 'sell');
-$x_paye = tax_by_date('localtax' . $local, $db, 0, 0, $date_start, $date_end, $modetax, 'buy');
-
-echo '';
+$x_coll = tax_by_rate('localtax' . $local, $db, 0, 0, $date_start, $date_end, $modetax, 'sell');
+$x_paye = tax_by_rate('localtax' . $local, $db, 0, 0, $date_start, $date_end, $modetax, 'buy');
if (! is_array($x_coll) || ! is_array($x_paye))
{
$langs->load("errors");
if ($x_coll == -1)
- print ''.$langs->trans("ErrorNoAccountancyModuleLoaded").' ';
+ print ''.$langs->trans("ErrorNoAccountancyModuleLoaded").' ';
else if ($x_coll == -2)
- print ''.$langs->trans("FeatureNotYetAvailable").' ';
+ print ''.$langs->trans("FeatureNotYetAvailable").' ';
else
- print ''.$langs->trans("Error").' ';
+ print ''.$langs->trans("Error").' ';
}
else
{
@@ -228,6 +232,7 @@ else
$invoice_customer->id=$x_coll[$my_coll_rate]['facid'][$id];
$invoice_customer->ref=$x_coll[$my_coll_rate]['facnum'][$id];
$invoice_customer->type=$x_coll[$my_coll_rate]['type'][$id];
+ $company_static->fetch($x_coll[$my_coll_rate]['company_id'][$id]);
$x_both[$my_coll_rate]['coll']['detail'][] = array(
'id' =>$x_coll[$my_coll_rate]['facid'][$id],
'descr' =>$x_coll[$my_coll_rate]['descr'][$id],
@@ -239,20 +244,24 @@ else
'ftotal_ttc'=>$x_coll[$my_coll_rate]['ftotal_ttc'][$id],
'dtotal_ttc'=>$x_coll[$my_coll_rate]['dtotal_ttc'][$id],
'dtype' =>$x_coll[$my_coll_rate]['dtype'][$id],
+ 'datef' =>$x_coll[$my_coll_rate]['datef'][$id],
+ 'datep' =>$x_coll[$my_coll_rate]['datep'][$id],
+ 'company_link'=>$company_static->getNomUrl(1,'',20),
'ddate_start'=>$x_coll[$my_coll_rate]['ddate_start'][$id],
'ddate_end' =>$x_coll[$my_coll_rate]['ddate_end'][$id],
'totalht' =>$x_coll[$my_coll_rate]['totalht_list'][$id],
'localtax1'=> $x_coll[$my_coll_rate]['localtax1_list'][$id],
'localtax2'=> $x_coll[$my_coll_rate]['localtax2_list'][$id],
'vat' =>$x_coll[$my_coll_rate]['vat_list'][$id],
- 'link' =>$invoice_customer->getNomUrl(1,'',12));
+ 'link' =>$invoice_customer->getNomUrl(1,'',12)
+ );
}
}
// tva paid
- foreach(array_keys($x_paye) as $my_paye_rate){
+ foreach(array_keys($x_paye) as $my_paye_rate) {
$x_both[$my_paye_rate]['paye']['totalht'] = $x_paye[$my_paye_rate]['totalht'];
$x_both[$my_paye_rate]['paye']['vat'] = $x_paye[$my_paye_rate]['vat'];
- if(!isset($x_both[$my_paye_rate]['coll']['totalht'])){
+ if(!isset($x_both[$my_paye_rate]['coll']['totalht'])) {
$x_both[$my_paye_rate]['coll']['totalht'] = 0;
$x_both[$my_paye_rate]['coll']['vat'] = 0;
}
@@ -275,35 +284,39 @@ else
'ftotal_ttc'=>price2num($x_paye[$my_paye_rate]['ftotal_ttc'][$id]),
'dtotal_ttc'=>price2num($x_paye[$my_paye_rate]['dtotal_ttc'][$id]),
'dtype' =>$x_paye[$my_paye_rate]['dtype'][$id],
+ 'datef' =>$x_paye[$my_paye_rate]['datef'][$id],
+ 'datep' =>$x_paye[$my_paye_rate]['datep'][$id],
+ 'company_link'=>$company_static->getNomUrl(1,'',20),
'ddate_start'=>$x_paye[$my_paye_rate]['ddate_start'][$id],
'ddate_end' =>$x_paye[$my_paye_rate]['ddate_end'][$id],
'totalht' =>price2num($x_paye[$my_paye_rate]['totalht_list'][$id]),
'localtax1'=> $x_paye[$my_paye_rate]['localtax1_list'][$id],
'localtax2'=> $x_paye[$my_paye_rate]['localtax2_list'][$id],
'vat' =>$x_paye[$my_paye_rate]['vat_list'][$id],
- 'link' =>$invoice_supplier->getNomUrl(1,'',12));
+ 'link' =>$invoice_supplier->getNomUrl(1,'',12)
+ );
}
}
//now we have an array (x_both) indexed by rates for coll and paye
+ //print table headers for this quadri - incomes first
+
$x_coll_sum = 0;
$x_coll_ht = 0;
$x_paye_sum = 0;
$x_paye_ht = 0;
- $span=3;
- if ($modetax == 0) $span+=2;
+ $span=$columns;
+ if ($modetax != 1) $span+=2;
- if($conf->global->$calc ==0 || $conf->global->$calc == 2){
+ //if ($modetax == 0 || $modetax == 2)
+ //{
// Customers invoices
print '';
print ''.$elementcust.' ';
print ''.$productcust.' ';
- if ($modetax == 0)
- {
- print ''.$amountcust.' ';
- print ''.$langs->trans("Payment").' ('.$langs->trans("PercentOfInvoice").') ';
- }
+ if ($modetax != 2) print ''.$amountcust.' ';
+ if ($modetax != 1) print ''.$langs->trans("Payment").' ('.$langs->trans("PercentOfInvoice").') ';
print ''.$langs->trans("BI").' ';
print ''.$vatcust.' ';
print ' ';
@@ -319,8 +332,6 @@ else
if (is_array($x_both[$rate]['coll']['detail']))
{
// VAT Rate
- $var=true;
-
if($rate!=0){
print "";
print ''.$langs->trans("Rate").': '.vatrate($rate).'% ';
@@ -328,116 +339,116 @@ else
}
foreach($x_both[$rate]['coll']['detail'] as $index => $fields)
{
- if(($local==1 && $fields['localtax1']!=0) || ($local==2 && $fields['localtax2']!=0)){
- // Define type
- $type=($fields['dtype']?$fields['dtype']:$fields['ptype']);
- // Try to enhance type detection using date_start and date_end for free lines where type
- // was not saved.
- if (! empty($fields['ddate_start'])) $type=1;
- if (! empty($fields['ddate_end'])) $type=1;
-
-
- print ' ';
-
- // Ref
- print ''.$fields['link'].' ';
-
- // Description
- print '';
- if ($fields['pid'])
+ if(($local==1 && $fields['localtax1']!=0) || ($local==2 && $fields['localtax2']!=0))
{
- $product_static->id=$fields['pid'];
- $product_static->ref=$fields['pref'];
- $product_static->type=$fields['ptype'];
- print $product_static->getNomUrl(1);
- if (dol_string_nohtmltag($fields['descr'])) print ' - '.dol_trunc(dol_string_nohtmltag($fields['descr']),16);
- }
- else
- {
- if ($type) $text = img_object($langs->trans('Service'),'service');
- else $text = img_object($langs->trans('Product'),'product');
- if (preg_match('/^\((.*)\)$/',$fields['descr'],$reg))
- {
- if ($reg[1]=='DEPOSIT') $fields['descr']=$langs->transnoentitiesnoconv('Deposit');
- elseif ($reg[1]=='CREDIT_NOTE') $fields['descr']=$langs->transnoentitiesnoconv('CreditNote');
- else $fields['descr']=$langs->transnoentitiesnoconv($reg[1]);
- }
- print $text.' '.dol_trunc(dol_string_nohtmltag($fields['descr']),16);
+ // Define type
+ $type=($fields['dtype']?$fields['dtype']:$fields['ptype']);
+ // Try to enhance type detection using date_start and date_end for free lines where type
+ // was not saved.
+ if (! empty($fields['ddate_start'])) $type=1;
+ if (! empty($fields['ddate_end'])) $type=1;
- // Show range
- print_date_range($fields['ddate_start'],$fields['ddate_end']);
- }
- print ' ';
- // Total HT
- if ($modetax == 0)
- {
- print '';
- print price($fields['totalht']);
- if (price2num($fields['ftotal_ttc']))
+ print ' ';
+
+ // Ref
+ print ''.$fields['link'].' ';
+
+ // Description
+ print '';
+ if ($fields['pid'])
{
- $ratiolineinvoice=($fields['dtotal_ttc']/$fields['ftotal_ttc']);
+ $product_static->id=$fields['pid'];
+ $product_static->ref=$fields['pref'];
+ $product_static->type=$fields['ptype'];
+ print $product_static->getNomUrl(1);
+ if (dol_string_nohtmltag($fields['descr'])) print ' - '.dol_trunc(dol_string_nohtmltag($fields['descr']),16);
+ }
+ else
+ {
+ if ($type) $text = img_object($langs->trans('Service'),'service');
+ else $text = img_object($langs->trans('Product'),'product');
+ if (preg_match('/^\((.*)\)$/',$fields['descr'],$reg))
+ {
+ if ($reg[1]=='DEPOSIT') $fields['descr']=$langs->transnoentitiesnoconv('Deposit');
+ elseif ($reg[1]=='CREDIT_NOTE') $fields['descr']=$langs->transnoentitiesnoconv('CreditNote');
+ else $fields['descr']=$langs->transnoentitiesnoconv($reg[1]);
+ }
+ print $text.' '.dol_trunc(dol_string_nohtmltag($fields['descr']),16);
+
+ // Show range
+ print_date_range($fields['ddate_start'],$fields['ddate_end']);
}
print ' ';
- }
- // Payment
- $ratiopaymentinvoice=1;
- if ($modetax == 0)
- {
- if (isset($fields['payment_amount']) && $fields['ftotal_ttc']) $ratiopaymentinvoice=($fields['payment_amount']/$fields['ftotal_ttc']);
+ // Total HT
+ if ($modetax != 2)
+ {
+ print '';
+ print price($fields['totalht']);
+ if (price2num($fields['ftotal_ttc']))
+ {
+ $ratiolineinvoice=($fields['dtotal_ttc']/$fields['ftotal_ttc']);
+ }
+ print ' ';
+ }
+
+ // Payment
+ $ratiopaymentinvoice=1;
+ if ($modetax != 1)
+ {
+ if (isset($fields['payment_amount']) && $fields['ftotal_ttc']) $ratiopaymentinvoice=($fields['payment_amount']/$fields['ftotal_ttc']);
+ print '';
+ if ($fields['payment_amount'] && $fields['ftotal_ttc'])
+ {
+ $payment_static->id=$fields['payment_id'];
+ print $payment_static->getNomUrl(2);
+ }
+ if ($type == 0)
+ {
+ print $langs->trans("NotUsedForGoods");
+ }
+ else {
+ print price($fields['payment_amount']);
+ if (isset($fields['payment_amount'])) print ' ('.round($ratiopaymentinvoice*100,2).'%)';
+ }
+ print ' ';
+ }
+
+ // Total collected
print '';
- if ($fields['payment_amount'] && $fields['ftotal_ttc'])
- {
- $payment_static->id=$fields['payment_id'];
- print $payment_static->getNomUrl(2);
- }
- if ($type == 0)
- {
- print $langs->trans("NotUsedForGoods");
- }
- else {
- print price($fields['payment_amount']);
- if (isset($fields['payment_amount'])) print ' ('.round($ratiopaymentinvoice*100,2).'%)';
- }
+ $temp_ht=$fields['totalht'];
+ if ($type == 1) $temp_ht=$fields['totalht']*$ratiopaymentinvoice;
+ print price(price2num($temp_ht,'MT'));
print ' ';
+
+ // Localtax
+ print '';
+ $temp_vat= $local==1?$fields['localtax1']:$fields['localtax2'];
+ print price(price2num($temp_vat,'MT'));
+ //print price($fields['vat']);
+ print ' ';
+ print ' ';
+
+ $subtot_coll_total_ht += $temp_ht;
+ $subtot_coll_vat += $temp_vat;
+ $x_coll_sum += $temp_vat;
}
-
- // Total collected
- print '';
- $temp_ht=$fields['totalht'];
- if ($type == 1) $temp_ht=$fields['totalht']*$ratiopaymentinvoice;
- print price(price2num($temp_ht,'MT'));
- print ' ';
-
- // Localtax
- print '';
- $temp_vat= $local==1?$fields['localtax1']:$fields['localtax2'];
- print price(price2num($temp_vat,'MT'));
- //print price($fields['vat']);
- print ' ';
- print '';
-
- $subtot_coll_total_ht += $temp_ht;
- $subtot_coll_vat += $temp_vat;
- $x_coll_sum += $temp_vat;
}
}
- }
- if($rate!=0){
- // Total customers for this vat rate
- print '';
- print ' ';
- print ''.$langs->trans("Total").': ';
- if ($modetax == 0)
- {
- print ' ';
- print ' ';
- }
- print ''.price(price2num($subtot_coll_total_ht,'MT')).' ';
- print ''.price(price2num($subtot_coll_vat,'MT')).' ';
- print ' ';
- }
+
+ // Total customers for this vat rate
+ print '';
+ print ' ';
+ print ''.$langs->trans("Total").': ';
+ if ($modetax != 1)
+ {
+ print ' ';
+ print ' ';
+ }
+ print ''.price(price2num($subtot_coll_total_ht,'MT')).' ';
+ print ''.price(price2num($subtot_coll_vat,'MT')).' ';
+ print ' ';
}
if (count($x_coll) == 0) // Show a total ine if nothing shown
@@ -459,15 +470,15 @@ else
print ' ';
print '
';
$diff=$x_coll_sum;
- }
+ //}
- if($conf->global->$calc ==0 || $conf->global->$calc == 1){
+ //if($conf->global->$calc ==0 || $conf->global->$calc == 1){
echo '';
//print table headers for this quadri - expenses now
print '';
print ''.$elementsup.' ';
print ''.$productsup.' ';
- if ($modetax == 0)
+ if ($modetax != 1)
{
print ''.$amountsup.' ';
print ''.$langs->trans("Payment").' ('.$langs->trans("PercentOfInvoice").') ';
@@ -481,9 +492,8 @@ else
$subtot_paye_total_ht = 0;
$subtot_paye_vat = 0;
- if(is_array($x_both[$rate]['paye']['detail']))
+ if (is_array($x_both[$rate]['paye']['detail']))
{
- $var=true;
if($rate!=0){
print " ";
print ''.$langs->trans("Rate").': '.vatrate($rate).'% ';
@@ -491,149 +501,144 @@ else
}
foreach($x_both[$rate]['paye']['detail'] as $index=>$fields)
{
- if(($local==1 && $fields['localtax1']!=0) || ($local==2 && $fields['localtax2']!=0)){
- // Define type
- $type=($fields['dtype']?$fields['dtype']:$fields['ptype']);
- // Try to enhance type detection using date_start and date_end for free lines where type
- // was not saved.
- if (! empty($fields['ddate_start'])) $type=1;
- if (! empty($fields['ddate_end'])) $type=1;
-
-
- print ' ';
-
- // Ref
- print ''.$fields['link'].' ';
-
- // Description
- print '';
- if ($fields['pid'])
+ if(($local==1 && $fields['localtax1']!=0) || ($local==2 && $fields['localtax2']!=0))
{
- $product_static->id=$fields['pid'];
- $product_static->ref=$fields['pref'];
- $product_static->type=$fields['ptype'];
- print $product_static->getNomUrl(1);
- if (dol_string_nohtmltag($fields['descr'])) print ' - '.dol_trunc(dol_string_nohtmltag($fields['descr']),16);
- }
- else
- {
- if ($type) $text = img_object($langs->trans('Service'),'service');
- else $text = img_object($langs->trans('Product'),'product');
- print $text.' '.dol_trunc(dol_string_nohtmltag($fields['descr']),16);
+ // Define type
+ $type=($fields['dtype']?$fields['dtype']:$fields['ptype']);
+ // Try to enhance type detection using date_start and date_end for free lines where type
+ // was not saved.
+ if (! empty($fields['ddate_start'])) $type=1;
+ if (! empty($fields['ddate_end'])) $type=1;
- // Show range
- print_date_range($fields['ddate_start'],$fields['ddate_end']);
- }
- print ' ';
- // Total HT
- if ($modetax == 0)
- {
- print '';
- print price($fields['totalht']);
- if (price2num($fields['ftotal_ttc']))
+ print ' ';
+
+ // Ref
+ print ''.$fields['link'].' ';
+
+ // Description
+ print '';
+ if ($fields['pid'])
{
- //print $fields['dtotal_ttc']."/".$fields['ftotal_ttc']." - ";
- $ratiolineinvoice=($fields['dtotal_ttc']/$fields['ftotal_ttc']);
- //print ' ('.round($ratiolineinvoice*100,2).'%)';
- }
- print ' ';
- }
-
- // Payment
- $ratiopaymentinvoice=1;
- if ($modetax == 0)
- {
- if (isset($fields['payment_amount']) && $fields['ftotal_ttc']) $ratiopaymentinvoice=($fields['payment_amount']/$fields['ftotal_ttc']);
- print '';
- if ($fields['payment_amount'] && $fields['ftotal_ttc'])
- {
- $paymentfourn_static->id=$fields['payment_id'];
- print $paymentfourn_static->getNomUrl(2);
- }
- if ($type == 0)
- {
- print $langs->trans("NotUsedForGoods");
+ $product_static->id=$fields['pid'];
+ $product_static->ref=$fields['pref'];
+ $product_static->type=$fields['ptype'];
+ print $product_static->getNomUrl(1);
+ if (dol_string_nohtmltag($fields['descr'])) print ' - '.dol_trunc(dol_string_nohtmltag($fields['descr']),16);
}
else
{
- print price($fields['payment_amount']);
- if (isset($fields['payment_amount'])) print ' ('.round($ratiopaymentinvoice*100,2).'%)';
+ if ($type) $text = img_object($langs->trans('Service'),'service');
+ else $text = img_object($langs->trans('Product'),'product');
+ print $text.' '.dol_trunc(dol_string_nohtmltag($fields['descr']),16);
+
+ // Show range
+ print_date_range($fields['ddate_start'],$fields['ddate_end']);
}
print ' ';
+
+ // Total HT
+ if ($modetax != 2)
+ {
+ print '';
+ print price($fields['totalht']);
+ if (price2num($fields['ftotal_ttc']))
+ {
+ //print $fields['dtotal_ttc']."/".$fields['ftotal_ttc']." - ";
+ $ratiolineinvoice=($fields['dtotal_ttc']/$fields['ftotal_ttc']);
+ //print ' ('.round($ratiolineinvoice*100,2).'%)';
+ }
+ print ' ';
+ }
+
+ // Payment
+ $ratiopaymentinvoice=1;
+ if ($modetax != 1)
+ {
+ print '';
+ if (isset($fields['payment_amount']) && $fields['ftotal_ttc']) $ratiopaymentinvoice=($fields['payment_amount']/$fields['ftotal_ttc']);
+ if ($fields['payment_amount'] && $fields['ftotal_ttc'])
+ {
+ $paymentfourn_static->id=$fields['payment_id'];
+ print $paymentfourn_static->getNomUrl(2);
+ }
+ if ($type == 0)
+ {
+ print $langs->trans("NA");
+ }
+ else
+ {
+ print price(price2num($fields['payment_amount'],'MT'));
+ if (isset($fields['payment_amount'])) {
+ print ' ('.round($ratiopaymentinvoice*100,2).'%)';
+ }
+ }
+ print ' ';
+ }
+
+ // VAT paid
+ print '';
+ $temp_ht=$fields['totalht']*$ratiopaymentinvoice;
+ print price(price2num($temp_ht,'MT'),1);
+ print ' ';
+
+ // Localtax
+ print '';
+ $temp_vat=($local==1?$fields['localtax1']:$fields['localtax2'])*$ratiopaymentinvoice;;
+ print price(price2num($temp_vat,'MT'),1);
+ //print price($fields['vat']);
+ print ' ';
+ print ' ';
+
+ $subtot_paye_total_ht += $temp_ht;
+ $subtot_paye_vat += $temp_vat;
+ $x_paye_sum += $temp_vat;
}
-
- // VAT paid
- print '';
- $temp_ht=$fields['totalht'];
- if ($type == 1) $temp_ht=$fields['totalht']*$ratiopaymentinvoice;
- print price(price2num($temp_ht,'MT'));
- print ' ';
-
- // Localtax
- print '';
- $temp_vat= $local==1?$fields['localtax1']:$fields['localtax2'];
- print price(price2num($temp_vat,'MT'));
- //print price($fields['vat']);
- print ' ';
- print '';
-
- $subtot_paye_total_ht += $temp_ht;
- $subtot_paye_vat += $temp_vat;
- $x_paye_sum += $temp_vat;
}
}
- }
- if($rate!=0){
- // Total suppliers for this vat rate
- print '';
- print ' ';
- print ''.$langs->trans("Total").': ';
- if ($modetax == 0)
- {
- print ' ';
- print ' ';
- }
- print ''.price(price2num($subtot_paye_total_ht,'MT')).' ';
- print ''.price(price2num($subtot_paye_vat,'MT')).' ';
- print ' ';
- }
+
+ // Total suppliers for this vat rate
+ print '';
+ print ' ';
+ print ''.$langs->trans("Total").': ';
+ if ($modetax != 1)
+ {
+ print ' ';
+ print ' ';
+ }
+ print ''.price(price2num($subtot_paye_total_ht,'MT')).' ';
+ print ''.price(price2num($subtot_paye_vat,'MT')).' ';
+ print ' ';
}
- if (count($x_paye) == 0) // Show a total ine if nothing shown
- {
- print '';
- print ' ';
- print ''.$langs->trans("Total").': ';
- if ($modetax == 0)
- {
- print ' ';
- print ' ';
- }
- print ''.price(price2num(0,'MT')).' ';
- print ''.price(price2num(0,'MT')).' ';
- print ' ';
+ if (count($x_paye) == 0) { // Show a total line if nothing shown
+ print '';
+ print ' ';
+ print ''.$langs->trans("Total").': ';
+ if ($modetax != 1) {
+ print ' ';
+ print ' ';
+ }
+ print ''.price(price2num(0,'MT')).' ';
+ print ''.price(price2num(0,'MT')).' ';
+ print ' ';
}
print '
';
- $diff=$x_paye_sum;
- }
+ //}
- if($conf->global->$calc ==0){$diff=$x_coll_sum - $x_paye_sum;}
- echo '';
- // Total to pay
- print ' ';
- print '';
- //$diff = $local==1?$x_coll_sum:$x_paye_sum;
- print '';
- print ''.$langs->trans("TotalToPay").($q?', '.$langs->trans("Quadri").' '.$q:'').' ';
- print ''.price(price2num($diff,'MT'))." \n";
- print " \n";
-
- echo '
';
+ // Total to pay
+ print ' ';
+ print '';
+ $diff = $x_coll_sum - $x_paye_sum;
+ print '';
+ print ''.$langs->trans("TotalToPay").($q?', '.$langs->trans("Quadri").' '.$q:'').' ';
+ print ''.price(price2num($diff,'MT'))." \n";
+ print " \n";
$i++;
}
+print '
';
llxFooter();
$db->close();
diff --git a/htdocs/compta/paiement.php b/htdocs/compta/paiement.php
index 11751fe258b..c2ce95dd827 100644
--- a/htdocs/compta/paiement.php
+++ b/htdocs/compta/paiement.php
@@ -35,10 +35,8 @@ require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
-$langs->load('companies');
-$langs->load('bills');
-$langs->load('banks');
-$langs->load('multicurrency');
+// Load translation files required by the page
+$langs->loadLangs(array('companies', 'bills', 'banks', 'multicurrency'));
$action = GETPOST('action','alpha');
$confirm = GETPOST('confirm');
@@ -88,11 +86,11 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e
if (empty($reshook))
{
- if ($action == 'add_paiement' || ($action == 'confirm_paiement' && $confirm=='yes'))
+ if ($action == 'add_paiement' || ($action == 'confirm_paiement' && $confirm == 'yes'))
{
$error = 0;
- $datepaye = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
+ $datepaye = dol_mktime(12, 0, 0, GETPOST('remonth','int'), GETPOST('reday','int'), GETPOST('reyear','int'));
$paiement_id = 0;
$totalpayment = 0;
$multicurrency_totalpayment = 0;
@@ -504,18 +502,18 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie
print ''.$langs->trans('CheckTransmitter');
print ' ('.$langs->trans("ChequeMaker").') ';
print ' ';
- print ' ';
+ print ' ';
// Bank name
print ''.$langs->trans('Bank');
print ' ('.$langs->trans("ChequeBank").') ';
print ' ';
- print ' ';
+ print ' ';
// Comments
print ''.$langs->trans('Comments').' ';
print '';
- print ''.GETPOST('comment').' ';
+ print ''.GETPOST('comment','none').' ';
print '
';
@@ -591,7 +589,6 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie
print ' ';
print "\n";
- $var=true;
$total=0;
$totalrecu=0;
$totalrecucreditnote=0;
@@ -601,7 +598,6 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie
{
$objp = $db->fetch_object($resql);
-
$soc = new Societe($db);
$soc->fetch($objp->socid);
@@ -819,7 +815,7 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie
if (! GETPOST('action','aZ09'))
{
if ($page == -1) $page = 0 ;
- $limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit;
+ $limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit;
$offset = $limit * $page ;
if (! $sortorder) $sortorder='DESC';
@@ -827,7 +823,7 @@ if (! GETPOST('action','aZ09'))
$sql = 'SELECT p.datep as dp, p.amount, f.amount as fa_amount, f.facnumber';
$sql.=', f.rowid as facid, c.libelle as paiement_type, p.num_paiement';
- $sql.= ' FROM '.MAIN_DB_PREFIX.'paiement as p LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id AND c.entity IN (' . getEntity('c_paiement').')';
+ $sql.= ' FROM '.MAIN_DB_PREFIX.'paiement as p LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id';
$sql.= ', '.MAIN_DB_PREFIX.'facture as f';
$sql.= ' WHERE p.fk_facture = f.rowid';
$sql.= ' AND f.entity IN (' . getEntity('facture').')';
@@ -844,7 +840,6 @@ if (! GETPOST('action','aZ09'))
{
$num = $db->num_rows($resql);
$i = 0;
- $var=true;
print_barre_liste($langs->trans('Payments'), $page, $_SERVER["PHP_SELF"],'',$sortfield,$sortorder,'',$num);
print '';
diff --git a/htdocs/compta/paiement/card.php b/htdocs/compta/paiement/card.php
index 3a6727b4299..656d6c673f2 100644
--- a/htdocs/compta/paiement/card.php
+++ b/htdocs/compta/paiement/card.php
@@ -34,9 +34,8 @@ require_once DOL_DOCUMENT_ROOT .'/core/modules/facture/modules_facture.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
if (! empty($conf->banque->enabled)) require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
-$langs->load('bills');
-$langs->load('banks');
-$langs->load('companies');
+// Load translation files required by the page
+$langs->loadLangs(array('bills','banks','companies'));
$id=GETPOST('id','int');
$ref=GETPOST('ref', 'alpha');
@@ -222,57 +221,64 @@ print '
';
print ''."\n";
// Date payment
-print ''.$form->editfieldkey("Date",'datep',$object->date,$object,$user->rights->facture->paiement).' ';
+print ' '.$form->editfieldkey("Date",'datep',$object->date,$object,$user->rights->facture->paiement).' ';
print $form->editfieldval("Date",'datep',$object->date,$object,$user->rights->facture->paiement,'datepicker','',null,$langs->trans('PaymentDateUpdateSucceeded'));
print ' ';
// Payment type (VIR, LIQ, ...)
$labeltype=$langs->trans("PaymentType".$object->type_code)!=("PaymentType".$object->type_code)?$langs->trans("PaymentType".$object->type_code):$object->type_libelle;
-print ''.$langs->trans('PaymentMode').' '.$labeltype.' ';
-
-// Payment numero
-print ''.$form->editfieldkey("Numero",'num_paiement',$object->numero,$object,$object->statut == 0 && $user->rights->fournisseur->facture->creer).' ';
-print $form->editfieldval("Numero",'num_paiement',$object->numero,$object,$object->statut == 0 && $user->rights->fournisseur->facture->creer,'string','',null,$langs->trans('PaymentNumberUpdateSucceeded'));
-print ' ';
-
-// Amount
-print ''.$langs->trans('Amount').' '.price($object->amount,'',$langs,0,-1,-1,$conf->currency).' ';
-
-// Note
-print ''.$form->editfieldkey("Note",'note',$object->note,$object,$user->rights->facture->paiement).' ';
-print $form->editfieldval("Note",'note',$object->note,$object,$user->rights->facture->paiement,'textarea');
-print ' ';
+print ''.$langs->trans('PaymentMode').' '.$labeltype.' ';
$disable_delete = 0;
// Bank account
if (! empty($conf->banque->enabled))
{
- if ($object->fk_account > 0)
- {
- $bankline=new AccountLine($db);
- $bankline->fetch($object->bank_line);
- if ($bankline->rappro)
- {
- $disable_delete = 1;
- $title_button = dol_escape_htmltag($langs->transnoentitiesnoconv("CantRemoveConciliatedPayment"));
- }
+ if ($object->fk_account > 0)
+ {
+ $bankline=new AccountLine($db);
+ $bankline->fetch($object->bank_line);
+ if ($bankline->rappro)
+ {
+ $disable_delete = 1;
+ $title_button = dol_escape_htmltag($langs->transnoentitiesnoconv("CantRemoveConciliatedPayment"));
+ }
- print '';
- print ''.$langs->trans('BankTransactionLine').' ';
- print '';
- print $bankline->getNomUrl(1,0,'showconciliated');
- print ' ';
- print ' ';
-
- print '';
- print ''.$langs->trans('BankAccount').' ';
- print '';
+ print ' ';
+ print ''.$langs->trans('BankAccount').' ';
+ print '';
$accountstatic=new Account($db);
$accountstatic->fetch($bankline->fk_account);
- print $accountstatic->getNomUrl(1);
- print ' ';
- print ' ';
+ print $accountstatic->getNomUrl(1);
+ print '';
+ print '';
+ }
+}
+// Payment numero
+/*
+$titlefield=$langs->trans('Numero').' ('.$langs->trans("ChequeOrTransferNumber").') ';
+print ''.$form->editfieldkey($titlefield,'num_paiement',$object->num_paiement,$object,$object->statut == 0 && $user->rights->fournisseur->facture->creer).' ';
+print $form->editfieldval($titlefield,'num_paiement',$object->num_paiement,$object,$object->statut == 0 && $user->rights->fournisseur->facture->creer,'string','',null,$langs->trans('PaymentNumberUpdateSucceeded'));
+print ' ';
+
+// Check transmitter
+$titlefield=$langs->trans('CheckTransmitter').' ('.$langs->trans("ChequeMaker").') ';
+print ''.$form->editfieldkey($titlefield,'chqemetteur',$object->,$object,$object->statut == 0 && $user->rights->fournisseur->facture->creer).' ';
+print $form->editfieldval($titlefield,'chqemetteur',$object->aaa,$object,$object->statut == 0 && $user->rights->fournisseur->facture->creer,'string','',null,$langs->trans('ChequeMakeUpdateSucceeded'));
+print ' ';
+
+// Bank name
+$titlefield=$langs->trans('Bank').' ('.$langs->trans("ChequeBank").') ';
+print ''.$form->editfieldkey($titlefield,'chqbank',$object->aaa,$object,$object->statut == 0 && $user->rights->fournisseur->facture->creer).' ';
+print $form->editfieldval($titlefield,'chqbank',$object->aaa,$object,$object->statut == 0 && $user->rights->fournisseur->facture->creer,'string','',null,$langs->trans('ChequeBankUpdateSucceeded'));
+print ' ';
+*/
+
+// Bank account
+if (! empty($conf->banque->enabled))
+{
+ if ($object->fk_account > 0)
+ {
if ($object->type_code == 'CHQ' && $bankline->fk_bordereau > 0)
{
dol_include_once('/compta/paiement/cheque/class/remisecheque.class.php');
@@ -280,15 +286,30 @@ if (! empty($conf->banque->enabled))
$bordereau->fetch($bankline->fk_bordereau);
print '';
- print ''.$langs->trans('CheckReceipt').' ';
- print '';
+ print ' '.$langs->trans('CheckReceipt').' ';
+ print '';
print $bordereau->getNomUrl(1);
- print ' ';
- print ' ';
+ print '';
+ print '';
}
- }
+ }
+
+ print '';
+ print ''.$langs->trans('BankTransactionLine').' ';
+ print '';
+ print $bankline->getNomUrl(1,0,'showconciliated');
+ print ' ';
+ print ' ';
}
+// Comments
+print ''.$form->editfieldkey("Comments",'note',$object->note,$object,$user->rights->facture->paiement).' ';
+print $form->editfieldval("Note",'note',$object->note,$object,$user->rights->facture->paiement,'textarea:'.ROWS_3.':90%');
+print ' ';
+
+// Amount
+print ''.$langs->trans('Amount').' '.price($object->amount,'',$langs,0,-1,-1,$conf->currency).' ';
+
print '
';
print '';
@@ -332,8 +353,6 @@ if ($resql)
if ($num > 0)
{
- $var=True;
-
while ($i < $num)
{
$objp = $db->fetch_object($resql);
diff --git a/htdocs/compta/paiement/cheque/card.php b/htdocs/compta/paiement/cheque/card.php
index 8a165ebe811..69f3bd102df 100644
--- a/htdocs/compta/paiement/cheque/card.php
+++ b/htdocs/compta/paiement/cheque/card.php
@@ -32,11 +32,8 @@ require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/paiement/cheque/class/remisecheque.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
-$langs->load("banks");
-$langs->load("categories");
-$langs->load('bills');
-$langs->load('companies');
-$langs->load('compta');
+// Load translation files required by the page
+$langs->loadLangs(array('banks', 'categories', 'bills', 'companies', 'compta'));
$id =GETPOST('id','int');
$ref=GETPOST('ref', 'alpha');
@@ -54,7 +51,7 @@ $page=GETPOST('page', 'int');
if (! $sortorder) $sortorder="ASC";
if (! $sortfield) $sortfield="b.dateo,b.rowid";
if (empty($page) || $page == -1) { $page = 0; }
-$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit;
+$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit;
$offset = $limit * $page ;
$dir=$conf->bank->dir_output.'/checkdeposits/';
diff --git a/htdocs/compta/paiement/cheque/index.php b/htdocs/compta/paiement/cheque/index.php
index 74fe9ea9455..527bd05e3a1 100644
--- a/htdocs/compta/paiement/cheque/index.php
+++ b/htdocs/compta/paiement/cheque/index.php
@@ -28,10 +28,8 @@ require('../../../main.inc.php');
require_once DOL_DOCUMENT_ROOT.'/compta/paiement/cheque/class/remisecheque.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
-$langs->load("banks");
-$langs->load("categories");
-$langs->load("compta");
-$langs->load("bills");
+// Load translation files required by the page
+$langs->loadLangs(array('banks', 'categories', 'compta', 'bills'));
// Security check
if ($user->societe_id) $socid=$user->societe_id;
@@ -70,7 +68,6 @@ print "\n";
if ($resql)
{
- $var=false;
if ($row = $db->fetch_row($resql) )
{
$num = $row[0];
@@ -116,7 +113,6 @@ if ($resql)
print ''.$langs->trans("Status").' ';
print "\n";
- $var=true;
while ( $objp = $db->fetch_object($resql) )
{
$checkdepositstatic->id=$objp->rowid;
diff --git a/htdocs/compta/paiement/cheque/list.php b/htdocs/compta/paiement/cheque/list.php
index 76c52215281..800f40b9694 100644
--- a/htdocs/compta/paiement/cheque/list.php
+++ b/htdocs/compta/paiement/cheque/list.php
@@ -31,9 +31,8 @@ require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
-$langs->load("banks");
-$langs->load("categories");
-$langs->load("bills");
+// Load translation files required by the page
+$langs->loadLangs(array('banks', 'categories', 'bills'));
// Security check
if ($user->societe_id) $socid=$user->societe_id;
@@ -43,7 +42,7 @@ $search_ref = GETPOST('search_ref','alpha');
$search_account = GETPOST('search_account','int');
$search_amount = GETPOST('search_amount','alpha');
-$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit;
+$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit;
$sortfield = GETPOST("sortfield",'alpha');
$sortorder = GETPOST("sortorder",'alpha');
$page = GETPOST("page",'int');
@@ -117,6 +116,11 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
{
$result = $db->query($sql);
$nbtotalofrecords = $db->num_rows($result);
+ if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0
+ {
+ $page = 0;
+ $offset = 0;
+ }
}
$sql.= $db->plimit($limit+1, $offset);
@@ -131,6 +135,14 @@ if ($resql)
if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage;
if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit;
+ $newcardbutton='';
+ if ($user->rights->banque->cheque)
+ {
+ $newcardbutton = ''.$langs->trans('NewCheckDeposit').' ';
+ $newcardbutton.= ' ';
+ $newcardbutton.= ' ';
+ }
+
print '';
if ($optioncss != '') print ' ';
print ' ';
@@ -140,7 +152,7 @@ if ($resql)
print ' ';
print ' ';
- print_barre_liste($langs->trans("MenuChequeDeposits"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_bank.png', '', '', $limit);
+ print_barre_liste($langs->trans("MenuChequeDeposits"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_bank.png', 0, $newcardbutton, '', $limit);
$moreforfilter='';
@@ -183,7 +195,6 @@ if ($resql)
if ($num > 0)
{
- $var=true;
while ($i < min($num,$limit))
{
$objp = $db->fetch_object($resql);
diff --git a/htdocs/compta/paiement/class/cpaiement.class.php b/htdocs/compta/paiement/class/cpaiement.class.php
index b089cac6aab..59f13023b24 100644
--- a/htdocs/compta/paiement/class/cpaiement.class.php
+++ b/htdocs/compta/paiement/class/cpaiement.class.php
@@ -107,7 +107,7 @@ class Cpaiement
// Insert request
$sql = 'INSERT INTO ' . MAIN_DB_PREFIX . $this->table_element . '(';
- $sql.= 'id,';
+ $sql.= 'entity,';
$sql.= 'code,';
$sql.= 'libelle,';
$sql.= 'type,';
@@ -118,7 +118,7 @@ class Cpaiement
$sql .= ') VALUES (';
- $sql .= ' '.(! isset($this->id)?'NULL':$this->id).',';
+ $sql .= ' '.(! isset($this->entity)?getEntity('c_paiement'):$this->entity).',';
$sql .= ' '.(! isset($this->code)?'NULL':"'".$this->db->escape($this->code)."'").',';
$sql .= ' '.(! isset($this->libelle)?'NULL':"'".$this->db->escape($this->libelle)."'").',';
$sql .= ' '.(! isset($this->type)?'NULL':$this->type).',';
@@ -186,7 +186,8 @@ class Cpaiement
$sql .= " t.module";
$sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t';
if (null !== $ref) {
- $sql .= ' WHERE t.code = ' . '\'' . $ref . '\'';
+ $sql .= ' WHERE t.entity IN ('.getEntity('c_paiement').')';
+ $sql .= ' AND t.code = ' . '\'' . $ref . '\'';
} else {
$sql .= ' WHERE t.id = ' . $id;
}
diff --git a/htdocs/compta/paiement/class/paiement.class.php b/htdocs/compta/paiement/class/paiement.class.php
index 088e14c5543..539c70f591b 100644
--- a/htdocs/compta/paiement/class/paiement.class.php
+++ b/htdocs/compta/paiement/class/paiement.class.php
@@ -60,6 +60,7 @@ class Paiement extends CommonObject
// de llx_paiement qui est lie aux types de
//paiement de llx_c_paiement
var $num_paiement; // Numero du CHQ, VIR, etc...
+ var $num_payment; // Numero du CHQ, VIR, etc...
var $bank_account; // Id compte bancaire du paiement
var $bank_line; // Id de la ligne d'ecriture bancaire
// fk_paiement dans llx_paiement est l'id du type de paiement (7 pour CHQ, ...)
@@ -89,7 +90,7 @@ class Paiement extends CommonObject
{
$sql = 'SELECT p.rowid, p.ref, p.datep as dp, p.amount, p.statut, p.fk_bank,';
$sql.= ' c.code as type_code, c.libelle as type_libelle,';
- $sql.= ' p.num_paiement, p.note,';
+ $sql.= ' p.num_paiement as num_payment, p.note,';
$sql.= ' b.fk_account';
$sql.= ' FROM '.MAIN_DB_PREFIX.'paiement as p LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id';
$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid';
@@ -111,7 +112,9 @@ class Paiement extends CommonObject
$this->ref = $obj->ref?$obj->ref:$obj->rowid;
$this->date = $this->db->jdate($obj->dp);
$this->datepaye = $this->db->jdate($obj->dp);
- $this->numero = $obj->num_paiement;
+ $this->numero = $obj->num_payment; // deprecated
+ $this->num_paiement = $obj->num_payment; // deprecated
+ $this->num_payment = $obj->num_payment;
$this->montant = $obj->amount; // deprecated
$this->amount = $obj->amount;
$this->note = $obj->note;
@@ -210,9 +213,10 @@ class Paiement extends CommonObject
$total = $totalamount_converted; // Maybe use price2num with MT for the converted value
$mtotal = $totalamount;
}
+ $note = ($this->note_public?$this->note_public:$this->note);
$sql = "INSERT INTO ".MAIN_DB_PREFIX."paiement (entity, ref, datec, datep, amount, multicurrency_amount, fk_paiement, num_paiement, note, fk_user_creat)";
- $sql.= " VALUES (".$conf->entity.", '".$this->ref."', '". $this->db->idate($now)."', '".$this->db->idate($this->datepaye)."', '".$total."', '".$mtotal."', ".$this->paiementid.", '".$this->num_paiement."', '".$this->db->escape($this->note)."', ".$user->id.")";
+ $sql.= " VALUES (".$conf->entity.", '".$this->ref."', '". $this->db->idate($now)."', '".$this->db->idate($this->datepaye)."', '".$total."', '".$mtotal."', ".$this->paiementid.", '".$this->num_paiement."', '".$this->db->escape($note)."', ".$user->id.")";
dol_syslog(get_class($this)."::Create insert paiement", LOG_DEBUG);
$resql = $this->db->query($sql);
@@ -532,7 +536,7 @@ class Paiement extends CommonObject
{
if ($accountid <= 0)
{
- $this->error='Bad value for parameter accountid';
+ $this->error='Bad value for parameter accountid='.$accountid;
dol_syslog(get_class($this).'::addPaymentToBank '.$this->error, LOG_ERR);
return -1;
}
diff --git a/htdocs/compta/paiement/info.php b/htdocs/compta/paiement/info.php
index d0bda152b21..9f55761dba0 100644
--- a/htdocs/compta/paiement/info.php
+++ b/htdocs/compta/paiement/info.php
@@ -28,8 +28,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
-$langs->load("bills");
-$langs->load("companies");
+// Load translation files required by the page
+$langs->loadLangs(array('bills', 'companies'));
$id=GETPOST('id');
$ref=GETPOST('ref', 'alpha');
diff --git a/htdocs/compta/paiement/list.php b/htdocs/compta/paiement/list.php
index 595c9e868dc..064ca877c3f 100644
--- a/htdocs/compta/paiement/list.php
+++ b/htdocs/compta/paiement/list.php
@@ -6,6 +6,7 @@
* Copyright (C) 2015 Jean-François Ferry
* Copyright (C) 2015 Juanjo Menent
* Copyright (C) 2017 Alexandre Spangaro
+ * Copyright (C) 2018 Ferran Marcet
*
* 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
@@ -34,8 +35,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php';
-$langs->load("bills");
-$langs->load("compta");
+// Load translation files required by the page
+$langs->loadLangs(array('bills', 'compta'));
// Security check
$facid = GETPOST('facid','int');
@@ -59,7 +60,7 @@ $search_amount=GETPOST("search_amount",'alpha'); // alpha because we must be
$search_company=GETPOST("search_company",'alpha');
$search_payment_num=GETPOST('search_payment_num','alpha');
-$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit;
+$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit;
$sortfield = GETPOST("sortfield",'alpha');
$sortorder = GETPOST("sortorder",'alpha');
$page = GETPOST("page",'int');
@@ -138,7 +139,7 @@ else
$reshook=$hookmanager->executeHooks('printFieldListSelect',$parameters); // Note that $action and $object may have been modified by hook
$sql.=$hookmanager->resPrint;
$sql.= " FROM ".MAIN_DB_PREFIX."paiement as p";
- $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON p.fk_paiement = c.id AND c.entity IN (" . getEntity('c_paiement') . ")";
+ $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON p.fk_paiement = c.id";
$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON p.fk_bank = b.rowid";
$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid";
$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON p.rowid = pf.fk_paiement";
@@ -191,6 +192,11 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
{
$result = $db->query($sql);
$nbtotalofrecords = $db->num_rows($result);
+ if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0
+ {
+ $page = 0;
+ $offset = 0;
+ }
}
$sql.= $db->plimit($limit+1, $offset);
@@ -229,21 +235,21 @@ if ($resql)
// Lines for filters fields
print '';
print '';
- print ' ';
+ print ' ';
print ' ';
print '';
- if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ' ';
- print ' ';
+ if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ' ';
+ print ' ';
$formother->select_year($year?$year:-1,'year',1, 20, 5);
print ' ';
print '';
- print ' ';
+ print ' ';
print ' ';
print '';
$form->select_types_paiements($search_paymenttype,'search_paymenttype','',2,1,1);
print ' ';
print '';
- print ' ';
+ print ' ';
print ' ';
if (! empty($conf->banque->enabled))
{
@@ -252,7 +258,7 @@ if ($resql)
print '';
}
print '';
- print ' ';
+ print ' ';
print ' ';
print '';
$searchpicto=$form->showFilterAndCheckAddButtons(0);
@@ -278,7 +284,7 @@ if ($resql)
print_liste_field_titre("Amount",$_SERVER["PHP_SELF"],"p.amount","",$param,'align="right"',$sortfield,$sortorder);
//print_liste_field_titre("Invoices"),"","","",$param,'align="left"',$sortfield,$sortorder);
- $parameters=array();
+ $parameters=array('arrayfields'=>$arrayfields,'param'=>$param,'sortfield'=>$sortfield,'sortorder'=>$sortorder);
$reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;
diff --git a/htdocs/compta/paiement/avalider.php b/htdocs/compta/paiement/tovalidate.php
similarity index 89%
rename from htdocs/compta/paiement/avalider.php
rename to htdocs/compta/paiement/tovalidate.php
index beb2fb77ecd..e60f65f924e 100644
--- a/htdocs/compta/paiement/avalider.php
+++ b/htdocs/compta/paiement/tovalidate.php
@@ -17,13 +17,14 @@
*/
/**
- * \file htdocs/compta/paiement/avalider.php
+ * \file htdocs/compta/paiement/tovalidate.php
* \ingroup compta
- * \brief Page liste des paiements a valider des factures clients
+ * \brief Page list payment to validate. Visible in menu when option BILL_ADD_PAYMENT_VALIDATION is on.
*/
require '../../main.inc.php';
+// Load translation files required by the page
$langs->load("bills");
// Security check
@@ -38,7 +39,7 @@ if ($user->societe_id > 0)
}
-$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit;
+$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit;
$sortfield = GETPOST('sortfield','alpha');
$sortorder = GETPOST('sortorder','alpha');
$page = GETPOST('page','int');
@@ -85,6 +86,11 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
{
$result = $db->query($sql);
$nbtotalofrecords = $db->num_rows($result);
+ if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0
+ {
+ $page = 0;
+ $offset = 0;
+ }
}
$sql.= $db->plimit($limit + 1,$offset);
@@ -94,7 +100,6 @@ if ($resql)
{
$num = $db->num_rows($resql);
$i = 0;
- $var=True;
print_barre_liste($langs->trans("ReceivedCustomersPaymentsToValid"), $page, $_SERVER["PHP_SELF"],"",$sortfield,$sortorder,'',$num);
diff --git a/htdocs/compta/paiement_charge.php b/htdocs/compta/paiement_charge.php
index e966eba4a47..fba8723d818 100644
--- a/htdocs/compta/paiement_charge.php
+++ b/htdocs/compta/paiement_charge.php
@@ -27,6 +27,7 @@ require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php'
require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/paymentsocialcontribution.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
+// Load translation files required by the page
$langs->load("bills");
$chid=GETPOST("id", 'int');
@@ -271,7 +272,6 @@ if ($action == 'create')
print ' '.$langs->trans("Amount").' ';
print " \n";
- $var=true;
$total=0;
$totalrecu=0;
@@ -279,8 +279,6 @@ if ($action == 'create')
{
$objp = $charge;
-
-
print '';
if ($objp->date_ech > 0)
@@ -324,7 +322,7 @@ if ($action == 'create')
if ($i > 1)
{
// Print total
- print " ";
+ print ' ';
print ''.$langs->trans("Total").': ';
print "".price($total_ttc)." ";
print "".price($totalrecu)." ";
diff --git a/htdocs/compta/payment_sc/card.php b/htdocs/compta/payment_sc/card.php
index ea9bc5af42a..b395016aeed 100644
--- a/htdocs/compta/payment_sc/card.php
+++ b/htdocs/compta/payment_sc/card.php
@@ -32,9 +32,8 @@ require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php';
if (! empty($conf->banque->enabled)) require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
-$langs->load('bills');
-$langs->load('banks');
-$langs->load('companies');
+// Load translation files required by the page
+$langs->loadLangs(array('bills', 'banks', 'companies'));
// Security check
$id=GETPOST("id",'int');
@@ -245,13 +244,10 @@ if ($resql)
if ($num > 0)
{
- $var=True;
-
while ($i < $num)
{
$objp = $db->fetch_object($resql);
-
print ' ';
// Ref
print '';
diff --git a/htdocs/compta/prelevement/bons.php b/htdocs/compta/prelevement/bons.php
index 9d3da39e5c3..0cbaa9ce55e 100644
--- a/htdocs/compta/prelevement/bons.php
+++ b/htdocs/compta/prelevement/bons.php
@@ -28,16 +28,15 @@ require('../../main.inc.php');
require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
-$langs->load("banks");
-$langs->load("categories");
-$langs->load("widthdrawals");
+// Load translation files required by the page
+$langs->loadLangs(array('banks', 'categories', 'widthdrawals'));
// Security check
$socid = GETPOST('socid','int');
if ($user->societe_id) $socid=$user->societe_id;
$result = restrictedArea($user, 'prelevement','','','bons');
-$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit;
+$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit;
$sortfield = GETPOST('sortfield','alpha');
$sortorder = GETPOST('sortorder','alpha');
$page = GETPOST('page','int');
@@ -87,6 +86,11 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
{
$result = $db->query($sql);
$nbtotalofrecords = $db->num_rows($result);
+ if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0
+ {
+ $page = 0;
+ $offset = 0;
+ }
}
$sql.= $db->plimit($limit + 1,$offset);
@@ -101,6 +105,14 @@ if ($result)
$selectedfields='';
+ $newcardbutton='';
+ if ($user->rights->prelevement->bons->creer)
+ {
+ $newcardbutton = ''.$langs->trans('NewStandingOrder').' ';
+ $newcardbutton.= ' ';
+ $newcardbutton.= ' ';
+ }
+
// Lines of title fields
print '';
if ($optioncss != '') print ' ';
@@ -112,7 +124,7 @@ if ($result)
print ' ';
print ' ';
- print_barre_liste($langs->trans("WithdrawalsReceipts"), $page, $_SERVER["PHP_SELF"], $urladd, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_generic', 0, '', '', $limit);
+ print_barre_liste($langs->trans("WithdrawalsReceipts"), $page, $_SERVER["PHP_SELF"], $urladd, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_generic', 0, $newcardbutton, '', $limit);
$moreforfilter='';
diff --git a/htdocs/compta/prelevement/card.php b/htdocs/compta/prelevement/card.php
index ed0977ebabf..343a45472b6 100644
--- a/htdocs/compta/prelevement/card.php
+++ b/htdocs/compta/prelevement/card.php
@@ -29,8 +29,8 @@ require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/ligneprelevement.class
require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
-$langs->load("banks");
-$langs->load("categories");
+// Load translation files required by the page
+$langs->loadLangs(array('banks', 'categories'));
if (!$user->rights->prelevement->bons->lire)
accessforbidden();
@@ -322,6 +322,11 @@ if ($id > 0 || $ref)
{
$result = $db->query($sql);
$nbtotalofrecords = $db->num_rows($result);
+ if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0
+ {
+ $page = 0;
+ $offset = 0;
+ }
}
$sql.= $db->plimit($limit+1, $offset);
diff --git a/htdocs/compta/prelevement/class/bonprelevement.class.php b/htdocs/compta/prelevement/class/bonprelevement.class.php
index d0aa788fe48..245b25be3b6 100644
--- a/htdocs/compta/prelevement/class/bonprelevement.class.php
+++ b/htdocs/compta/prelevement/class/bonprelevement.class.php
@@ -4,6 +4,7 @@
* Copyright (C) 2010-2015 Juanjo Menent
* Copyright (C) 2010-2014 Laurent Destailleur
* Copyright (C) 2014-2016 Ferran Marcet
+ * Copyright (C) 2018 Nicolas ZABOURI
*
* 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
@@ -98,14 +99,6 @@ class BonPrelevement extends CommonObject
$this->methodes_trans[0] = "Internet";
$this->_fetched = 0;
-
-
- $langs->load("withdrawals");
- $this->labelstatut[0]=$langs->trans("StatusWaiting");
- $this->labelstatut[1]=$langs->trans("StatusTrans");
- $this->labelstatut[2]=$langs->trans("StatusCredited");
-
- return 1;
}
/**
@@ -726,16 +719,12 @@ class BonPrelevement extends CommonObject
$sql = "SELECT count(f.rowid) as nb";
$sql.= " FROM ".MAIN_DB_PREFIX."facture as f";
$sql.= ", ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
- //if ($banque || $agence) $sql.=", ".MAIN_DB_PREFIX."societe_rib as sr";
$sql.= " WHERE f.fk_statut = 1";
$sql.= " AND f.entity = ".$conf->entity;
$sql.= " AND f.rowid = pfd.fk_facture";
$sql.= " AND f.paye = 0";
$sql.= " AND pfd.traite = 0";
$sql.= " AND f.total_ttc > 0";
- //if ($banque || $agence) $sql.= " AND f.fk_soc = sr.rowid";
- //if ($banque) $sql.= " AND sr.code_banque = '".$conf->global->PRELEVEMENT_CODE_BANQUE."'";
- //if ($agence) $sql.= " AND sr.code_guichet = '".$conf->global->PRELEVEMENT_CODE_GUICHET."'";
dol_syslog(get_class($this)."::SommeAPrelever");
$resql = $this->db->query($sql);
@@ -764,9 +753,10 @@ class BonPrelevement extends CommonObject
* @param int $agence dolibarr mysoc bank office (guichet)
* @param string $mode real=do action, simu=test only
* @param string $format FRST, RCUR or ALL
+ * @param string $executiondate Date to execute the transfer
* @return int <0 if KO, nbre of invoice withdrawed if OK
*/
- function Create($banque=0, $agence=0, $mode='real', $format='ALL')
+ function Create($banque=0, $agence=0, $mode='real', $format='ALL',$executiondate='')
{
global $conf,$langs;
@@ -780,6 +770,8 @@ class BonPrelevement extends CommonObject
$error = 0;
$datetimeprev = time();
+ //Choice the date of the execution direct debit
+ if(!empty($executiondate)) $datetimeprev = $executiondate;
$month = strftime("%m", $datetimeprev);
$year = strftime("%Y", $datetimeprev);
@@ -805,9 +797,8 @@ class BonPrelevement extends CommonObject
$sql.= " FROM ".MAIN_DB_PREFIX."facture as f";
$sql.= ", ".MAIN_DB_PREFIX."societe as s";
$sql.= ", ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
- //if ($banque || $agence) $sql.= ", ".MAIN_DB_PREFIX."societe_rib as sr";
$sql.= " WHERE f.rowid = pfd.fk_facture";
- $sql.= " AND f.entity = ".$conf->entity;
+ $sql.= " AND f.entity IN (".getEntity('facture').')';
$sql.= " AND s.rowid = f.fk_soc";
//if ($banque || $agence) $sql.= " AND s.rowid = sr.fk_soc";
$sql.= " AND f.fk_statut = 1";
@@ -1082,7 +1073,7 @@ class BonPrelevement extends CommonObject
$this->factures = $factures_prev_id;
// Generation of SEPA file $this->filename
- $this->generate($format);
+ $this->generate($format,$executiondate);
}
dol_syslog(__METHOD__."::End withdraw receipt, file ".$this->filename, LOG_DEBUG);
}
@@ -1279,9 +1270,10 @@ class BonPrelevement extends CommonObject
* File is generated with name this->filename
*
* @param string $format FRST, RCUR or ALL
+ * @param string $executiondate Date to execute transfer
* @return int 0 if OK, <0 if KO
*/
- function generate($format='ALL')
+ function generate($format='ALL',$executiondate='')
{
global $conf,$langs,$mysoc;
@@ -1310,10 +1302,16 @@ class BonPrelevement extends CommonObject
*/
// SEPA Initialisation
$CrLf = "\n";
- $date_actu = dol_now();
+
+ $now = dol_now();
+
+ $dateTime_ECMA = dol_print_date($now, '%Y-%m-%dT%H:%M:%S');
+
+ $date_actu = $now;
+ if (!empty($executiondate)) $date_actu=$executiondate;
+
$dateTime_YMD = dol_print_date($date_actu, '%Y%m%d');
$dateTime_YMDHMS = dol_print_date($date_actu, '%Y%m%d%H%M%S');
- $dateTime_ECMA = dol_print_date($date_actu, '%Y-%m-%dT%H:%M:%S');
$fileDebiteurSection = '';
$fileEmetteurSection = '';
$i = 0;
@@ -1340,6 +1338,7 @@ class BonPrelevement extends CommonObject
$sql.= " AND soc.rowid = f.fk_soc";
$sql.= " AND rib.fk_soc = f.fk_soc";
$sql.= " AND rib.default_rib = 1";
+ $sql.= " AND rib.type = 'ban'";
//print $sql;
// Define $fileDebiteurSection. One section DrctDbtTxInf per invoice.
@@ -1883,48 +1882,52 @@ class BonPrelevement extends CommonObject
*/
function LibStatut($statut,$mode=0)
{
- global $langs;
+ if (empty($this->labelstatut))
+ {
+ global $langs;
+ $langs->load("withdrawals");
+ $this->labelstatut[0]=$langs->trans("StatusWaiting");
+ $this->labelstatut[1]=$langs->trans("StatusTrans");
+ $this->labelstatut[2]=$langs->trans("StatusCredited");
+ }
if ($mode == 0)
{
- return $langs->trans($this->labelstatut[$statut]);
+ return $this->labelstatut[$statut];
}
-
if ($mode == 1)
{
- if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1').' '.$langs->trans($this->labelstatut[$statut]);
- if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut3').' '.$langs->trans($this->labelstatut[$statut]);
- if ($statut==2) return img_picto($langs->trans($this->labelstatut[$statut]),'statut6').' '.$langs->trans($this->labelstatut[$statut]);
+ return $this->labelstatut[$statut];
}
if ($mode == 2)
{
- if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1');
- if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut3');
- if ($statut==2) return img_picto($langs->trans($this->labelstatut[$statut]),'statut6');
+ if ($statut==0) return img_picto($this->labelstatut[$statut],'statut1').' '.$this->labelstatut[$statut];
+ if ($statut==1) return img_picto($this->labelstatut[$statut],'statut3').' '.$this->labelstatut[$statut];
+ if ($statut==2) return img_picto($this->labelstatut[$statut],'statut6').' '.$this->labelstatut[$statut];
}
if ($mode == 3)
{
- if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1');
- if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut3');
- if ($statut==2) return img_picto($langs->trans($this->labelstatut[$statut]),'statut6');
+ if ($statut==0) return img_picto($this->labelstatut[$statut],'statut1');
+ if ($statut==1) return img_picto($this->labelstatut[$statut],'statut3');
+ if ($statut==2) return img_picto($this->labelstatut[$statut],'statut6');
}
if ($mode == 4)
{
- if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1').' '.$langs->trans($this->labelstatut[$statut]);
- if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut3').' '.$langs->trans($this->labelstatut[$statut]);
- if ($statut==2) return img_picto($langs->trans($this->labelstatut[$statut]),'statut6').' '.$langs->trans($this->labelstatut[$statut]);
+ if ($statut==0) return img_picto($this->labelstatut[$statut],'statut1').' '.$this->labelstatut[$statut];
+ if ($statut==1) return img_picto($this->labelstatut[$statut],'statut3').' '.$this->labelstatut[$statut];
+ if ($statut==2) return img_picto($this->labelstatut[$statut],'statut6').' '.$this->labelstatut[$statut];
}
if ($mode == 5)
{
- if ($statut==0) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut1');
- if ($statut==1) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut3');
- if ($statut==2) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut6');
+ if ($statut==0) return $this->labelstatut[$statut].' '.img_picto($this->labelstatut[$statut],'statut1');
+ if ($statut==1) return $this->labelstatut[$statut].' '.img_picto($this->labelstatut[$statut],'statut3');
+ if ($statut==2) return $this->labelstatut[$statut].' '.img_picto($this->labelstatut[$statut],'statut6');
}
if ($mode == 6)
{
- if ($statut==0) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut1');
- if ($statut==1) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut3');
- if ($statut==2) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut6');
+ if ($statut==0) return $this->labelstatut[$statut].' '.img_picto($this->labelstatut[$statut],'statut1');
+ if ($statut==1) return $this->labelstatut[$statut].' '.img_picto($this->labelstatut[$statut],'statut3');
+ if ($statut==2) return $this->labelstatut[$statut].' '.img_picto($this->labelstatut[$statut],'statut6');
}
}
diff --git a/htdocs/compta/prelevement/create.php b/htdocs/compta/prelevement/create.php
index af49e849e9f..9cc2cf77867 100644
--- a/htdocs/compta/prelevement/create.php
+++ b/htdocs/compta/prelevement/create.php
@@ -3,6 +3,7 @@
* Copyright (C) 2010-2015 Laurent Destailleur
* Copyright (C) 2005-2009 Regis Houssin
* Copyright (C) 2010-2012 Juanjo Menent
+ * Copyright (C) 2018 Nicolas ZABOURI
*
* 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
@@ -33,11 +34,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/prelevement.lib.php';
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
-$langs->load("banks");
-$langs->load("categories");
-$langs->load("widthdrawals");
-$langs->load("companies");
-$langs->load("bills");
+// Load translation files required by the page
+$langs->loadLangs(array('banks', 'categories', 'widthdrawals', 'companies', 'bills'));
// Security check
if ($user->societe_id) $socid=$user->societe_id;
@@ -68,7 +66,9 @@ if ($action == 'create')
{
// $conf->global->PRELEVEMENT_CODE_BANQUE and $conf->global->PRELEVEMENT_CODE_GUICHET should be empty
$bprev = new BonPrelevement($db);
- $result=$bprev->create($conf->global->PRELEVEMENT_CODE_BANQUE, $conf->global->PRELEVEMENT_CODE_GUICHET, $mode, $format);
+ $executiondate = dol_mktime(0, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
+
+ $result = $bprev->create($conf->global->PRELEVEMENT_CODE_BANQUE, $conf->global->PRELEVEMENT_CODE_GUICHET, $mode, $format,$executiondate);
if ($result < 0)
{
setEventMessages($bprev->error, $bprev->errors, 'errors');
@@ -93,6 +93,7 @@ if ($action == 'create')
/*
* View
*/
+$form = new Form($db);
$thirdpartystatic=new Societe($db);
$invoicestatic=new Facture($db);
@@ -147,23 +148,22 @@ print '';
if ($mesg) print $mesg;
print " ';
- $var=True;
-
while ($i < min($num,$limit))
{
$obj = $db->fetch_object($result);
diff --git a/htdocs/compta/prelevement/demandes.php b/htdocs/compta/prelevement/demandes.php
index 04ec746d7f6..d20f92cb188 100644
--- a/htdocs/compta/prelevement/demandes.php
+++ b/htdocs/compta/prelevement/demandes.php
@@ -30,10 +30,8 @@ require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
-$langs->load("banks");
-$langs->load("categories");
-$langs->load("withdrawals");
-$langs->load("companies");
+// Load translation files required by the page
+$langs->loadLangs(array('banks', 'categories', 'withdrawals', 'companies'));
// Security check
$socid = GETPOST('socid','int');
@@ -129,8 +127,6 @@ if ($resql)
print '';
print '';
- $var = True;
-
$users = array();
while ($i < min($num,$limit))
diff --git a/htdocs/compta/prelevement/factures.php b/htdocs/compta/prelevement/factures.php
index 64811c7604a..2eabd64873d 100644
--- a/htdocs/compta/prelevement/factures.php
+++ b/htdocs/compta/prelevement/factures.php
@@ -31,11 +31,8 @@ require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/rejetprelevement.class
require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
-$langs->load("banks");
-$langs->load("categories");
-$langs->load("companies");
-$langs->load('withdrawals');
-$langs->load('bills');
+// Load translation files required by the page
+$langs->loadLangs(array('banks', 'categories', 'companies', 'withdrawals', 'bills'));
// Securite acces client
if ($user->societe_id > 0) accessforbidden();
@@ -170,6 +167,11 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
{
$result = $db->query($sql);
$nbtotalofrecords = $db->num_rows($result);
+ if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0
+ {
+ $page = 0;
+ $offset = 0;
+ }
}
$sql.= $db->plimit($limit + 1,$offset);
diff --git a/htdocs/compta/prelevement/fiche-rejet.php b/htdocs/compta/prelevement/fiche-rejet.php
index 82431e3bdd2..113153bc896 100644
--- a/htdocs/compta/prelevement/fiche-rejet.php
+++ b/htdocs/compta/prelevement/fiche-rejet.php
@@ -31,6 +31,7 @@ require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/rejetprelevement.class
require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
+// Load translation files required by the page
$langs->loadLangs(array("banks","categories",'withdrawals','bills'));
// Securite acces client
@@ -169,6 +170,11 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
{
$result = $db->query($sql);
$nbtotalofrecords = $db->num_rows($result);
+ if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0
+ {
+ $page = 0;
+ $offset = 0;
+ }
}
$sql.= $db->plimit($limit+1, $offset);
diff --git a/htdocs/compta/prelevement/fiche-stat.php b/htdocs/compta/prelevement/fiche-stat.php
index f0e335da5cf..c126212f17c 100644
--- a/htdocs/compta/prelevement/fiche-stat.php
+++ b/htdocs/compta/prelevement/fiche-stat.php
@@ -29,6 +29,7 @@ require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.p
require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/ligneprelevement.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
+// Load translation files required by the page
$langs->loadLangs(array("banks","categories",'withdrawals','bills'));
// Security check
diff --git a/htdocs/compta/prelevement/index.php b/htdocs/compta/prelevement/index.php
index 271ce4da7fe..de99b56eb19 100644
--- a/htdocs/compta/prelevement/index.php
+++ b/htdocs/compta/prelevement/index.php
@@ -33,9 +33,8 @@ require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/prelevement.lib.php';
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
-$langs->load("banks");
-$langs->load("categories");
-$langs->load("withdrawals");
+// Load translation files required by the page
+$langs->loadLangs(array('banks', 'categories', 'withdrawals'));
// Security check
$socid = GETPOST('socid','int');
@@ -71,7 +70,6 @@ print '';
$thirdpartystatic=new Societe($db);
$invoicestatic=new Facture($db);
$bprev = new BonPrelevement($db);
-$var=true;
print '
';
print ''.$langs->trans("Statistics").' ';
@@ -117,7 +115,6 @@ if ($resql)
print ''.$langs->trans("InvoiceWaitingWithdraw").' ('.$num.') ';
if ($num)
{
- $var = True;
while ($i < $num && $i < 20)
{
$obj = $db->fetch_object($resql);
@@ -184,7 +181,6 @@ if ($result)
{
$num = $db->num_rows($result);
$i = 0;
- $var=True;
print"\n\n";
print '';
diff --git a/htdocs/compta/prelevement/ligne.php b/htdocs/compta/prelevement/ligne.php
index 20ac3d18082..721cf62bcd7 100644
--- a/htdocs/compta/prelevement/ligne.php
+++ b/htdocs/compta/prelevement/ligne.php
@@ -31,15 +31,12 @@ require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/rejetprelevement.class
require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
-$langs->load("banks");
-$langs->load("categories");
+// Load translation files required by the page
+$langs->loadlangs(array('banks', 'categories', 'bills', 'withdrawals'));
// Security check
if ($user->societe_id > 0) accessforbidden();
-$langs->load("bills");
-$langs->load("withdrawals");
-
// Get supervariables
$action = GETPOST('action','alpha');
$id = GETPOST('id','int');
diff --git a/htdocs/compta/prelevement/list.php b/htdocs/compta/prelevement/list.php
index ff6fe4e109c..8d657f00221 100644
--- a/htdocs/compta/prelevement/list.php
+++ b/htdocs/compta/prelevement/list.php
@@ -29,10 +29,8 @@ require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.p
require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/ligneprelevement.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
-$langs->load("banks");
-$langs->load("withdrawals");
-$langs->load("companies");
-$langs->load("categories");
+// Load translation files required by the page
+$langs->loadLangs(array('banks', 'withdrawals', 'companies', 'categories'));
// Security check
$socid = GETPOST('socid','int');
@@ -40,7 +38,7 @@ if ($user->societe_id) $socid=$user->societe_id;
$result = restrictedArea($user, 'prelevement','','','bons');
-$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit;
+$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit;
$sortfield = GETPOST('sortfield','alpha');
$sortorder = GETPOST('sortorder','alpha');
$page = GETPOST('page','int');
@@ -111,6 +109,11 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
{
$result = $db->query($sql);
$nbtotalofrecords = $db->num_rows($result);
+ if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0
+ {
+ $page = 0;
+ $offset = 0;
+ }
}
$sql.= $db->plimit($limit + 1,$offset);
diff --git a/htdocs/compta/prelevement/rejets.php b/htdocs/compta/prelevement/rejets.php
index 3c18207f451..c8812bba1a9 100644
--- a/htdocs/compta/prelevement/rejets.php
+++ b/htdocs/compta/prelevement/rejets.php
@@ -30,10 +30,8 @@ require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/ligneprelevement.class
require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
-$langs->load("banks");
-$langs->load("categories");
-$langs->load("withdrawals");
-$langs->load("companies");
+// Load translation files required by the page
+$langs->loadLangs(array('banks', 'categories', 'withdrawals', 'companies'));
// Security check
$socid = GETPOST('socid','int');
diff --git a/htdocs/compta/prelevement/stats.php b/htdocs/compta/prelevement/stats.php
index 406c2303b6a..20d213e820b 100644
--- a/htdocs/compta/prelevement/stats.php
+++ b/htdocs/compta/prelevement/stats.php
@@ -28,10 +28,8 @@ require('../../main.inc.php');
require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/ligneprelevement.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
-$langs->load("banks");
-$langs->load("categories");
-$langs->load("withdrawals");
-$langs->load("companies");
+// Load translation files required by the page
+$langs->loadLangs(array('banks', 'categories', 'withdrawals', 'companies'));
// Security check
$socid = GETPOST('socid','int');
diff --git a/htdocs/compta/recap-compta.php b/htdocs/compta/recap-compta.php
index dd320ebbeec..3a22666e2f7 100644
--- a/htdocs/compta/recap-compta.php
+++ b/htdocs/compta/recap-compta.php
@@ -28,6 +28,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
+// Load translation files required by the page
$langs->load("companies");
if (! empty($conf->facture->enabled)) $langs->load("bills");
@@ -128,7 +129,6 @@ if ($id > 0)
$resql=$db->query($sql);
if ($resql)
{
- $var=true;
$num = $db->num_rows($resql);
// Boucle sur chaque facture
diff --git a/htdocs/compta/resultat/clientfourn.php b/htdocs/compta/resultat/clientfourn.php
index b717b58edd2..c9e32b9a97f 100644
--- a/htdocs/compta/resultat/clientfourn.php
+++ b/htdocs/compta/resultat/clientfourn.php
@@ -36,6 +36,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/tax.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountancycategory.class.php';
+// Load translation files required by the page
$langs->loadLangs(array('compta','bills','donation','salaries','accountancy'));
$date_startmonth=GETPOST('date_startmonth','int');
@@ -822,7 +823,7 @@ else
$sql.= " FROM ".MAIN_DB_PREFIX."expensereport as p";
$sql.= " INNER JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid=p.fk_user_author";
$sql.= " INNER JOIN ".MAIN_DB_PREFIX."payment_expensereport as pe ON pe.fk_expensereport = p.rowid";
- $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id AND c.entity IN (".getEntity('c_paiement').")";
+ $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id";
$sql.= " WHERE p.entity IN (".getEntity('expensereport').")";
$sql.= " AND p.fk_statut>=5";
@@ -906,7 +907,7 @@ else
$sql = "SELECT p.societe as nom, p.firstname, p.lastname, date_format(p.datedon,'%Y-%m') as dm, sum(p.amount) as amount";
$sql.= " FROM ".MAIN_DB_PREFIX."don as p";
$sql.= " INNER JOIN ".MAIN_DB_PREFIX."payment_donation as pe ON pe.fk_donation = p.rowid";
- $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id AND c.entity IN (".getEntity('c_paiement').")";
+ $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id";
$sql.= " WHERE p.entity IN (".getEntity('donation').")";
$sql.= " AND fk_statut >= 2";
}
diff --git a/htdocs/compta/resultat/index.php b/htdocs/compta/resultat/index.php
index 1bbb8eca2cf..fbbc7a36eef 100644
--- a/htdocs/compta/resultat/index.php
+++ b/htdocs/compta/resultat/index.php
@@ -30,6 +30,7 @@ require '../../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
+// Load translation files required by the page
$langs->loadLangs(array('compta','bills','donation','salaries'));
$date_startmonth=GETPOST('date_startmonth','int');
@@ -90,7 +91,7 @@ $tmps=dol_getdate($date_start);
$year_start = $tmps['year'];
$tmpe=dol_getdate($date_end);
$year_end = $tmpe['year'];
-$nbofyear = ($year_end - $start_year) + 1;
+$nbofyear = ($year_end - $year_start) + 1;
//var_dump("year_start=".$year_start." year_end=".$year_end." nbofyear=".$nbofyear." date_start=".dol_print_date($date_start, 'dayhour')." date_end=".dol_print_date($date_end, 'dayhour'));
@@ -692,7 +693,7 @@ if (! empty($conf->expensereport->enabled) && ($modecompta == 'CREANCES-DETTES'
$sql.= " FROM ".MAIN_DB_PREFIX."expensereport as p";
$sql.= " INNER JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid=p.fk_user_author";
$sql.= " INNER JOIN ".MAIN_DB_PREFIX."payment_expensereport as pe ON pe.fk_expensereport = p.rowid";
- $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id AND c.entity IN (".getEntity('c_paiement').")";
+ $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id";
$sql.= " WHERE p.entity IN (".getEntity('expensereport').")";
$sql.= " AND p.fk_statut>=5";
@@ -755,7 +756,7 @@ if (! empty($conf->don->enabled) && ($modecompta == 'CREANCES-DETTES' || $modeco
$sql = "SELECT p.societe as nom, p.firstname, p.lastname, date_format(pe.datep,'%Y-%m') as dm, sum(p.amount) as amount";
$sql.= " FROM ".MAIN_DB_PREFIX."don as p";
$sql.= " INNER JOIN ".MAIN_DB_PREFIX."payment_donation as pe ON pe.fk_donation = p.rowid";
- $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id AND c.entity IN (".getEntity('c_paiement').")";
+ $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id";
$sql.= " WHERE p.entity IN (".getEntity('donation').")";
$sql.= " AND fk_statut >= 2";
if (! empty($date_start) && ! empty($date_end))
@@ -840,9 +841,13 @@ if (! empty($conf->accounting->enabled) && ($modecompta == 'BOOKKEEPING'))
$obj = $db->fetch_object($result);
if (! isset($encaiss[$obj->dm])) $encaiss[$obj->dm]=0;
- $encaiss[$obj->dm] += $obj->debit;
+ if (! isset($decaiss[$obj->dm])) $decaiss[$obj->dm]=0;
+ $encaiss[$obj->dm] += $obj->credit;
+ $decaiss[$obj->dm] += $obj->debit;
if (! isset($encaiss_ttc[$obj->dm])) $encaiss_ttc[$obj->dm]=0;
+ if (! isset($decaiss_ttc[$obj->dm])) $decaiss_ttc[$obj->dm]=0;
$encaiss_ttc[$obj->dm] += 0;
+ $decaiss_ttc[$obj->dm] += 0;
$i++;
}
diff --git a/htdocs/compta/resultat/result.php b/htdocs/compta/resultat/result.php
index 7854f6656ed..23c7e91b989 100644
--- a/htdocs/compta/resultat/result.php
+++ b/htdocs/compta/resultat/result.php
@@ -30,6 +30,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php';
require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountancycategory.class.php';
+// Load translation files required by the page
$langs->loadLangs(array('compta','bills','donation','salaries','accountancy'));
$error = 0;
@@ -537,4 +538,4 @@ print "
";
print '';
llxFooter();
-$db->close();
\ No newline at end of file
+$db->close();
diff --git a/htdocs/compta/salaries/card.php b/htdocs/compta/salaries/card.php
index 608b5a737b0..45fee127642 100644
--- a/htdocs/compta/salaries/card.php
+++ b/htdocs/compta/salaries/card.php
@@ -1,8 +1,8 @@
* Copyright (C) 2014 Laurent Destailleur
- * Copyright (C) 2015 Jean-François Ferry
- * Copyright (C) 2015 Charlie BENKE
+ * Copyright (C) 2015 Jean-François Ferry
+ * Copyright (C) 2015 Charlie BENKE
*
* 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
@@ -19,9 +19,9 @@
*/
/**
- * \file htdocs/compta/salaries/card.php
- * \ingroup salaries
- * \brief Page of salaries payments
+ * \file htdocs/compta/salaries/card.php
+ * \ingroup salaries
+ * \brief Page of salaries payments
*/
require '../../main.inc.php';
@@ -30,13 +30,8 @@ require_once DOL_DOCUMENT_ROOT.'/compta/salaries/class/paymentsalary.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/salaries.lib.php';
-
-$langs->load("compta");
-$langs->load("banks");
-$langs->load("bills");
-$langs->load("users");
-$langs->load("salaries");
-$langs->load('hrm');
+// Load translation files required by the page
+$langs->loadLangs(array("compta","banks","bills","users","salaries","hrm"));
$id=GETPOST("id",'int');
$action=GETPOST('action','aZ09');
@@ -73,7 +68,7 @@ if ($action == 'add' && $_POST["cancel"] <> $langs->trans("Cancel"))
$dateep=dol_mktime(12,0,0, $_POST["dateepmonth"], $_POST["dateepday"], $_POST["dateepyear"]);
if (empty($datev)) $datev=$datep;
- $type_payment = dol_getIdFromCode($db, GETPOST("paymenttype", 'alpha'), 'c_paiement');
+ $type_payment = dol_getIdFromCode($db, GETPOST("paymenttype", 'alpha'), 'c_paiement', 'code', 'id', 1);
$object->accountid=GETPOST("accountid") > 0 ? GETPOST("accountid","int") : 0;
$object->fk_user=GETPOST("fk_user") > 0 ? GETPOST("fk_user","int") : 0;
diff --git a/htdocs/compta/salaries/class/paymentsalary.class.php b/htdocs/compta/salaries/class/paymentsalary.class.php
index eab661c6614..3a3f34b85b4 100644
--- a/htdocs/compta/salaries/class/paymentsalary.class.php
+++ b/htdocs/compta/salaries/class/paymentsalary.class.php
@@ -31,9 +31,9 @@ require_once DOL_DOCUMENT_ROOT .'/core/class/commonobject.class.php';
*/
class PaymentSalary extends CommonObject
{
- //public $element='payment_salary'; //!< Id that identify managed objects
- //public $table_element='payment_salary'; //!< Name of table without prefix where object is stored
- public $picto='payment';
+ public $element='payment_salary'; //!< Id that identify managed objects
+ public $table_element='payment_salary'; //!< Name of table without prefix where object is stored
+ public $picto='payment';
public $tms;
public $fk_user;
@@ -388,7 +388,11 @@ class PaymentSalary extends CommonObject
-abs($this->amount),
$this->num_payment,
'',
- $user
+ $user,
+ '',
+ '',
+ '',
+ $this->datev
);
// Update fk_bank into llx_paiement.
diff --git a/htdocs/compta/salaries/class/salariesstats.class.php b/htdocs/compta/salaries/class/salariesstats.class.php
new file mode 100644
index 00000000000..647dc27f4a5
--- /dev/null
+++ b/htdocs/compta/salaries/class/salariesstats.class.php
@@ -0,0 +1,164 @@
+
+ * Copyright (c) 2018 Fidesio
+ *
+ * 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 3 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, see .
+ */
+
+/**
+ * \file htdocs/compta/salaries/class/salariesstats.class.php
+ * \ingroup salaries
+ * \brief Fichier de la classe de gestion des stats des salaires
+ */
+include_once DOL_DOCUMENT_ROOT . '/core/class/stats.class.php';
+include_once DOL_DOCUMENT_ROOT . '/compta/salaries/class/paymentsalary.class.php';
+
+/**
+ * Classe permettant la gestion des stats des salaires
+ */
+class SalariesStats extends Stats
+{
+ public $table_element;
+
+ var $socid;
+ var $userid;
+
+ var $from;
+ var $field;
+ var $where;
+
+ /**
+ * Constructor
+ *
+ * @param DoliDB $db Database handler
+ * @param int $socid Id third party
+ * @param mixed $userid Id user for filter or array of user ids
+ * @return void
+ */
+ function __construct($db, $socid=0, $userid=0)
+ {
+ global $conf;
+
+ $this->db = $db;
+ $this->socid = $socid;
+ $this->userid = $userid;
+
+ $object=new PaymentSalary($this->db);
+ $this->from = MAIN_DB_PREFIX.$object->table_element;
+ $this->field='amount';
+
+ $this->where.= " entity = ".$conf->entity;
+ if ($this->socid)
+ {
+ $this->where.=" AND fk_soc = ".$this->socid;
+ }
+ if (is_array($this->userid) && count($this->userid) > 0) $this->where.=' AND fk_user IN ('.join(',',$this->userid).')';
+ else if ($this->userid > 0) $this->where.=' AND fk_user = '.$this->userid;
+ }
+
+
+ /**
+ * Return the number of salary by year
+ *
+ * @return array Array of values
+ */
+ function getNbByYear()
+ {
+ $sql = "SELECT YEAR(datep) as dm, count(*)";
+ $sql.= " FROM ".$this->from;
+ $sql.= " GROUP BY dm DESC";
+ $sql.= " WHERE ".$this->where;
+
+ return $this->_getNbByYear($sql);
+ }
+
+
+ /**
+ * Return the number of salary by month, for a given year
+ *
+ * @param string $year Year to scan
+ * @param int $format 0=Label of absiss is a translated text, 1=Label of absiss is month number, 2=Label of absiss is first letter of month
+ * @return array Array of values
+ */
+ function getNbByMonth($year, $format=0)
+ {
+ $sql = "SELECT MONTH(datep) as dm, count(*)";
+ $sql.= " FROM ".$this->from;
+ $sql.= " WHERE YEAR(datep) = ".$year;
+ $sql.= " AND ".$this->where;
+ $sql.= " GROUP BY dm";
+ $sql.= $this->db->order('dm','DESC');
+
+ $res=$this->_getNbByMonth($year, $sql, $format);
+ //var_dump($res);print ' ';
+ return $res;
+ }
+
+
+ /**
+ * Return amount of salaries by month for a given year
+ *
+ * @param int $year Year to scan
+ * @param int $format 0=Label of absiss is a translated text, 1=Label of absiss is month number, 2=Label of absiss is first letter of month
+ * @return array Array of values
+ */
+ function getAmountByMonth($year, $format=0)
+ {
+ $sql = "SELECT date_format(datep,'%m') as dm, sum(".$this->field.")";
+ $sql.= " FROM ".$this->from;
+ $sql.= " WHERE date_format(datep,'%Y') = '".$year."'";
+ $sql.= " AND ".$this->where;
+ $sql.= " GROUP BY dm";
+ $sql.= $this->db->order('dm','DESC');
+
+ $res=$this->_getAmountByMonth($year, $sql, $format);
+ //var_dump($res);print ' ';
+ return $res;
+ }
+
+ /**
+ * Return average amount
+ *
+ * @param int $year Year to scan
+ * @return array Array of values
+ */
+ function getAverageByMonth($year)
+ {
+ $sql = "SELECT date_format(datep,'%m') as dm, avg(".$this->field.")";
+ $sql.= " FROM ".$this->from;
+ $sql.= " WHERE date_format(datep,'%Y') = '".$year."'";
+ $sql.= " AND ".$this->where;
+ $sql.= " GROUP BY dm";
+ $sql.= $this->db->order('dm','DESC');
+
+ return $this->_getAverageByMonth($year, $sql);
+ }
+
+ /**
+ * Return nb, total and average
+ *
+ * @return array Array of values
+ */
+ function getAllByYear()
+ {
+ $sql = "SELECT date_format(datep,'%Y') as year, count(*) as nb, sum(".$this->field.") as total, avg(".$this->field.") as avg";
+ $sql.= " FROM ".$this->from;
+ $sql.= " WHERE ".$this->where;
+ $sql.= " GROUP BY year";
+ $sql.= $this->db->order('year','DESC');
+
+ return $this->_getAllByYear($sql);
+ }
+}
+
diff --git a/htdocs/compta/salaries/document.php b/htdocs/compta/salaries/document.php
index 03cef9c07e8..99c34f60815 100644
--- a/htdocs/compta/salaries/document.php
+++ b/htdocs/compta/salaries/document.php
@@ -35,11 +35,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/salaries.lib.php';
require_once DOL_DOCUMENT_ROOT.'/compta/salaries/class/paymentsalary.class.php';
-$langs->load("other");
-$langs->load("users");
-$langs->load("salaries");
-$langs->load('hrm');
-$langs->load("companies");
+// Load translation files required by the page
+$langs->loadLangs(array("compta","bills","users","salaries","hrm"));
$id = GETPOST('id','int');
$ref = GETPOST('ref', 'alpha');
@@ -118,7 +115,7 @@ if ($object->id)
print '';
print ''.$langs->trans("NbOfAttachedFiles").' '.count($filearray).' ';
- print ''.$langs->trans("TotalSizeOfAttachedFiles").' '.$totalsize.' '.$langs->trans("bytes").' ';
+ print ''.$langs->trans("TotalSizeOfAttachedFiles").' '.dol_print_size($totalsize,1,1).' ';
print '
';
print '';
diff --git a/htdocs/compta/salaries/index.php b/htdocs/compta/salaries/index.php
index 47cafad0f0a..0b70275654f 100644
--- a/htdocs/compta/salaries/index.php
+++ b/htdocs/compta/salaries/index.php
@@ -28,17 +28,15 @@ require_once DOL_DOCUMENT_ROOT.'/compta/salaries/class/paymentsalary.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingjournal.class.php';
-$langs->load("compta");
-$langs->load("salaries");
-$langs->load("bills");
-$langs->load("hrm");
+// Load translation files required by the page
+$langs->loadLangs(array("compta","salaries","bills","hrm"));
// Security check
$socid = GETPOST("socid","int");
if ($user->societe_id) $socid=$user->societe_id;
$result = restrictedArea($user, 'salaries', '', '', '');
-$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit;
+$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit;
$search_ref = GETPOST('search_ref','int');
$search_user = GETPOST('search_user','alpha');
$search_label = GETPOST('search_label','alpha');
@@ -52,8 +50,8 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined,
$offset = $conf->liste_limit * $page;
$pageprev = $page - 1;
$pagenext = $page + 1;
-if (! $sortfield) $sortfield="s.datep";
-if (! $sortorder) $sortorder="DESC";
+if (! $sortfield) $sortfield="s.datep,s.rowid";
+if (! $sortorder) $sortorder="DESC,DESC";
$optioncss = GETPOST('optioncss','alpha');
$filtre=$_GET["filtre"];
@@ -105,7 +103,7 @@ $sql.= " s.rowid, s.fk_user, s.amount, s.salary, s.label, s.datep as datep, s.da
$sql.= " ba.rowid as bid, ba.ref as bref, ba.number as bnumber, ba.account_number, ba.fk_accountancy_journal, ba.label as blabel,";
$sql.= " pst.code as payment_code";
$sql.= " FROM ".MAIN_DB_PREFIX."payment_salary as s";
-$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pst ON s.fk_typepayment = pst.id AND pst.entity IN (".getEntity('c_paiement').")";
+$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pst ON s.fk_typepayment = pst.id";
$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON s.fk_bank = b.rowid";
$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid,";
$sql.= " ".MAIN_DB_PREFIX."user as u";
@@ -142,7 +140,6 @@ if ($result)
$num = $db->num_rows($result);
$i = 0;
$total = 0 ;
- $var=true;
$param='';
if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage;
@@ -150,7 +147,15 @@ if ($result)
if ($typeid) $param.='&typeid='.$typeid;
if ($optioncss != '') $param.='&optioncss='.$optioncss;
- print '';
+ $newcardbutton='';
+ if ($user->rights->salaries->payment->write)
+ {
+ $newcardbutton=''.$langs->trans('NewSalaryPayment').' ';
+ $newcardbutton.= ' ';
+ $newcardbutton.= ' ';
+ }
+
+ print ' ';
if ($optioncss != '') print ' ';
print ' ';
print ' ';
@@ -159,7 +164,7 @@ if ($result)
print ' ';
print ' ';
- print_barre_liste($langs->trans("SalariesPayments"),$page,$_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,'',$num, $totalnboflines, 'title_accountancy.png', 0, '', '', $limit);
+ print_barre_liste($langs->trans("SalariesPayments"),$page,$_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,'',$num, $totalnboflines, 'title_accountancy.png', 0, $newcardbutton, '', $limit);
print '';
print '
'."\n";
@@ -179,7 +184,7 @@ if ($result)
print ' ';
// Type
print '';
- $form->select_types_paiements($typeid,'typeid','',0,0,1,16);
+ $form->select_types_paiements($typeid,'typeid','',0,1,1,16);
print ' ';
// Account
if (! empty($conf->banque->enabled))
@@ -200,7 +205,7 @@ if ($result)
print_liste_field_titre("Ref",$_SERVER["PHP_SELF"],"s.rowid","",$param,"",$sortfield,$sortorder);
print_liste_field_titre("Employee",$_SERVER["PHP_SELF"],"u.rowid","",$param,"",$sortfield,$sortorder);
print_liste_field_titre("Label",$_SERVER["PHP_SELF"],"s.label","",$param,'align="left"',$sortfield,$sortorder);
- print_liste_field_titre("DatePayment",$_SERVER["PHP_SELF"],"s.datep","",$param,'align="center"',$sortfield,$sortorder);
+ print_liste_field_titre("DatePayment",$_SERVER["PHP_SELF"],"s.datep,s.rowid","",$param,'align="center"',$sortfield,$sortorder);
print_liste_field_titre("PaymentMode",$_SERVER["PHP_SELF"],"type","",$param,'align="left"',$sortfield,$sortorder);
if (! empty($conf->banque->enabled)) print_liste_field_titre("BankAccount",$_SERVER["PHP_SELF"],"ba.label","",$param,"",$sortfield,$sortorder);
print_liste_field_titre("PayedByThisPayment",$_SERVER["PHP_SELF"],"s.amount","",$param,'align="right"',$sortfield,$sortorder);
diff --git a/htdocs/compta/salaries/info.php b/htdocs/compta/salaries/info.php
index ddb79845748..467abe3618c 100644
--- a/htdocs/compta/salaries/info.php
+++ b/htdocs/compta/salaries/info.php
@@ -28,11 +28,8 @@ require_once DOL_DOCUMENT_ROOT.'/compta/salaries/class/paymentsalary.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/salaries.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
-$langs->load("compta");
-$langs->load("bills");
-$langs->load("users");
-$langs->load("salaries");
-$langs->load('hrm');
+// Load translation files required by the page
+$langs->loadLangs(array("compta","bills","users","salaries","hrm"));
$id=GETPOST('id','int');
$action=GETPOST('action','aZ09');
diff --git a/htdocs/compta/salaries/stats/index.php b/htdocs/compta/salaries/stats/index.php
new file mode 100644
index 00000000000..3e6fd56a266
--- /dev/null
+++ b/htdocs/compta/salaries/stats/index.php
@@ -0,0 +1,294 @@
+
+ * Copyright (C) 2018 Fidesio
+ *
+ * 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 3 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, see .
+ */
+
+/**
+ * \file htdocs/compta/salaries/stats/index.php
+ * \ingroup salaries
+ * \brief Page for statistics of module salaries
+ */
+
+require '../../../main.inc.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php';
+require_once DOL_DOCUMENT_ROOT.'/compta/salaries/class/salariesstats.class.php';
+
+// Load translation files required by the page
+$langs->loadLangs(array("salaries","companies"));
+
+$WIDTH=DolGraph::getDefaultGraphSizeForStats('width');
+$HEIGHT=DolGraph::getDefaultGraphSizeForStats('height');
+
+$userid=GETPOST('userid','int'); if ($userid < 0) $userid=0;
+$socid=GETPOST('socid','int'); if ($socid < 0) $socid=0;
+$id = GETPOST('id','int');
+
+// Security check
+$socid = GETPOST("socid","int");
+if ($user->societe_id) $socid=$user->societe_id;
+$result = restrictedArea($user, 'salaries', '', '', '');
+
+// Other security check
+$childids = $user->getAllChildIds();
+$childids[]=$user->id;
+if ($userid > 0)
+{
+ if (empty($user->rights->salaries->payment->readall) && ! in_array($userid, $childids))
+ {
+ accessforbidden();
+ exit;
+ }
+}
+
+$nowyear=strftime("%Y", dol_now());
+$year = GETPOST('year')>0?GETPOST('year'):$nowyear;
+//$startyear=$year-2;
+$startyear=$year-1;
+$endyear=$year;
+
+
+/*
+ * View
+ */
+
+$form=new Form($db);
+
+
+llxHeader();
+
+$title=$langs->trans("SalariesStatistics");
+$dir=$conf->salaries->dir_temp;
+
+print load_fiche_titre($title, $mesg);
+
+dol_mkdir($dir);
+
+$useridtofilter=$userid; // Filter from parameters
+if (empty($useridtofilter))
+{
+ $useridtofilter=$childids;
+ if (! empty($user->rights->salaries->payment->readall)) $useridtofilter=0;
+}
+
+$stats = new SalariesStats($db, $socid, $useridtofilter);
+
+
+// Build graphic number of object
+// $data = array(array('Lib',val1,val2,val3),...)
+//print "$endyear, $startyear";
+$data = $stats->getNbByMonthWithPrevYear($endyear,$startyear);
+//var_dump($data);
+
+$filenamenb = $dir."/salariesnbinyear-".$year.".png";
+$fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=salariesstats&file=salariesnbinyear-'.$year.'.png';
+
+$px1 = new DolGraph();
+$mesg = $px1->isGraphKo();
+if (! $mesg)
+{
+ $px1->SetData($data);
+ $px1->SetPrecisionY(0);
+ $i=$startyear;$legend=array();
+ while ($i <= $endyear)
+ {
+ $legend[]=$i;
+ $i++;
+ }
+ $px1->SetLegend($legend);
+ $px1->SetMaxValue($px1->GetCeilMaxValue());
+ $px1->SetWidth($WIDTH);
+ $px1->SetHeight($HEIGHT);
+ $px1->SetYLabel($langs->trans("Number"));
+ $px1->SetShading(3);
+ $px1->SetHorizTickIncrement(1);
+ $px1->SetPrecisionY(0);
+ $px1->mode='depth';
+ $px1->SetTitle($langs->trans("NumberByMonth"));
+
+ $px1->draw($filenamenb,$fileurlnb);
+}
+
+// Build graphic amount of object
+$data = $stats->getAmountByMonthWithPrevYear($endyear,$startyear);
+//var_dump($data);
+// $data = array(array('Lib',val1,val2,val3),...)
+
+$filenameamount = $dir."/salariesamountinyear-".$year.".png";
+$fileurlamount = DOL_URL_ROOT.'/viewimage.php?modulepart=salariesstats&file=salariesamountinyear-'.$year.'.png';
+
+$px2 = new DolGraph();
+$mesg = $px2->isGraphKo();
+if (! $mesg)
+{
+ $px2->SetData($data);
+ $i=$startyear;$legend=array();
+ while ($i <= $endyear)
+ {
+ $legend[]=$i;
+ $i++;
+ }
+ $px2->SetLegend($legend);
+ $px2->SetMaxValue($px2->GetCeilMaxValue());
+ $px2->SetMinValue(min(0,$px2->GetFloorMinValue()));
+ $px2->SetWidth($WIDTH);
+ $px2->SetHeight($HEIGHT);
+ $px2->SetYLabel($langs->trans("Amount"));
+ $px2->SetShading(3);
+ $px2->SetHorizTickIncrement(1);
+ $px2->SetPrecisionY(0);
+ $px2->mode='depth';
+ $px2->SetTitle($langs->trans("AmountTotal"));
+
+ $px2->draw($filenameamount,$fileurlamount);
+}
+
+
+$data = $stats->getAverageByMonthWithPrevYear($endyear, $startyear);
+
+$filename_avg = $dir."/salariesaverageinyear-".$year.".png";
+$fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=salariesstats&file=salariesaverageinyear-'.$year.'.png';
+
+$px3 = new DolGraph();
+$mesg = $px3->isGraphKo();
+if (! $mesg)
+{
+ $px3->SetData($data);
+ $i = $startyear;$legend=array();
+ while ($i <= $endyear)
+ {
+ $legend[]=$i;
+ $i++;
+ }
+ $px3->SetLegend($legend);
+ $px3->SetYLabel($langs->trans("AmountAverage"));
+ $px3->SetMaxValue($px3->GetCeilMaxValue());
+ $px3->SetMinValue($px3->GetFloorMinValue());
+ $px3->SetWidth($WIDTH);
+ $px3->SetHeight($HEIGHT);
+ $px3->SetShading(3);
+ $px3->SetHorizTickIncrement(1);
+ $px3->SetPrecisionY(0);
+ $px3->mode='depth';
+ $px3->SetTitle($langs->trans("AmountAverage"));
+
+ $px3->draw($filename_avg,$fileurl_avg);
+}
+
+
+// Show array
+$data = $stats->getAllByYear();
+$arrayyears=array();
+foreach($data as $val) {
+ $arrayyears[$val['year']]=$val['year'];
+}
+if (! count($arrayyears)) $arrayyears[$nowyear]=$nowyear;
+
+
+$h=0;
+$head = array();
+$head[$h][0] = DOL_URL_ROOT . '/compta/salaries/stats/index.php';
+$head[$h][1] = $langs->trans("ByMonthYear");
+$head[$h][2] = 'byyear';
+$h++;
+
+complete_head_from_modules($conf,$langs,null,$head,$h,'trip_stats');
+
+dol_fiche_head($head, 'byyear', $langs->trans("Statistics"), -1);
+
+
+print '';
+
+
+// Show filter box
+print '