Merge branch 'develop' of git@github.com:Dolibarr/dolibarr.git into develop

This commit is contained in:
Laurent Destailleur 2021-02-26 19:20:10 +01:00
commit 129120523c
107 changed files with 7682 additions and 6028 deletions

View File

@ -1053,10 +1053,9 @@ class pdf_crabe extends ModelePDFFactures
&& empty($conf->global->FACTURE_CHQ_NUMBER) && empty($conf->global->FACTURE_CHQ_NUMBER)
&& empty($conf->global->FACTURE_RIB_NUMBER)) { && empty($conf->global->FACTURE_RIB_NUMBER)) {
$this->error = $outputlangs->transnoentities("ErrorNoPaiementModeConfigured"); $this->error = $outputlangs->transnoentities("ErrorNoPaiementModeConfigured");
} } elseif (($object->mode_reglement_code == 'CHQ' && empty($conf->global->FACTURE_CHQ_NUMBER) && empty($object->fk_account) && empty($object->fk_bank))
// Avoid having any valid PDF with setup that is not complete
elseif (($object->mode_reglement_code == 'CHQ' && empty($conf->global->FACTURE_CHQ_NUMBER) && empty($object->fk_account) && empty($object->fk_bank))
|| ($object->mode_reglement_code == 'VIR' && empty($conf->global->FACTURE_RIB_NUMBER) && empty($object->fk_account) && empty($object->fk_bank))) { || ($object->mode_reglement_code == 'VIR' && empty($conf->global->FACTURE_RIB_NUMBER) && empty($object->fk_account) && empty($object->fk_bank))) {
// Avoid having any valid PDF with setup that is not complete
$outputlangs->load("errors"); $outputlangs->load("errors");
$pdf->SetXY($this->marge_gauche, $posy); $pdf->SetXY($this->marge_gauche, $posy);

View File

@ -1142,10 +1142,9 @@ class pdf_sponge extends ModelePDFFactures
&& empty($conf->global->FACTURE_CHQ_NUMBER) && empty($conf->global->FACTURE_CHQ_NUMBER)
&& empty($conf->global->FACTURE_RIB_NUMBER)) { && empty($conf->global->FACTURE_RIB_NUMBER)) {
$this->error = $outputlangs->transnoentities("ErrorNoPaiementModeConfigured"); $this->error = $outputlangs->transnoentities("ErrorNoPaiementModeConfigured");
} } elseif (($object->mode_reglement_code == 'CHQ' && empty($conf->global->FACTURE_CHQ_NUMBER) && empty($object->fk_account) && empty($object->fk_bank))
// Avoid having any valid PDF with setup that is not complete
elseif (($object->mode_reglement_code == 'CHQ' && empty($conf->global->FACTURE_CHQ_NUMBER) && empty($object->fk_account) && empty($object->fk_bank))
|| ($object->mode_reglement_code == 'VIR' && empty($conf->global->FACTURE_RIB_NUMBER) && empty($object->fk_account) && empty($object->fk_bank))) { || ($object->mode_reglement_code == 'VIR' && empty($conf->global->FACTURE_RIB_NUMBER) && empty($object->fk_account) && empty($object->fk_bank))) {
// Avoid having any valid PDF with setup that is not complete
$outputlangs->load("errors"); $outputlangs->load("errors");
$pdf->SetXY($this->marge_gauche, $posy); $pdf->SetXY($this->marge_gauche, $posy);

View File

@ -138,6 +138,9 @@ ALTER TABLE llx_menu ADD COLUMN prefix varchar(255) NULL AFTER titre;
ALTER TABLE llx_chargesociales ADD COLUMN fk_user integer DEFAULT NULL; ALTER TABLE llx_chargesociales ADD COLUMN fk_user integer DEFAULT NULL;
ALTER TABLE llx_mrp_production ADD COLUMN origin_id integer AFTER fk_mo;
ALTER TABLE llx_mrp_production ADD COLUMN origin_type varchar(10) AFTER origin_id;
ALTER TABLE llx_fichinter ADD COLUMN last_main_doc varchar(255) AFTER model_pdf; ALTER TABLE llx_fichinter ADD COLUMN last_main_doc varchar(255) AFTER model_pdf;
ALTER TABLE llx_projet ADD COLUMN last_main_doc varchar(255) AFTER model_pdf; ALTER TABLE llx_projet ADD COLUMN last_main_doc varchar(255) AFTER model_pdf;

View File

@ -17,6 +17,8 @@
CREATE TABLE llx_mrp_production( CREATE TABLE llx_mrp_production(
rowid integer AUTO_INCREMENT PRIMARY KEY NOT NULL, rowid integer AUTO_INCREMENT PRIMARY KEY NOT NULL,
fk_mo integer NOT NULL, fk_mo integer NOT NULL,
origin_id integer,
origin_type varchar(10), -- 'bom' bom production line or 'free' free production line added after Mo creation from bom
position integer NOT NULL DEFAULT 0, position integer NOT NULL DEFAULT 0,
fk_product integer NOT NULL, fk_product integer NOT NULL,
fk_warehouse integer, fk_warehouse integer,

View File

@ -655,6 +655,8 @@ class Mo extends CommonObject
$moline = new MoLine($this->db); $moline = new MoLine($this->db);
$moline->fk_mo = $this->id; $moline->fk_mo = $this->id;
$moline->origin_id = $line->id;
$moline->origin_type = 'bomline';
if ($line->qty_frozen) { if ($line->qty_frozen) {
$moline->qty = $line->qty; // Qty to consume does not depends on quantity to produce $moline->qty = $line->qty; // Qty to consume does not depends on quantity to produce
} else { } else {
@ -1386,6 +1388,8 @@ class MoLine extends CommonObjectLine
public $fields = array( public $fields = array(
'rowid' =>array('type'=>'integer', 'label'=>'ID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10), 'rowid' =>array('type'=>'integer', 'label'=>'ID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
'fk_mo' =>array('type'=>'integer', 'label'=>'Mo', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>15), 'fk_mo' =>array('type'=>'integer', 'label'=>'Mo', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>15),
'origin_id' =>array('type'=>'integer', 'label'=>'Origin', 'enabled'=>1, 'visible'=>-1, 'notnull'=>0, 'position'=>17),
'origin_type' =>array('type'=>'varchar(10)', 'label'=>'Origin type', 'enabled'=>1, 'visible'=>-1, 'notnull'=>0, 'position'=>18),
'position' =>array('type'=>'integer', 'label'=>'Position', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>20), 'position' =>array('type'=>'integer', 'label'=>'Position', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>20),
'fk_product' =>array('type'=>'integer', 'label'=>'Product', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>25), 'fk_product' =>array('type'=>'integer', 'label'=>'Product', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>25),
'fk_warehouse' =>array('type'=>'integer', 'label'=>'Warehouse', 'enabled'=>1, 'visible'=>-1, 'position'=>30), 'fk_warehouse' =>array('type'=>'integer', 'label'=>'Warehouse', 'enabled'=>1, 'visible'=>-1, 'position'=>30),
@ -1405,6 +1409,8 @@ class MoLine extends CommonObjectLine
public $rowid; public $rowid;
public $fk_mo; public $fk_mo;
public $origin_id;
public $origin_type;
public $position; public $position;
public $fk_product; public $fk_product;
public $fk_warehouse; public $fk_warehouse;
@ -1487,7 +1493,7 @@ class MoLine extends CommonObjectLine
public function fetch($id, $ref = null) public function fetch($id, $ref = null)
{ {
$result = $this->fetchCommon($id, $ref); $result = $this->fetchCommon($id, $ref);
if ($result > 0 && !empty($this->table_element_line)) $this->fetchLines();
return $result; return $result;
} }

View File

@ -119,7 +119,7 @@ $arrayfields = array(
'm.type_mouvement'=>array('label'=>$langs->trans("TypeMovement"), 'checked'=>1, 'position'=>48), 'm.type_mouvement'=>array('label'=>$langs->trans("TypeMovement"), 'checked'=>1, 'position'=>48),
'origin'=>array('label'=>$langs->trans("Origin"), 'enabled'=>0, 'checked'=>0, 'position'=>50), 'origin'=>array('label'=>$langs->trans("Origin"), 'enabled'=>0, 'checked'=>0, 'position'=>50),
'm.value'=>array('label'=>$langs->trans("Qty"), 'checked'=>1, 'position'=>60), 'm.value'=>array('label'=>$langs->trans("Qty"), 'checked'=>1, 'position'=>60),
'm.price'=>array('label'=>$langs->trans("UnitPurchaseValue"), 'enabled'=>0, 'checked'=>0, 'position'=>62), 'm.price'=>array('label'=>$langs->trans("UnitCost"), 'enabled'=>0, 'checked'=>0, 'position'=>62),
//'m.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), //'m.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500),
//'m.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500) //'m.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500)
); );
@ -139,7 +139,11 @@ $permissiontodelete = $user->rights->mrp->delete || ($permissiontoadd && isset($
$upload_dir = $conf->mrp->multidir_output[isset($object->entity) ? $object->entity : 1]; $upload_dir = $conf->mrp->multidir_output[isset($object->entity) ? $object->entity : 1];
$permissiontoproduce = $permissiontoadd; $permissiontoproduce = $permissiontoadd;
$permissiontoupdatecost = $user->rights->bom->write; // User who can define cost must have knowledge of pricing
if ($permissiontoupdatecost) {
$arrayfields['m.price']['enabled'] = 1;
}
/* /*
* Actions * Actions

View File

@ -34,6 +34,7 @@ require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
require_once DOL_DOCUMENT_ROOT.'/product/stock/class/productlot.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/stock/class/productlot.class.php';
require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
dol_include_once('/mrp/class/mo.class.php'); dol_include_once('/mrp/class/mo.class.php');
dol_include_once('/bom/class/bom.class.php');
dol_include_once('/mrp/lib/mrp_mo.lib.php'); dol_include_once('/mrp/lib/mrp_mo.lib.php');
// Load translation files required by the page // Load translation files required by the page
@ -88,6 +89,7 @@ $permissiontodelete = $user->rights->mrp->delete || ($permissiontoadd && isset($
$upload_dir = $conf->mrp->multidir_output[isset($object->entity) ? $object->entity : 1]; $upload_dir = $conf->mrp->multidir_output[isset($object->entity) ? $object->entity : 1];
$permissiontoproduce = $permissiontoadd; $permissiontoproduce = $permissiontoadd;
$permissiontoupdatecost = $user->rights->bom->read; // User who can define cost must have knowledge of pricing
/* /*
@ -150,6 +152,7 @@ if (empty($reshook))
$moline->qty = GETPOST('qtytoadd', 'int'); ; $moline->qty = GETPOST('qtytoadd', 'int'); ;
$moline->fk_product = GETPOST('productidtoadd', 'int'); $moline->fk_product = GETPOST('productidtoadd', 'int');
$moline->role = 'toconsume'; $moline->role = 'toconsume';
$moline->origin_type = 'free'; // free consume line
$moline->position = 0; $moline->position = 0;
$resultline = $moline->create($user, false); // Never use triggers here $resultline = $moline->create($user, false); // Never use triggers here
@ -168,7 +171,7 @@ if (empty($reshook))
$codemovement = GETPOST('inventorycode', 'alphanohtml'); $codemovement = GETPOST('inventorycode', 'alphanohtml');
$db->begin(); $db->begin();
$pos = 0;
// Process line to consume // Process line to consume
foreach ($object->lines as $line) { foreach ($object->lines as $line) {
if ($line->role == 'toconsume') { if ($line->role == 'toconsume') {
@ -199,7 +202,11 @@ if (empty($reshook))
// Record stock movement // Record stock movement
$id_product_batch = 0; $id_product_batch = 0;
$stockmove->origin = $object; $stockmove->origin = $object;
if ($qtytoprocess >= 0) {
$idstockmove = $stockmove->livraison($user, $line->fk_product, GETPOST('idwarehouse-'.$line->id.'-'.$i), $qtytoprocess, 0, $labelmovement, dol_now(), '', '', GETPOST('batch-'.$line->id.'-'.$i), $id_product_batch, $codemovement); $idstockmove = $stockmove->livraison($user, $line->fk_product, GETPOST('idwarehouse-'.$line->id.'-'.$i), $qtytoprocess, 0, $labelmovement, dol_now(), '', '', GETPOST('batch-'.$line->id.'-'.$i), $id_product_batch, $codemovement);
} else {
$idstockmove = $stockmove->reception($user, $line->fk_product, GETPOST('idwarehouse-'.$line->id.'-'.$i), $qtytoprocess, 0, $labelmovement, dol_now(), '', '', GETPOST('batch-'.$line->id.'-'.$i), $id_product_batch, $codemovement);
}
if ($idstockmove < 0) { if ($idstockmove < 0) {
$error++; $error++;
setEventMessages($stockmove->error, $stockmove->errors, 'errors'); setEventMessages($stockmove->error, $stockmove->errors, 'errors');
@ -207,7 +214,6 @@ if (empty($reshook))
} }
if (!$error) { if (!$error) {
$pos = 0;
// Record consumption // Record consumption
$moline = new MoLine($db); $moline = new MoLine($db);
$moline->fk_mo = $object->id; $moline->fk_mo = $object->id;
@ -237,6 +243,7 @@ if (empty($reshook))
} }
// Process line to produce // Process line to produce
$pos = 0;
foreach ($object->lines as $line) { foreach ($object->lines as $line) {
if ($line->role == 'toproduce') { if ($line->role == 'toproduce') {
$tmpproduct = new Product($db); $tmpproduct = new Product($db);
@ -245,8 +252,8 @@ if (empty($reshook))
$i = 1; $i = 1;
while (GETPOSTISSET('qtytoproduce-'.$line->id.'-'.$i)) { while (GETPOSTISSET('qtytoproduce-'.$line->id.'-'.$i)) {
$qtytoprocess = price2num(GETPOST('qtytoproduce-'.$line->id.'-'.$i)); $qtytoprocess = price2num(GETPOST('qtytoproduce-'.$line->id.'-'.$i));
$pricetoprocess = GETPOST('pricetoproduce-'.$line->id.'-'.$i) ? price2num(GETPOST('pricetoproduce-'.$line->id.'-'.$i)) : 0;
if ($qtytoprocess != 0) {
// Check warehouse is set if we should have to // Check warehouse is set if we should have to
if (GETPOSTISSET('idwarehousetoproduce-'.$line->id.'-'.$i)) { // If there is a warehouse to set if (GETPOSTISSET('idwarehousetoproduce-'.$line->id.'-'.$i)) { // If there is a warehouse to set
if (!(GETPOST('idwarehousetoproduce-'.$line->id.'-'.$i) > 0)) { // If there is no warehouse set. if (!(GETPOST('idwarehousetoproduce-'.$line->id.'-'.$i) > 0)) { // If there is no warehouse set.
@ -266,15 +273,14 @@ if (empty($reshook))
// Record stock movement // Record stock movement
$id_product_batch = 0; $id_product_batch = 0;
$stockmove->origin = $object; $stockmove->origin = $object;
$idstockmove = $stockmove->reception($user, $line->fk_product, GETPOST('idwarehousetoproduce-'.$line->id.'-'.$i), $qtytoprocess, 0, $labelmovement, '', '', GETPOST('batchtoproduce-'.$line->id.'-'.$i), dol_now(), $id_product_batch, $codemovement); $idstockmove = $stockmove->reception($user, $line->fk_product, GETPOST('idwarehousetoproduce-'.$line->id.'-'.$i), $qtytoprocess, $pricetoprocess, $labelmovement, '', '', GETPOST('batchtoproduce-'.$line->id.'-'.$i), dol_now(), $id_product_batch, $codemovement);
if ($idstockmove < 0) { if ($idstockmove < 0) {
$error++; $error++;
setEventMessages($stockmove->error, $stockmove->errors, 'errors'); setEventMessages($stockmove->error, $stockmove->errors, 'errors');
} }
} }
if ($qtytoprocess != 0) {
if (!$error) { if (!$error) {
$pos = 0;
// Record production // Record production
$moline = new MoLine($db); $moline = new MoLine($db);
$moline->fk_mo = $object->id; $moline->fk_mo = $object->id;
@ -677,12 +683,23 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
// Show object lines // Show object lines
$object->fetchLines(); $object->fetchLines();
$bomcost = 0;
if ($object->fk_bom > 0) {
$bom = new Bom($db);
$res = $bom->fetch($object->fk_bom);
if ($res > 0) {
$bomcost = $bom->unit_cost;
}
}
// consumtion
print '<div class="fichecenter">'; print '<div class="fichecenter">';
print '<div class="fichehalfleft">'; print '<div class="fichehalfleft">';
print '<div class="clearboth"></div>'; print '<div class="clearboth"></div>';
$newlinetext = ''; $newlinetext = '';
if ($action != 'consumeorproduce' && $action != 'consumeandproduceall') { if ($object->status != $object::STATUS_PRODUCED && $object->status != $object::STATUS_CANCELED && $action != 'consumeorproduce' && $action != 'consumeandproduceall') {
$newlinetext = '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=addconsumeline">'.$langs->trans("AddNewConsumeLines").'</a>'; $newlinetext = '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=addconsumeline">'.$langs->trans("AddNewConsumeLines").'</a>';
} }
print load_fiche_titre($langs->trans('Consumption'), '', '', 0, '', '', $newlinetext); print load_fiche_titre($langs->trans('Consumption'), '', '', 0, '', '', $newlinetext);
@ -693,6 +710,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
print '<td>'.$langs->trans("Product").'</td>'; print '<td>'.$langs->trans("Product").'</td>';
print '<td class="right">'.$langs->trans("Qty").'</td>'; print '<td class="right">'.$langs->trans("Qty").'</td>';
if ($permissiontoupdatecost) print '<td class="right">'.$langs->trans("UnitCost").'</td>';
print '<td class="right">'.$langs->trans("QtyAlreadyConsumed").'</td>'; print '<td class="right">'.$langs->trans("QtyAlreadyConsumed").'</td>';
print '<td>'; print '<td>';
if ($collapse || in_array($action, array('consumeorproduce', 'consumeandproduceall'))) print $langs->trans("Warehouse"); if ($collapse || in_array($action, array('consumeorproduce', 'consumeandproduceall'))) print $langs->trans("Warehouse");
@ -711,6 +729,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
print $form->select_produits('', 'productidtoadd', '', 0, 0, -1, 2, '', 0, array(), 0, '1', 0, 'maxwidth300'); print $form->select_produits('', 'productidtoadd', '', 0, 0, -1, 2, '', 0, array(), 0, '1', 0, 'maxwidth300');
print '</td>'; print '</td>';
print '<td class="right"><input type="text" name="qtytoadd" value="1" class="width50 right"></td>'; print '<td class="right"><input type="text" name="qtytoadd" value="1" class="width50 right"></td>';
if ($permissiontoupdatecost) print '<td></td>';
print '<td class="right"></td>'; print '<td class="right"></td>';
print '<td>'; print '<td>';
print '<input type="submit" class="button buttongen" name="addconsumelinebutton" value="'.$langs->trans("Add").'">'; print '<input type="submit" class="button buttongen" name="addconsumelinebutton" value="'.$langs->trans("Add").'">';
@ -739,6 +758,29 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
$tmpproduct = new Product($db); $tmpproduct = new Product($db);
$tmpproduct->fetch($line->fk_product); $tmpproduct->fetch($line->fk_product);
$linecost = price2num($tmpproduct->pmp, 'MT');
if ($line->origin_type == 'free' && $object->qty > 0) {
// add free consume line cost to bomcost
$costprice = price2num((!empty($tmpproduct->cost_price)) ? $tmpproduct->cost_price : $tmpproduct->pmp);
if (empty($costprice)) {
require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
$productFournisseur = new ProductFournisseur($db);
if ($productFournisseur->find_min_price_product_fournisseur($line->fk_product) > 0){
$costprice = $productFournisseur->fourn_unitprice;
} else {
$costprice = 0;
}
}
$linecost = price2num(($line->qty * $costprice) / $object->qty, 'MT');
$bomcost += $linecost;
} elseif ($line->origin_id > 0 && $line->origin_type == 'bom' && $object->qty > 0) {
foreach ($bom->lines as $bomline) {
if ($bomline->id == $line->origin_id) {
$linecost = price2num(($line->qty * $bomline->unit_cost) / $object->qty, 'MT');
}
}
}
$arrayoflines = $object->fetchLinesLinked('consumed', $line->id); $arrayoflines = $object->fetchLinesLinked('consumed', $line->id);
$alreadyconsumed = 0; $alreadyconsumed = 0;
@ -760,6 +802,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
print $line->qty; print $line->qty;
} }
print '</td>'; print '</td>';
if ($permissiontoupdatecost) {
print '<td class="right nowraponall">';
print price($linecost);
print '</td>';
}
print '<td class="right">'; print '<td class="right">';
if ($alreadyconsumed) { if ($alreadyconsumed) {
print '<script>'; print '<script>';
@ -799,6 +846,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
print '</td>'; print '</td>';
print '<td></td>'; print '<td></td>';
print '<td class="right">'.$line2['qty'].'</td>'; print '<td class="right">'.$line2['qty'].'</td>';
if ($permissiontoupdatecost) print '<td></td>';
print '<td class="tdoverflowmax150">'; print '<td class="tdoverflowmax150">';
if ($line2['fk_warehouse'] > 0) { if ($line2['fk_warehouse'] > 0) {
$result = $tmpwarehouse->fetch($line2['fk_warehouse']); $result = $tmpwarehouse->fetch($line2['fk_warehouse']);
@ -823,6 +871,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
$preselected = (GETPOSTISSET('qty-'.$line->id.'-'.$i) ? GETPOST('qty-'.$line->id.'-'.$i) : max(0, $line->qty - $alreadyconsumed)); $preselected = (GETPOSTISSET('qty-'.$line->id.'-'.$i) ? GETPOST('qty-'.$line->id.'-'.$i) : max(0, $line->qty - $alreadyconsumed));
if ($action == 'consumeorproduce' && !GETPOSTISSET('qty-'.$line->id.'-'.$i)) $preselected = 0; if ($action == 'consumeorproduce' && !GETPOSTISSET('qty-'.$line->id.'-'.$i)) $preselected = 0;
print '<td class="right"><input type="text" class="width50 right" name="qty-'.$line->id.'-'.$i.'" value="'.$preselected.'"></td>'; print '<td class="right"><input type="text" class="width50 right" name="qty-'.$line->id.'-'.$i.'" value="'.$preselected.'"></td>';
if ($permissiontoupdatecost) print '<td></td>';
print '<td></td>'; print '<td></td>';
print '<td>'; print '<td>';
if ($tmpproduct->type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) { if ($tmpproduct->type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
@ -868,6 +917,13 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
print '<td>'.$langs->trans("Product").'</td>'; print '<td>'.$langs->trans("Product").'</td>';
print '<td class="right">'.$langs->trans("Qty").'</td>'; print '<td class="right">'.$langs->trans("Qty").'</td>';
if ($permissiontoupdatecost) {
if (empty($bomcost)) {
print '<td class="right">'.$langs->trans("PMPValue").'</td>';
} else {
print '<td class="right">'.$langs->trans("UnitCost").'</td>';
}
}
print '<td class="right">'.$langs->trans("QtyAlreadyProduced").'</td>'; print '<td class="right">'.$langs->trans("QtyAlreadyProduced").'</td>';
print '<td>'; print '<td>';
if ($collapse || in_array($action, array('consumeorproduce', 'consumeandproduceall'))) print $langs->trans("Warehouse"); if ($collapse || in_array($action, array('consumeorproduce', 'consumeandproduceall'))) print $langs->trans("Warehouse");
@ -899,6 +955,10 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
$tmpproduct = new Product($db); $tmpproduct = new Product($db);
$tmpproduct->fetch($line->fk_product); $tmpproduct->fetch($line->fk_product);
if (empty($bomcost)) {
$bomcost = $tmpproduct->pmp;
}
$arrayoflines = $object->fetchLinesLinked('produced', $line->id); $arrayoflines = $object->fetchLinesLinked('produced', $line->id);
$alreadyproduced = 0; $alreadyproduced = 0;
foreach ($arrayoflines as $line2) { foreach ($arrayoflines as $line2) {
@ -916,6 +976,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
print '<br><span class="opacitymedium small">'.$tmpproduct->label.'</span>'; print '<br><span class="opacitymedium small">'.$tmpproduct->label.'</span>';
print '</td>'; print '</td>';
print '<td class="right">'.$line->qty.'</td>'; print '<td class="right">'.$line->qty.'</td>';
if ($permissiontoupdatecost) {
print '<td class="right nowraponall">';
print price($bomcost);
print '</td>';
}
print '<td class="right nowraponall">'; print '<td class="right nowraponall">';
if ($alreadyproduced) { if ($alreadyproduced) {
print '<script>'; print '<script>';
@ -952,6 +1017,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
print '</td>'; print '</td>';
print '<td></td>'; print '<td></td>';
print '<td class="right">'.$line2['qty'].'</td>'; print '<td class="right">'.$line2['qty'].'</td>';
if ($permissiontoupdatecost) print '<td></td>';
print '<td class="tdoverflowmax150">'; print '<td class="tdoverflowmax150">';
if ($line2['fk_warehouse'] > 0) { if ($line2['fk_warehouse'] > 0) {
$result = $tmpwarehouse->fetch($line2['fk_warehouse']); $result = $tmpwarehouse->fetch($line2['fk_warehouse']);
@ -977,6 +1043,12 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
$preselected = (GETPOSTISSET('qtytoproduce-'.$line->id.'-'.$i) ? GETPOST('qtytoproduce-'.$line->id.'-'.$i) : max(0, $line->qty - $alreadyproduced)); $preselected = (GETPOSTISSET('qtytoproduce-'.$line->id.'-'.$i) ? GETPOST('qtytoproduce-'.$line->id.'-'.$i) : max(0, $line->qty - $alreadyproduced));
if ($action == 'consumeorproduce' && !GETPOSTISSET('qtytoproduce-'.$line->id.'-'.$i)) $preselected = 0; if ($action == 'consumeorproduce' && !GETPOSTISSET('qtytoproduce-'.$line->id.'-'.$i)) $preselected = 0;
print '<td class="right"><input type="text" class="width50 right" id="qtytoproduce-'.$line->id.'-'.$i.'" name="qtytoproduce-'.$line->id.'-'.$i.'" value="'.$preselected.'"></td>'; print '<td class="right"><input type="text" class="width50 right" id="qtytoproduce-'.$line->id.'-'.$i.'" name="qtytoproduce-'.$line->id.'-'.$i.'" value="'.$preselected.'"></td>';
if ($permissiontoupdatecost) {
$preselected = (GETPOSTISSET('pricetoproduce-'.$line->id.'-'.$i) ? GETPOST('pricetoproduce-'.$line->id.'-'.$i) : price($bomcost));
print '<td class="right"><input type="text" class="width50 right" name="pricetoproduce-'.$line->id.'-'.$i.'" value="'.$preselected.'"></td>';
} else {
print '<input type="hidden" class="width50 right" name="pricetoproduce-'.$line->id.'-'.$i.'" value="'.$bomcost.'"></td>';
}
print '<td></td>'; print '<td></td>';
print '<td>'; print '<td>';
if ($tmpproduct->type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) { if ($tmpproduct->type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) {

View File

@ -32,7 +32,9 @@ require_once DOL_DOCUMENT_ROOT."/opensurvey/fonctions.php";
// Security check // Security check
if (!$user->rights->opensurvey->read) accessforbidden(); if (!$user->rights->opensurvey->read) {
accessforbidden();
}
// Initialisation des variables // Initialisation des variables
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
@ -62,17 +64,21 @@ $expiredate = dol_mktime(0, 0, 0, GETPOST('expiremonth'), GETPOST('expireday'),
$parameters = array('id' => $numsondage); $parameters = array('id' => $numsondage);
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if (empty($reshook)) if (empty($reshook)) {
{ if ($cancel) {
if ($cancel) $action = ''; $action = '';
}
// Delete // Delete
if ($action == 'delete_confirm') if ($action == 'delete_confirm') {
{
// Security check // Security check
if (!$user->rights->opensurvey->write) accessforbidden(); if (!$user->rights->opensurvey->write) {
accessforbidden();
}
$result = $object->delete($user, '', $numsondage); $result = $object->delete($user, '', $numsondage);
@ -81,36 +87,33 @@ if (empty($reshook))
} }
// Close // Close
if ($action == 'close') if ($action == 'close') {
{
$object->status = Opensurveysondage::STATUS_CLOSED; $object->status = Opensurveysondage::STATUS_CLOSED;
$object->update($user); $object->update($user);
} }
// Reopend // Reopend
if ($action == 'reopen') if ($action == 'reopen') {
{
$object->status = Opensurveysondage::STATUS_VALIDATED; $object->status = Opensurveysondage::STATUS_VALIDATED;
$object->update($user); $object->update($user);
} }
// Update // Update
if ($action == 'update') if ($action == 'update') {
{
// Security check // Security check
if (!$user->rights->opensurvey->write) accessforbidden(); if (!$user->rights->opensurvey->write) {
accessforbidden();
}
$error = 0; $error = 0;
if (!GETPOST('nouveautitre')) if (!GETPOST('nouveautitre')) {
{
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Title")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Title")), null, 'errors');
$error++; $error++;
$action = 'edit'; $action = 'edit';
} }
if (!$error) if (!$error) {
{
$object->title = (string) GETPOST('nouveautitre', 'alphanohtml'); $object->title = (string) GETPOST('nouveautitre', 'alphanohtml');
$object->description = (string) GETPOST('nouveauxcommentaires', 'restricthtml'); $object->description = (string) GETPOST('nouveauxcommentaires', 'restricthtml');
$object->mail_admin = (string) GETPOST('nouvelleadresse', 'alpha'); $object->mail_admin = (string) GETPOST('nouvelleadresse', 'alpha');
@ -128,8 +131,7 @@ if (empty($reshook))
} }
// Add comment // Add comment
if (GETPOST('ajoutcomment')) if (GETPOST('ajoutcomment')) {
{
$error = 0; $error = 0;
if (!GETPOST('comment')) { if (!GETPOST('comment')) {
@ -147,8 +149,7 @@ if (empty($reshook))
$resql = $object->addComment($comment, $comment_user); $resql = $object->addComment($comment, $comment_user);
if (!$resql) if (!$resql) {
{
setEventMessages($langs->trans('ErrorInsertingComment'), null, 'errors'); setEventMessages($langs->trans('ErrorInsertingComment'), null, 'errors');
} }
} }
@ -156,17 +157,20 @@ if (empty($reshook))
// Delete comment // Delete comment
$idcomment = GETPOST('deletecomment', 'int'); $idcomment = GETPOST('deletecomment', 'int');
if ($idcomment) if ($idcomment) {
{
// Security check // Security check
if (!$user->rights->opensurvey->write) accessforbidden(); if (!$user->rights->opensurvey->write) {
accessforbidden();
}
$resql = $object->deleteComment($idcomment); $resql = $object->deleteComment($idcomment);
} }
if ($action == 'edit') { if ($action == 'edit') {
// Security check // Security check
if (!$user->rights->opensurvey->write) accessforbidden(); if (!$user->rights->opensurvey->write) {
accessforbidden();
}
} }
} }
@ -177,8 +181,7 @@ if (empty($reshook))
$form = new Form($db); $form = new Form($db);
if ($object->fk_user_creat) if ($object->fk_user_creat) {
{
$userstatic = new User($db); $userstatic = new User($db);
$userstatic->fetch($object->fk_user_creat); $userstatic->fetch($object->fk_user_creat);
} }
@ -193,8 +196,7 @@ llxHeader('', $title, $helpurl, 0, 0, 0, $arrayofjs, $arrayofcss);
// Define format of choices // Define format of choices
$toutsujet = explode(",", $object->sujet); $toutsujet = explode(",", $object->sujet);
$listofanswers = array(); $listofanswers = array();
foreach ($toutsujet as $value) foreach ($toutsujet as $value) {
{
$tmp = explode('@', $value); $tmp = explode('@', $value);
$listofanswers[] = array('label'=>$tmp[0], 'format'=>($tmp[1] ? $tmp[1] : 'checkbox')); $listofanswers[] = array('label'=>$tmp[0], 'format'=>($tmp[1] ? $tmp[1] : 'checkbox'));
} }
@ -232,16 +234,16 @@ print ' '.$langs->trans($type == 'classic' ? "TypeClassic" : "TypeDate").'</td><
print '<tr><td>'; print '<tr><td>';
$adresseadmin = $object->mail_admin; $adresseadmin = $object->mail_admin;
print $langs->trans("Title").'</td><td colspan="2">'; print $langs->trans("Title").'</td><td colspan="2">';
if ($action == 'edit') if ($action == 'edit') {
{
print '<input type="text" name="nouveautitre" style="width: 95%" value="'.dol_escape_htmltag(dol_htmlentities($object->title)).'">'; print '<input type="text" name="nouveautitre" style="width: 95%" value="'.dol_escape_htmltag(dol_htmlentities($object->title)).'">';
} else print dol_htmlentities($object->title); } else {
print dol_htmlentities($object->title);
}
print '</td></tr>'; print '</td></tr>';
// Description // Description
print '<tr><td class="tdtop">'.$langs->trans("Description").'</td><td colspan="2">'; print '<tr><td class="tdtop">'.$langs->trans("Description").'</td><td colspan="2">';
if ($action == 'edit') if ($action == 'edit') {
{
$doleditor = new DolEditor('nouveauxcommentaires', $object->description, '', 120, 'dolibarr_notes', 'In', 1, 1, 1, ROWS_7, '90%'); $doleditor = new DolEditor('nouveauxcommentaires', $object->description, '', 120, 'dolibarr_notes', 'In', 1, 1, 1, ROWS_7, '90%');
$doleditor->Create(0, ''); $doleditor->Create(0, '');
} else { } else {
@ -253,17 +255,17 @@ print '</td></tr>';
//If linked user, then emails are going to be sent to users' email //If linked user, then emails are going to be sent to users' email
if (!$object->fk_user_creat) { if (!$object->fk_user_creat) {
print '<tr><td>'.$langs->trans("EMail").'</td><td colspan="2">'; print '<tr><td>'.$langs->trans("EMail").'</td><td colspan="2">';
if ($action == 'edit') if ($action == 'edit') {
{
print '<input type="text" name="nouvelleadresse" class="minwith200" value="'.$object->mail_admin.'">'; print '<input type="text" name="nouvelleadresse" class="minwith200" value="'.$object->mail_admin.'">';
} else print dol_print_email($object->mail_admin, 0, 0, 1); } else {
print dol_print_email($object->mail_admin, 0, 0, 1);
}
print '</td></tr>'; print '</td></tr>';
} }
// Receive an email with each vote // Receive an email with each vote
print '<tr><td>'.$langs->trans('ToReceiveEMailForEachVote').'</td><td colspan="2">'; print '<tr><td>'.$langs->trans('ToReceiveEMailForEachVote').'</td><td colspan="2">';
if ($action == 'edit') if ($action == 'edit') {
{
print '<input type="checkbox" name="mailsonde" '.($object->mailsonde ? 'checked="checked"' : '').'">'; print '<input type="checkbox" name="mailsonde" '.($object->mailsonde ? 'checked="checked"' : '').'">';
} else { } else {
print yn($object->mailsonde); print yn($object->mailsonde);
@ -279,26 +281,31 @@ print '</td></tr>';
// Users can comment // Users can comment
print '<tr><td>'.$langs->trans('CanComment').'</td><td colspan="2">'; print '<tr><td>'.$langs->trans('CanComment').'</td><td colspan="2">';
if ($action == 'edit') if ($action == 'edit') {
{
print '<input type="checkbox" name="cancomment" '.($object->allow_comments ? 'checked="checked"' : '').'">'; print '<input type="checkbox" name="cancomment" '.($object->allow_comments ? 'checked="checked"' : '').'">';
} else print yn($object->allow_comments); } else {
print yn($object->allow_comments);
}
print '</td></tr>'; print '</td></tr>';
// Users can see others vote // Users can see others vote
print '<tr><td>'.$langs->trans('CanSeeOthersVote').'</td><td colspan="2">'; print '<tr><td>'.$langs->trans('CanSeeOthersVote').'</td><td colspan="2">';
if ($action == 'edit') if ($action == 'edit') {
{
print '<input type="checkbox" name="canseeothersvote" '.($object->allow_spy ? 'checked="checked"' : '').'">'; print '<input type="checkbox" name="canseeothersvote" '.($object->allow_spy ? 'checked="checked"' : '').'">';
} else print yn($object->allow_spy); } else {
print yn($object->allow_spy);
}
print '</td></tr>'; print '</td></tr>';
// Expire date // Expire date
print '<tr><td>'.$langs->trans('ExpireDate').'</td><td colspan="2">'; print '<tr><td>'.$langs->trans('ExpireDate').'</td><td colspan="2">';
if ($action == 'edit') print $form->selectDate($expiredate ? $expiredate : $object->date_fin, 'expire', 0, 0, 0, '', 1, 0); if ($action == 'edit') {
else { print $form->selectDate($expiredate ? $expiredate : $object->date_fin, 'expire', 0, 0, 0, '', 1, 0);
} else {
print dol_print_date($object->date_fin, 'day'); print dol_print_date($object->date_fin, 'day');
if ($object->date_fin && $object->date_fin < dol_now() && $object->status == Opensurveysondage::STATUS_VALIDATED) print img_warning($langs->trans("Expired")); if ($object->date_fin && $object->date_fin < dol_now() && $object->status == Opensurveysondage::STATUS_VALIDATED) {
print img_warning($langs->trans("Expired"));
}
} }
print '</td></tr>'; print '</td></tr>';
@ -322,7 +329,9 @@ $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domai
$url = $urlwithroot.'/public/opensurvey/studs.php?sondage='.$object->id_sondage; $url = $urlwithroot.'/public/opensurvey/studs.php?sondage='.$object->id_sondage;
print '<input type="text" style="width: 60%" '.($action == 'edit' ? 'disabled' : '').' id="opensurveyurl" name="opensurveyurl" value="'.$url.'">'; print '<input type="text" style="width: 60%" '.($action == 'edit' ? 'disabled' : '').' id="opensurveyurl" name="opensurveyurl" value="'.$url.'">';
if ($action != 'edit') print ajax_autoselect("opensurveyurl", $url); if ($action != 'edit') {
print ajax_autoselect("opensurveyurl", $url);
}
print '</td></tr>'; print '</td></tr>';
@ -332,8 +341,7 @@ print '</div>';
print dol_get_fiche_end(); print dol_get_fiche_end();
if ($action == 'edit') if ($action == 'edit') {
{
print '<div class="center">'; print '<div class="center">';
print '<input type="submit" class="button button-save" name="save" value="'.dol_escape_htmltag($langs->trans("Save")).'">'; print '<input type="submit" class="button button-save" name="save" value="'.dol_escape_htmltag($langs->trans("Save")).'">';
print ' &nbsp; '; print ' &nbsp; ';
@ -354,13 +362,11 @@ if ($action != 'edit' && $user->rights->opensurvey->write) {
//Modify button //Modify button
print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=edit&id='.$numsondage.'">'.$langs->trans("Modify").'</a>'; print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=edit&id='.$numsondage.'">'.$langs->trans("Modify").'</a>';
if ($object->status == Opensurveysondage::STATUS_VALIDATED) if ($object->status == Opensurveysondage::STATUS_VALIDATED) {
{
//Close button //Close button
print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=close&id='.$numsondage.'">'.$langs->trans("Close").'</a>'; print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=close&id='.$numsondage.'">'.$langs->trans("Close").'</a>';
} }
if ($object->status == Opensurveysondage::STATUS_CLOSED) if ($object->status == Opensurveysondage::STATUS_CLOSED) {
{
//Opened button //Opened button
print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=reopen&id='.$numsondage.'">'.$langs->trans("ReOpen").'</a>'; print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=reopen&id='.$numsondage.'">'.$langs->trans("ReOpen").'</a>';
} }
@ -371,8 +377,7 @@ if ($action != 'edit' && $user->rights->opensurvey->write) {
print '</div>'; print '</div>';
if ($action == 'delete') if ($action == 'delete') {
{
print $form->formconfirm($_SERVER["PHP_SELF"].'?&id='.$numsondage, $langs->trans("RemovePoll"), $langs->trans("ConfirmRemovalOfPoll", $id), 'delete_confirm', '', '', 1); print $form->formconfirm($_SERVER["PHP_SELF"].'?&id='.$numsondage, $langs->trans("RemovePoll"), $langs->trans("ConfirmRemovalOfPoll", $id), 'delete_confirm', '', '', 1);
} }

View File

@ -195,14 +195,18 @@ class Opensurveysondage extends CommonObject
dol_syslog(get_class($this)."::create", LOG_DEBUG); dol_syslog(get_class($this)."::create", LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } if (!$resql) {
$error++; $this->errors[] = "Error ".$this->db->lasterror();
}
if (!$error && !$notrigger) { if (!$error && !$notrigger) {
global $langs, $conf; global $langs, $conf;
// Call trigger // Call trigger
$result = $this->call_trigger('OPENSURVEY_CREATE', $user); $result = $this->call_trigger('OPENSURVEY_CREATE', $user);
if ($result < 0) $error++; if ($result < 0) {
$error++;
}
// End call triggers // End call triggers
} }
@ -250,10 +254,8 @@ class Opensurveysondage extends CommonObject
dol_syslog(get_class($this)."::fetch", LOG_DEBUG); dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{ if ($this->db->num_rows($resql)) {
if ($this->db->num_rows($resql))
{
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
$this->id_sondage = $obj->id_sondage; $this->id_sondage = $obj->id_sondage;
@ -336,15 +338,15 @@ class Opensurveysondage extends CommonObject
if (!$error && !$notrigger) { if (!$error && !$notrigger) {
// Call trigger // Call trigger
$result = $this->call_trigger('OPENSURVEY_MODIFY', $user); $result = $this->call_trigger('OPENSURVEY_MODIFY', $user);
if ($result < 0) $error++; if ($result < 0) {
$error++;
}
// End call triggers // End call triggers
} }
// Commit or rollback // Commit or rollback
if ($error) if ($error) {
{ foreach ($this->errors as $errmsg) {
foreach ($this->errors as $errmsg)
{
dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
$this->error .= ($this->error ? ', '.$errmsg : $errmsg); $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
} }
@ -369,8 +371,7 @@ class Opensurveysondage extends CommonObject
global $conf, $langs; global $conf, $langs;
$error = 0; $error = 0;
if (empty($numsondage)) if (empty($numsondage)) {
{
$numsondage = $this->id_sondage; $numsondage = $this->id_sondage;
} }
@ -379,12 +380,13 @@ class Opensurveysondage extends CommonObject
if (!$error && !$notrigger) { if (!$error && !$notrigger) {
// Call trigger // Call trigger
$result = $this->call_trigger('OPENSURVEY_DELETE', $user); $result = $this->call_trigger('OPENSURVEY_DELETE', $user);
if ($result < 0) $error++; if ($result < 0) {
$error++;
}
// End call triggers // End call triggers
} }
if (!$error) if (!$error) {
{
$sql = 'DELETE FROM '.MAIN_DB_PREFIX."opensurvey_comments WHERE id_sondage = '".$this->db->escape($numsondage)."'"; $sql = 'DELETE FROM '.MAIN_DB_PREFIX."opensurvey_comments WHERE id_sondage = '".$this->db->escape($numsondage)."'";
dol_syslog(get_class($this)."::delete", LOG_DEBUG); dol_syslog(get_class($this)."::delete", LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
@ -397,14 +399,14 @@ class Opensurveysondage extends CommonObject
dol_syslog(get_class($this)."::delete", LOG_DEBUG); dol_syslog(get_class($this)."::delete", LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } if (!$resql) {
$error++; $this->errors[] = "Error ".$this->db->lasterror();
}
} }
// Commit or rollback // Commit or rollback
if ($error) if ($error) {
{ foreach ($this->errors as $errmsg) {
foreach ($this->errors as $errmsg)
{
dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
$this->error .= ($this->error ? ', '.$errmsg : $errmsg); $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
} }
@ -431,7 +433,9 @@ class Opensurveysondage extends CommonObject
global $dolibarr_main_authentication, $dolibarr_main_demo; global $dolibarr_main_authentication, $dolibarr_main_demo;
global $menumanager; global $menumanager;
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 = ''; $result = '';
@ -444,14 +448,16 @@ class Opensurveysondage extends CommonObject
// Add param to save lastsearch_values or not // Add param to save lastsearch_values or not
$add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1; if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1'; $add_save_lastsearch_values = 1;
}
if ($add_save_lastsearch_values) {
$url .= '&save_lastsearch_values=1';
}
$linkclose = ''; $linkclose = '';
if (empty($notooltip)) if (empty($notooltip)) {
{ if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
{
$label = $langs->trans("ShowMyObject"); $label = $langs->trans("ShowMyObject");
$linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
} }
@ -466,8 +472,12 @@ class Opensurveysondage extends CommonObject
$linkend = '</a>'; $linkend = '</a>';
$result .= $linkstart; $result .= $linkstart;
if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); if ($withpicto) {
if ($withpicto != 2) $result .= $this->ref; $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
}
if ($withpicto != 2) {
$result .= $this->ref;
}
$result .= $linkend; $result .= $linkend;
return $result; return $result;
@ -488,19 +498,19 @@ class Opensurveysondage extends CommonObject
$sql .= " WHERE id_sondage = '".$this->db->escape($this->id_sondage)."'"; $sql .= " WHERE id_sondage = '".$this->db->escape($this->id_sondage)."'";
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{
$num = $this->db->num_rows($resql); $num = $this->db->num_rows($resql);
$i = 0; $i = 0;
while ($i < $num) while ($i < $num) {
{
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
$tmp = array('id_users'=>$obj->id_users, 'nom'=>$obj->name, 'reponses'=>$obj->reponses); $tmp = array('id_users'=>$obj->id_users, 'nom'=>$obj->name, 'reponses'=>$obj->reponses);
$ret[] = $tmp; $ret[] = $tmp;
$i++; $i++;
} }
} else dol_print_error($this->db); } else {
dol_print_error($this->db);
}
$this->lines = $ret; $this->lines = $ret;
@ -543,14 +553,11 @@ class Opensurveysondage extends CommonObject
$sql .= " ORDER BY id_comment"; $sql .= " ORDER BY id_comment";
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{
$num_rows = $this->db->num_rows($resql); $num_rows = $this->db->num_rows($resql);
if ($num_rows > 0) if ($num_rows > 0) {
{ while ($obj = $this->db->fetch_object($resql)) {
while ($obj = $this->db->fetch_object($resql))
{
$comments[] = $obj; $comments[] = $obj;
} }
} }
@ -642,8 +649,7 @@ class Opensurveysondage extends CommonObject
// phpcs:enable // phpcs:enable
global $langs, $conf; global $langs, $conf;
if (empty($this->labelStatus) || empty($this->labelStatusShort)) if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
{
global $langs; global $langs;
//$langs->load("mymodule"); //$langs->load("mymodule");
$this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Draft'); $this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Draft');
@ -656,10 +662,15 @@ class Opensurveysondage extends CommonObject
$statusType = 'status'.$status; $statusType = 'status'.$status;
if ($status == self::STATUS_VALIDATED) { if ($status == self::STATUS_VALIDATED) {
if (0) $statusType = 'status1'; if (0) {
else $statusType = 'status4'; $statusType = 'status1';
} else {
$statusType = 'status4';
}
}
if ($status == self::STATUS_CLOSED) {
$statusType = 'status6';
} }
if ($status == self::STATUS_CLOSED) $statusType = 'status6';
return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
} }

View File

@ -30,14 +30,15 @@ require_once DOL_DOCUMENT_ROOT."/opensurvey/class/opensurveysondage.class.php";
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
$numsondage = ''; $numsondage = '';
if (GETPOST('id')) if (GETPOST('id')) {
{
$numsondage = GETPOST("id", 'alpha'); $numsondage = GETPOST("id", 'alpha');
} }
$object = new Opensurveysondage($db); $object = new Opensurveysondage($db);
$result = $object->fetch(0, $numsondage); $result = $object->fetch(0, $numsondage);
if ($result <= 0) dol_print_error('', 'Failed to get survey id '.$numsondage); if ($result <= 0) {
dol_print_error('', 'Failed to get survey id '.$numsondage);
}
/* /*
@ -57,10 +58,8 @@ $toutsujet = explode(",", $object->sujet);
// affichage des sujets du sondage // affichage des sujets du sondage
$input .= $langs->trans("Name").";"; $input .= $langs->trans("Name").";";
for ($i = 0; $toutsujet[$i]; $i++) for ($i = 0; $toutsujet[$i]; $i++) {
{ if ($object->format == "D") {
if ($object->format == "D")
{
$input .= ''.dol_print_date($toutsujet[$i], 'dayhour').';'; $input .= ''.dol_print_date($toutsujet[$i], 'dayhour').';';
} else { } else {
$input .= ''.$toutsujet[$i].';'; $input .= ''.$toutsujet[$i].';';
@ -69,11 +68,9 @@ for ($i = 0; $toutsujet[$i]; $i++)
$input .= "\r\n"; $input .= "\r\n";
if (strpos($object->sujet, '@') !== false) if (strpos($object->sujet, '@') !== false) {
{
$input .= ";"; $input .= ";";
for ($i = 0; $toutsujet[$i]; $i++) for ($i = 0; $toutsujet[$i]; $i++) {
{
$heures = explode("@", $toutsujet[$i]); $heures = explode("@", $toutsujet[$i]);
$input .= ''.$heures[1].';'; $input .= ''.$heures[1].';';
} }
@ -87,12 +84,10 @@ $sql .= ' FROM '.MAIN_DB_PREFIX."opensurvey_user_studs";
$sql .= " WHERE id_sondage='".$db->escape($numsondage)."'"; $sql .= " WHERE id_sondage='".$db->escape($numsondage)."'";
$sql .= " ORDER BY id_users"; $sql .= " ORDER BY id_users";
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
$i = 0; $i = 0;
while ($i < $num) while ($i < $num) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
// Le name de l'utilisateur // Le name de l'utilisateur
@ -101,15 +96,12 @@ if ($resql)
//affichage des resultats //affichage des resultats
$ensemblereponses = $obj->reponses; $ensemblereponses = $obj->reponses;
for ($k = 0; $k < $nbcolonnes; $k++) for ($k = 0; $k < $nbcolonnes; $k++) {
{
$car = substr($ensemblereponses, $k, 1); $car = substr($ensemblereponses, $k, 1);
if ($car == "1") if ($car == "1") {
{
$input .= 'OK;'; $input .= 'OK;';
$somme[$k]++; $somme[$k]++;
} elseif ($car == "2") } elseif ($car == "2") {
{
$input .= 'KO;'; $input .= 'KO;';
$somme[$k]++; $somme[$k]++;
} else { } else {
@ -120,7 +112,9 @@ if ($resql)
$input .= "\r\n"; $input .= "\r\n";
$i++; $i++;
} }
} else dol_print_error($db); } else {
dol_print_error($db);
}
$filesize = strlen($input); $filesize = strlen($input);

View File

@ -96,19 +96,16 @@ function llxHeaderSurvey($title, $head = "", $disablejs = 0, $disablehead = 0, $
// Define urllogo // Define urllogo
$urllogo = ''; $urllogo = '';
$urllogofull = ''; $urllogofull = '';
if (!empty($logosmall) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$logosmall)) if (!empty($logosmall) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$logosmall)) {
{
$urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;entity='.$conf->entity.'&amp;file='.urlencode('logos/thumbs/'.$logosmall); $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;entity='.$conf->entity.'&amp;file='.urlencode('logos/thumbs/'.$logosmall);
$urllogofull = $dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/thumbs/'.$logosmall); $urllogofull = $dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/thumbs/'.$logosmall);
} elseif (!empty($logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$logo)) } elseif (!empty($logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$logo)) {
{
$urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;entity='.$conf->entity.'&amp;file='.urlencode('logos/'.$logo); $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;entity='.$conf->entity.'&amp;file='.urlencode('logos/'.$logo);
$urllogofull = $dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/'.$logo); $urllogofull = $dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/'.$logo);
} }
// Output html code for logo // Output html code for logo
if ($urllogo) if ($urllogo) {
{
print '<div class="backgreypublicpayment">'; print '<div class="backgreypublicpayment">';
print '<div class="logopublicpayment">'; print '<div class="logopublicpayment">';
print '<img id="dolpaymentlogo" src="'.$urllogo.'"'; print '<img id="dolpaymentlogo" src="'.$urllogo.'"';

View File

@ -31,7 +31,9 @@ require_once DOL_DOCUMENT_ROOT."/core/lib/files.lib.php";
$langs->load("opensurvey"); $langs->load("opensurvey");
// Security check // Security check
if (!$user->rights->opensurvey->read) accessforbidden(); if (!$user->rights->opensurvey->read) {
accessforbidden();
}
$hookmanager = new HookManager($db); $hookmanager = new HookManager($db);
@ -48,11 +50,12 @@ $sql = 'SELECT COUNT(*) as nb';
$sql .= ' FROM '.MAIN_DB_PREFIX.'opensurvey_sondage'; $sql .= ' FROM '.MAIN_DB_PREFIX.'opensurvey_sondage';
$sql .= ' WHERE entity IN ('.getEntity('survey').')'; $sql .= ' WHERE entity IN ('.getEntity('survey').')';
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
$nbsondages = $obj->nb; $nbsondages = $obj->nb;
} else dol_print_error($db, ''); } else {
dol_print_error($db, '');
}
$title = $langs->trans("OpenSurveyArea"); $title = $langs->trans("OpenSurveyArea");

View File

@ -50,7 +50,9 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST('sortfield', 'aZ09comma'); $sortfield = GETPOST('sortfield', 'aZ09comma');
$sortorder = GETPOST('sortorder', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) { $page = 0; } // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) {
$page = 0;
} // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
@ -67,24 +69,29 @@ $extrafields->fetch_name_optionals_label($object->table_element);
$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
// Default sort order (if not yet defined by previous GETPOST) // Default sort order (if not yet defined by previous GETPOST)
if (!$sortfield) $sortfield = "p.date_fin"; if (!$sortfield) {
if (!$sortorder) $sortorder = "DESC"; $sortfield = "p.date_fin";
}
if (!$sortorder) {
$sortorder = "DESC";
}
// Security check // Security check
if (!$user->rights->opensurvey->read) accessforbidden(); if (!$user->rights->opensurvey->read) {
accessforbidden();
}
// Definition of fields for list // Definition of fields for list
$arrayfields = array(); $arrayfields = array();
foreach ($arrayfields as $key => $val) foreach ($arrayfields as $key => $val) {
{
// If $val['visible']==0, then we never show the field // If $val['visible']==0, then we never show the field
if (!empty($val['visible'])) $arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>$val['enabled'], 'position'=>$val['position']); if (!empty($val['visible'])) {
$arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>$val['enabled'], 'position'=>$val['position']);
}
} }
// Extra fields // Extra fields
if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) {
{ foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val)
{
if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) { if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) {
$arrayfields["ef.".$key] = array( $arrayfields["ef.".$key] = array(
'label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'label'=>$extrafields->attributes[$object->table_element]['label'][$key],
@ -107,21 +114,25 @@ $permissiontodelete = $user->rights->opensurvey->delete;
* Actions * Actions
*/ */
if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } if (GETPOST('cancel', 'alpha')) {
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } $action = 'list'; $massaction = '';
}
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
$massaction = '';
}
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if (empty($reshook)) if (empty($reshook)) {
{
// Selection of new fields // Selection of new fields
include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
// Purge search criteria // Purge search criteria
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
{
$search_status = ''; $search_status = '';
$search_title = ''; $search_title = '';
$search_ref = ''; $search_ref = '';
@ -129,8 +140,7 @@ if (empty($reshook))
$search_array_options = array(); $search_array_options = array();
} }
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') 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')) || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) {
{
$massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation
} }
@ -160,11 +170,21 @@ $sql .= " u.login, u.firstname, u.lastname";
$sql .= " FROM ".MAIN_DB_PREFIX."opensurvey_sondage as p"; $sql .= " FROM ".MAIN_DB_PREFIX."opensurvey_sondage as p";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user u ON u.rowid = p.fk_user_creat"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user u ON u.rowid = p.fk_user_creat";
$sql .= " WHERE p.entity IN (".getEntity('survey').")"; $sql .= " WHERE p.entity IN (".getEntity('survey').")";
if ($search_status != '-1' && $search_status != '') $sql .= natural_search("p.status", $search_status, 2); if ($search_status != '-1' && $search_status != '') {
if ($search_expired == 'expired') $sql .= " AND p.date_fin < '".$db->idate($now)."'"; $sql .= natural_search("p.status", $search_status, 2);
if ($search_expired == 'opened') $sql .= " AND p.date_fin >= '".$db->idate($now)."'"; }
if ($search_ref) $sql .= natural_search("p.id_sondage", $search_ref); if ($search_expired == 'expired') {
if ($search_title) $sql .= natural_search("p.titre", $search_title); $sql .= " AND p.date_fin < '".$db->idate($now)."'";
}
if ($search_expired == 'opened') {
$sql .= " AND p.date_fin >= '".$db->idate($now)."'";
}
if ($search_ref) {
$sql .= natural_search("p.id_sondage", $search_ref);
}
if ($search_title) {
$sql .= natural_search("p.titre", $search_title);
}
// Add where from extra fields // Add where from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
// Add where from hooks // Add where from hooks
@ -176,26 +196,22 @@ $sql .= $db->order($sortfield, $sortorder);
// Count total nb of records // Count total nb of records
$nbtotalofrecords = ''; $nbtotalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
{
$resql = $db->query($sql); $resql = $db->query($sql);
$nbtotalofrecords = $db->num_rows($resql); $nbtotalofrecords = $db->num_rows($resql);
if (($page * $limit) > $nbtotalofrecords) // if total of record found is smaller than page * limit, goto and load page 0 if (($page * $limit) > $nbtotalofrecords) { // if total of record found is smaller than page * limit, goto and load page 0
{
$page = 0; $page = 0;
$offset = 0; $offset = 0;
} }
} }
// if total of record found is smaller than limit, no need to do paging and to restart another select with limits set. // if total of record found is smaller than limit, no need to do paging and to restart another select with limits set.
if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords) if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords) {
{
$num = $nbtotalofrecords; $num = $nbtotalofrecords;
} else { } else {
$sql .= $db->plimit($limit + 1, $offset); $sql .= $db->plimit($limit + 1, $offset);
$resql = $db->query($sql); $resql = $db->query($sql);
if (!$resql) if (!$resql) {
{
dol_print_error($db); dol_print_error($db);
exit; exit;
} }
@ -204,8 +220,7 @@ if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords)
} }
// Direct jump if only one record found // Direct jump if only one record found
if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
$id = $obj->rowid; $id = $obj->rowid;
header("Location: ".dol_buildpath('/opensurvey/card.php', 1).'?id='.$id); header("Location: ".dol_buildpath('/opensurvey/card.php', 1).'?id='.$id);
@ -221,11 +236,17 @@ llxHeader('', $title, $help_url);
$arrayofselected = is_array($toselect) ? $toselect : array(); $arrayofselected = is_array($toselect) ? $toselect : array();
$param = ''; $param = '';
if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); $param .= '&contextpage='.urlencode($contextpage);
}
if ($limit > 0 && $limit != $conf->liste_limit) {
$param .= '&limit='.urlencode($limit);
}
$fieldtosortuser = empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION) ? 'firstname' : 'lastname'; $fieldtosortuser = empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION) ? 'firstname' : 'lastname';
if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); if ($optioncss != '') {
$param .= '&optioncss='.urlencode($optioncss);
}
// Add $param from extra fields // Add $param from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
@ -234,15 +255,21 @@ $arrayofmassactions = array(
//'presend'=>$langs->trans("SendByMail"), //'presend'=>$langs->trans("SendByMail"),
//'builddoc'=>$langs->trans("PDFMerge"), //'builddoc'=>$langs->trans("PDFMerge"),
); );
if ($permissiontodelete) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); if ($permissiontodelete) {
if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete");
}
if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) {
$arrayofmassactions = array();
}
$massactionbutton = $form->selectMassAction('', $arrayofmassactions); $massactionbutton = $form->selectMassAction('', $arrayofmassactions);
// List of surveys into database // List of surveys into database
print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'; print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">';
if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; if ($optioncss != '') {
print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
}
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
print '<input type="hidden" name="action" value="list">'; print '<input type="hidden" name="action" value="list">';
@ -261,9 +288,10 @@ $objecttmp = new Opensurveysondage($db);
$trackid = 'surv'.$object->id; $trackid = 'surv'.$object->id;
include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';
if ($sall) if ($sall) {
{ foreach ($fieldstosearchall as $key => $val) {
foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); $fieldstosearchall[$key] = $langs->trans($val);
}
print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>'; print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>';
} }
@ -274,11 +302,13 @@ $moreforfilter.= '</div>';*/
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook
if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; if (empty($reshook)) {
else $moreforfilter = $hookmanager->resPrint; $moreforfilter .= $hookmanager->resPrint;
} else {
$moreforfilter = $hookmanager->resPrint;
}
if (!empty($moreforfilter)) if (!empty($moreforfilter)) {
{
print '<div class="liste_titre liste_titre_bydiv centpercent">'; print '<div class="liste_titre liste_titre_bydiv centpercent">';
print $moreforfilter; print $moreforfilter;
print '</div>'; print '</div>';
@ -346,18 +376,20 @@ print '</tr>'."\n";
// -------------------------------------------------------------------- // --------------------------------------------------------------------
$i = 0; $i = 0;
$totalarray = array(); $totalarray = array();
while ($i < min($num, $limit)) while ($i < min($num, $limit)) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
if (empty($obj)) break; // Should not happen if (empty($obj)) {
break; // Should not happen
}
$sql2 = 'select COUNT(*) as nb from '.MAIN_DB_PREFIX."opensurvey_user_studs where id_sondage='".$db->escape($obj->rowid)."'"; $sql2 = 'select COUNT(*) as nb from '.MAIN_DB_PREFIX."opensurvey_user_studs where id_sondage='".$db->escape($obj->rowid)."'";
$resql2 = $db->query($sql2); $resql2 = $db->query($sql2);
if ($resql2) if ($resql2) {
{
$obj2 = $db->fetch_object($resql2); $obj2 = $db->fetch_object($resql2);
$nbuser = $obj2->nb; $nbuser = $obj2->nb;
} else dol_print_error($db); } else {
dol_print_error($db);
}
$opensurvey_static->id = $obj->rowid; $opensurvey_static->id = $obj->rowid;
$opensurvey_static->ref = $obj->rowid; $opensurvey_static->ref = $obj->rowid;
@ -372,11 +404,15 @@ while ($i < min($num, $limit))
print '<td>'; print '<td>';
print $opensurvey_static->getNomUrl(1); print $opensurvey_static->getNomUrl(1);
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
// Title // Title
print '<td>'.dol_htmlentities($obj->title).'</td>'; print '<td>'.dol_htmlentities($obj->title).'</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
// Type // Type
print '<td>'; print '<td>';
@ -384,7 +420,9 @@ while ($i < min($num, $limit))
print img_picto('', dol_buildpath('/opensurvey/img/'.($type == 'classic' ? 'chart-32.png' : 'calendar-32.png'), 1), 'width="16"', 1); print img_picto('', dol_buildpath('/opensurvey/img/'.($type == 'classic' ? 'chart-32.png' : 'calendar-32.png'), 1), 'width="16"', 1);
print ' '.$langs->trans($type == 'classic' ? "TypeClassic" : "TypeDate"); print ' '.$langs->trans($type == 'classic' ? "TypeClassic" : "TypeDate");
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
print '<td>'; print '<td>';
// Author // Author
@ -400,23 +438,35 @@ while ($i < min($num, $limit))
print dol_htmlentities($obj->nom_admin); print dol_htmlentities($obj->nom_admin);
} }
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
// Nb of voters // Nb of voters
print'<td class="right">'.$nbuser.'</td>'."\n"; print'<td class="right">'.$nbuser.'</td>'."\n";
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
print '<td class="center">'.dol_print_date($db->jdate($obj->date_fin), 'day'); print '<td class="center">'.dol_print_date($db->jdate($obj->date_fin), 'day');
if ($db->jdate($obj->date_fin) < $now && $obj->status == Opensurveysondage::STATUS_VALIDATED) { print img_warning($langs->trans("Expired")); } if ($db->jdate($obj->date_fin) < $now && $obj->status == Opensurveysondage::STATUS_VALIDATED) {
print img_warning($langs->trans("Expired"));
}
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
print '<td class="center">'.dol_print_date($db->jdate($obj->tms), 'dayhour'); print '<td class="center">'.dol_print_date($db->jdate($obj->tms), 'dayhour');
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
print '<td class="center">'.$opensurvey_static->getLibStatut(5).'</td>'."\n"; print '<td class="center">'.$opensurvey_static->getLibStatut(5).'</td>'."\n";
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
// Extra fields // Extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
@ -426,14 +476,17 @@ while ($i < min($num, $limit))
print $hookmanager->resPrint; print $hookmanager->resPrint;
// Action column // Action column
print '<td class="nowrap center">'; print '<td class="nowrap center">';
if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
{
$selected = 0; $selected = 0;
if (in_array($obj->rowid, $arrayofselected)) $selected = 1; if (in_array($obj->rowid, $arrayofselected)) {
$selected = 1;
}
print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>'; print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>';
} }
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
print '</tr>'."\n"; print '</tr>'."\n";
$i++; $i++;
@ -444,10 +497,13 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php';
// If no record found // If no record found
if ($num == 0) if ($num == 0) {
{
$colspan = 8; $colspan = 8;
foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; } foreach ($arrayfields as $key => $val) {
if (!empty($val['checked'])) {
$colspan++;
}
}
print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>'; print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>';
} }
@ -463,10 +519,11 @@ print '</div>'."\n";
print '</form>'."\n"; print '</form>'."\n";
if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) {
{
$hidegeneratedfilelistifempty = 1; $hidegeneratedfilelistifempty = 1;
if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) {
$hidegeneratedfilelistifempty = 0;
}
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
$formfile = new FormFile($db); $formfile = new FormFile($db);

View File

@ -31,7 +31,9 @@ require_once DOL_DOCUMENT_ROOT."/opensurvey/fonctions.php";
// Security check // Security check
if (!$user->rights->opensurvey->read) accessforbidden(); if (!$user->rights->opensurvey->read) {
accessforbidden();
}
// Init vars // Init vars
@ -40,7 +42,9 @@ $numsondage = GETPOST("id");
$object = new Opensurveysondage($db); $object = new Opensurveysondage($db);
$result = $object->fetch(0, $numsondage); $result = $object->fetch(0, $numsondage);
if ($result <= 0) dol_print_error('', 'Failed to get survey id '.$numsondage); if ($result <= 0) {
dol_print_error('', 'Failed to get survey id '.$numsondage);
}
$nblines = $object->fetch_lines(); $nblines = $object->fetch_lines();
@ -58,20 +62,15 @@ if (GETPOST('retoursondage')) {
$nbcolonnes = substr_count($object->sujet, ',') + 1; $nbcolonnes = substr_count($object->sujet, ',') + 1;
// Add vote // Add vote
if (GETPOST("boutonp") || GETPOST("boutonp.x") || GETPOST("boutonp_x")) // boutonp for chrome, boutonp.x for firefox if (GETPOST("boutonp") || GETPOST("boutonp.x") || GETPOST("boutonp_x")) { // boutonp for chrome, boutonp.x for firefox
{ if (GETPOST('nom')) {
if (GETPOST('nom'))
{
$erreur_prenom = false; $erreur_prenom = false;
$nouveauchoix = ''; $nouveauchoix = '';
for ($i = 0; $i < $nbcolonnes; $i++) for ($i = 0; $i < $nbcolonnes; $i++) {
{ if (isset($_POST["choix$i"]) && $_POST["choix$i"] == '1') {
if (isset($_POST["choix$i"]) && $_POST["choix$i"] == '1')
{
$nouveauchoix .= "1"; $nouveauchoix .= "1";
} elseif (isset($_POST["choix$i"]) && $_POST["choix$i"] == '2') } elseif (isset($_POST["choix$i"]) && $_POST["choix$i"] == '2') {
{
$nouveauchoix .= "2"; $nouveauchoix .= "2";
} else { // sinon c'est 0 } else { // sinon c'est 0
$nouveauchoix .= "0"; $nouveauchoix .= "0";
@ -87,15 +86,16 @@ if (GETPOST("boutonp") || GETPOST("boutonp.x") || GETPOST("boutonp_x")) // bout
$sql .= ' ORDER BY id_users'; $sql .= ' ORDER BY id_users';
$resql = $db->query($sql); $resql = $db->query($sql);
$num_rows = $db->num_rows($resql); $num_rows = $db->num_rows($resql);
if ($num_rows > 0) if ($num_rows > 0) {
{
setEventMessages($langs->trans("VoteNameAlreadyExists"), null, 'errors'); setEventMessages($langs->trans("VoteNameAlreadyExists"), null, 'errors');
$error++; $error++;
} else { } else {
$sql = 'INSERT INTO '.MAIN_DB_PREFIX.'opensurvey_user_studs (nom, id_sondage, reponses)'; $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'opensurvey_user_studs (nom, id_sondage, reponses)';
$sql .= " VALUES ('".$db->escape($nom)."', '".$db->escape($numsondage)."','".$db->escape($nouveauchoix)."')"; $sql .= " VALUES ('".$db->escape($nom)."', '".$db->escape($numsondage)."','".$db->escape($nouveauchoix)."')";
$resql = $db->query($sql); $resql = $db->query($sql);
if (!$resql) dol_print_error($db); if (!$resql) {
dol_print_error($db);
}
} }
} }
} }
@ -104,35 +104,30 @@ if (GETPOST("boutonp") || GETPOST("boutonp.x") || GETPOST("boutonp_x")) // bout
$testmodifier = false; $testmodifier = false;
$testligneamodifier = false; $testligneamodifier = false;
$ligneamodifier = -1; $ligneamodifier = -1;
for ($i = 0; $i < $nblines; $i++) for ($i = 0; $i < $nblines; $i++) {
{ if (isset($_POST['modifierligne'.$i])) {
if (isset($_POST['modifierligne'.$i]))
{
$ligneamodifier = $i; $ligneamodifier = $i;
$testligneamodifier = true; $testligneamodifier = true;
} }
//test pour voir si une ligne est a modifier //test pour voir si une ligne est a modifier
if (isset($_POST['validermodifier'.$i])) if (isset($_POST['validermodifier'.$i])) {
{
$modifier = $i; $modifier = $i;
$testmodifier = true; $testmodifier = true;
} }
} }
if ($testmodifier) if ($testmodifier) {
{
// Security check // Security check
if (!$user->rights->opensurvey->write) accessforbidden(); if (!$user->rights->opensurvey->write) {
accessforbidden();
}
$nouveauchoix = ''; $nouveauchoix = '';
for ($i = 0; $i < $nbcolonnes; $i++) for ($i = 0; $i < $nbcolonnes; $i++) {
{
//var_dump($_POST["choix$i"]); //var_dump($_POST["choix$i"]);
if (isset($_POST["choix$i"]) && $_POST["choix$i"] == '1') if (isset($_POST["choix$i"]) && $_POST["choix$i"] == '1') {
{
$nouveauchoix .= "1"; $nouveauchoix .= "1";
} elseif (isset($_POST["choix$i"]) && $_POST["choix$i"] == '2') } elseif (isset($_POST["choix$i"]) && $_POST["choix$i"] == '2') {
{
$nouveauchoix .= "2"; $nouveauchoix .= "2";
} else { // sinon c'est 0 } else { // sinon c'est 0
$nouveauchoix .= "0"; $nouveauchoix .= "0";
@ -145,14 +140,17 @@ if ($testmodifier)
$sql .= " WHERE id_users = '".$db->escape($idtomodify)."'"; $sql .= " WHERE id_users = '".$db->escape($idtomodify)."'";
$resql = $db->query($sql); $resql = $db->query($sql);
if (!$resql) dol_print_error($db); if (!$resql) {
dol_print_error($db);
}
} }
// Add column (not for date) // Add column (not for date)
if (GETPOST("ajoutercolonne") && GETPOST('nouvellecolonne') && $object->format == "A") if (GETPOST("ajoutercolonne") && GETPOST('nouvellecolonne') && $object->format == "A") {
{
// Security check // Security check
if (!$user->rights->opensurvey->write) accessforbidden(); if (!$user->rights->opensurvey->write) {
accessforbidden();
}
$nouveauxsujets = $object->sujet; $nouveauxsujets = $object->sujet;
@ -165,17 +163,19 @@ if (GETPOST("ajoutercolonne") && GETPOST('nouvellecolonne') && $object->format =
$sql .= " SET sujet = '".$db->escape($nouveauxsujets)."'"; $sql .= " SET sujet = '".$db->escape($nouveauxsujets)."'";
$sql .= " WHERE id_sondage = '".$db->escape($numsondage)."'"; $sql .= " WHERE id_sondage = '".$db->escape($numsondage)."'";
$resql = $db->query($sql); $resql = $db->query($sql);
if (!$resql) dol_print_error($db); if (!$resql) {
else { dol_print_error($db);
} else {
header('Location: results.php?id='.$object->id_sondage); header('Location: results.php?id='.$object->id_sondage);
} }
} }
// Add column (with format date) // Add column (with format date)
if (isset($_POST["ajoutercolonne"]) && $object->format == "D") if (isset($_POST["ajoutercolonne"]) && $object->format == "D") {
{
// Security check // Security check
if (!$user->rights->opensurvey->write) accessforbidden(); if (!$user->rights->opensurvey->write) {
accessforbidden();
}
$nouveauxsujets = $object->sujet; $nouveauxsujets = $object->sujet;
@ -223,8 +223,7 @@ if (isset($_POST["ajoutercolonne"]) && $object->format == "D")
$cleinsertion = count($datesbase); $cleinsertion = count($datesbase);
} else { } else {
$nbdatesbase = count($datesbase); $nbdatesbase = count($datesbase);
for ($i = 0; $i < $nbdatesbase; $i++) for ($i = 0; $i < $nbdatesbase; $i++) {
{
$j = $i + 1; $j = $i + 1;
if ($nouvelledate > $datesbase[$i] && $nouvelledate < $datesbase[$j]) { if ($nouvelledate > $datesbase[$i] && $nouvelledate < $datesbase[$j]) {
$cleinsertion = $j; $cleinsertion = $j;
@ -244,14 +243,14 @@ if (isset($_POST["ajoutercolonne"]) && $object->format == "D")
$dateinsertion = substr("$dateinsertion", 1); $dateinsertion = substr("$dateinsertion", 1);
// update with new topics into database // update with new topics into database
if (isset($erreur_ajout_date) && empty($erreur_ajout_date)) if (isset($erreur_ajout_date) && empty($erreur_ajout_date)) {
{
$sql = 'UPDATE '.MAIN_DB_PREFIX."opensurvey_sondage"; $sql = 'UPDATE '.MAIN_DB_PREFIX."opensurvey_sondage";
$sql .= " SET sujet = '".$db->escape($dateinsertion)."'"; $sql .= " SET sujet = '".$db->escape($dateinsertion)."'";
$sql .= " WHERE id_sondage = '".$db->escape($numsondage)."'"; $sql .= " WHERE id_sondage = '".$db->escape($numsondage)."'";
$resql = $db->query($sql); $resql = $db->query($sql);
if (!$resql) dol_print_error($db); if (!$resql) {
else { dol_print_error($db);
} else {
header('Location: results.php?id='.$object->id_sondage); header('Location: results.php?id='.$object->id_sondage);
} }
} }
@ -263,12 +262,12 @@ if (isset($_POST["ajoutercolonne"]) && $object->format == "D")
} }
// Delete line // Delete line
for ($i = 0; $i < $nblines; $i++) for ($i = 0; $i < $nblines; $i++) {
{ if (GETPOST("effaceligne".$i) || GETPOST("effaceligne".$i."_x") || GETPOST("effaceligne".$i.".x")) { // effacelignei for chrome, effacelignei_x for firefox
if (GETPOST("effaceligne".$i) || GETPOST("effaceligne".$i."_x") || GETPOST("effaceligne".$i.".x")) // effacelignei for chrome, effacelignei_x for firefox
{
// Security check // Security check
if (!$user->rights->opensurvey->write) accessforbidden(); if (!$user->rights->opensurvey->write) {
accessforbidden();
}
$compteur = 0; $compteur = 0;
@ -278,14 +277,14 @@ for ($i = 0; $i < $nblines; $i++)
$sql .= " FROM ".MAIN_DB_PREFIX."opensurvey_user_studs"; $sql .= " FROM ".MAIN_DB_PREFIX."opensurvey_user_studs";
$sql .= " WHERE id_sondage = '".$db->escape($numsondage)."'"; $sql .= " WHERE id_sondage = '".$db->escape($numsondage)."'";
$resql = $db->query($sql); $resql = $db->query($sql);
if (!$resql) dol_print_error($db); if (!$resql) {
dol_print_error($db);
}
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
while ($compteur < $num) while ($compteur < $num) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
if ($compteur == $i) if ($compteur == $i) {
{
$sql2 = 'DELETE FROM '.MAIN_DB_PREFIX.'opensurvey_user_studs'; $sql2 = 'DELETE FROM '.MAIN_DB_PREFIX.'opensurvey_user_studs';
$sql2 .= ' WHERE id_users = '.$db->escape($obj->id_users); $sql2 .= ' WHERE id_users = '.$db->escape($obj->id_users);
$resql2 = $db->query($sql2); $resql2 = $db->query($sql2);
@ -297,13 +296,13 @@ for ($i = 0; $i < $nblines; $i++)
} }
// Delete column // Delete column
for ($i = 0; $i < $nbcolonnes; $i++) for ($i = 0; $i < $nbcolonnes; $i++) {
{
if ((GETPOST("effacecolonne".$i) || GETPOST("effacecolonne".$i."_x") || GETPOST("effacecolonne".$i.".x")) if ((GETPOST("effacecolonne".$i) || GETPOST("effacecolonne".$i."_x") || GETPOST("effacecolonne".$i.".x"))
&& $nbcolonnes > 1) // effacecolonnei for chrome, effacecolonnei_x for firefox && $nbcolonnes > 1) { // effacecolonnei for chrome, effacecolonnei_x for firefox
{
// Security check // Security check
if (!$user->rights->opensurvey->write) accessforbidden(); if (!$user->rights->opensurvey->write) {
accessforbidden();
}
$db->begin(); $db->begin();
@ -312,12 +311,12 @@ for ($i = 0; $i < $nbcolonnes; $i++)
$nouveauxsujets = ''; $nouveauxsujets = '';
//parcours de tous les sujets actuels //parcours de tous les sujets actuels
while (isset($toutsujet[$j])) while (isset($toutsujet[$j])) {
{
//si le sujet n'est pas celui qui a été effacé alors on concatene //si le sujet n'est pas celui qui a été effacé alors on concatene
if ($i != $j) if ($i != $j) {
{ if (!empty($nouveauxsujets)) {
if (!empty($nouveauxsujets)) $nouveauxsujets .= ','; $nouveauxsujets .= ',';
}
$nouveauxsujets .= $toutsujet[$j]; $nouveauxsujets .= $toutsujet[$j];
} }
@ -328,7 +327,9 @@ for ($i = 0; $i < $nbcolonnes; $i++)
$sql = 'UPDATE '.MAIN_DB_PREFIX."opensurvey_sondage"; $sql = 'UPDATE '.MAIN_DB_PREFIX."opensurvey_sondage";
$sql .= " SET sujet = '".$db->escape($nouveauxsujets)."' WHERE id_sondage = '".$db->escape($numsondage)."'"; $sql .= " SET sujet = '".$db->escape($nouveauxsujets)."' WHERE id_sondage = '".$db->escape($numsondage)."'";
$resql = $db->query($sql); $resql = $db->query($sql);
if (!$resql) dol_print_error($db); if (!$resql) {
dol_print_error($db);
}
// Clean current answer to remove deleted columns // Clean current answer to remove deleted columns
$compteur = 0; $compteur = 0;
@ -337,22 +338,19 @@ for ($i = 0; $i < $nbcolonnes; $i++)
$sql .= " WHERE id_sondage = '".$db->escape($numsondage)."'"; $sql .= " WHERE id_sondage = '".$db->escape($numsondage)."'";
dol_syslog('sql='.$sql); dol_syslog('sql='.$sql);
$resql = $db->query($sql); $resql = $db->query($sql);
if (!$resql) if (!$resql) {
{
dol_print_error($db); dol_print_error($db);
exit; exit;
} }
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
while ($compteur < $num) while ($compteur < $num) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
$newcar = ''; $newcar = '';
$ensemblereponses = $obj->reponses; $ensemblereponses = $obj->reponses;
// parcours de toutes les réponses actuelles // parcours de toutes les réponses actuelles
for ($j = 0; $j < $nbcolonnes; $j++) for ($j = 0; $j < $nbcolonnes; $j++) {
{
$car = substr($ensemblereponses, $j, 1); $car = substr($ensemblereponses, $j, 1);
//si les reponses ne concerne pas la colonne effacée, on concatene //si les reponses ne concerne pas la colonne effacée, on concatene
if ($i != $j) { if ($i != $j) {
@ -389,8 +387,7 @@ if ($object->fk_user_creat) {
} }
$result = $object->fetch(0, $numsondage); $result = $object->fetch(0, $numsondage);
if ($result <= 0) if ($result <= 0) {
{
dol_print_error($db, $object->error); dol_print_error($db, $object->error);
exit; exit;
} }
@ -405,8 +402,7 @@ llxHeader('', $title, $helpurl, 0, 0, 0, $arrayofjs, $arrayofcss);
// Define format of choices // Define format of choices
$toutsujet = explode(",", $object->sujet); $toutsujet = explode(",", $object->sujet);
$listofanswers = array(); $listofanswers = array();
foreach ($toutsujet as $value) foreach ($toutsujet as $value) {
{
$tmp = explode('@', $value); $tmp = explode('@', $value);
$listofanswers[] = array('label'=>$tmp[0], 'format'=>($tmp[1] ? $tmp[1] : 'checkbox')); $listofanswers[] = array('label'=>$tmp[0], 'format'=>($tmp[1] ? $tmp[1] : 'checkbox'));
} }
@ -452,10 +448,13 @@ print '</td></tr>';
// Expire date // Expire date
print '<tr><td>'.$langs->trans('ExpireDate').'</td><td colspan="2">'; print '<tr><td>'.$langs->trans('ExpireDate').'</td><td colspan="2">';
if ($action == 'edit') print $form->selectDate($expiredate ? $expiredate : $object->date_fin, 'expire', 0, 0, 0, '', 1, 0); if ($action == 'edit') {
else { print $form->selectDate($expiredate ? $expiredate : $object->date_fin, 'expire', 0, 0, 0, '', 1, 0);
} else {
print dol_print_date($object->date_fin, 'day'); print dol_print_date($object->date_fin, 'day');
if ($object->date_fin && $object->date_fin < dol_now() && $object->status == Opensurveysondage::STATUS_VALIDATED) print img_warning($langs->trans("Expired")); if ($object->date_fin && $object->date_fin < dol_now() && $object->status == Opensurveysondage::STATUS_VALIDATED) {
print img_warning($langs->trans("Expired"));
}
} }
print '</td></tr>'; print '</td></tr>';
@ -480,8 +479,7 @@ $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domai
$url = $urlwithouturlroot.dol_buildpath('/public/opensurvey/studs.php', 1).'?sondage='.$object->id_sondage; $url = $urlwithouturlroot.dol_buildpath('/public/opensurvey/studs.php', 1).'?sondage='.$object->id_sondage;
$urllink = '<input type="text" style="width: 60%" '.($action == 'edit' ? 'disabled' : '').' id="opensurveyurl" name="opensurveyurl" value="'.$url.'">'; $urllink = '<input type="text" style="width: 60%" '.($action == 'edit' ? 'disabled' : '').' id="opensurveyurl" name="opensurveyurl" value="'.$url.'">';
print $urllink; print $urllink;
if ($action != 'edit') if ($action != 'edit') {
{
print '<script type="text/javascript"> print '<script type="text/javascript">
jQuery(document).ready(function () { jQuery(document).ready(function () {
jQuery("#opensurveyurl").click(function() { jQuery(this).select(); } ); jQuery("#opensurveyurl").click(function() { jQuery(this).select(); } );
@ -511,10 +509,11 @@ print '</div>';
// Show form to add a new field/column // Show form to add a new field/column
if (GETPOST('ajoutsujet')) if (GETPOST('ajoutsujet')) {
{
// Security check // Security check
if (!$user->rights->opensurvey->write) accessforbidden(); if (!$user->rights->opensurvey->write) {
accessforbidden();
}
print '<form name="formulaire" action="" method="POST">'."\n"; print '<form name="formulaire" action="" method="POST">'."\n";
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
@ -524,8 +523,7 @@ if (GETPOST('ajoutsujet'))
print "<br><br>\n"; print "<br><br>\n";
// Add new column // Add new column
if ($object->format == "A") if ($object->format == "A") {
{
print $langs->trans("AddNewColumn").':<br><br>'; print $langs->trans("AddNewColumn").':<br><br>';
print $langs->trans("Title").' <input type="text" name="nouvellecolonne" size="40"><br>'; print $langs->trans("Title").' <input type="text" name="nouvellecolonne" size="40"><br>';
$tmparray = array('checkbox'=>$langs->trans("CheckBox"), 'yesno'=>$langs->trans("YesNoList"), 'foragainst'=>$langs->trans("PourContreList")); $tmparray = array('checkbox'=>$langs->trans("CheckBox"), 'yesno'=>$langs->trans("YesNoList"), 'foragainst'=>$langs->trans("PourContreList"));
@ -628,8 +626,7 @@ print '</tr>'."\n";
// Show choice titles // Show choice titles
if ($object->format == "D") if ($object->format == "D") {
{
//affichage des sujets du sondage //affichage des sujets du sondage
print '<tr>'."\n"; print '<tr>'."\n";
print '<td></td>'."\n"; print '<td></td>'."\n";
@ -638,8 +635,7 @@ if ($object->format == "D")
//affichage des années //affichage des années
$colspan = 1; $colspan = 1;
$nbofsujet = count($toutsujet); $nbofsujet = count($toutsujet);
for ($i = 0; $i < $nbofsujet; $i++) for ($i = 0; $i < $nbofsujet; $i++) {
{
$current = $toutsujet[$i]; $current = $toutsujet[$i];
if (strpos($toutsujet[$i], '@') !== false) { if (strpos($toutsujet[$i], '@') !== false) {
@ -653,15 +649,20 @@ if ($object->format == "D")
} }
$currenty = 0; $currenty = 0;
if ($current) $currenty = strftime("%Y", $current); if ($current) {
$currenty = strftime("%Y", $current);
}
$next = 0; $next = 0;
if ($next) $nexty = strftime("%Y", $next); if ($next) {
if (isset($toutsujet[$i + 1]) && ($currenty == $nexty)) $nexty = strftime("%Y", $next);
{ }
if (isset($toutsujet[$i + 1]) && ($currenty == $nexty)) {
$colspan++; $colspan++;
} else { } else {
print '<td colspan='.$colspan.' class="annee">'; print '<td colspan='.$colspan.' class="annee">';
if ($current) print strftime("%Y", $current); if ($current) {
print strftime("%Y", $current);
}
print '</td>'."\n"; print '</td>'."\n";
$colspan = 1; $colspan = 1;
} }
@ -756,8 +757,7 @@ if ($object->format == "D")
print '<td></td>'."\n"; print '<td></td>'."\n";
print '<td></td>'."\n"; print '<td></td>'."\n";
for ($i = 0; isset($toutsujet[$i]); $i++) for ($i = 0; isset($toutsujet[$i]); $i++) {
{
$tmp = explode('@', $toutsujet[$i]); $tmp = explode('@', $toutsujet[$i]);
print '<td class="sujet">'.dol_htmlentities($tmp[0]).'</td>'."\n"; print '<td class="sujet">'.dol_htmlentities($tmp[0]).'</td>'."\n";
} }
@ -776,14 +776,12 @@ $sql .= " FROM ".MAIN_DB_PREFIX."opensurvey_user_studs";
$sql .= " WHERE id_sondage = '".$db->escape($numsondage)."'"; $sql .= " WHERE id_sondage = '".$db->escape($numsondage)."'";
dol_syslog('sql='.$sql); dol_syslog('sql='.$sql);
$resql = $db->query($sql); $resql = $db->query($sql);
if (!$resql) if (!$resql) {
{
dol_print_error($db); dol_print_error($db);
exit; exit;
} }
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
while ($compteur < $num) while ($compteur < $num) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
$ensemblereponses = $obj->reponses; $ensemblereponses = $obj->reponses;
@ -798,121 +796,167 @@ while ($compteur < $num)
print '</td><td class="nom">'.dol_htmlentities($obj->name).'</td>'."\n"; print '</td><td class="nom">'.dol_htmlentities($obj->name).'</td>'."\n";
// si la ligne n'est pas a changer, on affiche les données // si la ligne n'est pas a changer, on affiche les données
if (!$testligneamodifier) if (!$testligneamodifier) {
{ for ($i = 0; $i < $nbcolonnes; $i++) {
for ($i = 0; $i < $nbcolonnes; $i++)
{
$car = substr($ensemblereponses, $i, 1); $car = substr($ensemblereponses, $i, 1);
//print 'xx'.$i."-".$car.'-'.$listofanswers[$i]['format'].'zz'; //print 'xx'.$i."-".$car.'-'.$listofanswers[$i]['format'].'zz';
if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) {
{ if (((string) $car) == "1") {
if (((string) $car) == "1") print '<td class="ok">OK</td>'."\n"; print '<td class="ok">OK</td>'."\n";
else print '<td class="non">KO</td>'."\n"; } else {
// Total print '<td class="non">KO</td>'."\n";
if (!isset($sumfor[$i])) $sumfor[$i] = 0;
if (((string) $car) == "1") $sumfor[$i]++;
} }
if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno')
{
if (((string) $car) == "1") print '<td class="ok">'.$langs->trans("Yes").'</td>'."\n";
elseif (((string) $car) == "0") print '<td class="non">'.$langs->trans("No").'</td>'."\n";
else print '<td class="vide">&nbsp;</td>'."\n";
// Total // Total
if (!isset($sumfor[$i])) $sumfor[$i] = 0; if (!isset($sumfor[$i])) {
if (!isset($sumagainst[$i])) $sumagainst[$i] = 0; $sumfor[$i] = 0;
if (((string) $car) == "1") $sumfor[$i]++; }
if (((string) $car) == "0") $sumagainst[$i]++; if (((string) $car) == "1") {
$sumfor[$i]++;
}
}
if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') {
if (((string) $car) == "1") {
print '<td class="ok">'.$langs->trans("Yes").'</td>'."\n";
} elseif (((string) $car) == "0") {
print '<td class="non">'.$langs->trans("No").'</td>'."\n";
} else {
print '<td class="vide">&nbsp;</td>'."\n";
} }
if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst')
{
if (((string) $car) == "1") print '<td class="ok">'.$langs->trans("For").'</td>'."\n";
elseif (((string) $car) == "0") print '<td class="non">'.$langs->trans("Against").'</td>'."\n";
else print '<td class="vide">&nbsp;</td>'."\n";
// Total // Total
if (!isset($sumfor[$i])) $sumfor[$i] = 0; if (!isset($sumfor[$i])) {
if (!isset($sumagainst[$i])) $sumagainst[$i] = 0; $sumfor[$i] = 0;
if (((string) $car) == "1") $sumfor[$i]++; }
if (((string) $car) == "0") $sumagainst[$i]++; if (!isset($sumagainst[$i])) {
$sumagainst[$i] = 0;
}
if (((string) $car) == "1") {
$sumfor[$i]++;
}
if (((string) $car) == "0") {
$sumagainst[$i]++;
}
}
if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') {
if (((string) $car) == "1") {
print '<td class="ok">'.$langs->trans("For").'</td>'."\n";
} elseif (((string) $car) == "0") {
print '<td class="non">'.$langs->trans("Against").'</td>'."\n";
} else {
print '<td class="vide">&nbsp;</td>'."\n";
}
// Total
if (!isset($sumfor[$i])) {
$sumfor[$i] = 0;
}
if (!isset($sumagainst[$i])) {
$sumagainst[$i] = 0;
}
if (((string) $car) == "1") {
$sumfor[$i]++;
}
if (((string) $car) == "0") {
$sumagainst[$i]++;
}
} }
} }
} else { } else {
//sinon on remplace les choix de l'utilisateur par une ligne de checkbox pour recuperer de nouvelles valeurs //sinon on remplace les choix de l'utilisateur par une ligne de checkbox pour recuperer de nouvelles valeurs
if ($compteur == $ligneamodifier) if ($compteur == $ligneamodifier) {
{ for ($i = 0; $i < $nbcolonnes; $i++) {
for ($i = 0; $i < $nbcolonnes; $i++)
{
$car = substr($ensemblereponses, $i, 1); $car = substr($ensemblereponses, $i, 1);
print '<td class="vide">'; print '<td class="vide">';
if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) {
{
print '<input type="checkbox" name="choix'.$i.'" value="1" '; print '<input type="checkbox" name="choix'.$i.'" value="1" ';
if ($car == '1') print 'checked'; if ($car == '1') {
print 'checked';
}
print '>'; print '>';
} }
if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') {
{
$arraychoice = array('2'=>'&nbsp;', '0'=>$langs->trans("No"), '1'=>$langs->trans("Yes")); $arraychoice = array('2'=>'&nbsp;', '0'=>$langs->trans("No"), '1'=>$langs->trans("Yes"));
print $form->selectarray("choix".$i, $arraychoice, $car); print $form->selectarray("choix".$i, $arraychoice, $car);
} }
if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') {
{
$arraychoice = array('2'=>'&nbsp;', '0'=>$langs->trans("Against"), '1'=>$langs->trans("For")); $arraychoice = array('2'=>'&nbsp;', '0'=>$langs->trans("Against"), '1'=>$langs->trans("For"));
print $form->selectarray("choix".$i, $arraychoice, $car); print $form->selectarray("choix".$i, $arraychoice, $car);
} }
print '</td>'."\n"; print '</td>'."\n";
} }
} else { } else {
for ($i = 0; $i < $nbcolonnes; $i++) for ($i = 0; $i < $nbcolonnes; $i++) {
{
$car = substr($ensemblereponses, $i, 1); $car = substr($ensemblereponses, $i, 1);
if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) {
{ if (((string) $car) == "1") {
if (((string) $car) == "1") print '<td class="ok">OK</td>'."\n"; print '<td class="ok">OK</td>'."\n";
else print '<td class="non">KO</td>'."\n"; } else {
// Total print '<td class="non">KO</td>'."\n";
if (!isset($sumfor[$i])) $sumfor[$i] = 0;
if (((string) $car) == "1") $sumfor[$i]++;
} }
if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno')
{
if (((string) $car) == "1") print '<td class="ok">'.$langs->trans("For").'</td>'."\n";
elseif (((string) $car) == "0") print '<td class="non">'.$langs->trans("Against").'</td>'."\n";
else print '<td class="vide">&nbsp;</td>'."\n";
// Total // Total
if (!isset($sumfor[$i])) $sumfor[$i] = 0; if (!isset($sumfor[$i])) {
if (!isset($sumagainst[$i])) $sumagainst[$i] = 0; $sumfor[$i] = 0;
if (((string) $car) == "1") $sumfor[$i]++; }
if (((string) $car) == "0") $sumagainst[$i]++; if (((string) $car) == "1") {
$sumfor[$i]++;
}
}
if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') {
if (((string) $car) == "1") {
print '<td class="ok">'.$langs->trans("For").'</td>'."\n";
} elseif (((string) $car) == "0") {
print '<td class="non">'.$langs->trans("Against").'</td>'."\n";
} else {
print '<td class="vide">&nbsp;</td>'."\n";
} }
if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst')
{
if (((string) $car) == "1") print '<td class="ok">'.$langs->trans("For").'</td>'."\n";
elseif (((string) $car) == "0") print '<td class="non">'.$langs->trans("Against").'</td>'."\n";
else print '<td class="vide">&nbsp;</td>'."\n";
// Total // Total
if (!isset($sumfor[$i])) $sumfor[$i] = 0; if (!isset($sumfor[$i])) {
if (!isset($sumagainst[$i])) $sumagainst[$i] = 0; $sumfor[$i] = 0;
if (((string) $car) == "1") $sumfor[$i]++; }
if (((string) $car) == "0") $sumagainst[$i]++; if (!isset($sumagainst[$i])) {
$sumagainst[$i] = 0;
}
if (((string) $car) == "1") {
$sumfor[$i]++;
}
if (((string) $car) == "0") {
$sumagainst[$i]++;
}
}
if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') {
if (((string) $car) == "1") {
print '<td class="ok">'.$langs->trans("For").'</td>'."\n";
} elseif (((string) $car) == "0") {
print '<td class="non">'.$langs->trans("Against").'</td>'."\n";
} else {
print '<td class="vide">&nbsp;</td>'."\n";
}
// Total
if (!isset($sumfor[$i])) {
$sumfor[$i] = 0;
}
if (!isset($sumagainst[$i])) {
$sumagainst[$i] = 0;
}
if (((string) $car) == "1") {
$sumfor[$i]++;
}
if (((string) $car) == "0") {
$sumagainst[$i]++;
}
} }
} }
} }
} }
// Button edit at end of line // Button edit at end of line
if ($compteur != $ligneamodifier && ($user->rights->opensurvey->write)) if ($compteur != $ligneamodifier && ($user->rights->opensurvey->write)) {
{
print '<td class="casevide"><input type="submit" class="button" name="modifierligne'.$compteur.'" value="'.dol_escape_htmltag($langs->trans("Edit")).'"></td>'."\n"; print '<td class="casevide"><input type="submit" class="button" name="modifierligne'.$compteur.'" value="'.dol_escape_htmltag($langs->trans("Edit")).'"></td>'."\n";
} }
//demande de confirmation pour modification de ligne //demande de confirmation pour modification de ligne
for ($i = 0; $i < $nblines; $i++) for ($i = 0; $i < $nblines; $i++) {
{ if (GETPOSTISSET("modifierligne".$i)) {
if (GETPOSTISSET("modifierligne".$i)) if ($compteur == $i) {
{
if ($compteur == $i)
{
print '<td class="casevide">'; print '<td class="casevide">';
print '<input type="hidden" name="idtomodify'.$compteur.'" value="'.$obj->id_users.'">'; print '<input type="hidden" name="idtomodify'.$compteur.'" value="'.$obj->id_users.'">';
print '<input type="submit" class="button button-save" name="validermodifier'.$compteur.'" value="'.dol_escape_htmltag($langs->trans("Save")).'">'; print '<input type="submit" class="button button-save" name="validermodifier'.$compteur.'" value="'.dol_escape_htmltag($langs->trans("Save")).'">';
@ -926,33 +970,27 @@ while ($compteur < $num)
} }
// Add line to add new record // Add line to add new record
if (empty($testligneamodifier)) if (empty($testligneamodifier)) {
{
print '<tr>'."\n"; print '<tr>'."\n";
print '<td></td>'."\n"; print '<td></td>'."\n";
print '<td class="nom">'."\n"; print '<td class="nom">'."\n";
print '<input type="text" placeholder="'.dol_escape_htmltag($langs->trans("Name")).'" name="nom" maxlength="64" size="24">'."\n"; print '<input type="text" placeholder="'.dol_escape_htmltag($langs->trans("Name")).'" name="nom" maxlength="64" size="24">'."\n";
print '</td>'."\n"; print '</td>'."\n";
for ($i = 0; $i < $nbcolonnes; $i++) for ($i = 0; $i < $nbcolonnes; $i++) {
{
print '<td class="vide">'; print '<td class="vide">';
if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) {
{
print '<input type="checkbox" name="choix'.$i.'" value="1"'; print '<input type="checkbox" name="choix'.$i.'" value="1"';
if (GETPOSTISSET('choix'.$i) && GETPOST('choix'.$i) == '1') if (GETPOSTISSET('choix'.$i) && GETPOST('choix'.$i) == '1') {
{
print ' checked'; print ' checked';
} }
print '>'; print '>';
} }
if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') {
{
$arraychoice = array('2'=>'&nbsp;', '0'=>$langs->trans("No"), '1'=>$langs->trans("Yes")); $arraychoice = array('2'=>'&nbsp;', '0'=>$langs->trans("No"), '1'=>$langs->trans("Yes"));
print $form->selectarray("choix".$i, $arraychoice); print $form->selectarray("choix".$i, $arraychoice);
} }
if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') {
{
$arraychoice = array('2'=>'&nbsp;', '0'=>$langs->trans("Against"), '1'=>$langs->trans("For")); $arraychoice = array('2'=>'&nbsp;', '0'=>$langs->trans("Against"), '1'=>$langs->trans("For"));
print $form->selectarray("choix".$i, $arraychoice); print $form->selectarray("choix".$i, $arraychoice);
} }
@ -966,18 +1004,15 @@ if (empty($testligneamodifier))
// Select value of best choice (for checkbox columns only) // Select value of best choice (for checkbox columns only)
$nbofcheckbox = 0; $nbofcheckbox = 0;
for ($i = 0; $i < $nbcolonnes + 1; $i++) for ($i = 0; $i < $nbcolonnes + 1; $i++) {
{ if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) {
if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst')))
$nbofcheckbox++; $nbofcheckbox++;
if (isset($sumfor[$i])) }
{ if (isset($sumfor[$i])) {
if ($i == 0) if ($i == 0) {
{
$meilleurecolonne = $sumfor[$i]; $meilleurecolonne = $sumfor[$i];
} }
if (isset($sumfor[$i]) && $sumfor[$i] > $meilleurecolonne) if (isset($sumfor[$i]) && $sumfor[$i] > $meilleurecolonne) {
{
$meilleurecolonne = $sumfor[$i]; $meilleurecolonne = $sumfor[$i];
} }
} }
@ -988,29 +1023,36 @@ for ($i = 0; $i < $nbcolonnes + 1; $i++)
print '<tr>'."\n"; print '<tr>'."\n";
print '<td></td>'."\n"; print '<td></td>'."\n";
print '<td class="center">'.$langs->trans("Total").'</td>'."\n"; print '<td class="center">'.$langs->trans("Total").'</td>'."\n";
for ($i = 0; $i < $nbcolonnes; $i++) for ($i = 0; $i < $nbcolonnes; $i++) {
{
$showsumfor = isset($sumfor[$i]) ? $sumfor[$i] : ''; $showsumfor = isset($sumfor[$i]) ? $sumfor[$i] : '';
$showsumagainst = isset($sumagainst[$i]) ? $sumagainst[$i] : ''; $showsumagainst = isset($sumagainst[$i]) ? $sumagainst[$i] : '';
if (empty($showsumfor)) $showsumfor = 0; if (empty($showsumfor)) {
if (empty($showsumagainst)) $showsumagainst = 0; $showsumfor = 0;
}
if (empty($showsumagainst)) {
$showsumagainst = 0;
}
print '<td>'; print '<td>';
if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) print $showsumfor; if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) {
if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') print $langs->trans("Yes").': '.$showsumfor.'<br>'.$langs->trans("No").': '.$showsumagainst; print $showsumfor;
if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') print $langs->trans("For").': '.$showsumfor.'<br>'.$langs->trans("Against").': '.$showsumagainst; }
if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') {
print $langs->trans("Yes").': '.$showsumfor.'<br>'.$langs->trans("No").': '.$showsumagainst;
}
if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') {
print $langs->trans("For").': '.$showsumfor.'<br>'.$langs->trans("Against").': '.$showsumagainst;
}
print '</td>'."\n"; print '</td>'."\n";
} }
print '</tr>'; print '</tr>';
// Show picto winner // Show picto winner
if ($nbofcheckbox >= 2) if ($nbofcheckbox >= 2) {
{
print '<tr>'."\n"; print '<tr>'."\n";
print '<td></td>'."\n"; print '<td></td>'."\n";
print '<td></td>'."\n"; print '<td></td>'."\n";
for ($i = 0; $i < $nbcolonnes; $i++) { for ($i = 0; $i < $nbcolonnes; $i++) {
if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst')) && isset($sumfor[$i]) && isset($meilleurecolonne) && $sumfor[$i] == $meilleurecolonne) if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst')) && isset($sumfor[$i]) && isset($meilleurecolonne) && $sumfor[$i] == $meilleurecolonne) {
{
print '<td class="somme"><img src="'.dol_buildpath('/opensurvey/img/medaille.png', 1).'"></td>'."\n"; print '<td class="somme"><img src="'.dol_buildpath('/opensurvey/img/medaille.png', 1).'"></td>'."\n";
} else { } else {
print '<td class="somme"></td>'."\n"; print '<td class="somme"></td>'."\n";
@ -1041,10 +1083,8 @@ $toutsujet = explode(",", $object->sujet); // With old versions, this field was
$compteursujet = 0; $compteursujet = 0;
$meilleursujet = ''; $meilleursujet = '';
for ($i = 0; $i < $nbcolonnes; $i++) for ($i = 0; $i < $nbcolonnes; $i++) {
{ if (isset($sumfor[$i]) === true && isset($meilleurecolonne) === true && $sumfor[$i] == $meilleurecolonne) {
if (isset($sumfor[$i]) === true && isset($meilleurecolonne) === true && $sumfor[$i] == $meilleurecolonne)
{
$meilleursujet .= ", "; $meilleursujet .= ", ";
if ($object->format == "D") { if ($object->format == "D") {
@ -1068,8 +1108,7 @@ $meilleursujet = substr($meilleursujet, 1);
$meilleursujet = str_replace("°", "'", $meilleursujet); $meilleursujet = str_replace("°", "'", $meilleursujet);
// Show best choice // Show best choice
if ($nbofcheckbox >= 2) if ($nbofcheckbox >= 2) {
{
$vote_str = $langs->trans('votes'); $vote_str = $langs->trans('votes');
print '<p class="affichageresultats">'."\n"; print '<p class="affichageresultats">'."\n";

View File

@ -28,7 +28,9 @@ require_once DOL_DOCUMENT_ROOT."/core/lib/files.lib.php";
require_once DOL_DOCUMENT_ROOT."/opensurvey/fonctions.php"; require_once DOL_DOCUMENT_ROOT."/opensurvey/fonctions.php";
// Security check // Security check
if (!$user->rights->opensurvey->write) accessforbidden(); if (!$user->rights->opensurvey->write) {
accessforbidden();
}
@ -53,20 +55,16 @@ if (isset($_SESSION["nbrecases"])) {
$_SESSION["nbrecases"] = 5; $_SESSION["nbrecases"] = 5;
} }
if (GETPOST("ajoutcases") || GETPOST("ajoutcases_x")) if (GETPOST("ajoutcases") || GETPOST("ajoutcases_x")) {
{
$_SESSION["nbrecases"] = $_SESSION["nbrecases"] + 5; $_SESSION["nbrecases"] = $_SESSION["nbrecases"] + 5;
} }
// Create survey into database // Create survey into database
if (GETPOSTISSET("confirmecreation")) if (GETPOSTISSET("confirmecreation")) {
{
//recuperation des données de champs textes //recuperation des données de champs textes
$toutchoix = ''; $toutchoix = '';
for ($i = 0; $i < $_SESSION["nbrecases"] + 1; $i++) for ($i = 0; $i < $_SESSION["nbrecases"] + 1; $i++) {
{ if (!empty($arrayofchoices[$i])) {
if (!empty($arrayofchoices[$i]))
{
$toutchoix .= ','; $toutchoix .= ',';
$toutchoix .= str_replace(array(",", "@"), " ", $arrayofchoices[$i]).(empty($arrayoftypecolumn[$i]) ? '' : '@'.$arrayoftypecolumn[$i]); $toutchoix .= str_replace(array(",", "@"), " ", $arrayofchoices[$i]).(empty($arrayoftypecolumn[$i]) ? '' : '@'.$arrayoftypecolumn[$i]);
} }
@ -77,10 +75,8 @@ if (GETPOSTISSET("confirmecreation"))
//test de remplissage des cases //test de remplissage des cases
$testremplissage = ''; $testremplissage = '';
for ($i = 0; $i < $_SESSION["nbrecases"]; $i++) for ($i = 0; $i < $_SESSION["nbrecases"]; $i++) {
{ if (isset($arrayofchoices[$i])) {
if (isset($arrayofchoices[$i]))
{
$testremplissage = "ok"; $testremplissage = "ok";
} }
} }
@ -107,8 +103,7 @@ $arrayofjs = array();
$arrayofcss = array('/opensurvey/css/style.css'); $arrayofcss = array('/opensurvey/css/style.css');
llxHeader('', $langs->trans("OpenSurvey"), "", '', 0, 0, $arrayofjs, $arrayofcss); llxHeader('', $langs->trans("OpenSurvey"), "", '', 0, 0, $arrayofjs, $arrayofcss);
if (empty($_SESSION['title'])) if (empty($_SESSION['title'])) {
{
dol_print_error('', $langs->trans('ErrorOpenSurveyFillFirstSection')); dol_print_error('', $langs->trans('ErrorOpenSurveyFillFirstSection'));
llxFooter(); llxFooter();
exit; exit;

View File

@ -28,7 +28,9 @@ require_once DOL_DOCUMENT_ROOT."/core/lib/files.lib.php";
require_once DOL_DOCUMENT_ROOT."/opensurvey/fonctions.php"; require_once DOL_DOCUMENT_ROOT."/opensurvey/fonctions.php";
// Security check // Security check
if (!$user->rights->opensurvey->write) accessforbidden(); if (!$user->rights->opensurvey->write) {
accessforbidden();
}
// Survey type is DATE // Survey type is DATE
$_SESSION["formatsondage"] = "D"; $_SESSION["formatsondage"] = "D";
@ -40,19 +42,15 @@ $erreur = false;
*/ */
// Insert survey // Insert survey
if (GETPOST('confirmation')) if (GETPOST('confirmation')) {
{
// We save hours entered // We save hours entered
if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true && issetAndNoEmpty('nbrecaseshoraires', $_SESSION) === true) if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true && issetAndNoEmpty('nbrecaseshoraires', $_SESSION) === true) {
{
$nbofchoice = count($_SESSION["totalchoixjour"]); $nbofchoice = count($_SESSION["totalchoixjour"]);
$errheure = array(); $errheure = array();
for ($i = 0; $i < $nbofchoice; $i++) for ($i = 0; $i < $nbofchoice; $i++) {
{
// Show hours choices // Show hours choices
for ($j = 0; $j < $_SESSION["nbrecaseshoraires"]; $j++) for ($j = 0; $j < $_SESSION["nbrecaseshoraires"]; $j++) {
{
$_SESSION["horaires$i"][$j] = $_POST["horaires$i"][$j]; $_SESSION["horaires$i"][$j] = $_POST["horaires$i"][$j];
$tmphorairesi = GETPOST('horaires'.$i, 'array'); $tmphorairesi = GETPOST('horaires'.$i, 'array');
@ -170,8 +168,7 @@ if (GETPOST('confirmation'))
} }
// Add survey into database // Add survey into database
if (!$erreur) if (!$erreur) {
{
$_SESSION["toutchoix"] = substr("$choixdate", 1); $_SESSION["toutchoix"] = substr("$choixdate", 1);
ajouter_sondage(); ajouter_sondage();
@ -179,11 +176,9 @@ if (GETPOST('confirmation'))
} }
// Reset days // Reset days
if (GETPOST('reset')) if (GETPOST('reset')) {
{
$nbofchoice = count($_SESSION["totalchoixjour"]); $nbofchoice = count($_SESSION["totalchoixjour"]);
for ($i = 0; $i < $nbofchoice; $i++) for ($i = 0; $i < $nbofchoice; $i++) {
{
for ($j = 0; $j < $_SESSION["nbrecaseshoraires"]; $j++) { for ($j = 0; $j < $_SESSION["nbrecaseshoraires"]; $j++) {
unset($_SESSION["horaires$i"][$j]); unset($_SESSION["horaires$i"][$j]);
} }
@ -199,8 +194,7 @@ if (GETPOST('reset'))
* View * View
*/ */
if (!isset($_SESSION['description']) && !isset($_SESSION['mail'])) if (!isset($_SESSION['description']) && !isset($_SESSION['mail'])) {
{
dol_print_error('', $langs->trans('ErrorOpenSurveyFillFirstSection')); dol_print_error('', $langs->trans('ErrorOpenSurveyFillFirstSection'));
exit; exit;
} }
@ -210,11 +204,9 @@ $arrayofcss = array('/opensurvey/css/style.css');
llxHeader('', $langs->trans("OpenSurvey"), "", '', 0, 0, $arrayofjs, $arrayofcss); llxHeader('', $langs->trans("OpenSurvey"), "", '', 0, 0, $arrayofjs, $arrayofcss);
//nombre de cases par défaut //nombre de cases par défaut
if (!isset($_SESSION["nbrecaseshoraires"])) if (!isset($_SESSION["nbrecaseshoraires"])) {
{
$_SESSION["nbrecaseshoraires"] = 5; $_SESSION["nbrecaseshoraires"] = 5;
} elseif (GETPOST('ajoutcases') && $_SESSION["nbrecaseshoraires"] == 5) } elseif (GETPOST('ajoutcases') && $_SESSION["nbrecaseshoraires"] == 5) {
{
$_SESSION["nbrecaseshoraires"] = 10; $_SESSION["nbrecaseshoraires"] = 10;
} }
@ -224,9 +216,15 @@ $moisAJ = date("n");
$anneeAJ = date("Y"); $anneeAJ = date("Y");
// Initialisation des jour, mois et année // Initialisation des jour, mois et année
if (!isset($_SESSION['jour'])) $_SESSION['jour'] = date('j'); if (!isset($_SESSION['jour'])) {
if (!isset($_SESSION['mois'])) $_SESSION['mois'] = date('n'); $_SESSION['jour'] = date('j');
if (!isset($_SESSION['annee'])) $_SESSION['annee'] = date('Y'); }
if (!isset($_SESSION['mois'])) {
$_SESSION['mois'] = date('n');
}
if (!isset($_SESSION['annee'])) {
$_SESSION['annee'] = date('Y');
}
//mise a jour des valeurs de session si bouton retour a aujourd'hui //mise a jour des valeurs de session si bouton retour a aujourd'hui
if (!issetAndNoEmpty('choixjourajout') && !issetAndNoEmpty('choixjourretrait') && (issetAndNoEmpty('retourmois') || issetAndNoEmpty('retourmois_x'))) { if (!issetAndNoEmpty('choixjourajout') && !issetAndNoEmpty('choixjourretrait') && (issetAndNoEmpty('retourmois') || issetAndNoEmpty('retourmois_x'))) {
@ -245,8 +243,7 @@ if (issetAndNoEmpty('moisavant_x') || issetAndNoEmpty('moisavant')) {
} }
//On sauvegarde les heures deja entrées //On sauvegarde les heures deja entrées
if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true) if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true) {
{
$nbofchoice = count($_SESSION["totalchoixjour"]); $nbofchoice = count($_SESSION["totalchoixjour"]);
for ($i = 0; $i < $nbofchoice; $i++) { for ($i = 0; $i < $nbofchoice; $i++) {
//affichage des 5 cases horaires //affichage des 5 cases horaires
@ -267,11 +264,9 @@ if (issetAndNoEmpty('moisapres_x') || issetAndNoEmpty('moisapres')) {
} }
//On sauvegarde les heures deja entrées //On sauvegarde les heures deja entrées
if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true) if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true) {
{
$nbofchoice = count($_SESSION["totalchoixjour"]); $nbofchoice = count($_SESSION["totalchoixjour"]);
for ($i = 0; $i < $nbofchoice; $i++) for ($i = 0; $i < $nbofchoice; $i++) {
{
//affichage des 5 cases horaires //affichage des 5 cases horaires
for ($j = 0; $j < $_SESSION["nbrecaseshoraires"]; $j++) { for ($j = 0; $j < $_SESSION["nbrecaseshoraires"]; $j++) {
$_SESSION["horaires$i"][$j] = $_POST["horaires$i"][$j]; $_SESSION["horaires$i"][$j] = $_POST["horaires$i"][$j];
@ -285,8 +280,7 @@ if (issetAndNoEmpty('anneeavant_x') || issetAndNoEmpty('anneeavant')) {
$_SESSION["annee"] -= 1; $_SESSION["annee"] -= 1;
//On sauvegarde les heures deja entrées //On sauvegarde les heures deja entrées
if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true) if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true) {
{
$nbofchoice = count($_SESSION["totalchoixjour"]); $nbofchoice = count($_SESSION["totalchoixjour"]);
for ($i = 0; $i < $nbofchoice; $i++) { for ($i = 0; $i < $nbofchoice; $i++) {
//affichage des 5 cases horaires //affichage des 5 cases horaires
@ -302,8 +296,7 @@ if (issetAndNoEmpty('anneeapres_x') || issetAndNoEmpty('anneeapres')) {
$_SESSION["annee"] += 1; $_SESSION["annee"] += 1;
//On sauvegarde les heures deja entrées //On sauvegarde les heures deja entrées
if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true) if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true) {
{
$nbofchoice = count($_SESSION["totalchoixjour"]); $nbofchoice = count($_SESSION["totalchoixjour"]);
for ($i = 0; $i < $nbofchoice; $i++) { for ($i = 0; $i < $nbofchoice; $i++) {
//affichage des 5 cases horaires //affichage des 5 cases horaires
@ -319,8 +312,7 @@ $nbrejourmois = date("t", mktime(0, 0, 0, $_SESSION["mois"], 1, $_SESSION["annee
$premierjourmois = date("N", mktime(0, 0, 0, $_SESSION["mois"], 1, $_SESSION["annee"])) - 1; $premierjourmois = date("N", mktime(0, 0, 0, $_SESSION["mois"], 1, $_SESSION["annee"])) - 1;
//traduction de la valeur du mois //traduction de la valeur du mois
if (is_integer($_SESSION["mois"]) && $_SESSION["mois"] > 0 && $_SESSION["mois"] < 13) if (is_integer($_SESSION["mois"]) && $_SESSION["mois"] > 0 && $_SESSION["mois"] < 13) {
{
$motmois = dol_print_date(mktime(0, 0, 0, $_SESSION["mois"], 10), '%B'); $motmois = dol_print_date(mktime(0, 0, 0, $_SESSION["mois"], 10), '%B');
} else { } else {
$motmois = dol_print_date(dol_now(), '%B'); $motmois = dol_print_date(dol_now(), '%B');
@ -356,8 +348,7 @@ print '<table align="center">'."\n"; // The div class=center has no effect on ta
print '<tr>'."\n"; print '<tr>'."\n";
//affichage des jours de la semaine en haut du tableau //affichage des jours de la semaine en haut du tableau
for ($i = 0; $i < 7; $i++) for ($i = 0; $i < 7; $i++) {
{
print '<td align="center" class="joursemaine">'.dol_print_date(mktime(0, 0, 0, 0, $i, 10), '%A').'</td>'; print '<td align="center" class="joursemaine">'.dol_print_date(mktime(0, 0, 0, 0, $i, 10), '%A').'</td>';
} }
@ -371,8 +362,7 @@ if (issetAndNoEmpty('choixjourajout')) {
// Test pour éviter les doublons dans la variable qui contient toutes les dates // Test pour éviter les doublons dans la variable qui contient toutes les dates
$journeuf = true; $journeuf = true;
if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true && issetAndNoEmpty('choixjourajout') === true) if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true && issetAndNoEmpty('choixjourajout') === true) {
{
$nbofchoice = count($_SESSION["totalchoixjour"]); $nbofchoice = count($_SESSION["totalchoixjour"]);
for ($i = 0; $i < $nbofchoice; $i++) { for ($i = 0; $i < $nbofchoice; $i++) {
if ($_SESSION["totalchoixjour"][$i] == mktime(0, 0, 0, $_SESSION["mois"], $_POST["choixjourajout"][0], $_SESSION["annee"])) { if ($_SESSION["totalchoixjour"][$i] == mktime(0, 0, 0, $_SESSION["mois"], $_POST["choixjourajout"][0], $_SESSION["annee"])) {
@ -421,10 +411,8 @@ if (issetAndNoEmpty('choixjourretrait')) {
} }
} }
for ($i = 0; $i < $nbofchoice; $i++) for ($i = 0; $i < $nbofchoice; $i++) {
{ if ($_SESSION["totalchoixjour"][$i] == mktime(0, 0, 0, $_SESSION["mois"], $_POST["choixjourretrait"][0], $_SESSION["annee"])) {
if ($_SESSION["totalchoixjour"][$i] == mktime(0, 0, 0, $_SESSION["mois"], $_POST["choixjourretrait"][0], $_SESSION["annee"]))
{
for ($j = $i; $j < $nbofchoice; $j++) { for ($j = $i; $j < $nbofchoice; $j++) {
$k = $j + 1; $k = $j + 1;
$_SESSION["horaires$j"] = $_SESSION["horaires$k"]; $_SESSION["horaires$j"] = $_SESSION["horaires$k"];
@ -468,8 +456,7 @@ for ($i = 0; $i < $nbrejourmois + $premierjourmois; $i++) {
if ($i < $premierjourmois) { if ($i < $premierjourmois) {
print '<td class="avant"></td>'."\n"; print '<td class="avant"></td>'."\n";
} else { } else {
if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true) if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true) {
{
$nbofchoice = count($_SESSION["totalchoixjour"]); $nbofchoice = count($_SESSION["totalchoixjour"]);
for ($j = 0; $j < $nbofchoice; $j++) { for ($j = 0; $j < $nbofchoice; $j++) {
// show red buttons // show red buttons
@ -501,8 +488,7 @@ print '</div></div>'."\n";
print '<div class="bodydate"><div class="center">'."\n"; print '<div class="bodydate"><div class="center">'."\n";
// affichage de tous les jours choisis // affichage de tous les jours choisis
if (issetAndNoEmpty('totalchoixjour', $_SESSION) || $erreur) if (issetAndNoEmpty('totalchoixjour', $_SESSION) || $erreur) {
{
//affichage des jours //affichage des jours
print '<br>'."\n"; print '<br>'."\n";
print '<div align="left">'; print '<div align="left">';
@ -528,8 +514,7 @@ if (issetAndNoEmpty('totalchoixjour', $_SESSION) || $erreur)
//affichage de la liste des jours choisis //affichage de la liste des jours choisis
$nbofchoice = count($_SESSION["totalchoixjour"]); $nbofchoice = count($_SESSION["totalchoixjour"]);
for ($i = 0; $i < $nbofchoice; $i++) for ($i = 0; $i < $nbofchoice; $i++) {
{
print '<tr>'."\n"; print '<tr>'."\n";
print '<td>'.dol_print_date($_SESSION["totalchoixjour"][$i], 'daytext').' ('.dol_print_date($_SESSION["totalchoixjour"][$i], '%A').')</td>'; print '<td>'.dol_print_date($_SESSION["totalchoixjour"][$i], 'daytext').' ('.dol_print_date($_SESSION["totalchoixjour"][$i], '%A').')</td>';

View File

@ -31,7 +31,9 @@ require_once DOL_DOCUMENT_ROOT."/core/class/doleditor.class.php";
require_once DOL_DOCUMENT_ROOT."/opensurvey/fonctions.php"; require_once DOL_DOCUMENT_ROOT."/opensurvey/fonctions.php";
// Security check // Security check
if (!$user->rights->opensurvey->write) accessforbidden(); if (!$user->rights->opensurvey->write) {
accessforbidden();
}
$langs->load("opensurvey"); $langs->load("opensurvey");
@ -43,9 +45,10 @@ $creation_sondage_autre = GETPOST('creation_sondage_autre');
// We init some session variable to avoir warning // We init some session variable to avoir warning
$session_var = array('title', 'description', 'mailsonde'); $session_var = array('title', 'description', 'mailsonde');
foreach ($session_var as $var) foreach ($session_var as $var) {
{ if (isset($_SESSION[$var])) {
if (isset($_SESSION[$var])) $_SESSION[$var] = null; $_SESSION[$var] = null;
}
} }
// On initialise également les autres variables // On initialise également les autres variables
@ -53,8 +56,7 @@ $cocheplus = '';
$cochemail = ''; $cochemail = '';
// Jump to correct page // Jump to correct page
if (!empty($creation_sondage_date) || !empty($creation_sondage_autre)) if (!empty($creation_sondage_date) || !empty($creation_sondage_autre)) {
{
$_SESSION["title"] = $title; $_SESSION["title"] = $title;
$_SESSION["description"] = $description; $_SESSION["description"] = $description;
@ -79,11 +81,9 @@ if (!empty($creation_sondage_date) || !empty($creation_sondage_autre))
$testdate = false; $testdate = false;
$champdatefin = dol_mktime(0, 0, 0, GETPOST('champdatefinmonth'), GETPOST('champdatefinday'), GETPOST('champdatefinyear')); $champdatefin = dol_mktime(0, 0, 0, GETPOST('champdatefinmonth'), GETPOST('champdatefinday'), GETPOST('champdatefinyear'));
if ($champdatefin && ($champdatefin > 0)) // A date was provided if ($champdatefin && ($champdatefin > 0)) { // A date was provided
{
// Expire date is not before today // Expire date is not before today
if ($champdatefin >= dol_now()) if ($champdatefin >= dol_now()) {
{
$testdate = true; $testdate = true;
$_SESSION['champdatefin'] = dol_print_date($champdatefin, 'dayrfc'); $_SESSION['champdatefin'] = dol_print_date($champdatefin, 'dayrfc');
} else { } else {
@ -99,16 +99,13 @@ if (!empty($creation_sondage_date) || !empty($creation_sondage_autre))
setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("ExpireDate")), null, 'errors'); setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("ExpireDate")), null, 'errors');
} }
if ($title && $testdate) if ($title && $testdate) {
{ if (!empty($creation_sondage_date)) {
if (!empty($creation_sondage_date))
{
header("Location: choix_date.php"); header("Location: choix_date.php");
exit(); exit();
} }
if (!empty($creation_sondage_autre)) if (!empty($creation_sondage_autre)) {
{
header("Location: choix_autre.php"); header("Location: choix_autre.php");
exit(); exit();
} }
@ -140,8 +137,7 @@ print dol_get_fiche_head();
print '<table class="border centpercent">'."\n"; print '<table class="border centpercent">'."\n";
print '<tr><td class="titlefieldcreate fieldrequired">'.$langs->trans("PollTitle").'</td><td><input type="text" name="title" class="minwidth300" maxlength="80" value="'.$_SESSION["title"].'"></td>'."\n"; print '<tr><td class="titlefieldcreate fieldrequired">'.$langs->trans("PollTitle").'</td><td><input type="text" name="title" class="minwidth300" maxlength="80" value="'.$_SESSION["title"].'"></td>'."\n";
if (!$_SESSION["title"] && (GETPOST('creation_sondage_date') || GETPOST('creation_sondage_autre'))) if (!$_SESSION["title"] && (GETPOST('creation_sondage_date') || GETPOST('creation_sondage_autre'))) {
{
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("PollTitle")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("PollTitle")), null, 'errors');
} }
@ -170,22 +166,34 @@ print '<br>'."\n";
// Check or not // Check or not
if ($_SESSION["mailsonde"]) $cochemail = "checked"; if ($_SESSION["mailsonde"]) {
$cochemail = "checked";
}
print '<input type="checkbox" name="mailsonde" '.$cochemail.'> '.$langs->trans("ToReceiveEMailForEachVote").'<br>'."\n"; print '<input type="checkbox" name="mailsonde" '.$cochemail.'> '.$langs->trans("ToReceiveEMailForEachVote").'<br>'."\n";
if ($_SESSION['allow_comments']) $allow_comments = 'checked'; if ($_SESSION['allow_comments']) {
if (GETPOSTISSET('allow_comments')) $allow_comments = GETPOST('allow_comments') ? 'checked' : ''; $allow_comments = 'checked';
}
if (GETPOSTISSET('allow_comments')) {
$allow_comments = GETPOST('allow_comments') ? 'checked' : '';
}
print '<input type="checkbox" name="allow_comments" '.$allow_comments.'"> '.$langs->trans('CanComment').'<br>'."\n"; print '<input type="checkbox" name="allow_comments" '.$allow_comments.'"> '.$langs->trans('CanComment').'<br>'."\n";
if ($_SESSION['allow_spy']) $allow_spy = 'checked'; if ($_SESSION['allow_spy']) {
if (GETPOSTISSET('allow_spy')) $allow_spy = GETPOST('allow_spy') ? 'checked' : ''; $allow_spy = 'checked';
}
if (GETPOSTISSET('allow_spy')) {
$allow_spy = GETPOST('allow_spy') ? 'checked' : '';
}
print '<input type="checkbox" name="allow_spy" '.$allow_spy.'> '.$langs->trans('CanSeeOthersVote').'<br>'."\n"; print '<input type="checkbox" name="allow_spy" '.$allow_spy.'> '.$langs->trans('CanSeeOthersVote').'<br>'."\n";
if (GETPOST('choix_sondage')) if (GETPOST('choix_sondage')) {
{ if (GETPOST('choix_sondage') == 'date') {
if (GETPOST('choix_sondage') == 'date') print '<input type="hidden" name="creation_sondage_date" value="date">'; print '<input type="hidden" name="creation_sondage_date" value="date">';
else print '<input type="hidden" name="creation_sondage_autre" value="autre">'; } else {
print '<input type="hidden" name="creation_sondage_autre" value="autre">';
}
print '<input type="hidden" name="choix_sondage" value="'.GETPOST('choix_sondage').'">'; print '<input type="hidden" name="choix_sondage" value="'.GETPOST('choix_sondage').'">';
print '<br><input type="submit" class="button" name="submit" value="'.$langs->trans("CreatePoll").' ('.(GETPOST('choix_sondage') == 'date' ? $langs->trans("TypeDate") : $langs->trans("TypeClassic")).')">'; print '<br><input type="submit" class="button" name="submit" value="'.$langs->trans("CreatePoll").' ('.(GETPOST('choix_sondage') == 'date' ? $langs->trans("TypeDate") : $langs->trans("TypeClassic")).')">';
} else { } else {

View File

@ -19,7 +19,9 @@
*/ */
if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); if (!defined('NOTOKENRENEWAL')) {
define('NOTOKENRENEWAL', '1');
}
require '../../main.inc.php'; require '../../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
@ -27,7 +29,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
require_once DOL_DOCUMENT_ROOT.'/opensurvey/fonctions.php'; require_once DOL_DOCUMENT_ROOT.'/opensurvey/fonctions.php';
// Security check // Security check
if (!$user->rights->opensurvey->write) accessforbidden(); if (!$user->rights->opensurvey->write) {
accessforbidden();
}
$langs->load("opensurvey"); $langs->load("opensurvey");

View File

@ -32,51 +32,80 @@ $servicename = 'PayBox';
// Load translation files required by the page // Load translation files required by the page
$langs->loadLangs(array('admin', 'other', 'paybox', 'paypal')); $langs->loadLangs(array('admin', 'other', 'paybox', 'paypal'));
if (!$user->admin) if (!$user->admin) {
accessforbidden(); accessforbidden();
}
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
if ($action == 'setvalue' && $user->admin) if ($action == 'setvalue' && $user->admin) {
{
$db->begin(); $db->begin();
//$result=dolibarr_set_const($db, "PAYBOX_IBS_DEVISE",$_POST["PAYBOX_IBS_DEVISE"],'chaine',0,'',$conf->entity); //$result=dolibarr_set_const($db, "PAYBOX_IBS_DEVISE",$_POST["PAYBOX_IBS_DEVISE"],'chaine',0,'',$conf->entity);
$result = dolibarr_set_const($db, "PAYBOX_CGI_URL_V1", GETPOST('PAYBOX_CGI_URL_V1', 'alpha'), 'chaine', 0, '', $conf->entity); $result = dolibarr_set_const($db, "PAYBOX_CGI_URL_V1", GETPOST('PAYBOX_CGI_URL_V1', 'alpha'), 'chaine', 0, '', $conf->entity);
if (!$result > 0) $error++; if (!$result > 0) {
$error++;
}
$result = dolibarr_set_const($db, "PAYBOX_CGI_URL_V2", GETPOST('PAYBOX_CGI_URL_V2', 'alpha'), 'chaine', 0, '', $conf->entity); $result = dolibarr_set_const($db, "PAYBOX_CGI_URL_V2", GETPOST('PAYBOX_CGI_URL_V2', 'alpha'), 'chaine', 0, '', $conf->entity);
if (!$result > 0) $error++; if (!$result > 0) {
$error++;
}
$result = dolibarr_set_const($db, "PAYBOX_IBS_SITE", GETPOST('PAYBOX_IBS_SITE', 'alpha'), 'chaine', 0, '', $conf->entity); $result = dolibarr_set_const($db, "PAYBOX_IBS_SITE", GETPOST('PAYBOX_IBS_SITE', 'alpha'), 'chaine', 0, '', $conf->entity);
if (!$result > 0) $error++; if (!$result > 0) {
$error++;
}
$result = dolibarr_set_const($db, "PAYBOX_IBS_RANG", GETPOST('PAYBOX_IBS_RANG', 'alpha'), 'chaine', 0, '', $conf->entity); $result = dolibarr_set_const($db, "PAYBOX_IBS_RANG", GETPOST('PAYBOX_IBS_RANG', 'alpha'), 'chaine', 0, '', $conf->entity);
if (!$result > 0) $error++; if (!$result > 0) {
$error++;
}
$result = dolibarr_set_const($db, "PAYBOX_PBX_IDENTIFIANT", GETPOST('PAYBOX_PBX_IDENTIFIANT', 'alpha'), 'chaine', 0, '', $conf->entity); $result = dolibarr_set_const($db, "PAYBOX_PBX_IDENTIFIANT", GETPOST('PAYBOX_PBX_IDENTIFIANT', 'alpha'), 'chaine', 0, '', $conf->entity);
if (!$result > 0) $error++; if (!$result > 0) {
$error++;
}
$result = dolibarr_set_const($db, "ONLINE_PAYMENT_CREDITOR", GETPOST('ONLINE_PAYMENT_CREDITOR', 'alpha'), 'chaine', 0, '', $conf->entity); $result = dolibarr_set_const($db, "ONLINE_PAYMENT_CREDITOR", GETPOST('ONLINE_PAYMENT_CREDITOR', 'alpha'), 'chaine', 0, '', $conf->entity);
if (!$result > 0) $error++; if (!$result > 0) {
$error++;
}
$result = dolibarr_set_const($db, "PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS", GETPOST('PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS', 'int'), 'chaine', 0, '', $conf->entity); $result = dolibarr_set_const($db, "PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS", GETPOST('PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS', 'int'), 'chaine', 0, '', $conf->entity);
if (!$result > 0) $error++; if (!$result > 0) {
$error++;
}
$result = dolibarr_set_const($db, "ONLINE_PAYMENT_CSS_URL", GETPOST('ONLINE_PAYMENT_CSS_URL', 'alpha'), 'chaine', 0, '', $conf->entity); $result = dolibarr_set_const($db, "ONLINE_PAYMENT_CSS_URL", GETPOST('ONLINE_PAYMENT_CSS_URL', 'alpha'), 'chaine', 0, '', $conf->entity);
if (!$result > 0) $error++; if (!$result > 0) {
$error++;
}
$result = dolibarr_set_const($db, "ONLINE_PAYMENT_MESSAGE_FORM", GETPOST('ONLINE_PAYMENT_MESSAGE_FORM', 'alpha'), 'chaine', 0, '', $conf->entity); $result = dolibarr_set_const($db, "ONLINE_PAYMENT_MESSAGE_FORM", GETPOST('ONLINE_PAYMENT_MESSAGE_FORM', 'alpha'), 'chaine', 0, '', $conf->entity);
if (!$result > 0) $error++; if (!$result > 0) {
$error++;
}
$result = dolibarr_set_const($db, "ONLINE_PAYMENT_MESSAGE_OK", GETPOST('ONLINE_PAYMENT_MESSAGE_OK', 'alpha'), 'chaine', 0, '', $conf->entity); $result = dolibarr_set_const($db, "ONLINE_PAYMENT_MESSAGE_OK", GETPOST('ONLINE_PAYMENT_MESSAGE_OK', 'alpha'), 'chaine', 0, '', $conf->entity);
if (!$result > 0) $error++; if (!$result > 0) {
$error++;
}
$result = dolibarr_set_const($db, "ONLINE_PAYMENT_MESSAGE_KO", GETPOST('ONLINE_PAYMENT_MESSAGE_KO', 'alpha'), 'chaine', 0, '', $conf->entity); $result = dolibarr_set_const($db, "ONLINE_PAYMENT_MESSAGE_KO", GETPOST('ONLINE_PAYMENT_MESSAGE_KO', 'alpha'), 'chaine', 0, '', $conf->entity);
if (!$result > 0) $error++; if (!$result > 0) {
$error++;
}
$result = dolibarr_set_const($db, "ONLINE_PAYMENT_SENDEMAIL", GETPOST('ONLINE_PAYMENT_SENDEMAIL'), 'chaine', 0, '', $conf->entity); $result = dolibarr_set_const($db, "ONLINE_PAYMENT_SENDEMAIL", GETPOST('ONLINE_PAYMENT_SENDEMAIL'), 'chaine', 0, '', $conf->entity);
if (!$result > 0) $error++; if (!$result > 0) {
$error++;
}
// Payment token for URL // Payment token for URL
$result = dolibarr_set_const($db, "PAYMENT_SECURITY_TOKEN", GETPOST('PAYMENT_SECURITY_TOKEN', 'alpha'), 'chaine', 0, '', $conf->entity); $result = dolibarr_set_const($db, "PAYMENT_SECURITY_TOKEN", GETPOST('PAYMENT_SECURITY_TOKEN', 'alpha'), 'chaine', 0, '', $conf->entity);
if (!$result > 0) $error++; if (!$result > 0) {
$error++;
}
$result = dolibarr_set_const($db, "PAYMENT_SECURITY_TOKEN_UNIQUE", GETPOST('PAYMENT_SECURITY_TOKEN_UNIQUE', 'alpha'), 'chaine', 0, '', $conf->entity); $result = dolibarr_set_const($db, "PAYMENT_SECURITY_TOKEN_UNIQUE", GETPOST('PAYMENT_SECURITY_TOKEN_UNIQUE', 'alpha'), 'chaine', 0, '', $conf->entity);
if (!$result > 0) $error++; if (!$result > 0) {
$error++;
}
$result = dolibarr_set_const($db, "PAYBOX_HMAC_KEY", dol_encode(GETPOST('PAYBOX_HMAC_KEY', 'alpha')), 'chaine', 0, '', $conf->entity); $result = dolibarr_set_const($db, "PAYBOX_HMAC_KEY", dol_encode(GETPOST('PAYBOX_HMAC_KEY', 'alpha')), 'chaine', 0, '', $conf->entity);
if (!$result > 0) $error++; if (!$result > 0) {
$error++;
}
if (!$error) if (!$error) {
{
$db->commit(); $db->commit();
setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
} else { } else {
@ -91,11 +120,17 @@ if ($action == 'setvalue' && $user->admin)
*/ */
$IBS_SITE = "1999888"; // Site test $IBS_SITE = "1999888"; // Site test
if (empty($conf->global->PAYBOX_IBS_SITE)) $conf->global->PAYBOX_IBS_SITE = $IBS_SITE; if (empty($conf->global->PAYBOX_IBS_SITE)) {
$conf->global->PAYBOX_IBS_SITE = $IBS_SITE;
}
$IBS_RANG = "99"; // Rang test $IBS_RANG = "99"; // Rang test
if (empty($conf->global->PAYBOX_IBS_RANG)) $conf->global->PAYBOX_IBS_RANG = $IBS_RANG; if (empty($conf->global->PAYBOX_IBS_RANG)) {
$conf->global->PAYBOX_IBS_RANG = $IBS_RANG;
}
$IBS_DEVISE = "978"; // Euro $IBS_DEVISE = "978"; // Euro
if (empty($conf->global->PAYBOX_IBS_DEVISE)) $conf->global->PAYBOX_IBS_DEVISE = $IBS_DEVISE; if (empty($conf->global->PAYBOX_IBS_DEVISE)) {
$conf->global->PAYBOX_IBS_DEVISE = $IBS_DEVISE;
}
llxHeader(); llxHeader();
@ -191,8 +226,7 @@ print '<br><span class="opacitymedium">'.$langs->trans("Example").': '.$mysoc->n
print '</td></tr>'; print '</td></tr>';
if (!empty($conf->banque->enabled)) if (!empty($conf->banque->enabled)) {
{
print '<tr class="oddeven"><td>'; print '<tr class="oddeven"><td>';
print $langs->trans("BankAccount").'</td><td>'; print $langs->trans("BankAccount").'</td><td>';
$form->select_comptes($conf->global->PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS, 'PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS', 0, '', 1); $form->select_comptes($conf->global->PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS, 'PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS', 0, '', 1);
@ -237,8 +271,9 @@ print '</td></tr>';
print '<tr class="oddeven"><td>'; print '<tr class="oddeven"><td>';
print $langs->trans("SecurityToken").'</td><td>'; print $langs->trans("SecurityToken").'</td><td>';
print '<input size="48" type="text" id="PAYMENT_SECURITY_TOKEN" name="PAYMENT_SECURITY_TOKEN" value="'.$conf->global->PAYMENT_SECURITY_TOKEN.'">'; print '<input size="48" type="text" id="PAYMENT_SECURITY_TOKEN" name="PAYMENT_SECURITY_TOKEN" value="'.$conf->global->PAYMENT_SECURITY_TOKEN.'">';
if (!empty($conf->use_javascript_ajax)) if (!empty($conf->use_javascript_ajax)) {
print '&nbsp;'.img_picto($langs->trans('Generate'), 'refresh', 'id="generate_token" class="linkobject"'); print '&nbsp;'.img_picto($langs->trans('Generate'), 'refresh', 'id="generate_token" class="linkobject"');
}
print '</td></tr>'; print '</td></tr>';
print '<tr class="oddeven"><td>'; print '<tr class="oddeven"><td>';

View File

@ -44,36 +44,46 @@ function print_paybox_redirect($PRICE, $CURRENCY, $EMAIL, $urlok, $urlko, $TAG)
// Clean parameters // Clean parameters
$PBX_IDENTIFIANT = "2"; // Identifiant pour v2 test $PBX_IDENTIFIANT = "2"; // Identifiant pour v2 test
if (!empty($conf->global->PAYBOX_PBX_IDENTIFIANT)) $PBX_IDENTIFIANT = $conf->global->PAYBOX_PBX_IDENTIFIANT; if (!empty($conf->global->PAYBOX_PBX_IDENTIFIANT)) {
$PBX_IDENTIFIANT = $conf->global->PAYBOX_PBX_IDENTIFIANT;
}
$IBS_SITE = "1999888"; // Site test $IBS_SITE = "1999888"; // Site test
if (!empty($conf->global->PAYBOX_IBS_SITE)) $IBS_SITE = $conf->global->PAYBOX_IBS_SITE; if (!empty($conf->global->PAYBOX_IBS_SITE)) {
$IBS_SITE = $conf->global->PAYBOX_IBS_SITE;
}
$IBS_RANG = "99"; // Rang test $IBS_RANG = "99"; // Rang test
if (!empty($conf->global->PAYBOX_IBS_RANG)) $IBS_RANG = $conf->global->PAYBOX_IBS_RANG; if (!empty($conf->global->PAYBOX_IBS_RANG)) {
$IBS_RANG = $conf->global->PAYBOX_IBS_RANG;
}
$IBS_DEVISE = "840"; // Currency (Dollar US by default) $IBS_DEVISE = "840"; // Currency (Dollar US by default)
if ($CURRENCY == 'EUR') $IBS_DEVISE = "978"; if ($CURRENCY == 'EUR') {
if ($CURRENCY == 'USD') $IBS_DEVISE = "840"; $IBS_DEVISE = "978";
}
if ($CURRENCY == 'USD') {
$IBS_DEVISE = "840";
}
$URLPAYBOX = ""; $URLPAYBOX = "";
if ($conf->global->PAYBOX_CGI_URL_V1) $URLPAYBOX = $conf->global->PAYBOX_CGI_URL_V1; if ($conf->global->PAYBOX_CGI_URL_V1) {
if ($conf->global->PAYBOX_CGI_URL_V2) $URLPAYBOX = $conf->global->PAYBOX_CGI_URL_V2; $URLPAYBOX = $conf->global->PAYBOX_CGI_URL_V1;
}
if ($conf->global->PAYBOX_CGI_URL_V2) {
$URLPAYBOX = $conf->global->PAYBOX_CGI_URL_V2;
}
if (empty($IBS_DEVISE)) if (empty($IBS_DEVISE)) {
{
dol_print_error('', "Paybox setup param PAYBOX_IBS_DEVISE not defined"); dol_print_error('', "Paybox setup param PAYBOX_IBS_DEVISE not defined");
return -1; return -1;
} }
if (empty($URLPAYBOX)) if (empty($URLPAYBOX)) {
{
dol_print_error('', "Paybox setup param PAYBOX_CGI_URL_V1 and PAYBOX_CGI_URL_V2 undefined"); dol_print_error('', "Paybox setup param PAYBOX_CGI_URL_V1 and PAYBOX_CGI_URL_V2 undefined");
return -1; return -1;
} }
if (empty($IBS_SITE)) if (empty($IBS_SITE)) {
{
dol_print_error('', "Paybox setup param PAYBOX_IBS_SITE not defined"); dol_print_error('', "Paybox setup param PAYBOX_IBS_SITE not defined");
return -1; return -1;
} }
if (empty($IBS_RANG)) if (empty($IBS_RANG)) {
{
dol_print_error('', "Paybox setup param PAYBOX_IBS_RANG not defined"); dol_print_error('', "Paybox setup param PAYBOX_IBS_RANG not defined");
return -1; return -1;
} }
@ -93,12 +103,24 @@ function print_paybox_redirect($PRICE, $CURRENCY, $EMAIL, $urlok, $urlko, $TAG)
$IBS_BKGD = "#FFFFFF"; $IBS_BKGD = "#FFFFFF";
$IBS_WAIT = "2000"; $IBS_WAIT = "2000";
$IBS_LANG = "GBR"; // By default GBR=english (FRA, GBR, ESP, ITA et DEU...) $IBS_LANG = "GBR"; // By default GBR=english (FRA, GBR, ESP, ITA et DEU...)
if (preg_match('/^FR/i', $langs->defaultlang)) $IBS_LANG = "FRA"; if (preg_match('/^FR/i', $langs->defaultlang)) {
if (preg_match('/^ES/i', $langs->defaultlang)) $IBS_LANG = "ESP"; $IBS_LANG = "FRA";
if (preg_match('/^IT/i', $langs->defaultlang)) $IBS_LANG = "ITA"; }
if (preg_match('/^DE/i', $langs->defaultlang)) $IBS_LANG = "DEU"; if (preg_match('/^ES/i', $langs->defaultlang)) {
if (preg_match('/^NL/i', $langs->defaultlang)) $IBS_LANG = "NLD"; $IBS_LANG = "ESP";
if (preg_match('/^SE/i', $langs->defaultlang)) $IBS_LANG = "SWE"; }
if (preg_match('/^IT/i', $langs->defaultlang)) {
$IBS_LANG = "ITA";
}
if (preg_match('/^DE/i', $langs->defaultlang)) {
$IBS_LANG = "DEU";
}
if (preg_match('/^NL/i', $langs->defaultlang)) {
$IBS_LANG = "NLD";
}
if (preg_match('/^SE/i', $langs->defaultlang)) {
$IBS_LANG = "SWE";
}
$IBS_OUTPUT = 'E'; $IBS_OUTPUT = 'E';
$PBX_SOURCE = 'HTML'; $PBX_SOURCE = 'HTML';
$PBX_TYPEPAIEMENT = 'CARTE'; $PBX_TYPEPAIEMENT = 'CARTE';

View File

@ -35,43 +35,72 @@ $servicename = 'PayPal';
// Load translation files required by the page // Load translation files required by the page
$langs->loadLangs(array('admin', 'other', 'paypal', 'paybox')); $langs->loadLangs(array('admin', 'other', 'paypal', 'paybox'));
if (!$user->admin) accessforbidden(); if (!$user->admin) {
accessforbidden();
}
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
if ($action == 'setvalue' && $user->admin) if ($action == 'setvalue' && $user->admin) {
{
$db->begin(); $db->begin();
$result = dolibarr_set_const($db, "PAYPAL_API_USER", GETPOST('PAYPAL_API_USER', 'alpha'), 'chaine', 0, '', $conf->entity); $result = dolibarr_set_const($db, "PAYPAL_API_USER", GETPOST('PAYPAL_API_USER', 'alpha'), 'chaine', 0, '', $conf->entity);
if (!$result > 0) $error++; if (!$result > 0) {
$error++;
}
$result = dolibarr_set_const($db, "PAYPAL_API_PASSWORD", GETPOST('PAYPAL_API_PASSWORD', 'alpha'), 'chaine', 0, '', $conf->entity); $result = dolibarr_set_const($db, "PAYPAL_API_PASSWORD", GETPOST('PAYPAL_API_PASSWORD', 'alpha'), 'chaine', 0, '', $conf->entity);
if (!$result > 0) $error++; if (!$result > 0) {
$error++;
}
$result = dolibarr_set_const($db, "PAYPAL_API_SIGNATURE", GETPOST('PAYPAL_API_SIGNATURE', 'alpha'), 'chaine', 0, '', $conf->entity); $result = dolibarr_set_const($db, "PAYPAL_API_SIGNATURE", GETPOST('PAYPAL_API_SIGNATURE', 'alpha'), 'chaine', 0, '', $conf->entity);
if (!$result > 0) $error++; if (!$result > 0) {
$error++;
}
$result = dolibarr_set_const($db, "PAYPAL_SSLVERSION", GETPOST('PAYPAL_SSLVERSION', 'alpha'), 'chaine', 0, '', $conf->entity); $result = dolibarr_set_const($db, "PAYPAL_SSLVERSION", GETPOST('PAYPAL_SSLVERSION', 'alpha'), 'chaine', 0, '', $conf->entity);
if (!$result > 0) $error++; if (!$result > 0) {
$error++;
}
$result = dolibarr_set_const($db, "ONLINE_PAYMENT_CREDITOR", GETPOST('ONLINE_PAYMENT_CREDITOR', 'alpha'), 'chaine', 0, '', $conf->entity); $result = dolibarr_set_const($db, "ONLINE_PAYMENT_CREDITOR", GETPOST('ONLINE_PAYMENT_CREDITOR', 'alpha'), 'chaine', 0, '', $conf->entity);
if (!$result > 0) $error++; if (!$result > 0) {
$error++;
}
$result = dolibarr_set_const($db, "PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS", GETPOST('PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS', 'int'), 'chaine', 0, '', $conf->entity); $result = dolibarr_set_const($db, "PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS", GETPOST('PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS', 'int'), 'chaine', 0, '', $conf->entity);
if (!$result > 0) $error++; if (!$result > 0) {
$error++;
}
$result = dolibarr_set_const($db, "PAYPAL_API_INTEGRAL_OR_PAYPALONLY", GETPOST('PAYPAL_API_INTEGRAL_OR_PAYPALONLY', 'alpha'), 'chaine', 0, '', $conf->entity); $result = dolibarr_set_const($db, "PAYPAL_API_INTEGRAL_OR_PAYPALONLY", GETPOST('PAYPAL_API_INTEGRAL_OR_PAYPALONLY', 'alpha'), 'chaine', 0, '', $conf->entity);
if (!$result > 0) $error++; if (!$result > 0) {
$error++;
}
$result = dolibarr_set_const($db, "ONLINE_PAYMENT_CSS_URL", GETPOST('ONLINE_PAYMENT_CSS_URL', 'alpha'), 'chaine', 0, '', $conf->entity); $result = dolibarr_set_const($db, "ONLINE_PAYMENT_CSS_URL", GETPOST('ONLINE_PAYMENT_CSS_URL', 'alpha'), 'chaine', 0, '', $conf->entity);
if (!$result > 0) $error++; if (!$result > 0) {
$error++;
}
$result = dolibarr_set_const($db, "PAYPAL_ADD_PAYMENT_URL", GETPOST('PAYPAL_ADD_PAYMENT_URL', 'alpha'), 'chaine', 0, '', $conf->entity); $result = dolibarr_set_const($db, "PAYPAL_ADD_PAYMENT_URL", GETPOST('PAYPAL_ADD_PAYMENT_URL', 'alpha'), 'chaine', 0, '', $conf->entity);
if (!$result > 0) $error++; if (!$result > 0) {
$error++;
}
$result = dolibarr_set_const($db, "ONLINE_PAYMENT_MESSAGE_FORM", GETPOST('ONLINE_PAYMENT_MESSAGE_FORM'), 'chaine', 0, '', $conf->entity); $result = dolibarr_set_const($db, "ONLINE_PAYMENT_MESSAGE_FORM", GETPOST('ONLINE_PAYMENT_MESSAGE_FORM'), 'chaine', 0, '', $conf->entity);
if (!$result > 0) $error++; if (!$result > 0) {
$error++;
}
$result = dolibarr_set_const($db, "ONLINE_PAYMENT_MESSAGE_OK", GETPOST('ONLINE_PAYMENT_MESSAGE_OK'), 'chaine', 0, '', $conf->entity); $result = dolibarr_set_const($db, "ONLINE_PAYMENT_MESSAGE_OK", GETPOST('ONLINE_PAYMENT_MESSAGE_OK'), 'chaine', 0, '', $conf->entity);
if (!$result > 0) $error++; if (!$result > 0) {
$error++;
}
$result = dolibarr_set_const($db, "ONLINE_PAYMENT_MESSAGE_KO", GETPOST('ONLINE_PAYMENT_MESSAGE_KO'), 'chaine', 0, '', $conf->entity); $result = dolibarr_set_const($db, "ONLINE_PAYMENT_MESSAGE_KO", GETPOST('ONLINE_PAYMENT_MESSAGE_KO'), 'chaine', 0, '', $conf->entity);
if (!$result > 0) $error++; if (!$result > 0) {
$error++;
}
$result = dolibarr_set_const($db, "ONLINE_PAYMENT_SENDEMAIL", GETPOST('ONLINE_PAYMENT_SENDEMAIL'), 'chaine', 0, '', $conf->entity); $result = dolibarr_set_const($db, "ONLINE_PAYMENT_SENDEMAIL", GETPOST('ONLINE_PAYMENT_SENDEMAIL'), 'chaine', 0, '', $conf->entity);
if (!$result > 0) $error++; if (!$result > 0) {
$error++;
}
// Payment token for URL // Payment token for URL
$result = dolibarr_set_const($db, "PAYMENT_SECURITY_TOKEN", GETPOST('PAYMENT_SECURITY_TOKEN', 'alpha'), 'chaine', 0, '', $conf->entity); $result = dolibarr_set_const($db, "PAYMENT_SECURITY_TOKEN", GETPOST('PAYMENT_SECURITY_TOKEN', 'alpha'), 'chaine', 0, '', $conf->entity);
if (!$result > 0) $error++; if (!$result > 0) {
$error++;
}
if (empty($conf->use_javascript_ajax)) { if (empty($conf->use_javascript_ajax)) {
$result = dolibarr_set_const($db, "PAYMENT_SECURITY_TOKEN_UNIQUE", GETPOST('PAYMENT_SECURITY_TOKEN_UNIQUE', 'alpha'), 'chaine', 0, '', $conf->entity); $result = dolibarr_set_const($db, "PAYMENT_SECURITY_TOKEN_UNIQUE", GETPOST('PAYMENT_SECURITY_TOKEN_UNIQUE', 'alpha'), 'chaine', 0, '', $conf->entity);
if (!$result > 0) { if (!$result > 0) {
@ -88,13 +117,13 @@ if ($action == 'setvalue' && $user->admin)
} }
} }
if ($action == "setlive") if ($action == "setlive") {
{
$liveenable = GETPOST('value', 'int') ? 0 : 1; $liveenable = GETPOST('value', 'int') ? 0 : 1;
$res = dolibarr_set_const($db, "PAYPAL_API_SANDBOX", $liveenable, 'yesno', 0, '', $conf->entity); $res = dolibarr_set_const($db, "PAYPAL_API_SANDBOX", $liveenable, 'yesno', 0, '', $conf->entity);
if (!($res > 0)) $error++; if (!($res > 0)) {
if (!$error) $error++;
{ }
if (!$error) {
setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
} else { } else {
setEventMessages($langs->trans("Error"), null, 'errors'); setEventMessages($langs->trans("Error"), null, 'errors');
@ -126,8 +155,7 @@ print dol_get_fiche_head($head, 'paypalaccount', '', -1);
print '<span class="opacitymedium">'.$langs->trans("PaypalDesc")."</span><br>\n"; print '<span class="opacitymedium">'.$langs->trans("PaypalDesc")."</span><br>\n";
// Test if php curl exist // Test if php curl exist
if (!function_exists('curl_version')) if (!function_exists('curl_version')) {
{
$langs->load("errors"); $langs->load("errors");
setEventMessages($langs->trans("ErrorPhpCurlNotInstalled"), null, 'errors'); setEventMessages($langs->trans("ErrorPhpCurlNotInstalled"), null, 'errors');
} }
@ -147,8 +175,7 @@ print "</tr>\n";
print '<tr class="oddeven">'; print '<tr class="oddeven">';
print '<td>'; print '<td>';
print $langs->trans("PaypalLiveEnabled").'</td><td>'; print $langs->trans("PaypalLiveEnabled").'</td><td>';
if (empty($conf->global->PAYPAL_API_SANDBOX)) if (empty($conf->global->PAYPAL_API_SANDBOX)) {
{
print '<a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=setlive&token='.newToken().'&value=0">'; print '<a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=setlive&token='.newToken().'&value=0">';
print img_picto($langs->trans("Activated"), 'switch_on'); print img_picto($langs->trans("Activated"), 'switch_on');
} else { } else {
@ -217,8 +244,7 @@ print '<input size="64" type="text" name="ONLINE_PAYMENT_CREDITOR" value="'.$con
print ' &nbsp; <span class="opacitymedium">'.$langs->trans("Example").': '.$mysoc->name.'</span>'; print ' &nbsp; <span class="opacitymedium">'.$langs->trans("Example").': '.$mysoc->name.'</span>';
print '</td></tr>'; print '</td></tr>';
if (!empty($conf->banque->enabled)) if (!empty($conf->banque->enabled)) {
{
print '<tr class="oddeven"><td>'; print '<tr class="oddeven"><td>';
print $langs->trans("BankAccount").'</td><td>'; print $langs->trans("BankAccount").'</td><td>';
print img_picto('', 'bank_account').' '; print img_picto('', 'bank_account').' ';
@ -315,8 +341,9 @@ print '<br><br>';
// Help doc // Help doc
print '<u>'.$langs->trans("InformationToFindParameters", "Paypal").'</u>:<br>'; print '<u>'.$langs->trans("InformationToFindParameters", "Paypal").'</u>:<br>';
if (!empty($conf->use_javascript_ajax)) if (!empty($conf->use_javascript_ajax)) {
print '<a class="reposition" id="apidoca">'.$langs->trans("ClickHere").'...</a>'; print '<a class="reposition" id="apidoca">'.$langs->trans("ClickHere").'...</a>';
}
$realpaypalurl = 'www.paypal.com'; $realpaypalurl = 'www.paypal.com';
$sandboxpaypalurl = 'developer.paypal.com'; $sandboxpaypalurl = 'developer.paypal.com';
@ -334,8 +361,7 @@ print 'Your API authentication information can be found with following steps. We
'; ';
print '</div>'; print '</div>';
if (!empty($conf->use_javascript_ajax)) if (!empty($conf->use_javascript_ajax)) {
{
print "\n".'<script type="text/javascript">'; print "\n".'<script type="text/javascript">';
print '$(document).ready(function () { print '$(document).ready(function () {
$("#apidoc").hide(); $("#apidoc").hide();

View File

@ -82,25 +82,24 @@ function print_paypal_redirect($paymentAmount, $currencyCodeType, $paymentType,
//' //'
//'------------------------------------------------- //'-------------------------------------------------
if (empty($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY)) $conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY = 'integral'; if (empty($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY)) {
$conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY = 'integral';
}
$solutionType = 'Sole'; $solutionType = 'Sole';
$landingPage = 'Billing'; $landingPage = 'Billing';
// For payment with Paypal only // For payment with Paypal only
if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'paypalonly') if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'paypalonly') {
{
$solutionType = 'Mark'; $solutionType = 'Mark';
$landingPage = 'Login'; $landingPage = 'Login';
} }
// For payment with Credit card or Paypal // For payment with Credit card or Paypal
if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'integral') if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'integral') {
{
$solutionType = 'Sole'; $solutionType = 'Sole';
$landingPage = 'Billing'; $landingPage = 'Billing';
} }
// For payment with Credit card // For payment with Credit card
if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'cconly') if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'cconly') {
{
$solutionType = 'Sole'; $solutionType = 'Sole';
$landingPage = 'Billing'; $landingPage = 'Billing';
} }
@ -130,8 +129,7 @@ function print_paypal_redirect($paymentAmount, $currencyCodeType, $paymentType,
dol_syslog("print_paypal_redirect resArray=".var_export($resArray, true), LOG_DEBUG); dol_syslog("print_paypal_redirect resArray=".var_export($resArray, true), LOG_DEBUG);
$ack = strtoupper($resArray["ACK"]); $ack = strtoupper($resArray["ACK"]);
if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") {
{
$token = $resArray["TOKEN"]; $token = $resArray["TOKEN"];
// Redirect to paypal.com here // Redirect to paypal.com here
@ -146,8 +144,7 @@ function print_paypal_redirect($paymentAmount, $currencyCodeType, $paymentType,
$ErrorLongMsg = urldecode($resArray["L_LONGMESSAGE0"]); $ErrorLongMsg = urldecode($resArray["L_LONGMESSAGE0"]);
$ErrorSeverityCode = urldecode($resArray["L_SEVERITYCODE0"]); $ErrorSeverityCode = urldecode($resArray["L_SEVERITYCODE0"]);
if ($ErrorCode == 10729) if ($ErrorCode == 10729) {
{
$mesg .= "PayPal can't accept payments for this thirdparty. An address is defined but is not complete (missing State).<br>Ask system administrator to fix address or to setup Paypal module to accept payments even on not complete addresses (remove option PAYPAL_REQUIRE_VALID_SHIPPING_ADDRESS).<br>\n"; $mesg .= "PayPal can't accept payments for this thirdparty. An address is defined but is not complete (missing State).<br>Ask system administrator to fix address or to setup Paypal module to accept payments even on not complete addresses (remove option PAYPAL_REQUIRE_VALID_SHIPPING_ADDRESS).<br>\n";
} else { } else {
$mesg = $langs->trans('SetExpressCheckoutAPICallFailed')."<br>\n"; $mesg = $langs->trans('SetExpressCheckoutAPICallFailed')."<br>\n";
@ -216,26 +213,25 @@ function callSetExpressCheckout($paymentAmount, $currencyCodeType, $paymentType,
//$nvpstr = $nvpstr . "&VERSION=".$API_version; // Already added by hash_call //$nvpstr = $nvpstr . "&VERSION=".$API_version; // Already added by hash_call
$nvpstr = $nvpstr."&RETURNURL=".urlencode($returnURL); $nvpstr = $nvpstr."&RETURNURL=".urlencode($returnURL);
$nvpstr = $nvpstr."&CANCELURL=".urlencode($cancelURL); $nvpstr = $nvpstr."&CANCELURL=".urlencode($cancelURL);
if (!empty($conf->global->PAYPAL_ALLOW_NOTES)) if (!empty($conf->global->PAYPAL_ALLOW_NOTES)) {
{
$nvpstr = $nvpstr."&ALLOWNOTE=0"; $nvpstr = $nvpstr."&ALLOWNOTE=0";
} }
if (empty($conf->global->PAYPAL_REQUIRE_VALID_SHIPPING_ADDRESS)) if (empty($conf->global->PAYPAL_REQUIRE_VALID_SHIPPING_ADDRESS)) {
{
$nvpstr = $nvpstr."&NOSHIPPING=1"; // An empty or not complete shipping address will be accepted $nvpstr = $nvpstr."&NOSHIPPING=1"; // An empty or not complete shipping address will be accepted
} else { } else {
$nvpstr = $nvpstr."&NOSHIPPING=0"; // A valid shipping address is required (full required fields mandatory) $nvpstr = $nvpstr."&NOSHIPPING=0"; // A valid shipping address is required (full required fields mandatory)
} }
$nvpstr = $nvpstr."&SOLUTIONTYPE=".urlencode($solutionType); $nvpstr = $nvpstr."&SOLUTIONTYPE=".urlencode($solutionType);
$nvpstr = $nvpstr."&LANDINGPAGE=".urlencode($landingPage); $nvpstr = $nvpstr."&LANDINGPAGE=".urlencode($landingPage);
if (!empty($conf->global->PAYPAL_CUSTOMER_SERVICE_NUMBER)) if (!empty($conf->global->PAYPAL_CUSTOMER_SERVICE_NUMBER)) {
{
$nvpstr = $nvpstr."&CUSTOMERSERVICENUMBER=".urlencode($conf->global->PAYPAL_CUSTOMER_SERVICE_NUMBER); // Hotline phone number $nvpstr = $nvpstr."&CUSTOMERSERVICENUMBER=".urlencode($conf->global->PAYPAL_CUSTOMER_SERVICE_NUMBER); // Hotline phone number
} }
$paypalprefix = 'PAYMENTREQUEST_0_'; $paypalprefix = 'PAYMENTREQUEST_0_';
//$paypalprefix = ''; //$paypalprefix = '';
if (!empty($paypalprefix) && $paymentType == 'Sole') $paymentType = 'Sale'; if (!empty($paypalprefix) && $paymentType == 'Sole') {
$paymentType = 'Sale';
}
$nvpstr = $nvpstr."&AMT=".urlencode($paymentAmount); // Total for all elements $nvpstr = $nvpstr."&AMT=".urlencode($paymentAmount); // Total for all elements
@ -258,11 +254,14 @@ function callSetExpressCheckout($paymentAmount, $currencyCodeType, $paymentType,
$nvpstr = $nvpstr."&".$paypalprefix."SHIPTOCOUNTRYCODE=".urlencode($shipToCountryCode); $nvpstr = $nvpstr."&".$paypalprefix."SHIPTOCOUNTRYCODE=".urlencode($shipToCountryCode);
$nvpstr = $nvpstr."&".$paypalprefix."SHIPTOZIP=".urlencode($shipToZip); $nvpstr = $nvpstr."&".$paypalprefix."SHIPTOZIP=".urlencode($shipToZip);
$nvpstr = $nvpstr."&".$paypalprefix."PHONENUM=".urlencode($phoneNum); $nvpstr = $nvpstr."&".$paypalprefix."PHONENUM=".urlencode($phoneNum);
if (!empty($email)) $nvpstr = $nvpstr."&".$paypalprefix."EMAIL=".urlencode($email); // EMAIL deprecated by paypal -> PAYMENTREQUEST_n_EMAIL if (!empty($email)) {
if (!empty($desc)) $nvpstr = $nvpstr."&".$paypalprefix."DESC=".urlencode($desc); // DESC deprecated by paypal -> PAYMENTREQUEST_n_DESC $nvpstr = $nvpstr."&".$paypalprefix."EMAIL=".urlencode($email); // EMAIL deprecated by paypal -> PAYMENTREQUEST_n_EMAIL
}
if (!empty($desc)) {
$nvpstr = $nvpstr."&".$paypalprefix."DESC=".urlencode($desc); // DESC deprecated by paypal -> PAYMENTREQUEST_n_DESC
}
if (!empty($conf->global->PAYPAL_LOGOIMG) && $mysoc->logo) if (!empty($conf->global->PAYPAL_LOGOIMG) && $mysoc->logo) {
{
global $dolibarr_main_url_root; global $dolibarr_main_url_root;
// Define $urlwithroot // Define $urlwithroot
@ -273,12 +272,10 @@ function callSetExpressCheckout($paymentAmount, $currencyCodeType, $paymentType,
$urllogo = $urlwithroot."/viewimage.php?modulepart=mycompany&file=".urlencode('logos/'.$mysoc->logo); $urllogo = $urlwithroot."/viewimage.php?modulepart=mycompany&file=".urlencode('logos/'.$mysoc->logo);
$nvpstr = $nvpstr."&LOGOIMG=".urlencode($urllogo); $nvpstr = $nvpstr."&LOGOIMG=".urlencode($urllogo);
} }
if (!empty($conf->global->PAYPAL_BRANDNAME)) if (!empty($conf->global->PAYPAL_BRANDNAME)) {
{
$nvpstr = $nvpstr."&BRANDNAME=".urlencode($conf->global->PAYPAL_BRANDNAME); // BRANDNAME $nvpstr = $nvpstr."&BRANDNAME=".urlencode($conf->global->PAYPAL_BRANDNAME); // BRANDNAME
} }
if (!empty($conf->global->PAYPAL_NOTETOBUYER)) if (!empty($conf->global->PAYPAL_NOTETOBUYER)) {
{
$nvpstr = $nvpstr."&NOTETOBUYER=".urlencode($conf->global->PAYPAL_NOTETOBUYER); // PAYPAL_NOTETOBUYER $nvpstr = $nvpstr."&NOTETOBUYER=".urlencode($conf->global->PAYPAL_NOTETOBUYER); // PAYPAL_NOTETOBUYER
} }
@ -294,8 +291,7 @@ function callSetExpressCheckout($paymentAmount, $currencyCodeType, $paymentType,
//'--------------------------------------------------------------------------------------------------------------- //'---------------------------------------------------------------------------------------------------------------
$resArray = hash_call("SetExpressCheckout", $nvpstr); $resArray = hash_call("SetExpressCheckout", $nvpstr);
$ack = strtoupper($resArray["ACK"]); $ack = strtoupper($resArray["ACK"]);
if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") {
{
$token = urldecode($resArray["TOKEN"]); $token = urldecode($resArray["TOKEN"]);
$_SESSION['TOKEN'] = $token; $_SESSION['TOKEN'] = $token;
} }
@ -339,8 +335,7 @@ function getDetails($token)
//'--------------------------------------------------------------------------- //'---------------------------------------------------------------------------
$resArray = hash_call("GetExpressCheckoutDetails", $nvpstr); $resArray = hash_call("GetExpressCheckoutDetails", $nvpstr);
$ack = strtoupper($resArray["ACK"]); $ack = strtoupper($resArray["ACK"]);
if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") {
{
$_SESSION['payer_id'] = $resArray['PAYERID']; $_SESSION['payer_id'] = $resArray['PAYERID'];
} }
return $resArray; return $resArray;
@ -462,8 +457,7 @@ function hash_call($methodName, $nvpStr)
// TODO problem with triggers // TODO problem with triggers
$API_version = "98.0"; $API_version = "98.0";
if (!empty($conf->global->PAYPAL_API_SANDBOX) || GETPOST('forcesandbox', 'alpha')) // We can force sand box with param 'forcesandbox' if (!empty($conf->global->PAYPAL_API_SANDBOX) || GETPOST('forcesandbox', 'alpha')) { // We can force sand box with param 'forcesandbox'
{
$API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp"; $API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp";
$API_Url = "https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token="; $API_Url = "https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token=";
} else { } else {
@ -473,13 +467,21 @@ function hash_call($methodName, $nvpStr)
// Clean parameters // Clean parameters
$PAYPAL_API_USER = ""; $PAYPAL_API_USER = "";
if (!empty($conf->global->PAYPAL_API_USER)) $PAYPAL_API_USER = $conf->global->PAYPAL_API_USER; if (!empty($conf->global->PAYPAL_API_USER)) {
$PAYPAL_API_USER = $conf->global->PAYPAL_API_USER;
}
$PAYPAL_API_PASSWORD = ""; $PAYPAL_API_PASSWORD = "";
if (!empty($conf->global->PAYPAL_API_PASSWORD)) $PAYPAL_API_PASSWORD = $conf->global->PAYPAL_API_PASSWORD; if (!empty($conf->global->PAYPAL_API_PASSWORD)) {
$PAYPAL_API_PASSWORD = $conf->global->PAYPAL_API_PASSWORD;
}
$PAYPAL_API_SIGNATURE = ""; $PAYPAL_API_SIGNATURE = "";
if (!empty($conf->global->PAYPAL_API_SIGNATURE)) $PAYPAL_API_SIGNATURE = $conf->global->PAYPAL_API_SIGNATURE; if (!empty($conf->global->PAYPAL_API_SIGNATURE)) {
$PAYPAL_API_SIGNATURE = $conf->global->PAYPAL_API_SIGNATURE;
}
$PAYPAL_API_SANDBOX = ""; $PAYPAL_API_SANDBOX = "";
if (!empty($conf->global->PAYPAL_API_SANDBOX)) $PAYPAL_API_SANDBOX = $conf->global->PAYPAL_API_SANDBOX; if (!empty($conf->global->PAYPAL_API_SANDBOX)) {
$PAYPAL_API_SANDBOX = $conf->global->PAYPAL_API_SANDBOX;
}
// TODO END problem with triggers // TODO END problem with triggers
dol_syslog("Paypal API endpoint ".$API_Endpoint); dol_syslog("Paypal API endpoint ".$API_Endpoint);
@ -507,12 +509,13 @@ function hash_call($methodName, $nvpStr)
curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POST, 1);
//if USE_PROXY constant set to true in Constants.php, then only proxy will be enabled. //if USE_PROXY constant set to true in Constants.php, then only proxy will be enabled.
if ($USE_PROXY) if ($USE_PROXY) {
{
dol_syslog("Paypal API hash_call set proxy to ".$PROXY_HOST.":".$PROXY_PORT." - ".$PROXY_USER.":".$PROXY_PASS); dol_syslog("Paypal API hash_call set proxy to ".$PROXY_HOST.":".$PROXY_PORT." - ".$PROXY_USER.":".$PROXY_PASS);
//curl_setopt ($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); // Curl 7.10 //curl_setopt ($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); // Curl 7.10
curl_setopt($ch, CURLOPT_PROXY, $PROXY_HOST.":".$PROXY_PORT); curl_setopt($ch, CURLOPT_PROXY, $PROXY_HOST.":".$PROXY_PORT);
if ($PROXY_USER) curl_setopt($ch, CURLOPT_PROXYUSERPWD, $PROXY_USER.":".$PROXY_PASS); if ($PROXY_USER) {
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $PROXY_USER.":".$PROXY_PASS);
}
} }
//NVPRequest for submitting to server //NVPRequest for submitting to server
@ -564,8 +567,7 @@ function deformatNVP($nvpstr)
$intial = 0; $intial = 0;
$nvpArray = array(); $nvpArray = array();
while (strlen($nvpstr)) while (strlen($nvpstr)) {
{
//postion of Key //postion of Key
$keypos = strpos($nvpstr, '='); $keypos = strpos($nvpstr, '=');
//position of value //position of value
@ -592,13 +594,11 @@ function getApiError()
$resArray = $_SESSION['reshash']; $resArray = $_SESSION['reshash'];
if (isset($_SESSION['curl_error_no'])) if (isset($_SESSION['curl_error_no'])) {
{
$errors[] = $_SESSION['curl_error_no'].'-'.$_SESSION['curl_error_msg']; $errors[] = $_SESSION['curl_error_no'].'-'.$_SESSION['curl_error_msg'];
} }
foreach ($resArray as $key => $value) foreach ($resArray as $key => $value) {
{
$errors[] = $key.'-'.$value; $errors[] = $key.'-'.$value;
} }

View File

@ -22,14 +22,13 @@
* \brief Page with Paypal init var. * \brief Page with Paypal init var.
*/ */
if (session_id() == "") if (session_id() == "") {
{
session_start(); session_start();
if (ini_get('register_globals')) // To solve bug in using $_SESSION if (ini_get('register_globals')) { // To solve bug in using $_SESSION
{ foreach ($_SESSION as $key => $value) {
foreach ($_SESSION as $key=>$value) if (isset($GLOBALS[$key])) {
{ unset($GLOBALS[$key]);
if (isset($GLOBALS[$key])) unset($GLOBALS[$key]); }
} }
} }
} }
@ -48,8 +47,7 @@ $API_version = "56";
' For the sandbox, the URL is https://www.sandbox.paypal.com/webscr&cmd=_express-checkout&token= ' For the sandbox, the URL is https://www.sandbox.paypal.com/webscr&cmd=_express-checkout&token=
' For the live site, the URL is https://www.paypal.com/webscr&cmd=_express-checkout&token= ' For the live site, the URL is https://www.paypal.com/webscr&cmd=_express-checkout&token=
*/ */
if (!empty($conf->global->PAYPAL_API_SANDBOX) || GETPOST('forcesandbox', 'alpha')) // We can force sand box with param 'forcesandbox' if (!empty($conf->global->PAYPAL_API_SANDBOX) || GETPOST('forcesandbox', 'alpha')) { // We can force sand box with param 'forcesandbox'
{
$API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp"; $API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp";
$API_Url = "https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token="; $API_Url = "https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token=";
} else { } else {
@ -59,13 +57,21 @@ if (!empty($conf->global->PAYPAL_API_SANDBOX) || GETPOST('forcesandbox', 'alpha'
// Clean parameters // Clean parameters
$PAYPAL_API_USER = ""; $PAYPAL_API_USER = "";
if (!empty($conf->global->PAYPAL_API_USER)) $PAYPAL_API_USER = $conf->global->PAYPAL_API_USER; if (!empty($conf->global->PAYPAL_API_USER)) {
$PAYPAL_API_USER = $conf->global->PAYPAL_API_USER;
}
$PAYPAL_API_PASSWORD = ""; $PAYPAL_API_PASSWORD = "";
if (!empty($conf->global->PAYPAL_API_PASSWORD)) $PAYPAL_API_PASSWORD = $conf->global->PAYPAL_API_PASSWORD; if (!empty($conf->global->PAYPAL_API_PASSWORD)) {
$PAYPAL_API_PASSWORD = $conf->global->PAYPAL_API_PASSWORD;
}
$PAYPAL_API_SIGNATURE = ""; $PAYPAL_API_SIGNATURE = "";
if (!empty($conf->global->PAYPAL_API_SIGNATURE)) $PAYPAL_API_SIGNATURE = $conf->global->PAYPAL_API_SIGNATURE; if (!empty($conf->global->PAYPAL_API_SIGNATURE)) {
$PAYPAL_API_SIGNATURE = $conf->global->PAYPAL_API_SIGNATURE;
}
$PAYPAL_API_SANDBOX = ""; $PAYPAL_API_SANDBOX = "";
if (!empty($conf->global->PAYPAL_API_SANDBOX)) $PAYPAL_API_SANDBOX = $conf->global->PAYPAL_API_SANDBOX; if (!empty($conf->global->PAYPAL_API_SANDBOX)) {
$PAYPAL_API_SANDBOX = $conf->global->PAYPAL_API_SANDBOX;
}
// Proxy // Proxy
$PROXY_HOST = $conf->global->MAIN_PROXY_HOST; $PROXY_HOST = $conf->global->MAIN_PROXY_HOST;

View File

@ -33,7 +33,9 @@ use OAuth\Common\Storage\DoliStorage;
// Load translation files required by the page // Load translation files required by the page
$langs->loadLangs(array('admin', 'printing', 'oauth')); $langs->loadLangs(array('admin', 'printing', 'oauth'));
if (!$user->admin) accessforbidden(); if (!$user->admin) {
accessforbidden();
}
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
$mode = GETPOST('mode', 'alpha'); $mode = GETPOST('mode', 'alpha');
@ -41,9 +43,13 @@ $value = GETPOST('value', 'alpha', 0, null, null, 1); // The value may be __goog
$varname = GETPOST('varname', 'alpha'); $varname = GETPOST('varname', 'alpha');
$driver = GETPOST('driver', 'alpha'); $driver = GETPOST('driver', 'alpha');
if (!empty($driver)) $langs->load($driver); if (!empty($driver)) {
$langs->load($driver);
}
if (!$mode) $mode = 'config'; if (!$mode) {
$mode = 'config';
}
$OAUTH_SERVICENAME_GOOGLE = 'Google'; $OAUTH_SERVICENAME_GOOGLE = 'Google';
@ -52,21 +58,21 @@ $OAUTH_SERVICENAME_GOOGLE = 'Google';
* Action * Action
*/ */
if (($mode == 'test' || $mode == 'setup') && empty($driver)) if (($mode == 'test' || $mode == 'setup') && empty($driver)) {
{
setEventMessages($langs->trans('PleaseSelectaDriverfromList'), null); setEventMessages($langs->trans('PleaseSelectaDriverfromList'), null);
header("Location: ".$_SERVER['PHP_SELF'].'?mode=config'); header("Location: ".$_SERVER['PHP_SELF'].'?mode=config');
exit; exit;
} }
if ($action == 'setconst' && $user->admin) if ($action == 'setconst' && $user->admin) {
{
$error = 0; $error = 0;
$db->begin(); $db->begin();
foreach ($_POST['setupdriver'] as $setupconst) { foreach ($_POST['setupdriver'] as $setupconst) {
//print '<pre>'.print_r($setupconst, true).'</pre>'; //print '<pre>'.print_r($setupconst, true).'</pre>';
$result = dolibarr_set_const($db, $setupconst['varname'], $setupconst['value'], 'chaine', 0, '', $conf->entity); $result = dolibarr_set_const($db, $setupconst['varname'], $setupconst['value'], 'chaine', 0, '', $conf->entity);
if (!$result > 0) $error++; if (!$result > 0) {
$error++;
}
} }
if (!$error) { if (!$error) {
@ -79,12 +85,13 @@ if ($action == 'setconst' && $user->admin)
$action = ''; $action = '';
} }
if ($action == 'setvalue' && $user->admin) if ($action == 'setvalue' && $user->admin) {
{
$db->begin(); $db->begin();
$result = dolibarr_set_const($db, $varname, $value, 'chaine', 0, '', $conf->entity); $result = dolibarr_set_const($db, $varname, $value, 'chaine', 0, '', $conf->entity);
if (!$result > 0) $error++; if (!$result > 0) {
$error++;
}
if (!$error) { if (!$error) {
$db->commit(); $db->commit();
@ -110,8 +117,7 @@ print load_fiche_titre($langs->trans("PrintingSetup"), $linkback, 'title_setup')
$head = printingAdminPrepareHead($mode); $head = printingAdminPrepareHead($mode);
if ($mode == 'setup' && $user->admin) if ($mode == 'setup' && $user->admin) {
{
print '<form method="post" action="'.$_SERVER["PHP_SELF"].'?mode=setup&amp;driver='.$driver.'" autocomplete="off">'; print '<form method="post" action="'.$_SERVER["PHP_SELF"].'?mode=setup&amp;driver='.$driver.'" autocomplete="off">';
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="action" value="setconst">'; print '<input type="hidden" name="action" value="setconst">';
@ -143,8 +149,7 @@ if ($mode == 'setup' && $user->admin)
$i = 0; $i = 0;
$submit_enabled = 0; $submit_enabled = 0;
foreach ($printer->conf as $key) foreach ($printer->conf as $key) {
{
switch ($key['type']) { switch ($key['type']) {
case "text": case "text":
case "password": case "password":
@ -159,8 +164,7 @@ if ($mode == 'setup' && $user->admin)
case "info": // Google Api setup or Google OAuth Token case "info": // Google Api setup or Google OAuth Token
print '<tr class="oddeven">'; print '<tr class="oddeven">';
print '<td'.($key['required'] ? ' class=required' : '').'>'; print '<td'.($key['required'] ? ' class=required' : '').'>';
if ($key['varname'] == 'PRINTGCP_TOKEN_ACCESS') if ($key['varname'] == 'PRINTGCP_TOKEN_ACCESS') {
{
print $langs->trans("IsTokenGenerated"); print $langs->trans("IsTokenGenerated");
} else { } else {
print $langs->trans($key['varname']); print $langs->trans($key['varname']);
@ -169,10 +173,11 @@ if ($mode == 'setup' && $user->admin)
print '<td>'.$langs->trans($key['info']).'</td>'; print '<td>'.$langs->trans($key['info']).'</td>';
print '<td>'; print '<td>';
//var_dump($key); //var_dump($key);
if ($key['varname'] == 'PRINTGCP_TOKEN_ACCESS') if ($key['varname'] == 'PRINTGCP_TOKEN_ACCESS') {
{
// Delete remote tokens // Delete remote tokens
if (!empty($key['delete'])) print '<a class="button" href="'.$key['delete'].'">'.$langs->trans('DeleteAccess').'</a><br><br>'; if (!empty($key['delete'])) {
print '<a class="button" href="'.$key['delete'].'">'.$langs->trans('DeleteAccess').'</a><br><br>';
}
// Request remote token // Request remote token
print '<a class="button" href="'.$key['renew'].'">'.$langs->trans('RequestAccess').'</a><br><br>'; print '<a class="button" href="'.$key['renew'].'">'.$langs->trans('RequestAccess').'</a><br><br>';
// Check remote access // Check remote access
@ -182,13 +187,14 @@ if ($mode == 'setup' && $user->admin)
print '</tr>'."\n"; print '</tr>'."\n";
break; break;
case "submit": case "submit":
if ($key['enabled']) $submit_enabled = 1; if ($key['enabled']) {
$submit_enabled = 1;
}
break; break;
} }
$i++; $i++;
if ($key['varname'] == 'PRINTGCP_TOKEN_ACCESS') if ($key['varname'] == 'PRINTGCP_TOKEN_ACCESS') {
{
// Token // Token
print '<tr class="oddeven">'; print '<tr class="oddeven">';
print '<td>'.$langs->trans("Token").'</td>'; print '<td>'.$langs->trans("Token").'</td>';
@ -198,12 +204,10 @@ if ($mode == 'setup' && $user->admin)
$storage = new DoliStorage($db, $conf); $storage = new DoliStorage($db, $conf);
try { try {
$tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME_GOOGLE); $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME_GOOGLE);
} catch (Exception $e) } catch (Exception $e) {
{
// Return an error if token not found // Return an error if token not found
} }
if (is_object($tokenobj)) if (is_object($tokenobj)) {
{
//var_dump($tokenobj); //var_dump($tokenobj);
print $tokenobj->getAccessToken().'<br>'; print $tokenobj->getAccessToken().'<br>';
//print 'Refresh: '.$tokenobj->getRefreshToken().'<br>'; //print 'Refresh: '.$tokenobj->getRefreshToken().'<br>';
@ -225,8 +229,7 @@ if ($mode == 'setup' && $user->admin)
print dol_get_fiche_end(); print dol_get_fiche_end();
if (!empty($driver)) if (!empty($driver)) {
{
if ($submit_enabled) { if ($submit_enabled) {
print '<div class="center"><input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans("Modify")).'"></div>'; print '<div class="center"><input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans("Modify")).'"></div>';
} }
@ -234,8 +237,7 @@ if ($mode == 'setup' && $user->admin)
print '</form>'; print '</form>';
} }
if ($mode == 'config' && $user->admin) if ($mode == 'config' && $user->admin) {
{
print dol_get_fiche_head($head, $mode, $langs->trans("ModuleSetup"), -1, 'technic'); print dol_get_fiche_head($head, $mode, $langs->trans("ModuleSetup"), -1, 'technic');
print $langs->trans("PrintingDesc")."<br><br>\n"; print $langs->trans("PrintingDesc")."<br><br>\n";
@ -287,8 +289,7 @@ if ($mode == 'config' && $user->admin)
print dol_get_fiche_end(); print dol_get_fiche_end();
} }
if ($mode == 'test' && $user->admin) if ($mode == 'test' && $user->admin) {
{
print dol_get_fiche_head($head, $mode, $langs->trans("ModuleSetup"), -1, 'technic'); print dol_get_fiche_head($head, $mode, $langs->trans("ModuleSetup"), -1, 'technic');
print $langs->trans('PrintTestDesc'.$driver)."<br><br>\n"; print $langs->trans('PrintTestDesc'.$driver)."<br><br>\n";
@ -325,8 +326,7 @@ if ($mode == 'test' && $user->admin)
print dol_get_fiche_end(); print dol_get_fiche_end();
} }
if ($mode == 'userconf' && $user->admin) if ($mode == 'userconf' && $user->admin) {
{
print dol_get_fiche_head($head, $mode, $langs->trans("ModuleSetup"), -1, 'technic'); print dol_get_fiche_head($head, $mode, $langs->trans("ModuleSetup"), -1, 'technic');
print $langs->trans('PrintUserConfDesc'.$driver)."<br><br>\n"; print $langs->trans('PrintUserConfDesc'.$driver)."<br><br>\n";

View File

@ -37,7 +37,9 @@ $cancel = GETPOST('cancel', 'alpha');
$selection = GETPOST('selection', 'int'); $selection = GETPOST('selection', 'int');
// Security check // Security check
if (!$user->admin) accessforbidden(); if (!$user->admin) {
accessforbidden();
}
//Objects //Objects
$price_globals = new PriceGlobalVariable($db); $price_globals = new PriceGlobalVariable($db);
@ -157,8 +159,7 @@ print '<span class="opacitymedium">'.$langs->trans("DynamicPriceDesc").'</span><
print '<br>'; print '<br>';
//Global variables table //Global variables table
if ($action != 'create_updater' && $action != 'edit_updater') if ($action != 'create_updater' && $action != 'edit_updater') {
{
print load_fiche_titre($langs->trans("GlobalVariables"), '', ''); print load_fiche_titre($langs->trans("GlobalVariables"), '', '');
print '<table summary="listofattributes" class="noborder centpercent">'; print '<table summary="listofattributes" class="noborder centpercent">';
@ -187,8 +188,7 @@ if ($action != 'create_updater' && $action != 'edit_updater')
} }
print '</table>'; print '</table>';
if (empty($action)) if (empty($action)) {
{
//Action Buttons //Action Buttons
print '<div class="tabsAction">'; print '<div class="tabsAction">';
print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=create_variable">'.$langs->trans("AddVariable").'</a>'; print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=create_variable">'.$langs->trans("AddVariable").'</a>';
@ -234,8 +234,7 @@ if ($action == 'create_variable' || $action == 'edit_variable') {
} }
// Updaters table // Updaters table
if ($action != 'create_variable' && $action != 'edit_variable') if ($action != 'create_variable' && $action != 'edit_variable') {
{
print load_fiche_titre($langs->trans("GlobalVariableUpdaters"), '', ''); print load_fiche_titre($langs->trans("GlobalVariableUpdaters"), '', '');
print '<table summary="listofattributes" class="noborder centpercent">'; print '<table summary="listofattributes" class="noborder centpercent">';
@ -250,8 +249,7 @@ if ($action != 'create_variable' && $action != 'edit_variable')
print '</tr>'; print '</tr>';
$arraypriceupdaters = $price_updaters->listUpdaters(); $arraypriceupdaters = $price_updaters->listUpdaters();
if (!empty($arraypriceupdaters)) if (!empty($arraypriceupdaters)) {
{
foreach ($arraypriceupdaters as $i => $entry) { foreach ($arraypriceupdaters as $i => $entry) {
$code = ""; $code = "";
if ($entry->fk_variable > 0) { if ($entry->fk_variable > 0) {
@ -278,8 +276,7 @@ if ($action != 'create_variable' && $action != 'edit_variable')
} }
print '</table>'; print '</table>';
if (empty($action)) if (empty($action)) {
{
//Action Buttons //Action Buttons
print '<div class="tabsAction">'; print '<div class="tabsAction">';
print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=create_updater&token='.newToken().'">'.$langs->trans("AddUpdater").'</a>'; print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=create_updater&token='.newToken().'">'.$langs->trans("AddUpdater").'</a>';

View File

@ -29,8 +29,9 @@ $langs->loadLangs(array('admin', 'products'));
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
// Security check // Security check
if (!$user->admin || (empty($conf->product->enabled) && empty($conf->service->enabled))) if (!$user->admin || (empty($conf->product->enabled) && empty($conf->service->enabled))) {
accessforbidden(); accessforbidden();
}
$error = 0; $error = 0;

View File

@ -40,8 +40,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formbarcode.class.php';
$langs->loadLangs(array("admin", "products")); $langs->loadLangs(array("admin", "products"));
// Security check // Security check
if (!$user->admin || (empty($conf->product->enabled) && empty($conf->service->enabled))) if (!$user->admin || (empty($conf->product->enabled) && empty($conf->service->enabled))) {
accessforbidden(); accessforbidden();
}
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
$value = GETPOST('value', 'alpha'); $value = GETPOST('value', 'alpha');
@ -56,9 +57,13 @@ $select_pricing_rules = array(
'PRODUIT_CUSTOMER_PRICES'=>$langs->trans('PriceByCustomer'), // Different price for each customer 'PRODUIT_CUSTOMER_PRICES'=>$langs->trans('PriceByCustomer'), // Different price for each customer
); );
$keyforparam = 'PRODUIT_CUSTOMER_PRICES_BY_QTY'; $keyforparam = 'PRODUIT_CUSTOMER_PRICES_BY_QTY';
if ($conf->global->MAIN_FEATURES_LEVEL >= 1 || !empty($conf->global->$keyforparam)) $select_pricing_rules['PRODUIT_CUSTOMER_PRICES_BY_QTY'] = $langs->trans('PriceByQuantity').' ('.$langs->trans("VersionExperimental").')'; // TODO If this is enabled, price must be hidden when price by qty is enabled, also price for quantity must be used when adding product into order/propal/invoice if ($conf->global->MAIN_FEATURES_LEVEL >= 1 || !empty($conf->global->$keyforparam)) {
$select_pricing_rules['PRODUIT_CUSTOMER_PRICES_BY_QTY'] = $langs->trans('PriceByQuantity').' ('.$langs->trans("VersionExperimental").')'; // TODO If this is enabled, price must be hidden when price by qty is enabled, also price for quantity must be used when adding product into order/propal/invoice
}
$keyforparam = 'PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES'; $keyforparam = 'PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES';
if ($conf->global->MAIN_FEATURES_LEVEL >= 2 || !empty($conf->global->$keyforparam)) $select_pricing_rules['PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES'] = $langs->trans('MultiPricesAbility').'+'.$langs->trans('PriceByQuantity').' ('.$langs->trans("VersionExperimental").')'; if ($conf->global->MAIN_FEATURES_LEVEL >= 2 || !empty($conf->global->$keyforparam)) {
$select_pricing_rules['PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES'] = $langs->trans('MultiPricesAbility').'+'.$langs->trans('PriceByQuantity').' ('.$langs->trans("VersionExperimental").')';
}
// Clean param // Clean param
if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($conf->global->PRODUIT_MULTIPRICES_LIMIT)) { if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($conf->global->PRODUIT_MULTIPRICES_LIMIT)) {
@ -75,10 +80,8 @@ $error = 0;
$nomessageinsetmoduleoptions = 1; $nomessageinsetmoduleoptions = 1;
include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php';
if ($action == 'setcodeproduct') if ($action == 'setcodeproduct') {
{ if (dolibarr_set_const($db, "PRODUCT_CODEPRODUCT_ADDON", $value, 'chaine', 0, '', $conf->entity) > 0) {
if (dolibarr_set_const($db, "PRODUCT_CODEPRODUCT_ADDON", $value, 'chaine', 0, '', $conf->entity) > 0)
{
header("Location: ".$_SERVER["PHP_SELF"]); header("Location: ".$_SERVER["PHP_SELF"]);
exit; exit;
} else { } else {
@ -86,33 +89,30 @@ if ($action == 'setcodeproduct')
} }
} }
if ($action == 'other' && GETPOST('value_PRODUIT_LIMIT_SIZE') >= 0) if ($action == 'other' && GETPOST('value_PRODUIT_LIMIT_SIZE') >= 0) {
{
$res = dolibarr_set_const($db, "PRODUIT_LIMIT_SIZE", GETPOST('value_PRODUIT_LIMIT_SIZE'), 'chaine', 0, '', $conf->entity); $res = dolibarr_set_const($db, "PRODUIT_LIMIT_SIZE", GETPOST('value_PRODUIT_LIMIT_SIZE'), 'chaine', 0, '', $conf->entity);
if (!($res > 0)) $error++; if (!($res > 0)) {
$error++;
} }
if ($action == 'other' && GETPOST('value_PRODUIT_MULTIPRICES_LIMIT') > 0) }
{ if ($action == 'other' && GETPOST('value_PRODUIT_MULTIPRICES_LIMIT') > 0) {
$res = dolibarr_set_const($db, "PRODUIT_MULTIPRICES_LIMIT", GETPOST('value_PRODUIT_MULTIPRICES_LIMIT'), 'chaine', 0, '', $conf->entity); $res = dolibarr_set_const($db, "PRODUIT_MULTIPRICES_LIMIT", GETPOST('value_PRODUIT_MULTIPRICES_LIMIT'), 'chaine', 0, '', $conf->entity);
if (!($res > 0)) $error++; if (!($res > 0)) {
$error++;
} }
if ($action == 'other') }
{ if ($action == 'other') {
$princingrules = GETPOST('princingrule', 'alpha'); $princingrules = GETPOST('princingrule', 'alpha');
foreach ($select_pricing_rules as $rule => $label) // Loop on each possible mode foreach ($select_pricing_rules as $rule => $label) { // Loop on each possible mode
{ if ($rule == $princingrules) { // We are on selected rule, we enable it
if ($rule == $princingrules) // We are on selected rule, we enable it if ($princingrules == 'PRODUCT_PRICE_UNIQ') { // For this case, we disable entries manually
{
if ($princingrules == 'PRODUCT_PRICE_UNIQ') // For this case, we disable entries manually
{
$res = dolibarr_set_const($db, 'PRODUIT_MULTIPRICES', 0, 'chaine', 0, '', $conf->entity); $res = dolibarr_set_const($db, 'PRODUIT_MULTIPRICES', 0, 'chaine', 0, '', $conf->entity);
$res = dolibarr_set_const($db, 'PRODUIT_CUSTOMER_PRICES_BY_QTY', 0, 'chaine', 0, '', $conf->entity); $res = dolibarr_set_const($db, 'PRODUIT_CUSTOMER_PRICES_BY_QTY', 0, 'chaine', 0, '', $conf->entity);
$res = dolibarr_set_const($db, 'PRODUIT_CUSTOMER_PRICES', 0, 'chaine', 0, '', $conf->entity); $res = dolibarr_set_const($db, 'PRODUIT_CUSTOMER_PRICES', 0, 'chaine', 0, '', $conf->entity);
dolibarr_set_const($db, 'PRODUCT_PRICE_UNIQ', 1, 'chaine', 0, '', $conf->entity); dolibarr_set_const($db, 'PRODUCT_PRICE_UNIQ', 1, 'chaine', 0, '', $conf->entity);
} else { } else {
$multirule = explode('&', $princingrules); $multirule = explode('&', $princingrules);
foreach ($multirule as $rulesselected) foreach ($multirule as $rulesselected) {
{
$res = dolibarr_set_const($db, $rulesselected, 1, 'chaine', 0, '', $conf->entity); $res = dolibarr_set_const($db, $rulesselected, 1, 'chaine', 0, '', $conf->entity);
} }
} }
@ -151,8 +151,7 @@ if ($action == 'other')
if ($value) { if ($value) {
$sql_test = "SELECT count(desc_fourn) as cpt FROM ".MAIN_DB_PREFIX."product_fournisseur_price WHERE 1"; $sql_test = "SELECT count(desc_fourn) as cpt FROM ".MAIN_DB_PREFIX."product_fournisseur_price WHERE 1";
$resql = $db->query($sql_test); $resql = $db->query($sql_test);
if (!$resql && $db->lasterrno == 'DB_ERROR_NOSUCHFIELD') // if the field does not exist, we create it if (!$resql && $db->lasterrno == 'DB_ERROR_NOSUCHFIELD') { // if the field does not exist, we create it
{
$sql_new = "ALTER TABLE ".MAIN_DB_PREFIX."product_fournisseur_price ADD COLUMN desc_fourn text"; $sql_new = "ALTER TABLE ".MAIN_DB_PREFIX."product_fournisseur_price ADD COLUMN desc_fourn text";
$resql_new = $db->query($sql_new); $resql_new = $db->query($sql_new);
} }
@ -163,16 +162,14 @@ if ($action == 'other')
if ($value) { if ($value) {
$sql_test = "SELECT count(packaging) as cpt FROM ".MAIN_DB_PREFIX."product_fournisseur_price WHERE 1"; $sql_test = "SELECT count(packaging) as cpt FROM ".MAIN_DB_PREFIX."product_fournisseur_price WHERE 1";
$resql = $db->query($sql_test); $resql = $db->query($sql_test);
if (!$resql && $db->lasterrno == 'DB_ERROR_NOSUCHFIELD') // if the field does not exist, we create it if (!$resql && $db->lasterrno == 'DB_ERROR_NOSUCHFIELD') { // if the field does not exist, we create it
{
$sql_new = "ALTER TABLE ".MAIN_DB_PREFIX."product_fournisseur_price ADD COLUMN packaging double(24,8) DEFAULT 1"; $sql_new = "ALTER TABLE ".MAIN_DB_PREFIX."product_fournisseur_price ADD COLUMN packaging double(24,8) DEFAULT 1";
$resql_new = $db->query($sql_new); $resql_new = $db->query($sql_new);
} }
} }
} }
if ($action == 'specimen') // For products if ($action == 'specimen') { // For products
{
$modele = GETPOST('module', 'alpha'); $modele = GETPOST('module', 'alpha');
$product = new Product($db); $product = new Product($db);
@ -181,25 +178,21 @@ if ($action == 'specimen') // For products
// Search template files // Search template files
$file = ''; $classname = ''; $filefound = 0; $file = ''; $classname = ''; $filefound = 0;
$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
foreach ($dirmodels as $reldir) foreach ($dirmodels as $reldir) {
{
$file = dol_buildpath($reldir."core/modules/product/doc/pdf_".$modele.".modules.php", 0); $file = dol_buildpath($reldir."core/modules/product/doc/pdf_".$modele.".modules.php", 0);
if (file_exists($file)) if (file_exists($file)) {
{
$filefound = 1; $filefound = 1;
$classname = "pdf_".$modele; $classname = "pdf_".$modele;
break; break;
} }
} }
if ($filefound) if ($filefound) {
{
require_once $file; require_once $file;
$module = new $classname($db); $module = new $classname($db);
if ($module->write_file($product, $langs, '') > 0) if ($module->write_file($product, $langs, '') > 0) {
{
header("Location: ".DOL_URL_ROOT."/document.php?modulepart=product&file=SPECIMEN.pdf"); header("Location: ".DOL_URL_ROOT."/document.php?modulepart=product&file=SPECIMEN.pdf");
return; return;
} else { } else {
@ -213,25 +206,22 @@ if ($action == 'specimen') // For products
} }
// Activate a model // Activate a model
if ($action == 'set') if ($action == 'set') {
{
$ret = addDocumentModel($value, $type, $label, $scandir); $ret = addDocumentModel($value, $type, $label, $scandir);
} }
if ($action == 'del') if ($action == 'del') {
{
$ret = delDocumentModel($value, $type); $ret = delDocumentModel($value, $type);
if ($ret > 0) if ($ret > 0) {
{ if ($conf->global->PRODUCT_ADDON_PDF == "$value") {
if ($conf->global->PRODUCT_ADDON_PDF == "$value") dolibarr_del_const($db, 'PRODUCT_ADDON_PDF', $conf->entity); dolibarr_del_const($db, 'PRODUCT_ADDON_PDF', $conf->entity);
}
} }
} }
// Set default model // Set default model
if ($action == 'setdoc') if ($action == 'setdoc') {
{ if (dolibarr_set_const($db, "PRODUCT_ADDON_PDF", $value, 'chaine', 0, '', $conf->entity)) {
if (dolibarr_set_const($db, "PRODUCT_ADDON_PDF", $value, 'chaine', 0, '', $conf->entity))
{
// La constante qui a ete lue en avant du nouveau set // La constante qui a ete lue en avant du nouveau set
// on passe donc par une variable pour avoir un affichage coherent // on passe donc par une variable pour avoir un affichage coherent
$conf->global->PRODUCT_ADDON_PDF = $value; $conf->global->PRODUCT_ADDON_PDF = $value;
@ -239,20 +229,23 @@ if ($action == 'setdoc')
// On active le modele // On active le modele
$ret = delDocumentModel($value, $type); $ret = delDocumentModel($value, $type);
if ($ret > 0) if ($ret > 0) {
{
$ret = addDocumentModel($value, $type, $label, $scandir); $ret = addDocumentModel($value, $type, $label, $scandir);
} }
} }
if ($action == 'set') if ($action == 'set') {
{
$const = "PRODUCT_SPECIAL_".strtoupper(GETPOST('spe', 'alpha')); $const = "PRODUCT_SPECIAL_".strtoupper(GETPOST('spe', 'alpha'));
$value = GETPOST('value'); $value = GETPOST('value');
if (GETPOST('value', 'alpha')) $res = dolibarr_set_const($db, $const, $value, 'chaine', 0, '', $conf->entity); if (GETPOST('value', 'alpha')) {
else $res = dolibarr_del_const($db, $const, $conf->entity); $res = dolibarr_set_const($db, $const, $value, 'chaine', 0, '', $conf->entity);
if (!($res > 0)) $error++; } else {
$res = dolibarr_del_const($db, $const, $conf->entity);
}
if (!($res > 0)) {
$error++;
}
} }
//if ($action == 'other') //if ($action == 'other')
@ -262,10 +255,8 @@ if ($action == 'set')
// if (! $res > 0) $error++; // if (! $res > 0) $error++;
//} //}
if ($action) if ($action) {
{ if (!$error) {
if (!$error)
{
setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
} else { } else {
setEventMessages($langs->trans("SetupNotError"), null, 'errors'); setEventMessages($langs->trans("SetupNotError"), null, 'errors');
@ -280,12 +271,10 @@ $formbarcode = new FormBarCode($db);
$title = $langs->trans('ProductServiceSetup'); $title = $langs->trans('ProductServiceSetup');
$tab = $langs->trans("ProductsAndServices"); $tab = $langs->trans("ProductsAndServices");
if (empty($conf->product->enabled)) if (empty($conf->product->enabled)) {
{
$title = $langs->trans('ServiceSetup'); $title = $langs->trans('ServiceSetup');
$tab = $langs->trans('Services'); $tab = $langs->trans('Services');
} elseif (empty($conf->service->enabled)) } elseif (empty($conf->service->enabled)) {
{
$title = $langs->trans('ProductSetup'); $title = $langs->trans('ProductSetup');
$tab = $langs->trans('Products'); $tab = $langs->trans('Products');
} }
@ -315,50 +304,53 @@ print ' <td class="center" width="80">'.$langs->trans("Status").'</td>';
print ' <td class="center" width="60">'.$langs->trans("ShortInfo").'</td>'; print ' <td class="center" width="60">'.$langs->trans("ShortInfo").'</td>';
print "</tr>\n"; print "</tr>\n";
foreach ($dirproduct as $dirroot) foreach ($dirproduct as $dirroot) {
{
$dir = dol_buildpath($dirroot, 0); $dir = dol_buildpath($dirroot, 0);
$handle = @opendir($dir); $handle = @opendir($dir);
if (is_resource($handle)) if (is_resource($handle)) {
{
// Loop on each module find in opened directory // Loop on each module find in opened directory
while (($file = readdir($handle)) !== false) while (($file = readdir($handle)) !== false) {
{ if (substr($file, 0, 16) == 'mod_codeproduct_' && substr($file, -3) == 'php') {
if (substr($file, 0, 16) == 'mod_codeproduct_' && substr($file, -3) == 'php')
{
$file = substr($file, 0, dol_strlen($file) - 4); $file = substr($file, 0, dol_strlen($file) - 4);
try { try {
dol_include_once($dirroot.$file.'.php'); dol_include_once($dirroot.$file.'.php');
} catch (Exception $e) } catch (Exception $e) {
{
dol_syslog($e->getMessage(), LOG_ERR); dol_syslog($e->getMessage(), LOG_ERR);
} }
$modCodeProduct = new $file; $modCodeProduct = new $file;
// Show modules according to features level // Show modules according to features level
if ($modCodeProduct->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; if ($modCodeProduct->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) {
if ($modCodeProduct->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) continue; continue;
}
if ($modCodeProduct->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) {
continue;
}
print '<tr class="oddeven">'."\n"; print '<tr class="oddeven">'."\n";
print '<td width="140">'.$modCodeProduct->name.'</td>'."\n"; print '<td width="140">'.$modCodeProduct->name.'</td>'."\n";
print '<td>'.$modCodeProduct->info($langs).'</td>'."\n"; print '<td>'.$modCodeProduct->info($langs).'</td>'."\n";
print '<td class="nowrap">'.$modCodeProduct->getExample($langs).'</td>'."\n"; print '<td class="nowrap">'.$modCodeProduct->getExample($langs).'</td>'."\n";
if (!empty($conf->global->PRODUCT_CODEPRODUCT_ADDON) && $conf->global->PRODUCT_CODEPRODUCT_ADDON == $file) if (!empty($conf->global->PRODUCT_CODEPRODUCT_ADDON) && $conf->global->PRODUCT_CODEPRODUCT_ADDON == $file) {
{
print '<td class="center">'."\n"; print '<td class="center">'."\n";
print img_picto($langs->trans("Activated"), 'switch_on'); print img_picto($langs->trans("Activated"), 'switch_on');
print "</td>\n"; print "</td>\n";
} else { } else {
$disabled = false; $disabled = false;
if (!empty($conf->multicompany->enabled) && (is_object($mc) && !empty($mc->sharings['referent']) && $mc->sharings['referent'] == $conf->entity) ? false : true); if (!empty($conf->multicompany->enabled) && (is_object($mc) && !empty($mc->sharings['referent']) && $mc->sharings['referent'] == $conf->entity) ? false : true) {
}
print '<td class="center">'; print '<td class="center">';
if (!$disabled) print '<a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=setcodeproduct&token='.newToken().'&value='.$file.'">'; if (!$disabled) {
print '<a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=setcodeproduct&token='.newToken().'&value='.$file.'">';
}
print img_picto($langs->trans("Disabled"), 'switch_off'); print img_picto($langs->trans("Disabled"), 'switch_off');
if (!$disabled) print '</a>'; if (!$disabled) {
print '</a>';
}
print '</td>'; print '</td>';
} }
@ -382,12 +374,10 @@ $sql .= " FROM ".MAIN_DB_PREFIX."document_model";
$sql .= " WHERE type = '".$db->escape($type)."'"; $sql .= " WHERE type = '".$db->escape($type)."'";
$sql .= " AND entity = ".$conf->entity; $sql .= " AND entity = ".$conf->entity;
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$i = 0; $i = 0;
$num_rows = $db->num_rows($resql); $num_rows = $db->num_rows($resql);
while ($i < $num_rows) while ($i < $num_rows) {
{
$array = $db->fetch_array($resql); $array = $db->fetch_array($resql);
array_push($def, $array[0]); array_push($def, $array[0]);
$i++; $i++;
@ -412,29 +402,21 @@ print "</tr>\n";
clearstatcache(); clearstatcache();
foreach ($dirmodels as $reldir) foreach ($dirmodels as $reldir) {
{ foreach (array('', '/doc') as $valdir) {
foreach (array('', '/doc') as $valdir)
{
$dir = dol_buildpath($reldir."core/modules/product".$valdir); $dir = dol_buildpath($reldir."core/modules/product".$valdir);
if (is_dir($dir)) if (is_dir($dir)) {
{
$handle = opendir($dir); $handle = opendir($dir);
if (is_resource($handle)) if (is_resource($handle)) {
{ while (($file = readdir($handle)) !== false) {
while (($file = readdir($handle)) !== false)
{
$filelist[] = $file; $filelist[] = $file;
} }
closedir($handle); closedir($handle);
arsort($filelist); arsort($filelist);
foreach ($filelist as $file) foreach ($filelist as $file) {
{ if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) {
if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) if (file_exists($dir.'/'.$file)) {
{
if (file_exists($dir.'/'.$file))
{
$name = substr($file, 4, dol_strlen($file) - 16); $name = substr($file, 4, dol_strlen($file) - 16);
$classname = substr($file, 0, dol_strlen($file) - 12); $classname = substr($file, 0, dol_strlen($file) - 12);
@ -442,21 +424,26 @@ foreach ($dirmodels as $reldir)
$module = new $classname($db); $module = new $classname($db);
$modulequalified = 1; $modulequalified = 1;
if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) $modulequalified = 0; if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) {
if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) $modulequalified = 0; $modulequalified = 0;
}
if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) {
$modulequalified = 0;
}
if ($modulequalified) if ($modulequalified) {
{
print '<tr class="oddeven"><td width="100">'; print '<tr class="oddeven"><td width="100">';
print (empty($module->name) ? $name : $module->name); print (empty($module->name) ? $name : $module->name);
print "</td><td>\n"; print "</td><td>\n";
if (method_exists($module, 'info')) print $module->info($langs); if (method_exists($module, 'info')) {
else print $module->description; print $module->info($langs);
} else {
print $module->description;
}
print '</td>'; print '</td>';
// Active // Active
if (in_array($name, $def)) if (in_array($name, $def)) {
{
print '<td class="center">'."\n"; print '<td class="center">'."\n";
print '<a href="'.$_SERVER["PHP_SELF"].'?action=del&value='.$name.'">'; print '<a href="'.$_SERVER["PHP_SELF"].'?action=del&value='.$name.'">';
print img_picto($langs->trans("Enabled"), 'switch_on'); print img_picto($langs->trans("Enabled"), 'switch_on');
@ -470,8 +457,7 @@ foreach ($dirmodels as $reldir)
// Defaut // Defaut
print '<td class="center">'; print '<td class="center">';
if ($conf->global->PRODUCT_ADDON_PDF == $name) if ($conf->global->PRODUCT_ADDON_PDF == $name) {
{
print img_picto($langs->trans("Default"), 'on'); print img_picto($langs->trans("Default"), 'on');
} else { } else {
print '<a href="'.$_SERVER["PHP_SELF"].'?action=setdoc&amp;token='.newToken().'&amp;value='.$name.'&amp;scan_dir='.$module->scandir.'&amp;label='.urlencode($module->name).'" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"), 'off').'</a>'; print '<a href="'.$_SERVER["PHP_SELF"].'?action=setdoc&amp;token='.newToken().'&amp;value='.$name.'&amp;scan_dir='.$module->scandir.'&amp;label='.urlencode($module->name).'" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"), 'off').'</a>';
@ -481,8 +467,7 @@ foreach ($dirmodels as $reldir)
// Info // Info
$htmltooltip = ''.$langs->trans("Name").': '.$module->name; $htmltooltip = ''.$langs->trans("Name").': '.$module->name;
$htmltooltip .= '<br>'.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown")); $htmltooltip .= '<br>'.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown"));
if ($module->type == 'pdf') if ($module->type == 'pdf') {
{
$htmltooltip .= '<br>'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; $htmltooltip .= '<br>'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur;
} }
$htmltooltip .= '<br><br><u>'.$langs->trans("FeaturesSupported").':</u>'; $htmltooltip .= '<br><br><u>'.$langs->trans("FeaturesSupported").':</u>';
@ -496,8 +481,7 @@ foreach ($dirmodels as $reldir)
// Preview // Preview
print '<td class="center">'; print '<td class="center">';
if ($module->type == 'pdf') if ($module->type == 'pdf') {
{
print '<a href="'.$_SERVER["PHP_SELF"].'?action=specimen&module='.$name.'">'.img_object($langs->trans("Preview"), 'contract').'</a>'; print '<a href="'.$_SERVER["PHP_SELF"].'?action=specimen&module='.$name.'">'.img_object($langs->trans("Preview"), 'contract').'</a>';
} else { } else {
print img_object($langs->trans("PreviewNotAvailable"), 'generic'); print img_object($langs->trans("PreviewNotAvailable"), 'generic');
@ -568,26 +552,32 @@ print '</tr>';
// Rule for price // Rule for price
print '<tr class="oddeven">'; print '<tr class="oddeven">';
if (empty($conf->multicompany->enabled)) if (empty($conf->multicompany->enabled)) {
{
print '<td>'.$langs->trans("PricingRule").'</td>'; print '<td>'.$langs->trans("PricingRule").'</td>';
} else { } else {
print '<td>'.$form->textwithpicto($langs->trans("PricingRule"), $langs->trans("SamePriceAlsoForSharedCompanies"), 1).'</td>'; print '<td>'.$form->textwithpicto($langs->trans("PricingRule"), $langs->trans("SamePriceAlsoForSharedCompanies"), 1).'</td>';
} }
print '<td class="right">'; print '<td class="right">';
$current_rule = 'PRODUCT_PRICE_UNIQ'; $current_rule = 'PRODUCT_PRICE_UNIQ';
if (!empty($conf->global->PRODUIT_MULTIPRICES)) $current_rule = 'PRODUIT_MULTIPRICES'; if (!empty($conf->global->PRODUIT_MULTIPRICES)) {
if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) $current_rule = 'PRODUIT_CUSTOMER_PRICES_BY_QTY'; $current_rule = 'PRODUIT_MULTIPRICES';
if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) $current_rule = 'PRODUIT_CUSTOMER_PRICES'; }
if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) $current_rule = 'PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES'; if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) {
$current_rule = 'PRODUIT_CUSTOMER_PRICES_BY_QTY';
}
if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
$current_rule = 'PRODUIT_CUSTOMER_PRICES';
}
if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
$current_rule = 'PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES';
}
print $form->selectarray("princingrule", $select_pricing_rules, $current_rule, 0, 0, 0, '', 1, 0, 0, '', 'maxwidth400', 1); print $form->selectarray("princingrule", $select_pricing_rules, $current_rule, 0, 0, 0, '', 1, 0, 0, '', 'maxwidth400', 1);
print '</td>'; print '</td>';
print '</tr>'; print '</tr>';
// multiprix nombre de prix a proposer // multiprix nombre de prix a proposer
if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
{
print '<tr class="oddeven">'; print '<tr class="oddeven">';
print '<td>'.$langs->trans("MultiPricesNumPrices").'</td>'; print '<td>'.$langs->trans("MultiPricesNumPrices").'</td>';
print '<td class="right"><input size="3" type="text" class="flat" name="value_PRODUIT_MULTIPRICES_LIMIT" value="'.$conf->global->PRODUIT_MULTIPRICES_LIMIT.'"></td>'; print '<td class="right"><input size="3" type="text" class="flat" name="value_PRODUIT_MULTIPRICES_LIMIT" value="'.$conf->global->PRODUIT_MULTIPRICES_LIMIT.'"></td>';
@ -606,8 +596,7 @@ print '</tr>';
print '<tr class="oddeven">'; print '<tr class="oddeven">';
print '<td>'.$form->textwithpicto($langs->trans("UseSearchToSelectProduct"), $langs->trans('UseSearchToSelectProductTooltip'), 1).'</td>'; print '<td>'.$form->textwithpicto($langs->trans("UseSearchToSelectProduct"), $langs->trans('UseSearchToSelectProductTooltip'), 1).'</td>';
if (empty($conf->use_javascript_ajax)) if (empty($conf->use_javascript_ajax)) {
{
print '<td class="nowrap right">'; print '<td class="nowrap right">';
print $langs->trans("NotAvailableWhenAjaxDisabled"); print $langs->trans("NotAvailableWhenAjaxDisabled");
print '</td>'; print '</td>';
@ -624,8 +613,7 @@ if (empty($conf->use_javascript_ajax))
} }
print '</tr>'; print '</tr>';
if (empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) if (empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
{
print '<tr class="oddeven">'; print '<tr class="oddeven">';
print '<td>'.$langs->trans("NumberOfProductShowInSelect").'</td>'; print '<td>'.$langs->trans("NumberOfProductShowInSelect").'</td>';
print '<td class="right"><input size="3" type="text" class="flat" name="value_PRODUIT_LIMIT_SIZE" value="'.$conf->global->PRODUIT_LIMIT_SIZE.'"></td>'; print '<td class="right"><input size="3" type="text" class="flat" name="value_PRODUIT_LIMIT_SIZE" value="'.$conf->global->PRODUIT_LIMIT_SIZE.'"></td>';
@ -685,8 +673,7 @@ print '</tr>';
*/ */
// View product description in thirdparty language // View product description in thirdparty language
if (!empty($conf->global->MAIN_MULTILANGS)) if (!empty($conf->global->MAIN_MULTILANGS)) {
{
print '<tr class="oddeven">'; print '<tr class="oddeven">';
print '<td>'.$langs->trans("ViewProductDescInThirdpartyLanguageAbility").'</td>'; print '<td>'.$langs->trans("ViewProductDescInThirdpartyLanguageAbility").'</td>';
print '<td class="right">'; print '<td class="right">';
@ -695,8 +682,7 @@ if (!empty($conf->global->MAIN_MULTILANGS))
print '</tr>'; print '</tr>';
} }
if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) {
{
print '<tr class="oddeven">'; print '<tr class="oddeven">';
print '<td>'.$langs->trans("UseProductFournDesc").'</td>'; print '<td>'.$langs->trans("UseProductFournDesc").'</td>';
print '<td class="right">'; print '<td class="right">';
@ -713,8 +699,7 @@ if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUP
} }
if (!empty($conf->global->PRODUCT_CANVAS_ABILITY)) if (!empty($conf->global->PRODUCT_CANVAS_ABILITY)) {
{
// Add canvas feature // Add canvas feature
$dir = DOL_DOCUMENT_ROOT."/product/canvas/"; $dir = DOL_DOCUMENT_ROOT."/product/canvas/";
@ -723,17 +708,13 @@ if (!empty($conf->global->PRODUCT_CANVAS_ABILITY))
print '<td class="right">'.$langs->trans("Value").'</td>'."\n"; print '<td class="right">'.$langs->trans("Value").'</td>'."\n";
print '</tr>'."\n"; print '</tr>'."\n";
if (is_dir($dir)) if (is_dir($dir)) {
{
require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
$handle = opendir($dir); $handle = opendir($dir);
if (is_resource($handle)) if (is_resource($handle)) {
{ while (($file = readdir($handle)) !== false) {
while (($file = readdir($handle)) !== false) if (file_exists($dir.$file.'/product.'.$file.'.class.php')) {
{
if (file_exists($dir.$file.'/product.'.$file.'.class.php'))
{
$classfile = $dir.$file.'/product.'.$file.'.class.php'; $classfile = $dir.$file.'/product.'.$file.'.class.php';
$classname = 'Product'.ucfirst($file); $classname = 'Product'.ucfirst($file);
@ -742,8 +723,7 @@ if (!empty($conf->global->PRODUCT_CANVAS_ABILITY))
$module = $object->module; $module = $object->module;
if ($conf->$module->enabled) if ($conf->$module->enabled) {
{
print '<tr class="oddeven"><td>'; print '<tr class="oddeven"><td>';
print $object->description; print $object->description;
@ -752,8 +732,7 @@ if (!empty($conf->global->PRODUCT_CANVAS_ABILITY))
$const = "PRODUCT_SPECIAL_".strtoupper($file); $const = "PRODUCT_SPECIAL_".strtoupper($file);
if ($conf->global->$const) if ($conf->global->$const) {
{
print img_picto($langs->trans("Active"), 'tick'); print img_picto($langs->trans("Active"), 'tick');
print '</td><td class="right">'; print '</td><td class="right">';
print '<a href="'.$_SERVER["PHP_SELF"].'?action=set&amp;token='.newToken().'&amp;spe='.urlencode($file).'&amp;value=0">'.$langs->trans("Disable").'</a>'; print '<a href="'.$_SERVER["PHP_SELF"].'?action=set&amp;token='.newToken().'&amp;spe='.urlencode($file).'&amp;value=0">'.$langs->trans("Disable").'</a>';

View File

@ -38,13 +38,17 @@ $form = new Form($db);
// List of supported format // List of supported format
$tmptype2label = ExtraFields::$type2label; $tmptype2label = ExtraFields::$type2label;
$type2label = array(''); $type2label = array('');
foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val); foreach ($tmptype2label as $key => $val) {
$type2label[$key] = $langs->transnoentitiesnoconv($val);
}
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
$attrname = GETPOST('attrname', 'alpha'); $attrname = GETPOST('attrname', 'alpha');
$elementtype = 'product'; //Must be the $element of the class that manage extrafield $elementtype = 'product'; //Must be the $element of the class that manage extrafield
if (!$user->admin) accessforbidden(); if (!$user->admin) {
accessforbidden();
}
/* /*
@ -61,12 +65,10 @@ require DOL_DOCUMENT_ROOT.'/core/actions_extrafields.inc.php';
$title = $langs->trans('ProductServiceSetup'); $title = $langs->trans('ProductServiceSetup');
$textobject = $langs->trans("ProductsAndServices"); $textobject = $langs->trans("ProductsAndServices");
if (empty($conf->product->enabled)) if (empty($conf->product->enabled)) {
{
$title = $langs->trans('ServiceSetup'); $title = $langs->trans('ServiceSetup');
$textobject = $langs->trans('Services'); $textobject = $langs->trans('Services');
} elseif (empty($conf->service->enabled)) } elseif (empty($conf->service->enabled)) {
{
$title = $langs->trans('ProductSetup'); $title = $langs->trans('ProductSetup');
$textobject = $langs->trans('Products'); $textobject = $langs->trans('Products');
} }
@ -90,8 +92,7 @@ print dol_get_fiche_end();
// Buttons // Buttons
if ($action != 'create' && $action != 'edit') if ($action != 'create' && $action != 'edit') {
{
print '<div class="tabsAction">'; print '<div class="tabsAction">';
print "<a class=\"butAction\" href=\"".$_SERVER["PHP_SELF"]."?action=create#newattrib\">".$langs->trans("NewAttribute")."</a>"; print "<a class=\"butAction\" href=\"".$_SERVER["PHP_SELF"]."?action=create#newattrib\">".$langs->trans("NewAttribute")."</a>";
print "</div>"; print "</div>";
@ -104,8 +105,7 @@ if ($action != 'create' && $action != 'edit')
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
if ($action == 'create') if ($action == 'create') {
{
print '<br><div id="newattrib"></div>'; print '<br><div id="newattrib"></div>';
print load_fiche_titre($langs->trans('NewAttribute')); print load_fiche_titre($langs->trans('NewAttribute'));
@ -117,8 +117,7 @@ if ($action == 'create')
/* Edition of an optional field */ /* Edition of an optional field */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
if ($action == 'edit' && !empty($attrname)) if ($action == 'edit' && !empty($attrname)) {
{
print "<br>"; print "<br>";
print load_fiche_titre($langs->trans("FieldEdition", $attrname)); print load_fiche_titre($langs->trans("FieldEdition", $attrname));

View File

@ -38,13 +38,17 @@ $form = new Form($db);
// List of supported format // List of supported format
$tmptype2label = ExtraFields::$type2label; $tmptype2label = ExtraFields::$type2label;
$type2label = array(''); $type2label = array('');
foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val); foreach ($tmptype2label as $key => $val) {
$type2label[$key] = $langs->transnoentitiesnoconv($val);
}
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
$attrname = GETPOST('attrname', 'alpha'); $attrname = GETPOST('attrname', 'alpha');
$elementtype = 'product_lot'; //Must be the $element of the class that manage extrafield $elementtype = 'product_lot'; //Must be the $element of the class that manage extrafield
if (!$user->admin) accessforbidden(); if (!$user->admin) {
accessforbidden();
}
/* /*
@ -81,8 +85,7 @@ print dol_get_fiche_end();
// Buttons // Buttons
if ($action != 'create' && $action != 'edit') if ($action != 'create' && $action != 'edit') {
{
print '<div class="tabsAction">'; print '<div class="tabsAction">';
print "<a class=\"butAction\" href=\"".$_SERVER["PHP_SELF"]."?action=create#newattrib\">".$langs->trans("NewAttribute")."</a>"; print "<a class=\"butAction\" href=\"".$_SERVER["PHP_SELF"]."?action=create#newattrib\">".$langs->trans("NewAttribute")."</a>";
print "</div>"; print "</div>";
@ -95,8 +98,7 @@ if ($action != 'create' && $action != 'edit')
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
if ($action == 'create') if ($action == 'create') {
{
print '<br><div id="newattrib"></div>'; print '<br><div id="newattrib"></div>';
print load_fiche_titre($langs->trans('NewAttribute')); print load_fiche_titre($langs->trans('NewAttribute'));
@ -108,8 +110,7 @@ if ($action == 'create')
/* Edition of an optional field */ /* Edition of an optional field */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
if ($action == 'edit' && !empty($attrname)) if ($action == 'edit' && !empty($attrname)) {
{
print "<br>"; print "<br>";
print load_fiche_titre($langs->trans("FieldEdition", $attrname)); print load_fiche_titre($langs->trans("FieldEdition", $attrname));

View File

@ -39,13 +39,17 @@ $form = new Form($db);
// List of supported format // List of supported format
$tmptype2label = ExtraFields::$type2label; $tmptype2label = ExtraFields::$type2label;
$type2label = array(''); $type2label = array('');
foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val); foreach ($tmptype2label as $key => $val) {
$type2label[$key] = $langs->transnoentitiesnoconv($val);
}
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
$attrname = GETPOST('attrname', 'alpha'); $attrname = GETPOST('attrname', 'alpha');
$elementtype = 'product_fournisseur_price'; //Must be the $element of the class that manage extrafield $elementtype = 'product_fournisseur_price'; //Must be the $element of the class that manage extrafield
if (!$user->admin) accessforbidden(); if (!$user->admin) {
accessforbidden();
}
/* /*
@ -62,12 +66,10 @@ require DOL_DOCUMENT_ROOT.'/core/actions_extrafields.inc.php';
$title = $langs->trans('ProductServiceSetup'); $title = $langs->trans('ProductServiceSetup');
$textobject = $langs->trans("ProductsAndServices"); $textobject = $langs->trans("ProductsAndServices");
if (empty($conf->product->enabled)) if (empty($conf->product->enabled)) {
{
$title = $langs->trans('ServiceSetup'); $title = $langs->trans('ServiceSetup');
$textobject = $langs->trans('Services'); $textobject = $langs->trans('Services');
} elseif (empty($conf->service->enabled)) } elseif (empty($conf->service->enabled)) {
{
$title = $langs->trans('ProductSetup'); $title = $langs->trans('ProductSetup');
$textobject = $langs->trans('Products'); $textobject = $langs->trans('Products');
} }
@ -91,8 +93,7 @@ print dol_get_fiche_end();
// Buttons // Buttons
if ($action != 'create' && $action != 'edit') if ($action != 'create' && $action != 'edit') {
{
print '<div class="tabsAction">'; print '<div class="tabsAction">';
print "<a class=\"butAction\" href=\"".$_SERVER["PHP_SELF"]."?action=create#newattrib\">".$langs->trans("NewAttribute")."</a>"; print "<a class=\"butAction\" href=\"".$_SERVER["PHP_SELF"]."?action=create#newattrib\">".$langs->trans("NewAttribute")."</a>";
print "</div>"; print "</div>";
@ -105,8 +106,7 @@ if ($action != 'create' && $action != 'edit')
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
if ($action == 'create') if ($action == 'create') {
{
print '<br><div id="newattrib"></div>'; print '<br><div id="newattrib"></div>';
print load_fiche_titre($langs->trans('NewAttribute')); print load_fiche_titre($langs->trans('NewAttribute'));
@ -118,8 +118,7 @@ if ($action == 'create')
/* Edition of an optional field */ /* Edition of an optional field */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
if ($action == 'edit' && !empty($attrname)) if ($action == 'edit' && !empty($attrname)) {
{
print "<br>"; print "<br>";
print load_fiche_titre($langs->trans("FieldEdition", $attrname)); print load_fiche_titre($langs->trans("FieldEdition", $attrname));

View File

@ -35,7 +35,9 @@ require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
$langs->loadLangs(array('admin', 'products')); $langs->loadLangs(array('admin', 'products'));
// Security check // Security check
if (!$user->admin) accessforbidden(); if (!$user->admin) {
accessforbidden();
}
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
$oldvatrate = GETPOST('oldvatrate', 'alpha'); $oldvatrate = GETPOST('oldvatrate', 'alpha');
@ -48,19 +50,16 @@ $newvatrate = GETPOST('newvatrate', 'alpha');
* Actions * Actions
*/ */
if ($action == 'convert') if ($action == 'convert') {
{
$error = 0; $error = 0;
if ($oldvatrate == $newvatrate) if ($oldvatrate == $newvatrate) {
{
$langs->load("errors"); $langs->load("errors");
setEventMessages($langs->trans("ErrorNewValueCantMatchOldValue"), null, 'errors'); setEventMessages($langs->trans("ErrorNewValueCantMatchOldValue"), null, 'errors');
$error++; $error++;
} }
if (!$error) if (!$error) {
{
$country_id = $mysoc->country_id; // TODO Allow to choose country into form $country_id = $mysoc->country_id; // TODO Allow to choose country into form
$nbrecordsmodified = 0; $nbrecordsmodified = 0;
@ -69,62 +68,65 @@ if ($action == 'convert')
// Clean vat code old // Clean vat code old
$vat_src_code_old = ''; $vat_src_code_old = '';
if (preg_match('/\((.*)\)/', $oldvatrate, $reg)) if (preg_match('/\((.*)\)/', $oldvatrate, $reg)) {
{
$vat_src_code_old = $reg[1]; $vat_src_code_old = $reg[1];
$oldvatrateclean = preg_replace('/\s*\(.*\)/', '', $oldvatrate); // Remove code into vatrate. $oldvatrateclean = preg_replace('/\s*\(.*\)/', '', $oldvatrate); // Remove code into vatrate.
} else $oldvatrateclean = $oldvatrate; } else {
$oldvatrateclean = $oldvatrate;
}
// Clean vat code new // Clean vat code new
$vat_src_code_new = ''; $vat_src_code_new = '';
if (preg_match('/\((.*)\)/', $newvatrate, $reg)) if (preg_match('/\((.*)\)/', $newvatrate, $reg)) {
{
$vat_src_code_new = $reg[1]; $vat_src_code_new = $reg[1];
$newvatrateclean = preg_replace('/\s*\(.*\)/', '', $newvatrate); // Remove code into vatrate. $newvatrateclean = preg_replace('/\s*\(.*\)/', '', $newvatrate); // Remove code into vatrate.
} else $newvatrateclean = $newvatrate; } else {
$newvatrateclean = $newvatrate;
}
// If country to edit is my country, so we change customer prices // If country to edit is my country, so we change customer prices
if ($country_id == $mysoc->country_id) if ($country_id == $mysoc->country_id) {
{
$sql = 'SELECT rowid'; $sql = 'SELECT rowid';
$sql .= ' FROM '.MAIN_DB_PREFIX.'product'; $sql .= ' FROM '.MAIN_DB_PREFIX.'product';
$sql .= ' WHERE entity IN ('.getEntity('product').')'; $sql .= ' WHERE entity IN ('.getEntity('product').')';
$sql .= " AND tva_tx = '".$db->escape($oldvatrateclean)."'"; $sql .= " AND tva_tx = '".$db->escape($oldvatrateclean)."'";
if ($vat_src_code_old) $sql .= " AND default_vat_code = '".$db->escape($vat_src_code_old)."'"; if ($vat_src_code_old) {
else " AND default_vat_code = IS NULL"; $sql .= " AND default_vat_code = '".$db->escape($vat_src_code_old)."'";
} else {
" AND default_vat_code = IS NULL";
}
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
$i = 0; $i = 0;
while ($i < $num) while ($i < $num) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
$objectstatic = new Product($db); // Object init must be into loop to avoid to get value of previous step $objectstatic = new Product($db); // Object init must be into loop to avoid to get value of previous step
$ret = $objectstatic->fetch($obj->rowid); $ret = $objectstatic->fetch($obj->rowid);
if ($ret > 0) if ($ret > 0) {
{
$ret = 0; $retm = 0; $updatelevel1 = false; $ret = 0; $retm = 0; $updatelevel1 = false;
// Update multiprice // Update multiprice
$listofmulti = array_reverse($objectstatic->multiprices, true); // To finish with level 1 $listofmulti = array_reverse($objectstatic->multiprices, true); // To finish with level 1
foreach ($listofmulti as $level => $multiprices) foreach ($listofmulti as $level => $multiprices) {
{
$price_base_type = $objectstatic->multiprices_base_type[$level]; // Get price_base_type of product/service to keep the same for update $price_base_type = $objectstatic->multiprices_base_type[$level]; // Get price_base_type of product/service to keep the same for update
if (empty($price_base_type)) continue; // Discard not defined price levels if (empty($price_base_type)) {
continue; // Discard not defined price levels
}
if ($price_base_type == 'TTC') if ($price_base_type == 'TTC') {
{
$newprice = price2num($objectstatic->multiprices_ttc[$level], 'MU'); // Second param must be MU (we want a unit price so 'MU'. If unit price was on 4 decimal, we must keep 4 decimals) $newprice = price2num($objectstatic->multiprices_ttc[$level], 'MU'); // Second param must be MU (we want a unit price so 'MU'. If unit price was on 4 decimal, we must keep 4 decimals)
$newminprice = $objectstatic->multiprices_min_ttc[$level]; $newminprice = $objectstatic->multiprices_min_ttc[$level];
} else { } else {
$newprice = price2num($objectstatic->multiprices[$level], 'MU'); // Second param must be MU (we want a unit price so 'MU'. If unit price was on 4 decimal, we must keep 4 decimals) $newprice = price2num($objectstatic->multiprices[$level], 'MU'); // Second param must be MU (we want a unit price so 'MU'. If unit price was on 4 decimal, we must keep 4 decimals)
$newminprice = $objectstatic->multiprices_min[$level]; $newminprice = $objectstatic->multiprices_min[$level];
} }
if ($newminprice > $newprice) $newminprice = $newprice; if ($newminprice > $newprice) {
$newminprice = $newprice;
}
$newvat = str_replace('*', '', $newvatrate); $newvat = str_replace('*', '', $newvatrate);
$localtaxes_type = getLocalTaxesFromRate($newvat, 0, $mysoc, $mysoc); $localtaxes_type = getLocalTaxesFromRate($newvat, 0, $mysoc, $mysoc);
@ -134,45 +136,51 @@ if ($action == 'convert')
//print "$objectstatic->id $newprice, $price_base_type, $newvat, $newminprice, $newlevel, $newnpr<br>\n"; //print "$objectstatic->id $newprice, $price_base_type, $newvat, $newminprice, $newlevel, $newnpr<br>\n";
$retm = $objectstatic->updatePrice($newprice, $price_base_type, $user, $newvatrateclean, $newminprice, $newlevel, $newnpr, 0, 0, $localtaxes_type, $newdefaultvatcode); $retm = $objectstatic->updatePrice($newprice, $price_base_type, $user, $newvatrateclean, $newminprice, $newlevel, $newnpr, 0, 0, $localtaxes_type, $newdefaultvatcode);
if ($retm < 0) if ($retm < 0) {
{
$error++; $error++;
break; break;
} }
if ($newlevel == 1) $updatelevel1 = true; if ($newlevel == 1) {
$updatelevel1 = true;
}
} }
// Update single price // Update single price
$price_base_type = $objectstatic->price_base_type; // Get price_base_type of product/service to keep the same for update $price_base_type = $objectstatic->price_base_type; // Get price_base_type of product/service to keep the same for update
if ($price_base_type == 'TTC') if ($price_base_type == 'TTC') {
{
$newprice = price2num($objectstatic->price_ttc, 'MU'); // Second param must be MU (we want a unit price so 'MU'. If unit price was on 4 decimal, we must keep 4 decimals) $newprice = price2num($objectstatic->price_ttc, 'MU'); // Second param must be MU (we want a unit price so 'MU'. If unit price was on 4 decimal, we must keep 4 decimals)
$newminprice = $objectstatic->price_min_ttc; $newminprice = $objectstatic->price_min_ttc;
} else { } else {
$newprice = price2num($objectstatic->price, 'MU'); // Second param must be MU (we want a unit price so 'MU'. If unit price was on 4 decimal, we must keep 4 decimals) $newprice = price2num($objectstatic->price, 'MU'); // Second param must be MU (we want a unit price so 'MU'. If unit price was on 4 decimal, we must keep 4 decimals)
$newminprice = $objectstatic->price_min; $newminprice = $objectstatic->price_min;
} }
if ($newminprice > $newprice) $newminprice = $newprice; if ($newminprice > $newprice) {
$newminprice = $newprice;
}
$newvat = str_replace('*', '', $newvatrate); $newvat = str_replace('*', '', $newvatrate);
$localtaxes_type = getLocalTaxesFromRate($newvat, 0, $mysoc, $mysoc); $localtaxes_type = getLocalTaxesFromRate($newvat, 0, $mysoc, $mysoc);
$newnpr = $objectstatic->recuperableonly; $newnpr = $objectstatic->recuperableonly;
$newdefaultvatcode = $vat_src_code_new; $newdefaultvatcode = $vat_src_code_new;
$newlevel = 0; $newlevel = 0;
if (!empty($price_base_type) && !$updatelevel1) if (!empty($price_base_type) && !$updatelevel1) {
{
//print "$objectstatic->id $newprice, $price_base_type, $newvat, $newminprice, $newlevel, $newnpr<br>\n"; //print "$objectstatic->id $newprice, $price_base_type, $newvat, $newminprice, $newlevel, $newnpr<br>\n";
$ret = $objectstatic->updatePrice($newprice, $price_base_type, $user, $newvatrateclean, $newminprice, $newlevel, $newnpr, 0, 0, $localtaxes_type, $newdefaultvatcode); $ret = $objectstatic->updatePrice($newprice, $price_base_type, $user, $newvatrateclean, $newminprice, $newlevel, $newnpr, 0, 0, $localtaxes_type, $newdefaultvatcode);
} }
if ($ret < 0 || $retm < 0) $error++; if ($ret < 0 || $retm < 0) {
else $nbrecordsmodified++; $error++;
} else {
$nbrecordsmodified++;
}
} }
unset($objectstatic); unset($objectstatic);
$i++; $i++;
} }
} else dol_print_error($db); } else {
dol_print_error($db);
}
} }
$fourn = new Fournisseur($db); $fourn = new Fournisseur($db);
@ -182,24 +190,24 @@ if ($action == 'convert')
$sql .= ' FROM '.MAIN_DB_PREFIX.'product_fournisseur_price as pfp, '.MAIN_DB_PREFIX.'societe as s'; $sql .= ' FROM '.MAIN_DB_PREFIX.'product_fournisseur_price as pfp, '.MAIN_DB_PREFIX.'societe as s';
$sql .= ' WHERE pfp.fk_soc = s.rowid AND pfp.entity IN ('.getEntity('product').')'; $sql .= ' WHERE pfp.fk_soc = s.rowid AND pfp.entity IN ('.getEntity('product').')';
$sql .= " AND tva_tx = '".$db->escape($oldvatrate)."'"; $sql .= " AND tva_tx = '".$db->escape($oldvatrate)."'";
if ($vat_src_code_old) $sql .= " AND default_vat_code = '".$db->escape($vat_src_code_old)."'"; if ($vat_src_code_old) {
else " AND default_vat_code = IS NULL"; $sql .= " AND default_vat_code = '".$db->escape($vat_src_code_old)."'";
} else {
" AND default_vat_code = IS NULL";
}
$sql .= " AND s.fk_pays = ".((int) $country_id); $sql .= " AND s.fk_pays = ".((int) $country_id);
//print $sql; //print $sql;
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
$i = 0; $i = 0;
while ($i < $num) while ($i < $num) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
$objectstatic2 = new ProductFournisseur($db); // Object init must be into loop to avoid to get value of previous step $objectstatic2 = new ProductFournisseur($db); // Object init must be into loop to avoid to get value of previous step
$ret = $objectstatic2->fetch_product_fournisseur_price($obj->rowid); $ret = $objectstatic2->fetch_product_fournisseur_price($obj->rowid);
if ($ret > 0) if ($ret > 0) {
{
$ret = 0; $retm = 0; $updatelevel1 = false; $ret = 0; $retm = 0; $updatelevel1 = false;
$price_base_type = 'HT'; $price_base_type = 'HT';
@ -226,34 +234,39 @@ if ($action == 'convert')
$newsupplierreputation = $objectstatic2->supplier_reputation; $newsupplierreputation = $objectstatic2->supplier_reputation;
$newlevel = 0; $newlevel = 0;
if (!empty($price_base_type) && !$updatelevel1) if (!empty($price_base_type) && !$updatelevel1) {
{
//print "$objectstatic2->id $newprice, $price_base_type, $newvat, $newminprice, $newlevel, $newnpr<br>\n"; //print "$objectstatic2->id $newprice, $price_base_type, $newvat, $newminprice, $newlevel, $newnpr<br>\n";
$fourn->id = $obj->fk_soc; $fourn->id = $obj->fk_soc;
$ret = $objectstatic2->update_buyprice($obj->qty, $newprice, $user, $price_base_type, $fourn, $obj->fk_availability, $obj->ref_fourn, $newvat, '', $newpercent, 0, $newnpr, $newdeliverydelay, $newsupplierreputation, $localtaxes_type, $newdefaultvatcode); $ret = $objectstatic2->update_buyprice($obj->qty, $newprice, $user, $price_base_type, $fourn, $obj->fk_availability, $obj->ref_fourn, $newvat, '', $newpercent, 0, $newnpr, $newdeliverydelay, $newsupplierreputation, $localtaxes_type, $newdefaultvatcode);
} }
if ($ret < 0 || $retm < 0) $error++; if ($ret < 0 || $retm < 0) {
else $nbrecordsmodified++; $error++;
} else {
$nbrecordsmodified++;
}
} }
unset($objectstatic2); unset($objectstatic2);
$i++; $i++;
} }
} else dol_print_error($db); } else {
dol_print_error($db);
}
if (!$error) if (!$error) {
{
$db->commit(); $db->commit();
} else { } else {
$db->rollback(); $db->rollback();
} }
// Output result // Output result
if (!$error) if (!$error) {
{ if ($nbrecordsmodified > 0) {
if ($nbrecordsmodified > 0) setEventMessages($langs->trans("RecordsModified", $nbrecordsmodified), null, 'mesgs'); setEventMessages($langs->trans("RecordsModified", $nbrecordsmodified), null, 'mesgs');
else setEventMessages($langs->trans("NoRecordFound"), null, 'warnings'); } else {
setEventMessages($langs->trans("NoRecordFound"), null, 'warnings');
}
} else { } else {
setEventMessages($langs->trans("Error"), null, 'errors'); setEventMessages($langs->trans("Error"), null, 'errors');
} }
@ -274,8 +287,7 @@ print load_fiche_titre($title, '', 'title_setup');
print $langs->trans("ProductVatMassChangeDesc").'<br><br>'; print $langs->trans("ProductVatMassChangeDesc").'<br><br>';
if (empty($mysoc->country_code)) if (empty($mysoc->country_code)) {
{
$langs->load("errors"); $langs->load("errors");
$warnpicto = img_error($langs->trans("WarningMandatorySetupNotComplete")); $warnpicto = img_error($langs->trans("WarningMandatorySetupNotComplete"));
print '<br><a href="'.DOL_URL_ROOT.'/admin/company.php?mainmenu=home">'.$warnpicto.' '.$langs->trans("WarningMandatorySetupNotComplete").'</a>'; print '<br><a href="'.DOL_URL_ROOT.'/admin/company.php?mainmenu=home">'.$warnpicto.' '.$langs->trans("WarningMandatorySetupNotComplete").'</a>';

View File

@ -37,13 +37,17 @@ $form = new Form($db);
// List of supported format // List of supported format
$tmptype2label = ExtraFields::$type2label; $tmptype2label = ExtraFields::$type2label;
$type2label = array(''); $type2label = array('');
foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val); foreach ($tmptype2label as $key => $val) {
$type2label[$key] = $langs->transnoentitiesnoconv($val);
}
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
$attrname = GETPOST('attrname', 'alpha'); $attrname = GETPOST('attrname', 'alpha');
$elementtype = 'entrepot'; //Must be the $table_element of the class that manage extrafield $elementtype = 'entrepot'; //Must be the $table_element of the class that manage extrafield
if (!$user->admin) accessforbidden(); if (!$user->admin) {
accessforbidden();
}
/* /*
@ -76,8 +80,7 @@ print dol_get_fiche_end();
// Buttons // Buttons
if ($action != 'create' && $action != 'edit') if ($action != 'create' && $action != 'edit') {
{
print '<div class="tabsAction">'; print '<div class="tabsAction">';
print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=create">'.$langs->trans("NewAttribute").'</a></div>'; print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=create">'.$langs->trans("NewAttribute").'</a></div>';
print "</div>"; print "</div>";
@ -90,8 +93,7 @@ if ($action != 'create' && $action != 'edit')
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
if ($action == 'create') if ($action == 'create') {
{
print "<br>"; print "<br>";
print load_fiche_titre($langs->trans('NewAttribute')); print load_fiche_titre($langs->trans('NewAttribute'));
@ -103,8 +105,7 @@ if ($action == 'create')
/* Edition of an optional field */ /* Edition of an optional field */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
if ($action == 'edit' && !empty($attrname)) if ($action == 'edit' && !empty($attrname)) {
{
print "<br>"; print "<br>";
print load_fiche_titre($langs->trans("FieldEdition", $attrname)); print load_fiche_titre($langs->trans("FieldEdition", $attrname));

View File

@ -36,10 +36,11 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
// Load translation files required by the page // Load translation files required by the page
$langs->load("companies"); $langs->load("companies");
if (GETPOST('actioncode', 'array')) if (GETPOST('actioncode', 'array')) {
{
$actioncode = GETPOST('actioncode', 'array', 3); $actioncode = GETPOST('actioncode', 'array', 3);
if (!count($actioncode)) $actioncode = '0'; if (!count($actioncode)) {
$actioncode = '0';
}
} else { } else {
$actioncode = GETPOST("actioncode", "alpha", 3) ?GETPOST("actioncode", "alpha", 3) : (GETPOST("actioncode") == '0' ? '0' : (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT)); $actioncode = GETPOST("actioncode", "alpha", 3) ?GETPOST("actioncode", "alpha", 3) : (GETPOST("actioncode") == '0' ? '0' : (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT));
} }
@ -48,19 +49,27 @@ $search_agenda_label = GETPOST('search_agenda_label');
// Security check // Security check
$id = GETPOST('id', 'int'); $id = GETPOST('id', 'int');
$ref = GETPOST('ref', 'alpha'); $ref = GETPOST('ref', 'alpha');
if ($user->socid) $id = $user->socid; if ($user->socid) {
$id = $user->socid;
}
$result = restrictedArea($user, 'produit|service', $id, 'product&product'); $result = restrictedArea($user, 'produit|service', $id, 'product&product');
$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST("sortfield", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if (!$sortfield) $sortfield = 'a.datep,a.id'; if (!$sortfield) {
if (!$sortorder) $sortorder = 'DESC,DESC'; $sortfield = 'a.datep,a.id';
}
if (!$sortorder) {
$sortorder = 'DESC,DESC';
}
// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
$hookmanager->initHooks(array('agendathirdparty')); $hookmanager->initHooks(array('agendathirdparty'));
@ -72,20 +81,19 @@ $hookmanager->initHooks(array('agendathirdparty'));
$parameters = array('id'=>$id); $parameters = array('id'=>$id);
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if (empty($reshook)) if (empty($reshook)) {
{
// Cancel // Cancel
if (GETPOST('cancel', 'alpha') && !empty($backtopage)) if (GETPOST('cancel', 'alpha') && !empty($backtopage)) {
{
header("Location: ".$backtopage); header("Location: ".$backtopage);
exit; exit;
} }
// Purge search criteria // Purge search criteria
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
{
$actioncode = ''; $actioncode = '';
$search_agenda_label = ''; $search_agenda_label = '';
} }
@ -101,8 +109,7 @@ $contactstatic = new Contact($db);
$form = new Form($db); $form = new Form($db);
if ($id > 0 || $ref) if ($id > 0 || $ref) {
{
require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
@ -113,12 +120,18 @@ if ($id > 0 || $ref)
$result = $object->fetch($id, $ref); $result = $object->fetch($id, $ref);
$title = $langs->trans("Agenda"); $title = $langs->trans("Agenda");
if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/productnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->name." - ".$title; if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/productnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) {
$title = $object->name." - ".$title;
}
llxHeader('', $title); llxHeader('', $title);
if (!empty($conf->notification->enabled)) $langs->load("mails"); if (!empty($conf->notification->enabled)) {
$langs->load("mails");
}
$type = $langs->trans('Product'); $type = $langs->trans('Product');
if ($object->isService()) $type = $langs->trans('Service'); if ($object->isService()) {
$type = $langs->trans('Service');
}
$head = product_prepare_head($object); $head = product_prepare_head($object);
@ -130,7 +143,9 @@ if ($id > 0 || $ref)
$object->next_prev_filter = " fk_product_type = ".$object->type; $object->next_prev_filter = " fk_product_type = ".$object->type;
$shownav = 1; $shownav = 1;
if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) {
$shownav = 0;
}
dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref');
@ -154,10 +169,11 @@ if ($id > 0 || $ref)
$out = ''; $out = '';
$permok = $user->rights->agenda->myactions->create; $permok = $user->rights->agenda->myactions->create;
if ((!empty($objproduct->id) || !empty($objcon->id)) && $permok) if ((!empty($objproduct->id) || !empty($objcon->id)) && $permok) {
{
//$out.='<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create'; //$out.='<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create';
if (get_class($objproduct) == 'Product') $out .= '&amp;prodid='.$objproduct->id.'&origin=product&originid='.$id; if (get_class($objproduct) == 'Product') {
$out .= '&amp;prodid='.$objproduct->id.'&origin=product&originid='.$id;
}
$out .= (!empty($objcon->id) ? '&amp;contactid='.$objcon->id : '').'&amp;backtopage=1&amp;percentage=-1'; $out .= (!empty($objcon->id) ? '&amp;contactid='.$objcon->id : '').'&amp;backtopage=1&amp;percentage=-1';
//$out.=$langs->trans("AddAnAction").' '; //$out.=$langs->trans("AddAnAction").' ';
//$out.=img_picto($langs->trans("AddAnAction"),'filenew'); //$out.=img_picto($langs->trans("AddAnAction"),'filenew');
@ -170,19 +186,21 @@ if ($id > 0 || $ref)
$morehtmlcenter = ''; $morehtmlcenter = '';
if (!empty($conf->agenda->enabled)) if (!empty($conf->agenda->enabled)) {
{
$linktocreatetimeBtnStatus = !empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create); $linktocreatetimeBtnStatus = !empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create);
$morehtmlcenter = dolGetButtonTitle($langs->trans('AddAction'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/comm/action/card.php?action=create'.$out, '', $linktocreatetimeBtnStatus); $morehtmlcenter = dolGetButtonTitle($langs->trans('AddAction'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/comm/action/card.php?action=create'.$out, '', $linktocreatetimeBtnStatus);
} }
if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) {
{
print '<br>'; print '<br>';
$param = '&id='.$id; $param = '&id='.$id;
if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage; if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit; $param .= '&contextpage='.$contextpage;
}
if ($limit > 0 && $limit != $conf->liste_limit) {
$param .= '&limit='.$limit;
}
print_barre_liste($langs->trans("ActionsOnProduct"), 0, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, '', 0, -1, '', 0, $morehtmlcenter, '', 0, 1, 1); print_barre_liste($langs->trans("ActionsOnProduct"), 0, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, '', 0, -1, '', 0, $morehtmlcenter, '', 0, 1, 1);

View File

@ -23,13 +23,27 @@
* \brief File to return Ajax response on product list request. * \brief File to return Ajax response on product list request.
*/ */
if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', 1); // Disables token renewal if (!defined('NOTOKENRENEWAL')) {
if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); define('NOTOKENRENEWAL', 1); // Disables token renewal
if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); }
if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); if (!defined('NOREQUIREMENU')) {
if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); define('NOREQUIREMENU', '1');
if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); }
if (empty($_GET['keysearch']) && !defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); if (!defined('NOREQUIREHTML')) {
define('NOREQUIREHTML', '1');
}
if (!defined('NOREQUIREAJAX')) {
define('NOREQUIREAJAX', '1');
}
if (!defined('NOREQUIRESOC')) {
define('NOREQUIRESOC', '1');
}
if (!defined('NOCSRFCHECK')) {
define('NOCSRFCHECK', '1');
}
if (empty($_GET['keysearch']) && !defined('NOREQUIREHTML')) {
define('NOREQUIREHTML', '1');
}
require '../../main.inc.php'; require '../../main.inc.php';
@ -58,8 +72,7 @@ $hidepriceinlabel = GETPOST('hidepriceinlabel', 'int');
dol_syslog(join(',', $_GET)); dol_syslog(join(',', $_GET));
// print_r($_GET); // print_r($_GET);
if (!empty($action) && $action == 'fetch' && !empty($id)) if (!empty($action) && $action == 'fetch' && !empty($id)) {
{
// action='fetch' is used to get product information on a product. So when action='fetch', id must be the product id. // action='fetch' is used to get product information on a product. So when action='fetch', id must be the product id.
require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
@ -68,8 +81,7 @@ if (!empty($action) && $action == 'fetch' && !empty($id))
$object = new Product($db); $object = new Product($db);
$ret = $object->fetch($id); $ret = $object->fetch($id);
if ($ret > 0) if ($ret > 0) {
{
$outref = $object->ref; $outref = $object->ref;
$outlabel = $object->label; $outlabel = $object->label;
$outlabel_trans =''; $outlabel_trans ='';
@ -107,8 +119,7 @@ if (!empty($action) && $action == 'fetch' && !empty($id))
} }
// Price by qty // Price by qty
if (!empty($price_by_qty_rowid) && $price_by_qty_rowid >= 1 && (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))) // If we need a particular price related to qty if (!empty($price_by_qty_rowid) && $price_by_qty_rowid >= 1 && (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))) { // If we need a particular price related to qty
{
$sql = "SELECT price, unitprice, quantity, remise_percent"; $sql = "SELECT price, unitprice, quantity, remise_percent";
$sql .= " FROM ".MAIN_DB_PREFIX."product_price_by_qty "; $sql .= " FROM ".MAIN_DB_PREFIX."product_price_by_qty ";
$sql .= " WHERE rowid=".$price_by_qty_rowid.""; $sql .= " WHERE rowid=".$price_by_qty_rowid."";
@ -129,8 +140,7 @@ if (!empty($action) && $action == 'fetch' && !empty($id))
} }
// Multiprice // Multiprice
if (!$found && isset($price_level) && $price_level >= 1 && (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))) // If we need a particular price level (from 1 to 6) if (!$found && isset($price_level) && $price_level >= 1 && (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))) { // If we need a particular price level (from 1 to 6)
{
$sql = "SELECT price, price_ttc, price_base_type, tva_tx"; $sql = "SELECT price, price_ttc, price_base_type, tva_tx";
$sql .= " FROM ".MAIN_DB_PREFIX."product_price "; $sql .= " FROM ".MAIN_DB_PREFIX."product_price ";
$sql .= " WHERE fk_product = '".$id."'"; $sql .= " WHERE fk_product = '".$id."'";
@ -203,8 +213,7 @@ if (!empty($action) && $action == 'fetch' && !empty($id))
top_httphead(); top_httphead();
if (empty($htmlname)) if (empty($htmlname)) {
{
print json_encode(array()); print json_encode(array());
return; return;
} }
@ -214,8 +223,7 @@ if (!empty($action) && $action == 'fetch' && !empty($id))
$idprod = (!empty($match[0]) ? $match[0] : ''); $idprod = (!empty($match[0]) ? $match[0] : '');
if (GETPOST($htmlname, 'alpha') == '' && (!$idprod || !GETPOST($idprod, 'alpha'))) if (GETPOST($htmlname, 'alpha') == '' && (!$idprod || !GETPOST($idprod, 'alpha'))) {
{
print json_encode(array()); print json_encode(array());
return; return;
} }
@ -233,6 +241,7 @@ if (!empty($action) && $action == 'fetch' && !empty($id))
$db->close(); $db->close();
if ($outjson) if ($outjson) {
print json_encode($arrayresult); print json_encode($arrayresult);
} }
}

View File

@ -81,7 +81,9 @@ class ActionsCardProduct
global $form, $formproduct; global $form, $formproduct;
$tmpobject = new Product($this->db); $tmpobject = new Product($this->db);
if (!empty($id) || !empty($ref)) $tmpobject->fetch($id, $ref); if (!empty($id) || !empty($ref)) {
$tmpobject->fetch($id, $ref);
}
$this->object = $tmpobject; $this->object = $tmpobject;
//parent::assign_values($action); //parent::assign_values($action);
@ -113,8 +115,7 @@ class ActionsCardProduct
// Note // Note
$this->tpl['note'] = nl2br($this->note); $this->tpl['note'] = nl2br($this->note);
if ($action == 'create') if ($action == 'create') {
{
// Price // Price
$this->tpl['price'] = $this->price; $this->tpl['price'] = $this->price;
$this->tpl['price_min'] = $this->price_min; $this->tpl['price_min'] = $this->price_min;
@ -124,8 +125,7 @@ class ActionsCardProduct
$this->tpl['tva_tx'] = $form->load_tva("tva_tx", -1, $mysoc, ''); $this->tpl['tva_tx'] = $form->load_tva("tva_tx", -1, $mysoc, '');
} }
if ($action == 'view') if ($action == 'view') {
{
$head = product_prepare_head($this->object); $head = product_prepare_head($this->object);
$this->tpl['showrefnav'] = $form->showrefnav($this->object, 'ref', '', 1, 'ref'); $this->tpl['showrefnav'] = $form->showrefnav($this->object, 'ref', '', 1, 'ref');
@ -152,19 +152,16 @@ class ActionsCardProduct
$this->tpl['note'] = $this->object->note; $this->tpl['note'] = $this->object->note;
$this->tpl['seuil_stock_alerte'] = $this->object->seuil_stock_alerte; $this->tpl['seuil_stock_alerte'] = $this->object->seuil_stock_alerte;
if ($action == 'create') if ($action == 'create') {
{
// Title // Title
$this->tpl['title'] = $langs->trans("NewProduct"); $this->tpl['title'] = $langs->trans("NewProduct");
} }
if ($action == 'edit') if ($action == 'edit') {
{
$this->tpl['title'] = $langs->trans('Modify').' '.$langs->trans('Product').' : '.$this->object->ref; $this->tpl['title'] = $langs->trans('Modify').' '.$langs->trans('Product').' : '.$this->object->ref;
} }
if ($action == 'create' || $action == 'edit') if ($action == 'create' || $action == 'edit') {
{
// Status // Status
$statutarray = array('1' => $langs->trans("OnSell"), '0' => $langs->trans("NotOnSell")); $statutarray = array('1' => $langs->trans("OnSell"), '0' => $langs->trans("NotOnSell"));
$this->tpl['status'] = $form->selectarray('statut', $statutarray, $this->object->status); $this->tpl['status'] = $form->selectarray('statut', $statutarray, $this->object->status);
@ -196,12 +193,10 @@ class ActionsCardProduct
$this->tpl['volume_units'] = $formproduct->selectMeasuringUnits("volume_units", "volume", $this->object->volume_units, 0, 2); $this->tpl['volume_units'] = $formproduct->selectMeasuringUnits("volume_units", "volume", $this->object->volume_units, 0, 2);
} }
if ($action == 'view') if ($action == 'view') {
{
// Photo // Photo
$this->tpl['nblines'] = 4; $this->tpl['nblines'] = 4;
if ($this->object->is_photo_available($conf->product->multidir_output[$this->object->entity])) if ($this->object->is_photo_available($conf->product->multidir_output[$this->object->entity])) {
{
$this->tpl['photos'] = $this->object->show_photos('product', $conf->product->multidir_output[$this->object->entity], 1, 1, 0, 0, 0, 80); $this->tpl['photos'] = $this->object->show_photos('product', $conf->product->multidir_output[$this->object->entity], 1, 1, 0, 0, 0, 80);
} }
@ -209,34 +204,29 @@ class ActionsCardProduct
$this->tpl['finished'] = $this->object->getLibFinished(); $this->tpl['finished'] = $this->object->getLibFinished();
// Weight // Weight
if ($this->object->weight != '') if ($this->object->weight != '') {
{
$this->tpl['weight'] = $this->object->weight." ".measuringUnitString(0, "weight", $this->object->weight_units); $this->tpl['weight'] = $this->object->weight." ".measuringUnitString(0, "weight", $this->object->weight_units);
} }
// Length // Length
if ($this->object->length != '') if ($this->object->length != '') {
{
$this->tpl['length'] = $this->object->length." ".measuringUnitString(0, "size", $this->object->length_units); $this->tpl['length'] = $this->object->length." ".measuringUnitString(0, "size", $this->object->length_units);
} }
// Surface // Surface
if ($this->object->surface != '') if ($this->object->surface != '') {
{
$this->tpl['surface'] = $this->object->surface." ".measuringUnitString(0, "surface", $this->object->surface_units); $this->tpl['surface'] = $this->object->surface." ".measuringUnitString(0, "surface", $this->object->surface_units);
} }
// Volume // Volume
if ($this->object->volume != '') if ($this->object->volume != '') {
{
$this->tpl['volume'] = $this->object->volume." ".measuringUnitString(0, "volume", $this->object->volume_units); $this->tpl['volume'] = $this->object->volume." ".measuringUnitString(0, "volume", $this->object->volume_units);
} }
$this->tpl['fiche_end'] = dol_get_fiche_end(); $this->tpl['fiche_end'] = dol_get_fiche_end();
} }
if ($action == 'list') if ($action == 'list') {
{
$this->LoadListDatas($limit, $offset, $sortfield, $sortorder); $this->LoadListDatas($limit, $offset, $sortfield, $sortorder);
} }
} }
@ -260,13 +250,11 @@ class ActionsCardProduct
$sql .= " ORDER BY rang ASC"; $sql .= " ORDER BY rang ASC";
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{
$num = $this->db->num_rows($resql); $num = $this->db->num_rows($resql);
$i = 0; $i = 0;
while ($i < $num) while ($i < $num) {
{
$fieldlist = array(); $fieldlist = array();
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
@ -315,10 +303,8 @@ class ActionsCardProduct
// Clean parameters // Clean parameters
$sall = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); $sall = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml'));
foreach ($this->field_list as $field) foreach ($this->field_list as $field) {
{ if ($field['enabled']) {
if ($field['enabled'])
{
$fieldname = "s".$field['alias']; $fieldname = "s".$field['alias'];
$$fieldname = GETPOST($fieldname); $$fieldname = GETPOST($fieldname);
} }
@ -330,10 +316,8 @@ class ActionsCardProduct
$sql .= 'p.rowid, p.price_base_type, p.fk_product_type, p.seuil_stock_alerte, p.entity'; $sql .= 'p.rowid, p.price_base_type, p.fk_product_type, p.seuil_stock_alerte, p.entity';
// Fields not requiered // Fields not requiered
foreach ($this->field_list as $field) foreach ($this->field_list as $field) {
{ if ($field['enabled']) {
if ($field['enabled'])
{
$sql .= ", ".$field['name']." as ".$field['alias']; $sql .= ", ".$field['name']." as ".$field['alias'];
} }
} }
@ -341,37 +325,34 @@ class ActionsCardProduct
$sql .= ' FROM '.MAIN_DB_PREFIX.'product as p'; $sql .= ' FROM '.MAIN_DB_PREFIX.'product as p';
$sql .= " WHERE p.entity IN (".getEntity('product').")"; $sql .= " WHERE p.entity IN (".getEntity('product').")";
if ($sall) if ($sall) {
{
$clause = ''; $clause = '';
$sql .= " AND ("; $sql .= " AND (";
foreach ($this->field_list as $field) foreach ($this->field_list as $field) {
{ if ($field['enabled']) {
if ($field['enabled'])
{
$sql .= $clause." ".$field['name']." LIKE '%".$this->db->escape($sall)."%'"; $sql .= $clause." ".$field['name']." LIKE '%".$this->db->escape($sall)."%'";
if ($clause == '') $clause = ' OR'; if ($clause == '') {
$clause = ' OR';
}
} }
} }
$sql .= ")"; $sql .= ")";
} }
// Search fields // Search fields
foreach ($this->field_list as $field) foreach ($this->field_list as $field) {
{ if ($field['enabled']) {
if ($field['enabled'])
{
$fieldname = "s".$field['alias']; $fieldname = "s".$field['alias'];
if (${$fieldname}) $sql .= " AND ".$field['name']." LIKE '%".$this->db->escape(${$fieldname})."%'"; if (${$fieldname}) {
$sql .= " AND ".$field['name']." LIKE '%".$this->db->escape(${$fieldname})."%'";
}
} }
} }
if (isset($_GET["tosell"]) && dol_strlen($_GET["tosell"]) > 0) if (isset($_GET["tosell"]) && dol_strlen($_GET["tosell"]) > 0) {
{
$sql .= " AND p.tosell = ".$this->db->escape($_GET["tosell"]); $sql .= " AND p.tosell = ".$this->db->escape($_GET["tosell"]);
} }
if (isset($_GET["canvas"]) && dol_strlen($_GET["canvas"]) > 0) if (isset($_GET["canvas"]) && dol_strlen($_GET["canvas"]) > 0) {
{
$sql .= " AND p.canvas = '".$this->db->escape($_GET["canvas"])."'"; $sql .= " AND p.canvas = '".$this->db->escape($_GET["canvas"])."'";
} }
$sql .= $this->db->order($sortfield, $sortorder); $sql .= $this->db->order($sortfield, $sortorder);
@ -379,42 +360,45 @@ class ActionsCardProduct
//print $sql; //print $sql;
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{
$num = $this->db->num_rows($resql); $num = $this->db->num_rows($resql);
$i = 0; $i = 0;
while ($i < min($num, $limit)) while ($i < min($num, $limit)) {
{
$datas = array(); $datas = array();
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
$datas["id"] = $obj->rowid; $datas["id"] = $obj->rowid;
foreach ($this->field_list as $field) foreach ($this->field_list as $field) {
{ if ($field['enabled']) {
if ($field['enabled'])
{
$alias = $field['alias']; $alias = $field['alias'];
if ($alias == 'ref') if ($alias == 'ref') {
{
$this->id = $obj->rowid; $this->id = $obj->rowid;
$this->ref = $obj->$alias; $this->ref = $obj->$alias;
$this->type = $obj->fk_product_type; $this->type = $obj->fk_product_type;
$this->entity = $obj->entity; $this->entity = $obj->entity;
$datas[$alias] = $this->getNomUrl(1, '', 24); $datas[$alias] = $this->getNomUrl(1, '', 24);
} elseif ($alias == 'stock') } elseif ($alias == 'stock') {
{
$this->load_stock(); $this->load_stock();
if ($this->stock_reel < $obj->seuil_stock_alerte) $datas[$alias] = $this->stock_reel.' '.img_warning($langs->trans("StockTooLow")); if ($this->stock_reel < $obj->seuil_stock_alerte) {
else $datas[$alias] = $this->stock_reel; $datas[$alias] = $this->stock_reel.' '.img_warning($langs->trans("StockTooLow"));
} elseif ($alias == 'label') $datas[$alias] = dol_trunc($obj->$alias, 40); } else {
elseif (preg_match('/price/i', $alias)) $datas[$alias] = price($obj->$alias); $datas[$alias] = $this->stock_reel;
elseif ($alias == 'datem') $datas[$alias] = dol_print_date($this->db->jdate($obj->$alias), 'day'); }
elseif ($alias == 'status') $datas[$alias] = $this->LibStatut($obj->$alias, 5); } elseif ($alias == 'label') {
else $datas[$alias] = $obj->$alias; $datas[$alias] = dol_trunc($obj->$alias, 40);
} elseif (preg_match('/price/i', $alias)) {
$datas[$alias] = price($obj->$alias);
} elseif ($alias == 'datem') {
$datas[$alias] = dol_print_date($this->db->jdate($obj->$alias), 'day');
} elseif ($alias == 'status') {
$datas[$alias] = $this->LibStatut($obj->$alias, 5);
} else {
$datas[$alias] = $obj->$alias;
}
} }
} }

View File

@ -16,8 +16,7 @@
*/ */
// Protection to avoid direct call of template // Protection to avoid direct call of template
if (empty($conf) || !is_object($conf)) if (empty($conf) || !is_object($conf)) {
{
print "Error, template page can't be called as URL"; print "Error, template page can't be called as URL";
exit; exit;
} }
@ -53,7 +52,9 @@ print dol_get_fiche_head('');
<tr> <tr>
<td class="fieldrequired" width="20%"><?php echo $langs->trans("Ref"); ?></td> <td class="fieldrequired" width="20%"><?php echo $langs->trans("Ref"); ?></td>
<td><input name="ref" size="40" maxlength="32" value="<?php echo $object->ref; ?>"> <td><input name="ref" size="40" maxlength="32" value="<?php echo $object->ref; ?>">
<?php if ($refalreadyexists == 1) echo $langs->trans("RefAlreadyExists"); ?> <?php if ($refalreadyexists == 1) {
echo $langs->trans("RefAlreadyExists");
} ?>
</td></tr> </td></tr>
<tr> <tr>

View File

@ -16,8 +16,7 @@
*/ */
// Protection to avoid direct call of template // Protection to avoid direct call of template
if (empty($conf) || !is_object($conf)) if (empty($conf) || !is_object($conf)) {
{
print "Error, template page can't be called as URL"; print "Error, template page can't be called as URL";
exit; exit;
} }

View File

@ -16,8 +16,7 @@
*/ */
// Protection to avoid direct call of template // Protection to avoid direct call of template
if (empty($conf) || !is_object($conf)) if (empty($conf) || !is_object($conf)) {
{
print "Error, template page can't be called as URL"; print "Error, template page can't be called as URL";
exit; exit;
} }
@ -37,7 +36,9 @@ $linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_value
$object->next_prev_filter = " fk_product_type = ".$object->type; $object->next_prev_filter = " fk_product_type = ".$object->type;
$shownav = 1; $shownav = 1;
if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) {
$shownav = 0;
}
dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref');
?> ?>

View File

@ -80,13 +80,14 @@ class ActionsCardService
global $form, $formproduct; global $form, $formproduct;
$tmpobject = new Product($this->db); $tmpobject = new Product($this->db);
if (!empty($id) || !empty($ref)) $tmpobject->fetch($id, $ref); if (!empty($id) || !empty($ref)) {
$tmpobject->fetch($id, $ref);
}
$this->object = $tmpobject; $this->object = $tmpobject;
//parent::assign_values($action); //parent::assign_values($action);
foreach ($this->object as $key => $value) foreach ($this->object as $key => $value) {
{
$this->tpl[$key] = $value; $this->tpl[$key] = $value;
} }
@ -113,8 +114,7 @@ class ActionsCardService
// Note // Note
$this->tpl['note'] = nl2br($this->note); $this->tpl['note'] = nl2br($this->note);
if ($action == 'create') if ($action == 'create') {
{
// Price // Price
$this->tpl['price'] = $this->price; $this->tpl['price'] = $this->price;
$this->tpl['price_min'] = $this->price_min; $this->tpl['price_min'] = $this->price_min;
@ -124,8 +124,7 @@ class ActionsCardService
$this->tpl['tva_tx'] = $form->load_tva("tva_tx", -1, $mysoc, ''); $this->tpl['tva_tx'] = $form->load_tva("tva_tx", -1, $mysoc, '');
} }
if ($action == 'view') if ($action == 'view') {
{
$head = product_prepare_head($this->object); $head = product_prepare_head($this->object);
$this->tpl['showrefnav'] = $form->showrefnav($this->object, 'ref', '', 1, 'ref'); $this->tpl['showrefnav'] = $form->showrefnav($this->object, 'ref', '', 1, 'ref');
@ -155,19 +154,16 @@ class ActionsCardService
// Duration // Duration
$this->tpl['duration_value'] = $this->object->duration_value; $this->tpl['duration_value'] = $this->object->duration_value;
if ($action == 'create') if ($action == 'create') {
{
// Title // Title
$this->tpl['title'] = $langs->trans("NewService"); $this->tpl['title'] = $langs->trans("NewService");
} }
if ($action == 'edit') if ($action == 'edit') {
{
$this->tpl['title'] = $langs->trans('Modify').' '.$langs->trans('Service').' : '.$this->object->ref; $this->tpl['title'] = $langs->trans('Modify').' '.$langs->trans('Service').' : '.$this->object->ref;
} }
if ($action == 'create' || $action == 'edit') if ($action == 'create' || $action == 'edit') {
{
// Status // Status
$statutarray = array('1' => $langs->trans("OnSell"), '0' => $langs->trans("NotOnSell")); $statutarray = array('1' => $langs->trans("OnSell"), '0' => $langs->trans("NotOnSell"));
$this->tpl['status'] = $form->selectarray('statut', $statutarray, $this->object->status); $this->tpl['status'] = $form->selectarray('statut', $statutarray, $this->object->status);
@ -192,21 +188,17 @@ class ActionsCardService
$this->tpl['duration_unit'] = $duration_unit; $this->tpl['duration_unit'] = $duration_unit;
} }
if ($action == 'view') if ($action == 'view') {
{
// Photo // Photo
$this->tpl['nblines'] = 4; $this->tpl['nblines'] = 4;
if ($this->object->is_photo_available($conf->service->multidir_output[$this->object->entity])) if ($this->object->is_photo_available($conf->service->multidir_output[$this->object->entity])) {
{
$this->tpl['photos'] = $this->object->show_photos('product', $conf->service->multidir_output[$this->object->entity], 1, 1, 0, 0, 0, 80); $this->tpl['photos'] = $this->object->show_photos('product', $conf->service->multidir_output[$this->object->entity], 1, 1, 0, 0, 0, 80);
} }
// Duration // Duration
if ($this->object->duration_value > 1) if ($this->object->duration_value > 1) {
{
$dur = array("h"=>$langs->trans("Hours"), "d"=>$langs->trans("Days"), "w"=>$langs->trans("Weeks"), "m"=>$langs->trans("Months"), "y"=>$langs->trans("Years")); $dur = array("h"=>$langs->trans("Hours"), "d"=>$langs->trans("Days"), "w"=>$langs->trans("Weeks"), "m"=>$langs->trans("Months"), "y"=>$langs->trans("Years"));
} elseif ($this->object->duration_value > 0) } elseif ($this->object->duration_value > 0) {
{
$dur = array("h"=>$langs->trans("Hour"), "d"=>$langs->trans("Day"), "w"=>$langs->trans("Week"), "m"=>$langs->trans("Month"), "y"=>$langs->trans("Year")); $dur = array("h"=>$langs->trans("Hour"), "d"=>$langs->trans("Day"), "w"=>$langs->trans("Week"), "m"=>$langs->trans("Month"), "y"=>$langs->trans("Year"));
} }
$this->tpl['duration_unit'] = $langs->trans($dur[$this->object->duration_unit]); $this->tpl['duration_unit'] = $langs->trans($dur[$this->object->duration_unit]);
@ -214,8 +206,7 @@ class ActionsCardService
$this->tpl['fiche_end'] = dol_get_fiche_end(); $this->tpl['fiche_end'] = dol_get_fiche_end();
} }
if ($action == 'list') if ($action == 'list') {
{
$this->LoadListDatas($limit, $offset, $sortfield, $sortorder); $this->LoadListDatas($limit, $offset, $sortfield, $sortorder);
} }
} }
@ -239,13 +230,11 @@ class ActionsCardService
$sql .= " ORDER BY rang ASC"; $sql .= " ORDER BY rang ASC";
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{
$num = $this->db->num_rows($resql); $num = $this->db->num_rows($resql);
$i = 0; $i = 0;
while ($i < $num) while ($i < $num) {
{
$fieldlist = array(); $fieldlist = array();
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
@ -294,40 +283,43 @@ class ActionsCardService
$sql .= ' p.duration, p.tosell as statut, p.seuil_stock_alerte'; $sql .= ' p.duration, p.tosell as statut, p.seuil_stock_alerte';
$sql .= ' FROM '.MAIN_DB_PREFIX.'product as p'; $sql .= ' FROM '.MAIN_DB_PREFIX.'product as p';
// We'll need this table joined to the select in order to filter by categ // We'll need this table joined to the select in order to filter by categ
if ($search_categ) $sql .= ", ".MAIN_DB_PREFIX."categorie_product as cp"; if ($search_categ) {
if (GETPOST("fourn_id", 'int') > 0) $sql .= ", ".MAIN_DB_PREFIX."categorie_product as cp";
{ }
if (GETPOST("fourn_id", 'int') > 0) {
$fourn_id = GETPOST("fourn_id", 'int'); $fourn_id = GETPOST("fourn_id", 'int');
$sql .= ", ".MAIN_DB_PREFIX."product_fournisseur_price as pfp"; $sql .= ", ".MAIN_DB_PREFIX."product_fournisseur_price as pfp";
} }
$sql .= " WHERE p.entity IN (".getEntity('product').")"; $sql .= " WHERE p.entity IN (".getEntity('product').")";
if ($search_categ) $sql .= " AND p.rowid = cp.fk_product"; // Join for the needed table to filter by categ if ($search_categ) {
if ($sall) $sql .= " AND p.rowid = cp.fk_product"; // Join for the needed table to filter by categ
{ }
if ($sall) {
$sql .= " AND (p.ref LIKE '%".$this->db->escape($sall)."%' OR p.label LIKE '%".$this->db->escape($sall)."%' OR p.description LIKE '%".$this->db->escape($sall)."%' OR p.note LIKE '%".$this->db->escape($sall)."%')"; $sql .= " AND (p.ref LIKE '%".$this->db->escape($sall)."%' OR p.label LIKE '%".$this->db->escape($sall)."%' OR p.description LIKE '%".$this->db->escape($sall)."%' OR p.note LIKE '%".$this->db->escape($sall)."%')";
} }
if ($sref) $sql .= " AND p.ref LIKE '%".$sref."%'"; if ($sref) {
if ($search_barcode) $sql .= " AND p.barcode LIKE '%".$search_barcode."%'"; $sql .= " AND p.ref LIKE '%".$sref."%'";
if ($snom) $sql .= " AND p.label LIKE '%".$this->db->escape($snom)."%'"; }
if (isset($_GET["tosell"]) && dol_strlen($_GET["tosell"]) > 0) if ($search_barcode) {
{ $sql .= " AND p.barcode LIKE '%".$search_barcode."%'";
}
if ($snom) {
$sql .= " AND p.label LIKE '%".$this->db->escape($snom)."%'";
}
if (isset($_GET["tosell"]) && dol_strlen($_GET["tosell"]) > 0) {
$sql .= " AND p.tosell = ".$this->db->escape($_GET["tosell"]); $sql .= " AND p.tosell = ".$this->db->escape($_GET["tosell"]);
} }
if (isset($_GET["canvas"]) && dol_strlen($_GET["canvas"]) > 0) if (isset($_GET["canvas"]) && dol_strlen($_GET["canvas"]) > 0) {
{
$sql .= " AND p.canvas = '".$this->db->escape($_GET["canvas"])."'"; $sql .= " AND p.canvas = '".$this->db->escape($_GET["canvas"])."'";
} }
if ($catid) if ($catid) {
{
$sql .= " AND cp.fk_categorie = ".$catid; $sql .= " AND cp.fk_categorie = ".$catid;
} }
if ($fourn_id > 0) if ($fourn_id > 0) {
{
$sql .= " AND p.rowid = pfp.fk_product AND pfp.fk_soc = ".$fourn_id; $sql .= " AND p.rowid = pfp.fk_product AND pfp.fk_soc = ".$fourn_id;
} }
// Insert categ filter // Insert categ filter
if ($search_categ) if ($search_categ) {
{
$sql .= " AND cp.fk_categorie = ".$this->db->escape($search_categ); $sql .= " AND cp.fk_categorie = ".$this->db->escape($search_categ);
} }
$sql .= $this->db->order($sortfield, $sortorder); $sql .= $this->db->order($sortfield, $sortorder);
@ -336,13 +328,11 @@ class ActionsCardService
$this->list_datas = array(); $this->list_datas = array();
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{
$num = $this->db->num_rows($resql); $num = $this->db->num_rows($resql);
$i = 0; $i = 0;
while ($i < min($num, $limit)) while ($i < min($num, $limit)) {
{
$datas = array(); $datas = array();
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);

View File

@ -16,8 +16,7 @@
*/ */
// Protection to avoid direct call of template // Protection to avoid direct call of template
if (empty($conf) || !is_object($conf)) if (empty($conf) || !is_object($conf)) {
{
print "Error, template page can't be called as URL"; print "Error, template page can't be called as URL";
exit; exit;
} }
@ -50,7 +49,9 @@ print dol_get_fiche_head('');
<tr> <tr>
<td class="fieldrequired" width="20%"><?php echo $langs->trans("Ref"); ?></td> <td class="fieldrequired" width="20%"><?php echo $langs->trans("Ref"); ?></td>
<td><input name="ref" size="40" maxlength="32" value="<?php echo $object->ref; ?>"> <td><input name="ref" size="40" maxlength="32" value="<?php echo $object->ref; ?>">
<?php if ($refalreadyexists == 1) echo $langs->trans("RefAlreadyExists"); ?> <?php if ($refalreadyexists == 1) {
echo $langs->trans("RefAlreadyExists");
} ?>
</td></tr> </td></tr>
<tr> <tr>

View File

@ -16,8 +16,7 @@
*/ */
// Protection to avoid direct call of template // Protection to avoid direct call of template
if (empty($conf) || !is_object($conf)) if (empty($conf) || !is_object($conf)) {
{
print "Error, template page can't be called as URL"; print "Error, template page can't be called as URL";
exit; exit;
} }

View File

@ -16,8 +16,7 @@
*/ */
// Protection to avoid direct call of template // Protection to avoid direct call of template
if (empty($conf) || !is_object($conf)) if (empty($conf) || !is_object($conf)) {
{
print "Error, template page can't be called as URL"; print "Error, template page can't be called as URL";
exit; exit;
} }
@ -37,7 +36,9 @@ $linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_value
$object->next_prev_filter = " fk_product_type = ".$object->type; $object->next_prev_filter = " fk_product_type = ".$object->type;
$shownav = 1; $shownav = 1;
if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) {
$shownav = 0;
}
dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref');
?> ?>

File diff suppressed because it is too large Load Diff

View File

@ -37,7 +37,7 @@ class Products extends DolibarrApi
/** /**
* @var array $FIELDS Mandatory fields, checked when create and update object * @var array $FIELDS Mandatory fields, checked when create and update object
*/ */
static $FIELDS = array( public static $FIELDS = array(
'ref', 'ref',
'label' 'label'
); );
@ -217,8 +217,7 @@ class Products extends DolibarrApi
$num = $this->db->num_rows($result); $num = $this->db->num_rows($result);
$min = min($num, ($limit <= 0 ? $num : $limit)); $min = min($num, ($limit <= 0 ? $num : $limit));
$i = 0; $i = 0;
while ($i < $min) while ($i < $min) {
{
$obj = $this->db->fetch_object($result); $obj = $this->db->fetch_object($result);
$product_static = new Product($this->db); $product_static = new Product($this->db);
if ($product_static->fetch($obj->rowid)) { if ($product_static->fetch($obj->rowid)) {
@ -290,7 +289,8 @@ class Products extends DolibarrApi
$oldproduct = dol_clone($this->product, 0); $oldproduct = dol_clone($this->product, 0);
foreach ($request_data as $field => $value) { foreach ($request_data as $field => $value) {
if ($field == 'id') { continue; if ($field == 'id') {
continue;
} }
if ($field == 'stock_reel') { if ($field == 'stock_reel') {
throw new RestException(400, 'Stock reel cannot be updated here. Use the /stockmovements endpoint instead'); throw new RestException(400, 'Stock reel cannot be updated here. Use the /stockmovements endpoint instead');
@ -309,24 +309,32 @@ class Products extends DolibarrApi
if ($result > 0 && !empty($conf->global->PRODUCT_PRICE_UNIQ)) { if ($result > 0 && !empty($conf->global->PRODUCT_PRICE_UNIQ)) {
// We update price only if it was changed // We update price only if it was changed
$pricemodified = false; $pricemodified = false;
if ($this->product->price_base_type != $oldproduct->price_base_type) { $pricemodified = true; if ($this->product->price_base_type != $oldproduct->price_base_type) {
$pricemodified = true;
} else { } else {
if ($this->product->tva_tx != $oldproduct->tva_tx) { $pricemodified = true; if ($this->product->tva_tx != $oldproduct->tva_tx) {
$pricemodified = true;
} }
if ($this->product->tva_npr != $oldproduct->tva_npr) { $pricemodified = true; if ($this->product->tva_npr != $oldproduct->tva_npr) {
$pricemodified = true;
} }
if ($this->product->default_vat_code != $oldproduct->default_vat_code) { $pricemodified = true; if ($this->product->default_vat_code != $oldproduct->default_vat_code) {
$pricemodified = true;
} }
if ($this->product->price_base_type == 'TTC') { if ($this->product->price_base_type == 'TTC') {
if ($this->product->price_ttc != $oldproduct->price_ttc) { $pricemodified = true; if ($this->product->price_ttc != $oldproduct->price_ttc) {
$pricemodified = true;
} }
if ($this->product->price_min_ttc != $oldproduct->price_min_ttc) { $pricemodified = true; if ($this->product->price_min_ttc != $oldproduct->price_min_ttc) {
$pricemodified = true;
} }
} else { } else {
if ($this->product->price != $oldproduct->price) { $pricemodified = true; if ($this->product->price != $oldproduct->price) {
$pricemodified = true;
} }
if ($this->product->price_min != $oldproduct->price_min) { $pricemodified = true; if ($this->product->price_min != $oldproduct->price_min) {
$pricemodified = true;
} }
} }
} }
@ -586,7 +594,9 @@ class Products extends DolibarrApi
$prodcustprice = new Productcustomerprice($this->db); $prodcustprice = new Productcustomerprice($this->db);
$filter = array(); $filter = array();
$filter['t.fk_product'] .= $id; $filter['t.fk_product'] .= $id;
if ($thirdparty_id) $filter['t.fk_soc'] .= $thirdparty_id; if ($thirdparty_id) {
$filter['t.fk_soc'] .= $thirdparty_id;
}
$result = $prodcustprice->fetch_all('', '', 0, 0, $filter); $result = $prodcustprice->fetch_all('', '', 0, 0, $filter);
} }
@ -805,8 +815,7 @@ class Products extends DolibarrApi
$num = $this->db->num_rows($result); $num = $this->db->num_rows($result);
$min = min($num, ($limit <= 0 ? $num : $limit)); $min = min($num, ($limit <= 0 ? $num : $limit));
$i = 0; $i = 0;
while ($i < $min) while ($i < $min) {
{
$obj = $this->db->fetch_object($result); $obj = $this->db->fetch_object($result);
$product_fourn = new ProductFournisseur($this->db); $product_fourn = new ProductFournisseur($this->db);
@ -1149,7 +1158,8 @@ class Products extends DolibarrApi
} }
foreach ($request_data as $field => $value) { foreach ($request_data as $field => $value) {
if ($field == 'rowid') { continue; if ($field == 'rowid') {
continue;
} }
$prodattr->$field = $value; $prodattr->$field = $value;
} }
@ -1447,7 +1457,8 @@ class Products extends DolibarrApi
} }
foreach ($request_data as $field => $value) { foreach ($request_data as $field => $value) {
if ($field == 'rowid') { continue; if ($field == 'rowid') {
continue;
} }
$objectval->$field = $value; $objectval->$field = $value;
} }
@ -1606,8 +1617,7 @@ class Products extends DolibarrApi
$prodcomb = new ProductCombination($this->db); $prodcomb = new ProductCombination($this->db);
$result = $prodcomb->createProductCombination(DolibarrApiAccess::$user, $this->product, $features, array(), $price_impact_is_percent, $price_impact, $weight_impact, $reference, $ref_ext); $result = $prodcomb->createProductCombination(DolibarrApiAccess::$user, $this->product, $features, array(), $price_impact_is_percent, $price_impact, $weight_impact, $reference, $ref_ext);
if ($result > 0) if ($result > 0) {
{
return $result; return $result;
} else { } else {
throw new RestException(500, "Error creating new product variant"); throw new RestException(500, "Error creating new product variant");
@ -1662,11 +1672,9 @@ class Products extends DolibarrApi
} }
$prodcomb = new ProductCombination($this->db); $prodcomb = new ProductCombination($this->db);
if (!$prodcomb->fetchByProductCombination2ValuePairs($this->product->id, $features)) if (!$prodcomb->fetchByProductCombination2ValuePairs($this->product->id, $features)) {
{
$result = $prodcomb->createProductCombination(DolibarrApiAccess::$user, $this->product, $features, array(), $price_impact_is_percent, $price_impact, $weight_impact); $result = $prodcomb->createProductCombination(DolibarrApiAccess::$user, $this->product, $features, array(), $price_impact_is_percent, $price_impact, $weight_impact);
if ($result > 0) if ($result > 0) {
{
return $result; return $result;
} else { } else {
throw new RestException(500, "Error creating new product variant"); throw new RestException(500, "Error creating new product variant");
@ -1698,14 +1706,14 @@ class Products extends DolibarrApi
$prodcomb->fetch((int) $id); $prodcomb->fetch((int) $id);
foreach ($request_data as $field => $value) { foreach ($request_data as $field => $value) {
if ($field == 'rowid') { continue; if ($field == 'rowid') {
continue;
} }
$prodcomb->$field = $value; $prodcomb->$field = $value;
} }
$result = $prodcomb->update(DolibarrApiAccess::$user); $result = $prodcomb->update(DolibarrApiAccess::$user);
if ($result > 0) if ($result > 0) {
{
return 1; return 1;
} }
throw new RestException(500, "Error editing variant"); throw new RestException(500, "Error editing variant");
@ -1731,8 +1739,7 @@ class Products extends DolibarrApi
$prodcomb = new ProductCombination($this->db); $prodcomb = new ProductCombination($this->db);
$prodcomb->id = (int) $id; $prodcomb->id = (int) $id;
$result = $prodcomb->delete(DolibarrApiAccess::$user); $result = $prodcomb->delete(DolibarrApiAccess::$user);
if ($result <= 0) if ($result <= 0) {
{
throw new RestException(500, "Error deleting variant"); throw new RestException(500, "Error deleting variant");
} }
return $result; return $result;

View File

@ -76,57 +76,54 @@ class FormProduct
{ {
global $conf, $langs; global $conf, $langs;
if (empty($fk_product) && count($this->cache_warehouses)) return 0; // Cache already loaded and we do not want a list with information specific to a product if (empty($fk_product) && count($this->cache_warehouses)) {
return 0; // Cache already loaded and we do not want a list with information specific to a product
}
if (is_array($exclude)) $excludeGroups = implode("','", $exclude); if (is_array($exclude)) {
$excludeGroups = implode("','", $exclude);
}
$warehouseStatus = array(); $warehouseStatus = array();
if (preg_match('/warehouseclosed/', $status)) if (preg_match('/warehouseclosed/', $status)) {
{
$warehouseStatus[] = Entrepot::STATUS_CLOSED; $warehouseStatus[] = Entrepot::STATUS_CLOSED;
} }
if (preg_match('/warehouseopen/', $status)) if (preg_match('/warehouseopen/', $status)) {
{
$warehouseStatus[] = Entrepot::STATUS_OPEN_ALL; $warehouseStatus[] = Entrepot::STATUS_OPEN_ALL;
} }
if (preg_match('/warehouseinternal/', $status)) if (preg_match('/warehouseinternal/', $status)) {
{
$warehouseStatus[] = Entrepot::STATUS_OPEN_INTERNAL; $warehouseStatus[] = Entrepot::STATUS_OPEN_INTERNAL;
} }
$sql = "SELECT e.rowid, e.ref as label, e.description, e.fk_parent"; $sql = "SELECT e.rowid, e.ref as label, e.description, e.fk_parent";
if (!empty($fk_product)) if (!empty($fk_product)) {
{ if (!empty($batch)) {
if (!empty($batch))
{
$sql .= ", pb.qty as stock"; $sql .= ", pb.qty as stock";
} else { } else {
$sql .= ", ps.reel as stock"; $sql .= ", ps.reel as stock";
} }
} elseif ($sumStock) } elseif ($sumStock) {
{
$sql .= ", sum(ps.reel) as stock"; $sql .= ", sum(ps.reel) as stock";
} }
$sql .= " FROM ".MAIN_DB_PREFIX."entrepot as e"; $sql .= " FROM ".MAIN_DB_PREFIX."entrepot as e";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps on ps.fk_entrepot = e.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps on ps.fk_entrepot = e.rowid";
if (!empty($fk_product)) if (!empty($fk_product)) {
{
$sql .= " AND ps.fk_product = ".((int) $fk_product); $sql .= " AND ps.fk_product = ".((int) $fk_product);
if (!empty($batch)) if (!empty($batch)) {
{
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_batch as pb on pb.fk_product_stock = ps.rowid AND pb.batch = '".$this->db->escape($batch)."'"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_batch as pb on pb.fk_product_stock = ps.rowid AND pb.batch = '".$this->db->escape($batch)."'";
} }
} }
$sql .= " WHERE e.entity IN (".getEntity('stock').")"; $sql .= " WHERE e.entity IN (".getEntity('stock').")";
if (count($warehouseStatus)) if (count($warehouseStatus)) {
{
$sql .= " AND e.statut IN (".$this->db->sanitize($this->db->escape(implode(',', $warehouseStatus))).")"; $sql .= " AND e.statut IN (".$this->db->sanitize($this->db->escape(implode(',', $warehouseStatus))).")";
} else { } else {
$sql .= " AND e.statut = 1"; $sql .= " AND e.statut = 1";
} }
if (!empty($exclude)) $sql .= ' AND e.rowid NOT IN('.$this->db->escape(implode(',', $exclude)).')'; if (!empty($exclude)) {
$sql .= ' AND e.rowid NOT IN('.$this->db->escape(implode(',', $exclude)).')';
}
// minimum stock // minimum stock
if ($stockMin !== false) { if ($stockMin !== false) {
@ -151,14 +148,14 @@ class FormProduct
dol_syslog(get_class($this).'::loadWarehouses', LOG_DEBUG); dol_syslog(get_class($this).'::loadWarehouses', LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{
$num = $this->db->num_rows($resql); $num = $this->db->num_rows($resql);
$i = 0; $i = 0;
while ($i < $num) while ($i < $num) {
{
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
if ($sumStock) $obj->stock = price2num($obj->stock, 5); if ($sumStock) {
$obj->stock = price2num($obj->stock, 5);
}
$this->cache_warehouses[$obj->rowid]['id'] = $obj->rowid; $this->cache_warehouses[$obj->rowid]['id'] = $obj->rowid;
$this->cache_warehouses[$obj->rowid]['label'] = $obj->label; $this->cache_warehouses[$obj->rowid]['label'] = $obj->label;
$this->cache_warehouses[$obj->rowid]['parent_id'] = $obj->fk_parent; $this->cache_warehouses[$obj->rowid]['parent_id'] = $obj->fk_parent;
@ -190,10 +187,13 @@ class FormProduct
private function get_parent_path($tab, $final_label = '') private function get_parent_path($tab, $final_label = '')
{ {
//phpcs:enable //phpcs:enable
if (empty($final_label)) $final_label = $tab['label']; if (empty($final_label)) {
$final_label = $tab['label'];
}
if (empty($tab['parent_id'])) return $final_label; if (empty($tab['parent_id'])) {
else { return $final_label;
} else {
if (!empty($this->cache_warehouses[$tab['parent_id']])) { if (!empty($this->cache_warehouses[$tab['parent_id']])) {
$final_label = $this->cache_warehouses[$tab['parent_id']]['label'].' >> '.$final_label; $final_label = $this->cache_warehouses[$tab['parent_id']]['label'].' >> '.$final_label;
return $this->get_parent_path($this->cache_warehouses[$tab['parent_id']], $final_label); return $this->get_parent_path($this->cache_warehouses[$tab['parent_id']], $final_label);
@ -235,14 +235,17 @@ class FormProduct
dol_syslog(get_class($this)."::selectWarehouses $selected, $htmlname, $filterstatus, $empty, $disabled, $fk_product, $empty_label, $showstock, $forcecombo, $morecss", LOG_DEBUG); dol_syslog(get_class($this)."::selectWarehouses $selected, $htmlname, $filterstatus, $empty, $disabled, $fk_product, $empty_label, $showstock, $forcecombo, $morecss", LOG_DEBUG);
$out = ''; $out = '';
if (empty($conf->global->ENTREPOT_EXTRA_STATUS)) $filterstatus = ''; if (empty($conf->global->ENTREPOT_EXTRA_STATUS)) {
if (!empty($fk_product)) $this->cache_warehouses = array(); $filterstatus = '';
}
if (!empty($fk_product)) {
$this->cache_warehouses = array();
}
$this->loadWarehouses($fk_product, '', $filterstatus, true, $exclude, $stockMin, $orderBy); $this->loadWarehouses($fk_product, '', $filterstatus, true, $exclude, $stockMin, $orderBy);
$nbofwarehouses = count($this->cache_warehouses); $nbofwarehouses = count($this->cache_warehouses);
if ($conf->use_javascript_ajax && !$forcecombo) if ($conf->use_javascript_ajax && !$forcecombo) {
{
include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
$comboenhancement = ajax_combobox($htmlname, $events); $comboenhancement = ajax_combobox($htmlname, $events);
$out .= $comboenhancement; $out .= $comboenhancement;
@ -250,22 +253,28 @@ class FormProduct
if (strpos($htmlname, 'search_') !== 0) { if (strpos($htmlname, 'search_') !== 0) {
if (empty($user->fk_warehouse) || $user->fk_warehouse == -1) { if (empty($user->fk_warehouse) || $user->fk_warehouse == -1) {
if (($selected == '-2' || $selected == 'ifone') && !empty($conf->global->MAIN_DEFAULT_WAREHOUSE)) $selected = $conf->global->MAIN_DEFAULT_WAREHOUSE; if (($selected == '-2' || $selected == 'ifone') && !empty($conf->global->MAIN_DEFAULT_WAREHOUSE)) {
$selected = $conf->global->MAIN_DEFAULT_WAREHOUSE;
}
} else {
if (($selected == '-2' || $selected == 'ifone') && !empty($conf->global->MAIN_DEFAULT_WAREHOUSE_USER)) {
$selected = $user->fk_warehouse;
} }
else {
if (($selected == '-2' || $selected == 'ifone') && !empty($conf->global->MAIN_DEFAULT_WAREHOUSE_USER)) $selected = $user->fk_warehouse;
} }
} }
$out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'"'.($disabled ? ' disabled' : '').' id="'.$htmlname.'" name="'.($htmlname.($disabled ? '_disabled' : '')).'">'; $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'"'.($disabled ? ' disabled' : '').' id="'.$htmlname.'" name="'.($htmlname.($disabled ? '_disabled' : '')).'">';
if ($empty) $out .= '<option value="-1">'.($empty_label ? $empty_label : '&nbsp;').'</option>'; if ($empty) {
foreach ($this->cache_warehouses as $id => $arraytypes) $out .= '<option value="-1">'.($empty_label ? $empty_label : '&nbsp;').'</option>';
{ }
foreach ($this->cache_warehouses as $id => $arraytypes) {
$label = ''; $label = '';
if ($showfullpath) $label .= $arraytypes['full_label']; if ($showfullpath) {
else $label .= $arraytypes['label']; $label .= $arraytypes['full_label'];
if (($fk_product || ($showstock > 0)) && ($arraytypes['stock'] != 0 || ($showstock > 0))) } else {
{ $label .= $arraytypes['label'];
}
if (($fk_product || ($showstock > 0)) && ($arraytypes['stock'] != 0 || ($showstock > 0))) {
if ($arraytypes['stock'] <= 0) { if ($arraytypes['stock'] <= 0) {
$label .= ' <span class= \'text-warning\'>('.$langs->trans("Stock").':'.$arraytypes['stock'].')</span>'; $label .= ' <span class= \'text-warning\'>('.$langs->trans("Stock").':'.$arraytypes['stock'].')</span>';
} else { } else {
@ -274,14 +283,18 @@ class FormProduct
} }
$out .= '<option value="'.$id.'"'; $out .= '<option value="'.$id.'"';
if ($selected == $id || ($selected == 'ifone' && $nbofwarehouses == 1)) $out .= ' selected'; if ($selected == $id || ($selected == 'ifone' && $nbofwarehouses == 1)) {
$out .= ' selected';
}
$out .= ' data-html="'.dol_escape_htmltag($label).'"'; $out .= ' data-html="'.dol_escape_htmltag($label).'"';
$out .= '>'; $out .= '>';
$out .= $label; $out .= $label;
$out .= '</option>'; $out .= '</option>';
} }
$out .= '</select>'; $out .= '</select>';
if ($disabled) $out .= '<input type="hidden" name="'.$htmlname.'" value="'.(($selected > 0) ? $selected : '').'">'; if ($disabled) {
$out .= '<input type="hidden" name="'.$htmlname.'" value="'.(($selected > 0) ? $selected : '').'">';
}
$parameters = array( $parameters = array(
'selected' => $selected, 'selected' => $selected,
@ -302,8 +315,11 @@ class FormProduct
); );
$reshook = $hookmanager->executeHooks('selectWarehouses', $parameters, $this); $reshook = $hookmanager->executeHooks('selectWarehouses', $parameters, $this);
if ($reshook > 0) $out = $hookmanager->resPrint; if ($reshook > 0) {
elseif ($reshook == 0) $out .= $hookmanager->resPrint; $out = $hookmanager->resPrint;
} elseif ($reshook == 0) {
$out .= $hookmanager->resPrint;
}
return $out; return $out;
} }
@ -385,7 +401,9 @@ class FormProduct
$filter = array(); $filter = array();
$filter['t.active'] = 1; $filter['t.active'] = 1;
if ($measuring_style) $filter['t.unit_type'] = $measuring_style; if ($measuring_style) {
$filter['t.unit_type'] = $measuring_style;
}
$result = $measuringUnits->fetchAll( $result = $measuringUnits->fetchAll(
'', '',
@ -399,24 +417,33 @@ class FormProduct
return -1; return -1;
} else { } else {
$return .= '<select class="flat" name="'.$name.'">'; $return .= '<select class="flat" name="'.$name.'">';
if ($adddefault || $adddefault === '') if ($adddefault || $adddefault === '') {
{
$return .= '<option value="0">'.($adddefault ? $langs->trans("Default") : '').'</option>'; $return .= '<option value="0">'.($adddefault ? $langs->trans("Default") : '').'</option>';
} }
foreach ($measuringUnits->records as $lines) foreach ($measuringUnits->records as $lines) {
{
$return .= '<option value="'; $return .= '<option value="';
if ($mode == 1) $return .= $lines->short_label; if ($mode == 1) {
elseif ($mode == 2) $return .= $lines->scale; $return .= $lines->short_label;
else $return .= $lines->id; } elseif ($mode == 2) {
$return .= $lines->scale;
} else {
$return .= $lines->id;
}
$return .= '"'; $return .= '"';
if ($mode == 1 && $lines->short_label == $default) $return .= ' selected'; if ($mode == 1 && $lines->short_label == $default) {
elseif ($mode == 2 && $lines->scale == $default) $return .= ' selected'; $return .= ' selected';
elseif ($mode == 0 && $lines->id == $default) $return .= ' selected'; } elseif ($mode == 2 && $lines->scale == $default) {
$return .= ' selected';
} elseif ($mode == 0 && $lines->id == $default) {
$return .= ' selected';
}
$return .= '>'; $return .= '>';
if ($measuring_style == 'time') $return .= $langs->trans(ucfirst($lines->label)); if ($measuring_style == 'time') {
else $return .= $langs->trans($lines->label); $return .= $langs->trans(ucfirst($lines->label));
} else {
$return .= $langs->trans($lines->label);
}
$return .= '</option>'; $return .= '</option>';
} }
$return .= '</select>'; $return .= '</select>';
@ -472,8 +499,11 @@ class FormProduct
if (!empty($productNature->records) && is_array($productNature->records)) { if (!empty($productNature->records) && is_array($productNature->records)) {
foreach ($productNature->records as $lines) { foreach ($productNature->records as $lines) {
$return .= '<option value="'; $return .= '<option value="';
if ($mode == 1) $return .= $lines->label; if ($mode == 1) {
else $return .= $lines->code; $return .= $lines->label;
} else {
$return .= $lines->code;
}
$return .= '"'; $return .= '"';
@ -520,42 +550,41 @@ class FormProduct
$out = ''; $out = '';
$productIdArray = array(); $productIdArray = array();
if (!is_array($objectLines) || !count($objectLines)) if (!is_array($objectLines) || !count($objectLines)) {
{ if (!empty($fk_product)) {
if (!empty($fk_product)) $productIdArray[] = $fk_product; $productIdArray[] = $fk_product;
}
} else { } else {
foreach ($objectLines as $line) { foreach ($objectLines as $line) {
if ($line->fk_product) $productIdArray[] = $line->fk_product; if ($line->fk_product) {
$productIdArray[] = $line->fk_product;
}
} }
} }
$nboflot = $this->loadLotStock($productIdArray); $nboflot = $this->loadLotStock($productIdArray);
if ($conf->use_javascript_ajax && !$forcecombo) if ($conf->use_javascript_ajax && !$forcecombo) {
{
include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
$comboenhancement = ajax_combobox($htmlname, $events); $comboenhancement = ajax_combobox($htmlname, $events);
$out .= $comboenhancement; $out .= $comboenhancement;
} }
$out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'"'.($disabled ? ' disabled' : '').' id="'.$htmlname.'" name="'.($htmlname.($disabled ? '_disabled' : '')).'">'; $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'"'.($disabled ? ' disabled' : '').' id="'.$htmlname.'" name="'.($htmlname.($disabled ? '_disabled' : '')).'">';
if ($empty) $out .= '<option value="-1">'.($empty_label ? $empty_label : '&nbsp;').'</option>'; if ($empty) {
if (!empty($fk_product)) $out .= '<option value="-1">'.($empty_label ? $empty_label : '&nbsp;').'</option>';
{ }
if (!empty($fk_product)) {
$productIdArray = array($fk_product); // only show lot stock for product $productIdArray = array($fk_product); // only show lot stock for product
} else { } else {
foreach ($this->cache_lot as $key => $value) foreach ($this->cache_lot as $key => $value) {
{
$productIdArray[] = $key; $productIdArray[] = $key;
} }
} }
foreach ($productIdArray as $productId) foreach ($productIdArray as $productId) {
{ foreach ($this->cache_lot[$productId] as $id => $arraytypes) {
foreach ($this->cache_lot[$productId] as $id => $arraytypes) if (empty($fk_entrepot) || $fk_entrepot == $arraytypes['entrepot_id']) {
{
if (empty($fk_entrepot) || $fk_entrepot == $arraytypes['entrepot_id'])
{
$label = $arraytypes['entrepot_label'].' - '; $label = $arraytypes['entrepot_label'].' - ';
$label .= $arraytypes['batch']; $label .= $arraytypes['batch'];
if ($arraytypes['qty'] <= 0) { if ($arraytypes['qty'] <= 0) {
@ -565,7 +594,9 @@ class FormProduct
} }
$out .= '<option value="'.$id.'"'; $out .= '<option value="'.$id.'"';
if ($selected == $id || ($selected == 'ifone' && $nboflot == 1)) $out .= ' selected'; if ($selected == $id || ($selected == 'ifone' && $nboflot == 1)) {
$out .= ' selected';
}
$out .= ' data-html="'.dol_escape_htmltag($label).'"'; $out .= ' data-html="'.dol_escape_htmltag($label).'"';
$out .= '>'; $out .= '>';
$out .= $label; $out .= $label;
@ -574,7 +605,9 @@ class FormProduct
} }
} }
$out .= '</select>'; $out .= '</select>';
if ($disabled) $out .= '<input type="hidden" name="'.$htmlname.'" value="'.(($selected > 0) ? $selected : '').'">'; if ($disabled) {
$out .= '<input type="hidden" name="'.$htmlname.'" value="'.(($selected > 0) ? $selected : '').'">';
}
return $out; return $out;
} }
@ -591,22 +624,18 @@ class FormProduct
global $conf, $langs; global $conf, $langs;
$cacheLoaded = false; $cacheLoaded = false;
if (empty($productIdArray)) if (empty($productIdArray)) {
{
// only Load lot stock for given products // only Load lot stock for given products
$this->cache_lot = array(); $this->cache_lot = array();
return 0; return 0;
} }
if (count($productIdArray) && count($this->cache_lot)) if (count($productIdArray) && count($this->cache_lot)) {
{
// check cache already loaded for product id's // check cache already loaded for product id's
foreach ($productIdArray as $productId) foreach ($productIdArray as $productId) {
{
$cacheLoaded = !empty($this->cache_lot[$productId]) ? true : false; $cacheLoaded = !empty($this->cache_lot[$productId]) ? true : false;
} }
} }
if ($cacheLoaded) if ($cacheLoaded) {
{
return count($this->cache_lot); return count($this->cache_lot);
} else { } else {
// clear cache // clear cache
@ -616,20 +645,17 @@ class FormProduct
$sql .= " FROM ".MAIN_DB_PREFIX."product_batch as pb"; $sql .= " FROM ".MAIN_DB_PREFIX."product_batch as pb";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps on ps.rowid = pb.fk_product_stock"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps on ps.rowid = pb.fk_product_stock";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."entrepot as e on e.rowid = ps.fk_entrepot AND e.entity IN (".getEntity('stock').")"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."entrepot as e on e.rowid = ps.fk_entrepot AND e.entity IN (".getEntity('stock').")";
if (!empty($productIdList)) if (!empty($productIdList)) {
{
$sql .= " WHERE ps.fk_product IN (".$productIdList.")"; $sql .= " WHERE ps.fk_product IN (".$productIdList.")";
} }
$sql .= " ORDER BY e.ref, pb.batch"; $sql .= " ORDER BY e.ref, pb.batch";
dol_syslog(get_class($this).'::loadLotStock', LOG_DEBUG); dol_syslog(get_class($this).'::loadLotStock', LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{
$num = $this->db->num_rows($resql); $num = $this->db->num_rows($resql);
$i = 0; $i = 0;
while ($i < $num) while ($i < $num) {
{
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
$this->cache_lot[$obj->fk_product][$obj->rowid]['id'] = $obj->rowid; $this->cache_lot[$obj->fk_product][$obj->rowid]['id'] = $obj->rowid;
$this->cache_lot[$obj->fk_product][$obj->rowid]['batch'] = $obj->batch; $this->cache_lot[$obj->fk_product][$obj->rowid]['batch'] = $obj->batch;

View File

@ -588,8 +588,7 @@ class Product extends CommonObject
if (empty($this->ref) || $this->ref == 'auto') { if (empty($this->ref) || $this->ref == 'auto') {
// Load object modCodeProduct // Load object modCodeProduct
$module = (!empty($conf->global->PRODUCT_CODEPRODUCT_ADDON) ? $conf->global->PRODUCT_CODEPRODUCT_ADDON : 'mod_codeproduct_leopard'); $module = (!empty($conf->global->PRODUCT_CODEPRODUCT_ADDON) ? $conf->global->PRODUCT_CODEPRODUCT_ADDON : 'mod_codeproduct_leopard');
if ($module != 'mod_codeproduct_leopard') // Do not load module file for leopard if ($module != 'mod_codeproduct_leopard') { // Do not load module file for leopard
{
if (substr($module, 0, 16) == 'mod_codeproduct_' && substr($module, -3) == 'php') { if (substr($module, 0, 16) == 'mod_codeproduct_' && substr($module, -3) == 'php') {
$module = substr($module, 0, dol_strlen($module) - 4); $module = substr($module, 0, dol_strlen($module) - 4);
} }
@ -728,7 +727,8 @@ class Product extends CommonObject
if (!$error && !$notrigger) { if (!$error && !$notrigger) {
// Call trigger // Call trigger
$result = $this->call_trigger('PRODUCT_CREATE', $user); $result = $this->call_trigger('PRODUCT_CREATE', $user);
if ($result < 0) { $error++; if ($result < 0) {
$error++;
} }
// End call triggers // End call triggers
} }
@ -802,10 +802,10 @@ class Product extends CommonObject
$module = strtolower($conf->global->BARCODE_PRODUCT_ADDON_NUM); $module = strtolower($conf->global->BARCODE_PRODUCT_ADDON_NUM);
$dirsociete = array_merge(array('/core/modules/barcode/'), $conf->modules_parts['barcode']); $dirsociete = array_merge(array('/core/modules/barcode/'), $conf->modules_parts['barcode']);
foreach ($dirsociete as $dirroot) foreach ($dirsociete as $dirroot) {
{
$res = dol_include_once($dirroot.$module.'.php'); $res = dol_include_once($dirroot.$module.'.php');
if ($res) { break; if ($res) {
break;
} }
} }
@ -947,16 +947,16 @@ class Product extends CommonObject
if ($this->hasbatch() && !$this->oldcopy->hasbatch()) { if ($this->hasbatch() && !$this->oldcopy->hasbatch()) {
//$valueforundefinedlot = 'Undefined'; // In previous version, 39 and lower //$valueforundefinedlot = 'Undefined'; // In previous version, 39 and lower
$valueforundefinedlot = '000000'; $valueforundefinedlot = '000000';
if (!empty($conf->global->STOCK_DEFAULT_BATCH)) $valueforundefinedlot = $conf->global->STOCK_DEFAULT_BATCH; if (!empty($conf->global->STOCK_DEFAULT_BATCH)) {
$valueforundefinedlot = $conf->global->STOCK_DEFAULT_BATCH;
}
dol_syslog("Flag batch of product id=".$this->id." is set to ON, so we will create missing records into product_batch"); dol_syslog("Flag batch of product id=".$this->id." is set to ON, so we will create missing records into product_batch");
$this->load_stock(); $this->load_stock();
foreach ($this->stock_warehouse as $idW => $ObjW) // For each warehouse where we have stocks defined for this product (for each lines in product_stock) foreach ($this->stock_warehouse as $idW => $ObjW) { // For each warehouse where we have stocks defined for this product (for each lines in product_stock)
{
$qty_batch = 0; $qty_batch = 0;
foreach ($ObjW->detail_batch as $detail) // Each lines of detail in product_batch of the current $ObjW = product_stock foreach ($ObjW->detail_batch as $detail) { // Each lines of detail in product_batch of the current $ObjW = product_stock
{
if ($detail->batch == $valueforundefinedlot || $detail->batch == 'Undefined') { if ($detail->batch == $valueforundefinedlot || $detail->batch == 'Undefined') {
// We discard this line, we will create it later // We discard this line, we will create it later
$sqlclean = "DELETE FROM ".MAIN_DB_PREFIX."product_batch WHERE batch in('Undefined', '".$this->db->escape($valueforundefinedlot)."') AND fk_product_stock = ".$ObjW->id; $sqlclean = "DELETE FROM ".MAIN_DB_PREFIX."product_batch WHERE batch in('Undefined', '".$this->db->escape($valueforundefinedlot)."') AND fk_product_stock = ".$ObjW->id;
@ -987,7 +987,8 @@ class Product extends CommonObject
} }
// For automatic creation // For automatic creation
if ($this->barcode == -1) { $this->barcode = $this->get_barcode($this, $this->barcode_type_code); if ($this->barcode == -1) {
$this->barcode = $this->get_barcode($this, $this->barcode_type_code);
} }
$sql = "UPDATE ".MAIN_DB_PREFIX."product"; $sql = "UPDATE ".MAIN_DB_PREFIX."product";
@ -1201,8 +1202,7 @@ class Product extends CommonObject
// Delete all child tables // Delete all child tables
if (!$error) { if (!$error) {
$elements = array('product_fournisseur_price', 'product_price', 'product_lang', 'categorie_product', 'product_stock', 'product_customer_price', 'product_lot'); // product_batch is done before $elements = array('product_fournisseur_price', 'product_price', 'product_lang', 'categorie_product', 'product_stock', 'product_customer_price', 'product_lot'); // product_batch is done before
foreach ($elements as $table) foreach ($elements as $table) {
{
if (!$error) { if (!$error) {
$sql = "DELETE FROM ".MAIN_DB_PREFIX.$table; $sql = "DELETE FROM ".MAIN_DB_PREFIX.$table;
$sql .= " WHERE fk_product = ".(int) $this->id; $sql .= " WHERE fk_product = ".(int) $this->id;
@ -1287,8 +1287,7 @@ class Product extends CommonObject
$this->db->commit(); $this->db->commit();
return 1; return 1;
} else { } else {
foreach ($this->errors as $errmsg) foreach ($this->errors as $errmsg) {
{
dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
$this->error .= ($this->error ? ', '.$errmsg : $errmsg); $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
} }
@ -1314,8 +1313,7 @@ class Product extends CommonObject
$langs_available = $langs->get_available_languages(DOL_DOCUMENT_ROOT, 0, 2); $langs_available = $langs->get_available_languages(DOL_DOCUMENT_ROOT, 0, 2);
$current_lang = $langs->getDefaultLang(); $current_lang = $langs->getDefaultLang();
foreach ($langs_available as $key => $value) foreach ($langs_available as $key => $value) {
{
if ($key == $current_lang) { if ($key == $current_lang) {
$sql = "SELECT rowid"; $sql = "SELECT rowid";
$sql .= " FROM ".MAIN_DB_PREFIX."product_lang"; $sql .= " FROM ".MAIN_DB_PREFIX."product_lang";
@ -1324,18 +1322,19 @@ class Product extends CommonObject
$result = $this->db->query($sql); $result = $this->db->query($sql);
if ($this->db->num_rows($result)) // if there is already a description line for this language if ($this->db->num_rows($result)) { // if there is already a description line for this language
{
$sql2 = "UPDATE ".MAIN_DB_PREFIX."product_lang"; $sql2 = "UPDATE ".MAIN_DB_PREFIX."product_lang";
$sql2 .= " SET "; $sql2 .= " SET ";
$sql2 .= " label='".$this->db->escape($this->label)."',"; $sql2 .= " label='".$this->db->escape($this->label)."',";
$sql2 .= " description='".$this->db->escape($this->description)."'"; $sql2 .= " description='".$this->db->escape($this->description)."'";
if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) { $sql2 .= ", note='".$this->db->escape($this->other)."'"; if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
$sql2 .= ", note='".$this->db->escape($this->other)."'";
} }
$sql2 .= " WHERE fk_product=".$this->id." AND lang='".$this->db->escape($key)."'"; $sql2 .= " WHERE fk_product=".$this->id." AND lang='".$this->db->escape($key)."'";
} else { } else {
$sql2 = "INSERT INTO ".MAIN_DB_PREFIX."product_lang (fk_product, lang, label, description"; $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."product_lang (fk_product, lang, label, description";
if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) { $sql2 .= ", note"; if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
$sql2 .= ", note";
} }
$sql2 .= ")"; $sql2 .= ")";
$sql2 .= " VALUES(".$this->id.",'".$this->db->escape($key)."','".$this->db->escape($this->label)."',"; $sql2 .= " VALUES(".$this->id.",'".$this->db->escape($key)."','".$this->db->escape($this->label)."',";
@ -1358,8 +1357,7 @@ class Product extends CommonObject
$result = $this->db->query($sql); $result = $this->db->query($sql);
if ($this->db->num_rows($result)) // if there is already a description line for this language if ($this->db->num_rows($result)) { // if there is already a description line for this language
{
$sql2 = "UPDATE ".MAIN_DB_PREFIX."product_lang"; $sql2 = "UPDATE ".MAIN_DB_PREFIX."product_lang";
$sql2 .= " SET "; $sql2 .= " SET ";
$sql2 .= " label='".$this->db->escape($this->multilangs["$key"]["label"])."',"; $sql2 .= " label='".$this->db->escape($this->multilangs["$key"]["label"])."',";
@ -1370,7 +1368,8 @@ class Product extends CommonObject
$sql2 .= " WHERE fk_product=".$this->id." AND lang='".$this->db->escape($key)."'"; $sql2 .= " WHERE fk_product=".$this->id." AND lang='".$this->db->escape($key)."'";
} else { } else {
$sql2 = "INSERT INTO ".MAIN_DB_PREFIX."product_lang (fk_product, lang, label, description"; $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."product_lang (fk_product, lang, label, description";
if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) { $sql2 .= ", note"; if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
$sql2 .= ", note";
} }
$sql2 .= ")"; $sql2 .= ")";
$sql2 .= " VALUES(".$this->id.",'".$this->db->escape($key)."','".$this->db->escape($this->multilangs["$key"]["label"])."',"; $sql2 .= " VALUES(".$this->id.",'".$this->db->escape($key)."','".$this->db->escape($this->multilangs["$key"]["label"])."',";
@ -1478,7 +1477,9 @@ class Product extends CommonObject
if ($resql) { if ($resql) {
// Call trigger // Call trigger
$result = $this->call_trigger('PRODUCT_MODIFY', $user); $result = $this->call_trigger('PRODUCT_MODIFY', $user);
if ($result < 0) $error++; if ($result < 0) {
$error++;
}
// End call triggers // End call triggers
if ($error) { if ($error) {
@ -1514,11 +1515,9 @@ class Product extends CommonObject
$result = $this->db->query($sql); $result = $this->db->query($sql);
if ($result) { if ($result) {
while ($obj = $this->db->fetch_object($result)) while ($obj = $this->db->fetch_object($result)) {
{
//print 'lang='.$obj->lang.' current='.$current_lang.'<br>'; //print 'lang='.$obj->lang.' current='.$current_lang.'<br>';
if ($obj->lang == $current_lang) // si on a les traduct. dans la langue courante on les charge en infos principales. if ($obj->lang == $current_lang) { // si on a les traduct. dans la langue courante on les charge en infos principales.
{
$this->label = $obj->label; $this->label = $obj->label;
$this->description = $obj->description; $this->description = $obj->description;
$this->other = $obj->other; $this->other = $obj->other;
@ -1618,7 +1617,9 @@ class Product extends CommonObject
// Update if prices fields are defined // Update if prices fields are defined
$tva_tx = get_default_tva($thirdparty_seller, $thirdparty_buyer, $this->id); $tva_tx = get_default_tva($thirdparty_seller, $thirdparty_buyer, $this->id);
$tva_npr = get_default_npr($thirdparty_seller, $thirdparty_buyer, $this->id); $tva_npr = get_default_npr($thirdparty_seller, $thirdparty_buyer, $this->id);
if (empty($tva_tx)) $tva_npr = 0; if (empty($tva_tx)) {
$tva_npr = 0;
}
$pu_ht = $this->price; $pu_ht = $this->price;
$pu_ttc = $this->price_ttc; $pu_ttc = $this->price_ttc;
@ -1631,11 +1632,16 @@ class Product extends CommonObject
$pu_ttc = $this->multiprices_ttc[$thirdparty_buyer->price_level]; $pu_ttc = $this->multiprices_ttc[$thirdparty_buyer->price_level];
$price_min = $this->multiprices_min[$thirdparty_buyer->price_level]; $price_min = $this->multiprices_min[$thirdparty_buyer->price_level];
$price_base_type = $this->multiprices_base_type[$thirdparty_buyer->price_level]; $price_base_type = $this->multiprices_base_type[$thirdparty_buyer->price_level];
if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) // using this option is a bug. kept for backward compatibility if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) { // using this option is a bug. kept for backward compatibility
{ if (isset($this->multiprices_tva_tx[$thirdparty_buyer->price_level])) {
if (isset($this->multiprices_tva_tx[$thirdparty_buyer->price_level])) $tva_tx = $this->multiprices_tva_tx[$thirdparty_buyer->price_level]; $tva_tx = $this->multiprices_tva_tx[$thirdparty_buyer->price_level];
if (isset($this->multiprices_recuperableonly[$thirdparty_buyer->price_level])) $tva_npr = $this->multiprices_recuperableonly[$thirdparty_buyer->price_level]; }
if (empty($tva_tx)) $tva_npr = 0; if (isset($this->multiprices_recuperableonly[$thirdparty_buyer->price_level])) {
$tva_npr = $this->multiprices_recuperableonly[$thirdparty_buyer->price_level];
}
if (empty($tva_tx)) {
$tva_npr = 0;
}
} }
} elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
// If price per customer // If price per customer
@ -1653,9 +1659,13 @@ class Product extends CommonObject
$pu_ttc = price($prodcustprice->lines[0]->price_ttc); $pu_ttc = price($prodcustprice->lines[0]->price_ttc);
$price_base_type = $prodcustprice->lines[0]->price_base_type; $price_base_type = $prodcustprice->lines[0]->price_base_type;
$tva_tx = $prodcustprice->lines[0]->tva_tx; $tva_tx = $prodcustprice->lines[0]->tva_tx;
if ($prodcustprice->lines[0]->default_vat_code && !preg_match('/\(.*\)/', $tva_tx)) $tva_tx .= ' ('.$prodcustprice->lines[0]->default_vat_code.')'; if ($prodcustprice->lines[0]->default_vat_code && !preg_match('/\(.*\)/', $tva_tx)) {
$tva_tx .= ' ('.$prodcustprice->lines[0]->default_vat_code.')';
}
$tva_npr = $prodcustprice->lines[0]->recuperableonly; $tva_npr = $prodcustprice->lines[0]->recuperableonly;
if (empty($tva_tx)) $tva_npr = 0; if (empty($tva_tx)) {
$tva_npr = 0;
}
} }
} }
} elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) { } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) {
@ -1664,10 +1674,11 @@ class Product extends CommonObject
// yes, this product has some prices per quantity // yes, this product has some prices per quantity
// Search price into product_price_by_qty from $this->id // Search price into product_price_by_qty from $this->id
foreach ($this->prices_by_qty_list[0] as $priceforthequantityarray) { foreach ($this->prices_by_qty_list[0] as $priceforthequantityarray) {
if ($priceforthequantityarray['rowid'] != $pqp) continue; if ($priceforthequantityarray['rowid'] != $pqp) {
continue;
}
// We found the price // We found the price
if ($priceforthequantityarray['price_base_type'] == 'HT') if ($priceforthequantityarray['price_base_type'] == 'HT') {
{
$pu_ht = $priceforthequantityarray['unitprice']; $pu_ht = $priceforthequantityarray['unitprice'];
} else { } else {
$pu_ttc = $priceforthequantityarray['unitprice']; $pu_ttc = $priceforthequantityarray['unitprice'];
@ -1680,12 +1691,12 @@ class Product extends CommonObject
if ($this->prices_by_qty[$thirdparty_buyer->price_level]) { if ($this->prices_by_qty[$thirdparty_buyer->price_level]) {
// yes, this product has some prices per quantity // yes, this product has some prices per quantity
// Search price into product_price_by_qty from $this->id // Search price into product_price_by_qty from $this->id
foreach ($this->prices_by_qty_list[$thirdparty_buyer->price_level] as $priceforthequantityarray) foreach ($this->prices_by_qty_list[$thirdparty_buyer->price_level] as $priceforthequantityarray) {
{ if ($priceforthequantityarray['rowid'] != $pqp) {
if ($priceforthequantityarray['rowid'] != $pqp) continue; continue;
}
// We found the price // We found the price
if ($priceforthequantityarray['price_base_type'] == 'HT') if ($priceforthequantityarray['price_base_type'] == 'HT') {
{
$pu_ht = $priceforthequantityarray['unitprice']; $pu_ht = $priceforthequantityarray['unitprice'];
} else { } else {
$pu_ttc = $priceforthequantityarray['unitprice']; $pu_ttc = $priceforthequantityarray['unitprice'];
@ -1723,10 +1734,13 @@ class Product extends CommonObject
$sql .= " pfp.fk_product, pfp.ref_fourn, pfp.desc_fourn, pfp.fk_soc, pfp.tva_tx, pfp.fk_supplier_price_expression,"; $sql .= " pfp.fk_product, pfp.ref_fourn, pfp.desc_fourn, pfp.fk_soc, pfp.tva_tx, pfp.fk_supplier_price_expression,";
$sql .= " pfp.default_vat_code,"; $sql .= " pfp.default_vat_code,";
$sql .= " pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code"; $sql .= " pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code";
if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) $sql .= ", pfp.packaging"; if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) {
$sql .= ", pfp.packaging";
}
$sql .= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price as pfp"; $sql .= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price as pfp";
$sql .= " WHERE pfp.rowid = ".$prodfournprice; $sql .= " WHERE pfp.rowid = ".$prodfournprice;
if ($qty > 0) { $sql .= " AND pfp.quantity <= ".$qty; if ($qty > 0) {
$sql .= " AND pfp.quantity <= ".$qty;
} }
$sql .= " ORDER BY pfp.quantity DESC"; $sql .= " ORDER BY pfp.quantity DESC";
@ -1734,8 +1748,7 @@ class Product extends CommonObject
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) { if ($resql) {
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
if ($obj && $obj->quantity > 0) // If we found a supplier prices from the id of supplier price if ($obj && $obj->quantity > 0) { // If we found a supplier prices from the id of supplier price
{
if (!empty($conf->dynamicprices->enabled) && !empty($obj->fk_supplier_price_expression)) { if (!empty($conf->dynamicprices->enabled) && !empty($obj->fk_supplier_price_expression)) {
include_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php'; include_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
$prod_supplier = new ProductFournisseur($this->db); $prod_supplier = new ProductFournisseur($this->db);
@ -1766,7 +1779,9 @@ class Product extends CommonObject
$this->fourn_multicurrency_tx = $obj->multicurrency_tx; $this->fourn_multicurrency_tx = $obj->multicurrency_tx;
$this->fourn_multicurrency_id = $obj->fk_multicurrency; $this->fourn_multicurrency_id = $obj->fk_multicurrency;
$this->fourn_multicurrency_code = $obj->multicurrency_code; $this->fourn_multicurrency_code = $obj->multicurrency_code;
if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) $this->packaging = $obj->packaging; if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) {
$this->packaging = $obj->packaging;
}
$result = $obj->fk_product; $result = $obj->fk_product;
return $result; return $result;
} else { // If not found } else { // If not found
@ -1778,11 +1793,14 @@ class Product extends CommonObject
$sql .= " pfp.packaging"; $sql .= " pfp.packaging";
$sql .= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price as pfp"; $sql .= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price as pfp";
$sql .= " WHERE pfp.fk_product = ".$product_id; $sql .= " WHERE pfp.fk_product = ".$product_id;
if ($fourn_ref != 'none') { $sql .= " AND pfp.ref_fourn = '".$this->db->escape($fourn_ref)."'"; if ($fourn_ref != 'none') {
$sql .= " AND pfp.ref_fourn = '".$this->db->escape($fourn_ref)."'";
} }
if ($fk_soc > 0) { $sql .= " AND pfp.fk_soc = ".$fk_soc; if ($fk_soc > 0) {
$sql .= " AND pfp.fk_soc = ".$fk_soc;
} }
if ($qty > 0) { $sql .= " AND pfp.quantity <= ".$qty; if ($qty > 0) {
$sql .= " AND pfp.quantity <= ".$qty;
} }
$sql .= " ORDER BY pfp.quantity DESC"; $sql .= " ORDER BY pfp.quantity DESC";
$sql .= " LIMIT 1"; $sql .= " LIMIT 1";
@ -1791,8 +1809,7 @@ class Product extends CommonObject
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) { if ($resql) {
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
if ($obj && $obj->quantity > 0) // If found if ($obj && $obj->quantity > 0) { // If found
{
if (!empty($conf->dynamicprices->enabled) && !empty($obj->fk_supplier_price_expression)) { if (!empty($conf->dynamicprices->enabled) && !empty($obj->fk_supplier_price_expression)) {
include_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php'; include_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
$prod_supplier = new ProductFournisseur($this->db); $prod_supplier = new ProductFournisseur($this->db);
@ -1824,7 +1841,9 @@ class Product extends CommonObject
$this->fourn_multicurrency_tx = $obj->multicurrency_tx; $this->fourn_multicurrency_tx = $obj->multicurrency_tx;
$this->fourn_multicurrency_id = $obj->fk_multicurrency; $this->fourn_multicurrency_id = $obj->fk_multicurrency;
$this->fourn_multicurrency_code = $obj->multicurrency_code; $this->fourn_multicurrency_code = $obj->multicurrency_code;
if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) $this->packaging = $obj->packaging; if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) {
$this->packaging = $obj->packaging;
}
$result = $obj->fk_product; $result = $obj->fk_product;
return $result; return $result;
} else { } else {
@ -2184,10 +2203,8 @@ class Product extends CommonObject
} }
// Load multiprices array // Load multiprices array
if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($ignore_price_load)) // prices per segment if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($ignore_price_load)) { // prices per segment
{ for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) {
for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++)
{
$sql = "SELECT price, price_ttc, price_min, price_min_ttc,"; $sql = "SELECT price, price_ttc, price_min, price_min_ttc,";
$sql .= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid, recuperableonly"; $sql .= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid, recuperableonly";
$sql .= " FROM ".MAIN_DB_PREFIX."product_price"; $sql .= " FROM ".MAIN_DB_PREFIX."product_price";
@ -2249,11 +2266,9 @@ class Product extends CommonObject
return -1; return -1;
} }
} }
} elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && empty($ignore_price_load)) // prices per customers } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && empty($ignore_price_load)) { // prices per customers
{
// Nothing loaded by default. List may be very long. // Nothing loaded by default. List may be very long.
} elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) && empty($ignore_price_load)) // prices per quantity } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) && empty($ignore_price_load)) { // prices per quantity
{
$sql = "SELECT price, price_ttc, price_min, price_min_ttc,"; $sql = "SELECT price, price_ttc, price_min, price_min_ttc,";
$sql .= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid"; $sql .= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid";
$sql .= " FROM ".MAIN_DB_PREFIX."product_price"; $sql .= " FROM ".MAIN_DB_PREFIX."product_price";
@ -2298,10 +2313,8 @@ class Product extends CommonObject
$this->error = $this->db->lasterror; $this->error = $this->db->lasterror;
return -1; return -1;
} }
} elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES) && empty($ignore_price_load)) // prices per customer and quantity } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES) && empty($ignore_price_load)) { // prices per customer and quantity
{ for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) {
for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++)
{
$sql = "SELECT price, price_ttc, price_min, price_min_ttc,"; $sql = "SELECT price, price_ttc, price_min, price_min_ttc,";
$sql .= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid, recuperableonly"; $sql .= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid, recuperableonly";
$sql .= " FROM ".MAIN_DB_PREFIX."product_price"; $sql .= " FROM ".MAIN_DB_PREFIX."product_price";
@ -2439,7 +2452,9 @@ class Product extends CommonObject
$parameters = array('socid' => $socid); $parameters = array('socid' => $socid);
$reshook = $hookmanager->executeHooks('loadStatsCustomerMO', $parameters, $this, $action); $reshook = $hookmanager->executeHooks('loadStatsCustomerMO', $parameters, $this, $action);
if ($reshook > 0) $this->stats_mo = $hookmanager->resArray['stats_mo']; if ($reshook > 0) {
$this->stats_mo = $hookmanager->resArray['stats_mo'];
}
return 1; return 1;
} }
@ -2506,7 +2521,9 @@ class Product extends CommonObject
$parameters = array('socid' => $socid); $parameters = array('socid' => $socid);
$reshook = $hookmanager->executeHooks('loadStatsCustomerMO', $parameters, $this, $action); $reshook = $hookmanager->executeHooks('loadStatsCustomerMO', $parameters, $this, $action);
if ($reshook > 0) $this->stats_bom = $hookmanager->resArray['stats_bom']; if ($reshook > 0) {
$this->stats_bom = $hookmanager->resArray['stats_bom'];
}
return 1; return 1;
} }
@ -2574,7 +2591,9 @@ class Product extends CommonObject
$parameters = array('socid' => $socid); $parameters = array('socid' => $socid);
$reshook = $hookmanager->executeHooks('loadStatsCustomerProposal', $parameters, $this, $action); $reshook = $hookmanager->executeHooks('loadStatsCustomerProposal', $parameters, $this, $action);
if ($reshook > 0) $this->stats_propale = $hookmanager->resArray['stats_propale']; if ($reshook > 0) {
$this->stats_propale = $hookmanager->resArray['stats_propale'];
}
return 1; return 1;
} else { } else {
@ -2626,7 +2645,9 @@ class Product extends CommonObject
$parameters = array('socid' => $socid); $parameters = array('socid' => $socid);
$reshook = $hookmanager->executeHooks('loadStatsSupplierProposal', $parameters, $this, $action); $reshook = $hookmanager->executeHooks('loadStatsSupplierProposal', $parameters, $this, $action);
if ($reshook > 0) $this->stats_proposal_supplier = $hookmanager->resArray['stats_proposal_supplier']; if ($reshook > 0) {
$this->stats_proposal_supplier = $hookmanager->resArray['stats_proposal_supplier'];
}
return 1; return 1;
} else { } else {
@ -2728,7 +2749,9 @@ class Product extends CommonObject
$parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock); $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock);
$reshook = $hookmanager->executeHooks('loadStatsCustomerOrder', $parameters, $this, $action); $reshook = $hookmanager->executeHooks('loadStatsCustomerOrder', $parameters, $this, $action);
if ($reshook > 0) $this->stats_commande = $hookmanager->resArray['stats_commande']; if ($reshook > 0) {
$this->stats_commande = $hookmanager->resArray['stats_commande'];
}
return 1; return 1;
} else { } else {
$this->error = $this->db->error(); $this->error = $this->db->error();
@ -2782,7 +2805,9 @@ class Product extends CommonObject
$parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock); $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock);
$reshook = $hookmanager->executeHooks('loadStatsSupplierOrder', $parameters, $this, $action); $reshook = $hookmanager->executeHooks('loadStatsSupplierOrder', $parameters, $this, $action);
if ($reshook > 0) $this->stats_commande_fournisseur = $hookmanager->resArray['stats_commande_fournisseur']; if ($reshook > 0) {
$this->stats_commande_fournisseur = $hookmanager->resArray['stats_commande_fournisseur'];
}
return 1; return 1;
} else { } else {
@ -2831,7 +2856,9 @@ class Product extends CommonObject
if ($filtrestatut <> '') { if ($filtrestatut <> '') {
$sql .= " AND c.fk_statut IN (".$this->db->sanitize($filtrestatut).")"; $sql .= " AND c.fk_statut IN (".$this->db->sanitize($filtrestatut).")";
} }
if (!empty($filterShipmentStatus)) $sql .= " AND e.fk_statut IN (".$this->db->sanitize($filterShipmentStatus).")"; if (!empty($filterShipmentStatus)) {
$sql .= " AND e.fk_statut IN (".$this->db->sanitize($filterShipmentStatus).")";
}
$result = $this->db->query($sql); $result = $this->db->query($sql);
if ($result) { if ($result) {
@ -2864,7 +2891,9 @@ class Product extends CommonObject
$parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock, 'filterShipmentStatus' => $filterShipmentStatus); $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock, 'filterShipmentStatus' => $filterShipmentStatus);
$reshook = $hookmanager->executeHooks('loadStatsSending', $parameters, $this, $action); $reshook = $hookmanager->executeHooks('loadStatsSending', $parameters, $this, $action);
if ($reshook > 0) $this->stats_expedition = $hookmanager->resArray['stats_expedition']; if ($reshook > 0) {
$this->stats_expedition = $hookmanager->resArray['stats_expedition'];
}
return 1; return 1;
} else { } else {
@ -2919,7 +2948,9 @@ class Product extends CommonObject
$parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock); $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock);
$reshook = $hookmanager->executeHooks('loadStatsReception', $parameters, $this, $action); $reshook = $hookmanager->executeHooks('loadStatsReception', $parameters, $this, $action);
if ($reshook > 0) $this->stats_reception = $hookmanager->resArray['stats_reception']; if ($reshook > 0) {
$this->stats_reception = $hookmanager->resArray['stats_reception'];
}
return 1; return 1;
} else { } else {
@ -3003,12 +3034,18 @@ class Product extends CommonObject
} }
// Clean data // Clean data
if ($this->stats_mrptoconsume['qty'] < 0) $this->stats_mrptoconsume['qty'] = 0; if ($this->stats_mrptoconsume['qty'] < 0) {
if ($this->stats_mrptoproduce['qty'] < 0) $this->stats_mrptoproduce['qty'] = 0; $this->stats_mrptoconsume['qty'] = 0;
}
if ($this->stats_mrptoproduce['qty'] < 0) {
$this->stats_mrptoproduce['qty'] = 0;
}
$parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock); $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock);
$reshook = $hookmanager->executeHooks('loadStatsInProduction', $parameters, $this, $action); $reshook = $hookmanager->executeHooks('loadStatsInProduction', $parameters, $this, $action);
if ($reshook > 0) $this->stats_mrptoproduce = $hookmanager->resArray['stats_mrptoproduce']; if ($reshook > 0) {
$this->stats_mrptoproduce = $hookmanager->resArray['stats_mrptoproduce'];
}
return 1; return 1;
} else { } else {
@ -3080,7 +3117,9 @@ class Product extends CommonObject
$parameters = array('socid' => $socid); $parameters = array('socid' => $socid);
$reshook = $hookmanager->executeHooks('loadStatsContract', $parameters, $this, $action); $reshook = $hookmanager->executeHooks('loadStatsContract', $parameters, $this, $action);
if ($reshook > 0) $this->stats_contrat = $hookmanager->resArray['stats_contrat']; if ($reshook > 0) {
$this->stats_contrat = $hookmanager->resArray['stats_contrat'];
}
return 1; return 1;
} else { } else {
@ -3152,7 +3191,9 @@ class Product extends CommonObject
$parameters = array('socid' => $socid); $parameters = array('socid' => $socid);
$reshook = $hookmanager->executeHooks('loadStatsCustomerInvoice', $parameters, $this, $action); $reshook = $hookmanager->executeHooks('loadStatsCustomerInvoice', $parameters, $this, $action);
if ($reshook > 0) $this->stats_facture = $hookmanager->resArray['stats_facture']; if ($reshook > 0) {
$this->stats_facture = $hookmanager->resArray['stats_facture'];
}
return 1; return 1;
} else { } else {
@ -3203,7 +3244,9 @@ class Product extends CommonObject
$parameters = array('socid' => $socid); $parameters = array('socid' => $socid);
$reshook = $hookmanager->executeHooks('loadStatsSupplierInvoice', $parameters, $this, $action); $reshook = $hookmanager->executeHooks('loadStatsSupplierInvoice', $parameters, $this, $action);
if ($reshook > 0) $this->stats_facture_fournisseur = $hookmanager->resArray['stats_facture_fournisseur']; if ($reshook > 0) {
$this->stats_facture_fournisseur = $hookmanager->resArray['stats_facture_fournisseur'];
}
return 1; return 1;
} else { } else {
@ -3230,8 +3273,7 @@ class Product extends CommonObject
if ($resql) { if ($resql) {
$num = $this->db->num_rows($resql); $num = $this->db->num_rows($resql);
$i = 0; $i = 0;
while ($i < $num) while ($i < $num) {
{
$arr = $this->db->fetch_array($resql); $arr = $this->db->fetch_array($resql);
$keyfortab = (string) $arr[1]; $keyfortab = (string) $arr[1];
if ($year == -1) { if ($year == -1) {
@ -3262,8 +3304,7 @@ class Product extends CommonObject
$result = array(); $result = array();
for ($j = 0; $j < 12; $j++) for ($j = 0; $j < 12; $j++) {
{
// $ids is 'D', 'N', 'O', 'S', ... (First letter of month in user language) // $ids is 'D', 'N', 'O', 'S', ... (First letter of month in user language)
$idx = ucfirst(dol_trunc(dol_print_date(dol_mktime(12, 0, 0, $month, 1, 1970), "%b"), 1, 'right', 'UTF-8', 1)); $idx = ucfirst(dol_trunc(dol_print_date(dol_mktime(12, 0, 0, $month, 1, 1970), "%b"), 1, 'right', 'UTF-8', 1));
@ -3912,8 +3953,10 @@ class Product extends CommonObject
$sql = "SELECT rowid"; $sql = "SELECT rowid";
$sql .= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price"; $sql .= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price";
$sql .= " WHERE fk_soc = ".$id_fourn; $sql .= " WHERE fk_soc = ".$id_fourn;
if ($ref_fourn) { $sql .= " AND ref_fourn = '".$this->db->escape($ref_fourn)."'"; if ($ref_fourn) {
} else { $sql .= " AND (ref_fourn = '' OR ref_fourn IS NULL)"; $sql .= " AND ref_fourn = '".$this->db->escape($ref_fourn)."'";
} else {
$sql .= " AND (ref_fourn = '' OR ref_fourn IS NULL)";
} }
$sql .= " AND quantity = ".$quantity; $sql .= " AND quantity = ".$quantity;
$sql .= " AND fk_product = ".$this->id; $sql .= " AND fk_product = ".$this->id;
@ -3986,8 +4029,7 @@ class Product extends CommonObject
if ($result) { if ($result) {
$num = $this->db->num_rows($result); $num = $this->db->num_rows($result);
$i = 0; $i = 0;
while ($i < $num) while ($i < $num) {
{
$obj = $this->db->fetch_object($result); $obj = $this->db->fetch_object($result);
$list[$i] = $obj->fk_soc; $list[$i] = $obj->fk_soc;
$i++; $i++;
@ -4177,21 +4219,22 @@ class Product extends CommonObject
$tmpproduct = null; $tmpproduct = null;
//var_dump($prod); //var_dump($prod);
foreach ($prod as $id_product => $desc_pere) // $id_product is 0 (first call starting with root top) or an id of a sub_product foreach ($prod as $id_product => $desc_pere) { // $id_product is 0 (first call starting with root top) or an id of a sub_product
{ if (is_array($desc_pere)) { // If desc_pere is an array, this means it's a child
if (is_array($desc_pere)) // If desc_pere is an array, this means it's a child
{
$id = (!empty($desc_pere[0]) ? $desc_pere[0] : ''); $id = (!empty($desc_pere[0]) ? $desc_pere[0] : '');
$nb = (!empty($desc_pere[1]) ? $desc_pere[1] : ''); $nb = (!empty($desc_pere[1]) ? $desc_pere[1] : '');
$type = (!empty($desc_pere[2]) ? $desc_pere[2] : ''); $type = (!empty($desc_pere[2]) ? $desc_pere[2] : '');
$label = (!empty($desc_pere[3]) ? $desc_pere[3] : ''); $label = (!empty($desc_pere[3]) ? $desc_pere[3] : '');
$incdec = !empty($desc_pere[4]) ? $desc_pere[4] : 0; $incdec = !empty($desc_pere[4]) ? $desc_pere[4] : 0;
if ($multiply < 1) { $multiply = 1; if ($multiply < 1) {
$multiply = 1;
} }
//print "XXX We add id=".$id." - label=".$label." - nb=".$nb." - multiply=".$multiply." fullpath=".$compl_path.$label."\n"; //print "XXX We add id=".$id." - label=".$label." - nb=".$nb." - multiply=".$multiply." fullpath=".$compl_path.$label."\n";
if (is_null($tmpproduct)) $tmpproduct = new Product($this->db); // So we initialize tmpproduct only once for all loop. if (is_null($tmpproduct)) {
$tmpproduct = new Product($this->db); // So we initialize tmpproduct only once for all loop.
}
$tmpproduct->fetch($id); // Load product to get ->ref $tmpproduct->fetch($id); // Load product to get ->ref
$tmpproduct->load_stock('nobatch,novirtual'); // Load stock to get true ->stock_reel $tmpproduct->load_stock('nobatch,novirtual'); // Load stock to get true ->stock_reel
//$this->fetch($id); // Load product to get ->ref //$this->fetch($id); // Load product to get ->ref
@ -4269,7 +4312,9 @@ class Product extends CommonObject
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) { if ($resql) {
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
if ($obj) { $nb = $obj->nb; } if ($obj) {
$nb = $obj->nb;
}
} else { } else {
return -1; return -1;
} }
@ -4291,7 +4336,8 @@ class Product extends CommonObject
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) { if ($resql) {
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
if ($obj) { $nb = $obj->nb; if ($obj) {
$nb = $obj->nb;
} }
} }
@ -4386,17 +4432,18 @@ class Product extends CommonObject
dol_syslog(get_class($this).'::getChildsArbo id='.$id.' level='.$level, LOG_DEBUG); dol_syslog(get_class($this).'::getChildsArbo id='.$id.' level='.$level, LOG_DEBUG);
if ($level == 1) { $alreadyfound = array($id=>1); // We init array of found object to start of tree, so if we found it later (should not happened), we stop immediatly if ($level == 1) {
$alreadyfound = array($id=>1); // We init array of found object to start of tree, so if we found it later (should not happened), we stop immediatly
} }
// Protection against infinite loop // Protection against infinite loop
if ($level > 30) { return array(); if ($level > 30) {
return array();
} }
$res = $this->db->query($sql); $res = $this->db->query($sql);
if ($res) { if ($res) {
$prods = array(); $prods = array();
while ($rec = $this->db->fetch_array($res)) while ($rec = $this->db->fetch_array($res)) {
{
if (!empty($alreadyfound[$rec['rowid']])) { if (!empty($alreadyfound[$rec['rowid']])) {
dol_syslog(get_class($this).'::getChildsArbo the product id='.$rec['rowid'].' was already found at a higher level in tree. We discard to avoid infinite loop', LOG_WARNING); dol_syslog(get_class($this).'::getChildsArbo the product id='.$rec['rowid'].' was already found at a higher level in tree. We discard to avoid infinite loop', LOG_WARNING);
continue; continue;
@ -4414,8 +4461,7 @@ class Product extends CommonObject
//$prods[$this->db->escape($rec['label'])]= array(0=>$rec['id'],1=>$rec['qty']); //$prods[$this->db->escape($rec['label'])]= array(0=>$rec['id'],1=>$rec['qty']);
if (empty($firstlevelonly)) { if (empty($firstlevelonly)) {
$listofchilds = $this->getChildsArbo($rec['rowid'], 0, $level + 1); $listofchilds = $this->getChildsArbo($rec['rowid'], 0, $level + 1);
foreach ($listofchilds as $keyChild => $valueChild) foreach ($listofchilds as $keyChild => $valueChild) {
{
$prods[$rec['rowid']]['childs'][$keyChild] = $valueChild; $prods[$rec['rowid']]['childs'][$keyChild] = $valueChild;
} }
} }
@ -4440,12 +4486,10 @@ class Product extends CommonObject
// phpcs:enable // phpcs:enable
$parent = array(); $parent = array();
foreach ($this->getChildsArbo($this->id) as $keyChild => $valueChild) // Warning. getChildsArbo can call getChildsArbo recursively. Starting point is $value[0]=id of product foreach ($this->getChildsArbo($this->id) as $keyChild => $valueChild) { // Warning. getChildsArbo can call getChildsArbo recursively. Starting point is $value[0]=id of product
{
$parent[$this->label][$keyChild] = $valueChild; $parent[$this->label][$keyChild] = $valueChild;
} }
foreach ($parent as $key => $value) // key=label, value is array of childs foreach ($parent as $key => $value) { // key=label, value is array of childs
{
$this->sousprods[$key] = $value; $this->sousprods[$key] = $value;
} }
} }
@ -4507,8 +4551,7 @@ class Product extends CommonObject
$label .= '<br><b>'.$langs->trans('BarCode').':</b> '.$this->barcode; $label .= '<br><b>'.$langs->trans('BarCode').':</b> '.$this->barcode;
} }
if ($this->type == Product::TYPE_PRODUCT) if ($this->type == Product::TYPE_PRODUCT) {
{
if ($this->weight) { if ($this->weight) {
$label .= "<br><b>".$langs->trans("Weight").'</b>: '.$this->weight.' '.measuringUnitString(0, "weight", $this->weight_units); $label .= "<br><b>".$langs->trans("Weight").'</b>: '.$this->weight.' '.measuringUnitString(0, "weight", $this->weight_units);
} }
@ -4522,7 +4565,9 @@ class Product extends CommonObject
if ($this->height) { if ($this->height) {
$labelsize .= ($labelsize ? " - " : "")."<b>".$langs->trans("Height").'</b>: '.$this->height.' '.measuringUnitString(0, 'size', $this->height_units); $labelsize .= ($labelsize ? " - " : "")."<b>".$langs->trans("Height").'</b>: '.$this->height.' '.measuringUnitString(0, 'size', $this->height_units);
} }
if ($labelsize) $label .= "<br>".$labelsize; if ($labelsize) {
$label .= "<br>".$labelsize;
}
$labelsurfacevolume = ""; $labelsurfacevolume = "";
if ($this->surface) { if ($this->surface) {
@ -4531,7 +4576,9 @@ class Product extends CommonObject
if ($this->volume) { if ($this->volume) {
$labelsurfacevolume .= ($labelsurfacevolume ? " - " : "")."<b>".$langs->trans("Volume").'</b>: '.$this->volume.' '.measuringUnitString(0, 'volume', $this->volume_units); $labelsurfacevolume .= ($labelsurfacevolume ? " - " : "")."<b>".$langs->trans("Volume").'</b>: '.$this->volume.' '.measuringUnitString(0, 'volume', $this->volume_units);
} }
if ($labelsurfacevolume) $label .= "<br>".$labelsurfacevolume; if ($labelsurfacevolume) {
$label .= "<br>".$labelsurfacevolume;
}
} }
if (!empty($conf->accounting->enabled) && $this->status) { if (!empty($conf->accounting->enabled) && $this->status) {
@ -4573,9 +4620,11 @@ class Product extends CommonObject
if ($option !== 'nolink') { if ($option !== 'nolink') {
// Add param to save lastsearch_values or not // Add param to save lastsearch_values or not
$add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) { $add_save_lastsearch_values = 1; if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
$add_save_lastsearch_values = 1;
} }
if ($add_save_lastsearch_values) { $url .= '&save_lastsearch_values=1'; if ($add_save_lastsearch_values) {
$url .= '&save_lastsearch_values=1';
} }
} }
@ -4584,8 +4633,7 @@ class Product extends CommonObject
$linkend = '</a>'; $linkend = '</a>';
$result .= $linkstart; $result .= $linkstart;
if ($withpicto) if ($withpicto) {
{
if ($this->type == Product::TYPE_PRODUCT) { if ($this->type == Product::TYPE_PRODUCT) {
$result .= (img_object(($notooltip ? '' : $label), 'product', ($notooltip ? 'class="paddingright"' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1)); $result .= (img_object(($notooltip ? '' : $label), 'product', ($notooltip ? 'class="paddingright"' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1));
} }
@ -4650,8 +4698,7 @@ class Product extends CommonObject
*/ */
public function getLibStatut($mode = 0, $type = 0) public function getLibStatut($mode = 0, $type = 0)
{ {
switch ($type) switch ($type) {
{
case 0: case 0:
return $this->LibStatut($this->status, $mode, $type); return $this->LibStatut($this->status, $mode, $type);
case 1: case 1:
@ -4681,12 +4728,12 @@ class Product extends CommonObject
$labelStatus = $labelStatusShort = ''; $labelStatus = $labelStatusShort = '';
$langs->load('products'); $langs->load('products');
if (!empty($conf->productbatch->enabled)) { $langs->load("productbatch"); if (!empty($conf->productbatch->enabled)) {
$langs->load("productbatch");
} }
if ($type == 2) { if ($type == 2) {
switch ($mode) switch ($mode) {
{
case 0: case 0:
$label = ($status == 0 ? $langs->trans('ProductStatusNotOnBatch') : ($status == 1 || empty($conf->global->MAIN_ADVANCE_NUMLOT) ? $langs->trans('ProductStatusOnBatch') : $langs->trans('ProductStatusOnSerial'))); $label = ($status == 0 ? $langs->trans('ProductStatusNotOnBatch') : ($status == 1 || empty($conf->global->MAIN_ADVANCE_NUMLOT) ? $langs->trans('ProductStatusOnBatch') : $langs->trans('ProductStatusOnSerial')));
return dolGetStatus($label); return dolGetStatus($label);
@ -4732,9 +4779,7 @@ class Product extends CommonObject
$labelStatus = ($status == 1 || empty($conf->global->MAIN_ADVANCE_NUMLOT) ? $langs->trans('ProductStatusOnBatch') : $langs->trans('ProductStatusOnSerial')); $labelStatus = ($status == 1 || empty($conf->global->MAIN_ADVANCE_NUMLOT) ? $langs->trans('ProductStatusOnBatch') : $langs->trans('ProductStatusOnSerial'));
$labelStatusShort = ($status == 1 || empty($conf->global->MAIN_ADVANCE_NUMLOT) ? $langs->trans('ProductStatusOnBatchShort') : $langs->trans('ProductStatusOnSerialShort')); $labelStatusShort = ($status == 1 || empty($conf->global->MAIN_ADVANCE_NUMLOT) ? $langs->trans('ProductStatusOnBatchShort') : $langs->trans('ProductStatusOnSerialShort'));
} }
} } elseif (! empty($conf->global->MAIN_ADVANCE_NUMLOT) && $type == 2 && $status == 2) {
elseif ( ! empty($conf->global->MAIN_ADVANCE_NUMLOT) && $type == 2 && $status == 2)
{
$labelStatus = $langs->trans('ProductStatusOnSerial'); $labelStatus = $langs->trans('ProductStatusOnSerial');
$labelStatusShort = $langs->trans('ProductStatusOnSerialShort'); $labelStatusShort = $langs->trans('ProductStatusOnSerialShort');
} }
@ -4915,8 +4960,7 @@ class Product extends CommonObject
$num = $this->db->num_rows($result); $num = $this->db->num_rows($result);
$i = 0; $i = 0;
if ($num > 0) { if ($num > 0) {
while ($i < $num) while ($i < $num) {
{
$row = $this->db->fetch_object($result); $row = $this->db->fetch_object($result);
$this->stock_warehouse[$row->fk_entrepot] = new stdClass(); $this->stock_warehouse[$row->fk_entrepot] = new stdClass();
$this->stock_warehouse[$row->fk_entrepot]->real = $row->reel; $this->stock_warehouse[$row->fk_entrepot]->real = $row->reel;
@ -4964,14 +5008,14 @@ class Product extends CommonObject
//dol_syslog("load_virtual_stock"); //dol_syslog("load_virtual_stock");
if (!empty($conf->commande->enabled)) if (!empty($conf->commande->enabled)) {
{
$result = $this->load_stats_commande(0, '1,2', 1); $result = $this->load_stats_commande(0, '1,2', 1);
if ($result < 0) dol_print_error($this->db, $this->error); if ($result < 0) {
dol_print_error($this->db, $this->error);
}
$stock_commande_client = $this->stats_commande['qty']; $stock_commande_client = $this->stats_commande['qty'];
} }
if (!empty($conf->expedition->enabled)) if (!empty($conf->expedition->enabled)) {
{
require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php'; require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
$filterShipmentStatus = ''; $filterShipmentStatus = '';
if (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT)) { if (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT)) {
@ -4980,37 +5024,49 @@ class Product extends CommonObject
$filterShipmentStatus = Expedition::STATUS_CLOSED; $filterShipmentStatus = Expedition::STATUS_CLOSED;
} }
$result = $this->load_stats_sending(0, '1,2', 1, $filterShipmentStatus); $result = $this->load_stats_sending(0, '1,2', 1, $filterShipmentStatus);
if ($result < 0) dol_print_error($this->db, $this->error); if ($result < 0) {
dol_print_error($this->db, $this->error);
}
$stock_sending_client = $this->stats_expedition['qty']; $stock_sending_client = $this->stats_expedition['qty'];
} }
if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled)) if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled)) {
{
$filterStatus = '1,2,3,4'; $filterStatus = '1,2,3,4';
if (isset($includedraftpoforvirtual)) $filterStatus = '0,'.$filterStatus; if (isset($includedraftpoforvirtual)) {
$filterStatus = '0,'.$filterStatus;
}
$result = $this->load_stats_commande_fournisseur(0, $filterStatus, 1); $result = $this->load_stats_commande_fournisseur(0, $filterStatus, 1);
if ($result < 0) dol_print_error($this->db, $this->error); if ($result < 0) {
dol_print_error($this->db, $this->error);
}
$stock_commande_fournisseur = $this->stats_commande_fournisseur['qty']; $stock_commande_fournisseur = $this->stats_commande_fournisseur['qty'];
} }
if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) && empty($conf->reception->enabled)) if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) && empty($conf->reception->enabled)) {
{
$filterStatus = '4'; $filterStatus = '4';
if (isset($includedraftpoforvirtual)) $filterStatus = '0,'.$filterStatus; if (isset($includedraftpoforvirtual)) {
$filterStatus = '0,'.$filterStatus;
}
$result = $this->load_stats_reception(0, $filterStatus, 1); $result = $this->load_stats_reception(0, $filterStatus, 1);
if ($result < 0) dol_print_error($this->db, $this->error); if ($result < 0) {
dol_print_error($this->db, $this->error);
}
$stock_reception_fournisseur = $this->stats_reception['qty']; $stock_reception_fournisseur = $this->stats_reception['qty'];
} }
if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) && empty($conf->reception->enabled)) if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) && empty($conf->reception->enabled)) {
{
$filterStatus = '4'; $filterStatus = '4';
if (isset($includedraftpoforvirtual)) $filterStatus = '0,'.$filterStatus; if (isset($includedraftpoforvirtual)) {
$filterStatus = '0,'.$filterStatus;
}
$result = $this->load_stats_reception(0, $filterStatus, 1); // Use same tables than when module reception is not used. $result = $this->load_stats_reception(0, $filterStatus, 1); // Use same tables than when module reception is not used.
if ($result < 0) dol_print_error($this->db, $this->error); if ($result < 0) {
dol_print_error($this->db, $this->error);
}
$stock_reception_fournisseur = $this->stats_reception['qty']; $stock_reception_fournisseur = $this->stats_reception['qty'];
} }
if (!empty($conf->mrp->enabled)) if (!empty($conf->mrp->enabled)) {
{
$result = $this->load_stats_inproduction(0, '1,2', 1); $result = $this->load_stats_inproduction(0, '1,2', 1);
if ($result < 0) dol_print_error($this->db, $this->error); if ($result < 0) {
dol_print_error($this->db, $this->error);
}
$stock_inproduction = $this->stats_mrptoproduce['qty'] - $this->stats_mrptoconsume['qty']; $stock_inproduction = $this->stats_mrptoproduce['qty'] - $this->stats_mrptoconsume['qty'];
} }
@ -5043,7 +5099,9 @@ class Product extends CommonObject
$parameters = array('id'=>$this->id, 'includedraftpoforvirtual' => $includedraftpoforvirtual); $parameters = array('id'=>$this->id, 'includedraftpoforvirtual' => $includedraftpoforvirtual);
// Note that $action and $object may have been modified by some hooks // Note that $action and $object may have been modified by some hooks
$reshook = $hookmanager->executeHooks('loadvirtualstock', $parameters, $this, $action); $reshook = $hookmanager->executeHooks('loadvirtualstock', $parameters, $this, $action);
if ($reshook > 0) $this->stock_theorique = $hookmanager->resArray['stock_theorique']; if ($reshook > 0) {
$this->stock_theorique = $hookmanager->resArray['stock_theorique'];
}
return 1; return 1;
} }
@ -5068,8 +5126,7 @@ class Product extends CommonObject
if ($resql) { if ($resql) {
$num = $this->db->num_rows($resql); $num = $this->db->num_rows($resql);
$i = 0; $i = 0;
while ($i < $num) while ($i < $num) {
{
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
$result[] = array('batch'=>$batch, 'eatby'=>$this->db->jdate($obj->eatby), 'sellby'=>$this->db->jdate($obj->sellby), 'qty'=>$obj->qty); $result[] = array('batch'=>$batch, 'eatby'=>$this->db->jdate($obj->eatby), 'sellby'=>$this->db->jdate($obj->sellby), 'qty'=>$obj->qty);
$i++; $i++;
@ -5157,8 +5214,7 @@ class Product extends CommonObject
if (file_exists($dir_osencoded)) { if (file_exists($dir_osencoded)) {
$handle = opendir($dir_osencoded); $handle = opendir($dir_osencoded);
if (is_resource($handle)) { if (is_resource($handle)) {
while (($file = readdir($handle)) !== false) while (($file = readdir($handle)) !== false) {
{
if (!utf8_check($file)) { if (!utf8_check($file)) {
$file = utf8_encode($file); // To be sure data is stored in UTF8 in memory $file = utf8_encode($file); // To be sure data is stored in UTF8 in memory
} }
@ -5191,9 +5247,9 @@ class Product extends CommonObject
$dir_osencoded = dol_osencode($dir); $dir_osencoded = dol_osencode($dir);
$handle = @opendir($dir_osencoded); $handle = @opendir($dir_osencoded);
if (is_resource($handle)) { if (is_resource($handle)) {
while (($file = readdir($handle)) !== false) while (($file = readdir($handle)) !== false) {
{ if (!utf8_check($file)) {
if (!utf8_check($file)) { $file = utf8_encode($file); // readdir returns ISO $file = utf8_encode($file); // readdir returns ISO
} }
if (dol_is_file($dir.$file) && image_format_supported($file) >= 0) { if (dol_is_file($dir.$file) && image_format_supported($file) >= 0) {
$nbphoto++; $nbphoto++;
@ -5210,14 +5266,17 @@ class Product extends CommonObject
// Objet // Objet
$obj = array(); $obj = array();
$obj['photo'] = $photo; $obj['photo'] = $photo;
if ($photo_vignette && dol_is_file($dirthumb.$photo_vignette)) { $obj['photo_vignette'] = 'thumbs/'.$photo_vignette; if ($photo_vignette && dol_is_file($dirthumb.$photo_vignette)) {
} else { $obj['photo_vignette'] = ""; $obj['photo_vignette'] = 'thumbs/'.$photo_vignette;
} else {
$obj['photo_vignette'] = "";
} }
$tabobj[$nbphoto - 1] = $obj; $tabobj[$nbphoto - 1] = $obj;
// On continue ou on arrete de boucler ? // On continue ou on arrete de boucler ?
if ($nbmax && $nbphoto >= $nbmax) { break; if ($nbmax && $nbphoto >= $nbmax) {
break;
} }
} }
} }
@ -5304,10 +5363,11 @@ class Product extends CommonObject
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) { if ($resql) {
while ($obj = $this->db->fetch_object($resql)) while ($obj = $this->db->fetch_object($resql)) {
{ if ($obj->fk_product_type == 1) {
if ($obj->fk_product_type == 1) { $this->nb["services"] = $obj->nb; $this->nb["services"] = $obj->nb;
} else { $this->nb["products"] = $obj->nb; } else {
$this->nb["products"] = $obj->nb;
} }
} }
$this->db->free($resql); $this->db->free($resql);
@ -5356,10 +5416,10 @@ class Product extends CommonObject
$result = ''; $result = '';
if (!empty($conf->global->BARCODE_PRODUCT_ADDON_NUM)) { if (!empty($conf->global->BARCODE_PRODUCT_ADDON_NUM)) {
$dirsociete = array_merge(array('/core/modules/barcode/'), $conf->modules_parts['barcode']); $dirsociete = array_merge(array('/core/modules/barcode/'), $conf->modules_parts['barcode']);
foreach ($dirsociete as $dirroot) foreach ($dirsociete as $dirroot) {
{
$res = dol_include_once($dirroot.$conf->global->BARCODE_PRODUCT_ADDON_NUM.'.php'); $res = dol_include_once($dirroot.$conf->global->BARCODE_PRODUCT_ADDON_NUM.'.php');
if ($res) { break; if ($res) {
break;
} }
} }
$var = $conf->global->BARCODE_PRODUCT_ADDON_NUM; $var = $conf->global->BARCODE_PRODUCT_ADDON_NUM;
@ -5483,8 +5543,7 @@ class Product extends CommonObject
$product_fourn_list = $product_fourn->list_product_fournisseur_price($this->id, '', ''); $product_fourn_list = $product_fourn->list_product_fournisseur_price($this->id, '', '');
if (is_array($product_fourn_list) && count($product_fourn_list) > 0) { if (is_array($product_fourn_list) && count($product_fourn_list) > 0) {
foreach ($product_fourn_list as $productfourn) foreach ($product_fourn_list as $productfourn) {
{
if ($productfourn->fourn_unitprice > $maxpricesupplier) { if ($productfourn->fourn_unitprice > $maxpricesupplier) {
$maxpricesupplier = $productfourn->fourn_unitprice; $maxpricesupplier = $productfourn->fourn_unitprice;
} }

View File

@ -107,15 +107,15 @@ class Productbatch extends CommonObject
dol_syslog(get_class($this)."::create", LOG_DEBUG); dol_syslog(get_class($this)."::create", LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } if (!$resql) {
if (!$error) $error++; $this->errors[] = "Error ".$this->db->lasterror();
{ }
if (!$error) {
$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.self::$_table_element); $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.self::$_table_element);
} }
// Commit or rollback // Commit or rollback
if ($error) if ($error) {
{
$this->db->rollback(); $this->db->rollback();
return -1 * $error; return -1 * $error;
} else { } else {
@ -155,10 +155,8 @@ class Productbatch extends CommonObject
dol_syslog(get_class($this)."::fetch", LOG_DEBUG); dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{ if ($this->db->num_rows($resql)) {
if ($this->db->num_rows($resql))
{
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
$this->id = $obj->rowid; $this->id = $obj->rowid;
@ -197,8 +195,7 @@ class Productbatch extends CommonObject
$this->cleanParam(); $this->cleanParam();
// TODO Check qty is ok for stock move. Negative may not be allowed. // TODO Check qty is ok for stock move. Negative may not be allowed.
if ($this->qty < 0) if ($this->qty < 0) {
{
} }
// Update request // Update request
@ -215,13 +212,13 @@ class Productbatch extends CommonObject
dol_syslog(get_class($this)."::update", LOG_DEBUG); dol_syslog(get_class($this)."::update", LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } if (!$resql) {
$error++; $this->errors[] = "Error ".$this->db->lasterror();
}
// Commit or rollback // Commit or rollback
if ($error) if ($error) {
{ foreach ($this->errors as $errmsg) {
foreach ($this->errors as $errmsg)
{
dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
$this->error .= ($this->error ? ', '.$errmsg : $errmsg); $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
} }
@ -247,21 +244,20 @@ class Productbatch extends CommonObject
$this->db->begin(); $this->db->begin();
if (!$error) if (!$error) {
{
$sql = "DELETE FROM ".MAIN_DB_PREFIX.self::$_table_element.""; $sql = "DELETE FROM ".MAIN_DB_PREFIX.self::$_table_element."";
$sql .= " WHERE rowid=".$this->id; $sql .= " WHERE rowid=".$this->id;
dol_syslog(get_class($this)."::delete", LOG_DEBUG); dol_syslog(get_class($this)."::delete", LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } if (!$resql) {
$error++; $this->errors[] = "Error ".$this->db->lasterror();
}
} }
// Commit or rollback // Commit or rollback
if ($error) if ($error) {
{ foreach ($this->errors as $errmsg) {
foreach ($this->errors as $errmsg)
{
dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
$this->error .= ($this->error ? ', '.$errmsg : $errmsg); $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
} }
@ -303,22 +299,19 @@ class Productbatch extends CommonObject
$result = $object->create($user); $result = $object->create($user);
// Other options // Other options
if ($result < 0) if ($result < 0) {
{
$this->error = $object->error; $this->error = $object->error;
$this->errors = array_merge($this->errors, $object->errors); $this->errors = array_merge($this->errors, $object->errors);
$error++; $error++;
} }
if (!$error) if (!$error) {
{
} }
unset($object->context['createfromclone']); unset($object->context['createfromclone']);
// End // End
if (!$error) if (!$error) {
{
$this->db->commit(); $this->db->commit();
return $object->id; return $object->id;
} else { } else {
@ -353,10 +346,18 @@ class Productbatch extends CommonObject
*/ */
private function cleanParam() private function cleanParam()
{ {
if (isset($this->fk_product_stock)) $this->fk_product_stock = (int) trim($this->fk_product_stock); if (isset($this->fk_product_stock)) {
if (isset($this->batch)) $this->batch = trim($this->batch); $this->fk_product_stock = (int) trim($this->fk_product_stock);
if (isset($this->qty)) $this->qty = (float) trim($this->qty); }
if (isset($this->import_key)) $this->import_key = trim($this->import_key); if (isset($this->batch)) {
$this->batch = trim($this->batch);
}
if (isset($this->qty)) {
$this->qty = (float) trim($this->qty);
}
if (isset($this->import_key)) {
$this->import_key = trim($this->import_key);
}
} }
/** /**
@ -385,19 +386,25 @@ class Productbatch extends CommonObject
$sql .= " FROM ".MAIN_DB_PREFIX.self::$_table_element." as t"; $sql .= " FROM ".MAIN_DB_PREFIX.self::$_table_element." as t";
$sql .= " WHERE fk_product_stock=".$fk_product_stock; $sql .= " WHERE fk_product_stock=".$fk_product_stock;
if (!empty($eatby)) array_push($where, " eatby = '".$this->db->idate($eatby)."'"); // deprecated if (!empty($eatby)) {
if (!empty($sellby)) array_push($where, " sellby = '".$this->db->idate($sellby)."'"); // deprecated array_push($where, " eatby = '".$this->db->idate($eatby)."'"); // deprecated
}
if (!empty($sellby)) {
array_push($where, " sellby = '".$this->db->idate($sellby)."'"); // deprecated
}
if (!empty($batch_number)) $sql .= " AND batch = '".$this->db->escape($batch_number)."'"; if (!empty($batch_number)) {
$sql .= " AND batch = '".$this->db->escape($batch_number)."'";
}
if (!empty($where)) $sql .= " AND (".implode(" OR ", $where).")"; if (!empty($where)) {
$sql .= " AND (".implode(" OR ", $where).")";
}
dol_syslog(get_class($this)."::fetch", LOG_DEBUG); dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{ if ($this->db->num_rows($resql)) {
if ($this->db->num_rows($resql))
{
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
$this->id = $obj->rowid; $this->id = $obj->rowid;
@ -441,27 +448,26 @@ class Productbatch extends CommonObject
$sql .= " t.batch,"; $sql .= " t.batch,";
$sql .= " t.qty,"; $sql .= " t.qty,";
$sql .= " t.import_key"; $sql .= " t.import_key";
if ($fk_product > 0) if ($fk_product > 0) {
{
$sql .= ", pl.rowid as lotid, pl.eatby as eatby, pl.sellby as sellby"; $sql .= ", pl.rowid as lotid, pl.eatby as eatby, pl.sellby as sellby";
// TODO May add extrafields to ? // TODO May add extrafields to ?
} }
$sql .= " FROM ".MAIN_DB_PREFIX."product_batch as t"; $sql .= " FROM ".MAIN_DB_PREFIX."product_batch as t";
if ($fk_product > 0) if ($fk_product > 0) {
{
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_lot as pl ON pl.fk_product = ".$fk_product." AND pl.batch = t.batch"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_lot as pl ON pl.fk_product = ".$fk_product." AND pl.batch = t.batch";
// TODO May add extrafields to ? // TODO May add extrafields to ?
} }
$sql .= " WHERE fk_product_stock=".$fk_product_stock; $sql .= " WHERE fk_product_stock=".$fk_product_stock;
if ($with_qty) $sql .= " AND t.qty <> 0"; if ($with_qty) {
$sql .= " AND t.qty <> 0";
}
dol_syslog("productbatch::findAll", LOG_DEBUG); dol_syslog("productbatch::findAll", LOG_DEBUG);
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) { if ($resql) {
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
$i = 0; $i = 0;
while ($i < $num) while ($i < $num) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
$tmp = new Productbatch($db); $tmp = new Productbatch($db);

View File

@ -107,36 +107,51 @@ class Productcustomerprice extends CommonObject
// Clean parameters // Clean parameters
if (isset($this->entity)) if (isset($this->entity)) {
$this->entity = trim($this->entity); $this->entity = trim($this->entity);
if (isset($this->fk_product)) }
if (isset($this->fk_product)) {
$this->fk_product = trim($this->fk_product); $this->fk_product = trim($this->fk_product);
if (isset($this->fk_soc)) }
if (isset($this->fk_soc)) {
$this->fk_soc = trim($this->fk_soc); $this->fk_soc = trim($this->fk_soc);
if (isset($this->ref_customer)) }
if (isset($this->ref_customer)) {
$this->ref_customer = trim($this->ref_customer); $this->ref_customer = trim($this->ref_customer);
if (isset($this->price)) }
if (isset($this->price)) {
$this->price = trim($this->price); $this->price = trim($this->price);
if (isset($this->price_ttc)) }
if (isset($this->price_ttc)) {
$this->price_ttc = trim($this->price_ttc); $this->price_ttc = trim($this->price_ttc);
if (isset($this->price_min)) }
if (isset($this->price_min)) {
$this->price_min = trim($this->price_min); $this->price_min = trim($this->price_min);
if (isset($this->price_min_ttc)) }
if (isset($this->price_min_ttc)) {
$this->price_min_ttc = trim($this->price_min_ttc); $this->price_min_ttc = trim($this->price_min_ttc);
if (isset($this->price_base_type)) }
if (isset($this->price_base_type)) {
$this->price_base_type = trim($this->price_base_type); $this->price_base_type = trim($this->price_base_type);
if (isset($this->tva_tx)) }
if (isset($this->tva_tx)) {
$this->tva_tx = trim($this->tva_tx); $this->tva_tx = trim($this->tva_tx);
if (isset($this->recuperableonly)) }
if (isset($this->recuperableonly)) {
$this->recuperableonly = trim($this->recuperableonly); $this->recuperableonly = trim($this->recuperableonly);
if (isset($this->localtax1_tx)) }
if (isset($this->localtax1_tx)) {
$this->localtax1_tx = trim($this->localtax1_tx); $this->localtax1_tx = trim($this->localtax1_tx);
if (isset($this->localtax2_tx)) }
if (isset($this->localtax2_tx)) {
$this->localtax2_tx = trim($this->localtax2_tx); $this->localtax2_tx = trim($this->localtax2_tx);
if (isset($this->fk_user)) }
if (isset($this->fk_user)) {
$this->fk_user = trim($this->fk_user); $this->fk_user = trim($this->fk_user);
if (isset($this->import_key)) }
if (isset($this->import_key)) {
$this->import_key = trim($this->import_key); $this->import_key = trim($this->import_key);
}
// Check parameters // Check parameters
// Put here code to add control on parameters values // Put here code to add control on parameters values
@ -342,8 +357,12 @@ class Productcustomerprice extends CommonObject
// phpcs:enable // phpcs:enable
global $langs; global $langs;
if (empty($sortfield)) $sortfield = "t.rowid"; if (empty($sortfield)) {
if (empty($sortorder)) $sortorder = "DESC"; $sortfield = "t.rowid";
}
if (empty($sortorder)) {
$sortorder = "DESC";
}
$sql = "SELECT"; $sql = "SELECT";
$sql .= " t.rowid,"; $sql .= " t.rowid,";
@ -394,7 +413,9 @@ class Productcustomerprice extends CommonObject
} }
} }
$sql .= $this->db->order($sortfield, $sortorder); $sql .= $this->db->order($sortfield, $sortorder);
if (!empty($limit)) $sql .= ' '.$this->db->plimit($limit + 1, $offset); if (!empty($limit)) {
$sql .= ' '.$this->db->plimit($limit + 1, $offset);
}
dol_syslog(get_class($this)."::fetch_all", LOG_DEBUG); dol_syslog(get_class($this)."::fetch_all", LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
@ -457,8 +478,12 @@ class Productcustomerprice extends CommonObject
// phpcs:enable // phpcs:enable
global $langs; global $langs;
if (!empty($sortfield)) $sortfield = "t.rowid"; if (!empty($sortfield)) {
if (!empty($sortorder)) $sortorder = "DESC"; $sortfield = "t.rowid";
}
if (!empty($sortorder)) {
$sortorder = "DESC";
}
$sql = "SELECT"; $sql = "SELECT";
$sql .= " t.rowid,"; $sql .= " t.rowid,";
@ -493,8 +518,7 @@ class Productcustomerprice extends CommonObject
// Manage filter // Manage filter
if (count($filter) > 0) { if (count($filter) > 0) {
foreach ($filter as $key => $value) { foreach ($filter as $key => $value) {
if (strpos($key, 'date')) // To allow $filter['YEAR(s.dated)']=>$year if (strpos($key, 'date')) { // To allow $filter['YEAR(s.dated)']=>$year
{
$sql .= ' AND '.$key.' = \''.$value.'\''; $sql .= ' AND '.$key.' = \''.$value.'\'';
} elseif ($key == 'soc.nom') { } elseif ($key == 'soc.nom') {
$sql .= ' AND '.$key.' LIKE \'%'.$value.'%\''; $sql .= ' AND '.$key.' LIKE \'%'.$value.'%\'';
@ -505,7 +529,9 @@ class Productcustomerprice extends CommonObject
} }
$sql .= $this->db->order($sortfield, $sortorder); $sql .= $this->db->order($sortfield, $sortorder);
if (!empty($limit)) $sql .= ' '.$this->db->plimit($limit + 1, $offset); if (!empty($limit)) {
$sql .= ' '.$this->db->plimit($limit + 1, $offset);
}
dol_syslog(get_class($this)."::fetch_all_log", LOG_DEBUG); dol_syslog(get_class($this)."::fetch_all_log", LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
@ -566,36 +592,51 @@ class Productcustomerprice extends CommonObject
// Clean parameters // Clean parameters
if (isset($this->entity)) if (isset($this->entity)) {
$this->entity = trim($this->entity); $this->entity = trim($this->entity);
if (isset($this->fk_product)) }
if (isset($this->fk_product)) {
$this->fk_product = trim($this->fk_product); $this->fk_product = trim($this->fk_product);
if (isset($this->fk_soc)) }
if (isset($this->fk_soc)) {
$this->fk_soc = trim($this->fk_soc); $this->fk_soc = trim($this->fk_soc);
if (isset($this->ref_customer)) }
if (isset($this->ref_customer)) {
$this->ref_customer = trim($this->ref_customer); $this->ref_customer = trim($this->ref_customer);
if (isset($this->price)) }
if (isset($this->price)) {
$this->price = trim($this->price); $this->price = trim($this->price);
if (isset($this->price_ttc)) }
if (isset($this->price_ttc)) {
$this->price_ttc = trim($this->price_ttc); $this->price_ttc = trim($this->price_ttc);
if (isset($this->price_min)) }
if (isset($this->price_min)) {
$this->price_min = trim($this->price_min); $this->price_min = trim($this->price_min);
if (isset($this->price_min_ttc)) }
if (isset($this->price_min_ttc)) {
$this->price_min_ttc = trim($this->price_min_ttc); $this->price_min_ttc = trim($this->price_min_ttc);
if (isset($this->price_base_type)) }
if (isset($this->price_base_type)) {
$this->price_base_type = trim($this->price_base_type); $this->price_base_type = trim($this->price_base_type);
if (isset($this->tva_tx)) }
if (isset($this->tva_tx)) {
$this->tva_tx = trim($this->tva_tx); $this->tva_tx = trim($this->tva_tx);
if (isset($this->recuperableonly)) }
if (isset($this->recuperableonly)) {
$this->recuperableonly = trim($this->recuperableonly); $this->recuperableonly = trim($this->recuperableonly);
if (isset($this->localtax1_tx)) }
if (isset($this->localtax1_tx)) {
$this->localtax1_tx = trim($this->localtax1_tx); $this->localtax1_tx = trim($this->localtax1_tx);
if (isset($this->localtax2_tx)) }
if (isset($this->localtax2_tx)) {
$this->localtax2_tx = trim($this->localtax2_tx); $this->localtax2_tx = trim($this->localtax2_tx);
if (isset($this->fk_user)) }
if (isset($this->fk_user)) {
$this->fk_user = trim($this->fk_user); $this->fk_user = trim($this->fk_user);
if (isset($this->import_key)) }
if (isset($this->import_key)) {
$this->import_key = trim($this->import_key); $this->import_key = trim($this->import_key);
}
// Check parameters // Check parameters
// Put here code to add a control on parameters values // Put here code to add a control on parameters values
@ -722,11 +763,12 @@ class Productcustomerprice extends CommonObject
$this->errors [] = "Error ".$this->db->lasterror(); $this->errors [] = "Error ".$this->db->lasterror();
} }
if (!$error && !$notrigger) if (!$error && !$notrigger) {
{
// Call trigger // Call trigger
$result = $this->call_trigger('PRODUCT_CUSTOMER_PRICE_UPDATE', $user); $result = $this->call_trigger('PRODUCT_CUSTOMER_PRICE_UPDATE', $user);
if ($result < 0) $error++; if ($result < 0) {
$error++;
}
// End call triggers // End call triggers
} }

View File

@ -79,12 +79,24 @@ class Propalmergepdfproduct extends CommonObject
// Clean parameters // Clean parameters
if (isset($this->fk_product)) $this->fk_product = trim($this->fk_product); if (isset($this->fk_product)) {
if (isset($this->file_name)) $this->file_name = trim($this->file_name); $this->fk_product = trim($this->fk_product);
if (isset($this->fk_user_author)) $this->fk_user_author = trim($this->fk_user_author); }
if (isset($this->fk_user_mod)) $this->fk_user_mod = trim($this->fk_user_mod); if (isset($this->file_name)) {
if (isset($this->lang)) $this->lang = trim($this->lang); $this->file_name = trim($this->file_name);
if (isset($this->import_key)) $this->import_key = trim($this->import_key); }
if (isset($this->fk_user_author)) {
$this->fk_user_author = trim($this->fk_user_author);
}
if (isset($this->fk_user_mod)) {
$this->fk_user_mod = trim($this->fk_user_mod);
}
if (isset($this->lang)) {
$this->lang = trim($this->lang);
}
if (isset($this->import_key)) {
$this->import_key = trim($this->import_key);
}
@ -122,18 +134,17 @@ class Propalmergepdfproduct extends CommonObject
dol_syslog(__METHOD__, LOG_DEBUG); dol_syslog(__METHOD__, LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } if (!$resql) {
$error++; $this->errors[] = "Error ".$this->db->lasterror();
}
if (!$error) if (!$error) {
{
$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."propal_merge_pdf_product"); $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."propal_merge_pdf_product");
} }
// Commit or rollback // Commit or rollback
if ($error) if ($error) {
{ foreach ($this->errors as $errmsg) {
foreach ($this->errors as $errmsg)
{
dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
$this->error .= ($this->error ? ', '.$errmsg : $errmsg); $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
} }
@ -174,10 +185,8 @@ class Propalmergepdfproduct extends CommonObject
dol_syslog(__METHOD__, LOG_DEBUG); dol_syslog(__METHOD__, LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{ if ($this->db->num_rows($resql)) {
if ($this->db->num_rows($resql))
{
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
$this->id = $obj->rowid; $this->id = $obj->rowid;
@ -237,10 +246,8 @@ class Propalmergepdfproduct extends CommonObject
dol_syslog(__METHOD__, LOG_DEBUG); dol_syslog(__METHOD__, LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{ if ($this->db->num_rows($resql)) {
if ($this->db->num_rows($resql))
{
while ($obj = $this->db->fetch_object($resql)) { while ($obj = $this->db->fetch_object($resql)) {
$line = new PropalmergepdfproductLine(); $line = new PropalmergepdfproductLine();
@ -290,10 +297,18 @@ class Propalmergepdfproduct extends CommonObject
// Clean parameters // Clean parameters
if (isset($this->fk_product)) $this->fk_product = trim($this->fk_product); if (isset($this->fk_product)) {
if (isset($this->file_name)) $this->file_name = trim($this->file_name); $this->fk_product = trim($this->fk_product);
if (isset($this->fk_user_mod)) $this->fk_user_mod = trim($this->fk_user_mod); }
if (isset($this->lang)) $this->lang = trim($this->lang); if (isset($this->file_name)) {
$this->file_name = trim($this->file_name);
}
if (isset($this->fk_user_mod)) {
$this->fk_user_mod = trim($this->fk_user_mod);
}
if (isset($this->lang)) {
$this->lang = trim($this->lang);
}
// Check parameters // Check parameters
// Put here code to add a control on parameters values // Put here code to add a control on parameters values
@ -315,13 +330,13 @@ class Propalmergepdfproduct extends CommonObject
dol_syslog(__METHOD__, LOG_DEBUG); dol_syslog(__METHOD__, LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } if (!$resql) {
$error++; $this->errors[] = "Error ".$this->db->lasterror();
}
// Commit or rollback // Commit or rollback
if ($error) if ($error) {
{ foreach ($this->errors as $errmsg) {
foreach ($this->errors as $errmsg)
{
dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
$this->error .= ($this->error ? ', '.$errmsg : $errmsg); $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
} }
@ -348,21 +363,20 @@ class Propalmergepdfproduct extends CommonObject
$this->db->begin(); $this->db->begin();
if (!$error) if (!$error) {
{
$sql = "DELETE FROM ".MAIN_DB_PREFIX."propal_merge_pdf_product"; $sql = "DELETE FROM ".MAIN_DB_PREFIX."propal_merge_pdf_product";
$sql .= " WHERE rowid=".$this->id; $sql .= " WHERE rowid=".$this->id;
dol_syslog(__METHOD__, LOG_DEBUG); dol_syslog(__METHOD__, LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } if (!$resql) {
$error++; $this->errors[] = "Error ".$this->db->lasterror();
}
} }
// Commit or rollback // Commit or rollback
if ($error) if ($error) {
{ foreach ($this->errors as $errmsg) {
foreach ($this->errors as $errmsg)
{
dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
$this->error .= ($this->error ? ', '.$errmsg : $errmsg); $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
} }
@ -392,8 +406,7 @@ class Propalmergepdfproduct extends CommonObject
$this->db->begin(); $this->db->begin();
if (!$error) if (!$error) {
{
$sql = "DELETE FROM ".MAIN_DB_PREFIX."propal_merge_pdf_product"; $sql = "DELETE FROM ".MAIN_DB_PREFIX."propal_merge_pdf_product";
$sql .= " WHERE fk_product=".$product_id; $sql .= " WHERE fk_product=".$product_id;
@ -403,14 +416,14 @@ class Propalmergepdfproduct extends CommonObject
dol_syslog(__METHOD__, LOG_DEBUG); dol_syslog(__METHOD__, LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } if (!$resql) {
$error++; $this->errors[] = "Error ".$this->db->lasterror();
}
} }
// Commit or rollback // Commit or rollback
if ($error) if ($error) {
{ foreach ($this->errors as $errmsg) {
foreach ($this->errors as $errmsg)
{
dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
$this->error .= ($this->error ? ', '.$errmsg : $errmsg); $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
} }
@ -437,21 +450,20 @@ class Propalmergepdfproduct extends CommonObject
$this->db->begin(); $this->db->begin();
if (!$error) if (!$error) {
{
$sql = "DELETE FROM ".MAIN_DB_PREFIX."propal_merge_pdf_product"; $sql = "DELETE FROM ".MAIN_DB_PREFIX."propal_merge_pdf_product";
$sql .= " WHERE fk_product=".$this->fk_product." AND file_name='".$this->db->escape($this->file_name)."'"; $sql .= " WHERE fk_product=".$this->fk_product." AND file_name='".$this->db->escape($this->file_name)."'";
dol_syslog(__METHOD__, LOG_DEBUG); dol_syslog(__METHOD__, LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } if (!$resql) {
$error++; $this->errors[] = "Error ".$this->db->lasterror();
}
} }
// Commit or rollback // Commit or rollback
if ($error) if ($error) {
{ foreach ($this->errors as $errmsg) {
foreach ($this->errors as $errmsg)
{
dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
$this->error .= ($this->error ? ', '.$errmsg : $errmsg); $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
} }
@ -493,22 +505,19 @@ class Propalmergepdfproduct extends CommonObject
$result = $object->create($user); $result = $object->create($user);
// Other options // Other options
if ($result < 0) if ($result < 0) {
{
$this->error = $object->error; $this->error = $object->error;
$this->errors = array_merge($this->errors, $object->errors); $this->errors = array_merge($this->errors, $object->errors);
$error++; $error++;
} }
if (!$error) if (!$error) {
{
} }
unset($object->context['createfromclone']); unset($object->context['createfromclone']);
// End // End
if (!$error) if (!$error) {
{
$this->db->commit(); $this->db->commit();
return $object->id; return $object->id;
} else { } else {

View File

@ -45,15 +45,16 @@ $key = GETPOST('key');
$parent = GETPOST('parent'); $parent = GETPOST('parent');
// Security check // Security check
if (!empty($user->socid)) $socid = $user->socid; if (!empty($user->socid)) {
$socid = $user->socid;
}
$fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : '')); $fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : ''));
$fieldtype = (!empty($ref) ? 'ref' : 'rowid'); $fieldtype = (!empty($ref) ? 'ref' : 'rowid');
$result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype);
$object = new Product($db); $object = new Product($db);
$objectid = 0; $objectid = 0;
if ($id > 0 || !empty($ref)) if ($id > 0 || !empty($ref)) {
{
$result = $object->fetch($id, $ref); $result = $object->fetch($id, $ref);
$objectid = $object->id; $objectid = $object->id;
$id = $object->id; $id = $object->id;
@ -64,21 +65,19 @@ if ($id > 0 || !empty($ref))
* Actions * Actions
*/ */
if ($cancel) $action = ''; if ($cancel) {
$action = '';
}
// Add subproduct to product // Add subproduct to product
if ($action == 'add_prod' && ($user->rights->produit->creer || $user->rights->service->creer)) if ($action == 'add_prod' && ($user->rights->produit->creer || $user->rights->service->creer)) {
{
$error = 0; $error = 0;
$maxprod = GETPOST("max_prod", 'int'); $maxprod = GETPOST("max_prod", 'int');
for ($i = 0; $i < $maxprod; $i++) for ($i = 0; $i < $maxprod; $i++) {
{
$qty = price2num(GETPOST("prod_qty_".$i, 'alpha'), 'MS'); $qty = price2num(GETPOST("prod_qty_".$i, 'alpha'), 'MS');
if ($qty > 0) if ($qty > 0) {
{ if ($object->add_sousproduit($id, GETPOST("prod_id_".$i, 'int'), $qty, GETPOST("prod_incdec_".$i, 'int')) > 0) {
if ($object->add_sousproduit($id, GETPOST("prod_id_".$i, 'int'), $qty, GETPOST("prod_incdec_".$i, 'int')) > 0)
{
//var_dump($i.' '.GETPOST("prod_id_".$i, 'int'), $qty, GETPOST("prod_incdec_".$i, 'int')); //var_dump($i.' '.GETPOST("prod_id_".$i, 'int'), $qty, GETPOST("prod_incdec_".$i, 'int'));
$action = 'edit'; $action = 'edit';
} else { } else {
@ -91,8 +90,7 @@ if ($action == 'add_prod' && ($user->rights->produit->creer || $user->rights->se
} }
} }
} else { } else {
if ($object->del_sousproduit($id, GETPOST("prod_id_".$i, 'int')) > 0) if ($object->del_sousproduit($id, GETPOST("prod_id_".$i, 'int')) > 0) {
{
$action = 'edit'; $action = 'edit';
} else { } else {
$error++; $error++;
@ -102,20 +100,19 @@ if ($action == 'add_prod' && ($user->rights->produit->creer || $user->rights->se
} }
} }
if (!$error) if (!$error) {
{
header("Location: ".$_SERVER["PHP_SELF"].'?id='.$object->id); header("Location: ".$_SERVER["PHP_SELF"].'?id='.$object->id);
exit; exit;
} }
} elseif ($action === 'save_composed_product') } elseif ($action === 'save_composed_product') {
{
$TProduct = GETPOST('TProduct', 'array'); $TProduct = GETPOST('TProduct', 'array');
if (!empty($TProduct)) if (!empty($TProduct)) {
{ foreach ($TProduct as $id_product => $row) {
foreach ($TProduct as $id_product => $row) if ($row['qty'] > 0) {
{ $object->update_sousproduit($id, $id_product, $row['qty'], isset($row['incdec']) ? 1 : 0);
if ($row['qty'] > 0) $object->update_sousproduit($id, $id_product, $row['qty'], isset($row['incdec']) ? 1 : 0); } else {
else $object->del_sousproduit($id, $id_product); $object->del_sousproduit($id, $id_product);
}
} }
setEventMessages('RecordSaved', null); setEventMessages('RecordSaved', null);
} }
@ -132,17 +129,20 @@ $productstatic = new Product($db);
$form = new Form($db); $form = new Form($db);
// action recherche des produits par mot-cle et/ou par categorie // action recherche des produits par mot-cle et/ou par categorie
if ($action == 'search') if ($action == 'search') {
{
$current_lang = $langs->getDefaultLang(); $current_lang = $langs->getDefaultLang();
$sql = 'SELECT DISTINCT p.rowid, p.ref, p.label, p.fk_product_type as type, p.barcode, p.price, p.price_ttc, p.price_base_type, p.entity,'; $sql = 'SELECT DISTINCT p.rowid, p.ref, p.label, p.fk_product_type as type, p.barcode, p.price, p.price_ttc, p.price_base_type, p.entity,';
$sql .= ' p.fk_product_type, p.tms as datem, p.tobatch'; $sql .= ' p.fk_product_type, p.tms as datem, p.tobatch';
$sql .= ', p.tosell as status, p.tobuy as status_buy'; $sql .= ', p.tosell as status, p.tobuy as status_buy';
if (!empty($conf->global->MAIN_MULTILANGS)) $sql .= ', pl.label as labelm, pl.description as descriptionm'; if (!empty($conf->global->MAIN_MULTILANGS)) {
$sql .= ', pl.label as labelm, pl.description as descriptionm';
}
$sql .= ' FROM '.MAIN_DB_PREFIX.'product as p'; $sql .= ' FROM '.MAIN_DB_PREFIX.'product as p';
$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON p.rowid = cp.fk_product'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON p.rowid = cp.fk_product';
if (!empty($conf->global->MAIN_MULTILANGS)) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_lang as pl ON pl.fk_product = p.rowid AND lang='".($current_lang)."'"; if (!empty($conf->global->MAIN_MULTILANGS)) {
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_lang as pl ON pl.fk_product = p.rowid AND lang='".($current_lang)."'";
}
$sql .= ' WHERE p.entity IN ('.getEntity('product').')'; $sql .= ' WHERE p.entity IN ('.getEntity('product').')';
if ($key != "") { if ($key != "") {
// For natural search // For natural search
@ -186,41 +186,37 @@ $picto = ($object->type == Product::TYPE_SERVICE ? 'service' : 'product');
print dol_get_fiche_head($head, 'subproduct', $titre, -1, $picto); print dol_get_fiche_head($head, 'subproduct', $titre, -1, $picto);
if ($id > 0 || !empty($ref)) if ($id > 0 || !empty($ref)) {
{
/* /*
* Fiche en mode edition * Fiche en mode edition
*/ */
if ($user->rights->produit->lire || $user->rights->service->lire) if ($user->rights->produit->lire || $user->rights->service->lire) {
{
$linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; $linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
$shownav = 1; $shownav = 1;
if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) {
$shownav = 0;
}
dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref', '', '', '', 0, '', '', 0); dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref', '', '', '', 0, '', '', 0);
if ($object->type != Product::TYPE_SERVICE || !empty($conf->global->STOCK_SUPPORTS_SERVICES) || empty($conf->global->PRODUIT_MULTIPRICES)) if ($object->type != Product::TYPE_SERVICE || !empty($conf->global->STOCK_SUPPORTS_SERVICES) || empty($conf->global->PRODUIT_MULTIPRICES)) {
{
print '<div class="fichecenter">'; print '<div class="fichecenter">';
print '<div class="underbanner clearboth"></div>'; print '<div class="underbanner clearboth"></div>';
print '<table class="border centpercent tableforfield">'; print '<table class="border centpercent tableforfield">';
// Nature // Nature
if ($object->type != Product::TYPE_SERVICE) if ($object->type != Product::TYPE_SERVICE) {
{
print '<tr><td class="titlefield">'.$langs->trans("Nature").'</td><td>'; print '<tr><td class="titlefield">'.$langs->trans("Nature").'</td><td>';
print $object->getLibFinished(); print $object->getLibFinished();
print '</td></tr>'; print '</td></tr>';
} }
if (empty($conf->global->PRODUIT_MULTIPRICES)) if (empty($conf->global->PRODUIT_MULTIPRICES)) {
{
// Price // Price
print '<tr><td class="titlefield">'.$langs->trans("SellingPrice").'</td><td>'; print '<tr><td class="titlefield">'.$langs->trans("SellingPrice").'</td><td>';
if ($object->price_base_type == 'TTC') if ($object->price_base_type == 'TTC') {
{
print price($object->price_ttc).' '.$langs->trans($object->price_base_type); print price($object->price_ttc).' '.$langs->trans($object->price_base_type);
} else { } else {
print price($object->price).' '.$langs->trans($object->price_base_type ? $object->price_base_type : 'HT'); print price($object->price).' '.$langs->trans($object->price_base_type ? $object->price_base_type : 'HT');
@ -229,8 +225,7 @@ if ($id > 0 || !empty($ref))
// Price minimum // Price minimum
print '<tr><td>'.$langs->trans("MinPrice").'</td><td>'; print '<tr><td>'.$langs->trans("MinPrice").'</td><td>';
if ($object->price_base_type == 'TTC') if ($object->price_base_type == 'TTC') {
{
print price($object->price_min_ttc).' '.$langs->trans($object->price_base_type); print price($object->price_min_ttc).' '.$langs->trans($object->price_base_type);
} else { } else {
print price($object->price_min).' '.$langs->trans($object->price_base_type ? $object->price_base_type : 'HT'); print price($object->price_min).' '.$langs->trans($object->price_base_type ? $object->price_base_type : 'HT');
@ -310,7 +305,9 @@ if ($id > 0 || !empty($ref))
print '<td>'.$langs->trans('Label').'</td>'; print '<td>'.$langs->trans('Label').'</td>';
print '<td class="right" colspan="2">'.$langs->trans('MinSupplierPrice').'</td>'; print '<td class="right" colspan="2">'.$langs->trans('MinSupplierPrice').'</td>';
print '<td class="right" colspan="2">'.$langs->trans('MinCustomerPrice').'</td>'; print '<td class="right" colspan="2">'.$langs->trans('MinCustomerPrice').'</td>';
if (!empty($conf->stock->enabled)) print '<td class="right">'.$langs->trans('Stock').'</td>'; if (!empty($conf->stock->enabled)) {
print '<td class="right">'.$langs->trans('Stock').'</td>';
}
print '<td class="center">'.$langs->trans('Qty').'</td>'; print '<td class="center">'.$langs->trans('Qty').'</td>';
print '<td class="center">'.$langs->trans('ComposedProductIncDecStock').'</td>'; print '<td class="center">'.$langs->trans('ComposedProductIncDecStock').'</td>';
print '</tr>'."\n"; print '</tr>'."\n";
@ -331,11 +328,13 @@ if ($id > 0 || !empty($ref))
// Best buying price // Best buying price
print '<td class="right">'; print '<td class="right">';
if ($product_fourn->find_min_price_product_fournisseur($productstatic->id) > 0) if ($product_fourn->find_min_price_product_fournisseur($productstatic->id) > 0) {
{
print $langs->trans("BuyingPriceMinShort").': '; print $langs->trans("BuyingPriceMinShort").': ';
if ($product_fourn->product_fourn_price_id > 0) print $product_fourn->display_price_product_fournisseur(0, 0); if ($product_fourn->product_fourn_price_id > 0) {
else { print $langs->trans("NotDefined"); $notdefined++; $atleastonenotdefined++; } print $product_fourn->display_price_product_fournisseur(0, 0);
} else {
print $langs->trans("NotDefined"); $notdefined++; $atleastonenotdefined++;
}
} }
print '</td>'; print '</td>';
@ -354,8 +353,7 @@ if ($id > 0 || !empty($ref))
// Best selling price // Best selling price
$pricesell = $productstatic->price; $pricesell = $productstatic->price;
if (!empty($conf->global->PRODUIT_MULTIPRICES)) if (!empty($conf->global->PRODUIT_MULTIPRICES)) {
{
$pricesell = 'Variable'; $pricesell = 'Variable';
} else { } else {
$totallinesell = price2num($value['nb'] * ($pricesell), 'MT'); $totallinesell = price2num($value['nb'] * ($pricesell), 'MT');
@ -363,16 +361,20 @@ if ($id > 0 || !empty($ref))
} }
print '<td class="right" colspan="2">'; print '<td class="right" colspan="2">';
print ($notdefined ? '' : ($value['nb'] > 1 ? $value['nb'].'x' : '')); print ($notdefined ? '' : ($value['nb'] > 1 ? $value['nb'].'x' : ''));
if (is_numeric($pricesell)) print price($pricesell, '', '', 0, 0, -1, $conf->currency); if (is_numeric($pricesell)) {
else print $langs->trans($pricesell); print price($pricesell, '', '', 0, 0, -1, $conf->currency);
} else {
print $langs->trans($pricesell);
}
print '</td>'; print '</td>';
// Stock // Stock
if (!empty($conf->stock->enabled)) print '<td class="right">'.$value['stock'].'</td>'; // Real stock if (!empty($conf->stock->enabled)) {
print '<td class="right">'.$value['stock'].'</td>'; // Real stock
}
// Qty + IncDec // Qty + IncDec
if ($user->rights->produit->creer || $user->rights->service->creer) if ($user->rights->produit->creer || $user->rights->service->creer) {
{
print '<td class="center"><input type="text" value="'.$nb_of_subproduct.'" name="TProduct['.$productstatic->id.'][qty]" size="4" class="right" /></td>'; print '<td class="center"><input type="text" value="'.$nb_of_subproduct.'" name="TProduct['.$productstatic->id.'][qty]" size="4" class="right" /></td>';
print '<td class="center"><input type="checkbox" name="TProduct['.$productstatic->id.'][incdec]" value="1" '.($value['incdec'] == 1 ? 'checked' : '').' /></td>'; print '<td class="center"><input type="checkbox" name="TProduct['.$productstatic->id.'][incdec]" value="1" '.($value['incdec'] == 1 ? 'checked' : '').' /></td>';
} else { } else {
@ -383,14 +385,18 @@ if ($id > 0 || !empty($ref))
print '</tr>'."\n"; print '</tr>'."\n";
} else { } else {
$hide = ''; $hide = '';
if (empty($conf->global->PRODUCT_SHOW_SUB_SUB_PRODUCTS)) $hide = ' hideobject'; // By default, we do not show this. It makes screen very difficult to understand if (empty($conf->global->PRODUCT_SHOW_SUB_SUB_PRODUCTS)) {
$hide = ' hideobject'; // By default, we do not show this. It makes screen very difficult to understand
}
print '<tr class="oddeven'.$hide.'" id="sub-'.$value['id_parent'].'">'; print '<tr class="oddeven'.$hide.'" id="sub-'.$value['id_parent'].'">';
//$productstatic->ref=$value['label']; //$productstatic->ref=$value['label'];
$productstatic->ref = $value['ref']; $productstatic->ref = $value['ref'];
print '<td>'; print '<td>';
for ($i = 0; $i < $value['level']; $i++) print ' &nbsp; &nbsp; '; // Add indentation for ($i = 0; $i < $value['level']; $i++) {
print ' &nbsp; &nbsp; '; // Add indentation
}
print $productstatic->getNomUrl(1, 'composition').'</td>'; print $productstatic->getNomUrl(1, 'composition').'</td>';
print '<td>'.$productstatic->label.'</td>'; print '<td>'.$productstatic->label.'</td>';
@ -401,7 +407,9 @@ if ($id > 0 || !empty($ref))
print '<td>&nbsp;</td>'; print '<td>&nbsp;</td>';
print '<td>&nbsp;</td>'; print '<td>&nbsp;</td>';
if (!empty($conf->stock->enabled)) print '<td></td>'; // Real stock if (!empty($conf->stock->enabled)) {
print '<td></td>'; // Real stock
}
print '<td class="center">'.$value['nb'].'</td>'; print '<td class="center">'.$value['nb'].'</td>';
print '<td>&nbsp;</td>'; print '<td>&nbsp;</td>';
@ -419,7 +427,9 @@ if ($id > 0 || !empty($ref))
print '</td>'; print '</td>';
print '<td class="liste_total right">'; print '<td class="liste_total right">';
if ($atleastonenotdefined) print $langs->trans("Unknown").' ('.$langs->trans("SomeSubProductHaveNoPrices").')'; if ($atleastonenotdefined) {
print $langs->trans("Unknown").' ('.$langs->trans("SomeSubProductHaveNoPrices").')';
}
print ($atleastonenotdefined ? '' : price($total, '', '', 0, 0, -1, $conf->currency)); print ($atleastonenotdefined ? '' : price($total, '', '', 0, 0, -1, $conf->currency));
print '</td>'; print '</td>';
@ -429,23 +439,28 @@ if ($id > 0 || !empty($ref))
print '</td>'; print '</td>';
print '<td class="liste_total right">'; print '<td class="liste_total right">';
if ($atleastonenotdefined) print $langs->trans("Unknown").' ('.$langs->trans("SomeSubProductHaveNoPrices").')'; if ($atleastonenotdefined) {
print $langs->trans("Unknown").' ('.$langs->trans("SomeSubProductHaveNoPrices").')';
}
print ($atleastonenotdefined ? '' : price($totalsell, '', '', 0, 0, -1, $conf->currency)); print ($atleastonenotdefined ? '' : price($totalsell, '', '', 0, 0, -1, $conf->currency));
print '</td>'; print '</td>';
// Stock // Stock
if (!empty($conf->stock->enabled)) print '<td class="liste_total right">&nbsp;</td>'; if (!empty($conf->stock->enabled)) {
print '<td class="liste_total right">&nbsp;</td>';
}
print '<td class="right" colspan="2">'; print '<td class="right" colspan="2">';
if ($user->rights->produit->creer || $user->rights->service->creer) if ($user->rights->produit->creer || $user->rights->service->creer) {
{
print '<input type="submit" class="button button-save" value="'.$langs->trans("Save").'">'; print '<input type="submit" class="button button-save" value="'.$langs->trans("Save").'">';
} }
print '</td>'; print '</td>';
print '</tr>'."\n"; print '</tr>'."\n";
} else { } else {
$colspan = 8; $colspan = 8;
if (!empty($conf->stock->enabled)) $colspan++; if (!empty($conf->stock->enabled)) {
$colspan++;
}
print '<tr class="oddeven">'; print '<tr class="oddeven">';
print '<td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("None").'</td>'; print '<td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("None").'</td>';
@ -464,12 +479,13 @@ if ($id > 0 || !empty($ref))
// Form with product to add // Form with product to add
if ((empty($action) || $action == 'view' || $action == 'edit' || $action == 'search' || $action == 're-edit') && ($user->rights->produit->creer || $user->rights->service->creer)) if ((empty($action) || $action == 'view' || $action == 'edit' || $action == 'search' || $action == 're-edit') && ($user->rights->produit->creer || $user->rights->service->creer)) {
{
print '<br>'; print '<br>';
$rowspan = 1; $rowspan = 1;
if (!empty($conf->categorie->enabled)) $rowspan++; if (!empty($conf->categorie->enabled)) {
$rowspan++;
}
print load_fiche_titre($langs->trans("ProductToAddSearch"), '', ''); print load_fiche_titre($langs->trans("ProductToAddSearch"), '', '');
print '<form action="'.DOL_URL_ROOT.'/product/composition/card.php?id='.$id.'" method="POST">'; print '<form action="'.DOL_URL_ROOT.'/product/composition/card.php?id='.$id.'" method="POST">';
@ -480,8 +496,7 @@ if ($id > 0 || !empty($ref))
print $langs->trans("KeywordFilter").': '; print $langs->trans("KeywordFilter").': ';
print '<input type="text" name="key" value="'.$key.'"> &nbsp; '; print '<input type="text" name="key" value="'.$key.'"> &nbsp; ';
print '</div>'; print '</div>';
if (!empty($conf->categorie->enabled)) if (!empty($conf->categorie->enabled)) {
{
require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
print '<div class="inline-block">'.$langs->trans("CategoryFilter").': '; print '<div class="inline-block">'.$langs->trans("CategoryFilter").': ';
print $form->select_all_categories(Categorie::TYPE_PRODUCT, $parent, 'parent').' &nbsp; </div>'; print $form->select_all_categories(Categorie::TYPE_PRODUCT, $parent, 'parent').' &nbsp; </div>';
@ -495,8 +510,7 @@ if ($id > 0 || !empty($ref))
// List of products // List of products
if ($action == 'search') if ($action == 'search') {
{
print '<br>'; print '<br>';
print '<form action="'.DOL_URL_ROOT.'/product/composition/card.php?id='.$id.'" method="post">'; print '<form action="'.DOL_URL_ROOT.'/product/composition/card.php?id='.$id.'" method="post">';
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
@ -510,20 +524,19 @@ if ($id > 0 || !empty($ref))
print '<th class="liste_titre right">'.$langs->trans("Qty").'</td>'; print '<th class="liste_titre right">'.$langs->trans("Qty").'</td>';
print '<th class="center">'.$langs->trans('ComposedProductIncDecStock').'</th>'; print '<th class="center">'.$langs->trans('ComposedProductIncDecStock').'</th>';
print '</tr>'; print '</tr>';
if ($resql) if ($resql) {
{
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
$i = 0; $i = 0;
if ($num == 0) print '<tr><td colspan="4">'.$langs->trans("NoMatchFound").'</td></tr>'; if ($num == 0) {
print '<tr><td colspan="4">'.$langs->trans("NoMatchFound").'</td></tr>';
}
$MAX = 100; $MAX = 100;
while ($i < min($num, $MAX)) while ($i < min($num, $MAX)) {
{
$objp = $db->fetch_object($resql); $objp = $db->fetch_object($resql);
if ($objp->rowid != $id) if ($objp->rowid != $id) {
{
// check if a product is not already a parent product of this one // check if a product is not already a parent product of this one
$prod_arbo = new Product($db); $prod_arbo = new Product($db);
$prod_arbo->id = $objp->rowid; $prod_arbo->id = $objp->rowid;
@ -560,13 +573,14 @@ if ($id > 0 || !empty($ref))
print '<td>'.$productstatic->getNomUrl(1, '', 24).'</td>'; print '<td>'.$productstatic->getNomUrl(1, '', 24).'</td>';
$labeltoshow = $objp->label; $labeltoshow = $objp->label;
if ($conf->global->MAIN_MULTILANGS && $objp->labelm) $labeltoshow = $objp->labelm; if ($conf->global->MAIN_MULTILANGS && $objp->labelm) {
$labeltoshow = $objp->labelm;
}
print '<td>'.$labeltoshow.'</td>'; print '<td>'.$labeltoshow.'</td>';
if ($object->is_sousproduit($id, $objp->rowid)) if ($object->is_sousproduit($id, $objp->rowid)) {
{
//$addchecked = ' checked'; //$addchecked = ' checked';
$qty = $object->is_sousproduit_qty; $qty = $object->is_sousproduit_qty;
$incdec = $object->is_sousproduit_incdec; $incdec = $object->is_sousproduit_incdec;
@ -583,8 +597,9 @@ if ($id > 0 || !empty($ref))
// Inc Dec // Inc Dec
print '<td class="center">'; print '<td class="center">';
if ($qty) print '<input type="checkbox" name="prod_incdec_'.$i.'" value="1" '.($incdec ? 'checked' : '').'>'; if ($qty) {
else { print '<input type="checkbox" name="prod_incdec_'.$i.'" value="1" '.($incdec ? 'checked' : '').'>';
} else {
// TODO Hide field and show it when setting a qty // TODO Hide field and show it when setting a qty
print '<input type="checkbox" name="prod_incdec_'.$i.'" value="1" checked>'; print '<input type="checkbox" name="prod_incdec_'.$i.'" value="1" checked>';
//print '<input type="checkbox" disabled name="prod_incdec_'.$i.'" value="1" checked>'; //print '<input type="checkbox" disabled name="prod_incdec_'.$i.'" value="1" checked>';
@ -609,8 +624,7 @@ if ($id > 0 || !empty($ref))
print '</table>'; print '</table>';
print '<input type="hidden" name="max_prod" value="'.$i.'">'; print '<input type="hidden" name="max_prod" value="'.$i.'">';
if ($num > 0) if ($num > 0) {
{
print '<br><div class="center">'; print '<br><div class="center">';
print '<input type="submit" class="button" name="save" value="'.$langs->trans("Add").'/'.$langs->trans("Update").'">'; print '<input type="submit" class="button" name="save" value="'.$langs->trans("Add").'/'.$langs->trans("Update").'">';
print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';

View File

@ -34,8 +34,9 @@ require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.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/lib/images.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
if (!empty($conf->global->PRODUIT_PDF_MERGE_PROPAL)) if (!empty($conf->global->PRODUIT_PDF_MERGE_PROPAL)) {
require_once DOL_DOCUMENT_ROOT.'/product/class/propalmergepdfproduct.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/propalmergepdfproduct.class.php';
}
// Load translation files required by the page // Load translation files required by the page
$langs->loadLangs(array('other', 'products')); $langs->loadLangs(array('other', 'products'));
@ -48,7 +49,9 @@ $confirm = GETPOST('confirm', 'alpha');
// Security check // Security check
$fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : '')); $fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : ''));
$fieldtype = (!empty($ref) ? 'ref' : 'rowid'); $fieldtype = (!empty($ref) ? 'ref' : 'rowid');
if ($user->socid) $socid = $user->socid; if ($user->socid) {
$socid = $user->socid;
}
$result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype);
// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
@ -59,26 +62,36 @@ $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST("sortfield", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if (!$sortorder) $sortorder = "ASC"; if (!$sortorder) {
if (!$sortfield) $sortfield = "position_name"; $sortorder = "ASC";
}
if (!$sortfield) {
$sortfield = "position_name";
}
$object = new Product($db); $object = new Product($db);
if ($id > 0 || !empty($ref)) if ($id > 0 || !empty($ref)) {
{
$result = $object->fetch($id, $ref); $result = $object->fetch($id, $ref);
if (!empty($conf->product->enabled)) $upload_dir = $conf->product->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, 'product'); if (!empty($conf->product->enabled)) {
elseif (!empty($conf->service->enabled)) $upload_dir = $conf->service->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, 'product'); $upload_dir = $conf->product->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, 'product');
} elseif (!empty($conf->service->enabled)) {
$upload_dir = $conf->service->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, 'product');
}
if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) // For backward compatiblity, we scan also old dirs if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) { // For backward compatiblity, we scan also old dirs
{ if (!empty($conf->product->enabled)) {
if (!empty($conf->product->enabled)) $upload_dirold = $conf->product->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2), 1, 1).'/'.substr(substr("000".$object->id, -2), 0, 1).'/'.$object->id."/photos"; $upload_dirold = $conf->product->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2), 1, 1).'/'.substr(substr("000".$object->id, -2), 0, 1).'/'.$object->id."/photos";
else $upload_dirold = $conf->service->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2), 1, 1).'/'.substr(substr("000".$object->id, -2), 0, 1).'/'.$object->id."/photos"; } else {
$upload_dirold = $conf->service->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2), 1, 1).'/'.substr(substr("000".$object->id, -2), 0, 1).'/'.$object->id."/photos";
}
} }
} }
$modulepart = 'produit'; $modulepart = 'produit';
@ -92,15 +105,14 @@ $permissiontoadd = (($object->type == Product::TYPE_PRODUCT && $user->rights->pr
$parameters = array('id'=>$id); $parameters = array('id'=>$id);
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if (empty($reshook)) if (empty($reshook)) {
{
// Delete line if product propal merge is linked to a file // Delete line if product propal merge is linked to a file
if (!empty($conf->global->PRODUIT_PDF_MERGE_PROPAL)) if (!empty($conf->global->PRODUIT_PDF_MERGE_PROPAL)) {
{ if ($action == 'confirm_deletefile' && $confirm == 'yes') {
if ($action == 'confirm_deletefile' && $confirm == 'yes')
{
//extract file name //extract file name
$urlfile = GETPOST('urlfile', 'alpha'); $urlfile = GETPOST('urlfile', 'alpha');
$filename = basename($urlfile); $filename = basename($urlfile);
@ -118,8 +130,7 @@ if (empty($reshook))
include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php';
} }
if ($action == 'filemerge') if ($action == 'filemerge') {
{
$is_refresh = GETPOST('refresh'); $is_refresh = GETPOST('refresh');
if (empty($is_refresh)) { if (empty($is_refresh)) {
$filetomerge_file_array = GETPOST('filetoadd'); $filetomerge_file_array = GETPOST('filetoadd');
@ -171,13 +182,11 @@ $form = new Form($db);
$title = $langs->trans('ProductServiceCard'); $title = $langs->trans('ProductServiceCard');
$helpurl = ''; $helpurl = '';
$shortlabel = dol_trunc($object->label, 16); $shortlabel = dol_trunc($object->label, 16);
if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) {
{
$title = $langs->trans('Product')." ".$shortlabel." - ".$langs->trans('Documents'); $title = $langs->trans('Product')." ".$shortlabel." - ".$langs->trans('Documents');
$helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos'; $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos';
} }
if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) {
{
$title = $langs->trans('Service')." ".$shortlabel." - ".$langs->trans('Documents'); $title = $langs->trans('Service')." ".$shortlabel." - ".$langs->trans('Documents');
$helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios'; $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios';
} }
@ -185,8 +194,7 @@ if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE))
llxHeader('', $title, $helpurl); llxHeader('', $title, $helpurl);
if ($object->id) if ($object->id) {
{
$head = product_prepare_head($object); $head = product_prepare_head($object);
$titre = $langs->trans("CardProduct".$object->type); $titre = $langs->trans("CardProduct".$object->type);
$picto = ($object->type == Product::TYPE_SERVICE ? 'service' : 'product'); $picto = ($object->type == Product::TYPE_SERVICE ? 'service' : 'product');
@ -196,20 +204,20 @@ if ($object->id)
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $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 $hookmanager->resPrint;
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
// Build file list // Build file list
$filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) // For backward compatiblity, we scan also old dirs if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) { // For backward compatiblity, we scan also old dirs
{
$filearrayold = dol_dir_list($upload_dirold, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $filearrayold = dol_dir_list($upload_dirold, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
$filearray = array_merge($filearray, $filearrayold); $filearray = array_merge($filearray, $filearrayold);
} }
$totalsize = 0; $totalsize = 0;
foreach ($filearray as $key => $file) foreach ($filearray as $key => $file) {
{
$totalsize += $file['size']; $totalsize += $file['size'];
} }
@ -218,7 +226,9 @@ if ($object->id)
$object->next_prev_filter = " fk_product_type = ".$object->type; $object->next_prev_filter = " fk_product_type = ".$object->type;
$shownav = 1; $shownav = 1;
if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) {
$shownav = 0;
}
dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref');
@ -241,8 +251,7 @@ if ($object->id)
// Merge propal PDF document PDF files // Merge propal PDF document PDF files
if (!empty($conf->global->PRODUIT_PDF_MERGE_PROPAL)) if (!empty($conf->global->PRODUIT_PDF_MERGE_PROPAL)) {
{
$filetomerge = new Propalmergepdfproduct($db); $filetomerge = new Propalmergepdfproduct($db);
if ($conf->global->MAIN_MULTILANGS) { if ($conf->global->MAIN_MULTILANGS) {
@ -257,14 +266,12 @@ if ($object->id)
$filearray = dol_dir_list($upload_dir, "files", 0, '', '\.meta$', 'name', SORT_ASC, 1); $filearray = dol_dir_list($upload_dir, "files", 0, '', '\.meta$', 'name', SORT_ASC, 1);
if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) // For backward compatiblity, we scan also old dirs if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) { // For backward compatiblity, we scan also old dirs
{
$filearray = array_merge($filearray, dol_dir_list($upload_dirold, "files", 0, '', '\.meta$', 'name', SORT_ASC, 1)); $filearray = array_merge($filearray, dol_dir_list($upload_dirold, "files", 0, '', '\.meta$', 'name', SORT_ASC, 1));
} }
// For each file build select list with PDF extention // For each file build select list with PDF extention
if (count($filearray) > 0) if (count($filearray) > 0) {
{
print '<br>'; print '<br>';
// Actual file to merge is : // Actual file to merge is :
if (count($filetomerge->lines) > 0) { if (count($filetomerge->lines) > 0) {
@ -299,23 +306,18 @@ if ($object->id)
print '</td></tr>'; print '</td></tr>';
} }
foreach ($filearray as $filetoadd) foreach ($filearray as $filetoadd) {
{ if ($ext = pathinfo($filetoadd['name'], PATHINFO_EXTENSION) == 'pdf') {
if ($ext = pathinfo($filetoadd['name'], PATHINFO_EXTENSION) == 'pdf')
{
$checked = ''; $checked = '';
$filename = $filetoadd['name']; $filename = $filetoadd['name'];
if ($conf->global->MAIN_MULTILANGS) if ($conf->global->MAIN_MULTILANGS) {
{ if (array_key_exists($filetoadd['name'].'_'.$default_lang, $filetomerge->lines)) {
if (array_key_exists($filetoadd['name'].'_'.$default_lang, $filetomerge->lines))
{
$filename = $filetoadd['name'].' - '.$langs->trans('Language_'.$default_lang); $filename = $filetoadd['name'].' - '.$langs->trans('Language_'.$default_lang);
$checked = ' checked '; $checked = ' checked ';
} }
} else { } else {
if (array_key_exists($filetoadd['name'], $filetomerge->lines)) if (array_key_exists($filetoadd['name'], $filetomerge->lines)) {
{
$checked = ' checked '; $checked = ' checked ';
} }
} }

View File

@ -80,8 +80,12 @@ class PriceExpression
$error = 0; $error = 0;
// Clean parameters // Clean parameters
if (isset($this->title)) $this->title = trim($this->title); if (isset($this->title)) {
if (isset($this->expression)) $this->expression = trim($this->expression); $this->title = trim($this->title);
}
if (isset($this->expression)) {
$this->expression = trim($this->expression);
}
// Insert request // Insert request
$sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." ("; $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." (";
@ -95,10 +99,11 @@ class PriceExpression
dol_syslog(__METHOD__, LOG_DEBUG); dol_syslog(__METHOD__, LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } if (!$resql) {
$error++; $this->errors[] = "Error ".$this->db->lasterror();
}
if (!$error) if (!$error) {
{
$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
//if (! $notrigger) //if (! $notrigger)
@ -114,10 +119,8 @@ class PriceExpression
} }
// Commit or rollback // Commit or rollback
if ($error) if ($error) {
{ foreach ($this->errors as $errmsg) {
foreach ($this->errors as $errmsg)
{
dol_syslog(__METHOD__." ".$errmsg, LOG_ERR); dol_syslog(__METHOD__." ".$errmsg, LOG_ERR);
$this->error .= ($this->error ? ', '.$errmsg : $errmsg); $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
} }
@ -139,8 +142,7 @@ class PriceExpression
public function fetch($id) public function fetch($id)
{ {
// Check parameters // Check parameters
if (empty($id)) if (empty($id)) {
{
$this->error = 'ErrorWrongParameters'; $this->error = 'ErrorWrongParameters';
return -1; return -1;
} }
@ -151,11 +153,9 @@ class PriceExpression
dol_syslog(__METHOD__); dol_syslog(__METHOD__);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
if ($obj) if ($obj) {
{
$this->id = $id; $this->id = $id;
$this->title = $obj->title; $this->title = $obj->title;
$this->expression = $obj->expression; $this->expression = $obj->expression;
@ -184,12 +184,10 @@ class PriceExpression
dol_syslog(__METHOD__, LOG_DEBUG); dol_syslog(__METHOD__, LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{
$retarray = array(); $retarray = array();
while ($record = $this->db->fetch_array($resql)) while ($record = $this->db->fetch_array($resql)) {
{
$price_expression_obj = new PriceExpression($this->db); $price_expression_obj = new PriceExpression($this->db);
$price_expression_obj->id = $record["rowid"]; $price_expression_obj->id = $record["rowid"];
$price_expression_obj->title = $record["title"]; $price_expression_obj->title = $record["title"];
@ -222,11 +220,9 @@ class PriceExpression
dol_syslog(__METHOD__, LOG_DEBUG); dol_syslog(__METHOD__, LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
if ($obj) if ($obj) {
{
return (int) $obj->rowid; return (int) $obj->rowid;
} else { } else {
return 0; return 0;
@ -250,8 +246,12 @@ class PriceExpression
$error = 0; $error = 0;
// Clean parameters // Clean parameters
if (isset($this->title)) $this->title = trim($this->title); if (isset($this->title)) {
if (isset($this->expression)) $this->expression = trim($this->expression); $this->title = trim($this->title);
}
if (isset($this->expression)) {
$this->expression = trim($this->expression);
}
// Update request // Update request
$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET"; $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
@ -263,7 +263,9 @@ class PriceExpression
dol_syslog(__METHOD__); dol_syslog(__METHOD__);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } if (!$resql) {
$error++; $this->errors[] = "Error ".$this->db->lasterror();
}
// if (! $error) // if (! $error)
// { // {
@ -280,10 +282,8 @@ class PriceExpression
// } // }
// Commit or rollback // Commit or rollback
if ($error) if ($error) {
{ foreach ($this->errors as $errmsg) {
foreach ($this->errors as $errmsg)
{
dol_syslog(__METHOD__." ".$errmsg, LOG_ERR); dol_syslog(__METHOD__." ".$errmsg, LOG_ERR);
$this->error .= ($this->error ? ', '.$errmsg : $errmsg); $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
} }
@ -325,21 +325,20 @@ class PriceExpression
// } // }
//} //}
if (!$error) if (!$error) {
{
$sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element; $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element;
$sql .= " WHERE rowid = ".$rowid; $sql .= " WHERE rowid = ".$rowid;
dol_syslog(__METHOD__); dol_syslog(__METHOD__);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } if (!$resql) {
$error++; $this->errors[] = "Error ".$this->db->lasterror();
}
} }
// Commit or rollback // Commit or rollback
if ($error) if ($error) {
{ foreach ($this->errors as $errmsg) {
foreach ($this->errors as $errmsg)
{
dol_syslog(__METHOD__." ".$errmsg, LOG_ERR); dol_syslog(__METHOD__." ".$errmsg, LOG_ERR);
$this->error .= ($this->error ? ', '.$errmsg : $errmsg); $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
} }

View File

@ -100,14 +100,14 @@ class PriceGlobalVariable
dol_syslog(__METHOD__); dol_syslog(__METHOD__);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } if (!$resql) {
$error++; $this->errors[] = "Error ".$this->db->lasterror();
}
if (!$error) if (!$error) {
{
$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
if (!$notrigger) if (!$notrigger) {
{
// Uncomment this and change MYOBJECT to your own tag if you // Uncomment this and change MYOBJECT to your own tag if you
// want this action calls a trigger. // want this action calls a trigger.
@ -119,10 +119,8 @@ class PriceGlobalVariable
} }
// Commit or rollback // Commit or rollback
if ($error) if ($error) {
{ foreach ($this->errors as $errmsg) {
foreach ($this->errors as $errmsg)
{
dol_syslog(__METHOD__." ".$errmsg, LOG_ERR); dol_syslog(__METHOD__." ".$errmsg, LOG_ERR);
$this->error .= ($this->error ? ', '.$errmsg : $errmsg); $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
} }
@ -149,11 +147,9 @@ class PriceGlobalVariable
dol_syslog(__METHOD__); dol_syslog(__METHOD__);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
if ($obj) if ($obj) {
{
$this->id = $id; $this->id = $id;
$this->code = $obj->code; $this->code = $obj->code;
$this->description = $obj->description; $this->description = $obj->description;
@ -193,7 +189,9 @@ class PriceGlobalVariable
dol_syslog(__METHOD__); dol_syslog(__METHOD__);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } if (!$resql) {
$error++; $this->errors[] = "Error ".$this->db->lasterror();
}
// if (! $error) // if (! $error)
// { // {
@ -210,10 +208,8 @@ class PriceGlobalVariable
// } // }
// Commit or rollback // Commit or rollback
if ($error) if ($error) {
{ foreach ($this->errors as $errmsg) {
foreach ($this->errors as $errmsg)
{
dol_syslog(__METHOD__." ".$errmsg, LOG_ERR); dol_syslog(__METHOD__." ".$errmsg, LOG_ERR);
$this->error .= ($this->error ? ', '.$errmsg : $errmsg); $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
} }
@ -240,10 +236,8 @@ class PriceGlobalVariable
$this->db->begin(); $this->db->begin();
if (!$error) if (!$error) {
{ if (!$notrigger) {
if (!$notrigger)
{
// Uncomment this and change MYOBJECT to your own tag if you // Uncomment this and change MYOBJECT to your own tag if you
// want this action calls a trigger. // want this action calls a trigger.
@ -254,21 +248,20 @@ class PriceGlobalVariable
} }
} }
if (!$error) if (!$error) {
{
$sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element; $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element;
$sql .= " WHERE rowid = ".$rowid; $sql .= " WHERE rowid = ".$rowid;
dol_syslog(__METHOD__); dol_syslog(__METHOD__);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } if (!$resql) {
$error++; $this->errors[] = "Error ".$this->db->lasterror();
}
} }
// Commit or rollback // Commit or rollback
if ($error) if ($error) {
{ foreach ($this->errors as $errmsg) {
foreach ($this->errors as $errmsg)
{
dol_syslog(__METHOD__." ".$errmsg, LOG_ERR); dol_syslog(__METHOD__." ".$errmsg, LOG_ERR);
$this->error .= ($this->error ? ', '.$errmsg : $errmsg); $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
} }
@ -302,11 +295,17 @@ class PriceGlobalVariable
public function checkParameters() public function checkParameters()
{ {
// Clean parameters // Clean parameters
if (isset($this->code)) $this->code = trim($this->code); if (isset($this->code)) {
if (isset($this->description)) $this->description = trim($this->description); $this->code = trim($this->code);
}
if (isset($this->description)) {
$this->description = trim($this->description);
}
// Check parameters // Check parameters
if (empty($this->value) || !is_numeric($this->value)) $this->value = 0; if (empty($this->value) || !is_numeric($this->value)) {
$this->value = 0;
}
} }
/** /**
@ -322,12 +321,10 @@ class PriceGlobalVariable
dol_syslog(__METHOD__, LOG_DEBUG); dol_syslog(__METHOD__, LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{
$retarray = array(); $retarray = array();
while ($record = $this->db->fetch_array($resql)) while ($record = $this->db->fetch_array($resql)) {
{
$variable_obj = new PriceGlobalVariable($this->db); $variable_obj = new PriceGlobalVariable($this->db);
$variable_obj->id = $record["rowid"]; $variable_obj->id = $record["rowid"];
$variable_obj->code = $record["code"]; $variable_obj->code = $record["code"];

View File

@ -116,14 +116,14 @@ class PriceGlobalVariableUpdater
dol_syslog(__METHOD__, LOG_DEBUG); dol_syslog(__METHOD__, LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } if (!$resql) {
$error++; $this->errors[] = "Error ".$this->db->lasterror();
}
if (!$error) if (!$error) {
{
$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
if (!$notrigger) if (!$notrigger) {
{
// Uncomment this and change MYOBJECT to your own tag if you // Uncomment this and change MYOBJECT to your own tag if you
// want this action calls a trigger. // want this action calls a trigger.
@ -135,10 +135,8 @@ class PriceGlobalVariableUpdater
} }
// Commit or rollback // Commit or rollback
if ($error) if ($error) {
{ foreach ($this->errors as $errmsg) {
foreach ($this->errors as $errmsg)
{
dol_syslog(__METHOD__." ".$errmsg, LOG_ERR); dol_syslog(__METHOD__." ".$errmsg, LOG_ERR);
$this->error .= ($this->error ? ', '.$errmsg : $errmsg); $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
} }
@ -165,11 +163,9 @@ class PriceGlobalVariableUpdater
dol_syslog(__METHOD__); dol_syslog(__METHOD__);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
if ($obj) if ($obj) {
{
$this->id = $id; $this->id = $id;
$this->type = $obj->type; $this->type = $obj->type;
$this->description = $obj->description; $this->description = $obj->description;
@ -217,7 +213,9 @@ class PriceGlobalVariableUpdater
dol_syslog(__METHOD__); dol_syslog(__METHOD__);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } if (!$resql) {
$error++; $this->errors[] = "Error ".$this->db->lasterror();
}
// if (! $error) // if (! $error)
// { // {
@ -234,10 +232,8 @@ class PriceGlobalVariableUpdater
// } // }
// Commit or rollback // Commit or rollback
if ($error) if ($error) {
{ foreach ($this->errors as $errmsg) {
foreach ($this->errors as $errmsg)
{
dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
$this->error .= ($this->error ? ', '.$errmsg : $errmsg); $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
} }
@ -277,21 +273,20 @@ class PriceGlobalVariableUpdater
// } // }
//} //}
if (!$error) if (!$error) {
{
$sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element; $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element;
$sql .= " WHERE rowid = ".$rowid; $sql .= " WHERE rowid = ".$rowid;
dol_syslog(__METHOD__); dol_syslog(__METHOD__);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } if (!$resql) {
$error++; $this->errors[] = "Error ".$this->db->lasterror();
}
} }
// Commit or rollback // Commit or rollback
if ($error) if ($error) {
{ foreach ($this->errors as $errmsg) {
foreach ($this->errors as $errmsg)
{
dol_syslog(__METHOD__." ".$errmsg, LOG_ERR); dol_syslog(__METHOD__." ".$errmsg, LOG_ERR);
$this->error .= ($this->error ? ', '.$errmsg : $errmsg); $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
} }
@ -345,15 +340,28 @@ class PriceGlobalVariableUpdater
public function checkParameters() public function checkParameters()
{ {
// Clean parameters // Clean parameters
if (isset($this->description)) $this->description = trim($this->description); if (isset($this->description)) {
if (isset($this->parameters)) $this->parameters = trim($this->parameters); $this->description = trim($this->description);
else $this->parameters = ""; }
if (isset($this->last_status)) $this->last_status = trim($this->last_status); if (isset($this->parameters)) {
$this->parameters = trim($this->parameters);
} else {
$this->parameters = "";
}
if (isset($this->last_status)) {
$this->last_status = trim($this->last_status);
}
// Check parameters // Check parameters
if (empty($this->type) || !is_numeric($this->type) || !in_array($this->type, $this->types)) $this->type = 0; if (empty($this->type) || !is_numeric($this->type) || !in_array($this->type, $this->types)) {
if (empty($this->update_interval) || !is_numeric($this->update_interval) || $this->update_interval < 1) $this->update_interval = $this->update_min; $this->type = 0;
if (empty($this->next_update) || !is_numeric($this->next_update) || $this->next_update < 0) $this->next_update = 0; }
if (empty($this->update_interval) || !is_numeric($this->update_interval) || $this->update_interval < 1) {
$this->update_interval = $this->update_min;
}
if (empty($this->next_update) || !is_numeric($this->next_update) || $this->next_update < 0) {
$this->next_update = 0;
}
} }
/** /**
@ -368,12 +376,10 @@ class PriceGlobalVariableUpdater
dol_syslog(__METHOD__, LOG_DEBUG); dol_syslog(__METHOD__, LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{
$retarray = array(); $retarray = array();
while ($record = $this->db->fetch_array($resql)) while ($record = $this->db->fetch_array($resql)) {
{
$updater_obj = new PriceGlobalVariableUpdater($this->db); $updater_obj = new PriceGlobalVariableUpdater($this->db);
$updater_obj->id = $record["rowid"]; $updater_obj->id = $record["rowid"];
$updater_obj->type = $record["type"]; $updater_obj->type = $record["type"];
@ -408,12 +414,10 @@ class PriceGlobalVariableUpdater
dol_syslog(__METHOD__, LOG_DEBUG); dol_syslog(__METHOD__, LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{
$retarray = array(); $retarray = array();
while ($record = $this->db->fetch_array($resql)) while ($record = $this->db->fetch_array($resql)) {
{
$updater_obj = new PriceGlobalVariableUpdater($this->db); $updater_obj = new PriceGlobalVariableUpdater($this->db);
$updater_obj->id = $record["rowid"]; $updater_obj->id = $record["rowid"];
$updater_obj->type = $record["type"]; $updater_obj->type = $record["type"];
@ -572,13 +576,13 @@ class PriceGlobalVariableUpdater
dol_syslog(__METHOD__); dol_syslog(__METHOD__);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } if (!$resql) {
$error++; $this->errors[] = "Error ".$this->db->lasterror();
}
// Commit or rollback // Commit or rollback
if ($error) if ($error) {
{ foreach ($this->errors as $errmsg) {
foreach ($this->errors as $errmsg)
{
dol_syslog(__METHOD__." ".$errmsg, LOG_ERR); dol_syslog(__METHOD__." ".$errmsg, LOG_ERR);
$this->error .= ($this->error ? ', '.$errmsg : $errmsg); $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
} }
@ -616,13 +620,13 @@ class PriceGlobalVariableUpdater
dol_syslog(__METHOD__); dol_syslog(__METHOD__);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } if (!$resql) {
$error++; $this->errors[] = "Error ".$this->db->lasterror();
}
// Commit or rollback // Commit or rollback
if ($error) if ($error) {
{ foreach ($this->errors as $errmsg) {
foreach ($this->errors as $errmsg)
{
dol_syslog(__METHOD__." ".$errmsg, LOG_ERR); dol_syslog(__METHOD__." ".$errmsg, LOG_ERR);
$this->error .= ($this->error ? ', '.$errmsg : $errmsg); $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
} }

View File

@ -100,17 +100,13 @@ class PriceParser
return $langs->trans("ErrorPriceExpressionUnknown", 0); //this is not supposed to happen return $langs->trans("ErrorPriceExpressionUnknown", 0); //this is not supposed to happen
} }
list($code, $info) = $this->error_parser; list($code, $info) = $this->error_parser;
if (in_array($code, array(9, 14, 19, 20))) //Errors which have 0 arg if (in_array($code, array(9, 14, 19, 20))) { //Errors which have 0 arg
{
return $langs->trans("ErrorPriceExpression".$code); return $langs->trans("ErrorPriceExpression".$code);
} elseif (in_array($code, array(1, 2, 3, 4, 5, 8, 10, 11, 17, 21, 22))) //Errors which have 1 arg } elseif (in_array($code, array(1, 2, 3, 4, 5, 8, 10, 11, 17, 21, 22))) { //Errors which have 1 arg
{
return $langs->trans("ErrorPriceExpression".$code, $info); return $langs->trans("ErrorPriceExpression".$code, $info);
} elseif (in_array($code, array(6, 23))) //Errors which have 2 args } elseif (in_array($code, array(6, 23))) { //Errors which have 2 args
{
return $langs->trans("ErrorPriceExpression".$code, $info[0], $info[1]); return $langs->trans("ErrorPriceExpression".$code, $info[0], $info[1]);
} elseif (in_array($code, array(7, 12, 13, 15, 16, 18))) //Internal errors } elseif (in_array($code, array(7, 12, 13, 15, 16, 18))) { //Internal errors
{
return $langs->trans("ErrorPriceExpressionInternal", $code); return $langs->trans("ErrorPriceExpressionInternal", $code);
} else //Unknown errors } else //Unknown errors
{ {
@ -140,8 +136,7 @@ class PriceParser
} }
//Check if empty //Check if empty
$expression = trim($expression); $expression = trim($expression);
if (empty($expression)) if (empty($expression)) {
{
$this->error_parser = array(20, null); $this->error_parser = array(20, null);
return -2; return -2;
} }
@ -161,10 +156,8 @@ class PriceParser
$extrafields = new ExtraFields($this->db); $extrafields = new ExtraFields($this->db);
$extrafields->fetch_name_optionals_label('product', true); $extrafields->fetch_name_optionals_label('product', true);
$product->fetch_optionals(); $product->fetch_optionals();
if (is_array($extrafields->attributes[$product->table_element]['label'])) if (is_array($extrafields->attributes[$product->table_element]['label'])) {
{ foreach ($extrafields->attributes[$product->table_element]['label'] as $key => $label) {
foreach ($extrafields->attributes[$product->table_element]['label'] as $key=>$label)
{
$values["extrafield_".$key] = $product->array_options['options_'.$key]; $values["extrafield_".$key] = $product->array_options['options_'.$key];
} }
} }
@ -182,8 +175,7 @@ class PriceParser
//Get all global values //Get all global values
$price_globals = new PriceGlobalVariable($this->db); $price_globals = new PriceGlobalVariable($this->db);
foreach ($price_globals->listGlobalVariables() as $entry) foreach ($price_globals->listGlobalVariables() as $entry) {
{
$values["global_".$entry->code] = $entry->value; $values["global_".$entry->code] = $entry->value;
} }
@ -198,8 +190,7 @@ class PriceParser
//Fill each variable in expression from values //Fill each variable in expression from values
$expression = str_replace("\n", $this->separator_chr, $expression); $expression = str_replace("\n", $this->separator_chr, $expression);
foreach ($values as $key => $value) foreach ($values as $key => $value) {
{
if ($value === null && strpos($expression, $key) !== false) { if ($value === null && strpos($expression, $key) !== false) {
$this->error_parser = array(24, $key); $this->error_parser = array(24, $key);
return -7; return -7;
@ -208,11 +199,12 @@ class PriceParser
} }
//Check if there is unfilled variable //Check if there is unfilled variable
if (strpos($expression, $this->special_chr) !== false) if (strpos($expression, $this->special_chr) !== false) {
{
$data = explode($this->special_chr, $expression); $data = explode($this->special_chr, $expression);
$variable = $this->special_chr.$data[1]; $variable = $this->special_chr.$data[1];
if (isset($data[2])) $variable .= $this->special_chr; if (isset($data[2])) {
$variable .= $this->special_chr;
}
$this->error_parser = array(23, array($variable, $expression)); $this->error_parser = array(23, array($variable, $expression));
return -6; return -6;
} }
@ -222,8 +214,7 @@ class PriceParser
$expressions = array_slice($expressions, 0, $this->limit); $expressions = array_slice($expressions, 0, $this->limit);
foreach ($expressions as $expr) { foreach ($expressions as $expr) {
$expr = trim($expr); $expr = trim($expr);
if (!empty($expr)) if (!empty($expr)) {
{
$last_result = $em->evaluate($expr); $last_result = $em->evaluate($expr);
$this->error_parser = $em->last_error_code; $this->error_parser = $em->last_error_code;
if ($this->error_parser !== null) { //$em->last_error_code is null if no error happened, so just check if error_parser is not null if ($this->error_parser !== null) { //$em->last_error_code is null if no error happened, so just check if error_parser is not null
@ -236,13 +227,11 @@ class PriceParser
if (empty($vars["price"])) { if (empty($vars["price"])) {
$vars["price"] = $last_result; $vars["price"] = $last_result;
} }
if (!isset($vars["price"])) if (!isset($vars["price"])) {
{
$this->error_parser = array(21, $expression); $this->error_parser = array(21, $expression);
return -4; return -4;
} }
if ($vars["price"] < 0) if ($vars["price"] < 0) {
{
$this->error_parser = array(22, $expression); $this->error_parser = array(22, $expression);
return -5; return -5;
} }
@ -305,8 +294,7 @@ class PriceParser
//Get the expression from db //Get the expression from db
$price_expression = new PriceExpression($this->db); $price_expression = new PriceExpression($this->db);
$res = $price_expression->fetch($product_supplier->fk_supplier_price_expression); $res = $price_expression->fetch($product_supplier->fk_supplier_price_expression);
if ($res < 1) if ($res < 1) {
{
$this->error_parser = array(19, null); $this->error_parser = array(19, null);
return -1; return -1;
} }

View File

@ -51,11 +51,9 @@ $price_expression = new PriceExpression($db);
$price_globals = new PriceGlobalVariable($db); $price_globals = new PriceGlobalVariable($db);
//Fetch expression data //Fetch expression data
if (empty($eid)) //This also disables fetch when eid == 0 if (empty($eid)) { //This also disables fetch when eid == 0
{
$eid = 0; $eid = 0;
} elseif ($action != 'delete') } elseif ($action != 'delete') {
{
$price_expression->fetch($eid); $price_expression->fetch($eid);
} }
@ -64,13 +62,10 @@ if (empty($eid)) //This also disables fetch when eid == 0
* Actions * Actions
*/ */
if ($action == 'add') if ($action == 'add') {
{ if ($eid == 0) {
if ($eid == 0)
{
$result = $price_expression->find_title($title); $result = $price_expression->find_title($title);
if ($result == 0) //No existing entry found with title, ok if ($result == 0) { //No existing entry found with title, ok
{
//Check the expression validity by parsing it //Check the expression validity by parsing it
$priceparser = new PriceParser($db); $priceparser = new PriceParser($db);
$price_result = $priceparser->testExpression($id, $expression); $price_result = $priceparser->testExpression($id, $expression);
@ -80,16 +75,14 @@ if ($action == 'add')
$price_expression->title = $title; $price_expression->title = $title;
$price_expression->expression = $expression; $price_expression->expression = $expression;
$result = $price_expression->create($user); $result = $price_expression->create($user);
if ($result > 0) //created successfully, set the eid to newly created entry if ($result > 0) { //created successfully, set the eid to newly created entry
{
$eid = $price_expression->id; $eid = $price_expression->id;
setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); setEventMessages($langs->trans("RecordSaved"), null, 'mesgs');
} else { } else {
setEventMessages("add: ".$price_expression->error, $price_expression->errors, 'errors'); setEventMessages("add: ".$price_expression->error, $price_expression->errors, 'errors');
} }
} }
} elseif ($result < 0) } elseif ($result < 0) {
{
setEventMessages("add find: ".$price_expression->error, $price_expression->errors, 'errors'); setEventMessages("add find: ".$price_expression->error, $price_expression->errors, 'errors');
} else { } else {
setEventMessages($langs->trans("ErrorRecordAlreadyExists"), null, 'errors'); setEventMessages($langs->trans("ErrorRecordAlreadyExists"), null, 'errors');
@ -97,13 +90,10 @@ if ($action == 'add')
} }
} }
if ($action == 'update') if ($action == 'update') {
{ if ($eid != 0) {
if ($eid != 0)
{
$result = $price_expression->find_title($title); $result = $price_expression->find_title($title);
if ($result == 0 || $result == $eid) //No existing entry found with title or existing one is the current one, ok if ($result == 0 || $result == $eid) { //No existing entry found with title or existing one is the current one, ok
{
//Check the expression validity by parsing it //Check the expression validity by parsing it
$priceparser = new PriceParser($db); $priceparser = new PriceParser($db);
$price_result = $priceparser->testExpression($id, $expression); $price_result = $priceparser->testExpression($id, $expression);
@ -114,15 +104,13 @@ if ($action == 'update')
$price_expression->title = $title; $price_expression->title = $title;
$price_expression->expression = $expression; $price_expression->expression = $expression;
$result = $price_expression->update($user); $result = $price_expression->update($user);
if ($result < 0) if ($result < 0) {
{
setEventMessages("update: ".$price_expression->error, $price_expression->errors, 'errors'); setEventMessages("update: ".$price_expression->error, $price_expression->errors, 'errors');
} else { } else {
setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); setEventMessages($langs->trans("RecordSaved"), null, 'mesgs');
} }
} }
} elseif ($result < 0) } elseif ($result < 0) {
{
setEventMessages("update find: ".$price_expression->error, $price_expression->errors, 'errors'); setEventMessages("update find: ".$price_expression->error, $price_expression->errors, 'errors');
} else { } else {
setEventMessages($langs->trans("ErrorRecordAlreadyExists"), null, 'errors'); setEventMessages($langs->trans("ErrorRecordAlreadyExists"), null, 'errors');
@ -130,14 +118,11 @@ if ($action == 'update')
} }
} }
if ($action == 'delete') if ($action == 'delete') {
{ if ($eid != 0) {
if ($eid != 0)
{
$price_expression->fetch($eid); $price_expression->fetch($eid);
$result = $price_expression->delete($user); $result = $price_expression->delete($user);
if ($result < 0) if ($result < 0) {
{
setEventMessages("delete: ".$price_expression->error, $price_expression->errors, 'errors'); setEventMessages("delete: ".$price_expression->error, $price_expression->errors, 'errors');
} }
$eid = 0; $eid = 0;
@ -202,8 +187,7 @@ print dol_get_fiche_end();
print '<div class="center">'; print '<div class="center">';
print '<input type="submit" class="butAction button-save" value="'.$langs->trans("Save").'">'; print '<input type="submit" class="butAction button-save" value="'.$langs->trans("Save").'">';
print '<span id="back" class="butAction">'.$langs->trans("Back").'</span>'; print '<span id="back" class="butAction">'.$langs->trans("Back").'</span>';
if ($eid == 0) if ($eid == 0) {
{
print '<div class="inline-block divButAction"><span id="action-delete" class="butActionRefused classfortooltip">'.$langs->trans('Delete').'</span></div>'."\n"; print '<div class="inline-block divButAction"><span id="action-delete" class="butActionRefused classfortooltip">'.$langs->trans('Delete').'</span></div>'."\n";
} else { } else {
print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$id.'&amp;tab='.$tab.'&amp;eid='.$eid.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans("Delete").'</a></div>'; print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$id.'&amp;tab='.$tab.'&amp;eid='.$eid.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans("Delete").'</a></div>';

View File

@ -40,7 +40,9 @@ require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_expression.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_expression.class.php';
require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
if (!empty($conf->barcode->enabled)) dol_include_once('/core/class/html.formbarcode.class.php'); if (!empty($conf->barcode->enabled)) {
dol_include_once('/core/class/html.formbarcode.class.php');
}
// Load translation files required by the page // Load translation files required by the page
$langs->loadLangs(array('products', 'suppliers', 'bills', 'margins', 'stocks')); $langs->loadLangs(array('products', 'suppliers', 'bills', 'margins', 'stocks'));
@ -59,8 +61,7 @@ $error = 0;
$extrafields = new ExtraFields($db); $extrafields = new ExtraFields($db);
// If socid provided by ajax company selector // If socid provided by ajax company selector
if (!empty($_REQUEST['search_fourn_id'])) if (!empty($_REQUEST['search_fourn_id'])) {
{
$_GET['id_fourn'] = $_GET['search_fourn_id']; $_GET['id_fourn'] = $_GET['search_fourn_id'];
$_POST['id_fourn'] = $_POST['search_fourn_id']; $_POST['id_fourn'] = $_POST['search_fourn_id'];
$_REQUEST['id_fourn'] = $_REQUEST['search_fourn_id']; $_REQUEST['id_fourn'] = $_REQUEST['search_fourn_id'];
@ -69,62 +70,75 @@ if (!empty($_REQUEST['search_fourn_id']))
// Security check // Security check
$fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : '')); $fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : ''));
$fieldtype = (!empty($ref) ? 'ref' : 'rowid'); $fieldtype = (!empty($ref) ? 'ref' : 'rowid');
if ($user->socid) $socid = $user->socid; if ($user->socid) {
$socid = $user->socid;
}
$result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype);
if (empty($user->rights->fournisseur->lire)) accessforbidden(); if (empty($user->rights->fournisseur->lire)) {
accessforbidden();
}
$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST("sortfield", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha');
$page = (GETPOST("page", 'int') ?GETPOST("page", 'int') : 0); $page = (GETPOST("page", 'int') ?GETPOST("page", 'int') : 0);
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if (!$sortfield) $sortfield = "s.nom"; if (!$sortfield) {
if (!$sortorder) $sortorder = "ASC"; $sortfield = "s.nom";
}
if (!$sortorder) {
$sortorder = "ASC";
}
// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
$hookmanager->initHooks(array('pricesuppliercard', 'globalcard')); $hookmanager->initHooks(array('pricesuppliercard', 'globalcard'));
$object = new ProductFournisseur($db); $object = new ProductFournisseur($db);
if ($id > 0 || $ref) if ($id > 0 || $ref) {
{
$object->fetch($id, $ref); $object->fetch($id, $ref);
} }
$sortfield = GETPOST("sortfield", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha');
if (!$sortfield) $sortfield = "s.nom"; if (!$sortfield) {
if (!$sortorder) $sortorder = "ASC"; $sortfield = "s.nom";
}
if (!$sortorder) {
$sortorder = "ASC";
}
/* /*
* Actions * Actions
*/ */
if ($cancel) $action = ''; if ($cancel) {
$action = '';
}
$usercanread = (($object->type == Product::TYPE_PRODUCT && $user->rights->produit->lire) || ($object->type == Product::TYPE_SERVICE && $user->rights->service->lire)); $usercanread = (($object->type == Product::TYPE_PRODUCT && $user->rights->produit->lire) || ($object->type == Product::TYPE_SERVICE && $user->rights->service->lire));
$usercancreate = (($object->type == Product::TYPE_PRODUCT && $user->rights->produit->creer) || ($object->type == Product::TYPE_SERVICE && $user->rights->service->creer)); $usercancreate = (($object->type == Product::TYPE_PRODUCT && $user->rights->produit->creer) || ($object->type == Product::TYPE_SERVICE && $user->rights->service->creer));
$parameters = array('socid'=>$socid, 'id_prod'=>$id); $parameters = array('socid'=>$socid, 'id_prod'=>$id);
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if (empty($reshook)) if (empty($reshook)) {
{ if ($action == 'setcost_price') {
if ($action == 'setcost_price') if ($id) {
{
if ($id)
{
$result = $object->fetch($id); $result = $object->fetch($id);
$object->cost_price = price2num($cost_price); $object->cost_price = price2num($cost_price);
$result = $object->update($object->id, $user); $result = $object->update($object->id, $user);
if ($result > 0) if ($result > 0) {
{
setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); setEventMessages($langs->trans("RecordSaved"), null, 'mesgs');
$action = ''; $action = '';
} else { } else {
@ -134,10 +148,8 @@ if (empty($reshook))
} }
} }
if ($action == 'confirm_remove_pf') if ($action == 'confirm_remove_pf') {
{ if ($rowid) { // id of product supplier price to remove
if ($rowid) // id of product supplier price to remove
{
$action = ''; $action = '';
$result = $object->remove_product_fournisseur_price($rowid); $result = $object->remove_product_fournisseur_price($rowid);
if ($result > 0) { if ($result > 0) {
@ -150,14 +162,19 @@ if (empty($reshook))
} }
} }
if ($action == 'save_price') if ($action == 'save_price') {
{
$id_fourn = GETPOST("id_fourn"); $id_fourn = GETPOST("id_fourn");
if (empty($id_fourn)) $id_fourn = GETPOST("search_id_fourn"); if (empty($id_fourn)) {
$id_fourn = GETPOST("search_id_fourn");
}
$ref_fourn = GETPOST("ref_fourn"); $ref_fourn = GETPOST("ref_fourn");
if (empty($ref_fourn)) $ref_fourn = GETPOST("search_ref_fourn"); if (empty($ref_fourn)) {
$ref_fourn = GETPOST("search_ref_fourn");
}
$ref_fourn_old = GETPOST("ref_fourn_old"); $ref_fourn_old = GETPOST("ref_fourn_old");
if (empty($ref_fourn_old)) $ref_fourn_old = $ref_fourn; if (empty($ref_fourn_old)) {
$ref_fourn_old = $ref_fourn;
}
$quantity = price2num(GETPOST("qty", 'nohtml'), 'MS'); $quantity = price2num(GETPOST("qty", 'nohtml'), 'MS');
$remise_percent = price2num(GETPOST('remise_percent', 'alpha')); $remise_percent = price2num(GETPOST('remise_percent', 'alpha'));
@ -175,40 +192,33 @@ if (empty($reshook))
$fk_barcode_type = GETPOST('fk_barcode_type', 'int'); $fk_barcode_type = GETPOST('fk_barcode_type', 'int');
$packaging = price2num(GETPOST("packaging", 'alphanohtml'), 'MS'); $packaging = price2num(GETPOST("packaging", 'alphanohtml'), 'MS');
if ($tva_tx == '') if ($tva_tx == '') {
{
$error++; $error++;
$langs->load("errors"); $langs->load("errors");
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("VATRateForSupplierProduct")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("VATRateForSupplierProduct")), null, 'errors');
} }
if (!is_numeric($tva_tx)) if (!is_numeric($tva_tx)) {
{
$error++; $error++;
$langs->load("errors"); $langs->load("errors");
setEventMessages($langs->trans("ErrorFieldMustBeANumeric", $langs->transnoentities("VATRateForSupplierProduct")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldMustBeANumeric", $langs->transnoentities("VATRateForSupplierProduct")), null, 'errors');
} }
if (empty($quantity)) if (empty($quantity)) {
{
$error++; $error++;
$langs->load("errors"); $langs->load("errors");
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Qty")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Qty")), null, 'errors');
} }
if (empty($ref_fourn)) if (empty($ref_fourn)) {
{
$error++; $error++;
$langs->load("errors"); $langs->load("errors");
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("RefSupplier")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("RefSupplier")), null, 'errors');
} }
if ($id_fourn <= 0) if ($id_fourn <= 0) {
{
$error++; $error++;
$langs->load("errors"); $langs->load("errors");
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Supplier")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Supplier")), null, 'errors');
} }
if (price2num($_POST["price"]) < 0 || $_POST["price"] == '') if (price2num($_POST["price"]) < 0 || $_POST["price"] == '') {
{ if ($price_expression === '') { // Return error of missing price only if price_expression not set
if ($price_expression === '') // Return error of missing price only if price_expression not set
{
$error++; $error++;
$langs->load("errors"); $langs->load("errors");
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Price")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Price")), null, 'errors');
@ -234,30 +244,25 @@ if (empty($reshook))
} }
} }
if (!$error) if (!$error) {
{
$db->begin(); $db->begin();
if (!$error) if (!$error) {
{
$ret = $object->add_fournisseur($user, $id_fourn, $ref_fourn_old, $quantity); // This insert record with no value for price. Values are update later with update_buyprice $ret = $object->add_fournisseur($user, $id_fourn, $ref_fourn_old, $quantity); // This insert record with no value for price. Values are update later with update_buyprice
if ($ret == -3) if ($ret == -3) {
{
$error++; $error++;
$object->fetch($object->product_id_already_linked); $object->fetch($object->product_id_already_linked);
$productLink = $object->getNomUrl(1, 'supplier'); $productLink = $object->getNomUrl(1, 'supplier');
setEventMessages($langs->trans("ReferenceSupplierIsAlreadyAssociatedWithAProduct", $productLink), null, 'errors'); setEventMessages($langs->trans("ReferenceSupplierIsAlreadyAssociatedWithAProduct", $productLink), null, 'errors');
} elseif ($ret < 0) } elseif ($ret < 0) {
{
$error++; $error++;
setEventMessages($object->error, $object->errors, 'errors'); setEventMessages($object->error, $object->errors, 'errors');
} }
} }
if (!$error) if (!$error) {
{
$supplier = new Fournisseur($db); $supplier = new Fournisseur($db);
$result = $supplier->fetch($id_fourn); $result = $supplier->fetch($id_fourn);
if (GETPOSTISSET('ref_fourn_price_id')) { if (GETPOSTISSET('ref_fourn_price_id')) {
@ -294,12 +299,15 @@ if (empty($reshook))
$newprice = price2num(GETPOST("price", "alpha")); $newprice = price2num(GETPOST("price", "alpha"));
if (empty($packaging)) $packaging = 1; if (empty($packaging)) {
if ($packaging < $quantity) $packaging = $quantity; $packaging = 1;
}
if ($packaging < $quantity) {
$packaging = $quantity;
}
$object->packaging = $packaging; $object->packaging = $packaging;
if (!empty($conf->multicurrency->enabled)) if (!empty($conf->multicurrency->enabled)) {
{
$multicurrency_tx = price2num(GETPOST("multicurrency_tx", 'alpha')); $multicurrency_tx = price2num(GETPOST("multicurrency_tx", 'alpha'));
$multicurrency_price = price2num(GETPOST("multicurrency_price", 'alpha')); $multicurrency_price = price2num(GETPOST("multicurrency_price", 'alpha'));
$multicurrency_code = GETPOST("multicurrency_code", 'alpha'); $multicurrency_code = GETPOST("multicurrency_code", 'alpha');
@ -308,13 +316,11 @@ if (empty($reshook))
} else { } else {
$ret = $object->update_buyprice($quantity, $newprice, $user, GETPOST("price_base_type"), $supplier, GETPOST("oselDispo"), $ref_fourn, $tva_tx, GETPOST("charges"), $remise_percent, 0, $npr, $delivery_time_days, $supplier_reputation, array(), '', 0, 'HT', 1, '', $supplier_description, $barcode, $fk_barcode_type); $ret = $object->update_buyprice($quantity, $newprice, $user, GETPOST("price_base_type"), $supplier, GETPOST("oselDispo"), $ref_fourn, $tva_tx, GETPOST("charges"), $remise_percent, 0, $npr, $delivery_time_days, $supplier_reputation, array(), '', 0, 'HT', 1, '', $supplier_description, $barcode, $fk_barcode_type);
} }
if ($ret < 0) if ($ret < 0) {
{
$error++; $error++;
setEventMessages($object->error, $object->errors, 'errors'); setEventMessages($object->error, $object->errors, 'errors');
} else { } else {
if (!empty($conf->dynamicprices->enabled) && $price_expression !== '') if (!empty($conf->dynamicprices->enabled) && $price_expression !== '') {
{
//Check the expression validity by parsing it //Check the expression validity by parsing it
$priceparser = new PriceParser($db); $priceparser = new PriceParser($db);
$object->fk_supplier_price_expression = $price_expression; $object->fk_supplier_price_expression = $price_expression;
@ -324,12 +330,10 @@ if (empty($reshook))
setEventMessages($priceparser->translatedError(), null, 'errors'); setEventMessages($priceparser->translatedError(), null, 'errors');
} }
} }
if (!$error && !empty($conf->dynamicprices->enabled)) if (!$error && !empty($conf->dynamicprices->enabled)) {
{
//Set the price expression for this supplier price //Set the price expression for this supplier price
$ret = $object->setSupplierPriceExpression($price_expression); $ret = $object->setSupplierPriceExpression($price_expression);
if ($ret < 0) if ($ret < 0) {
{
$error++; $error++;
setEventMessages($object->error, $object->errors, 'errors'); setEventMessages($object->error, $object->errors, 'errors');
} }
@ -337,8 +341,7 @@ if (empty($reshook))
} }
} }
if (!$error) if (!$error) {
{
$db->commit(); $db->commit();
$action = ''; $action = '';
} else { } else {
@ -358,13 +361,11 @@ if (empty($reshook))
$title = $langs->trans('ProductServiceCard'); $title = $langs->trans('ProductServiceCard');
$helpurl = ''; $helpurl = '';
$shortlabel = dol_trunc($object->label, 16); $shortlabel = dol_trunc($object->label, 16);
if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) {
{
$title = $langs->trans('Product')." ".$shortlabel." - ".$langs->trans('BuyingPrices'); $title = $langs->trans('Product')." ".$shortlabel." - ".$langs->trans('BuyingPrices');
$helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos'; $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos';
} }
if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) {
{
$title = $langs->trans('Service')." ".$shortlabel." - ".$langs->trans('BuyingPrices'); $title = $langs->trans('Service')." ".$shortlabel." - ".$langs->trans('BuyingPrices');
$helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios'; $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios';
} }
@ -373,18 +374,15 @@ llxHeader('', $title, $helpurl, '', 0, 0, '', '', '', 'classforhorizontalscrollo
$form = new Form($db); $form = new Form($db);
if ($id > 0 || $ref) if ($id > 0 || $ref) {
{ if ($result) {
if ($result)
{
if ($action == 'ask_remove_pf') { if ($action == 'ask_remove_pf') {
$form = new Form($db); $form = new Form($db);
$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$id.'&rowid='.$rowid, $langs->trans('DeleteProductBuyPrice'), $langs->trans('ConfirmDeleteProductBuyPrice'), 'confirm_remove_pf', '', 0, 1); $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$id.'&rowid='.$rowid, $langs->trans('DeleteProductBuyPrice'), $langs->trans('ConfirmDeleteProductBuyPrice'), 'confirm_remove_pf', '', 0, 1);
echo $formconfirm; echo $formconfirm;
} }
if ($action <> 'edit' && $action <> 're-edit') if ($action <> 'edit' && $action <> 're-edit') {
{
$head = product_prepare_head($object); $head = product_prepare_head($object);
$titre = $langs->trans("CardProduct".$object->type); $titre = $langs->trans("CardProduct".$object->type);
$picto = ($object->type == Product::TYPE_SERVICE ? 'service' : 'product'); $picto = ($object->type == Product::TYPE_SERVICE ? 'service' : 'product');
@ -395,7 +393,9 @@ if ($id > 0 || $ref)
$object->next_prev_filter = " fk_product_type = ".$object->type; $object->next_prev_filter = " fk_product_type = ".$object->type;
$shownav = 1; $shownav = 1;
if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) {
$shownav = 0;
}
dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref');
@ -417,7 +417,9 @@ if ($id > 0 || $ref)
// PMP // PMP
print '<tr><td class="titlefieldcreate">'.$form->textwithpicto($langs->trans("AverageUnitPricePMPShort"), $langs->trans("AverageUnitPricePMPDesc")).'</td>'; print '<tr><td class="titlefieldcreate">'.$form->textwithpicto($langs->trans("AverageUnitPricePMPShort"), $langs->trans("AverageUnitPricePMPDesc")).'</td>';
print '<td>'; print '<td>';
if ($object->pmp > 0) print price($object->pmp).' '.$langs->trans("HT"); if ($object->pmp > 0) {
print price($object->pmp).' '.$langs->trans("HT");
}
print '</td>'; print '</td>';
print '</tr>'; print '</tr>';
@ -425,10 +427,12 @@ if ($id > 0 || $ref)
print '<tr><td class="titlefieldcreate">'.$langs->trans("BuyingPriceMin").'</td>'; print '<tr><td class="titlefieldcreate">'.$langs->trans("BuyingPriceMin").'</td>';
print '<td colspan="2">'; print '<td colspan="2">';
$product_fourn = new ProductFournisseur($db); $product_fourn = new ProductFournisseur($db);
if ($product_fourn->find_min_price_product_fournisseur($object->id) > 0) if ($product_fourn->find_min_price_product_fournisseur($object->id) > 0) {
{ if ($product_fourn->product_fourn_price_id > 0) {
if ($product_fourn->product_fourn_price_id > 0) print $product_fourn->display_price_product_fournisseur(); print $product_fourn->display_price_product_fournisseur();
else print $langs->trans("NotDefined"); } else {
print $langs->trans("NotDefined");
}
} }
print '</td></tr>'; print '</td></tr>';
@ -441,12 +445,10 @@ if ($id > 0 || $ref)
// Form to add or update a price // Form to add or update a price
if (($action == 'add_price' || $action == 'update_price') && $usercancreate) if (($action == 'add_price' || $action == 'update_price') && $usercancreate) {
{
$langs->load("suppliers"); $langs->load("suppliers");
if ($rowid) if ($rowid) {
{
$object->fetch_product_fournisseur_price($rowid, 1); //Ignore the math expression when getting the price $object->fetch_product_fournisseur_price($rowid, 1); //Ignore the math expression when getting the price
print load_fiche_titre($langs->trans("ChangeSupplierPrice")); print load_fiche_titre($langs->trans("ChangeSupplierPrice"));
} else { } else {
@ -463,8 +465,7 @@ if ($id > 0 || $ref)
// Supplier // Supplier
print '<tr><td class="titlefieldcreate fieldrequired">'.$langs->trans("Supplier").'</td><td>'; print '<tr><td class="titlefieldcreate fieldrequired">'.$langs->trans("Supplier").'</td><td>';
if ($rowid) if ($rowid) {
{
$supplier = new Fournisseur($db); $supplier = new Fournisseur($db);
$supplier->fetch($socid); $supplier->fetch($socid);
print $supplier->getNomUrl(1); print $supplier->getNomUrl(1);
@ -479,10 +480,8 @@ if ($id > 0 || $ref)
$parameters = array('filtre'=>"fournisseur=1", 'html_name'=>'id_fourn', 'selected'=>GETPOST("id_fourn"), 'showempty'=>1, 'prod_id'=>$object->id); $parameters = array('filtre'=>"fournisseur=1", 'html_name'=>'id_fourn', 'selected'=>GETPOST("id_fourn"), 'showempty'=>1, 'prod_id'=>$object->id);
$reshook = $hookmanager->executeHooks('formCreateThirdpartyOptions', $parameters, $object, $action); $reshook = $hookmanager->executeHooks('formCreateThirdpartyOptions', $parameters, $object, $action);
if (empty($reshook)) if (empty($reshook)) {
{ if (empty($form->result)) {
if (empty($form->result))
{
print ' - <a href="'.DOL_URL_ROOT.'/societe/card.php?action=create&type=f&backtopage='.urlencode($_SERVER["PHP_SELF"].'?id='.$object->id.'&action='.$action).'">'.$langs->trans("CreateDolibarrThirdPartySupplier").'</a>'; print ' - <a href="'.DOL_URL_ROOT.'/societe/card.php?action=create&type=f&backtopage='.urlencode($_SERVER["PHP_SELF"].'?id='.$object->id.'&action='.$action).'">'.$langs->trans("CreateDolibarrThirdPartySupplier").'</a>';
} }
} }
@ -491,8 +490,7 @@ if ($id > 0 || $ref)
// Ref supplier // Ref supplier
print '<tr><td class="fieldrequired">'.$langs->trans("SupplierRef").'</td><td>'; print '<tr><td class="fieldrequired">'.$langs->trans("SupplierRef").'</td><td>';
if ($rowid) if ($rowid) {
{
print '<input type="hidden" name="ref_fourn_old" value="'.$object->ref_supplier.'">'; print '<input type="hidden" name="ref_fourn_old" value="'.$object->ref_supplier.'">';
print '<input class="flat width150" maxlength="30" name="ref_fourn" value="'.$object->ref_supplier.'">'; print '<input class="flat width150" maxlength="30" name="ref_fourn" value="'.$object->ref_supplier.'">';
} else { } else {
@ -502,8 +500,7 @@ if ($id > 0 || $ref)
print '</tr>'; print '</tr>';
// Availability // Availability
if (!empty($conf->global->FOURN_PRODUCT_AVAILABILITY)) if (!empty($conf->global->FOURN_PRODUCT_AVAILABILITY)) {
{
$langs->load("propal"); $langs->load("propal");
print '<tr><td>'.$langs->trans("Availability").'</td><td>'; print '<tr><td>'.$langs->trans("Availability").'</td><td>';
$form->selectAvailabilityDelay($object->fk_availability, "oselDispo", 1); $form->selectAvailabilityDelay($object->fk_availability, "oselDispo", 1);
@ -515,8 +512,7 @@ if ($id > 0 || $ref)
print '<td class="fieldrequired">'.$langs->trans("QtyMin").'</td>'; print '<td class="fieldrequired">'.$langs->trans("QtyMin").'</td>';
print '<td>'; print '<td>';
$quantity = GETPOSTISSET('qty') ? price2num(GETPOST('qty', 'nohtml'), 'MS') : "1"; $quantity = GETPOSTISSET('qty') ? price2num(GETPOST('qty', 'nohtml'), 'MS') : "1";
if ($rowid) if ($rowid) {
{
print '<input type="hidden" name="qty" value="'.$object->fourn_qty.'">'; print '<input type="hidden" name="qty" value="'.$object->fourn_qty.'">';
print $object->fourn_qty; print $object->fourn_qty;
} else { } else {
@ -558,20 +554,20 @@ if ($id > 0 || $ref)
$mysoc2->tva_assuj = 1; $mysoc2->tva_assuj = 1;
$default_vat = get_default_tva($mysoc2, $mysoc, $object->id, 0); $default_vat = get_default_tva($mysoc2, $mysoc, $object->id, 0);
$default_npr = get_default_npr($mysoc2, $mysoc, $object->id, 0); $default_npr = get_default_npr($mysoc2, $mysoc, $object->id, 0);
if (empty($default_vat)) $default_npr = $default_vat; if (empty($default_vat)) {
$default_npr = $default_vat;
}
print '<tr><td class="fieldrequired">'.$langs->trans("VATRateForSupplierProduct").'</td>'; print '<tr><td class="fieldrequired">'.$langs->trans("VATRateForSupplierProduct").'</td>';
print '<td>'; print '<td>';
//print $form->load_tva('tva_tx',$object->tva_tx,$supplier,$mysoc); // Do not use list here as it may be any vat rates for any country //print $form->load_tva('tva_tx',$object->tva_tx,$supplier,$mysoc); // Do not use list here as it may be any vat rates for any country
if (!empty($rowid)) // If we have a supplier, it is an update, we must show the vat of current supplier price if (!empty($rowid)) { // If we have a supplier, it is an update, we must show the vat of current supplier price
{
$tmpproductsupplier = new ProductFournisseur($db); $tmpproductsupplier = new ProductFournisseur($db);
$tmpproductsupplier->fetch_product_fournisseur_price($rowid, 1); $tmpproductsupplier->fetch_product_fournisseur_price($rowid, 1);
$default_vat = $tmpproductsupplier->fourn_tva_tx; $default_vat = $tmpproductsupplier->fourn_tva_tx;
$default_npr = $tmpproductsupplier->fourn_tva_npr; $default_npr = $tmpproductsupplier->fourn_tva_npr;
} else { } else {
if (empty($default_vat)) if (empty($default_vat)) {
{
$default_vat = $object->tva_tx; $default_vat = $object->tva_tx;
} }
} }
@ -580,8 +576,7 @@ if ($id > 0 || $ref)
print '<input type="text" class="flat" size="5" name="tva_tx" value="'.$vattosuggest.'">'; print '<input type="text" class="flat" size="5" name="tva_tx" value="'.$vattosuggest.'">';
print '</td></tr>'; print '</td></tr>';
if (!empty($conf->dynamicprices->enabled)) //Only show price mode and expression selector if module is enabled if (!empty($conf->dynamicprices->enabled)) { //Only show price mode and expression selector if module is enabled
{
// Price mode selector // Price mode selector
print '<tr><td class="fieldrequired">'.$langs->trans("PriceMode").'</td><td>'; print '<tr><td class="fieldrequired">'.$langs->trans("PriceMode").'</td><td>';
$price_expression = new PriceExpression($db); $price_expression = new PriceExpression($db);
@ -619,7 +614,9 @@ if ($id > 0 || $ref)
print '<tr><td class="fieldrequired">'.$langs->trans("Currency").'</td>'; print '<tr><td class="fieldrequired">'.$langs->trans("Currency").'</td>';
print '<td>'; print '<td>';
$currencycodetouse = GETPOST('multicurrency_code') ?GETPOST('multicurrency_code') : (isset($object->fourn_multicurrency_code) ? $object->fourn_multicurrency_code : ''); $currencycodetouse = GETPOST('multicurrency_code') ?GETPOST('multicurrency_code') : (isset($object->fourn_multicurrency_code) ? $object->fourn_multicurrency_code : '');
if (empty($currencycodetouse) && $object->fourn_multicurrency_tx == 1) $currencycodetouse = $conf->currency; if (empty($currencycodetouse) && $object->fourn_multicurrency_tx == 1) {
$currencycodetouse = $conf->currency;
}
print $form->selectMultiCurrency($currencycodetouse, "multicurrency_code", 1); print $form->selectMultiCurrency($currencycodetouse, "multicurrency_code", 1);
print ' &nbsp; '.$langs->trans("CurrencyRate").' '; print ' &nbsp; '.$langs->trans("CurrencyRate").' ';
print '<input class="flat" name="multicurrency_tx" size="4" value="'.vatrate(GETPOST('multicurrency_tx') ? GETPOST('multicurrency_tx') : (isset($object->fourn_multicurrency_tx) ? $object->fourn_multicurrency_tx : '')).'">'; print '<input class="flat" name="multicurrency_tx" size="4" value="'.vatrate(GETPOST('multicurrency_tx') ? GETPOST('multicurrency_tx') : (isset($object->fourn_multicurrency_tx) ? $object->fourn_multicurrency_tx : '')).'">';
@ -724,8 +721,7 @@ END;
print '</td></tr>'; print '</td></tr>';
// Barcode // Barcode
if (!empty($conf->barcode->enabled)) if (!empty($conf->barcode->enabled)) {
{
// Option to define a transport cost on supplier price // Option to define a transport cost on supplier price
print '<tr>'; print '<tr>';
print '<td>'.$langs->trans('BarcodeValue').'</td>'; print '<td>'.$langs->trans('BarcodeValue').'</td>';
@ -743,10 +739,8 @@ END;
} }
// Option to define a transport cost on supplier price // Option to define a transport cost on supplier price
if ($conf->global->PRODUCT_CHARGES) if ($conf->global->PRODUCT_CHARGES) {
{ if (!empty($conf->margin->enabled)) {
if (!empty($conf->margin->enabled))
{
print '<tr>'; print '<tr>';
print '<td>'.$langs->trans("Charges").'</td>'; print '<td>'.$langs->trans("Charges").'</td>';
print '<td><input class="flat" name="charges" size="8" value="'.(GETPOST('charges') ?price(GETPOST('charges')) : (isset($object->fourn_charges) ?price($object->fourn_charges) : '')).'">'; print '<td><input class="flat" name="charges" size="8" value="'.(GETPOST('charges') ?price(GETPOST('charges')) : (isset($object->fourn_charges) ?price($object->fourn_charges) : '')).'">';
@ -756,8 +750,7 @@ END;
} }
// Product description of the supplier // Product description of the supplier
if (!empty($conf->global->PRODUIT_FOURN_TEXTS)) if (!empty($conf->global->PRODUIT_FOURN_TEXTS)) {
{
//WYSIWYG Editor //WYSIWYG Editor
require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
@ -780,11 +773,16 @@ END;
if (empty($rowid)) { if (empty($rowid)) {
foreach ($extralabels as $key => $value) { foreach ($extralabels as $key => $value) {
if (!empty($extrafields->attributes["product_fournisseur_price"]['list'][$key]) && ($extrafields->attributes["product_fournisseur_price"]['list'][$key] == 1 || $extrafields->attributes["product_fournisseur_price"]['list'][$key] == 3 || ($action == "update_price" && $extrafields->attributes["product_fournisseur_price"]['list'][$key] == 4))) { if (!empty($extrafields->attributes["product_fournisseur_price"]['list'][$key]) && ($extrafields->attributes["product_fournisseur_price"]['list'][$key] == 1 || $extrafields->attributes["product_fournisseur_price"]['list'][$key] == 3 || ($action == "update_price" && $extrafields->attributes["product_fournisseur_price"]['list'][$key] == 4))) {
if (!empty($extrafields->attributes["product_fournisseur_price"]['langfile'][$key])) $langs->load($extrafields->attributes["product_fournisseur_price"]['langfile'][$key]); if (!empty($extrafields->attributes["product_fournisseur_price"]['langfile'][$key])) {
$langs->load($extrafields->attributes["product_fournisseur_price"]['langfile'][$key]);
}
print '<tr><td'.($extrafields->attributes["product_fournisseur_price"]['required'][$key] ? ' class="fieldrequired"' : '').'>'; print '<tr><td'.($extrafields->attributes["product_fournisseur_price"]['required'][$key] ? ' class="fieldrequired"' : '').'>';
if (!empty($extrafields->attributes["product_fournisseur_price"]['help'][$key])) print $form->textwithpicto($langs->trans($value), $langs->trans($extrafields->attributes["product_fournisseur_price"]['help'][$key])); if (!empty($extrafields->attributes["product_fournisseur_price"]['help'][$key])) {
else print $langs->trans($value); print $form->textwithpicto($langs->trans($value), $langs->trans($extrafields->attributes["product_fournisseur_price"]['help'][$key]));
} else {
print $langs->trans($value);
}
print '</td><td>'.$extrafields->showInputField($key, GETPOSTISSET('options_'.$key) ? $extrafield_values['options_'.$key] : '', '', '', '', '', 0, 'product_fournisseur_price').'</td></tr>'; print '</td><td>'.$extrafields->showInputField($key, GETPOSTISSET('options_'.$key) ? $extrafield_values['options_'.$key] : '', '', '', '', '', 0, 'product_fournisseur_price').'</td></tr>';
} }
} }
@ -801,11 +799,16 @@ END;
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
foreach ($extralabels as $key => $value) { foreach ($extralabels as $key => $value) {
if (!empty($extrafields->attributes["product_fournisseur_price"]['list'][$key]) && ($extrafields->attributes["product_fournisseur_price"]['list'][$key] == 1 || $extrafields->attributes["product_fournisseur_price"]['list'][$key] == 3 || ($action == "update_price" && $extrafields->attributes["product_fournisseur_price"]['list'][$key] == 4))) { if (!empty($extrafields->attributes["product_fournisseur_price"]['list'][$key]) && ($extrafields->attributes["product_fournisseur_price"]['list'][$key] == 1 || $extrafields->attributes["product_fournisseur_price"]['list'][$key] == 3 || ($action == "update_price" && $extrafields->attributes["product_fournisseur_price"]['list'][$key] == 4))) {
if (!empty($extrafields->attributes["product_fournisseur_price"]['langfile'][$key])) $langs->load($extrafields->attributes["product_fournisseur_price"]['langfile'][$key]); if (!empty($extrafields->attributes["product_fournisseur_price"]['langfile'][$key])) {
$langs->load($extrafields->attributes["product_fournisseur_price"]['langfile'][$key]);
}
print '<tr><td'.($extrafields->attributes["product_fournisseur_price"]['required'][$key] ? ' class="fieldrequired"' : '').'>'; print '<tr><td'.($extrafields->attributes["product_fournisseur_price"]['required'][$key] ? ' class="fieldrequired"' : '').'>';
if (!empty($extrafields->attributes["product_fournisseur_price"]['help'][$key])) print $form->textwithpicto($langs->trans($value), $langs->trans($extrafields->attributes["product_fournisseur_price"]['help'][$key])); if (!empty($extrafields->attributes["product_fournisseur_price"]['help'][$key])) {
else print $langs->trans($value); print $form->textwithpicto($langs->trans($value), $langs->trans($extrafields->attributes["product_fournisseur_price"]['help'][$key]));
} else {
print $langs->trans($value);
}
print '</td><td>'.$extrafields->showInputField($key, GETPOSTISSET('options_'.$key) ? $extrafield_values['options_'.$key] : $obj->{$key}, '', '', '', '', 0, 'product_fournisseur_price'); print '</td><td>'.$extrafields->showInputField($key, GETPOSTISSET('options_'.$key) ? $extrafield_values['options_'.$key] : $obj->{$key}, '', '', '', '', 0, 'product_fournisseur_price');
print '</td></tr>'; print '</td></tr>';
@ -816,8 +819,7 @@ END;
} }
} }
if (is_object($hookmanager)) if (is_object($hookmanager)) {
{
$parameters = array('id_fourn'=>$id_fourn, 'prod_id'=>$object->id); $parameters = array('id_fourn'=>$id_fourn, 'prod_id'=>$object->id);
$reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action);
print $hookmanager->resPrint; print $hookmanager->resPrint;
@ -840,14 +842,11 @@ END;
print "\n<div class=\"tabsAction\">\n"; print "\n<div class=\"tabsAction\">\n";
if ($action != 'add_price' && $action != 'update_price') if ($action != 'add_price' && $action != 'update_price') {
{
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
if (empty($reshook)) if (empty($reshook)) {
{ if ($usercancreate) {
if ($usercancreate)
{
print '<a class="butAction" href="'.DOL_URL_ROOT.'/product/fournisseurs.php?id='.$object->id.'&amp;action=add_price">'; print '<a class="butAction" href="'.DOL_URL_ROOT.'/product/fournisseurs.php?id='.$object->id.'&amp;action=add_price">';
print $langs->trans("AddSupplierPrice").'</a>'; print $langs->trans("AddSupplierPrice").'</a>';
} }
@ -857,11 +856,14 @@ END;
print "\n</div>\n"; print "\n</div>\n";
print '<br>'; print '<br>';
if ($user->rights->fournisseur->lire) // Duplicate ? this check is already in the head of this file if ($user->rights->fournisseur->lire) { // Duplicate ? this check is already in the head of this file
{
$param = ''; $param = '';
if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); $param .= '&contextpage='.urlencode($contextpage);
}
if ($limit > 0 && $limit != $conf->liste_limit) {
$param .= '&limit='.urlencode($limit);
}
$param .= '&ref='.urlencode($object->ref); $param .= '&ref='.urlencode($object->ref);
$product_fourn = new ProductFournisseur($db); $product_fourn = new ProductFournisseur($db);
@ -869,7 +871,9 @@ END;
$product_fourn_list_all = $product_fourn->list_product_fournisseur_price($object->id, $sortfield, $sortorder, 0, 0); $product_fourn_list_all = $product_fourn->list_product_fournisseur_price($object->id, $sortfield, $sortorder, 0, 0);
$nbtotalofrecords = count($product_fourn_list_all); $nbtotalofrecords = count($product_fourn_list_all);
$num = count($product_fourn_list); $num = count($product_fourn_list);
if (($num + ($offset * $limit)) < $nbtotalofrecords) $num++; if (($num + ($offset * $limit)) < $nbtotalofrecords) {
$num++;
}
print_barre_liste($langs->trans('SupplierPrices'), $page, $_SERVER['PHP_SELF'], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_accountancy.png', 0, '', '', $limit, 1); print_barre_liste($langs->trans('SupplierPrices'), $page, $_SERVER['PHP_SELF'], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_accountancy.png', 0, '', '', $limit, 1);
@ -924,24 +928,52 @@ END;
$param = "&id=".$object->id; $param = "&id=".$object->id;
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
if (!empty($arrayfields['pfp.datec']['checked'])) print_liste_field_titre("AppliedPricesFrom", $_SERVER["PHP_SELF"], "pfp.datec", "", $param, "", $sortfield, $sortorder, '', '', 1); if (!empty($arrayfields['pfp.datec']['checked'])) {
if (!empty($arrayfields['s.nom']['checked'])) print_liste_field_titre("Suppliers", $_SERVER["PHP_SELF"], "s.nom", "", $param, "", $sortfield, $sortorder, '', '', 1); print_liste_field_titre("AppliedPricesFrom", $_SERVER["PHP_SELF"], "pfp.datec", "", $param, "", $sortfield, $sortorder, '', '', 1);
}
if (!empty($arrayfields['s.nom']['checked'])) {
print_liste_field_titre("Suppliers", $_SERVER["PHP_SELF"], "s.nom", "", $param, "", $sortfield, $sortorder, '', '', 1);
}
print_liste_field_titre("SupplierRef", $_SERVER["PHP_SELF"], "", "", $param, "", $sortfield, $sortorder, '', '', 1); print_liste_field_titre("SupplierRef", $_SERVER["PHP_SELF"], "", "", $param, "", $sortfield, $sortorder, '', '', 1);
if (!empty($arrayfields['pfp.fk_availability']['checked'])) print_liste_field_titre("Availability", $_SERVER["PHP_SELF"], "pfp.fk_availability", "", $param, "", $sortfield, $sortorder); if (!empty($arrayfields['pfp.fk_availability']['checked'])) {
if (!empty($arrayfields['pfp.quantity']['checked'])) print_liste_field_titre("QtyMin", $_SERVER["PHP_SELF"], "pfp.quantity", "", $param, '', $sortfield, $sortorder, 'right '); print_liste_field_titre("Availability", $_SERVER["PHP_SELF"], "pfp.fk_availability", "", $param, "", $sortfield, $sortorder);
}
if (!empty($arrayfields['pfp.quantity']['checked'])) {
print_liste_field_titre("QtyMin", $_SERVER["PHP_SELF"], "pfp.quantity", "", $param, '', $sortfield, $sortorder, 'right ');
}
print_liste_field_titre("VATRate", $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, 'right '); print_liste_field_titre("VATRate", $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, 'right ');
print_liste_field_titre("PriceQtyMinHT", $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, 'right '); print_liste_field_titre("PriceQtyMinHT", $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, 'right ');
if (!empty($conf->multicurrency->enabled)) print_liste_field_titre("PriceQtyMinHTCurrency", $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, 'right '); if (!empty($conf->multicurrency->enabled)) {
if (!empty($arrayfields['pfp.unitprice']['checked'])) print_liste_field_titre("UnitPriceHT", $_SERVER["PHP_SELF"], "pfp.unitprice", "", $param, '', $sortfield, $sortorder, 'right '); print_liste_field_titre("PriceQtyMinHTCurrency", $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, 'right ');
if (!empty($arrayfields['pfp.multicurrency_unitprice']['checked'])) print_liste_field_titre("UnitPriceHTCurrency", $_SERVER["PHP_SELF"], "pfp.multicurrency_unitprice", "", $param, '', $sortfield, $sortorder, 'right '); }
if (!empty($conf->multicurrency->enabled)) print_liste_field_titre("Currency", $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder, 'right '); if (!empty($arrayfields['pfp.unitprice']['checked'])) {
print_liste_field_titre("UnitPriceHT", $_SERVER["PHP_SELF"], "pfp.unitprice", "", $param, '', $sortfield, $sortorder, 'right ');
}
if (!empty($arrayfields['pfp.multicurrency_unitprice']['checked'])) {
print_liste_field_titre("UnitPriceHTCurrency", $_SERVER["PHP_SELF"], "pfp.multicurrency_unitprice", "", $param, '', $sortfield, $sortorder, 'right ');
}
if (!empty($conf->multicurrency->enabled)) {
print_liste_field_titre("Currency", $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder, 'right ');
}
print_liste_field_titre("DiscountQtyMin", $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, 'right '); print_liste_field_titre("DiscountQtyMin", $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, 'right ');
if (!empty($arrayfields['pfp.delivery_time_days']['checked'])) print_liste_field_titre("NbDaysToDelivery", $_SERVER["PHP_SELF"], "pfp.delivery_time_days", "", $param, '', $sortfield, $sortorder, 'right '); if (!empty($arrayfields['pfp.delivery_time_days']['checked'])) {
if (!empty($arrayfields['pfp.supplier_reputation']['checked'])) print_liste_field_titre("ReputationForThisProduct", $_SERVER["PHP_SELF"], "pfp.supplier_reputation", "", $param, '', $sortfield, $sortorder, 'center '); print_liste_field_titre("NbDaysToDelivery", $_SERVER["PHP_SELF"], "pfp.delivery_time_days", "", $param, '', $sortfield, $sortorder, 'right ');
if (!empty($arrayfields['pfp.barcode']['checked'])) print_liste_field_titre("BarcodeValue", $_SERVER["PHP_SELF"], "pfp.barcode", "", $param, '', $sortfield, $sortorder, 'center '); }
if (!empty($arrayfields['pfp.fk_barcode_type']['checked'])) print_liste_field_titre("BarcodeType", $_SERVER["PHP_SELF"], "pfp.fk_barcode_type", "", $param, '', $sortfield, $sortorder, 'center '); if (!empty($arrayfields['pfp.supplier_reputation']['checked'])) {
if (!empty($arrayfields['pfp.packaging']['checked'])) print_liste_field_titre("PackagingForThisProduct", $_SERVER["PHP_SELF"], "pfp.packaging", "", $param, 'align="center"', $sortfield, $sortorder); print_liste_field_titre("ReputationForThisProduct", $_SERVER["PHP_SELF"], "pfp.supplier_reputation", "", $param, '', $sortfield, $sortorder, 'center ');
if (!empty($arrayfields['pfp.tms']['checked'])) print_liste_field_titre("DateModification", $_SERVER["PHP_SELF"], "pfp.tms", "", $param, '', $sortfield, $sortorder, 'right ', '', 1); }
if (!empty($arrayfields['pfp.barcode']['checked'])) {
print_liste_field_titre("BarcodeValue", $_SERVER["PHP_SELF"], "pfp.barcode", "", $param, '', $sortfield, $sortorder, 'center ');
}
if (!empty($arrayfields['pfp.fk_barcode_type']['checked'])) {
print_liste_field_titre("BarcodeType", $_SERVER["PHP_SELF"], "pfp.fk_barcode_type", "", $param, '', $sortfield, $sortorder, 'center ');
}
if (!empty($arrayfields['pfp.packaging']['checked'])) {
print_liste_field_titre("PackagingForThisProduct", $_SERVER["PHP_SELF"], "pfp.packaging", "", $param, 'align="center"', $sortfield, $sortorder);
}
if (!empty($arrayfields['pfp.tms']['checked'])) {
print_liste_field_titre("DateModification", $_SERVER["PHP_SELF"], "pfp.tms", "", $param, '', $sortfield, $sortorder, 'right ', '', 1);
}
// fetch optionals attributes and labels // fetch optionals attributes and labels
$extrafields->fetch_name_optionals_label("product_fournisseur_price"); $extrafields->fetch_name_optionals_label("product_fournisseur_price");
@ -951,26 +983,30 @@ END;
foreach ($extralabels as $key => $value) { foreach ($extralabels as $key => $value) {
// Show field if not hidden // Show field if not hidden
if (!empty($extrafields->attributes["product_fournisseur_price"]['list'][$key]) && $extrafields->attributes["product_fournisseur_price"]['list'][$key] != 3) { if (!empty($extrafields->attributes["product_fournisseur_price"]['list'][$key]) && $extrafields->attributes["product_fournisseur_price"]['list'][$key] != 3) {
if (!empty($extrafields->attributes["product_fournisseur_price"]['langfile'][$key])) $langs->load($extrafields->attributes["product_fournisseur_price"]['langfile'][$key]); if (!empty($extrafields->attributes["product_fournisseur_price"]['langfile'][$key])) {
if (!empty($extrafields->attributes["product_fournisseur_price"]['help'][$key])) $extratitle = $form->textwithpicto($langs->trans($value), $langs->trans($extrafields->attributes["product_fournisseur_price"]['help'][$key])); $langs->load($extrafields->attributes["product_fournisseur_price"]['langfile'][$key]);
else $extratitle = $langs->trans($value); }
if (!empty($arrayfields['ef.'.$key]['checked'])) print_liste_field_titre($extratitle, $_SERVER["PHP_SELF"], 'ef.'.$key, '', $param, '', $sortfield, $sortorder, 'right '); if (!empty($extrafields->attributes["product_fournisseur_price"]['help'][$key])) {
$extratitle = $form->textwithpicto($langs->trans($value), $langs->trans($extrafields->attributes["product_fournisseur_price"]['help'][$key]));
} else {
$extratitle = $langs->trans($value);
}
if (!empty($arrayfields['ef.'.$key]['checked'])) {
print_liste_field_titre($extratitle, $_SERVER["PHP_SELF"], 'ef.'.$key, '', $param, '', $sortfield, $sortorder, 'right ');
}
} }
} }
} }
if (is_object($hookmanager)) if (is_object($hookmanager)) {
{
$parameters = array('id_fourn'=>$id_fourn, 'prod_id'=>$object->id); $parameters = array('id_fourn'=>$id_fourn, 'prod_id'=>$object->id);
$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object, $action); $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object, $action);
} }
print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ');
print "</tr>\n"; print "</tr>\n";
if (is_array($product_fourn_list)) if (is_array($product_fourn_list)) {
{ foreach ($product_fourn_list as $productfourn) {
foreach ($product_fourn_list as $productfourn)
{
print '<tr class="oddeven">'; print '<tr class="oddeven">';
// Date from // Date from
@ -991,8 +1027,7 @@ END;
} }
// Availability // Availability
if (!empty($arrayfields['pfp.fk_availability']['checked'])) if (!empty($arrayfields['pfp.fk_availability']['checked'])) {
{
$form->load_cache_availability(); $form->load_cache_availability();
$availability = $form->cache_availability[$productfourn->fk_availability]['label']; $availability = $form->cache_availability[$productfourn->fk_availability]['label'];
print '<td class="left">'.$availability.'</td>'; print '<td class="left">'.$availability.'</td>';
@ -1041,7 +1076,8 @@ END;
if (!empty($arrayfields['pfp.multicurrency_unitprice']['checked'])) { if (!empty($arrayfields['pfp.multicurrency_unitprice']['checked'])) {
print '<td class="right">'; print '<td class="right">';
print price($productfourn->fourn_multicurrency_unitprice); print price($productfourn->fourn_multicurrency_unitprice);
print '</td>'; } print '</td>';
}
// Currency // Currency
if (!empty($conf->multicurrency->enabled)) { if (!empty($conf->multicurrency->enabled)) {
@ -1130,8 +1166,7 @@ END;
} }
} }
if (is_object($hookmanager)) if (is_object($hookmanager)) {
{
$parameters = array('id_pfp'=>$productfourn->product_fourn_price_id, 'id_fourn'=>$id_fourn, 'prod_id'=>$object->id); $parameters = array('id_pfp'=>$productfourn->product_fourn_price_id, 'id_fourn'=>$id_fourn, 'prod_id'=>$object->id);
$reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object, $action); $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object, $action);
} }
@ -1139,8 +1174,7 @@ END;
// Modify-Remove // Modify-Remove
print '<td class="center nowraponall">'; print '<td class="center nowraponall">';
if ($usercancreate) if ($usercancreate) {
{
print '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;socid='.$productfourn->fourn_id.'&amp;action=update_price&amp;rowid='.$productfourn->product_fourn_price_id.'">'.img_edit()."</a>"; print '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;socid='.$productfourn->fourn_id.'&amp;action=update_price&amp;rowid='.$productfourn->product_fourn_price_id.'">'.img_edit()."</a>";
print ' &nbsp; '; print ' &nbsp; ';
print '<a href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;socid='.$productfourn->fourn_id.'&amp;action=ask_remove_pf&amp;rowid='.$productfourn->product_fourn_price_id.'">'.img_picto($langs->trans("Remove"), 'delete').'</a>'; print '<a href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;socid='.$productfourn->fourn_id.'&amp;action=ask_remove_pf&amp;rowid='.$productfourn->product_fourn_price_id.'">'.img_picto($langs->trans("Remove"), 'delete').'</a>';

View File

@ -34,13 +34,21 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
$type = GETPOST("type", 'int'); $type = GETPOST("type", 'int');
if ($type == '' && !$user->rights->produit->lire) $type = '1'; // Force global page on service page only if ($type == '' && !$user->rights->produit->lire) {
if ($type == '' && !$user->rights->service->lire) $type = '0'; // Force global page on product page only $type = '1'; // Force global page on service page only
}
if ($type == '' && !$user->rights->service->lire) {
$type = '0'; // Force global page on product page only
}
// Security check // Security check
if ($type == '0') $result = restrictedArea($user, 'produit'); if ($type == '0') {
elseif ($type == '1') $result = restrictedArea($user, 'service'); $result = restrictedArea($user, 'produit');
else $result = restrictedArea($user, 'produit|service|expedition'); } elseif ($type == '1') {
$result = restrictedArea($user, 'service');
} else {
$result = restrictedArea($user, 'produit|service|expedition');
}
// Load translation files required by the page // Load translation files required by the page
$langs->loadLangs(array('products', 'stocks')); $langs->loadLangs(array('products', 'stocks'));
@ -58,18 +66,15 @@ $product_static = new Product($db);
$transAreaType = $langs->trans("ProductsAndServicesArea"); $transAreaType = $langs->trans("ProductsAndServicesArea");
$helpurl = ''; $helpurl = '';
if (!isset($_GET["type"])) if (!isset($_GET["type"])) {
{
$transAreaType = $langs->trans("ProductsAndServicesArea"); $transAreaType = $langs->trans("ProductsAndServicesArea");
$helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos'; $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos';
} }
if ((isset($_GET["type"]) && $_GET["type"] == 0) || empty($conf->service->enabled)) if ((isset($_GET["type"]) && $_GET["type"] == 0) || empty($conf->service->enabled)) {
{
$transAreaType = $langs->trans("ProductsArea"); $transAreaType = $langs->trans("ProductsArea");
$helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos'; $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos';
} }
if ((isset($_GET["type"]) && $_GET["type"] == 1) || empty($conf->product->enabled)) if ((isset($_GET["type"]) && $_GET["type"] == 1) || empty($conf->product->enabled)) {
{
$transAreaType = $langs->trans("ServicesArea"); $transAreaType = $langs->trans("ServicesArea");
$helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios'; $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios';
} }
@ -83,27 +88,27 @@ print load_fiche_titre($transAreaType, $linkback, 'product');
print '<div class="fichecenter"><div class="fichethirdleft">'; print '<div class="fichecenter"><div class="fichethirdleft">';
if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is useless due to the global search combo if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) { // This is useless due to the global search combo
{
// Search contract // Search contract
if ((!empty($conf->product->enabled) || !empty($conf->service->enabled)) && ($user->rights->produit->lire || $user->rights->service->lire)) if ((!empty($conf->product->enabled) || !empty($conf->service->enabled)) && ($user->rights->produit->lire || $user->rights->service->lire)) {
{
$listofsearchfields['search_product'] = array('text'=>'ProductOrService'); $listofsearchfields['search_product'] = array('text'=>'ProductOrService');
} }
if (count($listofsearchfields)) if (count($listofsearchfields)) {
{
print '<form method="post" action="'.DOL_URL_ROOT.'/core/search.php">'; print '<form method="post" action="'.DOL_URL_ROOT.'/core/search.php">';
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<div class="div-table-responsive-no-min">'; print '<div class="div-table-responsive-no-min">';
print '<table class="noborder nohover centpercent">'; print '<table class="noborder nohover centpercent">';
$i = 0; $i = 0;
foreach ($listofsearchfields as $key => $value) foreach ($listofsearchfields as $key => $value) {
{ if ($i == 0) {
if ($i == 0) print '<tr class="liste_titre"><td colspan="3">'.$langs->trans("Search").'</td></tr>'; print '<tr class="liste_titre"><td colspan="3">'.$langs->trans("Search").'</td></tr>';
}
print '<tr class="oddeven">'; print '<tr class="oddeven">';
print '<td class="nowrap"><label for="'.$key.'">'.$langs->trans($value["text"]).'</label></td><td><input type="text" class="flat inputsearch" name="'.$key.'" id="'.$key.'" size="18"></td>'; print '<td class="nowrap"><label for="'.$key.'">'.$langs->trans($value["text"]).'</label></td><td><input type="text" class="flat inputsearch" name="'.$key.'" id="'.$key.'" size="18"></td>';
if ($i == 0) print '<td rowspan="'.count($listofsearchfields).'"><input type="submit" value="'.$langs->trans("Search").'" class="button"></td>'; if ($i == 0) {
print '<td rowspan="'.count($listofsearchfields).'"><input type="submit" value="'.$langs->trans("Search").'" class="button"></td>';
}
print '</tr>'; print '</tr>';
$i++; $i++;
} }
@ -117,8 +122,7 @@ if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is useles
/* /*
* Number of products and/or services * Number of products and/or services
*/ */
if ((!empty($conf->product->enabled) || !empty($conf->service->enabled)) && ($user->rights->produit->lire || $user->rights->service->lire)) if ((!empty($conf->product->enabled) || !empty($conf->service->enabled)) && ($user->rights->produit->lire || $user->rights->service->lire)) {
{
$prodser = array(); $prodser = array();
$prodser[0][0] = $prodser[0][1] = $prodser[0][2] = $prodser[0][3] = 0; $prodser[0][0] = $prodser[0][1] = $prodser[0][2] = $prodser[0][3] = 0;
$prodser[1][0] = $prodser[1][1] = $prodser[1][2] = $prodser[1][3] = 0; $prodser[1][0] = $prodser[1][1] = $prodser[1][2] = $prodser[1][3] = 0;
@ -132,20 +136,30 @@ if ((!empty($conf->product->enabled) || !empty($conf->service->enabled)) && ($us
$sql .= $hookmanager->resPrint; $sql .= $hookmanager->resPrint;
$sql .= " GROUP BY p.fk_product_type, p.tosell, p.tobuy"; $sql .= " GROUP BY p.fk_product_type, p.tosell, p.tobuy";
$result = $db->query($sql); $result = $db->query($sql);
while ($objp = $db->fetch_object($result)) while ($objp = $db->fetch_object($result)) {
{
$status = 3; // On sale + On purchase $status = 3; // On sale + On purchase
if (!$objp->tosell && !$objp->tobuy) $status = 0; // Not on sale, not on purchase if (!$objp->tosell && !$objp->tobuy) {
if ($objp->tosell && !$objp->tobuy) $status = 1; // On sale only $status = 0; // Not on sale, not on purchase
if (!$objp->tosell && $objp->tobuy) $status = 2; // On purchase only }
if ($objp->tosell && !$objp->tobuy) {
$status = 1; // On sale only
}
if (!$objp->tosell && $objp->tobuy) {
$status = 2; // On purchase only
}
$prodser[$objp->fk_product_type][$status] = $objp->total; $prodser[$objp->fk_product_type][$status] = $objp->total;
if ($objp->tosell) $prodser[$objp->fk_product_type]['sell'] += $objp->total; if ($objp->tosell) {
if ($objp->tobuy) $prodser[$objp->fk_product_type]['buy'] += $objp->total; $prodser[$objp->fk_product_type]['sell'] += $objp->total;
if (!$objp->tosell && !$objp->tobuy) $prodser[$objp->fk_product_type]['none'] += $objp->total; }
if ($objp->tobuy) {
$prodser[$objp->fk_product_type]['buy'] += $objp->total;
}
if (!$objp->tosell && !$objp->tobuy) {
$prodser[$objp->fk_product_type]['none'] += $objp->total;
}
} }
if ($conf->use_javascript_ajax) if ($conf->use_javascript_ajax) {
{
print '<div class="div-table-responsive-no-min">'; print '<div class="div-table-responsive-no-min">';
print '<table class="noborder centpercent">'; print '<table class="noborder centpercent">';
print '<tr class="liste_titre"><th>'.$langs->trans("Statistics").'</th></tr>'; print '<tr class="liste_titre"><th>'.$langs->trans("Statistics").'</th></tr>';
@ -164,14 +178,12 @@ if ((!empty($conf->product->enabled) || !empty($conf->service->enabled)) && ($us
$total = $SommeA + $SommeB + $SommeC + $SommeD + $SommeE + $SommeF; $total = $SommeA + $SommeB + $SommeC + $SommeD + $SommeE + $SommeF;
$dataseries = array(); $dataseries = array();
if (!empty($conf->product->enabled)) if (!empty($conf->product->enabled)) {
{
$dataseries[] = array($langs->transnoentitiesnoconv("ProductsOnSale"), round($SommeA)); $dataseries[] = array($langs->transnoentitiesnoconv("ProductsOnSale"), round($SommeA));
$dataseries[] = array($langs->transnoentitiesnoconv("ProductsOnPurchase"), round($SommeB)); $dataseries[] = array($langs->transnoentitiesnoconv("ProductsOnPurchase"), round($SommeB));
$dataseries[] = array($langs->transnoentitiesnoconv("ProductsNotOnSell"), round($SommeC)); $dataseries[] = array($langs->transnoentitiesnoconv("ProductsNotOnSell"), round($SommeC));
} }
if (!empty($conf->service->enabled)) if (!empty($conf->service->enabled)) {
{
$dataseries[] = array($langs->transnoentitiesnoconv("ServicesOnSale"), round($SommeD)); $dataseries[] = array($langs->transnoentitiesnoconv("ServicesOnSale"), round($SommeD));
$dataseries[] = array($langs->transnoentitiesnoconv("ServicesOnPurchase"), round($SommeE)); $dataseries[] = array($langs->transnoentitiesnoconv("ServicesOnPurchase"), round($SommeE));
$dataseries[] = array($langs->transnoentitiesnoconv("ServicesNotOnSell"), round($SommeF)); $dataseries[] = array($langs->transnoentitiesnoconv("ServicesNotOnSell"), round($SommeF));
@ -193,8 +205,7 @@ if ((!empty($conf->product->enabled) || !empty($conf->service->enabled)) && ($us
} }
if (!empty($conf->categorie->enabled) && !empty($conf->global->CATEGORY_GRAPHSTATS_ON_PRODUCTS)) if (!empty($conf->categorie->enabled) && !empty($conf->global->CATEGORY_GRAPHSTATS_ON_PRODUCTS)) {
{
require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
print '<br>'; print '<br>';
print '<div class="div-table-responsive-no-min">'; print '<div class="div-table-responsive-no-min">';
@ -209,20 +220,16 @@ if (!empty($conf->categorie->enabled) && !empty($conf->global->CATEGORY_GRAPHSTA
$sql .= " GROUP BY c.label"; $sql .= " GROUP BY c.label";
$total = 0; $total = 0;
$result = $db->query($sql); $result = $db->query($sql);
if ($result) if ($result) {
{
$num = $db->num_rows($result); $num = $db->num_rows($result);
$i = 0; $i = 0;
if (!empty($conf->use_javascript_ajax)) if (!empty($conf->use_javascript_ajax)) {
{
$dataseries = array(); $dataseries = array();
$rest = 0; $rest = 0;
$nbmax = 10; $nbmax = 10;
while ($i < $num) while ($i < $num) {
{
$obj = $db->fetch_object($result); $obj = $db->fetch_object($result);
if ($i < $nbmax) if ($i < $nbmax) {
{
$dataseries[] = array($obj->label, round($obj->nb)); $dataseries[] = array($obj->label, round($obj->nb));
} else { } else {
$rest += $obj->nb; $rest += $obj->nb;
@ -230,8 +237,7 @@ if (!empty($conf->categorie->enabled) && !empty($conf->global->CATEGORY_GRAPHSTA
$total += $obj->nb; $total += $obj->nb;
$i++; $i++;
} }
if ($i > $nbmax) if ($i > $nbmax) {
{
$dataseries[] = array($langs->trans("Other"), round($rest)); $dataseries[] = array($langs->trans("Other"), round($rest));
} }
@ -245,8 +251,7 @@ if (!empty($conf->categorie->enabled) && !empty($conf->global->CATEGORY_GRAPHSTA
$dolgraph->draw('idstatscategproduct'); $dolgraph->draw('idstatscategproduct');
print $dolgraph->show($total ? 0 : 1); print $dolgraph->show($total ? 0 : 1);
} else { } else {
while ($i < $num) while ($i < $num) {
{
$obj = $db->fetch_object($result); $obj = $db->fetch_object($result);
print '<tr><td>'.$obj->label.'</td><td>'.$obj->nb.'</td></tr>'; print '<tr><td>'.$obj->label.'</td><td>'.$obj->nb.'</td></tr>';
@ -268,15 +273,16 @@ print '</div><div class="fichetwothirdright"><div class="ficheaddleft">';
/* /*
* Latest modified products * Latest modified products
*/ */
if ((!empty($conf->product->enabled) || !empty($conf->service->enabled)) && ($user->rights->produit->lire || $user->rights->service->lire)) if ((!empty($conf->product->enabled) || !empty($conf->service->enabled)) && ($user->rights->produit->lire || $user->rights->service->lire)) {
{
$max = 15; $max = 15;
$sql = "SELECT p.rowid, p.label, p.price, p.ref, p.fk_product_type, p.tosell, p.tobuy, p.tobatch, p.fk_price_expression,"; $sql = "SELECT p.rowid, p.label, p.price, p.ref, p.fk_product_type, p.tosell, p.tobuy, p.tobatch, p.fk_price_expression,";
$sql .= " p.entity,"; $sql .= " p.entity,";
$sql .= " p.tms as datem"; $sql .= " p.tms as datem";
$sql .= " FROM ".MAIN_DB_PREFIX."product as p"; $sql .= " FROM ".MAIN_DB_PREFIX."product as p";
$sql .= " WHERE p.entity IN (".getEntity($product_static->element, 1).")"; $sql .= " WHERE p.entity IN (".getEntity($product_static->element, 1).")";
if ($type != '') $sql .= " AND p.fk_product_type = ".$type; if ($type != '') {
$sql .= " AND p.fk_product_type = ".$type;
}
// Add where from hooks // Add where from hooks
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook
@ -286,30 +292,33 @@ if ((!empty($conf->product->enabled) || !empty($conf->service->enabled)) && ($us
//print $sql; //print $sql;
$result = $db->query($sql); $result = $db->query($sql);
if ($result) if ($result) {
{
$num = $db->num_rows($result); $num = $db->num_rows($result);
$i = 0; $i = 0;
if ($num > 0) if ($num > 0) {
{
$transRecordedType = $langs->trans("LastModifiedProductsAndServices", $max); $transRecordedType = $langs->trans("LastModifiedProductsAndServices", $max);
if (isset($_GET["type"]) && $_GET["type"] == 0) $transRecordedType = $langs->trans("LastRecordedProducts", $max); if (isset($_GET["type"]) && $_GET["type"] == 0) {
if (isset($_GET["type"]) && $_GET["type"] == 1) $transRecordedType = $langs->trans("LastRecordedServices", $max); $transRecordedType = $langs->trans("LastRecordedProducts", $max);
}
if (isset($_GET["type"]) && $_GET["type"] == 1) {
$transRecordedType = $langs->trans("LastRecordedServices", $max);
}
print '<div class="div-table-responsive-no-min">'; print '<div class="div-table-responsive-no-min">';
print '<table class="noborder centpercent">'; print '<table class="noborder centpercent">';
$colnb = 2; $colnb = 2;
if (empty($conf->global->PRODUIT_MULTIPRICES)) $colnb++; if (empty($conf->global->PRODUIT_MULTIPRICES)) {
$colnb++;
}
print '<tr class="liste_titre"><th colspan="'.$colnb.'">'.$transRecordedType.'</th>'; print '<tr class="liste_titre"><th colspan="'.$colnb.'">'.$transRecordedType.'</th>';
print '<th class="right" colspan="3"><a href="'.DOL_URL_ROOT.'/product/list.php?sortfield=p.tms&sortorder=DESC">'.$langs->trans("FullList").'</td>'; print '<th class="right" colspan="3"><a href="'.DOL_URL_ROOT.'/product/list.php?sortfield=p.tms&sortorder=DESC">'.$langs->trans("FullList").'</td>';
print '</tr>'; print '</tr>';
while ($i < $num) while ($i < $num) {
{
$objp = $db->fetch_object($result); $objp = $db->fetch_object($result);
$product_static->id = $objp->rowid; $product_static->id = $objp->rowid;
@ -322,18 +331,18 @@ if ((!empty($conf->product->enabled) || !empty($conf->service->enabled)) && ($us
$product_static->status_batch = $objp->tobatch; $product_static->status_batch = $objp->tobatch;
//Multilangs //Multilangs
if (!empty($conf->global->MAIN_MULTILANGS)) if (!empty($conf->global->MAIN_MULTILANGS)) {
{
$sql = "SELECT label"; $sql = "SELECT label";
$sql .= " FROM ".MAIN_DB_PREFIX."product_lang"; $sql .= " FROM ".MAIN_DB_PREFIX."product_lang";
$sql .= " WHERE fk_product=".$objp->rowid; $sql .= " WHERE fk_product=".$objp->rowid;
$sql .= " AND lang='".$db->escape($langs->getDefaultLang())."'"; $sql .= " AND lang='".$db->escape($langs->getDefaultLang())."'";
$resultd = $db->query($sql); $resultd = $db->query($sql);
if ($resultd) if ($resultd) {
{
$objtp = $db->fetch_object($resultd); $objtp = $db->fetch_object($resultd);
if ($objtp && $objtp->label != '') $objp->label = $objtp->label; if ($objtp && $objtp->label != '') {
$objp->label = $objtp->label;
}
} }
} }
@ -347,10 +356,8 @@ if ((!empty($conf->product->enabled) || !empty($conf->service->enabled)) && ($us
print dol_print_date($db->jdate($objp->datem), 'day'); print dol_print_date($db->jdate($objp->datem), 'day');
print "</td>"; print "</td>";
// Sell price // Sell price
if (empty($conf->global->PRODUIT_MULTIPRICES)) if (empty($conf->global->PRODUIT_MULTIPRICES)) {
{ if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_price_expression)) {
if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_price_expression))
{
$product = new Product($db); $product = new Product($db);
$product->fetch($objp->rowid); $product->fetch($objp->rowid);
$priceparser = new PriceParser($db); $priceparser = new PriceParser($db);
@ -360,8 +367,11 @@ if ((!empty($conf->product->enabled) || !empty($conf->service->enabled)) && ($us
} }
} }
print '<td class="nowrap right">'; print '<td class="nowrap right">';
if (isset($objp->price_base_type) && $objp->price_base_type == 'TTC') print price($objp->price_ttc).' '.$langs->trans("TTC"); if (isset($objp->price_base_type) && $objp->price_base_type == 'TTC') {
else print price($objp->price).' '.$langs->trans("HT"); print price($objp->price_ttc).' '.$langs->trans("TTC");
} else {
print price($objp->price).' '.$langs->trans("HT");
}
print '</td>'; print '</td>';
} }
print '<td class="right nowrap width25"><span class="statusrefsell">'; print '<td class="right nowrap width25"><span class="statusrefsell">';
@ -389,10 +399,13 @@ if ((!empty($conf->product->enabled) || !empty($conf->service->enabled)) && ($us
// TODO Move this into a page that should be available into menu "accountancy - report - turnover - per quarter" // TODO Move this into a page that should be available into menu "accountancy - report - turnover - per quarter"
// Also method used for counting must provide the 2 possible methods like done by all other reports into menu "accountancy - report - turnover": // Also method used for counting must provide the 2 possible methods like done by all other reports into menu "accountancy - report - turnover":
// "commitment engagment" method and "cash accounting" method // "commitment engagment" method and "cash accounting" method
if (!empty($conf->global->MAIN_SHOW_PRODUCT_ACTIVITY_TRIM)) if (!empty($conf->global->MAIN_SHOW_PRODUCT_ACTIVITY_TRIM)) {
{ if (!empty($conf->product->enabled)) {
if (!empty($conf->product->enabled)) activitytrim(0); activitytrim(0);
if (!empty($conf->service->enabled)) activitytrim(1); }
if (!empty($conf->service->enabled)) {
activitytrim(1);
}
} }
@ -433,8 +446,7 @@ function activitytrim($product_type)
$sql .= " ORDER BY annee, mois "; $sql .= " ORDER BY annee, mois ";
$result = $db->query($sql); $result = $db->query($sql);
if ($result) if ($result) {
{
$tmpyear = 0; $tmpyear = 0;
$trim1 = 0; $trim1 = 0;
$trim2 = 0; $trim2 = 0;
@ -443,14 +455,15 @@ function activitytrim($product_type)
$lgn = 0; $lgn = 0;
$num = $db->num_rows($result); $num = $db->num_rows($result);
if ($num > 0) if ($num > 0) {
{
print '<div class="div-table-responsive-no-min">'; print '<div class="div-table-responsive-no-min">';
print '<table class="noborder" width="75%">'; print '<table class="noborder" width="75%">';
if ($product_type == 0) if ($product_type == 0) {
print '<tr class="liste_titre"><td class=left>'.$langs->trans("ProductSellByQuarterHT").'</td>'; print '<tr class="liste_titre"><td class=left>'.$langs->trans("ProductSellByQuarterHT").'</td>';
else print '<tr class="liste_titre"><td class=left>'.$langs->trans("ServiceSellByQuarterHT").'</td>'; } else {
print '<tr class="liste_titre"><td class=left>'.$langs->trans("ServiceSellByQuarterHT").'</td>';
}
print '<td class=right>'.$langs->trans("Quarter1").'</td>'; print '<td class=right>'.$langs->trans("Quarter1").'</td>';
print '<td class=right>'.$langs->trans("Quarter2").'</td>'; print '<td class=right>'.$langs->trans("Quarter2").'</td>';
print '<td class=right>'.$langs->trans("Quarter3").'</td>'; print '<td class=right>'.$langs->trans("Quarter3").'</td>';
@ -460,13 +473,10 @@ function activitytrim($product_type)
} }
$i = 0; $i = 0;
while ($i < $num) while ($i < $num) {
{
$objp = $db->fetch_object($result); $objp = $db->fetch_object($result);
if ($tmpyear != $objp->annee) if ($tmpyear != $objp->annee) {
{ if ($trim1 + $trim2 + $trim3 + $trim4 > 0) {
if ($trim1 + $trim2 + $trim3 + $trim4 > 0)
{
print '<tr class="oddeven"><td class=left>'.$tmpyear.'</td>'; print '<tr class="oddeven"><td class=left>'.$tmpyear.'</td>';
print '<td class="nowrap right">'.price($trim1).'</td>'; print '<td class="nowrap right">'.price($trim1).'</td>';
print '<td class="nowrap right">'.price($trim2).'</td>'; print '<td class="nowrap right">'.price($trim2).'</td>';
@ -484,22 +494,25 @@ function activitytrim($product_type)
$trim4 = 0; $trim4 = 0;
} }
if ($objp->mois == "01" || $objp->mois == "02" || $objp->mois == "03") if ($objp->mois == "01" || $objp->mois == "02" || $objp->mois == "03") {
$trim1 += $objp->Mnttot; $trim1 += $objp->Mnttot;
}
if ($objp->mois == "04" || $objp->mois == "05" || $objp->mois == "06") if ($objp->mois == "04" || $objp->mois == "05" || $objp->mois == "06") {
$trim2 += $objp->Mnttot; $trim2 += $objp->Mnttot;
}
if ($objp->mois == "07" || $objp->mois == "08" || $objp->mois == "09") if ($objp->mois == "07" || $objp->mois == "08" || $objp->mois == "09") {
$trim3 += $objp->Mnttot; $trim3 += $objp->Mnttot;
}
if ($objp->mois == "10" || $objp->mois == "11" || $objp->mois == "12") if ($objp->mois == "10" || $objp->mois == "11" || $objp->mois == "12") {
$trim4 += $objp->Mnttot; $trim4 += $objp->Mnttot;
}
$i++; $i++;
} }
if ($trim1 + $trim2 + $trim3 + $trim4 > 0) if ($trim1 + $trim2 + $trim3 + $trim4 > 0) {
{
print '<tr class="oddeven"><td class=left>'.$tmpyear.'</td>'; print '<tr class="oddeven"><td class=left>'.$tmpyear.'</td>';
print '<td class="nowrap right">'.price($trim1).'</td>'; print '<td class="nowrap right">'.price($trim1).'</td>';
print '<td class="nowrap right">'.price($trim2).'</td>'; print '<td class="nowrap right">'.price($trim2).'</td>';
@ -508,7 +521,8 @@ function activitytrim($product_type)
print '<td class="nowrap right">'.price($trim1 + $trim2 + $trim3 + $trim4).'</td>'; print '<td class="nowrap right">'.price($trim1 + $trim2 + $trim3 + $trim4).'</td>';
print '</tr>'; print '</tr>';
} }
if ($num > 0) if ($num > 0) {
print '</table></div>'; print '</table></div>';
} }
} }
}

View File

@ -6,16 +6,16 @@ require_once DOL_DOCUMENT_ROOT.'/product/inventory/class/inventory.class.php';
$get = GETPOST('get', 'alpha'); $get = GETPOST('get', 'alpha');
$put = GETPOST('put', 'alpha'); $put = GETPOST('put', 'alpha');
switch ($put) switch ($put) {
{
case 'qty': case 'qty':
if (empty($user->rights->stock->creer)) { echo -1; exit; } if (empty($user->rights->stock->creer)) {
echo -1; exit;
}
$fk_det_inventory = GETPOST('fk_det_inventory'); $fk_det_inventory = GETPOST('fk_det_inventory');
$det = new InventoryLine($db); $det = new InventoryLine($db);
if ($det->fetch($fk_det_inventory)) if ($det->fetch($fk_det_inventory)) {
{
$det->qty_view += GETPOST('qty'); $det->qty_view += GETPOST('qty');
$res = $det->update($user); $res = $det->update($user);
@ -27,13 +27,14 @@ switch ($put)
break; break;
case 'pmp': case 'pmp':
if (empty($user->rights->stock->creer) || empty($user->rights->stock->changePMP)) { echo -1; exit; } if (empty($user->rights->stock->creer) || empty($user->rights->stock->changePMP)) {
echo -1; exit;
}
$fk_det_inventory = GETPOST('fk_det_inventory'); $fk_det_inventory = GETPOST('fk_det_inventory');
$det = new InventoryLine($db); $det = new InventoryLine($db);
if ($det->fetch($fk_det_inventory)) if ($det->fetch($fk_det_inventory)) {
{
$det->new_pmp = price2num(GETPOST('pmp')); $det->new_pmp = price2num(GETPOST('pmp'));
$det->update($user); $det->update($user);

View File

@ -40,8 +40,7 @@ $cancel = GETPOST('cancel', 'aZ09');
$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'inventorycard'; // To manage different context of search $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'inventorycard'; // To manage different context of search
$backtopage = GETPOST('backtopage', 'alpha'); $backtopage = GETPOST('backtopage', 'alpha');
if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) {
{
$result = restrictedArea($user, 'stock', $id); $result = restrictedArea($user, 'stock', $id);
} else { } else {
$result = restrictedArea($user, 'stock', $id, '', 'inventory_advance'); $result = restrictedArea($user, 'stock', $id, '', 'inventory_advance');
@ -61,12 +60,15 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_elemen
// Initialize array of search criterias // Initialize array of search criterias
$search_all = GETPOST("search_all", 'alpha'); $search_all = GETPOST("search_all", 'alpha');
$search = array(); $search = array();
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{ if (GETPOST('search_'.$key, 'alpha')) {
if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha'); $search[$key] = GETPOST('search_'.$key, 'alpha');
}
} }
if (empty($action) && empty($id) && empty($ref)) $action = 'view'; if (empty($action) && empty($id) && empty($ref)) {
$action = 'view';
}
// Load object // Load object
include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once.
@ -76,8 +78,7 @@ include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be includ
//if ($user->socid > 0) $socid = $user->socid; //if ($user->socid > 0) $socid = $user->socid;
//$result = restrictedArea($user, 'mymodule', $id); //$result = restrictedArea($user, 'mymodule', $id);
if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) {
{
$permissiontoread = $user->rights->stock->lire; $permissiontoread = $user->rights->stock->lire;
$permissiontoadd = $user->rights->stock->creer; $permissiontoadd = $user->rights->stock->creer;
$permissiontodelete = $user->rights->stock->supprimer; $permissiontodelete = $user->rights->stock->supprimer;
@ -100,18 +101,22 @@ if (empty($conf->global->MAIN_USE_ADVANCED_PERMS))
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if (empty($reshook)) if (empty($reshook)) {
{
$error = 0; $error = 0;
$backurlforlist = DOL_URL_ROOT.'/product/inventory/list.php'; $backurlforlist = DOL_URL_ROOT.'/product/inventory/list.php';
if (empty($backtopage) || ($cancel && empty($id))) { if (empty($backtopage) || ($cancel && empty($id))) {
if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) { if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) {
if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) $backtopage = $backurlforlist; if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) {
else $backtopage = dol_buildpath('/product/inventory/card.php', 1).'?id='.($id > 0 ? $id : '__ID__'); $backtopage = $backurlforlist;
} else {
$backtopage = dol_buildpath('/product/inventory/card.php', 1).'?id='.($id > 0 ? $id : '__ID__');
}
} }
} }
$triggermodname = 'STOCK_INVENTORY_MODIFY'; // Name of trigger action code to execute when we modify record $triggermodname = 'STOCK_INVENTORY_MODIFY'; // Name of trigger action code to execute when we modify record
@ -135,8 +140,7 @@ if (empty($reshook))
{ {
$object->setValueFrom('fk_soc', GETPOST('fk_soc', 'int'), '', '', 'date', '', $user, 'MYOBJECT_MODIFY'); $object->setValueFrom('fk_soc', GETPOST('fk_soc', 'int'), '', '', 'date', '', $user, 'MYOBJECT_MODIFY');
}*/ }*/
if ($action == 'classin' && $permissiontoadd) if ($action == 'classin' && $permissiontoadd) {
{
$object->setProject(GETPOST('projectid', 'int')); $object->setProject(GETPOST('projectid', 'int'));
} }
@ -179,15 +183,18 @@ jQuery(document).ready(function() {
// Part to create // Part to create
if ($action == 'create') if ($action == 'create') {
{
print load_fiche_titre($langs->trans("NewInventory"), '', 'product'); print load_fiche_titre($langs->trans("NewInventory"), '', 'product');
print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="action" value="add">'; print '<input type="hidden" name="action" value="add">';
if ($backtopage) print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; if ($backtopage) {
if ($backtopageforcancel) print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">'; print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
}
if ($backtopageforcancel) {
print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">';
}
print dol_get_fiche_head(array(), ''); print dol_get_fiche_head(array(), '');
@ -218,16 +225,19 @@ if ($action == 'create')
} }
// Part to edit record // Part to edit record
if (($id || $ref) && $action == 'edit') if (($id || $ref) && $action == 'edit') {
{
print load_fiche_titre($langs->trans("Inventory"), '', 'product'); print load_fiche_titre($langs->trans("Inventory"), '', 'product');
print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="action" value="update">'; print '<input type="hidden" name="action" value="update">';
print '<input type="hidden" name="id" value="'.$object->id.'">'; print '<input type="hidden" name="id" value="'.$object->id.'">';
if ($backtopage) print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; if ($backtopage) {
if ($backtopageforcancel) print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">'; print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
}
if ($backtopageforcancel) {
print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">';
}
print dol_get_fiche_head(); print dol_get_fiche_head();
@ -251,8 +261,7 @@ if (($id || $ref) && $action == 'edit')
} }
// Part to show record // Part to show record
if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) {
{
$res = $object->fetch_optionals(); $res = $object->fetch_optionals();
$head = inventoryPrepareHead($object); $head = inventoryPrepareHead($object);
@ -277,8 +286,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
} }
// Confirmation of action xxxx // Confirmation of action xxxx
if ($action == 'xxx') if ($action == 'xxx') {
{
$formquestion = array(); $formquestion = array();
/* /*
$forcecombo=0; $forcecombo=0;
@ -296,8 +304,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
// Call Hook formConfirm // Call Hook formConfirm
$parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid); $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid);
$reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; if (empty($reshook)) {
elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; $formconfirm .= $hookmanager->resPrint;
} elseif ($reshook > 0) {
$formconfirm = $hookmanager->resPrint;
}
// Print form confirm // Print form confirm
print $formconfirm; print $formconfirm;
@ -378,29 +389,26 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
print '<div class="tabsAction">'."\n"; print '<div class="tabsAction">'."\n";
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if (empty($reshook)) if (empty($reshook)) {
{
// Send // Send
if (empty($user->socid)) { if (empty($user->socid)) {
print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=presend&mode=init#formmailbeforetitle">'.$langs->trans('SendMail').'</a>'."\n"; print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=presend&mode=init#formmailbeforetitle">'.$langs->trans('SendMail').'</a>'."\n";
} }
// Back to draft // Back to draft
if ($object->status == $object::STATUS_VALIDATED) if ($object->status == $object::STATUS_VALIDATED) {
{ if ($permissiontoadd) {
if ($permissiontoadd)
{
print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=confirm_setdraft&confirm=yes">'.$langs->trans("SetToDraft").'</a>'; print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=confirm_setdraft&confirm=yes">'.$langs->trans("SetToDraft").'</a>';
} }
} }
// Modify // Modify
if ($object->status == $object::STATUS_DRAFT) if ($object->status == $object::STATUS_DRAFT) {
{ if ($permissiontoadd) {
if ($permissiontoadd)
{
print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=edit">'.$langs->trans("Modify").'</a>'."\n"; print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=edit">'.$langs->trans("Modify").'</a>'."\n";
} else { } else {
print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Modify').'</a>'."\n"; print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Modify').'</a>'."\n";
@ -408,10 +416,8 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
} }
// Validate // Validate
if ($object->status == $object::STATUS_DRAFT) if ($object->status == $object::STATUS_DRAFT) {
{ if ($permissiontoadd) {
if ($permissiontoadd)
{
print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=confirm_validate&confirm=yes">'.$langs->trans("Validate").' ('.$langs->trans("Start").')</a>'; print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=confirm_validate&confirm=yes">'.$langs->trans("Validate").' ('.$langs->trans("Start").')</a>';
} }
} }
@ -423,8 +429,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
}*/ }*/
// Delete (need delete permission, or if draft, just need create/modify permission) // Delete (need delete permission, or if draft, just need create/modify permission)
if ($permissiontodelete || ($object->status == $object::STATUS_DRAFT && $permissiontoadd)) if ($permissiontodelete || ($object->status == $object::STATUS_DRAFT && $permissiontoadd)) {
{
print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans('Delete').'</a>'."\n"; print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans('Delete').'</a>'."\n";
} else { } else {
print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Delete').'</a>'."\n"; print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Delete').'</a>'."\n";
@ -439,8 +444,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
$action = 'presend'; $action = 'presend';
} }
if ($action != 'presend') if ($action != 'presend') {
{
print '<div class="fichecenter"><div class="fichehalfleft">'; print '<div class="fichecenter"><div class="fichehalfleft">';
print '<a name="builddoc"></a>'; // ancre print '<a name="builddoc"></a>'; // ancre
@ -478,7 +482,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
//Select mail models is same action as presend //Select mail models is same action as presend
if (GETPOST('modelselected')) $action = 'presend'; if (GETPOST('modelselected')) {
$action = 'presend';
}
// Presend form // Presend form
$modelmail = 'inventory'; $modelmail = 'inventory';

View File

@ -222,8 +222,12 @@ class Inventory extends CommonObject
$this->db = $db; $this->db = $db;
if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) $this->fields['rowid']['visible'] = 0; if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) {
if (empty($conf->multicompany->enabled)) $this->fields['entity']['enabled'] = 0; $this->fields['rowid']['visible'] = 0;
}
if (empty($conf->multicompany->enabled)) {
$this->fields['entity']['enabled'] = 0;
}
} }
@ -272,20 +276,24 @@ class Inventory extends CommonObject
$sql .= ' '.MAIN_DB_PREFIX.'product as p, '.MAIN_DB_PREFIX.'entrepot as e'; $sql .= ' '.MAIN_DB_PREFIX.'product as p, '.MAIN_DB_PREFIX.'entrepot as e';
$sql .= ' WHERE p.entity IN ('.getEntity('product').')'; $sql .= ' WHERE p.entity IN ('.getEntity('product').')';
$sql .= ' AND ps.fk_product = p.rowid AND ps.fk_entrepot = e.rowid'; $sql .= ' AND ps.fk_product = p.rowid AND ps.fk_entrepot = e.rowid';
if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) $sql .= " AND p.fk_product_type = 0"; if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
if ($this->fk_product > 0) $sql .= ' AND ps.fk_product = '.$this->fk_product; $sql .= " AND p.fk_product_type = 0";
if ($this->fk_warehouse > 0) $sql .= ' AND ps.fk_entrepot = '.$this->fk_warehouse; }
if ($this->fk_product > 0) {
$sql .= ' AND ps.fk_product = '.$this->fk_product;
}
if ($this->fk_warehouse > 0) {
$sql .= ' AND ps.fk_entrepot = '.$this->fk_warehouse;
}
$inventoryline = new InventoryLine($this->db); $inventoryline = new InventoryLine($this->db);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{
$num = $this->db->num_rows($resql); $num = $this->db->num_rows($resql);
$i = 0; $i = 0;
while ($i < $num) while ($i < $num) {
{
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
$inventoryline->fk_inventory = $this->id; $inventoryline->fk_inventory = $this->id;
@ -464,8 +472,7 @@ class Inventory extends CommonObject
*/ */
public function deleteLine(User $user, $idline, $notrigger = false) public function deleteLine(User $user, $idline, $notrigger = false)
{ {
if ($this->status < 0) if ($this->status < 0) {
{
$this->error = 'ErrorDeleteLineNotAllowedByObjectStatus'; $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
return -2; return -2;
} }
@ -489,7 +496,9 @@ class Inventory extends CommonObject
global $dolibarr_main_authentication, $dolibarr_main_demo; global $dolibarr_main_authentication, $dolibarr_main_demo;
global $menumanager; global $menumanager;
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 = ''; $result = '';
$companylink = ''; $companylink = '';
@ -501,24 +510,28 @@ class Inventory extends CommonObject
$url = dol_buildpath('/product/inventory/card.php', 1).'?id='.$this->id; $url = dol_buildpath('/product/inventory/card.php', 1).'?id='.$this->id;
$linkclose = ''; $linkclose = '';
if (empty($notooltip)) if (empty($notooltip)) {
{ if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
{
$label = $langs->trans("ShowInventory"); $label = $langs->trans("ShowInventory");
$linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
} }
$linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
$linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
} else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); } else {
$linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
}
$linkstart = '<a href="'.$url.'"'; $linkstart = '<a href="'.$url.'"';
$linkstart .= $linkclose.'>'; $linkstart .= $linkclose.'>';
$linkend = '</a>'; $linkend = '</a>';
$result .= $linkstart; $result .= $linkstart;
if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); if ($withpicto) {
if ($withpicto != 2) $result .= $this->ref; $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
}
if ($withpicto != 2) {
$result .= $this->ref;
}
$result .= $linkend; $result .= $linkend;
//if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
@ -573,28 +586,23 @@ class Inventory extends CommonObject
$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
$sql .= ' WHERE t.rowid = '.$id; $sql .= ' WHERE t.rowid = '.$id;
$result = $this->db->query($sql); $result = $this->db->query($sql);
if ($result) if ($result) {
{ if ($this->db->num_rows($result)) {
if ($this->db->num_rows($result))
{
$obj = $this->db->fetch_object($result); $obj = $this->db->fetch_object($result);
$this->id = $obj->rowid; $this->id = $obj->rowid;
if ($obj->fk_user_author) if ($obj->fk_user_author) {
{
$cuser = new User($this->db); $cuser = new User($this->db);
$cuser->fetch($obj->fk_user_author); $cuser->fetch($obj->fk_user_author);
$this->user_creation = $cuser; $this->user_creation = $cuser;
} }
if ($obj->fk_user_valid) if ($obj->fk_user_valid) {
{
$vuser = new User($this->db); $vuser = new User($this->db);
$vuser->fetch($obj->fk_user_valid); $vuser->fetch($obj->fk_user_valid);
$this->user_validation = $vuser; $this->user_validation = $vuser;
} }
if ($obj->fk_user_cloture) if ($obj->fk_user_cloture) {
{
$cluser = new User($this->db); $cluser = new User($this->db);
$cluser->fetch($obj->fk_user_cloture); $cluser->fetch($obj->fk_user_cloture);
$this->user_cloture = $cluser; $this->user_cloture = $cluser;

View File

@ -45,8 +45,7 @@ $fk_product = GETPOST('fk_product', 'int');
$lineid = GETPOST('lineid', 'int'); $lineid = GETPOST('lineid', 'int');
$batch = GETPOST('batch', 'alphanohtml'); $batch = GETPOST('batch', 'alphanohtml');
if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) {
{
$result = restrictedArea($user, 'stock', $id); $result = restrictedArea($user, 'stock', $id);
} else { } else {
$result = restrictedArea($user, 'stock', $id, '', 'inventory_advance'); $result = restrictedArea($user, 'stock', $id, '', 'inventory_advance');
@ -66,12 +65,15 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_elemen
// Initialize array of search criterias // Initialize array of search criterias
$search_all = GETPOST("search_all", 'alpha'); $search_all = GETPOST("search_all", 'alpha');
$search = array(); $search = array();
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{ if (GETPOST('search_'.$key, 'alpha')) {
if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha'); $search[$key] = GETPOST('search_'.$key, 'alpha');
}
} }
if (empty($action) && empty($id) && empty($ref)) $action = 'view'; if (empty($action) && empty($id) && empty($ref)) {
$action = 'view';
}
// Load object // Load object
include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once.
@ -81,8 +83,7 @@ include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be includ
//if ($user->socid > 0) $socid = $user->socid; //if ($user->socid > 0) $socid = $user->socid;
//$result = restrictedArea($user, 'mymodule', $id); //$result = restrictedArea($user, 'mymodule', $id);
if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) {
{
$permissiontoadd = $user->rights->stock->creer; $permissiontoadd = $user->rights->stock->creer;
$permissiontodelete = $user->rights->stock->supprimer; $permissiontodelete = $user->rights->stock->supprimer;
} else { } else {
@ -99,10 +100,11 @@ $now = dol_now();
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if (empty($reshook)) if (empty($reshook)) {
{
$error = 0; $error = 0;
$backurlforlist = DOL_URL_ROOT.'/product/inventory/list.php'; $backurlforlist = DOL_URL_ROOT.'/product/inventory/list.php';
@ -197,8 +199,7 @@ jQuery(document).ready(function() {
// Part to show record // Part to show record
if ($object->id > 0) if ($object->id > 0) {
{
$res = $object->fetch_optionals(); $res = $object->fetch_optionals();
$head = inventoryPrepareHead($object); $head = inventoryPrepareHead($object);
@ -211,8 +212,7 @@ if ($object->id > 0)
$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteInventory'), $langs->trans('ConfirmDeleteOrder'), 'confirm_delete', '', 0, 1); $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteInventory'), $langs->trans('ConfirmDeleteOrder'), 'confirm_delete', '', 0, 1);
} }
// Confirmation to delete line // Confirmation to delete line
if ($action == 'deleteline') if ($action == 'deleteline') {
{
$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_deleteline', '', 0, 1); $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_deleteline', '', 0, 1);
} }
@ -226,8 +226,11 @@ if ($object->id > 0)
// Call Hook formConfirm // Call Hook formConfirm
$parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid); $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid);
$reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; if (empty($reshook)) {
elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; $formconfirm .= $hookmanager->resPrint;
} elseif ($reshook > 0) {
$formconfirm = $hookmanager->resPrint;
}
// Print form confirm // Print form confirm
print $formconfirm; print $formconfirm;
@ -309,7 +312,9 @@ if ($object->id > 0)
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="action" value="update">'; print '<input type="hidden" name="action" value="update">';
print '<input type="hidden" name="id" value="'.$object->id.'">'; print '<input type="hidden" name="id" value="'.$object->id.'">';
if ($backtopage) print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; if ($backtopage) {
print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
}
print '<div class="center">'; print '<div class="center">';
print '<span class="opacitymedium">'.$langs->trans("InventoryDesc").'</span><br>'; print '<span class="opacitymedium">'.$langs->trans("InventoryDesc").'</span><br>';
@ -323,24 +328,21 @@ if ($object->id > 0)
print '<div class="tabsAction">'."\n"; print '<div class="tabsAction">'."\n";
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if (empty($reshook)) if (empty($reshook)) {
{ if ($object->status == Inventory::STATUS_DRAFT) {
if ($object->status == Inventory::STATUS_DRAFT) if ($permissiontoadd) {
{
if ($permissiontoadd)
{
print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_validate&confirm=yes">'.$langs->trans("Validate").' ('.$langs->trans("Start").')</a>'."\n"; print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_validate&confirm=yes">'.$langs->trans("Validate").' ('.$langs->trans("Start").')</a>'."\n";
} else { } else {
print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Validate').' ('.$langs->trans("Start").')</a>'."\n"; print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Validate').' ('.$langs->trans("Start").')</a>'."\n";
} }
} }
if ($object->status == Inventory::STATUS_VALIDATED) if ($object->status == Inventory::STATUS_VALIDATED) {
{ if ($permissiontoadd) {
if ($permissiontoadd)
{
/* /*
if (!empty($conf->barcode->enabled)) { if (!empty($conf->barcode->enabled)) {
print '<a href="#" class="butAction">'.$langs->trans("UpdateByScaningProductBarcode").'</a>'; print '<a href="#" class="butAction">'.$langs->trans("UpdateByScaningProductBarcode").'</a>';
@ -356,10 +358,8 @@ if ($object->id > 0)
} }
} }
if ($object->status == Inventory::STATUS_VALIDATED) if ($object->status == Inventory::STATUS_VALIDATED) {
{ if ($permissiontoadd) {
if ($permissiontoadd)
{
print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=record">'.$langs->trans("Finish").'</a>'."\n"; print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=record">'.$langs->trans("Finish").'</a>'."\n";
} else { } else {
print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Finish').'</a>'."\n"; print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Finish').'</a>'."\n";
@ -394,7 +394,9 @@ if ($object->id > 0)
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="action" value="updateinventorylines">'; print '<input type="hidden" name="action" value="updateinventorylines">';
print '<input type="hidden" name="id" value="'.$object->id.'">'; print '<input type="hidden" name="id" value="'.$object->id.'">';
if ($backtopage) print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; if ($backtopage) {
print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
}
print '<div class="fichecenter">'; print '<div class="fichecenter">';
//print '<div class="fichehalfleft">'; //print '<div class="fichehalfleft">';
@ -459,14 +461,12 @@ if ($object->id > 0)
//$sql = ''; //$sql = '';
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
$i = 0; $i = 0;
$totalarray = array(); $totalarray = array();
while ($i < $num) while ($i < $num) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
if (is_object($cacheOfWarehouses[$obj->fk_warehouse])) { if (is_object($cacheOfWarehouses[$obj->fk_warehouse])) {

View File

@ -48,7 +48,9 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST('sortfield', 'aZ09comma'); $sortfield = GETPOST('sortfield', 'aZ09comma');
$sortorder = GETPOST('sortorder', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) { $page = 0; } // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) {
$page = 0;
} // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
@ -63,18 +65,20 @@ $extrafields->fetch_name_optionals_label($object->table_element);
$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
// Default sort order (if not yet defined by previous GETPOST) // Default sort order (if not yet defined by previous GETPOST)
if (!$sortfield) $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition. if (!$sortfield) {
if (!$sortorder) $sortorder = "ASC"; $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition.
}
if (!$sortorder) {
$sortorder = "ASC";
}
// Security check // Security check
$socid = 0; $socid = 0;
if ($user->socid > 0) // Protection if external user if ($user->socid > 0) { // Protection if external user
{
//$socid = $user->socid; //$socid = $user->socid;
accessforbidden(); accessforbidden();
} }
if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) {
{
$result = restrictedArea($user, 'stock', $objectid); $result = restrictedArea($user, 'stock', $objectid);
} else { } else {
$result = restrictedArea($user, 'stock', $objectid, '', 'inventory_advance'); $result = restrictedArea($user, 'stock', $objectid, '', 'inventory_advance');
@ -83,30 +87,31 @@ if (empty($conf->global->MAIN_USE_ADVANCED_PERMS))
// Initialize array of search criterias // Initialize array of search criterias
$search_all = GETPOST("search_all", 'alpha'); $search_all = GETPOST("search_all", 'alpha');
$search = array(); $search = array();
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{ if (GETPOST('search_'.$key, 'alpha')) {
if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha'); $search[$key] = GETPOST('search_'.$key, 'alpha');
}
} }
// List of fields to search into when doing a "search in all" // List of fields to search into when doing a "search in all"
$fieldstosearchall = array(); $fieldstosearchall = array();
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{ if ($val['searchall']) {
if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label']; $fieldstosearchall['t.'.$key] = $val['label'];
}
} }
// Definition of fields for list // Definition of fields for list
$arrayfields = array(); $arrayfields = array();
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{
// If $val['visible']==0, then we never show the field // If $val['visible']==0, then we never show the field
if (!empty($val['visible'])) $arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>($val['enabled'] && ($val['visible'] != 3)), 'position'=>$val['position']); if (!empty($val['visible'])) {
$arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>($val['enabled'] && ($val['visible'] != 3)), 'position'=>$val['position']);
}
} }
// Extra fields // Extra fields
if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) {
{ foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val)
{
if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) { if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) {
$arrayfields["ef.".$key] = array( $arrayfields["ef.".$key] = array(
'label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'label'=>$extrafields->attributes[$object->table_element]['label'][$key],
@ -129,31 +134,33 @@ $permissiontodelete = $user->rights->stock->supprimer;
* Actions * Actions
*/ */
if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } if (GETPOST('cancel', 'alpha')) {
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } $action = 'list'; $massaction = '';
}
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
$massaction = '';
}
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if (empty($reshook)) if (empty($reshook)) {
{
// Selection of new fields // Selection of new fields
include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
// Purge search criteria // Purge search criteria
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
{ foreach ($object->fields as $key => $val) {
foreach ($object->fields as $key => $val)
{
$search[$key] = ''; $search[$key] = '';
} }
$toselect = ''; $toselect = '';
$search_array_options = array(); $search_array_options = array();
} }
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') 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')) || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) {
{
$massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation
} }
@ -182,13 +189,14 @@ $title = $langs->trans('ListOfInventories');
// Build and execute select // Build and execute select
// -------------------------------------------------------------------- // --------------------------------------------------------------------
$sql = 'SELECT '; $sql = 'SELECT ';
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{
$sql .= 't.'.$key.', '; $sql .= 't.'.$key.', ';
} }
// Add fields from extrafields // Add fields from extrafields
if (!empty($extrafields->attributes[$object->table_element]['label'])) { if (!empty($extrafields->attributes[$object->table_element]['label'])) {
foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.' as options_'.$key.', ' : ''); foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
$sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.' as options_'.$key.', ' : '');
}
} }
// Add fields from hooks // Add fields from hooks
$parameters = array(); $parameters = array();
@ -196,20 +204,32 @@ $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $obje
$sql .= preg_replace('/^,/', '', $hookmanager->resPrint); $sql .= preg_replace('/^,/', '', $hookmanager->resPrint);
$sql = preg_replace('/,\s*$/', '', $sql); $sql = preg_replace('/,\s*$/', '', $sql);
$sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t"; $sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t";
if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) {
if ($object->ismultientitymanaged == 1) $sql .= " WHERE t.entity IN (".getEntity($object->element).")"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)";
else $sql .= " WHERE 1 = 1"; }
foreach ($search as $key => $val) if ($object->ismultientitymanaged == 1) {
{ $sql .= " WHERE t.entity IN (".getEntity($object->element).")";
if ($key == 'status' && $search[$key] == -1) continue; } else {
$sql .= " WHERE 1 = 1";
}
foreach ($search as $key => $val) {
if ($key == 'status' && $search[$key] == -1) {
continue;
}
$mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0); $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0);
if (strpos($object->fields[$key]['type'], 'integer:') === 0) { if (strpos($object->fields[$key]['type'], 'integer:') === 0) {
if ($search[$key] == '-1') $search[$key] = ''; if ($search[$key] == '-1') {
$search[$key] = '';
}
$mode_search = 2; $mode_search = 2;
} }
if ($search[$key] != '') $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search)); if ($search[$key] != '') {
$sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search));
}
}
if ($search_all) {
$sql .= natural_search(array_keys($fieldstosearchall), $search_all);
} }
if ($search_all) $sql .= natural_search(array_keys($fieldstosearchall), $search_all);
//$sql.= dolSqlDateFilter("t.field", $search_xxxday, $search_xxxmonth, $search_xxxyear); //$sql.= dolSqlDateFilter("t.field", $search_xxxday, $search_xxxmonth, $search_xxxyear);
// Add where from extra fields // Add where from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
@ -239,26 +259,24 @@ $sql .= $db->order($sortfield, $sortorder);
// Count total nb of records // Count total nb of records
$nbtotalofrecords = ''; $nbtotalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
{
$resql = $db->query($sql); $resql = $db->query($sql);
$nbtotalofrecords = $db->num_rows($resql); $nbtotalofrecords = $db->num_rows($resql);
if (($page * $limit) > $nbtotalofrecords) // if total of record found is smaller than page * limit, goto and load page 0 if (($page * $limit) > $nbtotalofrecords) { // if total of record found is smaller than page * limit, goto and load page 0
{
$page = 0; $page = 0;
$offset = 0; $offset = 0;
} }
} }
// if total of record found is smaller than limit, no need to do paging and to restart another select with limits set. // if total of record found is smaller than limit, no need to do paging and to restart another select with limits set.
if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit))) if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit))) {
{
$num = $nbtotalofrecords; $num = $nbtotalofrecords;
} else { } else {
if ($limit) $sql .= $db->plimit($limit + 1, $offset); if ($limit) {
$sql .= $db->plimit($limit + 1, $offset);
}
$resql = $db->query($sql); $resql = $db->query($sql);
if (!$resql) if (!$resql) {
{
dol_print_error($db); dol_print_error($db);
exit; exit;
} }
@ -267,8 +285,7 @@ if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit
} }
// Direct jump if only one record found // Direct jump if only one record found
if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
$id = $obj->rowid; $id = $obj->rowid;
header("Location: ".DOL_URL_ROOT.'/inventory/card.php?id='.$id); header("Location: ".DOL_URL_ROOT.'/inventory/card.php?id='.$id);
@ -284,14 +301,24 @@ llxHeader('', $title, $help_url);
$arrayofselected = is_array($toselect) ? $toselect : array(); $arrayofselected = is_array($toselect) ? $toselect : array();
$param = ''; $param = '';
if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); $param .= '&contextpage='.urlencode($contextpage);
foreach ($search as $key => $val) }
{ if ($limit > 0 && $limit != $conf->liste_limit) {
if (is_array($search[$key]) && count($search[$key])) foreach ($search[$key] as $skey) $param .= '&search_'.$key.'[]='.urlencode($skey); $param .= '&limit='.urlencode($limit);
else $param .= '&search_'.$key.'='.urlencode($search[$key]); }
foreach ($search as $key => $val) {
if (is_array($search[$key]) && count($search[$key])) {
foreach ($search[$key] as $skey) {
$param .= '&search_'.$key.'[]='.urlencode($skey);
}
} else {
$param .= '&search_'.$key.'='.urlencode($search[$key]);
}
}
if ($optioncss != '') {
$param .= '&optioncss='.urlencode($optioncss);
} }
if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss);
// Add $param from extra fields // Add $param from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
@ -302,12 +329,18 @@ $arrayofmassactions = array(
//'builddoc'=>$langs->trans("PDFMerge"), //'builddoc'=>$langs->trans("PDFMerge"),
//'presend'=>$langs->trans("SendByMail"), //'presend'=>$langs->trans("SendByMail"),
); );
if ($permissiontodelete) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); if ($permissiontodelete) {
if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete");
}
if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) {
$arrayofmassactions = array();
}
$massactionbutton = $form->selectMassAction('', $arrayofmassactions); $massactionbutton = $form->selectMassAction('', $arrayofmassactions);
print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'; print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">';
if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; if ($optioncss != '') {
print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
}
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
print '<input type="hidden" name="action" value="list">'; print '<input type="hidden" name="action" value="list">';
@ -327,9 +360,10 @@ $objecttmp = new Inventory($db);
$trackid = 'stockinv'.$object->id; $trackid = 'stockinv'.$object->id;
include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';
if ($search_all) if ($search_all) {
{ foreach ($fieldstosearchall as $key => $val) {
foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); $fieldstosearchall[$key] = $langs->trans($val);
}
print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'</div>'; print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'</div>';
} }
@ -340,11 +374,13 @@ $moreforfilter.= '</div>';*/
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook
if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; if (empty($reshook)) {
else $moreforfilter = $hookmanager->resPrint; $moreforfilter .= $hookmanager->resPrint;
} else {
$moreforfilter = $hookmanager->resPrint;
}
if (!empty($moreforfilter)) if (!empty($moreforfilter)) {
{
print '<div class="liste_titre liste_titre_bydiv centpercent">'; print '<div class="liste_titre liste_titre_bydiv centpercent">';
print $moreforfilter; print $moreforfilter;
print '</div>'; print '</div>';
@ -361,20 +397,26 @@ print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" :
// Fields title search // Fields title search
// -------------------------------------------------------------------- // --------------------------------------------------------------------
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{
$cssforfield = (empty($val['css']) ? '' : $val['css']); $cssforfield = (empty($val['css']) ? '' : $val['css']);
if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; if ($key == 'status') {
elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; $cssforfield .= ($cssforfield ? ' ' : '').'center';
elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right'; $cssforfield .= ($cssforfield ? ' ' : '').'center';
if (!empty($arrayfields['t.'.$key]['checked'])) } elseif (in_array($val['type'], array('timestamp'))) {
{ $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
} elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') {
$cssforfield .= ($cssforfield ? ' ' : '').'right';
}
if (!empty($arrayfields['t.'.$key]['checked'])) {
print '<td class="liste_titre'.($cssforfield ? ' '.$cssforfield : '').'">'; print '<td class="liste_titre'.($cssforfield ? ' '.$cssforfield : '').'">';
if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
elseif (strpos($val['type'], 'integer:') === 0) { print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1);
} elseif (strpos($val['type'], 'integer:') === 0) {
print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth150', 1); print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth150', 1);
} elseif (!preg_match('/^(date|timestamp)/', $val['type'])) print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'">'; } elseif (!preg_match('/^(date|timestamp)/', $val['type'])) {
print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'">';
}
print '</td>'; print '</td>';
} }
} }
@ -396,15 +438,18 @@ print '</tr>'."\n";
// Fields title label // Fields title label
// -------------------------------------------------------------------- // --------------------------------------------------------------------
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{
$cssforfield = (empty($val['css']) ? '' : $val['css']); $cssforfield = (empty($val['css']) ? '' : $val['css']);
if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; if ($key == 'status') {
elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; $cssforfield .= ($cssforfield ? ' ' : '').'center';
elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right'; $cssforfield .= ($cssforfield ? ' ' : '').'center';
if (!empty($arrayfields['t.'.$key]['checked'])) } elseif (in_array($val['type'], array('timestamp'))) {
{ $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
} elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') {
$cssforfield .= ($cssforfield ? ' ' : '').'right';
}
if (!empty($arrayfields['t.'.$key]['checked'])) {
print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n"; print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n";
} }
} }
@ -421,11 +466,11 @@ print '</tr>'."\n";
// Detect if we need a fetch on each output line // Detect if we need a fetch on each output line
$needToFetchEachLine = 0; $needToFetchEachLine = 0;
if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) {
{ foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) {
foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) if (preg_match('/\$object/', $val)) {
{ $needToFetchEachLine++; // There is at least one compute field that use $object
if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object }
} }
} }
@ -433,37 +478,50 @@ if (is_array($extrafields->attributes[$object->table_element]['computed']) && co
// -------------------------------------------------------------------- // --------------------------------------------------------------------
$i = 0; $i = 0;
$totalarray = array(); $totalarray = array();
while ($i < ($limit ? min($num, $limit) : $num)) while ($i < ($limit ? min($num, $limit) : $num)) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
if (empty($obj)) break; // Should not happen if (empty($obj)) {
break; // Should not happen
}
// Store properties in $object // Store properties in $object
$object->setVarsFromFetchObj($obj); $object->setVarsFromFetchObj($obj);
// Show here line of result // Show here line of result
print '<tr class="oddeven">'; print '<tr class="oddeven">';
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{
$cssforfield = (empty($val['css']) ? '' : $val['css']); $cssforfield = (empty($val['css']) ? '' : $val['css']);
if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
elseif ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; $cssforfield .= ($cssforfield ? ' ' : '').'center';
} elseif ($key == 'status') {
$cssforfield .= ($cssforfield ? ' ' : '').'center';
}
if (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; if (in_array($val['type'], array('timestamp'))) {
elseif ($key == 'ref') $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
} elseif ($key == 'ref') {
$cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
}
if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $key != 'status') $cssforfield .= ($cssforfield ? ' ' : '').'right'; if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $key != 'status') {
$cssforfield .= ($cssforfield ? ' ' : '').'right';
}
if (!empty($arrayfields['t.'.$key]['checked'])) if (!empty($arrayfields['t.'.$key]['checked'])) {
{
print '<td'.($cssforfield ? ' class="'.$cssforfield.'"' : '').'>'; print '<td'.($cssforfield ? ' class="'.$cssforfield.'"' : '').'>';
if ($key == 'status') print $object->getLibStatut(5); if ($key == 'status') {
else print $object->showOutputField($val, $key, $object->$key, ''); print $object->getLibStatut(5);
} else {
print $object->showOutputField($val, $key, $object->$key, '');
}
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
if (!empty($val['isameasure'])) $totalarray['nbfield']++;
{ }
if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; if (!empty($val['isameasure'])) {
if (!$i) {
$totalarray['pos'][$totalarray['nbfield']] = 't.'.$key;
}
$totalarray['val']['t.'.$key] += $object->$key; $totalarray['val']['t.'.$key] += $object->$key;
} }
} }
@ -476,14 +534,17 @@ while ($i < ($limit ? min($num, $limit) : $num))
print $hookmanager->resPrint; print $hookmanager->resPrint;
// Action column // Action column
print '<td class="nowrap center">'; print '<td class="nowrap center">';
if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
{
$selected = 0; $selected = 0;
if (in_array($object->id, $arrayofselected)) $selected = 1; if (in_array($object->id, $arrayofselected)) {
$selected = 1;
}
print '<input id="cb'.$object->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$object->id.'"'.($selected ? ' checked="checked"' : '').'>'; print '<input id="cb'.$object->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$object->id.'"'.($selected ? ' checked="checked"' : '').'>';
} }
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
print '</tr>'."\n"; print '</tr>'."\n";
@ -495,10 +556,13 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php';
// If no record found // If no record found
if ($num == 0) if ($num == 0) {
{
$colspan = 1; $colspan = 1;
foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; } foreach ($arrayfields as $key => $val) {
if (!empty($val['checked'])) {
$colspan++;
}
}
print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>'; print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>';
} }
@ -514,10 +578,11 @@ print '</div>'."\n";
print '</form>'."\n"; print '</form>'."\n";
if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) {
{
$hidegeneratedfilelistifempty = 1; $hidegeneratedfilelistifempty = 1;
if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) {
$hidegeneratedfilelistifempty = 0;
}
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
$formfile = new FormFile($db); $formfile = new FormFile($db);

File diff suppressed because it is too large Load Diff

View File

@ -40,11 +40,15 @@ $action = GETPOST('action', 'aZ09');
// Security check // Security check
$fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : '')); $fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : ''));
$fieldtype = (!empty($ref) ? 'ref' : 'rowid'); $fieldtype = (!empty($ref) ? 'ref' : 'rowid');
if ($user->socid) $socid = $user->socid; if ($user->socid) {
$socid = $user->socid;
}
$result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype);
$object = new Product($db); $object = new Product($db);
if ($id > 0 || !empty($ref)) $object->fetch($id, $ref); if ($id > 0 || !empty($ref)) {
$object->fetch($id, $ref);
}
$permissionnote = $user->rights->produit->creer; // Used by the include of actions_setnotes.inc.php $permissionnote = $user->rights->produit->creer; // Used by the include of actions_setnotes.inc.php
@ -63,30 +67,33 @@ include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include,
$form = new Form($db); $form = new Form($db);
$helpurl = ''; $helpurl = '';
if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos'; if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) {
if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios'; $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos';
}
if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) {
$helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios';
}
$title = $langs->trans('ProductServiceCard'); $title = $langs->trans('ProductServiceCard');
$shortlabel = dol_trunc($object->label, 16); $shortlabel = dol_trunc($object->label, 16);
if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) {
{
$title = $langs->trans('Product')." ".$shortlabel." - ".$langs->trans('Notes'); $title = $langs->trans('Product')." ".$shortlabel." - ".$langs->trans('Notes');
$helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos'; $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos';
} }
if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) {
{
$title = $langs->trans('Service')." ".$shortlabel." - ".$langs->trans('Notes'); $title = $langs->trans('Service')." ".$shortlabel." - ".$langs->trans('Notes');
$helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios'; $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios';
} }
llxHeader('', $title, $help_url); llxHeader('', $title, $help_url);
if ($id > 0 || !empty($ref)) if ($id > 0 || !empty($ref)) {
{
/* /*
* Affichage onglets * Affichage onglets
*/ */
if (!empty($conf->notification->enabled)) $langs->load("mails"); if (!empty($conf->notification->enabled)) {
$langs->load("mails");
}
$head = product_prepare_head($object); $head = product_prepare_head($object);
$titre = $langs->trans("CardProduct".$object->type); $titre = $langs->trans("CardProduct".$object->type);
@ -98,7 +105,9 @@ if ($id > 0 || !empty($ref))
$object->next_prev_filter = " fk_product_type = ".$object->type; $object->next_prev_filter = " fk_product_type = ".$object->type;
$shownav = 1; $shownav = 1;
if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) {
$shownav = 0;
}
dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref');

View File

@ -39,16 +39,24 @@ $type = GETPOST("type", "int");
$mode = GETPOST('mode', 'alpha') ? GETPOST('mode', 'alpha') : ''; $mode = GETPOST('mode', 'alpha') ? GETPOST('mode', 'alpha') : '';
// Security check // Security check
if (!empty($user->socid)) $socid = $user->socid; if (!empty($user->socid)) {
$socid = $user->socid;
}
$result = restrictedArea($user, 'produit|service'); $result = restrictedArea($user, 'produit|service');
$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST("sortfield", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
if (!$sortfield) $sortfield = "c"; $page = 0;
if (!$sortorder) $sortorder = "DESC"; } // If $page is not defined, or '' or -1
if (!$sortfield) {
$sortfield = "c";
}
if (!$sortorder) {
$sortorder = "DESC";
}
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
@ -88,8 +96,12 @@ if ((string) $type == '0') {
$title = $langs->trans("ListProductByPopularity"); $title = $langs->trans("ListProductByPopularity");
} }
if ($type != '') $param .= '&type='.urlencode($type); if ($type != '') {
if ($mode != '') $param .= '&mode='.urlencode($mode); $param .= '&type='.urlencode($type);
}
if ($mode != '') {
$param .= '&mode='.urlencode($mode);
}
$h = 0; $h = 0;
$head = array(); $head = array();
@ -134,8 +146,7 @@ $sql .= " GROUP BY p.rowid, p.label, p.ref, p.fk_product_type";
if (!empty($mode) && $mode != '-1') { if (!empty($mode) && $mode != '-1') {
$result = $db->query($sql); $result = $db->query($sql);
if ($result) if ($result) {
{
$totalnboflines = $db->num_rows($result); $totalnboflines = $db->num_rows($result);
} }
@ -143,13 +154,11 @@ if (!empty($mode) && $mode != '-1') {
$sql .= $db->plimit($limit + 1, $offset); $sql .= $db->plimit($limit + 1, $offset);
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
$i = 0; $i = 0;
while ($i < $num) while ($i < $num) {
{
$objp = $db->fetch_object($resql); $objp = $db->fetch_object($resql);
$infoprod[$objp->rowid] = array('type'=>$objp->type, 'ref'=>$objp->ref, 'label'=>$objp->label); $infoprod[$objp->rowid] = array('type'=>$objp->type, 'ref'=>$objp->ref, 'label'=>$objp->label);
@ -179,8 +188,12 @@ print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="mode" value="'.$mode.'">'; print '<input type="hidden" name="mode" value="'.$mode.'">';
print '<input type="hidden" name="type" value="'.$type.'">'; print '<input type="hidden" name="type" value="'.$type.'">';
print '<input type="hidden" name="action" value="add">'; print '<input type="hidden" name="action" value="add">';
if ($backtopage) print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; if ($backtopage) {
if ($backtopageforcancel) print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">'; print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
}
if ($backtopageforcancel) {
print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">';
}
print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, "", $num, $totalnboflines, '', 0, '', '', -1, 0, 0, 1); print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, "", $num, $totalnboflines, '', 0, '', '', -1, 0, 0, 1);
@ -195,11 +208,9 @@ print_liste_field_titre($textforqty, $_SERVER["PHP_SELF"], 'c', '', $param, '',
print "</tr>\n"; print "</tr>\n";
if ($mode && $mode != '-1') { if ($mode && $mode != '-1') {
foreach ($infoprod as $prodid => $vals) foreach ($infoprod as $prodid => $vals) {
{
// Multilangs // Multilangs
if (!empty($conf->global->MAIN_MULTILANGS)) // si l'option est active if (!empty($conf->global->MAIN_MULTILANGS)) { // si l'option est active
{
$sql = "SELECT label"; $sql = "SELECT label";
$sql .= " FROM ".MAIN_DB_PREFIX."product_lang"; $sql .= " FROM ".MAIN_DB_PREFIX."product_lang";
$sql .= " WHERE fk_product=".$prodid; $sql .= " WHERE fk_product=".$prodid;
@ -207,22 +218,29 @@ if ($mode && $mode != '-1') {
$sql .= " LIMIT 1"; $sql .= " LIMIT 1";
$resultp = $db->query($sql); $resultp = $db->query($sql);
if ($resultp) if ($resultp) {
{
$objtp = $db->fetch_object($resultp); $objtp = $db->fetch_object($resultp);
if (!empty($objtp->label)) $vals['label'] = $objtp->label; if (!empty($objtp->label)) {
$vals['label'] = $objtp->label;
}
} }
} }
print "<tr>"; print "<tr>";
print '<td><a href="'.DOL_URL_ROOT.'/product/stats/card.php?id='.$prodid.'">'; print '<td><a href="'.DOL_URL_ROOT.'/product/stats/card.php?id='.$prodid.'">';
if ($vals['type'] == 1) print img_object($langs->trans("ShowService"), "service"); if ($vals['type'] == 1) {
else print img_object($langs->trans("ShowProduct"), "product"); print img_object($langs->trans("ShowService"), "service");
} else {
print img_object($langs->trans("ShowProduct"), "product");
}
print " "; print " ";
print $vals['ref'].'</a></td>'; print $vals['ref'].'</a></td>';
print '<td>'; print '<td>';
if ($vals['type'] == 1) print $langs->trans("Service"); if ($vals['type'] == 1) {
else print $langs->trans("Product"); print $langs->trans("Service");
} else {
print $langs->trans("Product");
}
print '</td>'; print '</td>';
print '<td>'.$vals['label'].'</td>'; print '<td>'.$vals['label'].'</td>';
print '<td class="right">'.$vals['nbline'].'</td>'; print '<td class="right">'.$vals['nbline'].'</td>';

File diff suppressed because it is too large Load Diff

View File

@ -36,7 +36,9 @@ require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
$langs->loadLangs(array('products', 'stocks')); $langs->loadLangs(array('products', 'stocks'));
// Security check // Security check
if ($user->socid) $socid = $user->socid; if ($user->socid) {
$socid = $user->socid;
}
$result = restrictedArea($user, 'produit|service'); $result = restrictedArea($user, 'produit|service');
@ -55,11 +57,19 @@ $fourn_id = GETPOST("fourn_id", 'int');
$sortfield = GETPOST("sortfield", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page < 0) $page = 0; if (empty($page) || $page < 0) {
if (!$sortfield) $sortfield = "p.ref"; $page = 0;
if (!$sortorder) $sortorder = "ASC"; }
if (!$sortfield) {
$sortfield = "p.ref";
}
if (!$sortorder) {
$sortorder = "ASC";
}
$limit = GETPOST('limit', 'int') ?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 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
// Load sale and categ filters // Load sale and categ filters
@ -69,8 +79,7 @@ $search_categ = GETPOST("search_categ");
// Get object canvas (By default, this is not defined, so standard usage of dolibarr) // Get object canvas (By default, this is not defined, so standard usage of dolibarr)
$canvas = GETPOST("canvas"); $canvas = GETPOST("canvas");
$objcanvas = null; $objcanvas = null;
if (!empty($canvas)) if (!empty($canvas)) {
{
require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php';
$objcanvas = new Canvas($db, $action); $objcanvas = new Canvas($db, $action);
$objcanvas->getCanvas('product', 'list', $canvas); $objcanvas->getCanvas('product', 'list', $canvas);
@ -83,8 +92,7 @@ if (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT)
|| !empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE) || !empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)
|| !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION)
|| !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE)
|| !empty($conf->mrp->enabled)) || !empty($conf->mrp->enabled)) {
{
$virtualdiffersfromphysical = 1; // According to increase/decrease stock options, virtual and physical stock may differs. $virtualdiffersfromphysical = 1; // According to increase/decrease stock options, virtual and physical stock may differs.
} }
@ -97,8 +105,7 @@ $hookmanager->initHooks(array('productreassortlist'));
* Actions * Actions
*/ */
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
{
$sref = ""; $sref = "";
$snom = ""; $snom = "";
$sall = ""; $sall = "";
@ -128,7 +135,9 @@ $sql = 'SELECT p.rowid, p.ref, p.label, p.barcode, p.price, p.price_ttc, p.price
$sql .= ' p.fk_product_type, p.tms as datem,'; $sql .= ' p.fk_product_type, p.tms as datem,';
$sql .= ' p.duration, p.tosell as statut, p.tobuy, p.seuil_stock_alerte, p.desiredstock,'; $sql .= ' p.duration, p.tosell as statut, p.tobuy, p.seuil_stock_alerte, p.desiredstock,';
$sql .= ' SUM(s.reel) as stock_physique'; $sql .= ' SUM(s.reel) as stock_physique';
if (!empty($conf->global->PRODUCT_USE_UNITS)) $sql .= ', u.short_label as unit_short'; if (!empty($conf->global->PRODUCT_USE_UNITS)) {
$sql .= ', u.short_label as unit_short';
}
// Add fields from hooks // Add fields from hooks
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook
@ -136,49 +145,73 @@ $sql .= $hookmanager->resPrint;
$sql .= ' FROM '.MAIN_DB_PREFIX.'product as p'; $sql .= ' FROM '.MAIN_DB_PREFIX.'product as p';
$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_stock as s ON p.rowid = s.fk_product'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_stock as s ON p.rowid = s.fk_product';
$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'entrepot as e ON s.fk_entrepot = e.rowid AND e.entity IN ('.getEntity('entrepot').')'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'entrepot as e ON s.fk_entrepot = e.rowid AND e.entity IN ('.getEntity('entrepot').')';
if (!empty($conf->global->PRODUCT_USE_UNITS)) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_units as u on p.fk_unit = u.rowid'; if (!empty($conf->global->PRODUCT_USE_UNITS)) {
$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_units as u on p.fk_unit = u.rowid';
}
// We'll need this table joined to the select in order to filter by categ // We'll need this table joined to the select in order to filter by categ
if ($search_categ) $sql .= ", ".MAIN_DB_PREFIX."categorie_product as cp"; if ($search_categ) {
$sql .= ", ".MAIN_DB_PREFIX."categorie_product as cp";
}
$sql .= " WHERE p.entity IN (".getEntity('product').")"; $sql .= " WHERE p.entity IN (".getEntity('product').")";
if ($search_categ) $sql .= " AND p.rowid = cp.fk_product"; // Join for the needed table to filter by categ if ($search_categ) {
if ($sall) $sql .= natural_search(array('p.ref', 'p.label', 'p.description', 'p.note'), $sall); $sql .= " AND p.rowid = cp.fk_product"; // Join for the needed table to filter by categ
}
if ($sall) {
$sql .= natural_search(array('p.ref', 'p.label', 'p.description', 'p.note'), $sall);
}
// if the type is not 1, we show all products (type = 0,2,3) // if the type is not 1, we show all products (type = 0,2,3)
if (dol_strlen($type)) if (dol_strlen($type)) {
{ if ($type == 1) {
if ($type == 1)
{
$sql .= " AND p.fk_product_type = '1'"; $sql .= " AND p.fk_product_type = '1'";
} else { } else {
$sql .= " AND p.fk_product_type <> '1'"; $sql .= " AND p.fk_product_type <> '1'";
} }
} }
if ($sref) $sql .= natural_search('p.ref', $sref); if ($sref) {
if ($search_barcode) $sql .= natural_search('p.barcode', $search_barcode); $sql .= natural_search('p.ref', $sref);
if ($snom) $sql .= natural_search('p.label', $snom); }
if (!empty($tosell)) $sql .= " AND p.tosell = ".$tosell; if ($search_barcode) {
if (!empty($tobuy)) $sql .= " AND p.tobuy = ".$tobuy; $sql .= natural_search('p.barcode', $search_barcode);
if (!empty($canvas)) $sql .= " AND p.canvas = '".$db->escape($canvas)."'"; }
if ($catid) $sql .= " AND cp.fk_categorie = ".$catid; if ($snom) {
if ($fourn_id > 0) $sql .= " AND p.rowid = pf.fk_product AND pf.fk_soc = ".$fourn_id; $sql .= natural_search('p.label', $snom);
}
if (!empty($tosell)) {
$sql .= " AND p.tosell = ".$tosell;
}
if (!empty($tobuy)) {
$sql .= " AND p.tobuy = ".$tobuy;
}
if (!empty($canvas)) {
$sql .= " AND p.canvas = '".$db->escape($canvas)."'";
}
if ($catid) {
$sql .= " AND cp.fk_categorie = ".$catid;
}
if ($fourn_id > 0) {
$sql .= " AND p.rowid = pf.fk_product AND pf.fk_soc = ".$fourn_id;
}
// Insert categ filter // Insert categ filter
if ($search_categ) $sql .= " AND cp.fk_categorie = ".$db->escape($search_categ); if ($search_categ) {
$sql .= " AND cp.fk_categorie = ".$db->escape($search_categ);
}
$sql .= " GROUP BY p.rowid, p.ref, p.label, p.barcode, p.price, p.price_ttc, p.price_base_type, p.entity,"; $sql .= " GROUP BY p.rowid, p.ref, p.label, p.barcode, p.price, p.price_ttc, p.price_base_type, p.entity,";
$sql .= " p.fk_product_type, p.tms, p.duration, p.tosell, p.tobuy, p.seuil_stock_alerte, p.desiredstock"; $sql .= " p.fk_product_type, p.tms, p.duration, p.tosell, p.tobuy, p.seuil_stock_alerte, p.desiredstock";
// Add fields from hooks // Add fields from hooks
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('printFieldSelect', $parameters); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('printFieldSelect', $parameters); // Note that $action and $object may have been modified by hook
$sql .= $hookmanager->resPrint; $sql .= $hookmanager->resPrint;
if ($toolowstock) $sql .= " HAVING SUM(".$db->ifsql('s.reel IS NULL', '0', 's.reel').") < p.seuil_stock_alerte"; if ($toolowstock) {
$sql .= " HAVING SUM(".$db->ifsql('s.reel IS NULL', '0', 's.reel').") < p.seuil_stock_alerte";
}
$sql .= $db->order($sortfield, $sortorder); $sql .= $db->order($sortfield, $sortorder);
// Count total nb of records // Count total nb of records
$nbtotalofrecords = ''; $nbtotalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
{
$result = $db->query($sql); $result = $db->query($sql);
$nbtotalofrecords = $db->num_rows($result); $nbtotalofrecords = $db->num_rows($result);
if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0
{
$page = 0; $page = 0;
$offset = 0; $offset = 0;
} }
@ -187,41 +220,68 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
$sql .= $db->plimit($limit + 1, $offset); $sql .= $db->plimit($limit + 1, $offset);
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
$i = 0; $i = 0;
if ($num == 1 && GETPOST('autojumpifoneonly') && ($sall || $snom || $sref)) if ($num == 1 && GETPOST('autojumpifoneonly') && ($sall || $snom || $sref)) {
{
$objp = $db->fetch_object($resql); $objp = $db->fetch_object($resql);
header("Location: card.php?id=$objp->rowid"); header("Location: card.php?id=$objp->rowid");
exit; exit;
} }
if (isset($type)) if (isset($type)) {
{ if ($type == 1) {
if ($type == 1) { $texte = $langs->trans("Services"); } else { $texte = $langs->trans("Products"); } $texte = $langs->trans("Services");
} else {
$texte = $langs->trans("Products");
}
} else { } else {
$texte = $langs->trans("ProductsAndServices"); $texte = $langs->trans("ProductsAndServices");
} }
$texte .= ' ('.$langs->trans("MenuStocks").')'; $texte .= ' ('.$langs->trans("MenuStocks").')';
$param = ''; $param = '';
if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); if ($limit > 0 && $limit != $conf->liste_limit) {
if ($sall) $param .= "&sall=".urlencode($sall); $param .= '&limit='.urlencode($limit);
if ($tosell) $param .= "&tosell=".urlencode($tosell); }
if ($tobuy) $param .= "&tobuy=".urlencode($tobuy); if ($sall) {
if ($type) $param .= "&type=".urlencode($type); $param .= "&sall=".urlencode($sall);
if ($fourn_id) $param .= "&fourn_id=".urlencode($fourn_id); }
if ($snom) $param .= "&snom=".urlencode($snom); if ($tosell) {
if ($sref) $param .= "&sref=".urlencode($sref); $param .= "&tosell=".urlencode($tosell);
if ($search_sale) $param .= "&search_sale=".urlencode($search_sale); }
if ($search_categ) $param .= "&search_categ=".urlencode($search_categ); if ($tobuy) {
if ($toolowstock) $param .= "&toolowstock=".urlencode($toolowstock); $param .= "&tobuy=".urlencode($tobuy);
if ($sbarcode) $param .= "&sbarcode=".urlencode($sbarcode); }
if ($catid) $param .= "&catid=".urlencode($catid); if ($type) {
$param .= "&type=".urlencode($type);
}
if ($fourn_id) {
$param .= "&fourn_id=".urlencode($fourn_id);
}
if ($snom) {
$param .= "&snom=".urlencode($snom);
}
if ($sref) {
$param .= "&sref=".urlencode($sref);
}
if ($search_sale) {
$param .= "&search_sale=".urlencode($search_sale);
}
if ($search_categ) {
$param .= "&search_categ=".urlencode($search_categ);
}
if ($toolowstock) {
$param .= "&toolowstock=".urlencode($toolowstock);
}
if ($sbarcode) {
$param .= "&sbarcode=".urlencode($sbarcode);
}
if ($catid) {
$param .= "&catid=".urlencode($catid);
}
llxHeader("", $texte, $helpurl); llxHeader("", $texte, $helpurl);
@ -234,8 +294,7 @@ if ($resql)
print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'product', 0, '', '', $limit); print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'product', 0, '', '', $limit);
if (!empty($catid)) if (!empty($catid)) {
{
print "<div id='ways'>"; print "<div id='ways'>";
$c = new Categorie($db); $c = new Categorie($db);
$c->fetch($catid); $c->fetch($catid);
@ -246,8 +305,7 @@ if ($resql)
// Filter on categories // Filter on categories
$moreforfilter = ''; $moreforfilter = '';
if (!empty($conf->categorie->enabled)) if (!empty($conf->categorie->enabled)) {
{
$moreforfilter .= '<div class="divsearchfield">'; $moreforfilter .= '<div class="divsearchfield">';
$moreforfilter .= $langs->trans('Categories').': '; $moreforfilter .= $langs->trans('Categories').': ';
$moreforfilter .= $htmlother->select_categories(Categorie::TYPE_PRODUCT, $search_categ, 'search_categ'); $moreforfilter .= $htmlother->select_categories(Categorie::TYPE_PRODUCT, $search_categ, 'search_categ');
@ -258,8 +316,7 @@ if ($resql)
$moreforfilter .= $langs->trans("StockTooLow").' <input type="checkbox" name="toolowstock" value="1"'.($toolowstock ? ' checked' : '').'>'; $moreforfilter .= $langs->trans("StockTooLow").' <input type="checkbox" name="toolowstock" value="1"'.($toolowstock ? ' checked' : '').'>';
$moreforfilter .= '</div>'; $moreforfilter .= '</div>';
if (!empty($moreforfilter)) if (!empty($moreforfilter)) {
{
print '<div class="liste_titre liste_titre_bydiv centpercent">'; print '<div class="liste_titre liste_titre_bydiv centpercent">';
print $moreforfilter; print $moreforfilter;
$parameters = array(); $parameters = array();
@ -269,21 +326,39 @@ if ($resql)
} }
$param = ''; $param = '';
if ($tosell) $param .= "&tosell=".urlencode($tosell); if ($tosell) {
if ($tobuy) $param .= "&tobuy=".urlencode($tobuy); $param .= "&tosell=".urlencode($tosell);
if ($type) $param .= "&type=".urlencode($type); }
if ($fourn_id) $param .= "&fourn_id=".urlencode($fourn_id); if ($tobuy) {
if ($snom) $param .= "&snom=".urlencode($snom); $param .= "&tobuy=".urlencode($tobuy);
if ($sref) $param .= "&sref=".urlencode($sref); }
if ($toolowstock) $param .= "&toolowstock=".urlencode($toolowstock); if ($type) {
if ($search_categ) $param .= "&search_categ=".urlencode($search_categ); $param .= "&type=".urlencode($type);
}
if ($fourn_id) {
$param .= "&fourn_id=".urlencode($fourn_id);
}
if ($snom) {
$param .= "&snom=".urlencode($snom);
}
if ($sref) {
$param .= "&sref=".urlencode($sref);
}
if ($toolowstock) {
$param .= "&toolowstock=".urlencode($toolowstock);
}
if ($search_categ) {
$param .= "&search_categ=".urlencode($search_categ);
}
$formProduct = new FormProduct($db); $formProduct = new FormProduct($db);
$formProduct->loadWarehouses(); $formProduct->loadWarehouses();
$warehouses_list = $formProduct->cache_warehouses; $warehouses_list = $formProduct->cache_warehouses;
$nb_warehouse = count($warehouses_list); $nb_warehouse = count($warehouses_list);
$colspan_warehouse = 1; $colspan_warehouse = 1;
if (!empty($conf->global->STOCK_DETAIL_ON_WAREHOUSE)) { $colspan_warehouse = $nb_warehouse > 1 ? $nb_warehouse + 1 : 1; } if (!empty($conf->global->STOCK_DETAIL_ON_WAREHOUSE)) {
$colspan_warehouse = $nb_warehouse > 1 ? $nb_warehouse + 1 : 1;
}
print '<div class="div-table-responsive">'; print '<div class="div-table-responsive">';
print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'; print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">';
@ -297,8 +372,7 @@ if ($resql)
print '<input class="flat" type="text" name="snom" size="8" value="'.$snom.'">'; print '<input class="flat" type="text" name="snom" size="8" value="'.$snom.'">';
print '</td>'; print '</td>';
// Duration // Duration
if (!empty($conf->service->enabled) && $type == 1) if (!empty($conf->service->enabled) && $type == 1) {
{
print '<td class="liste_titre">'; print '<td class="liste_titre">';
print '&nbsp;'; print '&nbsp;';
print '</td>'; print '</td>';
@ -307,7 +381,9 @@ if ($resql)
print '<td class="liste_titre">&nbsp;</td>'; print '<td class="liste_titre">&nbsp;</td>';
print '<td class="liste_titre right">&nbsp;</td>'; print '<td class="liste_titre right">&nbsp;</td>';
print '<td class="liste_titre">&nbsp;</td>'; print '<td class="liste_titre">&nbsp;</td>';
if ($virtualdiffersfromphysical) print '<td class="liste_titre">&nbsp;</td>'; if ($virtualdiffersfromphysical) {
print '<td class="liste_titre">&nbsp;</td>';
}
print '<td class="liste_titre">&nbsp;</td>'; print '<td class="liste_titre">&nbsp;</td>';
print '<td class="liste_titre" colspan="'.$colspan_warehouse.'">&nbsp;</td>'; print '<td class="liste_titre" colspan="'.$colspan_warehouse.'">&nbsp;</td>';
print '<td class="liste_titre"></td>'; print '<td class="liste_titre"></td>';
@ -324,20 +400,23 @@ if ($resql)
print "<tr class=\"liste_titre\">"; print "<tr class=\"liste_titre\">";
print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "p.ref", $param, "", "", $sortfield, $sortorder); print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "p.ref", $param, "", "", $sortfield, $sortorder);
print_liste_field_titre("Label", $_SERVER["PHP_SELF"], "p.label", $param, "", "", $sortfield, $sortorder); print_liste_field_titre("Label", $_SERVER["PHP_SELF"], "p.label", $param, "", "", $sortfield, $sortorder);
if (!empty($conf->service->enabled) && $type == 1) print_liste_field_titre("Duration", $_SERVER["PHP_SELF"], "p.duration", $param, "", '', $sortfield, $sortorder, 'center '); if (!empty($conf->service->enabled) && $type == 1) {
print_liste_field_titre("Duration", $_SERVER["PHP_SELF"], "p.duration", $param, "", '', $sortfield, $sortorder, 'center ');
}
print_liste_field_titre("StockLimit", $_SERVER["PHP_SELF"], "p.seuil_stock_alerte", $param, "", '', $sortfield, $sortorder, 'right '); print_liste_field_titre("StockLimit", $_SERVER["PHP_SELF"], "p.seuil_stock_alerte", $param, "", '', $sortfield, $sortorder, 'right ');
print_liste_field_titre("DesiredStock", $_SERVER["PHP_SELF"], "p.desiredstock", $param, "", '', $sortfield, $sortorder, 'right '); print_liste_field_titre("DesiredStock", $_SERVER["PHP_SELF"], "p.desiredstock", $param, "", '', $sortfield, $sortorder, 'right ');
print_liste_field_titre("PhysicalStock", $_SERVER["PHP_SELF"], "stock_physique", $param, "", '', $sortfield, $sortorder, 'right '); print_liste_field_titre("PhysicalStock", $_SERVER["PHP_SELF"], "stock_physique", $param, "", '', $sortfield, $sortorder, 'right ');
// Details per warehouse // Details per warehouse
if (!empty($conf->global->STOCK_DETAIL_ON_WAREHOUSE)) // TODO This should be moved into the selection of fields on page product/list (page product/stock will be removed and replaced with product/list with its own context) if (!empty($conf->global->STOCK_DETAIL_ON_WAREHOUSE)) { // TODO This should be moved into the selection of fields on page product/list (page product/stock will be removed and replaced with product/list with its own context)
{
if ($nb_warehouse > 1) { if ($nb_warehouse > 1) {
foreach ($warehouses_list as &$wh) { foreach ($warehouses_list as &$wh) {
print_liste_field_titre($wh['label'], '', '', '', '', '', '', '', 'right '); print_liste_field_titre($wh['label'], '', '', '', '', '', '', '', 'right ');
} }
} }
} }
if ($virtualdiffersfromphysical) print_liste_field_titre("VirtualStock", $_SERVER["PHP_SELF"], "", $param, "", '', $sortfield, $sortorder, 'right ', 'VirtualStockDesc'); if ($virtualdiffersfromphysical) {
print_liste_field_titre("VirtualStock", $_SERVER["PHP_SELF"], "", $param, "", '', $sortfield, $sortorder, 'right ', 'VirtualStockDesc');
}
// Units // Units
if (!empty($conf->global->PRODUCT_USE_UNITS)) { if (!empty($conf->global->PRODUCT_USE_UNITS)) {
print_liste_field_titre("Unit", $_SERVER["PHP_SELF"], "unit_short", $param, "", 'align="right"', $sortfield, $sortorder); print_liste_field_titre("Unit", $_SERVER["PHP_SELF"], "unit_short", $param, "", 'align="right"', $sortfield, $sortorder);
@ -352,8 +431,7 @@ if ($resql)
print_liste_field_titre(''); print_liste_field_titre('');
print "</tr>\n"; print "</tr>\n";
while ($i < min($num, $limit)) while ($i < min($num, $limit)) {
{
$objp = $db->fetch_object($resql); $objp = $db->fetch_object($resql);
$product = new Product($db); $product = new Product($db);
@ -367,13 +445,17 @@ if ($resql)
print '</td>'; print '</td>';
print '<td>'.$product->label.'</td>'; print '<td>'.$product->label.'</td>';
if (!empty($conf->service->enabled) && $type == 1) if (!empty($conf->service->enabled) && $type == 1) {
{
print '<td class="center">'; print '<td class="center">';
if (preg_match('/([0-9]+)y/i', $objp->duration, $regs)) print $regs[1].' '.$langs->trans("DurationYear"); if (preg_match('/([0-9]+)y/i', $objp->duration, $regs)) {
elseif (preg_match('/([0-9]+)m/i', $objp->duration, $regs)) print $regs[1].' '.$langs->trans("DurationMonth"); print $regs[1].' '.$langs->trans("DurationYear");
elseif (preg_match('/([0-9]+)d/i', $objp->duration, $regs)) print $regs[1].' '.$langs->trans("DurationDay"); } elseif (preg_match('/([0-9]+)m/i', $objp->duration, $regs)) {
else print $objp->duration; print $regs[1].' '.$langs->trans("DurationMonth");
} elseif (preg_match('/([0-9]+)d/i', $objp->duration, $regs)) {
print $regs[1].' '.$langs->trans("DurationDay");
} else {
print $objp->duration;
}
print '</td>'; print '</td>';
} }
//print '<td class="right">'.$objp->stock_theorique.'</td>'; //print '<td class="right">'.$objp->stock_theorique.'</td>';
@ -381,13 +463,14 @@ if ($resql)
print '<td class="right">'.$objp->desiredstock.'</td>'; print '<td class="right">'.$objp->desiredstock.'</td>';
// Real stock // Real stock
print '<td class="right">'; print '<td class="right">';
if ($objp->seuil_stock_alerte != '' && ($objp->stock_physique < $objp->seuil_stock_alerte)) print img_warning($langs->trans("StockTooLow")).' '; if ($objp->seuil_stock_alerte != '' && ($objp->stock_physique < $objp->seuil_stock_alerte)) {
print img_warning($langs->trans("StockTooLow")).' ';
}
print price2num($objp->stock_physique, 'MS'); print price2num($objp->stock_physique, 'MS');
print '</td>'; print '</td>';
// Details per warehouse // Details per warehouse
if (!empty($conf->global->STOCK_DETAIL_ON_WAREHOUSE)) // TODO This should be moved into the selection of fields on page product/list (page product/stock will be removed and replaced with product/list with its own context) if (!empty($conf->global->STOCK_DETAIL_ON_WAREHOUSE)) { // TODO This should be moved into the selection of fields on page product/list (page product/stock will be removed and replaced with product/list with its own context)
{
if ($nb_warehouse > 1) { if ($nb_warehouse > 1) {
foreach ($warehouses_list as &$wh) { foreach ($warehouses_list as &$wh) {
print '<td class="right">'; print '<td class="right">';
@ -398,10 +481,11 @@ if ($resql)
} }
// Virtual stock // Virtual stock
if ($virtualdiffersfromphysical) if ($virtualdiffersfromphysical) {
{
print '<td class="right">'; print '<td class="right">';
if ($objp->seuil_stock_alerte != '' && ($product->stock_theorique < $objp->seuil_stock_alerte)) print img_warning($langs->trans("StockTooLow")).' '; if ($objp->seuil_stock_alerte != '' && ($product->stock_theorique < $objp->seuil_stock_alerte)) {
print img_warning($langs->trans("StockTooLow")).' ';
}
print price2num($product->stock_theorique, 'MS'); print price2num($product->stock_theorique, 'MS');
print '</td>'; print '</td>';
} }

View File

@ -38,7 +38,9 @@ require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
$langs->loadLangs(array('products', 'stocks', 'productbatch')); $langs->loadLangs(array('products', 'stocks', 'productbatch'));
// Security check // Security check
if ($user->socid) $socid = $user->socid; if ($user->socid) {
$socid = $user->socid;
}
$result = restrictedArea($user, 'produit|service'); $result = restrictedArea($user, 'produit|service');
@ -59,11 +61,19 @@ $fourn_id = GETPOST("fourn_id", 'int');
$sortfield = GETPOST("sortfield", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page < 0) $page = 0; if (empty($page) || $page < 0) {
if (!$sortfield) $sortfield = "p.ref"; $page = 0;
if (!$sortorder) $sortorder = "ASC"; }
if (!$sortfield) {
$sortfield = "p.ref";
}
if (!$sortorder) {
$sortorder = "ASC";
}
$limit = GETPOST('limit', 'int') ?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 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
// Load sale and categ filters // Load sale and categ filters
@ -73,8 +83,7 @@ $search_categ = GETPOST("search_categ");
// Get object canvas (By default, this is not defined, so standard usage of dolibarr) // Get object canvas (By default, this is not defined, so standard usage of dolibarr)
$canvas = GETPOST("canvas"); $canvas = GETPOST("canvas");
$objcanvas = null; $objcanvas = null;
if (!empty($canvas)) if (!empty($canvas)) {
{
require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php';
$objcanvas = new Canvas($db, $action); $objcanvas = new Canvas($db, $action);
$objcanvas->getCanvas('product', 'list', $canvas); $objcanvas->getCanvas('product', 'list', $canvas);
@ -86,8 +95,7 @@ if (!empty($canvas))
* Actions * Actions
*/ */
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
{
$sref = ""; $sref = "";
$snom = ""; $snom = "";
$sall = ""; $sall = "";
@ -129,32 +137,58 @@ $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'entrepot as e on ps.fk_entrepot = e.rowid'
$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_batch as pb on pb.fk_product_stock = ps.rowid'; // Detail for each lot on each warehouse $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_batch as pb on pb.fk_product_stock = ps.rowid'; // Detail for each lot on each warehouse
$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_lot as pl on pl.fk_product = p.rowid AND pl.batch = pb.batch'; // Link on unique key $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_lot as pl on pl.fk_product = p.rowid AND pl.batch = pb.batch'; // Link on unique key
// We'll need this table joined to the select in order to filter by categ // We'll need this table joined to the select in order to filter by categ
if ($search_categ) $sql .= ", ".MAIN_DB_PREFIX."categorie_product as cp"; if ($search_categ) {
$sql .= ", ".MAIN_DB_PREFIX."categorie_product as cp";
}
$sql .= " WHERE p.entity IN (".getEntity('product').")"; $sql .= " WHERE p.entity IN (".getEntity('product').")";
if ($search_categ) $sql .= " AND p.rowid = cp.fk_product"; // Join for the needed table to filter by categ if ($search_categ) {
if ($sall) $sql .= natural_search(array('p.ref', 'p.label', 'p.description', 'p.note'), $sall); $sql .= " AND p.rowid = cp.fk_product"; // Join for the needed table to filter by categ
}
if ($sall) {
$sql .= natural_search(array('p.ref', 'p.label', 'p.description', 'p.note'), $sall);
}
// if the type is not 1, we show all products (type = 0,2,3) // if the type is not 1, we show all products (type = 0,2,3)
if (dol_strlen($type)) if (dol_strlen($type)) {
{ if ($type == 1) {
if ($type == 1)
{
$sql .= " AND p.fk_product_type = '1'"; $sql .= " AND p.fk_product_type = '1'";
} else { } else {
$sql .= " AND p.fk_product_type <> '1'"; $sql .= " AND p.fk_product_type <> '1'";
} }
} }
if ($sref) $sql .= natural_search("p.ref", $sref); if ($sref) {
if ($search_barcode) $sql .= natural_search("p.barcode", $search_barcode); $sql .= natural_search("p.ref", $sref);
if ($snom) $sql .= natural_search("p.label", $snom); }
if (!empty($tosell)) $sql .= " AND p.tosell = ".$tosell; if ($search_barcode) {
if (!empty($tobuy)) $sql .= " AND p.tobuy = ".$tobuy; $sql .= natural_search("p.barcode", $search_barcode);
if (!empty($canvas)) $sql .= " AND p.canvas = '".$db->escape($canvas)."'"; }
if ($catid) $sql .= " AND cp.fk_categorie = ".$catid; if ($snom) {
if ($fourn_id > 0) $sql .= " AND p.rowid = pf.fk_product AND pf.fk_soc = ".$fourn_id; $sql .= natural_search("p.label", $snom);
}
if (!empty($tosell)) {
$sql .= " AND p.tosell = ".$tosell;
}
if (!empty($tobuy)) {
$sql .= " AND p.tobuy = ".$tobuy;
}
if (!empty($canvas)) {
$sql .= " AND p.canvas = '".$db->escape($canvas)."'";
}
if ($catid) {
$sql .= " AND cp.fk_categorie = ".$catid;
}
if ($fourn_id > 0) {
$sql .= " AND p.rowid = pf.fk_product AND pf.fk_soc = ".$fourn_id;
}
// Insert categ filter // Insert categ filter
if ($search_categ) $sql .= " AND cp.fk_categorie = ".$db->escape($search_categ); if ($search_categ) {
if ($search_warehouse) $sql .= natural_search("e.ref", $search_warehouse); $sql .= " AND cp.fk_categorie = ".$db->escape($search_categ);
if ($search_batch) $sql .= natural_search("pb.batch", $search_batch); }
if ($search_warehouse) {
$sql .= natural_search("e.ref", $search_warehouse);
}
if ($search_batch) {
$sql .= natural_search("pb.batch", $search_batch);
}
$sql .= " GROUP BY p.rowid, p.ref, p.label, p.barcode, p.price, p.price_ttc, p.price_base_type, p.entity,"; $sql .= " GROUP BY p.rowid, p.ref, p.label, p.barcode, p.price, p.price_ttc, p.price_base_type, p.entity,";
$sql .= " p.fk_product_type, p.tms,"; $sql .= " p.fk_product_type, p.tms,";
$sql .= " p.duration, p.tosell, p.tobuy, p.seuil_stock_alerte, p.desiredstock, p.stock, p.tosell, p.tobuy, p.tobatch,"; $sql .= " p.duration, p.tosell, p.tobuy, p.seuil_stock_alerte, p.desiredstock, p.stock, p.tosell, p.tobuy, p.tobatch,";
@ -162,16 +196,16 @@ $sql .= " ps.fk_entrepot,";
$sql .= " e.ref, e.lieu, e.fk_parent,"; $sql .= " e.ref, e.lieu, e.fk_parent,";
$sql .= " pb.batch, pb.eatby, pb.sellby,"; $sql .= " pb.batch, pb.eatby, pb.sellby,";
$sql .= " pl.rowid, pl.eatby, pl.sellby"; $sql .= " pl.rowid, pl.eatby, pl.sellby";
if ($toolowstock) $sql .= " HAVING SUM(".$db->ifsql('ps.reel IS NULL', '0', 'ps.reel').") < p.seuil_stock_alerte"; // Not used yet if ($toolowstock) {
$sql .= " HAVING SUM(".$db->ifsql('ps.reel IS NULL', '0', 'ps.reel').") < p.seuil_stock_alerte"; // Not used yet
}
$sql .= $db->order($sortfield, $sortorder); $sql .= $db->order($sortfield, $sortorder);
$nbtotalofrecords = ''; $nbtotalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
{
$result = $db->query($sql); $result = $db->query($sql);
$nbtotalofrecords = $db->num_rows($result); $nbtotalofrecords = $db->num_rows($result);
if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0
{
$page = 0; $page = 0;
$offset = 0; $offset = 0;
} }
@ -180,43 +214,74 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
$sql .= $db->plimit($limit + 1, $offset); $sql .= $db->plimit($limit + 1, $offset);
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
$i = 0; $i = 0;
if ($num == 1 && GETPOST('autojumpifoneonly') && ($sall or $snom or $sref)) if ($num == 1 && GETPOST('autojumpifoneonly') && ($sall or $snom or $sref)) {
{
$objp = $db->fetch_object($resql); $objp = $db->fetch_object($resql);
header("Location: card.php?id=$objp->rowid"); header("Location: card.php?id=$objp->rowid");
exit; exit;
} }
if (isset($type)) if (isset($type)) {
{ if ($type == 1) {
if ($type == 1) { $texte = $langs->trans("Services"); } else { $texte = $langs->trans("Products"); } $texte = $langs->trans("Services");
} else {
$texte = $langs->trans("Products");
}
} else { } else {
$texte = $langs->trans("ProductsAndServices"); $texte = $langs->trans("ProductsAndServices");
} }
$texte .= ' ('.$langs->trans("StocksByLotSerial").')'; $texte .= ' ('.$langs->trans("StocksByLotSerial").')';
$param = ''; $param = '';
if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); if ($limit > 0 && $limit != $conf->liste_limit) {
if ($sall) $param .= "&sall=".urlencode($sall); $param .= '&limit='.urlencode($limit);
if ($tosell) $param .= "&tosell=".urlencode($tosell); }
if ($tobuy) $param .= "&tobuy=".urlencode($tobuy); if ($sall) {
if ($type) $param .= "&type=".urlencode($type); $param .= "&sall=".urlencode($sall);
if ($fourn_id) $param .= "&fourn_id=".urlencode($fourn_id); }
if ($snom) $param .= "&snom=".urlencode($snom); if ($tosell) {
if ($sref) $param .= "&sref=".urlencode($sref); $param .= "&tosell=".urlencode($tosell);
if ($search_batch) $param .= "&search_batch=".urlencode($search_batch); }
if ($sbarcode) $param .= "&sbarcode=".urlencode($sbarcode); if ($tobuy) {
if ($search_warehouse) $param .= "&search_warehouse=".urlencode($search_warehouse); $param .= "&tobuy=".urlencode($tobuy);
if ($catid) $param .= "&catid=".urlencode($catid); }
if ($toolowstock) $param .= "&toolowstock=".urlencode($toolowstock); if ($type) {
if ($search_sale) $param .= "&search_sale=".urlencode($search_sale); $param .= "&type=".urlencode($type);
if ($search_categ) $param .= "&search_categ=".urlencode($search_categ); }
if ($fourn_id) {
$param .= "&fourn_id=".urlencode($fourn_id);
}
if ($snom) {
$param .= "&snom=".urlencode($snom);
}
if ($sref) {
$param .= "&sref=".urlencode($sref);
}
if ($search_batch) {
$param .= "&search_batch=".urlencode($search_batch);
}
if ($sbarcode) {
$param .= "&sbarcode=".urlencode($sbarcode);
}
if ($search_warehouse) {
$param .= "&search_warehouse=".urlencode($search_warehouse);
}
if ($catid) {
$param .= "&catid=".urlencode($catid);
}
if ($toolowstock) {
$param .= "&toolowstock=".urlencode($toolowstock);
}
if ($search_sale) {
$param .= "&search_sale=".urlencode($search_sale);
}
if ($search_categ) {
$param .= "&search_categ=".urlencode($search_categ);
}
/*if ($eatby) $param.="&eatby=".$eatby; /*if ($eatby) $param.="&eatby=".$eatby;
if ($sellby) $param.="&sellby=".$sellby;*/ if ($sellby) $param.="&sellby=".$sellby;*/
@ -231,8 +296,7 @@ if ($resql)
print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'product', 0, '', '', $limit, 0, 0, 1); print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'product', 0, '', '', $limit, 0, 0, 1);
if (!empty($catid)) if (!empty($catid)) {
{
print "<div id='ways'>"; print "<div id='ways'>";
$c = new Categorie($db); $c = new Categorie($db);
$c->fetch($catid); $c->fetch($catid);
@ -243,8 +307,7 @@ if ($resql)
// Filter on categories // Filter on categories
$moreforfilter = ''; $moreforfilter = '';
if (!empty($conf->categorie->enabled)) if (!empty($conf->categorie->enabled)) {
{
$moreforfilter .= '<div class="divsearchfield">'; $moreforfilter .= '<div class="divsearchfield">';
$moreforfilter .= $langs->trans('Categories').': '; $moreforfilter .= $langs->trans('Categories').': ';
$moreforfilter .= $htmlother->select_categories(Categorie::TYPE_PRODUCT, $search_categ, 'search_categ'); $moreforfilter .= $htmlother->select_categories(Categorie::TYPE_PRODUCT, $search_categ, 'search_categ');
@ -252,8 +315,7 @@ if ($resql)
} }
//$moreforfilter.=$langs->trans("StockTooLow").' <input type="checkbox" name="toolowstock" value="1"'.($toolowstock?' checked':'').'>'; //$moreforfilter.=$langs->trans("StockTooLow").' <input type="checkbox" name="toolowstock" value="1"'.($toolowstock?' checked':'').'>';
if (!empty($moreforfilter)) if (!empty($moreforfilter)) {
{
print '<div class="liste_titre liste_titre_bydiv centpercent">'; print '<div class="liste_titre liste_titre_bydiv centpercent">';
print $moreforfilter; print $moreforfilter;
$parameters = array(); $parameters = array();
@ -274,8 +336,7 @@ if ($resql)
print '<td class="liste_titre">'; print '<td class="liste_titre">';
print '<input class="flat" type="text" name="snom" size="8" value="'.$snom.'">'; print '<input class="flat" type="text" name="snom" size="8" value="'.$snom.'">';
print '</td>'; print '</td>';
if (!empty($conf->service->enabled) && $type == 1) if (!empty($conf->service->enabled) && $type == 1) {
{
print '<td class="liste_titre">'; print '<td class="liste_titre">';
print '&nbsp;'; print '&nbsp;';
print '</td>'; print '</td>';
@ -302,7 +363,9 @@ if ($resql)
print "<tr class=\"liste_titre\">"; print "<tr class=\"liste_titre\">";
print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "p.ref", $param, "", "", $sortfield, $sortorder); print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "p.ref", $param, "", "", $sortfield, $sortorder);
print_liste_field_titre("Label", $_SERVER["PHP_SELF"], "p.label", $param, "", "", $sortfield, $sortorder); print_liste_field_titre("Label", $_SERVER["PHP_SELF"], "p.label", $param, "", "", $sortfield, $sortorder);
if (!empty($conf->service->enabled) && $type == 1) print_liste_field_titre("Duration", $_SERVER["PHP_SELF"], "p.duration", $param, "", '', $sortfield, $sortorder, 'center '); if (!empty($conf->service->enabled) && $type == 1) {
print_liste_field_titre("Duration", $_SERVER["PHP_SELF"], "p.duration", $param, "", '', $sortfield, $sortorder, 'center ');
}
print_liste_field_titre("Warehouse", $_SERVER["PHP_SELF"], "e.ref", $param, "", '', $sortfield, $sortorder); print_liste_field_titre("Warehouse", $_SERVER["PHP_SELF"], "e.ref", $param, "", '', $sortfield, $sortorder);
//print_liste_field_titre("DesiredStock", $_SERVER["PHP_SELF"], "p.desiredstock",$param,"",'',$sortfield,$sortorder, 'right ); //print_liste_field_titre("DesiredStock", $_SERVER["PHP_SELF"], "p.desiredstock",$param,"",'',$sortfield,$sortorder, 'right );
print_liste_field_titre("Batch", $_SERVER["PHP_SELF"], "pb.batch", $param, "", '', $sortfield, $sortorder, 'center '); print_liste_field_titre("Batch", $_SERVER["PHP_SELF"], "pb.batch", $param, "", '', $sortfield, $sortorder, 'center ');
@ -325,13 +388,11 @@ if ($resql)
$product_lot_static = new Productlot($db); $product_lot_static = new Productlot($db);
$warehousetmp = new Entrepot($db); $warehousetmp = new Entrepot($db);
while ($i < min($num, $limit)) while ($i < min($num, $limit)) {
{
$objp = $db->fetch_object($resql); $objp = $db->fetch_object($resql);
// Multilangs // Multilangs
if (!empty($conf->global->MAIN_MULTILANGS)) // si l'option est active if (!empty($conf->global->MAIN_MULTILANGS)) { // si l'option est active
{
$sql = "SELECT label"; $sql = "SELECT label";
$sql .= " FROM ".MAIN_DB_PREFIX."product_lang"; $sql .= " FROM ".MAIN_DB_PREFIX."product_lang";
$sql .= " WHERE fk_product=".$objp->rowid; $sql .= " WHERE fk_product=".$objp->rowid;
@ -339,10 +400,11 @@ if ($resql)
$sql .= " LIMIT 1"; $sql .= " LIMIT 1";
$result = $db->query($sql); $result = $db->query($sql);
if ($result) if ($result) {
{
$objtp = $db->fetch_object($result); $objtp = $db->fetch_object($result);
if (!empty($objtp->label)) $objp->label = $objtp->label; if (!empty($objtp->label)) {
$objp->label = $objtp->label;
}
} }
} }
@ -379,13 +441,17 @@ if ($resql)
// Label // Label
print '<td>'.$objp->label.'</td>'; print '<td>'.$objp->label.'</td>';
if (!empty($conf->service->enabled) && $type == 1) if (!empty($conf->service->enabled) && $type == 1) {
{
print '<td class="center">'; print '<td class="center">';
if (preg_match('/([0-9]+)y/i', $objp->duration, $regs)) print $regs[1].' '.$langs->trans("DurationYear"); if (preg_match('/([0-9]+)y/i', $objp->duration, $regs)) {
elseif (preg_match('/([0-9]+)m/i', $objp->duration, $regs)) print $regs[1].' '.$langs->trans("DurationMonth"); print $regs[1].' '.$langs->trans("DurationYear");
elseif (preg_match('/([0-9]+)d/i', $objp->duration, $regs)) print $regs[1].' '.$langs->trans("DurationDay"); } elseif (preg_match('/([0-9]+)m/i', $objp->duration, $regs)) {
else print $objp->duration; print $regs[1].' '.$langs->trans("DurationMonth");
} elseif (preg_match('/([0-9]+)d/i', $objp->duration, $regs)) {
print $regs[1].' '.$langs->trans("DurationDay");
} else {
print $objp->duration;
}
print '</td>'; print '</td>';
} }
//print '<td class="right">'.$objp->stock_theorique.'</td>'; //print '<td class="right">'.$objp->stock_theorique.'</td>';
@ -394,16 +460,14 @@ if ($resql)
// Warehouse // Warehouse
print '<td class="nowrap">'; print '<td class="nowrap">';
if ($objp->fk_entrepot > 0) if ($objp->fk_entrepot > 0) {
{
print $warehousetmp->getNomUrl(1); print $warehousetmp->getNomUrl(1);
} }
print '</td>'; print '</td>';
// Lot // Lot
print '<td class="center nowrap">'; print '<td class="center nowrap">';
if ($product_lot_static->batch) if ($product_lot_static->batch) {
{
print $product_lot_static->getNomUrl(1); print $product_lot_static->getNomUrl(1);
} }
print '</td>'; print '</td>';

View File

@ -38,7 +38,9 @@ $ref = GETPOST('ref', 'alpha');
// Security check // Security check
$fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : '')); $fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : ''));
$fieldtype = (!empty($ref) ? 'ref' : 'rowid'); $fieldtype = (!empty($ref) ? 'ref' : 'rowid');
if ($user->socid) $socid = $user->socid; if ($user->socid) {
$socid = $user->socid;
}
$result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype);
// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
@ -52,12 +54,18 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST("sortfield", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if (!$sortorder) $sortorder = "DESC"; if (!$sortorder) {
if (!$sortfield) $sortfield = "b.date_valid"; $sortorder = "DESC";
}
if (!$sortfield) {
$sortfield = "b.date_valid";
}
/* /*
@ -66,8 +74,7 @@ if (!$sortfield) $sortfield = "b.date_valid";
$form = new Form($db); $form = new Form($db);
if ($id > 0 || !empty($ref)) if ($id > 0 || !empty($ref)) {
{
$product = new Product($db); $product = new Product($db);
$result = $product->fetch($id, $ref); $result = $product->fetch($id, $ref);
@ -75,12 +82,13 @@ if ($id > 0 || !empty($ref))
$parameters = array('id'=>$id); $parameters = array('id'=>$id);
$reshook = $hookmanager->executeHooks('doActions', $parameters, $product, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $product, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
llxHeader("", "", $langs->trans("CardProduct".$product->type)); llxHeader("", "", $langs->trans("CardProduct".$product->type));
if ($result > 0) if ($result > 0) {
{
$head = product_prepare_head($product); $head = product_prepare_head($product);
$titre = $langs->trans("CardProduct".$product->type); $titre = $langs->trans("CardProduct".$product->type);
$picto = ($product->type == Product::TYPE_SERVICE ? 'service' : 'product'); $picto = ($product->type == Product::TYPE_SERVICE ? 'service' : 'product');
@ -88,12 +96,16 @@ if ($id > 0 || !empty($ref))
$reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $product, $action); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $product, $action); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint; print $hookmanager->resPrint;
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
$linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; $linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
$shownav = 1; $shownav = 1;
if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) {
$shownav = 0;
}
dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref');
@ -130,8 +142,7 @@ if ($id > 0 || !empty($ref))
// Count total nb of records // Count total nb of records
$totalofrecords = ''; $totalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
{
$result = $db->query($sql); $result = $db->query($sql);
if ($result) { if ($result) {
$totalofrecords = $db->num_rows($result); $totalofrecords = $db->num_rows($result);
@ -180,8 +191,7 @@ if ($id > 0 || !empty($ref))
// Count total nb of records // Count total nb of records
$totalofrecords = ''; $totalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
{
$result = $db->query($sql); $result = $db->query($sql);
if ($result) { if ($result) {
$totalofrecords = $db->num_rows($result); $totalofrecords = $db->num_rows($result);
@ -223,20 +233,32 @@ if ($id > 0 || !empty($ref))
$db->free($result); $db->free($result);
if ($limit > 0 && $limit != $conf->liste_limit) $option .= '&limit='.urlencode($limit); if ($limit > 0 && $limit != $conf->liste_limit) {
if (!empty($id)) $option .= '&id='.$product->id; $option .= '&limit='.urlencode($limit);
if (!empty($search_month)) $option .= '&search_month='.urlencode($search_month); }
if (!empty($search_year)) $option .= '&search_year='.urlencode($search_year); if (!empty($id)) {
$option .= '&id='.$product->id;
}
if (!empty($search_month)) {
$option .= '&search_month='.urlencode($search_month);
}
if (!empty($search_year)) {
$option .= '&search_year='.urlencode($search_year);
}
print '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$product->id.'" name="search_form">'."\n"; print '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$product->id.'" name="search_form">'."\n";
if (!empty($sortfield)) if (!empty($sortfield)) {
print '<input type="hidden" name="sortfield" value="'.$sortfield.'"/>'; print '<input type="hidden" name="sortfield" value="'.$sortfield.'"/>';
if (!empty($sortorder)) }
if (!empty($sortorder)) {
print '<input type="hidden" name="sortorder" value="'.$sortorder.'"/>'; print '<input type="hidden" name="sortorder" value="'.$sortorder.'"/>';
}
print_barre_liste($langs->trans("BOMs"), $page, $_SERVER["PHP_SELF"], $option, $sortfield, $sortorder, '', count($bom_data_result), count($bom_data_result), '', 0, '', '', $limit, 0, 0, 1); print_barre_liste($langs->trans("BOMs"), $page, $_SERVER["PHP_SELF"], $option, $sortfield, $sortorder, '', count($bom_data_result), count($bom_data_result), '', 0, '', '', $limit, 0, 0, 1);
if (!empty($page)) $option .= '&page='.urlencode($page); if (!empty($page)) {
$option .= '&page='.urlencode($page);
}
print '<div class="div-table-responsive">'; print '<div class="div-table-responsive">';
print '<table class="tagtable liste listwithfilterbefore" width="100%">'; print '<table class="tagtable liste listwithfilterbefore" width="100%">';
@ -250,8 +272,7 @@ if ($id > 0 || !empty($ref))
print "</tr>\n"; print "</tr>\n";
if (!empty($bom_data_result)) { if (!empty($bom_data_result)) {
foreach ($bom_data_result as $data) foreach ($bom_data_result as $data) {
{
print '<tr class="oddeven">'; print '<tr class="oddeven">';
print '<td>'; print '<td>';
print $data['link']; print $data['link'];

View File

@ -51,7 +51,9 @@ $mesg = '';
$graphfiles = array(); $graphfiles = array();
$socid = ''; $socid = '';
if (!empty($user->socid)) $socid = $user->socid; if (!empty($user->socid)) {
$socid = $user->socid;
}
// Security check // Security check
$fieldvalue = (!empty($id) ? $id : $ref); $fieldvalue = (!empty($id) ? $id : $ref);
@ -60,7 +62,9 @@ $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product
$tmp = dol_getdate(dol_now()); $tmp = dol_getdate(dol_now());
$currentyear = $tmp['year']; $currentyear = $tmp['year'];
if (empty($search_year)) $search_year = $currentyear; if (empty($search_year)) {
$search_year = $currentyear;
}
/* /*
@ -99,7 +103,9 @@ if (!$id && empty($ref)) {
} }
$picto = 'product'; $picto = 'product';
if ($type == 1) $picto = 'service'; if ($type == 1) {
$picto = 'service';
}
print load_fiche_titre($title, $mesg, $picto); print load_fiche_titre($title, $mesg, $picto);
} else { } else {
@ -189,12 +195,15 @@ if ($result || empty($id)) {
// Year // Year
print '<tr><td class="titlefield">'.$langs->trans("Year").'</td><td>'; print '<tr><td class="titlefield">'.$langs->trans("Year").'</td><td>';
$arrayyears = array(); $arrayyears = array();
for ($year = $currentyear - 25; $year < $currentyear; $year++) for ($year = $currentyear - 25; $year < $currentyear; $year++) {
{
$arrayyears[$year] = $year; $arrayyears[$year] = $year;
} }
if (!in_array($year, $arrayyears)) $arrayyears[$year] = $year; if (!in_array($year, $arrayyears)) {
if (!in_array($currentyear, $arrayyears)) $arrayyears[$currentyear] = $currentyear; $arrayyears[$year] = $year;
}
if (!in_array($currentyear, $arrayyears)) {
$arrayyears[$currentyear] = $currentyear;
}
arsort($arrayyears); arsort($arrayyears);
print $form->selectarray('search_year', $arrayyears, $search_year, 1); print $form->selectarray('search_year', $arrayyears, $search_year, 1);
print '</td></tr>'; print '</td></tr>';
@ -206,25 +215,45 @@ if ($result || empty($id)) {
// Choice of stats mode (byunit or bynumber) // Choice of stats mode (byunit or bynumber)
if (!empty($conf->dol_use_jmobile)) print "\n".'<div class="fichecenter"><div class="nowrap">'."\n"; if (!empty($conf->dol_use_jmobile)) {
print "\n".'<div class="fichecenter"><div class="nowrap">'."\n";
}
if ($mode == 'bynumber') print '<a class="a-mesure-disabled" href="'.$_SERVER["PHP_SELF"].'?id='.(GETPOST('id') ?GETPOST('id') : $object->id).($type != '' ? '&type='.$type : '').'&mode=byunit&search_year='.$search_year.'">'; if ($mode == 'bynumber') {
else print '<span class="a-mesure">'; print '<a class="a-mesure-disabled" href="'.$_SERVER["PHP_SELF"].'?id='.(GETPOST('id') ?GETPOST('id') : $object->id).($type != '' ? '&type='.$type : '').'&mode=byunit&search_year='.$search_year.'">';
} else {
print '<span class="a-mesure">';
}
print $langs->trans("StatsByNumberOfUnits"); print $langs->trans("StatsByNumberOfUnits");
if ($mode == 'bynumber') print '</a>'; if ($mode == 'bynumber') {
else print '</span>'; print '</a>';
} else {
print '</span>';
}
if (!empty($conf->dol_use_jmobile)) print '</div>'."\n".'<div class="nowrap">'."\n"; if (!empty($conf->dol_use_jmobile)) {
else print ' &nbsp; '; print '</div>'."\n".'<div class="nowrap">'."\n";
} else {
print ' &nbsp; ';
}
if ($mode == 'byunit') print '<a class="a-mesure-disabled" href="'.$_SERVER["PHP_SELF"].'?id='.(GETPOST('id') ?GETPOST('id') : $object->id).($type != '' ? '&type='.$type : '').'&mode=bynumber&search_year='.$search_year.'">'; if ($mode == 'byunit') {
else print '<span class="a-mesure">'; print '<a class="a-mesure-disabled" href="'.$_SERVER["PHP_SELF"].'?id='.(GETPOST('id') ?GETPOST('id') : $object->id).($type != '' ? '&type='.$type : '').'&mode=bynumber&search_year='.$search_year.'">';
} else {
print '<span class="a-mesure">';
}
print $langs->trans("StatsByNumberOfEntities"); print $langs->trans("StatsByNumberOfEntities");
if ($mode == 'byunit') print '</a>'; if ($mode == 'byunit') {
else print '</span>'; print '</a>';
} else {
print '</span>';
}
if (!empty($conf->dol_use_jmobile)) print '</div></div>'; if (!empty($conf->dol_use_jmobile)) {
else print '<br>'; print '</div></div>';
} else {
print '<br>';
}
print '<br>'; print '<br>';
//print '<table width="100%">'; //print '<table width="100%">';
@ -294,7 +323,9 @@ if ($result || empty($id)) {
$mesg = $px->isGraphKo(); $mesg = $px->isGraphKo();
if (!$mesg) { if (!$mesg) {
foreach ($graphfiles as $key => $val) { foreach ($graphfiles as $key => $val) {
if (!$graphfiles[$key]['file']) continue; if (!$graphfiles[$key]['file']) {
continue;
}
$graph_data = array(); $graph_data = array();
@ -312,14 +343,30 @@ if ($result || empty($id)) {
$morefilters = ' AND d.fk_product NOT IN (SELECT cp.fk_product from '.MAIN_DB_PREFIX.'categorie_product as cp)'; $morefilters = ' AND d.fk_product NOT IN (SELECT cp.fk_product from '.MAIN_DB_PREFIX.'categorie_product as cp)';
} }
if ($key == 'propal') $graph_data = $object->get_nb_propal($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters); if ($key == 'propal') {
if ($key == 'orders') $graph_data = $object->get_nb_order($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters); $graph_data = $object->get_nb_propal($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters);
if ($key == 'invoices') $graph_data = $object->get_nb_vente($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters); }
if ($key == 'proposalssuppliers') $graph_data = $object->get_nb_propalsupplier($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters); if ($key == 'orders') {
if ($key == 'invoicessuppliers') $graph_data = $object->get_nb_achat($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters); $graph_data = $object->get_nb_order($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters);
if ($key == 'orderssuppliers') $graph_data = $object->get_nb_ordersupplier($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters); }
if ($key == 'contracts') $graph_data = $object->get_nb_contract($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters); if ($key == 'invoices') {
if ($key == 'mrp') $graph_data = $object->get_nb_mos($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters); $graph_data = $object->get_nb_vente($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters);
}
if ($key == 'proposalssuppliers') {
$graph_data = $object->get_nb_propalsupplier($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters);
}
if ($key == 'invoicessuppliers') {
$graph_data = $object->get_nb_achat($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters);
}
if ($key == 'orderssuppliers') {
$graph_data = $object->get_nb_ordersupplier($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters);
}
if ($key == 'contracts') {
$graph_data = $object->get_nb_contract($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters);
}
if ($key == 'mrp') {
$graph_data = $object->get_nb_mos($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters);
}
// TODO Save cachefile $graphfiles[$key]['file'] // TODO Save cachefile $graphfiles[$key]['file']
} }
@ -354,15 +401,31 @@ if ($result || empty($id)) {
$i = 0; $i = 0;
if (count($graphfiles) > 0) { if (count($graphfiles) > 0) {
foreach ($graphfiles as $key => $val) { foreach ($graphfiles as $key => $val) {
if (!$graphfiles[$key]['file']) continue; if (!$graphfiles[$key]['file']) {
continue;
}
if ($graphfiles == 'propal' && !$user->rights->propale->lire) continue; if ($graphfiles == 'propal' && !$user->rights->propale->lire) {
if ($graphfiles == 'order' && !$user->rights->commande->lire) continue; continue;
if ($graphfiles == 'invoices' && !$user->rights->facture->lire) continue; }
if ($graphfiles == 'proposals_suppliers' && !$user->rights->supplier_proposal->lire) continue; if ($graphfiles == 'order' && !$user->rights->commande->lire) {
if ($graphfiles == 'invoices_suppliers' && !$user->rights->fournisseur->facture->lire) continue; continue;
if ($graphfiles == 'orders_suppliers' && !$user->rights->fournisseur->commande->lire) continue; }
if ($graphfiles == 'mrp' && empty($user->rights->mrp->mo->read)) continue; if ($graphfiles == 'invoices' && !$user->rights->facture->lire) {
continue;
}
if ($graphfiles == 'proposals_suppliers' && !$user->rights->supplier_proposal->lire) {
continue;
}
if ($graphfiles == 'invoices_suppliers' && !$user->rights->fournisseur->facture->lire) {
continue;
}
if ($graphfiles == 'orders_suppliers' && !$user->rights->fournisseur->commande->lire) {
continue;
}
if ($graphfiles == 'mrp' && empty($user->rights->mrp->mo->read)) {
continue;
}
if ($i % 2 == 0) { if ($i % 2 == 0) {
@ -373,8 +436,11 @@ if ($result || empty($id)) {
// Date generation // Date generation
if ($graphfiles[$key]['output'] && !$px->isGraphKo()) { if ($graphfiles[$key]['output'] && !$px->isGraphKo()) {
if (file_exists($dir."/".$graphfiles[$key]['file']) && filemtime($dir."/".$graphfiles[$key]['file'])) $dategenerated = $langs->trans("GeneratedOn", dol_print_date(filemtime($dir."/".$graphfiles[$key]['file']), "dayhour")); if (file_exists($dir."/".$graphfiles[$key]['file']) && filemtime($dir."/".$graphfiles[$key]['file'])) {
else $dategenerated = $langs->trans("GeneratedOn", dol_print_date(dol_now(), "dayhour")); $dategenerated = $langs->trans("GeneratedOn", dol_print_date(filemtime($dir."/".$graphfiles[$key]['file']), "dayhour"));
} else {
$dategenerated = $langs->trans("GeneratedOn", dol_print_date(dol_now(), "dayhour"));
}
} else { } else {
$dategenerated = ($mesg ? '<font class="error">'.$mesg.'</font>' : $langs->trans("ChartNotGenerated")); $dategenerated = ($mesg ? '<font class="error">'.$mesg.'</font>' : $langs->trans("ChartNotGenerated"));
} }

View File

@ -40,7 +40,9 @@ $ref = GETPOST('ref', 'alpha');
$fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : '')); $fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : ''));
$fieldtype = (!empty($ref) ? 'ref' : 'rowid'); $fieldtype = (!empty($ref) ? 'ref' : 'rowid');
$socid = ''; $socid = '';
if (!empty($user->socid)) $socid = $user->socid; if (!empty($user->socid)) {
$socid = $user->socid;
}
$result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype);
// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
@ -53,12 +55,18 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST("sortfield", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if (!$sortorder) $sortorder = "DESC"; if (!$sortorder) {
if (!$sortfield) $sortfield = "c.date_commande"; $sortorder = "DESC";
}
if (!$sortfield) {
$sortfield = "c.date_commande";
}
$search_month = GETPOST('search_month', 'int'); $search_month = GETPOST('search_month', 'int');
$search_year = GETPOST('search_year', 'int'); $search_year = GETPOST('search_year', 'int');
@ -77,8 +85,7 @@ $societestatic = new Societe($db);
$form = new Form($db); $form = new Form($db);
$formother = new FormOther($db); $formother = new FormOther($db);
if ($id > 0 || !empty($ref)) if ($id > 0 || !empty($ref)) {
{
$product = new Product($db); $product = new Product($db);
$result = $product->fetch($id, $ref); $result = $product->fetch($id, $ref);
@ -86,12 +93,13 @@ if ($id > 0 || !empty($ref))
$parameters = array('id'=>$id); $parameters = array('id'=>$id);
$reshook = $hookmanager->executeHooks('doActions', $parameters, $product, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $product, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
llxHeader("", "", $langs->trans("CardProduct".$product->type)); llxHeader("", "", $langs->trans("CardProduct".$product->type));
if ($result > 0) if ($result > 0) {
{
$head = product_prepare_head($product); $head = product_prepare_head($product);
$titre = $langs->trans("CardProduct".$product->type); $titre = $langs->trans("CardProduct".$product->type);
$picto = ($product->type == Product::TYPE_SERVICE ? 'service' : 'product'); $picto = ($product->type == Product::TYPE_SERVICE ? 'service' : 'product');
@ -99,12 +107,16 @@ if ($id > 0 || !empty($ref))
$reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $product, $action); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $product, $action); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint; print $hookmanager->resPrint;
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
$linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; $linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
$shownav = 1; $shownav = 1;
if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) {
$shownav = 0;
}
dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref');
@ -123,26 +135,35 @@ if ($id > 0 || !empty($ref))
print dol_get_fiche_end(); print dol_get_fiche_end();
if ($user->rights->commande->lire) if ($user->rights->commande->lire) {
{
$sql = "SELECT DISTINCT s.nom as name, s.rowid as socid, s.code_client, c.rowid, d.total_ht as total_ht, c.ref,"; $sql = "SELECT DISTINCT s.nom as name, s.rowid as socid, s.code_client, c.rowid, d.total_ht as total_ht, c.ref,";
$sql .= " c.ref_client,"; $sql .= " c.ref_client,";
$sql .= " c.date_commande, c.fk_statut as statut, c.facture, c.rowid as commandeid, d.rowid, d.qty"; $sql .= " c.date_commande, c.fk_statut as statut, c.facture, c.rowid as commandeid, d.rowid, d.qty";
if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user "; if (!$user->rights->societe->client->voir && !$socid) {
$sql .= ", sc.fk_soc, sc.fk_user ";
}
$sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
$sql .= ", ".MAIN_DB_PREFIX."commande as c"; $sql .= ", ".MAIN_DB_PREFIX."commande as c";
$sql .= ", ".MAIN_DB_PREFIX."commandedet as d"; $sql .= ", ".MAIN_DB_PREFIX."commandedet as d";
if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if (!$user->rights->societe->client->voir && !$socid) {
$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
}
$sql .= " WHERE c.fk_soc = s.rowid"; $sql .= " WHERE c.fk_soc = s.rowid";
$sql .= " AND c.entity IN (".getEntity('commande').")"; $sql .= " AND c.entity IN (".getEntity('commande').")";
$sql .= " AND d.fk_commande = c.rowid"; $sql .= " AND d.fk_commande = c.rowid";
$sql .= " AND d.fk_product =".$product->id; $sql .= " AND d.fk_product =".$product->id;
if (!empty($search_month)) if (!empty($search_month)) {
$sql .= ' AND MONTH(c.date_commande) IN ('.$search_month.')'; $sql .= ' AND MONTH(c.date_commande) IN ('.$search_month.')';
if (!empty($search_year)) }
if (!empty($search_year)) {
$sql .= ' AND YEAR(c.date_commande) IN ('.$search_year.')'; $sql .= ' AND YEAR(c.date_commande) IN ('.$search_year.')';
if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; }
if ($socid) $sql .= " AND c.fk_soc = ".$socid; if (!$user->rights->societe->client->voir && !$socid) {
$sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
}
if ($socid) {
$sql .= " AND c.fk_soc = ".$socid;
}
$sql .= $db->order($sortfield, $sortorder); $sql .= $db->order($sortfield, $sortorder);
//Calcul total qty and amount for global if full scan list //Calcul total qty and amount for global if full scan list
@ -151,8 +172,7 @@ if ($id > 0 || !empty($ref))
// Count total nb of records // Count total nb of records
$totalofrecords = ''; $totalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
{
$result = $db->query($sql); $result = $db->query($sql);
$totalofrecords = $db->num_rows($result); $totalofrecords = $db->num_rows($result);
} }
@ -160,25 +180,36 @@ if ($id > 0 || !empty($ref))
$sql .= $db->plimit($limit + 1, $offset); $sql .= $db->plimit($limit + 1, $offset);
$result = $db->query($sql); $result = $db->query($sql);
if ($result) if ($result) {
{
$num = $db->num_rows($result); $num = $db->num_rows($result);
if ($limit > 0 && $limit != $conf->liste_limit) $option .= '&limit='.urlencode($limit); if ($limit > 0 && $limit != $conf->liste_limit) {
if (!empty($id)) $option .= '&id='.$product->id; $option .= '&limit='.urlencode($limit);
if (!empty($search_month)) $option .= '&search_month='.urlencode($search_month); }
if (!empty($search_year)) $option .= '&search_year='.urlencode($search_year); if (!empty($id)) {
$option .= '&id='.$product->id;
}
if (!empty($search_month)) {
$option .= '&search_month='.urlencode($search_month);
}
if (!empty($search_year)) {
$option .= '&search_year='.urlencode($search_year);
}
print '<form method="post" action="'.$_SERVER ['PHP_SELF'].'?id='.$product->id.'" name="search_form">'."\n"; print '<form method="post" action="'.$_SERVER ['PHP_SELF'].'?id='.$product->id.'" name="search_form">'."\n";
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
if (!empty($sortfield)) if (!empty($sortfield)) {
print '<input type="hidden" name="sortfield" value="'.$sortfield.'"/>'; print '<input type="hidden" name="sortfield" value="'.$sortfield.'"/>';
if (!empty($sortorder)) }
if (!empty($sortorder)) {
print '<input type="hidden" name="sortorder" value="'.$sortorder.'"/>'; print '<input type="hidden" name="sortorder" value="'.$sortorder.'"/>';
}
print_barre_liste($langs->trans("CustomersOrders"), $page, $_SERVER["PHP_SELF"], $option, $sortfield, $sortorder, '', $num, $totalofrecords, '', 0, '', '', $limit, 0, 0, 1); print_barre_liste($langs->trans("CustomersOrders"), $page, $_SERVER["PHP_SELF"], $option, $sortfield, $sortorder, '', $num, $totalofrecords, '', 0, '', '', $limit, 0, 0, 1);
if (!empty($page)) $option .= '&page='.urlencode($page); if (!empty($page)) {
$option .= '&page='.urlencode($page);
}
print '<div class="liste_titre liste_titre_bydiv centpercent">'; print '<div class="liste_titre liste_titre_bydiv centpercent">';
print '<div class="divsearchfield">'; print '<div class="divsearchfield">';
@ -205,10 +236,8 @@ if ($id > 0 || !empty($ref))
print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "c.fk_statut", "", $option, 'align="right"', $sortfield, $sortorder); print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "c.fk_statut", "", $option, 'align="right"', $sortfield, $sortorder);
print "</tr>\n"; print "</tr>\n";
if ($num > 0) if ($num > 0) {
{ while ($i < min($num, $limit)) {
while ($i < min($num, $limit))
{
$objp = $db->fetch_object($result); $objp = $db->fetch_object($result);
$total_ht += $objp->total_ht; $total_ht += $objp->total_ht;
@ -235,8 +264,11 @@ if ($id > 0 || !empty($ref))
} }
} }
print '<tr class="liste_total">'; print '<tr class="liste_total">';
if ($num < $limit) print '<td class="left">'.$langs->trans("Total").'</td>'; if ($num < $limit) {
else print '<td class="left">'.$langs->trans("Totalforthispage").'</td>'; print '<td class="left">'.$langs->trans("Total").'</td>';
} else {
print '<td class="left">'.$langs->trans("Totalforthispage").'</td>';
}
print '<td colspan="3"></td>'; print '<td colspan="3"></td>';
print '<td class="center">'.$total_qty.'</td>'; print '<td class="center">'.$total_qty.'</td>';
print '<td align="right">'.price($total_ht).'</td>'; print '<td align="right">'.price($total_ht).'</td>';

View File

@ -39,8 +39,9 @@ $ref = GETPOST('ref', 'alpha');
$fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : '')); $fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : ''));
$fieldtype = (!empty($ref) ? 'ref' : 'rowid'); $fieldtype = (!empty($ref) ? 'ref' : 'rowid');
$socid = ''; $socid = '';
if (!empty($user->socid)) if (!empty($user->socid)) {
$socid = $user->socid; $socid = $user->socid;
}
$result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype);
// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
@ -53,14 +54,18 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST('sortfield', 'aZ09comma'); $sortfield = GETPOST('sortfield', 'aZ09comma');
$sortorder = GETPOST('sortorder', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if (!$sortorder) if (!$sortorder) {
$sortorder = "DESC"; $sortorder = "DESC";
if (!$sortfield) }
if (!$sortfield) {
$sortfield = "c.date_commande"; $sortfield = "c.date_commande";
}
$search_month = GETPOST('search_month', 'int'); $search_month = GETPOST('search_month', 'int');
$search_year = GETPOST('search_year', 'int'); $search_year = GETPOST('search_year', 'int');
@ -88,13 +93,13 @@ if ($id > 0 || !empty($ref)) {
$parameters = array('id' => $id); $parameters = array('id' => $id);
$reshook = $hookmanager->executeHooks('doActions', $parameters, $product, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $product, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
llxHeader("", "", $langs->trans("CardProduct".$product->type)); llxHeader("", "", $langs->trans("CardProduct".$product->type));
if ($result > 0) if ($result > 0) {
{
$head = product_prepare_head($product); $head = product_prepare_head($product);
$titre = $langs->trans("CardProduct".$product->type); $titre = $langs->trans("CardProduct".$product->type);
$picto = ($product->type == Product::TYPE_SERVICE ? 'service' : 'product'); $picto = ($product->type == Product::TYPE_SERVICE ? 'service' : 'product');
@ -102,12 +107,16 @@ if ($id > 0 || !empty($ref)) {
$reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $product, $action); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $product, $action); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint; print $hookmanager->resPrint;
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
$linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; $linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
$shownav = 1; $shownav = 1;
if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) {
$shownav = 0;
}
dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref');
@ -126,30 +135,35 @@ if ($id > 0 || !empty($ref)) {
print dol_get_fiche_end(); print dol_get_fiche_end();
if ($user->rights->fournisseur->commande->lire) if ($user->rights->fournisseur->commande->lire) {
{
$sql = "SELECT DISTINCT s.nom as name, s.rowid as socid, s.code_client,"; $sql = "SELECT DISTINCT s.nom as name, s.rowid as socid, s.code_client,";
$sql .= " c.rowid, d.total_ht as total_ht, c.ref,"; $sql .= " c.rowid, d.total_ht as total_ht, c.ref,";
$sql .= " c.date_commande, c.fk_statut as statut, c.rowid as commandeid, d.rowid, d.qty"; $sql .= " c.date_commande, c.fk_statut as statut, c.rowid as commandeid, d.rowid, d.qty";
if (!$user->rights->societe->client->voir && !$socid) if (!$user->rights->societe->client->voir && !$socid) {
$sql .= ", sc.fk_soc, sc.fk_user "; $sql .= ", sc.fk_soc, sc.fk_user ";
}
$sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
$sql .= ", ".MAIN_DB_PREFIX."commande_fournisseur as c"; $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseur as c";
$sql .= ", ".MAIN_DB_PREFIX."commande_fournisseurdet as d"; $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseurdet as d";
if (!$user->rights->societe->client->voir && !$socid) if (!$user->rights->societe->client->voir && !$socid) {
$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
}
$sql .= " WHERE c.fk_soc = s.rowid"; $sql .= " WHERE c.fk_soc = s.rowid";
$sql .= " AND c.entity = ".$conf->entity; $sql .= " AND c.entity = ".$conf->entity;
$sql .= " AND d.fk_commande = c.rowid"; $sql .= " AND d.fk_commande = c.rowid";
$sql .= " AND d.fk_product =".$product->id; $sql .= " AND d.fk_product =".$product->id;
if (!empty($search_month)) if (!empty($search_month)) {
$sql .= ' AND MONTH(c.date_commande) IN ('.$search_month.')'; $sql .= ' AND MONTH(c.date_commande) IN ('.$search_month.')';
if (!empty($search_year)) }
if (!empty($search_year)) {
$sql .= ' AND YEAR(c.date_commande) IN ('.$search_year.')'; $sql .= ' AND YEAR(c.date_commande) IN ('.$search_year.')';
if (!$user->rights->societe->client->voir && !$socid) }
if (!$user->rights->societe->client->voir && !$socid) {
$sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
if ($socid) }
if ($socid) {
$sql .= " AND c.fk_soc = ".$socid; $sql .= " AND c.fk_soc = ".$socid;
}
$sql .= $db->order($sortfield, $sortorder); $sql .= $db->order($sortfield, $sortorder);
// Calcul total qty and amount for global if full scan list // Calcul total qty and amount for global if full scan list
@ -158,8 +172,7 @@ if ($id > 0 || !empty($ref)) {
// Count total nb of records // Count total nb of records
$totalofrecords = ''; $totalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
{
$result = $db->query($sql); $result = $db->query($sql);
$totalofrecords = $db->num_rows($result); $totalofrecords = $db->num_rows($result);
} }
@ -170,20 +183,32 @@ if ($id > 0 || !empty($ref)) {
if ($result) { if ($result) {
$num = $db->num_rows($result); $num = $db->num_rows($result);
if ($limit > 0 && $limit != $conf->liste_limit) $option .= '&limit='.urlencode($limit); if ($limit > 0 && $limit != $conf->liste_limit) {
if (!empty($id)) $option .= '&id='.$product->id; $option .= '&limit='.urlencode($limit);
if (!empty($search_month)) $option .= '&search_month='.urlencode($search_month); }
if (!empty($search_year)) $option .= '&search_year='.urlencode($search_year); if (!empty($id)) {
$option .= '&id='.$product->id;
}
if (!empty($search_month)) {
$option .= '&search_month='.urlencode($search_month);
}
if (!empty($search_year)) {
$option .= '&search_year='.urlencode($search_year);
}
print '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$product->id.'" name="search_form">'."\n"; print '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$product->id.'" name="search_form">'."\n";
if (!empty($sortfield)) if (!empty($sortfield)) {
print '<input type="hidden" name="sortfield" value="'.$sortfield.'"/>'; print '<input type="hidden" name="sortfield" value="'.$sortfield.'"/>';
if (!empty($sortorder)) }
if (!empty($sortorder)) {
print '<input type="hidden" name="sortorder" value="'.$sortorder.'"/>'; print '<input type="hidden" name="sortorder" value="'.$sortorder.'"/>';
}
print_barre_liste($langs->trans("SuppliersOrders"), $page, $_SERVER["PHP_SELF"], $option, $sortfield, $sortorder, '', $num, $totalofrecords, '', 0, '', '', $limit, 0, 0, 1); print_barre_liste($langs->trans("SuppliersOrders"), $page, $_SERVER["PHP_SELF"], $option, $sortfield, $sortorder, '', $num, $totalofrecords, '', 0, '', '', $limit, 0, 0, 1);
if (!empty($page)) $option .= '&page='.urlencode($page); if (!empty($page)) {
$option .= '&page='.urlencode($page);
}
print '<div class="liste_titre liste_titre_bydiv centpercent">'; print '<div class="liste_titre liste_titre_bydiv centpercent">';
print '<div class="divsearchfield">'; print '<div class="divsearchfield">';
@ -210,10 +235,8 @@ if ($id > 0 || !empty($ref)) {
print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "c.fk_statut", "", $option, 'align="right"', $sortfield, $sortorder); print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "c.fk_statut", "", $option, 'align="right"', $sortfield, $sortorder);
print "</tr>\n"; print "</tr>\n";
if ($num > 0) if ($num > 0) {
{ while ($i < min($num, $limit)) {
while ($i < min($num, $limit))
{
$objp = $db->fetch_object($result); $objp = $db->fetch_object($result);
$total_ht += $objp->total_ht; $total_ht += $objp->total_ht;
@ -240,8 +263,11 @@ if ($id > 0 || !empty($ref)) {
} }
} }
print '<tr class="liste_total">'; print '<tr class="liste_total">';
if ($num < $limit) print '<td class="left">'.$langs->trans("Total").'</td>'; if ($num < $limit) {
else print '<td class="left">'.$langs->trans("Totalforthispage").'</td>'; print '<td class="left">'.$langs->trans("Total").'</td>';
} else {
print '<td class="left">'.$langs->trans("Totalforthispage").'</td>';
}
print '<td colspan="3"></td>'; print '<td colspan="3"></td>';
print '<td class="center">'.$total_qty.'</td>'; print '<td class="center">'.$total_qty.'</td>';
print '<td align="right">'.price($total_ht).'</td>'; print '<td align="right">'.price($total_ht).'</td>';

View File

@ -37,7 +37,9 @@ $ref = GETPOST('ref', 'alpha');
// Security check // Security check
$fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : '')); $fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : ''));
$fieldtype = (!empty($ref) ? 'ref' : 'rowid'); $fieldtype = (!empty($ref) ? 'ref' : 'rowid');
if ($user->socid) $socid = $user->socid; if ($user->socid) {
$socid = $user->socid;
}
$result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype);
// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
@ -50,12 +52,18 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST("sortfield", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if (!$sortorder) $sortorder = "DESC"; if (!$sortorder) {
if (!$sortfield) $sortfield = "c.date_contrat"; $sortorder = "DESC";
}
if (!$sortfield) {
$sortfield = "c.date_contrat";
}
/* /*
@ -67,8 +75,7 @@ $staticcontratligne = new ContratLigne($db);
$form = new Form($db); $form = new Form($db);
if ($id > 0 || !empty($ref)) if ($id > 0 || !empty($ref)) {
{
$product = new Product($db); $product = new Product($db);
$result = $product->fetch($id, $ref); $result = $product->fetch($id, $ref);
@ -76,12 +83,13 @@ if ($id > 0 || !empty($ref))
$parameters = array('id'=>$id); $parameters = array('id'=>$id);
$reshook = $hookmanager->executeHooks('doActions', $parameters, $product, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $product, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
llxHeader("", "", $langs->trans("CardProduct".$product->type)); llxHeader("", "", $langs->trans("CardProduct".$product->type));
if ($result > 0) if ($result > 0) {
{
$head = product_prepare_head($product); $head = product_prepare_head($product);
$titre = $langs->trans("CardProduct".$product->type); $titre = $langs->trans("CardProduct".$product->type);
$picto = ($product->type == Product::TYPE_SERVICE ? 'service' : 'product'); $picto = ($product->type == Product::TYPE_SERVICE ? 'service' : 'product');
@ -89,12 +97,16 @@ if ($id > 0 || !empty($ref))
$reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $product, $action); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $product, $action); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint; print $hookmanager->resPrint;
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
$linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; $linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
$shownav = 1; $shownav = 1;
if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) {
$shownav = 0;
}
dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref');
@ -123,15 +135,21 @@ if ($id > 0 || !empty($ref))
$sql .= " c.rowid as rowid, c.ref, c.ref_customer, c.ref_supplier, c.date_contrat, c.statut as statut,"; $sql .= " c.rowid as rowid, c.ref, c.ref_customer, c.ref_supplier, c.date_contrat, c.statut as statut,";
$sql .= " s.nom as name, s.rowid as socid, s.code_client"; $sql .= " s.nom as name, s.rowid as socid, s.code_client";
$sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if (!$user->rights->societe->client->voir && !$socid) {
$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
}
$sql .= ", ".MAIN_DB_PREFIX."contrat as c"; $sql .= ", ".MAIN_DB_PREFIX."contrat as c";
$sql .= ", ".MAIN_DB_PREFIX."contratdet as cd"; $sql .= ", ".MAIN_DB_PREFIX."contratdet as cd";
$sql .= " WHERE c.rowid = cd.fk_contrat"; $sql .= " WHERE c.rowid = cd.fk_contrat";
$sql .= " AND c.fk_soc = s.rowid"; $sql .= " AND c.fk_soc = s.rowid";
$sql .= " AND c.entity IN (".getEntity('contract').")"; $sql .= " AND c.entity IN (".getEntity('contract').")";
$sql .= " AND cd.fk_product =".$product->id; $sql .= " AND cd.fk_product =".$product->id;
if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; if (!$user->rights->societe->client->voir && !$socid) {
if ($socid) $sql .= " AND s.rowid = ".$socid; $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
}
if ($socid) {
$sql .= " AND s.rowid = ".$socid;
}
$sql .= " GROUP BY c.rowid, c.ref, c.ref_customer, c.ref_supplier, c.date_contrat, c.statut, s.nom, s.rowid, s.code_client"; $sql .= " GROUP BY c.rowid, c.ref, c.ref_customer, c.ref_supplier, c.date_contrat, c.statut, s.nom, s.rowid, s.code_client";
$sql .= $db->order($sortfield, $sortorder); $sql .= $db->order($sortfield, $sortorder);
@ -141,8 +159,7 @@ if ($id > 0 || !empty($ref))
// Count total nb of records // Count total nb of records
$totalofrecords = ''; $totalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
{
$result = $db->query($sql); $result = $db->query($sql);
$totalofrecords = $db->num_rows($result); $totalofrecords = $db->num_rows($result);
} }
@ -150,25 +167,36 @@ if ($id > 0 || !empty($ref))
$sql .= $db->plimit($limit + 1, $offset); $sql .= $db->plimit($limit + 1, $offset);
$result = $db->query($sql); $result = $db->query($sql);
if ($result) if ($result) {
{
$num = $db->num_rows($result); $num = $db->num_rows($result);
if ($limit > 0 && $limit != $conf->liste_limit) $option .= '&limit='.urlencode($limit); if ($limit > 0 && $limit != $conf->liste_limit) {
if (!empty($id)) $option .= '&id='.$product->id; $option .= '&limit='.urlencode($limit);
if (!empty($search_month)) $option .= '&search_month='.urlencode($search_month); }
if (!empty($search_year)) $option .= '&search_year='.urlencode($search_year); if (!empty($id)) {
$option .= '&id='.$product->id;
}
if (!empty($search_month)) {
$option .= '&search_month='.urlencode($search_month);
}
if (!empty($search_year)) {
$option .= '&search_year='.urlencode($search_year);
}
print '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$product->id.'" name="search_form">'."\n"; print '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$product->id.'" name="search_form">'."\n";
if (!empty($sortfield)) if (!empty($sortfield)) {
print '<input type="hidden" name="sortfield" value="'.$sortfield.'"/>'; print '<input type="hidden" name="sortfield" value="'.$sortfield.'"/>';
if (!empty($sortorder)) }
if (!empty($sortorder)) {
print '<input type="hidden" name="sortorder" value="'.$sortorder.'"/>'; print '<input type="hidden" name="sortorder" value="'.$sortorder.'"/>';
}
print_barre_liste($langs->trans("Contrats"), $page, $_SERVER["PHP_SELF"], $option, $sortfield, $sortorder, '', $num, $totalofrecords, '', 0, '', '', $limit, 0, 0, 1); print_barre_liste($langs->trans("Contrats"), $page, $_SERVER["PHP_SELF"], $option, $sortfield, $sortorder, '', $num, $totalofrecords, '', 0, '', '', $limit, 0, 0, 1);
if (!empty($page)) $option .= '&page='.urlencode($page); if (!empty($page)) {
$option .= '&page='.urlencode($page);
}
$i = 0; $i = 0;
print '<div class="div-table-responsive">'; print '<div class="div-table-responsive">';
@ -187,10 +215,8 @@ if ($id > 0 || !empty($ref))
$contracttmp = new Contrat($db); $contracttmp = new Contrat($db);
if ($num > 0) if ($num > 0) {
{ while ($i < min($num, $limit)) {
while ($i < min($num, $limit))
{
$objp = $db->fetch_object($result); $objp = $db->fetch_object($result);
$contracttmp->id = $objp->rowid; $contracttmp->id = $objp->rowid;

View File

@ -41,7 +41,9 @@ $ref = GETPOST('ref', 'alpha');
$fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : '')); $fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : ''));
$fieldtype = (!empty($ref) ? 'ref' : 'rowid'); $fieldtype = (!empty($ref) ? 'ref' : 'rowid');
$socid = ''; $socid = '';
if (!empty($user->socid)) $socid = $user->socid; if (!empty($user->socid)) {
$socid = $user->socid;
}
$result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype);
// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
@ -54,12 +56,18 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST("sortfield", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if (!$sortorder) $sortorder = "DESC"; if (!$sortorder) {
if (!$sortfield) $sortfield = "f.datef"; $sortorder = "DESC";
}
if (!$sortfield) {
$sortfield = "f.datef";
}
$search_month = GETPOST('search_month', 'int'); $search_month = GETPOST('search_month', 'int');
$search_year = GETPOST('search_year', 'int'); $search_year = GETPOST('search_year', 'int');
@ -81,8 +89,7 @@ $societestatic = new Societe($db);
$form = new Form($db); $form = new Form($db);
$formother = new FormOther($db); $formother = new FormOther($db);
if ($id > 0 || !empty($ref)) if ($id > 0 || !empty($ref)) {
{
$product = new Product($db); $product = new Product($db);
$result = $product->fetch($id, $ref); $result = $product->fetch($id, $ref);
@ -90,26 +97,25 @@ if ($id > 0 || !empty($ref))
$parameters = array('id'=>$id); $parameters = array('id'=>$id);
$reshook = $hookmanager->executeHooks('doActions', $parameters, $product, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $product, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
$title = $langs->trans('ProductServiceCard'); $title = $langs->trans('ProductServiceCard');
$helpurl = ''; $helpurl = '';
$shortlabel = dol_trunc($object->label, 16); $shortlabel = dol_trunc($object->label, 16);
if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) {
{
$title = $langs->trans('Product')." ".$shortlabel." - ".$langs->trans('Referers'); $title = $langs->trans('Product')." ".$shortlabel." - ".$langs->trans('Referers');
$helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos'; $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos';
} }
if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) {
{
$title = $langs->trans('Service')." ".$shortlabel." - ".$langs->trans('Referers'); $title = $langs->trans('Service')." ".$shortlabel." - ".$langs->trans('Referers');
$helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios'; $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios';
} }
llxHeader('', $title, $helpurl); llxHeader('', $title, $helpurl);
if ($result > 0) if ($result > 0) {
{
$head = product_prepare_head($product); $head = product_prepare_head($product);
$titre = $langs->trans("CardProduct".$product->type); $titre = $langs->trans("CardProduct".$product->type);
$picto = ($product->type == Product::TYPE_SERVICE ? 'service' : 'product'); $picto = ($product->type == Product::TYPE_SERVICE ? 'service' : 'product');
@ -117,12 +123,16 @@ if ($id > 0 || !empty($ref))
$reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $product, $action); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $product, $action); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint; print $hookmanager->resPrint;
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
$linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; $linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
$shownav = 1; $shownav = 1;
if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) {
$shownav = 0;
}
dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref');
@ -140,29 +150,37 @@ if ($id > 0 || !empty($ref))
print dol_get_fiche_end(); print dol_get_fiche_end();
if ($showmessage && $nboflines > 1) if ($showmessage && $nboflines > 1) {
{
print '<span class="opacitymedium">'.$langs->trans("ClinkOnALinkOfColumn", $langs->transnoentitiesnoconv("Referers")).'</span>'; print '<span class="opacitymedium">'.$langs->trans("ClinkOnALinkOfColumn", $langs->transnoentitiesnoconv("Referers")).'</span>';
} elseif ($user->rights->facture->lire) } elseif ($user->rights->facture->lire) {
{
$sql = "SELECT DISTINCT s.nom as name, s.rowid as socid, s.code_client,"; $sql = "SELECT DISTINCT s.nom as name, s.rowid as socid, s.code_client,";
$sql .= " f.ref, f.datef, f.paye, f.type, f.fk_statut as statut, f.rowid as facid,"; $sql .= " f.ref, f.datef, f.paye, f.type, f.fk_statut as statut, f.rowid as facid,";
$sql .= " d.rowid, d.total_ht as total_ht, d.qty"; // We must keep the d.rowid here to not loose record because of the distinct used to ignore duplicate line when link on societe_commerciaux is used $sql .= " d.rowid, d.total_ht as total_ht, d.qty"; // We must keep the d.rowid here to not loose record because of the distinct used to ignore duplicate line when link on societe_commerciaux is used
if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user "; if (!$user->rights->societe->client->voir && !$socid) {
$sql .= ", sc.fk_soc, sc.fk_user ";
}
$sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
$sql .= ", ".MAIN_DB_PREFIX."facture as f"; $sql .= ", ".MAIN_DB_PREFIX."facture as f";
$sql .= ", ".MAIN_DB_PREFIX."facturedet as d"; $sql .= ", ".MAIN_DB_PREFIX."facturedet as d";
if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if (!$user->rights->societe->client->voir && !$socid) {
$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
}
$sql .= " WHERE f.fk_soc = s.rowid"; $sql .= " WHERE f.fk_soc = s.rowid";
$sql .= " AND f.entity IN (".getEntity('invoice').")"; $sql .= " AND f.entity IN (".getEntity('invoice').")";
$sql .= " AND d.fk_facture = f.rowid"; $sql .= " AND d.fk_facture = f.rowid";
$sql .= " AND d.fk_product =".$product->id; $sql .= " AND d.fk_product =".$product->id;
if (!empty($search_month)) if (!empty($search_month)) {
$sql .= ' AND MONTH(f.datef) IN ('.$search_month.')'; $sql .= ' AND MONTH(f.datef) IN ('.$search_month.')';
if (!empty($search_year)) }
if (!empty($search_year)) {
$sql .= ' AND YEAR(f.datef) IN ('.$search_year.')'; $sql .= ' AND YEAR(f.datef) IN ('.$search_year.')';
if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; }
if ($socid) $sql .= " AND f.fk_soc = ".$socid; if (!$user->rights->societe->client->voir && !$socid) {
$sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
}
if ($socid) {
$sql .= " AND f.fk_soc = ".$socid;
}
$sql .= $db->order($sortfield, $sortorder); $sql .= $db->order($sortfield, $sortorder);
// Calcul total qty and amount for global if full scan list // Calcul total qty and amount for global if full scan list
@ -171,8 +189,7 @@ if ($id > 0 || !empty($ref))
// Count total nb of records // Count total nb of records
$totalofrecords = ''; $totalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
{
$result = $db->query($sql); $result = $db->query($sql);
$totalofrecords = $db->num_rows($result); $totalofrecords = $db->num_rows($result);
} }
@ -180,24 +197,35 @@ if ($id > 0 || !empty($ref))
$sql .= $db->plimit($limit + 1, $offset); $sql .= $db->plimit($limit + 1, $offset);
$result = $db->query($sql); $result = $db->query($sql);
if ($result) if ($result) {
{
$num = $db->num_rows($result); $num = $db->num_rows($result);
if ($limit > 0 && $limit != $conf->liste_limit) $option .= '&limit='.urlencode($limit); if ($limit > 0 && $limit != $conf->liste_limit) {
if (!empty($id)) $option .= '&id='.$product->id; $option .= '&limit='.urlencode($limit);
if (!empty($search_month)) $option .= '&search_month='.urlencode($search_month); }
if (!empty($search_year)) $option .= '&search_year='.urlencode($search_year); if (!empty($id)) {
$option .= '&id='.$product->id;
}
if (!empty($search_month)) {
$option .= '&search_month='.urlencode($search_month);
}
if (!empty($search_year)) {
$option .= '&search_year='.urlencode($search_year);
}
print '<form method="post" action="'.$_SERVER ['PHP_SELF'].'?id='.$product->id.'" name="search_form">'."\n"; print '<form method="post" action="'.$_SERVER ['PHP_SELF'].'?id='.$product->id.'" name="search_form">'."\n";
if (!empty($sortfield)) if (!empty($sortfield)) {
print '<input type="hidden" name="sortfield" value="'.$sortfield.'"/>'; print '<input type="hidden" name="sortfield" value="'.$sortfield.'"/>';
if (!empty($sortorder)) }
if (!empty($sortorder)) {
print '<input type="hidden" name="sortorder" value="'.$sortorder.'"/>'; print '<input type="hidden" name="sortorder" value="'.$sortorder.'"/>';
}
print_barre_liste($langs->trans("CustomersInvoices"), $page, $_SERVER["PHP_SELF"], $option, $sortfield, $sortorder, '', $num, $totalofrecords, '', 0, '', '', $limit, 0, 0, 1); print_barre_liste($langs->trans("CustomersInvoices"), $page, $_SERVER["PHP_SELF"], $option, $sortfield, $sortorder, '', $num, $totalofrecords, '', 0, '', '', $limit, 0, 0, 1);
if (!empty($page)) $option .= '&page='.urlencode($page); if (!empty($page)) {
$option .= '&page='.urlencode($page);
}
print '<div class="liste_titre liste_titre_bydiv centpercent">'; print '<div class="liste_titre liste_titre_bydiv centpercent">';
print '<div class="divsearchfield">'; print '<div class="divsearchfield">';
@ -224,13 +252,13 @@ if ($id > 0 || !empty($ref))
print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "f.paye,f.fk_statut", "", $option, 'align="right"', $sortfield, $sortorder); print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "f.paye,f.fk_statut", "", $option, 'align="right"', $sortfield, $sortorder);
print "</tr>\n"; print "</tr>\n";
if ($num > 0) if ($num > 0) {
{ while ($i < min($num, $limit)) {
while ($i < min($num, $limit))
{
$objp = $db->fetch_object($result); $objp = $db->fetch_object($result);
if ($objp->type == Facture::TYPE_CREDIT_NOTE) $objp->qty = -($objp->qty); if ($objp->type == Facture::TYPE_CREDIT_NOTE) {
$objp->qty = -($objp->qty);
}
$total_ht += $objp->total_ht; $total_ht += $objp->total_ht;
$total_qty += $objp->qty; $total_qty += $objp->qty;
@ -256,8 +284,11 @@ if ($id > 0 || !empty($ref))
} }
} }
print '<tr class="liste_total">'; print '<tr class="liste_total">';
if ($num < $limit) print '<td class="left">'.$langs->trans("Total").'</td>'; if ($num < $limit) {
else print '<td class="left">'.$langs->trans("Totalforthispage").'</td>'; print '<td class="left">'.$langs->trans("Total").'</td>';
} else {
print '<td class="left">'.$langs->trans("Totalforthispage").'</td>';
}
print '<td colspan="3"></td>'; print '<td colspan="3"></td>';
print '<td class="center">'.$total_qty.'</td>'; print '<td class="center">'.$total_qty.'</td>';
print '<td align="right">'.price($total_ht).'</td>'; print '<td align="right">'.price($total_ht).'</td>';

View File

@ -41,7 +41,9 @@ $ref = GETPOST('ref', 'alpha');
$fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : '')); $fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : ''));
$fieldtype = (!empty($ref) ? 'ref' : 'rowid'); $fieldtype = (!empty($ref) ? 'ref' : 'rowid');
$socid = ''; $socid = '';
if (!empty($user->socid)) $socid = $user->socid; if (!empty($user->socid)) {
$socid = $user->socid;
}
$result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype);
// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
@ -54,12 +56,18 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST("sortfield", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if (!$sortorder) $sortorder = "DESC"; if (!$sortorder) {
if (!$sortfield) $sortfield = "f.datef"; $sortorder = "DESC";
}
if (!$sortfield) {
$sortfield = "f.datef";
}
$search_month = GETPOST('search_month', 'int'); $search_month = GETPOST('search_month', 'int');
$search_year = GETPOST('search_year', 'int'); $search_year = GETPOST('search_year', 'int');
@ -78,8 +86,7 @@ $societestatic = new Societe($db);
$form = new Form($db); $form = new Form($db);
$formother = new FormOther($db); $formother = new FormOther($db);
if ($id > 0 || !empty($ref)) if ($id > 0 || !empty($ref)) {
{
$product = new Product($db); $product = new Product($db);
$result = $product->fetch($id, $ref); $result = $product->fetch($id, $ref);
@ -87,12 +94,13 @@ if ($id > 0 || !empty($ref))
$parameters = array('id' => $id); $parameters = array('id' => $id);
$reshook = $hookmanager->executeHooks('doActions', $parameters, $product, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $product, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
llxHeader("", "", $langs->trans("CardProduct".$product->type)); llxHeader("", "", $langs->trans("CardProduct".$product->type));
if ($result > 0) if ($result > 0) {
{
$head = product_prepare_head($product); $head = product_prepare_head($product);
$titre = $langs->trans("CardProduct".$product->type); $titre = $langs->trans("CardProduct".$product->type);
$picto = ($product->type == Product::TYPE_SERVICE ? 'service' : 'product'); $picto = ($product->type == Product::TYPE_SERVICE ? 'service' : 'product');
@ -100,12 +108,16 @@ if ($id > 0 || !empty($ref))
$reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $product, $action); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $product, $action); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint; print $hookmanager->resPrint;
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
$linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; $linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
$shownav = 1; $shownav = 1;
if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) {
$shownav = 0;
}
dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref');
@ -124,26 +136,34 @@ if ($id > 0 || !empty($ref))
print dol_get_fiche_end(); print dol_get_fiche_end();
if ($user->rights->fournisseur->facture->lire) if ($user->rights->fournisseur->facture->lire) {
{
$sql = "SELECT DISTINCT s.nom as name, s.rowid as socid, s.code_client, d.rowid, d.total_ht as line_total_ht,"; $sql = "SELECT DISTINCT s.nom as name, s.rowid as socid, s.code_client, d.rowid, d.total_ht as line_total_ht,";
$sql .= " f.rowid as facid, f.ref, f.ref_supplier, f.datef, f.libelle as label, f.total_ht, f.total_ttc, f.total_tva, f.paye, f.fk_statut as statut, d.qty"; $sql .= " f.rowid as facid, f.ref, f.ref_supplier, f.datef, f.libelle as label, f.total_ht, f.total_ttc, f.total_tva, f.paye, f.fk_statut as statut, d.qty";
if (!$user->rights->societe->client->voir && !$socid) if (!$user->rights->societe->client->voir && !$socid) {
$sql .= ", sc.fk_soc, sc.fk_user "; $sql .= ", sc.fk_soc, sc.fk_user ";
}
$sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
$sql .= ", ".MAIN_DB_PREFIX."facture_fourn as f"; $sql .= ", ".MAIN_DB_PREFIX."facture_fourn as f";
$sql .= ", ".MAIN_DB_PREFIX."facture_fourn_det as d"; $sql .= ", ".MAIN_DB_PREFIX."facture_fourn_det as d";
if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if (!$user->rights->societe->client->voir && !$socid) {
$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
}
$sql .= " WHERE f.fk_soc = s.rowid"; $sql .= " WHERE f.fk_soc = s.rowid";
$sql .= " AND f.entity IN (".getEntity('facture_fourn').")"; $sql .= " AND f.entity IN (".getEntity('facture_fourn').")";
$sql .= " AND d.fk_facture_fourn = f.rowid"; $sql .= " AND d.fk_facture_fourn = f.rowid";
$sql .= " AND d.fk_product =".$product->id; $sql .= " AND d.fk_product =".$product->id;
if (!empty($search_month)) if (!empty($search_month)) {
$sql .= ' AND MONTH(f.datef) IN ('.$search_month.')'; $sql .= ' AND MONTH(f.datef) IN ('.$search_month.')';
if (!empty($search_year)) }
if (!empty($search_year)) {
$sql .= ' AND YEAR(f.datef) IN ('.$search_year.')'; $sql .= ' AND YEAR(f.datef) IN ('.$search_year.')';
if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; }
if ($socid) $sql .= " AND f.fk_soc = ".$socid; if (!$user->rights->societe->client->voir && !$socid) {
$sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
}
if ($socid) {
$sql .= " AND f.fk_soc = ".$socid;
}
$sql .= " ORDER BY $sortfield $sortorder "; $sql .= " ORDER BY $sortfield $sortorder ";
// Calcul total qty and amount for global if full scan list // Calcul total qty and amount for global if full scan list
@ -152,8 +172,7 @@ if ($id > 0 || !empty($ref))
// Count total nb of records // Count total nb of records
$totalofrecords = ''; $totalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
{
$result = $db->query($sql); $result = $db->query($sql);
$totalofrecords = $db->num_rows($result); $totalofrecords = $db->num_rows($result);
} }
@ -161,24 +180,35 @@ if ($id > 0 || !empty($ref))
$sql .= $db->plimit($limit + 1, $offset); $sql .= $db->plimit($limit + 1, $offset);
$result = $db->query($sql); $result = $db->query($sql);
if ($result) if ($result) {
{
$num = $db->num_rows($result); $num = $db->num_rows($result);
if ($limit > 0 && $limit != $conf->liste_limit) $option .= '&limit='.urlencode($limit); if ($limit > 0 && $limit != $conf->liste_limit) {
if (!empty($id)) $option .= '&id='.$product->id; $option .= '&limit='.urlencode($limit);
if (!empty($search_month)) $option .= '&search_month='.urlencode($search_month); }
if (!empty($search_year)) $option .= '&search_year='.urlencode($search_year); if (!empty($id)) {
$option .= '&id='.$product->id;
}
if (!empty($search_month)) {
$option .= '&search_month='.urlencode($search_month);
}
if (!empty($search_year)) {
$option .= '&search_year='.urlencode($search_year);
}
print '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$product->id.'" name="search_form">'."\n"; print '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$product->id.'" name="search_form">'."\n";
if (!empty($sortfield)) if (!empty($sortfield)) {
print '<input type="hidden" name="sortfield" value="'.$sortfield.'"/>'; print '<input type="hidden" name="sortfield" value="'.$sortfield.'"/>';
if (!empty($sortorder)) }
if (!empty($sortorder)) {
print '<input type="hidden" name="sortorder" value="'.$sortorder.'"/>'; print '<input type="hidden" name="sortorder" value="'.$sortorder.'"/>';
}
print_barre_liste($langs->trans("SuppliersInvoices"), $page, $_SERVER["PHP_SELF"], $option, $sortfield, $sortorder, '', $num, $totalofrecords, '', 0, '', '', $limit, 0, 0, 1); print_barre_liste($langs->trans("SuppliersInvoices"), $page, $_SERVER["PHP_SELF"], $option, $sortfield, $sortorder, '', $num, $totalofrecords, '', 0, '', '', $limit, 0, 0, 1);
if (!empty($page)) $option .= '&page='.urlencode($page); if (!empty($page)) {
$option .= '&page='.urlencode($page);
}
print '<div class="liste_titre liste_titre_bydiv centpercent">'; print '<div class="liste_titre liste_titre_bydiv centpercent">';
print '<div class="divsearchfield">'; print '<div class="divsearchfield">';
@ -205,10 +235,8 @@ if ($id > 0 || !empty($ref))
print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "f.paye,f.fk_statut", "", $option, 'align="right"', $sortfield, $sortorder); print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "f.paye,f.fk_statut", "", $option, 'align="right"', $sortfield, $sortorder);
print "</tr>\n"; print "</tr>\n";
if ($num > 0) if ($num > 0) {
{ while ($i < min($num, $limit)) {
while ($i < min($num, $limit))
{
$objp = $db->fetch_object($result); $objp = $db->fetch_object($result);
$total_ht += $objp->line_total_ht; $total_ht += $objp->line_total_ht;
@ -241,8 +269,11 @@ if ($id > 0 || !empty($ref))
} }
} }
print '<tr class="liste_total">'; print '<tr class="liste_total">';
if ($num < $limit) print '<td class="left">'.$langs->trans("Total").'</td>'; if ($num < $limit) {
else print '<td class="left">'.$langs->trans("Totalforthispage").'</td>'; print '<td class="left">'.$langs->trans("Total").'</td>';
} else {
print '<td class="left">'.$langs->trans("Totalforthispage").'</td>';
}
print '<td colspan="3"></td>'; print '<td colspan="3"></td>';
print '<td class="center">'.$total_qty.'</td>'; print '<td class="center">'.$total_qty.'</td>';
print '<td align="right">'.price($total_ht).'</td>'; print '<td align="right">'.price($total_ht).'</td>';

View File

@ -37,7 +37,9 @@ $ref = GETPOST('ref', 'alpha');
// Security check // Security check
$fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : '')); $fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : ''));
$fieldtype = (!empty($ref) ? 'ref' : 'rowid'); $fieldtype = (!empty($ref) ? 'ref' : 'rowid');
if ($user->socid) $socid = $user->socid; if ($user->socid) {
$socid = $user->socid;
}
$result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype);
// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
@ -50,12 +52,18 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST("sortfield", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if (!$sortorder) $sortorder = "DESC"; if (!$sortorder) {
if (!$sortfield) $sortfield = "c.date_valid"; $sortorder = "DESC";
}
if (!$sortfield) {
$sortfield = "c.date_valid";
}
/* /*
@ -67,8 +75,7 @@ $staticmoligne = new MoLine($db);
$form = new Form($db); $form = new Form($db);
if ($id > 0 || !empty($ref)) if ($id > 0 || !empty($ref)) {
{
$product = new Product($db); $product = new Product($db);
$result = $product->fetch($id, $ref); $result = $product->fetch($id, $ref);
@ -76,12 +83,13 @@ if ($id > 0 || !empty($ref))
$parameters = array('id'=>$id); $parameters = array('id'=>$id);
$reshook = $hookmanager->executeHooks('doActions', $parameters, $product, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $product, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
llxHeader("", "", $langs->trans("CardProduct".$product->type)); llxHeader("", "", $langs->trans("CardProduct".$product->type));
if ($result > 0) if ($result > 0) {
{
$head = product_prepare_head($product); $head = product_prepare_head($product);
$titre = $langs->trans("CardProduct".$product->type); $titre = $langs->trans("CardProduct".$product->type);
$picto = ($product->type == Product::TYPE_SERVICE ? 'service' : 'product'); $picto = ($product->type == Product::TYPE_SERVICE ? 'service' : 'product');
@ -89,12 +97,16 @@ if ($id > 0 || !empty($ref))
$reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $product, $action); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $product, $action); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint; print $hookmanager->resPrint;
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
$linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; $linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
$shownav = 1; $shownav = 1;
if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) {
$shownav = 0;
}
dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref');
@ -127,7 +139,9 @@ if ($id > 0 || !empty($ref))
$sql .= " WHERE c.rowid = cd.fk_mo"; $sql .= " WHERE c.rowid = cd.fk_mo";
$sql .= " AND c.entity IN (".getEntity('mo').")"; $sql .= " AND c.entity IN (".getEntity('mo').")";
$sql .= " AND cd.fk_product =".$product->id; $sql .= " AND cd.fk_product =".$product->id;
if ($socid) $sql .= " AND s.rowid = ".$socid; if ($socid) {
$sql .= " AND s.rowid = ".$socid;
}
$sql .= " GROUP BY c.rowid, c.ref, c.date_valid, c.status"; $sql .= " GROUP BY c.rowid, c.ref, c.date_valid, c.status";
//$sql .= ", s.nom, s.rowid, s.code_client"; //$sql .= ", s.nom, s.rowid, s.code_client";
$sql .= $db->order($sortfield, $sortorder); $sql .= $db->order($sortfield, $sortorder);
@ -138,8 +152,7 @@ if ($id > 0 || !empty($ref))
// Count total nb of records // Count total nb of records
$totalofrecords = ''; $totalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
{
$result = $db->query($sql); $result = $db->query($sql);
$totalofrecords = $db->num_rows($result); $totalofrecords = $db->num_rows($result);
} }
@ -147,24 +160,35 @@ if ($id > 0 || !empty($ref))
$sql .= $db->plimit($limit + 1, $offset); $sql .= $db->plimit($limit + 1, $offset);
$result = $db->query($sql); $result = $db->query($sql);
if ($result) if ($result) {
{
$num = $db->num_rows($result); $num = $db->num_rows($result);
if ($limit > 0 && $limit != $conf->liste_limit) $option .= '&limit='.urlencode($limit); if ($limit > 0 && $limit != $conf->liste_limit) {
if (!empty($id)) $option .= '&id='.$product->id; $option .= '&limit='.urlencode($limit);
if (!empty($search_month)) $option .= '&search_month='.urlencode($search_month); }
if (!empty($search_year)) $option .= '&search_year='.urlencode($search_year); if (!empty($id)) {
$option .= '&id='.$product->id;
}
if (!empty($search_month)) {
$option .= '&search_month='.urlencode($search_month);
}
if (!empty($search_year)) {
$option .= '&search_year='.urlencode($search_year);
}
print '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$product->id.'" name="search_form">'."\n"; print '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$product->id.'" name="search_form">'."\n";
if (!empty($sortfield)) if (!empty($sortfield)) {
print '<input type="hidden" name="sortfield" value="'.$sortfield.'"/>'; print '<input type="hidden" name="sortfield" value="'.$sortfield.'"/>';
if (!empty($sortorder)) }
if (!empty($sortorder)) {
print '<input type="hidden" name="sortorder" value="'.$sortorder.'"/>'; print '<input type="hidden" name="sortorder" value="'.$sortorder.'"/>';
}
print_barre_liste($langs->trans("Mos"), $page, $_SERVER["PHP_SELF"], $option, $sortfield, $sortorder, '', $num, $totalofrecords, '', 0, '', '', $limit, 0, 0, 1); print_barre_liste($langs->trans("Mos"), $page, $_SERVER["PHP_SELF"], $option, $sortfield, $sortorder, '', $num, $totalofrecords, '', 0, '', '', $limit, 0, 0, 1);
if (!empty($page)) $option .= '&page='.urlencode($page); if (!empty($page)) {
$option .= '&page='.urlencode($page);
}
$i = 0; $i = 0;
print '<div class="div-table-responsive">'; print '<div class="div-table-responsive">';
@ -183,10 +207,8 @@ if ($id > 0 || !empty($ref))
$motmp = new Mo($db); $motmp = new Mo($db);
if ($num > 0) if ($num > 0) {
{ while ($i < min($num, $limit)) {
while ($i < min($num, $limit))
{
$objp = $db->fetch_object($result); $objp = $db->fetch_object($result);
$motmp->id = $objp->rowid; $motmp->id = $objp->rowid;

View File

@ -40,7 +40,9 @@ $ref = GETPOST('ref', 'alpha');
$fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : '')); $fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : ''));
$fieldtype = (!empty($ref) ? 'ref' : 'rowid'); $fieldtype = (!empty($ref) ? 'ref' : 'rowid');
$socid = ''; $socid = '';
if (!empty($user->socid)) $socid = $user->socid; if (!empty($user->socid)) {
$socid = $user->socid;
}
$result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype);
// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
@ -53,12 +55,18 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST('sortfield', 'aZ09comma'); $sortfield = GETPOST('sortfield', 'aZ09comma');
$sortorder = GETPOST('sortorder', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if (!$sortorder) $sortorder = "DESC"; if (!$sortorder) {
if (!$sortfield) $sortfield = "p.datep"; $sortorder = "DESC";
}
if (!$sortfield) {
$sortfield = "p.datep";
}
$search_month = GETPOST('search_month', 'int'); $search_month = GETPOST('search_month', 'int');
$search_year = GETPOST('search_year', 'int'); $search_year = GETPOST('search_year', 'int');
@ -78,8 +86,7 @@ $societestatic = new Societe($db);
$form = new Form($db); $form = new Form($db);
$formother = new FormOther($db); $formother = new FormOther($db);
if ($id > 0 || !empty($ref)) if ($id > 0 || !empty($ref)) {
{
$product = new Product($db); $product = new Product($db);
$result = $product->fetch($id, $ref); $result = $product->fetch($id, $ref);
@ -87,12 +94,13 @@ if ($id > 0 || !empty($ref))
$parameters = array('id' => $id); $parameters = array('id' => $id);
$reshook = $hookmanager->executeHooks('doActions', $parameters, $product, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $product, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
llxHeader("", "", $langs->trans("CardProduct".$product->type)); llxHeader("", "", $langs->trans("CardProduct".$product->type));
if ($result > 0) if ($result > 0) {
{
$head = product_prepare_head($product); $head = product_prepare_head($product);
$titre = $langs->trans("CardProduct".$product->type); $titre = $langs->trans("CardProduct".$product->type);
$picto = ($product->type == Product::TYPE_SERVICE ? 'service' : 'product'); $picto = ($product->type == Product::TYPE_SERVICE ? 'service' : 'product');
@ -100,12 +108,16 @@ if ($id > 0 || !empty($ref))
$reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $product, $action); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $product, $action); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint; print $hookmanager->resPrint;
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
$linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; $linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
$shownav = 1; $shownav = 1;
if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) {
$shownav = 0;
}
dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref');
@ -124,30 +136,35 @@ if ($id > 0 || !empty($ref))
print dol_get_fiche_end(); print dol_get_fiche_end();
if ($user->rights->propale->lire) if ($user->rights->propale->lire) {
{
$sql = "SELECT DISTINCT s.nom as name, s.rowid as socid, p.rowid as propalid, p.ref, d.total_ht as amount,"; $sql = "SELECT DISTINCT s.nom as name, s.rowid as socid, p.rowid as propalid, p.ref, d.total_ht as amount,";
$sql .= " p.ref_client,"; $sql .= " p.ref_client,";
$sql .= "p.datep, p.fk_statut as statut, d.rowid, d.qty"; $sql .= "p.datep, p.fk_statut as statut, d.rowid, d.qty";
if (!$user->rights->societe->client->voir && !$socid) if (!$user->rights->societe->client->voir && !$socid) {
$sql .= ", sc.fk_soc, sc.fk_user "; $sql .= ", sc.fk_soc, sc.fk_user ";
}
$sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
$sql .= ",".MAIN_DB_PREFIX."propal as p"; $sql .= ",".MAIN_DB_PREFIX."propal as p";
$sql .= ", ".MAIN_DB_PREFIX."propaldet as d"; $sql .= ", ".MAIN_DB_PREFIX."propaldet as d";
if (!$user->rights->societe->client->voir && !$socid) if (!$user->rights->societe->client->voir && !$socid) {
$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
}
$sql .= " WHERE p.fk_soc = s.rowid"; $sql .= " WHERE p.fk_soc = s.rowid";
$sql .= " AND p.entity IN (".getEntity('propal').")"; $sql .= " AND p.entity IN (".getEntity('propal').")";
$sql .= " AND d.fk_propal = p.rowid"; $sql .= " AND d.fk_propal = p.rowid";
$sql .= " AND d.fk_product =".$product->id; $sql .= " AND d.fk_product =".$product->id;
if (!empty($search_month)) if (!empty($search_month)) {
$sql .= ' AND MONTH(p.datep) IN ('.$search_month.')'; $sql .= ' AND MONTH(p.datep) IN ('.$search_month.')';
if (!empty($search_year)) }
if (!empty($search_year)) {
$sql .= ' AND YEAR(p.datep) IN ('.$search_year.')'; $sql .= ' AND YEAR(p.datep) IN ('.$search_year.')';
if (!$user->rights->societe->client->voir && !$socid) }
if (!$user->rights->societe->client->voir && !$socid) {
$sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
if ($socid) }
if ($socid) {
$sql .= " AND p.fk_soc = ".$socid; $sql .= " AND p.fk_soc = ".$socid;
}
$sql .= $db->order($sortfield, $sortorder); $sql .= $db->order($sortfield, $sortorder);
// Calcul total qty and amount for global if full scan list // Calcul total qty and amount for global if full scan list
@ -156,8 +173,7 @@ if ($id > 0 || !empty($ref))
// Count total nb of records // Count total nb of records
$totalofrecords = ''; $totalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
{
$result = $db->query($sql); $result = $db->query($sql);
$totalofrecords = $db->num_rows($result); $totalofrecords = $db->num_rows($result);
} }
@ -165,24 +181,35 @@ if ($id > 0 || !empty($ref))
$sql .= $db->plimit($limit + 1, $offset); $sql .= $db->plimit($limit + 1, $offset);
$result = $db->query($sql); $result = $db->query($sql);
if ($result) if ($result) {
{
$num = $db->num_rows($result); $num = $db->num_rows($result);
if ($limit > 0 && $limit != $conf->liste_limit) $option .= '&limit='.urlencode($limit); if ($limit > 0 && $limit != $conf->liste_limit) {
if (!empty($id)) $option .= '&id='.$product->id; $option .= '&limit='.urlencode($limit);
if (!empty($search_month)) $option .= '&search_month='.urlencode($search_month); }
if (!empty($search_year)) $option .= '&search_year='.urlencode($search_year); if (!empty($id)) {
$option .= '&id='.$product->id;
}
if (!empty($search_month)) {
$option .= '&search_month='.urlencode($search_month);
}
if (!empty($search_year)) {
$option .= '&search_year='.urlencode($search_year);
}
print '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$product->id.'" name="search_form">'."\n"; print '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$product->id.'" name="search_form">'."\n";
if (!empty($sortfield)) if (!empty($sortfield)) {
print '<input type="hidden" name="sortfield" value="'.$sortfield.'"/>'; print '<input type="hidden" name="sortfield" value="'.$sortfield.'"/>';
if (!empty($sortorder)) }
if (!empty($sortorder)) {
print '<input type="hidden" name="sortorder" value="'.$sortorder.'"/>'; print '<input type="hidden" name="sortorder" value="'.$sortorder.'"/>';
}
print_barre_liste($langs->trans("Proposals"), $page, $_SERVER["PHP_SELF"], $option, $sortfield, $sortorder, '', $num, $totalofrecords, '', 0, '', '', $limit, 0, 0, 1); print_barre_liste($langs->trans("Proposals"), $page, $_SERVER["PHP_SELF"], $option, $sortfield, $sortorder, '', $num, $totalofrecords, '', 0, '', '', $limit, 0, 0, 1);
if (!empty($page)) $option .= '&page='.urlencode($page); if (!empty($page)) {
$option .= '&page='.urlencode($page);
}
print '<div class="liste_titre liste_titre_bydiv centpercent">'; print '<div class="liste_titre liste_titre_bydiv centpercent">';
print '<div class="divsearchfield">'; print '<div class="divsearchfield">';
@ -208,10 +235,8 @@ if ($id > 0 || !empty($ref))
print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "p.fk_statut", "", $option, 'align="right"', $sortfield, $sortorder); print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "p.fk_statut", "", $option, 'align="right"', $sortfield, $sortorder);
print "</tr>\n"; print "</tr>\n";
if ($num > 0) if ($num > 0) {
{ while ($i < min($num, $limit)) {
while ($i < min($num, $limit))
{
$objp = $db->fetch_object($result); $objp = $db->fetch_object($result);
$total_ht += $objp->amount; $total_ht += $objp->amount;
@ -238,8 +263,11 @@ if ($id > 0 || !empty($ref))
} }
print '<tr class="liste_total">'; print '<tr class="liste_total">';
if ($num < $limit) print '<td class="left">'.$langs->trans("Total").'</td>'; if ($num < $limit) {
else print '<td class="left">'.$langs->trans("Totalforthispage").'</td>'; print '<td class="left">'.$langs->trans("Total").'</td>';
} else {
print '<td class="left">'.$langs->trans("Totalforthispage").'</td>';
}
print '<td colspan="2"></td>'; print '<td colspan="2"></td>';
print '<td class="center">'.$total_qty.'</td>'; print '<td class="center">'.$total_qty.'</td>';
print '<td align="right">'.price($total_ht).'</td>'; print '<td align="right">'.price($total_ht).'</td>';

View File

@ -40,7 +40,9 @@ $ref = GETPOST('ref', 'alpha');
$fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : '')); $fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : ''));
$fieldtype = (!empty($ref) ? 'ref' : 'rowid'); $fieldtype = (!empty($ref) ? 'ref' : 'rowid');
$socid = ''; $socid = '';
if (!empty($user->socid)) $socid = $user->socid; if (!empty($user->socid)) {
$socid = $user->socid;
}
$result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype);
// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
@ -53,12 +55,18 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST('sortfield', 'aZ09comma'); $sortfield = GETPOST('sortfield', 'aZ09comma');
$sortorder = GETPOST('sortorder', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if (!$sortorder) $sortorder = "DESC"; if (!$sortorder) {
if (!$sortfield) $sortfield = "p.date_valid"; $sortorder = "DESC";
}
if (!$sortfield) {
$sortfield = "p.date_valid";
}
$search_month = GETPOST('search_month', 'int'); $search_month = GETPOST('search_month', 'int');
$search_year = GETPOST('search_year', 'int'); $search_year = GETPOST('search_year', 'int');
@ -78,8 +86,7 @@ $societestatic = new Societe($db);
$form = new Form($db); $form = new Form($db);
$formother = new FormOther($db); $formother = new FormOther($db);
if ($id > 0 || !empty($ref)) if ($id > 0 || !empty($ref)) {
{
$product = new Product($db); $product = new Product($db);
$result = $product->fetch($id, $ref); $result = $product->fetch($id, $ref);
@ -87,12 +94,13 @@ if ($id > 0 || !empty($ref))
$parameters = array('id' => $id); $parameters = array('id' => $id);
$reshook = $hookmanager->executeHooks('doActions', $parameters, $product, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $product, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
llxHeader("", "", $langs->trans("CardProduct".$product->type)); llxHeader("", "", $langs->trans("CardProduct".$product->type));
if ($result > 0) if ($result > 0) {
{
$head = product_prepare_head($product); $head = product_prepare_head($product);
$titre = $langs->trans("CardProduct".$product->type); $titre = $langs->trans("CardProduct".$product->type);
$picto = ($product->type == Product::TYPE_SERVICE ? 'service' : 'product'); $picto = ($product->type == Product::TYPE_SERVICE ? 'service' : 'product');
@ -100,12 +108,16 @@ if ($id > 0 || !empty($ref))
$reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $product, $action); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $product, $action); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint; print $hookmanager->resPrint;
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
$linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; $linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
$shownav = 1; $shownav = 1;
if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) {
$shownav = 0;
}
dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref');
@ -124,30 +136,35 @@ if ($id > 0 || !empty($ref))
print dol_get_fiche_end(); print dol_get_fiche_end();
if ($user->rights->propale->lire) if ($user->rights->propale->lire) {
{
$sql = "SELECT DISTINCT s.nom as name, s.rowid as socid, p.rowid as propalid, p.ref, d.total_ht as amount,"; $sql = "SELECT DISTINCT s.nom as name, s.rowid as socid, p.rowid as propalid, p.ref, d.total_ht as amount,";
//$sql .= " p.ref_supplier,"; //$sql .= " p.ref_supplier,";
$sql .= "p.date_valid, p.fk_statut as statut, d.rowid, d.qty"; $sql .= "p.date_valid, p.fk_statut as statut, d.rowid, d.qty";
if (!$user->rights->societe->client->voir && !$socid) if (!$user->rights->societe->client->voir && !$socid) {
$sql .= ", sc.fk_soc, sc.fk_user "; $sql .= ", sc.fk_soc, sc.fk_user ";
}
$sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
$sql .= ",".MAIN_DB_PREFIX."supplier_proposal as p"; $sql .= ",".MAIN_DB_PREFIX."supplier_proposal as p";
$sql .= ", ".MAIN_DB_PREFIX."supplier_proposaldet as d"; $sql .= ", ".MAIN_DB_PREFIX."supplier_proposaldet as d";
if (!$user->rights->societe->client->voir && !$socid) if (!$user->rights->societe->client->voir && !$socid) {
$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
}
$sql .= " WHERE p.fk_soc = s.rowid"; $sql .= " WHERE p.fk_soc = s.rowid";
$sql .= " AND p.entity IN (".getEntity('supplier_proposal').")"; $sql .= " AND p.entity IN (".getEntity('supplier_proposal').")";
$sql .= " AND d.fk_supplier_proposal = p.rowid"; $sql .= " AND d.fk_supplier_proposal = p.rowid";
$sql .= " AND d.fk_product =".$product->id; $sql .= " AND d.fk_product =".$product->id;
if (!empty($search_month)) if (!empty($search_month)) {
$sql .= ' AND MONTH(p.datep) IN ('.$search_month.')'; $sql .= ' AND MONTH(p.datep) IN ('.$search_month.')';
if (!empty($search_year)) }
if (!empty($search_year)) {
$sql .= ' AND YEAR(p.datep) IN ('.$search_year.')'; $sql .= ' AND YEAR(p.datep) IN ('.$search_year.')';
if (!$user->rights->societe->client->voir && !$socid) }
if (!$user->rights->societe->client->voir && !$socid) {
$sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
if ($socid) }
if ($socid) {
$sql .= " AND p.fk_soc = ".$socid; $sql .= " AND p.fk_soc = ".$socid;
}
$sql .= $db->order($sortfield, $sortorder); $sql .= $db->order($sortfield, $sortorder);
// Calcul total qty and amount for global if full scan list // Calcul total qty and amount for global if full scan list
@ -156,8 +173,7 @@ if ($id > 0 || !empty($ref))
// Count total nb of records // Count total nb of records
$totalofrecords = ''; $totalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
{
$result = $db->query($sql); $result = $db->query($sql);
$totalofrecords = $db->num_rows($result); $totalofrecords = $db->num_rows($result);
} }
@ -165,24 +181,35 @@ if ($id > 0 || !empty($ref))
$sql .= $db->plimit($limit + 1, $offset); $sql .= $db->plimit($limit + 1, $offset);
$result = $db->query($sql); $result = $db->query($sql);
if ($result) if ($result) {
{
$num = $db->num_rows($result); $num = $db->num_rows($result);
if ($limit > 0 && $limit != $conf->liste_limit) $option .= '&limit='.urlencode($limit); if ($limit > 0 && $limit != $conf->liste_limit) {
if (!empty($id)) $option .= '&id='.$product->id; $option .= '&limit='.urlencode($limit);
if (!empty($search_month)) $option .= '&search_month='.urlencode($search_month); }
if (!empty($search_year)) $option .= '&search_year='.urlencode($search_year); if (!empty($id)) {
$option .= '&id='.$product->id;
}
if (!empty($search_month)) {
$option .= '&search_month='.urlencode($search_month);
}
if (!empty($search_year)) {
$option .= '&search_year='.urlencode($search_year);
}
print '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$product->id.'" name="search_form">'."\n"; print '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$product->id.'" name="search_form">'."\n";
if (!empty($sortfield)) if (!empty($sortfield)) {
print '<input type="hidden" name="sortfield" value="'.$sortfield.'"/>'; print '<input type="hidden" name="sortfield" value="'.$sortfield.'"/>';
if (!empty($sortorder)) }
if (!empty($sortorder)) {
print '<input type="hidden" name="sortorder" value="'.$sortorder.'"/>'; print '<input type="hidden" name="sortorder" value="'.$sortorder.'"/>';
}
print_barre_liste($langs->trans("Proposals"), $page, $_SERVER["PHP_SELF"], $option, $sortfield, $sortorder, '', $num, $totalofrecords, '', 0, '', '', $limit, 0, 0, 1); print_barre_liste($langs->trans("Proposals"), $page, $_SERVER["PHP_SELF"], $option, $sortfield, $sortorder, '', $num, $totalofrecords, '', 0, '', '', $limit, 0, 0, 1);
if (!empty($page)) $option .= '&page='.urlencode($page); if (!empty($page)) {
$option .= '&page='.urlencode($page);
}
print '<div class="liste_titre liste_titre_bydiv centpercent">'; print '<div class="liste_titre liste_titre_bydiv centpercent">';
print '<div class="divsearchfield">'; print '<div class="divsearchfield">';
@ -208,10 +235,8 @@ if ($id > 0 || !empty($ref))
print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "p.fk_statut", "", $option, 'align="right"', $sortfield, $sortorder); print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "p.fk_statut", "", $option, 'align="right"', $sortfield, $sortorder);
print "</tr>\n"; print "</tr>\n";
if ($num > 0) if ($num > 0) {
{ while ($i < min($num, $limit)) {
while ($i < min($num, $limit))
{
$objp = $db->fetch_object($result); $objp = $db->fetch_object($result);
$total_ht += $objp->amount; $total_ht += $objp->amount;
@ -237,8 +262,11 @@ if ($id > 0 || !empty($ref))
} }
print '<tr class="liste_total">'; print '<tr class="liste_total">';
if ($num < $limit) print '<td class="left">'.$langs->trans("Total").'</td>'; if ($num < $limit) {
else print '<td class="left">'.$langs->trans("Totalforthispage").'</td>'; print '<td class="left">'.$langs->trans("Total").'</td>';
} else {
print '<td class="left">'.$langs->trans("Totalforthispage").'</td>';
}
print '<td colspan="2"></td>'; print '<td colspan="2"></td>';
print '<td class="center">'.$total_qty.'</td>'; print '<td class="center">'.$total_qty.'</td>';
print '<td align="right">'.price($total_ht).'</td>'; print '<td align="right">'.price($total_ht).'</td>';

View File

@ -47,8 +47,12 @@ $ref = GETPOST('ref', 'alpha');
$sortfield = GETPOST("sortfield", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha');
if (!$sortfield) $sortfield = "p.ref"; if (!$sortfield) {
if (!$sortorder) $sortorder = "DESC"; $sortfield = "p.ref";
}
if (!$sortorder) {
$sortorder = "DESC";
}
$backtopage = GETPOST('backtopage', 'alpha'); $backtopage = GETPOST('backtopage', 'alpha');
@ -87,12 +91,12 @@ $usercandelete = (($user->rights->stock->supprimer));
$parameters = array('id'=>$id, 'ref'=>$ref); $parameters = array('id'=>$id, 'ref'=>$ref);
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
if (empty($reshook)) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
{ }
if (empty($reshook)) {
// Ajout entrepot // Ajout entrepot
if ($action == 'add' && $user->rights->stock->creer) if ($action == 'add' && $user->rights->stock->creer) {
{
$object->ref = (string) GETPOST("ref", "alpha"); $object->ref = (string) GETPOST("ref", "alpha");
$object->fk_parent = (int) GETPOST("fk_parent", "int"); $object->fk_parent = (int) GETPOST("fk_parent", "int");
$object->label = (string) GETPOST("libelle", "alpha"); $object->label = (string) GETPOST("libelle", "alpha");
@ -140,12 +144,10 @@ if (empty($reshook))
} }
// Delete warehouse // Delete warehouse
if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->stock->supprimer) if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->stock->supprimer) {
{
$object->fetch(GETPOST('id', 'int')); $object->fetch(GETPOST('id', 'int'));
$result = $object->delete($user); $result = $object->delete($user);
if ($result > 0) if ($result > 0) {
{
setEventMessages($langs->trans("RecordDeleted"), null, 'mesgs'); setEventMessages($langs->trans("RecordDeleted"), null, 'mesgs');
header("Location: ".DOL_URL_ROOT.'/product/stock/list.php?restore_lastsearch_values=1'); header("Location: ".DOL_URL_ROOT.'/product/stock/list.php?restore_lastsearch_values=1');
exit; exit;
@ -156,10 +158,8 @@ if (empty($reshook))
} }
// Modification entrepot // Modification entrepot
if ($action == 'update' && $cancel <> $langs->trans("Cancel")) if ($action == 'update' && $cancel <> $langs->trans("Cancel")) {
{ if ($object->fetch($id)) {
if ($object->fetch($id))
{
$object->label = GETPOST("libelle"); $object->label = GETPOST("libelle");
$object->fk_parent = GETPOST("fk_parent"); $object->fk_parent = GETPOST("fk_parent");
$object->description = GETPOST("desc"); $object->description = GETPOST("desc");
@ -174,11 +174,15 @@ if (empty($reshook))
// Fill array 'array_options' with data from add form // Fill array 'array_options' with data from add form
$ret = $extrafields->setOptionalsFromPost(null, $object); $ret = $extrafields->setOptionalsFromPost(null, $object);
if ($ret < 0) $error++; if ($ret < 0) {
$error++;
}
if (!$error) { if (!$error) {
$ret = $object->update($id, $user); $ret = $object->update($id, $user);
if ($ret < 0) $error++; if ($ret < 0) {
$error++;
}
} }
if ($error) { if ($error) {
@ -198,7 +202,9 @@ if (empty($reshook))
// Fill array 'array_options' with data from update form // Fill array 'array_options' with data from update form
$ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml')); $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml'));
if ($ret < 0) $error++; if ($ret < 0) {
$error++;
}
if (!$error) { if (!$error) {
$result = $object->insertExtraFields(); $result = $object->insertExtraFields();
if ($result < 0) { if ($result < 0) {
@ -206,11 +212,12 @@ if (empty($reshook))
$error++; $error++;
} }
} }
if ($error) $action = 'edit_extras'; if ($error) {
$action = 'edit_extras';
}
} }
if ($cancel == $langs->trans("Cancel")) if ($cancel == $langs->trans("Cancel")) {
{
$action = ''; $action = '';
} }
@ -236,8 +243,7 @@ $help_url = 'EN:Module_Stocks_En|FR:Module_Stock|ES:M&oacute;dulo_Stocks';
llxHeader("", $langs->trans("WarehouseCard"), $help_url); llxHeader("", $langs->trans("WarehouseCard"), $help_url);
if ($action == 'create') if ($action == 'create') {
{
print load_fiche_titre($langs->trans("NewWarehouse"), '', 'stock'); print load_fiche_titre($langs->trans("NewWarehouse"), '', 'stock');
dol_set_focus('input[name="libelle"]'); dol_set_focus('input[name="libelle"]');
@ -285,7 +291,9 @@ if ($action == 'create')
print '<tr><td>'.$langs->trans('Country').'</td><td>'; print '<tr><td>'.$langs->trans('Country').'</td><td>';
print img_picto('', 'globe-americas', 'class="paddingright"'); print img_picto('', 'globe-americas', 'class="paddingright"');
print $form->select_country((!empty($object->country_id) ? $object->country_id : $mysoc->country_code), 'country_id'); print $form->select_country((!empty($object->country_id) ? $object->country_id : $mysoc->country_code), 'country_id');
if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); if ($user->admin) {
print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
}
print '</td></tr>'; print '</td></tr>';
// Phone / Fax // Phone / Fax
@ -300,10 +308,8 @@ if ($action == 'create')
// Status // Status
print '<tr><td>'.$langs->trans("Status").'</td><td>'; print '<tr><td>'.$langs->trans("Status").'</td><td>';
print '<select name="statut" class="flat">'; print '<select name="statut" class="flat">';
foreach ($object->statuts as $key => $value) foreach ($object->statuts as $key => $value) {
{ if ($key == 1) {
if ($key == 1)
{
print '<option value="'.$key.'" selected>'.$langs->trans($value).'</option>'; print '<option value="'.$key.'" selected>'.$langs->trans($value).'</option>';
} else { } else {
print '<option value="'.$key.'">'.$langs->trans($value).'</option>'; print '<option value="'.$key.'">'.$langs->trans($value).'</option>';
@ -335,12 +341,10 @@ if ($action == 'create')
print '</form>'; print '</form>';
} else { } else {
$id = GETPOST("id", 'int'); $id = GETPOST("id", 'int');
if ($id > 0 || $ref) if ($id > 0 || $ref) {
{
$object = new Entrepot($db); $object = new Entrepot($db);
$result = $object->fetch($id, $ref); $result = $object->fetch($id, $ref);
if ($result <= 0) if ($result <= 0) {
{
print 'No record found'; print 'No record found';
exit; exit;
} }
@ -348,8 +352,7 @@ if ($action == 'create')
/* /*
* Affichage fiche * Affichage fiche
*/ */
if ($action <> 'edit' && $action <> 're-edit') if ($action <> 'edit' && $action <> 're-edit') {
{
$head = stock_prepare_head($object); $head = stock_prepare_head($object);
print dol_get_fiche_head($head, 'card', $langs->trans("Warehouse"), -1, 'stock'); print dol_get_fiche_head($head, 'card', $langs->trans("Warehouse"), -1, 'stock');
@ -357,16 +360,18 @@ if ($action == 'create')
$formconfirm = ''; $formconfirm = '';
// Confirm delete warehouse // Confirm delete warehouse
if ($action == 'delete') if ($action == 'delete') {
{
$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("DeleteAWarehouse"), $langs->trans("ConfirmDeleteWarehouse", $object->label), "confirm_delete", '', 0, 2); $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("DeleteAWarehouse"), $langs->trans("ConfirmDeleteWarehouse", $object->label), "confirm_delete", '', 0, 2);
} }
// Call Hook formConfirm // Call Hook formConfirm
$parameters = array('formConfirm' => $formconfirm); $parameters = array('formConfirm' => $formconfirm);
$reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; if (empty($reshook)) {
elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; $formconfirm .= $hookmanager->resPrint;
} elseif ($reshook > 0) {
$formconfirm = $hookmanager->resPrint;
}
// Print form confirm // Print form confirm
print $formconfirm; print $formconfirm;
@ -379,7 +384,9 @@ if ($action == 'create')
$morehtmlref .= '</div>'; $morehtmlref .= '</div>';
$shownav = 1; $shownav = 1;
if ($user->socid && !in_array('stock', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; if ($user->socid && !in_array('stock', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) {
$shownav = 0;
}
dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref', 'ref', $morehtmlref); dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref', 'ref', $morehtmlref);
@ -481,21 +488,17 @@ if ($action == 'create')
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
if (empty($reshook)) if (empty($reshook)) {
{ if (empty($action)) {
if (empty($action))
{
if ($user->rights->stock->creer) { if ($user->rights->stock->creer) {
print '<a class="butAction" href="card.php?action=edit&token='.newToken().'&id='.$object->id.'">'.$langs->trans("Modify").'</a>'; print '<a class="butAction" href="card.php?action=edit&token='.newToken().'&id='.$object->id.'">'.$langs->trans("Modify").'</a>';
} } else {
else {
print '<a class="butActionRefused classfortooltip" href="#">'.$langs->trans("Modify").'</a>'; print '<a class="butActionRefused classfortooltip" href="#">'.$langs->trans("Modify").'</a>';
} }
if ($user->rights->stock->supprimer) { if ($user->rights->stock->supprimer) {
print '<a class="butActionDelete" href="card.php?action=delete&token='.newToken().'&id='.$object->id.'">'.$langs->trans("Delete").'</a>'; print '<a class="butActionDelete" href="card.php?action=delete&token='.newToken().'&id='.$object->id.'">'.$langs->trans("Delete").'</a>';
} } else {
else {
print '<a class="butActionRefused classfortooltip" href="#">'.$langs->trans("Delete").'</a>'; print '<a class="butActionRefused classfortooltip" href="#">'.$langs->trans("Delete").'</a>';
} }
} }
@ -516,7 +519,9 @@ if ($action == 'create')
print_liste_field_titre("Product", "", "p.ref", "&amp;id=".$id, "", "", $sortfield, $sortorder); print_liste_field_titre("Product", "", "p.ref", "&amp;id=".$id, "", "", $sortfield, $sortorder);
print_liste_field_titre("Label", "", "p.label", "&amp;id=".$id, "", "", $sortfield, $sortorder); print_liste_field_titre("Label", "", "p.label", "&amp;id=".$id, "", "", $sortfield, $sortorder);
print_liste_field_titre("Units", "", "ps.reel", "&amp;id=".$id, "", '', $sortfield, $sortorder, 'right '); print_liste_field_titre("Units", "", "ps.reel", "&amp;id=".$id, "", '', $sortfield, $sortorder, 'right ');
if (!empty($conf->global->PRODUCT_USE_UNITS)) print_liste_field_titre("Unit", "", "p.fk_unit", "&amp;id=".$id, "", 'align="left"', $sortfield, $sortorder); if (!empty($conf->global->PRODUCT_USE_UNITS)) {
print_liste_field_titre("Unit", "", "p.fk_unit", "&amp;id=".$id, "", 'align="left"', $sortfield, $sortorder);
}
print_liste_field_titre("AverageUnitPricePMPShort", "", "p.pmp", "&amp;id=".$id, "", '', $sortfield, $sortorder, 'right '); print_liste_field_titre("AverageUnitPricePMPShort", "", "p.pmp", "&amp;id=".$id, "", '', $sortfield, $sortorder, 'right ');
print_liste_field_titre("EstimatedStockValueShort", "", "", "&amp;id=".$id, "", '', $sortfield, $sortorder, 'right '); print_liste_field_titre("EstimatedStockValueShort", "", "", "&amp;id=".$id, "", '', $sortfield, $sortorder, 'right ');
if (empty($conf->global->PRODUIT_MULTIPRICES)) { if (empty($conf->global->PRODUIT_MULTIPRICES)) {
@ -538,7 +543,9 @@ if ($action == 'create')
$sql = "SELECT p.rowid as rowid, p.ref, p.label as produit, p.tobatch, p.fk_product_type as type, p.pmp as ppmp, p.price, p.price_ttc, p.entity,"; $sql = "SELECT p.rowid as rowid, p.ref, p.label as produit, p.tobatch, p.fk_product_type as type, p.pmp as ppmp, p.price, p.price_ttc, p.entity,";
$sql .= " ps.reel as value"; $sql .= " ps.reel as value";
if (!empty($conf->global->PRODUCT_USE_UNITS)) $sql .= ",fk_unit"; if (!empty($conf->global->PRODUCT_USE_UNITS)) {
$sql .= ",fk_unit";
}
$sql .= " FROM ".MAIN_DB_PREFIX."product_stock as ps, ".MAIN_DB_PREFIX."product as p"; $sql .= " FROM ".MAIN_DB_PREFIX."product_stock as ps, ".MAIN_DB_PREFIX."product as p";
$sql .= " WHERE ps.fk_product = p.rowid"; $sql .= " WHERE ps.fk_product = p.rowid";
$sql .= " AND ps.reel <> 0"; // We do not show if stock is 0 (no product in this warehouse) $sql .= " AND ps.reel <> 0"; // We do not show if stock is 0 (no product in this warehouse)
@ -547,17 +554,14 @@ if ($action == 'create')
dol_syslog('List products', LOG_DEBUG); dol_syslog('List products', LOG_DEBUG);
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
$i = 0; $i = 0;
while ($i < $num) while ($i < $num) {
{
$objp = $db->fetch_object($resql); $objp = $db->fetch_object($resql);
// Multilangs // Multilangs
if (!empty($conf->global->MAIN_MULTILANGS)) // si l'option est active if (!empty($conf->global->MAIN_MULTILANGS)) { // si l'option est active
{
$sql = "SELECT label"; $sql = "SELECT label";
$sql .= " FROM ".MAIN_DB_PREFIX."product_lang"; $sql .= " FROM ".MAIN_DB_PREFIX."product_lang";
$sql .= " WHERE fk_product=".$objp->rowid; $sql .= " WHERE fk_product=".$objp->rowid;
@ -565,10 +569,11 @@ if ($action == 'create')
$sql .= " LIMIT 1"; $sql .= " LIMIT 1";
$result = $db->query($sql); $result = $db->query($sql);
if ($result) if ($result) {
{
$objtp = $db->fetch_object($result); $objtp = $db->fetch_object($result);
if ($objtp->label != '') $objp->produit = $objtp->label; if ($objtp->label != '') {
$objp->produit = $objtp->label;
}
} }
} }
@ -598,7 +603,9 @@ if ($action == 'create')
if (!empty($conf->global->PRODUCT_USE_UNITS)) { if (!empty($conf->global->PRODUCT_USE_UNITS)) {
// Units // Units
print '<td align="left">'; print '<td align="left">';
if (is_null($productstatic->fk_unit))$productstatic->fk_unit = 1; if (is_null($productstatic->fk_unit)) {
$productstatic->fk_unit = 1;
}
print $langs->trans($productstatic->getLabelOfUnit()); print $langs->trans($productstatic->getLabelOfUnit());
print '</td>'; print '</td>';
} }
@ -610,8 +617,7 @@ if ($action == 'create')
$totalvalue += price2num($objp->ppmp * $objp->value, 'MT'); $totalvalue += price2num($objp->ppmp * $objp->value, 'MT');
// Price sell min // Price sell min
if (empty($conf->global->PRODUIT_MULTIPRICES)) if (empty($conf->global->PRODUIT_MULTIPRICES)) {
{
$pricemin = $objp->price; $pricemin = $objp->price;
print '<td class="right">'; print '<td class="right">';
print price(price2num($pricemin, 'MU'), 1); print price(price2num($pricemin, 'MU'), 1);
@ -623,22 +629,23 @@ if ($action == 'create')
} }
$totalvaluesell += price2num($pricemin * $objp->value, 'MT'); $totalvaluesell += price2num($pricemin * $objp->value, 'MT');
if ($user->rights->stock->mouvement->creer) if ($user->rights->stock->mouvement->creer) {
{
print '<td class="center"><a href="'.DOL_URL_ROOT.'/product/stock/product.php?dwid='.$object->id.'&id='.$objp->rowid.'&action=transfert&backtopage='.urlencode($_SERVER["PHP_SELF"].'?id='.$id).'">'; print '<td class="center"><a href="'.DOL_URL_ROOT.'/product/stock/product.php?dwid='.$object->id.'&id='.$objp->rowid.'&action=transfert&backtopage='.urlencode($_SERVER["PHP_SELF"].'?id='.$id).'">';
print img_picto($langs->trans("StockMovement"), 'uparrow.png', 'class="hideonsmartphone"').' '.$langs->trans("StockMovement"); print img_picto($langs->trans("StockMovement"), 'uparrow.png', 'class="hideonsmartphone"').' '.$langs->trans("StockMovement");
print "</a></td>"; print "</a></td>";
} }
if ($user->rights->stock->creer) if ($user->rights->stock->creer) {
{
print '<td class="center"><a href="'.DOL_URL_ROOT.'/product/stock/product.php?dwid='.$object->id.'&id='.$objp->rowid.'&action=correction&backtopage='.urlencode($_SERVER["PHP_SELF"].'?id='.$id).'">'; print '<td class="center"><a href="'.DOL_URL_ROOT.'/product/stock/product.php?dwid='.$object->id.'&id='.$objp->rowid.'&action=correction&backtopage='.urlencode($_SERVER["PHP_SELF"].'?id='.$id).'">';
print $langs->trans("StockCorrection"); print $langs->trans("StockCorrection");
print "</a></td>"; print "</a></td>";
} }
if (!empty($conf->global->PRODUCT_USE_UNITS)) { if (!empty($conf->global->PRODUCT_USE_UNITS)) {
if ($i == 0) $units = $productstatic->fk_unit; if ($i == 0) {
elseif ($productstatic->fk_unit != $units) $sameunits = false; $units = $productstatic->fk_unit;
} elseif ($productstatic->fk_unit != $units) {
$sameunits = false;
}
} }
print "</tr>"; print "</tr>";
$i++; $i++;
@ -648,14 +655,17 @@ if ($action == 'create')
print '<tr class="liste_total"><td class="liste_total" colspan="2">'.$langs->trans("Total").'</td>'; print '<tr class="liste_total"><td class="liste_total" colspan="2">'.$langs->trans("Total").'</td>';
print '<td class="liste_total right">'; print '<td class="liste_total right">';
$valtoshow = price2num($totalunit, 'MS'); $valtoshow = price2num($totalunit, 'MS');
if (empty($conf->global->PRODUCT_USE_UNITS) || $sameunits) print empty($valtoshow) ? '0' : $valtoshow; if (empty($conf->global->PRODUCT_USE_UNITS) || $sameunits) {
print empty($valtoshow) ? '0' : $valtoshow;
}
print '</td>'; print '</td>';
print '<td class="liste_total">'; print '<td class="liste_total">';
if (empty($conf->global->PRODUCT_USE_UNITS) && $sameunits) print $langs->trans($productstatic->getLabelOfUnit()); if (empty($conf->global->PRODUCT_USE_UNITS) && $sameunits) {
print $langs->trans($productstatic->getLabelOfUnit());
}
print '</td>'; print '</td>';
print '<td class="liste_total right">'.price(price2num($totalvalue, 'MT')).'</td>'; print '<td class="liste_total right">'.price(price2num($totalvalue, 'MT')).'</td>';
if (empty($conf->global->PRODUIT_MULTIPRICES)) if (empty($conf->global->PRODUIT_MULTIPRICES)) {
{
print '<td class="liste_total">&nbsp;</td>'; print '<td class="liste_total">&nbsp;</td>';
print '<td class="liste_total right">'.price(price2num($totalvaluesell, 'MT')).'</td>'; print '<td class="liste_total right">'.price(price2num($totalvaluesell, 'MT')).'</td>';
} }
@ -672,8 +682,7 @@ if ($action == 'create')
/* /*
* Edition fiche * Edition fiche
*/ */
if ($action == 'edit' || $action == 're-edit') if ($action == 'edit' || $action == 're-edit') {
{
$langs->trans("WarehouseEdit"); $langs->trans("WarehouseEdit");
print '<form action="card.php" method="POST">'; print '<form action="card.php" method="POST">';
@ -721,7 +730,9 @@ if ($action == 'create')
print '<tr><td>'.$langs->trans('Country').'</td><td>'; print '<tr><td>'.$langs->trans('Country').'</td><td>';
print img_picto('', 'globe-americas', 'class="paddingright"'); print img_picto('', 'globe-americas', 'class="paddingright"');
print $form->select_country($object->country_id ? $object->country_id : $mysoc->country_code, 'country_id'); print $form->select_country($object->country_id ? $object->country_id : $mysoc->country_code, 'country_id');
if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); if ($user->admin) {
print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
}
print '</td></tr>'; print '</td></tr>';
// Phone / Fax // Phone / Fax
@ -735,10 +746,8 @@ if ($action == 'create')
// Status // Status
print '<tr><td>'.$langs->trans("Status").'</td><td>'; print '<tr><td>'.$langs->trans("Status").'</td><td>';
print '<select name="statut" class="flat">'; print '<select name="statut" class="flat">';
foreach ($object->statuts as $key => $value) foreach ($object->statuts as $key => $value) {
{ if ($key == $object->statut) {
if ($key == $object->statut)
{
print '<option value="'.$key.'" selected>'.$langs->trans($value).'</option>'; print '<option value="'.$key.'" selected>'.$langs->trans($value).'</option>';
} else { } else {
print '<option value="'.$key.'">'.$langs->trans($value).'</option>'; print '<option value="'.$key.'">'.$langs->trans($value).'</option>';
@ -751,14 +760,12 @@ if ($action == 'create')
$parameters = array('colspan' => ' colspan="3"', 'cols' => '3'); $parameters = array('colspan' => ' colspan="3"', 'cols' => '3');
$reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $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 $hookmanager->resPrint;
if (empty($reshook)) if (empty($reshook)) {
{
print $object->showOptionals($extrafields, 'edit', $parameters); print $object->showOptionals($extrafields, 'edit', $parameters);
} }
// Tags-Categories // Tags-Categories
if ($conf->categorie->enabled) if ($conf->categorie->enabled) {
{
print '<tr><td class="tdtop">'.$langs->trans("Categories").'</td><td colspan="3">'; print '<tr><td class="tdtop">'.$langs->trans("Categories").'</td><td colspan="3">';
$cate_arbo = $form->select_all_categories(Categorie::TYPE_WAREHOUSE, '', 'parent', 64, 0, 1); $cate_arbo = $form->select_all_categories(Categorie::TYPE_WAREHOUSE, '', 'parent', 64, 0, 1);
$c = new Categorie($db); $c = new Categorie($db);
@ -792,8 +799,7 @@ if ($action == 'create')
$modulepart = 'stock'; $modulepart = 'stock';
if ($action != 'create' && $action != 'edit' && $action != 'delete') if ($action != 'create' && $action != 'edit' && $action != 'delete') {
{
print '<br>'; print '<br>';
print '<div class="fichecenter"><div class="fichehalfleft">'; print '<div class="fichecenter"><div class="fichehalfleft">';
print '<a name="builddoc"></a>'; // ancre print '<a name="builddoc"></a>'; // ancre

View File

@ -31,7 +31,7 @@ class StockMovements extends DolibarrApi
/** /**
* @var array $FIELDS Mandatory fields, checked when create and update object * @var array $FIELDS Mandatory fields, checked when create and update object
*/ */
static $FIELDS = array( public static $FIELDS = array(
'product_id', 'product_id',
'warehouse_id', 'warehouse_id',
'qty' 'qty'
@ -108,10 +108,8 @@ class StockMovements extends DolibarrApi
//$sql.= ' WHERE t.entity IN ('.getEntity('stock').')'; //$sql.= ' WHERE t.entity IN ('.getEntity('stock').')';
$sql .= ' WHERE 1 = 1'; $sql .= ' WHERE 1 = 1';
// Add sql filters // Add sql filters
if ($sqlfilters) if ($sqlfilters) {
{ if (!DolibarrApi::_checkFilters($sqlfilters)) {
if (!DolibarrApi::_checkFilters($sqlfilters))
{
throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
} }
$regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
@ -120,8 +118,7 @@ class StockMovements extends DolibarrApi
$sql .= $this->db->order($sortfield, $sortorder); $sql .= $this->db->order($sortfield, $sortorder);
if ($limit) { if ($limit) {
if ($page < 0) if ($page < 0) {
{
$page = 0; $page = 0;
} }
$offset = $limit * $page; $offset = $limit * $page;
@ -130,13 +127,11 @@ class StockMovements extends DolibarrApi
} }
$result = $this->db->query($sql); $result = $this->db->query($sql);
if ($result) if ($result) {
{
$i = 0; $i = 0;
$num = $this->db->num_rows($result); $num = $this->db->num_rows($result);
$min = min($num, ($limit <= 0 ? $num : $limit)); $min = min($num, ($limit <= 0 ? $num : $limit));
while ($i < $min) while ($i < $min) {
{
$obj = $this->db->fetch_object($result); $obj = $this->db->fetch_object($result);
$stockmovement_static = new MouvementStock($this->db); $stockmovement_static = new MouvementStock($this->db);
if ($stockmovement_static->fetch($obj->rowid)) { if ($stockmovement_static->fetch($obj->rowid)) {
@ -196,7 +191,9 @@ class StockMovements extends DolibarrApi
if ($this->stockmovement->_create(DolibarrApiAccess::$user, $product_id, $warehouse_id, $qty, $type, $price, $movementlabel, $movementcode, '', $eatBy, $sellBy, $lot) <= 0) { if ($this->stockmovement->_create(DolibarrApiAccess::$user, $product_id, $warehouse_id, $qty, $type, $price, $movementlabel, $movementcode, '', $eatBy, $sellBy, $lot) <= 0) {
$errormessage = $this->stockmovement->error; $errormessage = $this->stockmovement->error;
if (empty($errormessage)) $errormessage = join(',', $this->stockmovement->errors); if (empty($errormessage)) {
$errormessage = join(',', $this->stockmovement->errors);
}
throw new RestException(503, 'Error when create stock movement : '.$errormessage); throw new RestException(503, 'Error when create stock movement : '.$errormessage);
} }
@ -341,8 +338,9 @@ class StockMovements extends DolibarrApi
{ {
$stockmovement = array(); $stockmovement = array();
foreach (self::$FIELDS as $field) { foreach (self::$FIELDS as $field) {
if (!isset($data[$field])) if (!isset($data[$field])) {
throw new RestException(400, "$field field missing"); throw new RestException(400, "$field field missing");
}
$stockmovement[$field] = $data[$field]; $stockmovement[$field] = $data[$field];
} }
return $stockmovement; return $stockmovement;

View File

@ -31,7 +31,7 @@ class Warehouses extends DolibarrApi
/** /**
* @var array $FIELDS Mandatory fields, checked when create and update object * @var array $FIELDS Mandatory fields, checked when create and update object
*/ */
static $FIELDS = array( public static $FIELDS = array(
'label', 'label',
); );
@ -115,10 +115,8 @@ class Warehouses extends DolibarrApi
$sql .= " AND c.fk_warehouse = t.rowid "; $sql .= " AND c.fk_warehouse = t.rowid ";
} }
// Add sql filters // Add sql filters
if ($sqlfilters) if ($sqlfilters) {
{ if (!DolibarrApi::_checkFilters($sqlfilters)) {
if (!DolibarrApi::_checkFilters($sqlfilters))
{
throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
} }
$regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
@ -127,8 +125,7 @@ class Warehouses extends DolibarrApi
$sql .= $this->db->order($sortfield, $sortorder); $sql .= $this->db->order($sortfield, $sortorder);
if ($limit) { if ($limit) {
if ($page < 0) if ($page < 0) {
{
$page = 0; $page = 0;
} }
$offset = $limit * $page; $offset = $limit * $page;
@ -137,13 +134,11 @@ class Warehouses extends DolibarrApi
} }
$result = $this->db->query($sql); $result = $this->db->query($sql);
if ($result) if ($result) {
{
$i = 0; $i = 0;
$num = $this->db->num_rows($result); $num = $this->db->num_rows($result);
$min = min($num, ($limit <= 0 ? $num : $limit)); $min = min($num, ($limit <= 0 ? $num : $limit));
while ($i < $min) while ($i < $min) {
{
$obj = $this->db->fetch_object($result); $obj = $this->db->fetch_object($result);
$warehouse_static = new Entrepot($this->db); $warehouse_static = new Entrepot($this->db);
if ($warehouse_static->fetch($obj->rowid)) { if ($warehouse_static->fetch($obj->rowid)) {
@ -208,12 +203,15 @@ class Warehouses extends DolibarrApi
} }
foreach ($request_data as $field => $value) { foreach ($request_data as $field => $value) {
if ($field == 'id') continue; if ($field == 'id') {
continue;
}
$this->warehouse->$field = $value; $this->warehouse->$field = $value;
} }
if ($this->warehouse->update($id, DolibarrApiAccess::$user)) if ($this->warehouse->update($id, DolibarrApiAccess::$user)) {
return $this->get($id); return $this->get($id);
}
return false; return false;
} }
@ -282,8 +280,9 @@ class Warehouses extends DolibarrApi
{ {
$warehouse = array(); $warehouse = array();
foreach (Warehouses::$FIELDS as $field) { foreach (Warehouses::$FIELDS as $field) {
if (!isset($data[$field])) if (!isset($data[$field])) {
throw new RestException(400, "$field field missing"); throw new RestException(400, "$field field missing");
}
$warehouse[$field] = $data[$field]; $warehouse[$field] = $data[$field];
} }
return $warehouse; return $warehouse;

View File

@ -203,37 +203,29 @@ class Entrepot extends CommonObject
dol_syslog(get_class($this)."::create", LOG_DEBUG); dol_syslog(get_class($this)."::create", LOG_DEBUG);
$result = $this->db->query($sql); $result = $this->db->query($sql);
if ($result) if ($result) {
{
$id = $this->db->last_insert_id(MAIN_DB_PREFIX."entrepot"); $id = $this->db->last_insert_id(MAIN_DB_PREFIX."entrepot");
if ($id > 0) if ($id > 0) {
{
$this->id = $id; $this->id = $id;
if (!$error) if (!$error) {
{
$result = $this->update($id, $user); $result = $this->update($id, $user);
if ($result <= 0) if ($result <= 0) {
{
$error++; $error++;
} }
} }
// Actions on extra fields // Actions on extra fields
if (!$error) if (!$error) {
{ if (!$error) {
if (!$error)
{
$result = $this->insertExtraFields(); $result = $this->insertExtraFields();
if ($result < 0) if ($result < 0) {
{
$error++; $error++;
} }
} }
} }
if (!$error) if (!$error) {
{
$this->db->commit(); $this->db->commit();
return $id; return $id;
} else { } else {
@ -267,16 +259,18 @@ class Entrepot extends CommonObject
$error = 0; $error = 0;
if (empty($id)) $id = $this->id; if (empty($id)) {
if (empty($this->label)) $this->label = $this->libelle; // For backward compatibility $id = $this->id;
}
if (empty($this->label)) {
$this->label = $this->libelle; // For backward compatibility
}
// Check if new parent is already a child of current warehouse // Check if new parent is already a child of current warehouse
if (!empty($this->fk_parent)) if (!empty($this->fk_parent)) {
{
$TChildWarehouses = array($id); $TChildWarehouses = array($id);
$TChildWarehouses = $this->get_children_warehouses($this->id, $TChildWarehouses); $TChildWarehouses = $this->get_children_warehouses($this->id, $TChildWarehouses);
if (in_array($this->fk_parent, $TChildWarehouses)) if (in_array($this->fk_parent, $TChildWarehouses)) {
{
$this->error = 'ErrorCannotAddThisParentWarehouse'; $this->error = 'ErrorCannotAddThisParentWarehouse';
return -2; return -2;
} }
@ -319,8 +313,7 @@ class Entrepot extends CommonObject
if (!$error) { if (!$error) {
$result = $this->insertExtraFields(); $result = $this->insertExtraFields();
if ($result < 0) if ($result < 0) {
{
$error++; $error++;
} }
} }
@ -353,25 +346,23 @@ class Entrepot extends CommonObject
$this->db->begin(); $this->db->begin();
if (!$error && empty($notrigger)) if (!$error && empty($notrigger)) {
{
// Call trigger // Call trigger
$result = $this->call_trigger('WAREHOUSE_DELETE', $user); $result = $this->call_trigger('WAREHOUSE_DELETE', $user);
if ($result < 0) { $error++; } if ($result < 0) {
$error++;
}
// End call triggers // End call triggers
} }
$elements = array('stock_mouvement', 'product_stock', 'product_warehouse_properties'); $elements = array('stock_mouvement', 'product_stock', 'product_warehouse_properties');
foreach ($elements as $table) foreach ($elements as $table) {
{ if (!$error) {
if (!$error)
{
$sql = "DELETE FROM ".MAIN_DB_PREFIX.$table; $sql = "DELETE FROM ".MAIN_DB_PREFIX.$table;
$sql .= " WHERE fk_entrepot = ".$this->id; $sql .= " WHERE fk_entrepot = ".$this->id;
$result = $this->db->query($sql); $result = $this->db->query($sql);
if (!$result) if (!$result) {
{
$error++; $error++;
$this->errors[] = $this->db->lasterror(); $this->errors[] = $this->db->lasterror();
} }
@ -379,47 +370,39 @@ class Entrepot extends CommonObject
} }
// Removed extrafields // Removed extrafields
if (!$error) if (!$error) {
{ if (!$error) {
if (!$error)
{
$result = $this->deleteExtraFields(); $result = $this->deleteExtraFields();
if ($result < 0) if ($result < 0) {
{
$error++; $error++;
dol_syslog(get_class($this)."::delete Error ".$this->error, LOG_ERR); dol_syslog(get_class($this)."::delete Error ".$this->error, LOG_ERR);
} }
} }
} }
if (!$error) if (!$error) {
{
$sql = "DELETE FROM ".MAIN_DB_PREFIX."entrepot"; $sql = "DELETE FROM ".MAIN_DB_PREFIX."entrepot";
$sql .= " WHERE rowid = ".$this->id; $sql .= " WHERE rowid = ".$this->id;
$resql1 = $this->db->query($sql); $resql1 = $this->db->query($sql);
if (!$resql1) if (!$resql1) {
{
$error++; $error++;
$this->errors[] = $this->db->lasterror(); $this->errors[] = $this->db->lasterror();
dol_syslog(get_class($this)."::delete Error ".$this->db->lasterror(), LOG_ERR); dol_syslog(get_class($this)."::delete Error ".$this->db->lasterror(), LOG_ERR);
} }
} }
if (!$error) if (!$error) {
{
// Update denormalized fields because we change content of produt_stock. Warning: Do not use "SET p.stock", does not works with pgsql // Update denormalized fields because we change content of produt_stock. Warning: Do not use "SET p.stock", does not works with pgsql
$sql = "UPDATE ".MAIN_DB_PREFIX."product as p SET stock = (SELECT SUM(ps.reel) FROM ".MAIN_DB_PREFIX."product_stock as ps WHERE ps.fk_product = p.rowid)"; $sql = "UPDATE ".MAIN_DB_PREFIX."product as p SET stock = (SELECT SUM(ps.reel) FROM ".MAIN_DB_PREFIX."product_stock as ps WHERE ps.fk_product = p.rowid)";
$resql2 = $this->db->query($sql); $resql2 = $this->db->query($sql);
if (!$resql2) if (!$resql2) {
{
$error++; $error++;
$this->errors[] = $this->db->lasterror(); $this->errors[] = $this->db->lasterror();
dol_syslog(get_class($this)."::delete Error ".$this->db->lasterror(), LOG_ERR); dol_syslog(get_class($this)."::delete Error ".$this->db->lasterror(), LOG_ERR);
} }
} }
if (!$error) if (!$error) {
{
$this->db->commit(); $this->db->commit();
return 1; return 1;
} else { } else {
@ -443,8 +426,7 @@ class Entrepot extends CommonObject
dol_syslog(get_class($this)."::fetch id=".$id." ref=".$ref); dol_syslog(get_class($this)."::fetch id=".$id." ref=".$ref);
// Check parameters // Check parameters
if (!$id && !$ref) if (!$id && !$ref) {
{
$this->error = 'ErrorWrongParameters'; $this->error = 'ErrorWrongParameters';
dol_syslog(get_class($this)."::fetch ".$this->error); dol_syslog(get_class($this)."::fetch ".$this->error);
return -1; return -1;
@ -453,19 +435,18 @@ class Entrepot extends CommonObject
$sql = "SELECT rowid, entity, fk_parent, ref as label, description, statut, lieu, address, zip, town, fk_pays as country_id, phone, fax,"; $sql = "SELECT rowid, entity, fk_parent, ref as label, description, statut, lieu, address, zip, town, fk_pays as country_id, phone, fax,";
$sql .= " model_pdf, import_key"; $sql .= " model_pdf, import_key";
$sql .= " FROM ".MAIN_DB_PREFIX."entrepot"; $sql .= " FROM ".MAIN_DB_PREFIX."entrepot";
if ($id) if ($id) {
{
$sql .= " WHERE rowid = '".$id."'"; $sql .= " WHERE rowid = '".$id."'";
} else { } else {
$sql .= " WHERE entity = ".$conf->entity; $sql .= " WHERE entity = ".$conf->entity;
if ($ref) $sql .= " AND ref = '".$this->db->escape($ref)."'"; if ($ref) {
$sql .= " AND ref = '".$this->db->escape($ref)."'";
}
} }
$result = $this->db->query($sql); $result = $this->db->query($sql);
if ($result) if ($result) {
{ if ($this->db->num_rows($result) > 0) {
if ($this->db->num_rows($result) > 0)
{
$obj = $this->db->fetch_object($result); $obj = $this->db->fetch_object($result);
$this->id = $obj->rowid; $this->id = $obj->rowid;
@ -522,10 +503,8 @@ class Entrepot extends CommonObject
dol_syslog(get_class($this)."::info", LOG_DEBUG); dol_syslog(get_class($this)."::info", LOG_DEBUG);
$result = $this->db->query($sql); $result = $this->db->query($sql);
if ($result) if ($result) {
{ if ($this->db->num_rows($result)) {
if ($this->db->num_rows($result))
{
$obj = $this->db->fetch_object($result); $obj = $this->db->fetch_object($result);
$this->id = $obj->rowid; $this->id = $obj->rowid;
@ -573,10 +552,8 @@ class Entrepot extends CommonObject
$result = $this->db->query($sql); $result = $this->db->query($sql);
$i = 0; $i = 0;
$num = $this->db->num_rows($result); $num = $this->db->num_rows($result);
if ($result) if ($result) {
{ while ($i < $num) {
while ($i < $num)
{
$row = $this->db->fetch_row($result); $row = $this->db->fetch_row($result);
$liste[$row[0]] = $row[1]; $liste[$row[0]] = $row[1];
$i++; $i++;
@ -605,8 +582,7 @@ class Entrepot extends CommonObject
//print $sql; //print $sql;
$result = $this->db->query($sql); $result = $this->db->query($sql);
if ($result) if ($result) {
{
$obj = $this->db->fetch_object($result); $obj = $this->db->fetch_object($result);
$ret['nb'] = $obj->nb; $ret['nb'] = $obj->nb;
$this->db->free($result); $this->db->free($result);
@ -637,8 +613,7 @@ class Entrepot extends CommonObject
//print $sql; //print $sql;
$result = $this->db->query($sql); $result = $this->db->query($sql);
if ($result) if ($result) {
{
$obj = $this->db->fetch_object($result); $obj = $this->db->fetch_object($result);
$ret['nb'] = $obj->nb; $ret['nb'] = $obj->nb;
$ret['value'] = $obj->value; $ret['value'] = $obj->value;
@ -676,7 +651,9 @@ class Entrepot extends CommonObject
global $langs; global $langs;
$statusType = 'status5'; $statusType = 'status5';
if ($status > 0) $statusType = 'status4'; if ($status > 0) {
$statusType = 'status4';
}
$langs->load('stocks'); $langs->load('stocks');
$label = $langs->trans($this->statuts[$status]); $label = $langs->trans($this->statuts[$status]);
@ -700,9 +677,13 @@ class Entrepot extends CommonObject
global $conf, $langs, $hookmanager; global $conf, $langs, $hookmanager;
$langs->load("stocks"); $langs->load("stocks");
if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips if (!empty($conf->dol_no_mouse_hover)) {
$notooltip = 1; // Force disable tooltips
}
if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpicto) $withpicto = 0; if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpicto) {
$withpicto = 0;
}
$result = ''; $result = '';
@ -718,10 +699,8 @@ class Entrepot extends CommonObject
$url = DOL_URL_ROOT.'/product/stock/card.php?id='.$this->id; $url = DOL_URL_ROOT.'/product/stock/card.php?id='.$this->id;
$linkclose = ''; $linkclose = '';
if (empty($notooltip)) if (empty($notooltip)) {
{ if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
{
$label = $langs->trans("Warehouse"); $label = $langs->trans("Warehouse");
$linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
} }
@ -734,8 +713,12 @@ class Entrepot extends CommonObject
$linkend = '</a>'; $linkend = '</a>';
$result .= $linkstart; $result .= $linkstart;
if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); if ($withpicto) {
if ($withpicto != 2) $result .= (($showfullpath || !empty($conf->global->STOCK_ALWAYS_SHOW_FULL_ARBO)) ? $this->get_full_arbo() : (empty($this->label) ? $this->libelle : $this->label)); $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
}
if ($withpicto != 2) {
$result .= (($showfullpath || !empty($conf->global->STOCK_ALWAYS_SHOW_FULL_ARBO)) ? $this->get_full_arbo() : (empty($this->label) ? $this->libelle : $this->label));
}
$result .= $linkend; $result .= $linkend;
global $action; global $action;
@ -798,20 +781,21 @@ class Entrepot extends CommonObject
$parentid = $this->fk_parent; // If parent_id not defined on current object, we do not start consecutive searches of parents $parentid = $this->fk_parent; // If parent_id not defined on current object, we do not start consecutive searches of parents
$i = 0; $i = 0;
while ($parentid > 0 && $i < $protection) while ($parentid > 0 && $i < $protection) {
{
$sql = 'SELECT fk_parent FROM '.MAIN_DB_PREFIX.'entrepot WHERE rowid = '.$parentid; $sql = 'SELECT fk_parent FROM '.MAIN_DB_PREFIX.'entrepot WHERE rowid = '.$parentid;
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{
$objarbo = $this->db->fetch_object($resql); $objarbo = $this->db->fetch_object($resql);
if ($objarbo) if ($objarbo) {
{
$warehousetmp->fetch($parentid); $warehousetmp->fetch($parentid);
$TArbo[] = $warehousetmp->label; $TArbo[] = $warehousetmp->label;
$parentid = $objarbo->fk_parent; $parentid = $objarbo->fk_parent;
} else break; } else {
} else dol_print_error($this->db); break;
}
} else {
dol_print_error($this->db);
}
$i++; $i++;
} }

View File

@ -1020,15 +1020,13 @@ class MouvementStock extends CommonObject
break; break;
default: default:
if ($origintype) if ($origintype) {
{
// Separate originetype with "@" : left part is class name, right part is module name // Separate originetype with "@" : left part is class name, right part is module name
$origintype_array = explode('@', $origintype); $origintype_array = explode('@', $origintype);
$classname = ucfirst($origintype_array[0]); $classname = ucfirst($origintype_array[0]);
$modulename = empty($origintype_array[1]) ? $classname : $origintype_array[1]; $modulename = empty($origintype_array[1]) ? $classname : $origintype_array[1];
$result = dol_include_once('/'.$modulename.'/class/'.strtolower($classname).'.class.php'); $result = dol_include_once('/'.$modulename.'/class/'.strtolower($classname).'.class.php');
if ($result) if ($result) {
{
$classname = ucfirst($classname); $classname = ucfirst($classname);
$origin = new $classname($this->db); $origin = new $classname($this->db);
} }
@ -1036,7 +1034,9 @@ class MouvementStock extends CommonObject
break; break;
} }
if (empty($origin) || !is_object($origin)) return ''; if (empty($origin) || !is_object($origin)) {
return '';
}
if ($origin->fetch($fk_origin) > 0) { if ($origin->fetch($fk_origin) > 0) {
return $origin->getNomUrl(1); return $origin->getNomUrl(1);
@ -1055,17 +1055,16 @@ class MouvementStock extends CommonObject
*/ */
public function setOrigin($origin_element, $origin_id) public function setOrigin($origin_element, $origin_id)
{ {
if (!empty($origin_element) && $origin_id > 0) if (!empty($origin_element) && $origin_id > 0) {
{
$origin = ''; $origin = '';
if ($origin_element == 'project') if ($origin_element == 'project') {
{ if (!class_exists('Project')) {
if (!class_exists('Project')) require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
}
$origin = new Project($this->db); $origin = new Project($this->db);
} }
if (!empty($origin)) if (!empty($origin)) {
{
$this->origin = $origin; $this->origin = $origin;
$this->origin->id = $origin_id; $this->origin->id = $origin_id;
} }
@ -1119,10 +1118,11 @@ class MouvementStock extends CommonObject
$link .= '>'; $link .= '>';
$linkend = '</a>'; $linkend = '</a>';
if ($withpicto) if ($withpicto) {
{
$result .= ($link.img_object(($notooltip ? '' : $label), 'stock', ($notooltip ? '' : 'class="classfortooltip"')).$linkend); $result .= ($link.img_object(($notooltip ? '' : $label), 'stock', ($notooltip ? '' : 'class="classfortooltip"')).$linkend);
if ($withpicto != 2) $result .= ' '; if ($withpicto != 2) {
$result .= ' ';
}
} }
$result .= $link.$this->id.$linkend; $result .= $link.$this->id.$linkend;
return $result; return $result;

View File

@ -215,11 +215,9 @@ class Productlot extends CommonObject
$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
// Actions on extra fields // Actions on extra fields
if (!$error) if (!$error) {
{
$result = $this->insertExtraFields(); $result = $this->insertExtraFields();
if ($result < 0) if ($result < 0) {
{
$error++; $error++;
} }
} }
@ -230,7 +228,9 @@ class Productlot extends CommonObject
// Call triggers // Call triggers
$result = $this->call_trigger('PRODUCTLOT_CREATE', $user); $result = $this->call_trigger('PRODUCTLOT_CREATE', $user);
if ($result < 0) $error++; if ($result < 0) {
$error++;
}
// End call triggers // End call triggers
} }
} }
@ -358,8 +358,7 @@ class Productlot extends CommonObject
// Check parameters // Check parameters
// Put here code to add a control on parameters values // Put here code to add a control on parameters values
if (empty($this->oldcopy)) if (empty($this->oldcopy)) {
{
$org = new self($this->db); $org = new self($this->db);
$org->fetch($this->id); $org->fetch($this->id);
$this->oldcopy = $org; $this->oldcopy = $org;
@ -389,11 +388,9 @@ class Productlot extends CommonObject
} }
// Actions on extra fields // Actions on extra fields
if (!$error) if (!$error) {
{
$result = $this->insertExtraFields(); $result = $this->insertExtraFields();
if ($result < 0) if ($result < 0) {
{
$error++; $error++;
} }
} }
@ -401,7 +398,9 @@ class Productlot extends CommonObject
if (!$error && !$notrigger) { if (!$error && !$notrigger) {
// Call triggers // Call triggers
$result = $this->call_trigger('PRODUCTLOT_MODIFY', $user); $result = $this->call_trigger('PRODUCTLOT_MODIFY', $user);
if ($result < 0) { $error++; } if ($result < 0) {
$error++;
}
// End call triggers // End call triggers
} }
@ -581,25 +580,28 @@ class Productlot extends CommonObject
$url = DOL_URL_ROOT.'/product/stock/productlot_card.php?id='.$this->id; $url = DOL_URL_ROOT.'/product/stock/productlot_card.php?id='.$this->id;
if ($option != 'nolink') if ($option != 'nolink') {
{
// Add param to save lastsearch_values or not // Add param to save lastsearch_values or not
$add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1; if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1'; $add_save_lastsearch_values = 1;
}
if ($add_save_lastsearch_values) {
$url .= '&save_lastsearch_values=1';
}
} }
$linkclose = ''; $linkclose = '';
if (empty($notooltip)) if (empty($notooltip)) {
{ if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
{
$label = $langs->trans("ShowMyObject"); $label = $langs->trans("ShowMyObject");
$linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
} }
$linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
$linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
} else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); } else {
$linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
}
if ($option == 'nolink') { if ($option == 'nolink') {
$linkstart = '<span'; $linkstart = '<span';
@ -614,8 +616,12 @@ class Productlot extends CommonObject
} }
$result .= $linkstart; $result .= $linkstart;
if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); if ($withpicto) {
if ($withpicto != 2) $result .= $this->batch; $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
}
if ($withpicto != 2) {
$result .= $this->batch;
}
$result .= $linkend; $result .= $linkend;
return $result; return $result;

View File

@ -93,11 +93,21 @@ class ProductStockEntrepot extends CommonObject
// Clean parameters // Clean parameters
if (isset($this->fk_product)) $this->fk_product = (int) $this->fk_product; if (isset($this->fk_product)) {
if (isset($this->fk_entrepot)) $this->fk_entrepot = (int) $this->fk_entrepot; $this->fk_product = (int) $this->fk_product;
if (isset($this->seuil_stock_alerte)) $this->seuil_stock_alerte = trim($this->seuil_stock_alerte); }
if (isset($this->desiredstock)) $this->desiredstock = trim($this->desiredstock); if (isset($this->fk_entrepot)) {
if (isset($this->import_key)) $this->import_key = trim($this->import_key); $this->fk_entrepot = (int) $this->fk_entrepot;
}
if (isset($this->seuil_stock_alerte)) {
$this->seuil_stock_alerte = trim($this->seuil_stock_alerte);
}
if (isset($this->desiredstock)) {
$this->desiredstock = trim($this->desiredstock);
}
if (isset($this->import_key)) {
$this->import_key = trim($this->import_key);
}
// Check parameters // Check parameters
// Put here code to add control on parameters values // Put here code to add control on parameters values
@ -168,7 +178,9 @@ class ProductStockEntrepot extends CommonObject
*/ */
public function fetch($id, $fk_product = 0, $fk_entrepot = 0) public function fetch($id, $fk_product = 0, $fk_entrepot = 0)
{ {
if (empty($id) && (empty($fk_product) || empty($fk_entrepot))) return -1; if (empty($id) && (empty($fk_product) || empty($fk_entrepot))) {
return -1;
}
dol_syslog(__METHOD__, LOG_DEBUG); dol_syslog(__METHOD__, LOG_DEBUG);
@ -181,15 +193,16 @@ class ProductStockEntrepot extends CommonObject
$sql .= " t.desiredstock,"; $sql .= " t.desiredstock,";
$sql .= " t.import_key"; $sql .= " t.import_key";
$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
if (!empty($id)) $sql .= ' WHERE t.rowid = '.$id; if (!empty($id)) {
else $sql .= ' WHERE t.fk_product = '.$fk_product.' AND t.fk_entrepot = '.$fk_entrepot; $sql .= ' WHERE t.rowid = '.$id;
} else {
$sql .= ' WHERE t.fk_product = '.$fk_product.' AND t.fk_entrepot = '.$fk_entrepot;
}
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{
$numrows = $this->db->num_rows($resql); $numrows = $this->db->num_rows($resql);
if ($numrows) if ($numrows) {
{
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
$this->id = $obj->rowid; $this->id = $obj->rowid;
@ -263,14 +276,23 @@ class ProductStockEntrepot extends CommonObject
$sqlwhere [] = $key.' LIKE \'%'.$this->db->escape($value).'%\''; $sqlwhere [] = $key.' LIKE \'%'.$this->db->escape($value).'%\'';
} }
} }
if (count($sqlwhere) > 0) $sql .= ' AND '.implode(' '.$filtermode.' ', $sqlwhere); if (count($sqlwhere) > 0) {
$sql .= ' AND '.implode(' '.$filtermode.' ', $sqlwhere);
}
if (!empty($fk_product)) $sql .= ' AND fk_product = '.$fk_product; if (!empty($fk_product)) {
elseif (!empty($fk_entrepot)) $sql .= ' AND fk_entrepot = '.$fk_entrepot; $sql .= ' AND fk_product = '.$fk_product;
} elseif (!empty($fk_entrepot)) {
$sql .= ' AND fk_entrepot = '.$fk_entrepot;
}
// "elseif" used instead of "if" because getting list with specified fk_product and specified fk_entrepot would be the same as doing a fetch // "elseif" used instead of "if" because getting list with specified fk_product and specified fk_entrepot would be the same as doing a fetch
if (!empty($sortfield)) $sql .= $this->db->order($sortfield, $sortorder); if (!empty($sortfield)) {
if (!empty($limit)) $sql .= ' '.$this->db->plimit($limit, $offset); $sql .= $this->db->order($sortfield, $sortorder);
}
if (!empty($limit)) {
$sql .= ' '.$this->db->plimit($limit, $offset);
}
$lines = array(); $lines = array();
@ -312,11 +334,21 @@ class ProductStockEntrepot extends CommonObject
// Clean parameters // Clean parameters
if (isset($this->fk_product)) $this->fk_product = (int) $this->fk_product; if (isset($this->fk_product)) {
if (isset($this->fk_entrepot)) $this->fk_entrepot = (int) $this->fk_entrepot; $this->fk_product = (int) $this->fk_product;
if (isset($this->seuil_stock_alerte)) $this->seuil_stock_alerte = trim($this->seuil_stock_alerte); }
if (isset($this->desiredstock)) $this->desiredstock = trim($this->desiredstock); if (isset($this->fk_entrepot)) {
if (isset($this->import_key)) $this->import_key = trim($this->import_key); $this->fk_entrepot = (int) $this->fk_entrepot;
}
if (isset($this->seuil_stock_alerte)) {
$this->seuil_stock_alerte = trim($this->seuil_stock_alerte);
}
if (isset($this->desiredstock)) {
$this->desiredstock = trim($this->desiredstock);
}
if (isset($this->import_key)) {
$this->import_key = trim($this->import_key);
}
// Check parameters // Check parameters
@ -495,10 +527,11 @@ class ProductStockEntrepot extends CommonObject
$link .= '>'; $link .= '>';
$linkend = '</a>'; $linkend = '</a>';
if ($withpicto) if ($withpicto) {
{
$result .= ($link.img_object(($notooltip ? '' : $label), 'label', ($notooltip ? '' : 'class="classfortooltip"'), 0, 0, $notooltip ? 0 : 1).$linkend); $result .= ($link.img_object(($notooltip ? '' : $label), 'label', ($notooltip ? '' : 'class="classfortooltip"'), 0, 0, $notooltip ? 0 : 1).$linkend);
if ($withpicto != 2) $result .= ' '; if ($withpicto != 2) {
$result .= ' ';
}
} }
$result .= $link.$this->ref.$linkend; $result .= $link.$this->ref.$linkend;
return $result; return $result;
@ -528,30 +561,42 @@ class ProductStockEntrepot extends CommonObject
// phpcs:enable // phpcs:enable
global $langs; global $langs;
if ($mode == 0) if ($mode == 0) {
{ if ($status == 1) {
if ($status == 1) return $langs->trans('Enabled'); return $langs->trans('Enabled');
elseif ($status == 0) return $langs->trans('Disabled'); } elseif ($status == 0) {
} elseif ($mode == 1) return $langs->trans('Disabled');
{ }
if ($status == 1) return $langs->trans('Enabled'); } elseif ($mode == 1) {
elseif ($status == 0) return $langs->trans('Disabled'); if ($status == 1) {
} elseif ($mode == 2) return $langs->trans('Enabled');
{ } elseif ($status == 0) {
if ($status == 1) return img_picto($langs->trans('Enabled'), 'statut4').' '.$langs->trans('Enabled'); return $langs->trans('Disabled');
elseif ($status == 0) return img_picto($langs->trans('Disabled'), 'statut5').' '.$langs->trans('Disabled'); }
} elseif ($mode == 3) } elseif ($mode == 2) {
{ if ($status == 1) {
if ($status == 1) return img_picto($langs->trans('Enabled'), 'statut4'); return img_picto($langs->trans('Enabled'), 'statut4').' '.$langs->trans('Enabled');
elseif ($status == 0) return img_picto($langs->trans('Disabled'), 'statut5'); } elseif ($status == 0) {
} elseif ($mode == 4) return img_picto($langs->trans('Disabled'), 'statut5').' '.$langs->trans('Disabled');
{ }
if ($status == 1) return img_picto($langs->trans('Enabled'), 'statut4').' '.$langs->trans('Enabled'); } elseif ($mode == 3) {
elseif ($status == 0) return img_picto($langs->trans('Disabled'), 'statut5').' '.$langs->trans('Disabled'); if ($status == 1) {
} elseif ($mode == 5) return img_picto($langs->trans('Enabled'), 'statut4');
{ } elseif ($status == 0) {
if ($status == 1) return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'), 'statut4'); return img_picto($langs->trans('Disabled'), 'statut5');
elseif ($status == 0) return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'), 'statut5'); }
} elseif ($mode == 4) {
if ($status == 1) {
return img_picto($langs->trans('Enabled'), 'statut4').' '.$langs->trans('Enabled');
} elseif ($status == 0) {
return img_picto($langs->trans('Disabled'), 'statut5').' '.$langs->trans('Disabled');
}
} elseif ($mode == 5) {
if ($status == 1) {
return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'), 'statut4');
} elseif ($status == 0) {
return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'), 'statut5');
}
} }
} }

View File

@ -43,14 +43,14 @@ $form = new Form($db);
$help_url = 'EN:Module_Stocks_En|FR:Module_Stock|ES:M&oacute;dulo_Stocks'; $help_url = 'EN:Module_Stocks_En|FR:Module_Stock|ES:M&oacute;dulo_Stocks';
llxHeader("", $langs->trans("WarehouseCard"), $help_url); llxHeader("", $langs->trans("WarehouseCard"), $help_url);
if ($_GET["id"]) if ($_GET["id"]) {
{ if ($mesg) {
if ($mesg) print $mesg; print $mesg;
}
$entrepot = new Entrepot($db); $entrepot = new Entrepot($db);
$result = $entrepot->fetch($_GET["id"]); $result = $entrepot->fetch($_GET["id"]);
if ($result < 0) if ($result < 0) {
{
dol_print_error($db); dol_print_error($db);
} }
@ -120,13 +120,11 @@ if ($_GET["id"])
if (file_exists($file)) if (file_exists($file)) {
{
$url = DOL_URL_ROOT.'/viewimage.php?modulepart=graph_stock&amp;file=entrepot-'.$entrepot->id.'-'.$year.'.png'; $url = DOL_URL_ROOT.'/viewimage.php?modulepart=graph_stock&amp;file=entrepot-'.$entrepot->id.'-'.$year.'.png';
print '<img src="'.$url.'" alt="Valorisation du stock annee '.($year).'">'; print '<img src="'.$url.'" alt="Valorisation du stock annee '.($year).'">';
if (file_exists(DOL_DATA_ROOT.'/entrepot/temp/entrepot-'.$entrepot->id.'-'.($year - 1).'.png')) if (file_exists(DOL_DATA_ROOT.'/entrepot/temp/entrepot-'.$entrepot->id.'-'.($year - 1).'.png')) {
{
$url = DOL_URL_ROOT.'/viewimage.php?modulepart=graph_stock&amp;file=entrepot-'.$entrepot->id.'-'.($year - 1).'.png'; $url = DOL_URL_ROOT.'/viewimage.php?modulepart=graph_stock&amp;file=entrepot-'.$entrepot->id.'-'.($year - 1).'.png';
print '<br><img src="'.$url.'" alt="Valorisation du stock annee '.($year - 1).'">'; print '<br><img src="'.$url.'" alt="Valorisation du stock annee '.($year - 1).'">';
} }

View File

@ -60,8 +60,7 @@ print load_fiche_titre($langs->trans("StocksArea"), '', 'stock');
print '<div class="fichecenter"><div class="fichethirdleft">'; print '<div class="fichecenter"><div class="fichethirdleft">';
if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is useless due to the global search combo if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) { // This is useless due to the global search combo
{
print '<form method="post" action="'.DOL_URL_ROOT.'/product/stock/list.php">'; print '<form method="post" action="'.DOL_URL_ROOT.'/product/stock/list.php">';
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<div class="div-table-responsive-no-min">'; print '<div class="div-table-responsive-no-min">';
@ -84,8 +83,7 @@ $sql .= $db->plimit($max + 1, 0);
$result = $db->query($sql); $result = $db->query($sql);
if ($result) if ($result) {
{
$num = $db->num_rows($result); $num = $db->num_rows($result);
print '<div class="div-table-responsive-no-min">'; print '<div class="div-table-responsive-no-min">';
@ -102,10 +100,8 @@ if ($result)
print '</tr>'; print '</tr>';
$i = 0; $i = 0;
if ($num) if ($num) {
{ while ($i < min($max, $num)) {
while ($i < min($max, $num))
{
$objp = $db->fetch_object($result); $objp = $db->fetch_object($result);
$warehouse->id = $objp->rowid; $warehouse->id = $objp->rowid;
@ -153,14 +149,15 @@ $sql .= ", ".MAIN_DB_PREFIX."product as p";
$sql .= " WHERE m.fk_product = p.rowid"; $sql .= " WHERE m.fk_product = p.rowid";
$sql .= " AND m.fk_entrepot = e.rowid"; $sql .= " AND m.fk_entrepot = e.rowid";
$sql .= " AND e.entity IN (".getEntity('stock').")"; $sql .= " AND e.entity IN (".getEntity('stock').")";
if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) $sql .= " AND p.fk_product_type = ".Product::TYPE_PRODUCT; if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
$sql .= " AND p.fk_product_type = ".Product::TYPE_PRODUCT;
}
$sql .= $db->order("datem", "DESC"); $sql .= $db->order("datem", "DESC");
$sql .= $db->plimit($max, 0); $sql .= $db->plimit($max, 0);
dol_syslog("Index:list stock movements", LOG_DEBUG); dol_syslog("Index:list stock movements", LOG_DEBUG);
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
print '<div class="div-table-responsive-no-min">'; print '<div class="div-table-responsive-no-min">';
@ -168,8 +165,7 @@ if ($resql)
print "<tr class=\"liste_titre\">"; print "<tr class=\"liste_titre\">";
print '<th>'.$langs->trans("LastMovements", min($num, $max)).'</th>'; print '<th>'.$langs->trans("LastMovements", min($num, $max)).'</th>';
print '<th>'.$langs->trans("Product").'</th>'; print '<th>'.$langs->trans("Product").'</th>';
if (!empty($conf->productbatch->enabled)) if (!empty($conf->productbatch->enabled)) {
{
print '<th>'.$langs->trans("Batch").'</th>'; print '<th>'.$langs->trans("Batch").'</th>';
/*if (empty($conf->global->PRODUCT_DISABLE_SELLBY)) { /*if (empty($conf->global->PRODUCT_DISABLE_SELLBY)) {
print '<th>'.$langs->trans("SellByDate").'</th>'; print '<th>'.$langs->trans("SellByDate").'</th>';
@ -185,8 +181,7 @@ if ($resql)
$tmplotstatic = new Productlot($db); $tmplotstatic = new Productlot($db);
$i = 0; $i = 0;
while ($i < min($num, $max)) while ($i < min($num, $max)) {
{
$objp = $db->fetch_object($resql); $objp = $db->fetch_object($resql);
$producttmp->id = $objp->rowid; $producttmp->id = $objp->rowid;
@ -225,7 +220,9 @@ if ($resql)
print $warehouse->getNomUrl(1); print $warehouse->getNomUrl(1);
print "</td>\n"; print "</td>\n";
print '<td class="right">'; print '<td class="right">';
if ($objp->qty > 0) print '+'; if ($objp->qty > 0) {
print '+';
}
print $objp->qty.'</td>'; print $objp->qty.'</td>';
print "</tr>\n"; print "</tr>\n";
$i++; $i++;

View File

@ -60,7 +60,9 @@ $morehtmlref .= $langs->trans("LocationSummary").' : '.$object->lieu;
$morehtmlref .= '</div>'; $morehtmlref .= '</div>';
$shownav = 1; $shownav = 1;
if ($user->socid && !in_array('stock', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; if ($user->socid && !in_array('stock', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) {
$shownav = 0;
}
dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref', 'ref', $morehtmlref); dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref', 'ref', $morehtmlref);

View File

@ -43,30 +43,33 @@ function dolDispatchToDo($order_id)
$sql .= ' GROUP BY fk_product'; $sql .= ' GROUP BY fk_product';
$sql .= ' ORDER by fk_product'; $sql .= ' ORDER by fk_product';
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql && $db->num_rows($resql)) if ($resql && $db->num_rows($resql)) {
{ while ($obj = $db->fetch_object($resql)) {
while ($obj = $db->fetch_object($resql))
$dispatched[$obj->fk_product] = $obj; $dispatched[$obj->fk_product] = $obj;
} }
}
// Count nb of quantity to dispatch per product // Count nb of quantity to dispatch per product
$sql = 'SELECT fk_product, SUM(qty) FROM '.MAIN_DB_PREFIX.'commande_fournisseurdet'; $sql = 'SELECT fk_product, SUM(qty) FROM '.MAIN_DB_PREFIX.'commande_fournisseurdet';
$sql .= ' WHERE fk_commande = '.$order_id; $sql .= ' WHERE fk_commande = '.$order_id;
$sql .= ' AND fk_product > 0'; $sql .= ' AND fk_product > 0';
if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) $sql .= ' AND product_type = 0'; if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
$sql .= ' AND product_type = 0';
}
$sql .= ' GROUP BY fk_product'; $sql .= ' GROUP BY fk_product';
$sql .= ' ORDER by fk_product'; $sql .= ' ORDER by fk_product';
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql && $db->num_rows($resql)) if ($resql && $db->num_rows($resql)) {
{ while ($obj = $db->fetch_object($resql)) {
while ($obj = $db->fetch_object($resql))
$ordered[$obj->fk_product] = $obj; $ordered[$obj->fk_product] = $obj;
} }
}
$todispatch = 0; $todispatch = 0;
foreach ($ordered as $key => $val) foreach ($ordered as $key => $val) {
{ if ($ordered[$key] > $dispatched[$key]) {
if ($ordered[$key] > $dispatched[$key]) $todispatch++; $todispatch++;
}
} }
return ($todispatch ? true : false); return ($todispatch ? true : false);
@ -85,19 +88,15 @@ function dispatchedOrders()
$sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'commande_fournisseur'; $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'commande_fournisseur';
$resql = $db->query($sql); $resql = $db->query($sql);
$resarray = array(); $resarray = array();
if ($resql && $db->num_rows($resql) > 0) if ($resql && $db->num_rows($resql) > 0) {
{ while ($obj = $db->fetch_object($resql)) {
while ($obj = $db->fetch_object($resql)) if (!dolDispatchToDo($obj->rowid)) {
{
if (!dolDispatchToDo($obj->rowid))
{
$resarray[] = $obj->rowid; $resarray[] = $obj->rowid;
} }
} }
} }
if (count($resarray)) if (count($resarray)) {
{
$res = '('.implode(',', $resarray).')'; $res = '('.implode(',', $resarray).')';
} else { } else {
//hack to make sure ordered SQL request won't syntax error //hack to make sure ordered SQL request won't syntax error
@ -131,11 +130,9 @@ function ordered($product_id)
$sql .= ' GROUP BY cfd.fk_product'; $sql .= ' GROUP BY cfd.fk_product';
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$exists = $db->num_rows($resql); $exists = $db->num_rows($resql);
if ($exists) if ($exists) {
{
$obj = $db->fetch_array($resql); $obj = $db->fetch_array($resql);
return $obj['qty']; //. ' ' . img_picto('','tick'); return $obj['qty']; //. ' ' . img_picto('','tick');
} else { } else {

View File

@ -28,8 +28,7 @@
require '../../main.inc.php'; require '../../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
if (!empty($conf->categorie->enabled)) if (!empty($conf->categorie->enabled)) {
{
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcategory.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcategory.class.php';
require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
} }
@ -54,8 +53,7 @@ $search_ref = GETPOST("sref", "alpha") ?GETPOST("sref", "alpha") : GETPOST("sear
$search_label = GETPOST("snom", "alpha") ?GETPOST("snom", "alpha") : GETPOST("search_label", "alpha"); $search_label = GETPOST("snom", "alpha") ?GETPOST("snom", "alpha") : GETPOST("search_label", "alpha");
$search_status = GETPOST("search_status", "int"); $search_status = GETPOST("search_status", "int");
if (!empty($conf->categorie->enabled)) if (!empty($conf->categorie->enabled)) {
{
$search_category_list = GETPOST("search_category_".Categorie::TYPE_WAREHOUSE."_list", "array"); $search_category_list = GETPOST("search_category_".Categorie::TYPE_WAREHOUSE."_list", "array");
} }
@ -64,12 +62,18 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST('sortfield', 'aZ09comma'); $sortfield = GETPOST('sortfield', 'aZ09comma');
$sortorder = GETPOST('sortorder', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) { $page = 0; } // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) {
$page = 0;
} // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if (!$sortfield) $sortfield = "t.ref"; if (!$sortfield) {
if (!$sortorder) $sortorder = "ASC"; $sortfield = "t.ref";
}
if (!$sortorder) {
$sortorder = "ASC";
}
// Security check // Security check
$result = restrictedArea($user, 'stock'); $result = restrictedArea($user, 'stock');
@ -89,18 +93,22 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_elemen
// Initialize array of search criterias // Initialize array of search criterias
$search_all = GETPOST("search_all", 'alpha'); $search_all = GETPOST("search_all", 'alpha');
$search = array(); $search = array();
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{
$search_key = $key; $search_key = $key;
if ($search_key == 'statut') $search_key = 'status'; // remove this after refactor entrepot.class property statut to status if ($search_key == 'statut') {
if (GETPOST('search_'.$search_key, 'alpha') !== '') $search[$search_key] = GETPOST('search_'.$search_key, 'alpha'); $search_key = 'status'; // remove this after refactor entrepot.class property statut to status
}
if (GETPOST('search_'.$search_key, 'alpha') !== '') {
$search[$search_key] = GETPOST('search_'.$search_key, 'alpha');
}
} }
// List of fields to search into when doing a "search in all" // List of fields to search into when doing a "search in all"
$fieldstosearchall = array(); $fieldstosearchall = array();
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{ if ($val['searchall']) {
if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label']; $fieldstosearchall['t.'.$key] = $val['label'];
}
} }
// Definition of array of fields for columns // Definition of array of fields for columns
@ -133,31 +141,33 @@ $arrayfields = dol_sort_array($arrayfields, 'position');
* Actions * Actions
*/ */
if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } if (GETPOST('cancel', 'alpha')) {
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } $action = 'list'; $massaction = '';
}
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
$massaction = '';
}
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if (empty($reshook)) if (empty($reshook)) {
{
// Selection of new fields // Selection of new fields
include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
// Purge search criteria // Purge search criteria
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
{ foreach ($object->fields as $key => $val) {
foreach ($object->fields as $key => $val)
{
$search[$key] = ''; $search[$key] = '';
} }
$toselect = array(); $toselect = array();
$search_array_options = array(); $search_array_options = array();
} }
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') 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')) || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) {
{
$massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation
} }
@ -189,13 +199,14 @@ $title = $langs->trans("ListOfWarehouses");
// Build and execute select // Build and execute select
// -------------------------------------------------------------------- // --------------------------------------------------------------------
$sql = 'SELECT '; $sql = 'SELECT ';
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{
$sql .= 't.'.$key.', '; $sql .= 't.'.$key.', ';
} }
// Add fields from extrafields // Add fields from extrafields
if (!empty($extrafields->attributes[$object->table_element]['label'])) { if (!empty($extrafields->attributes[$object->table_element]['label'])) {
foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.' as options_'.$key.', ' : ''); foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
$sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.' as options_'.$key.', ' : '');
}
} }
$sql .= " SUM(p.pmp * ps.reel) as estimatedvalue, SUM(p.price * ps.reel) as sellvalue, SUM(ps.reel) as stockqty"; $sql .= " SUM(p.pmp * ps.reel) as estimatedvalue, SUM(p.price * ps.reel) as sellvalue, SUM(ps.reel) as stockqty";
// Add fields from hooks // Add fields from hooks
@ -204,33 +215,42 @@ $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $obje
$sql .= $hookmanager->resPrint; $sql .= $hookmanager->resPrint;
$sql = preg_replace('/,\s*$/', '', $sql); $sql = preg_replace('/,\s*$/', '', $sql);
$sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t"; $sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t";
if (!empty($conf->categorie->enabled)) if (!empty($conf->categorie->enabled)) {
{
$sql .= Categorie::getFilterJoinQuery(Categorie::TYPE_WAREHOUSE, "t.rowid"); $sql .= Categorie::getFilterJoinQuery(Categorie::TYPE_WAREHOUSE, "t.rowid");
} }
if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) {
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)";
}
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps ON t.rowid = ps.fk_entrepot"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps ON t.rowid = ps.fk_entrepot";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON ps.fk_product = p.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON ps.fk_product = p.rowid";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as c_dep ON c_dep.rowid = t.fk_departement"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as c_dep ON c_dep.rowid = t.fk_departement";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as ccount ON ccount.rowid = t.fk_pays"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as ccount ON ccount.rowid = t.fk_pays";
$sql .= " WHERE t.entity IN (".getEntity('stock').")"; $sql .= " WHERE t.entity IN (".getEntity('stock').")";
if (!empty($conf->categorie->enabled)) if (!empty($conf->categorie->enabled)) {
{
$sql .= Categorie::getFilterSelectQuery(Categorie::TYPE_WAREHOUSE, "t.rowid", $search_category_list); $sql .= Categorie::getFilterSelectQuery(Categorie::TYPE_WAREHOUSE, "t.rowid", $search_category_list);
} }
foreach ($search as $key => $val) foreach ($search as $key => $val) {
{
$class_key = $key; $class_key = $key;
if ($class_key == 'status') $class_key = 'statut'; // remove this after refactor entrepot.class property statut to status if ($class_key == 'status') {
if (($key == 'status' && $search[$key] == -1) || $key == 'entity') continue; $class_key = 'statut'; // remove this after refactor entrepot.class property statut to status
}
if (($key == 'status' && $search[$key] == -1) || $key == 'entity') {
continue;
}
$mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0); $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0);
if (strpos($object->fields[$key]['type'], 'integer:') === 0) { if (strpos($object->fields[$key]['type'], 'integer:') === 0) {
if ($search[$key] == '-1') $search[$key] = ''; if ($search[$key] == '-1') {
$search[$key] = '';
}
$mode_search = 2; $mode_search = 2;
} }
if ($search[$key] != '') $sql .= natural_search((($key == 'ref') ? 't.ref' : 't.'.$class_key), $search[$key], (($key == 'status') ? 2 : $mode_search)); if ($search[$key] != '') {
$sql .= natural_search((($key == 'ref') ? 't.ref' : 't.'.$class_key), $search[$key], (($key == 'status') ? 2 : $mode_search));
}
}
if ($search_all) {
$sql .= natural_search(array_keys($fieldstosearchall), $search_all);
} }
if ($search_all) $sql .= natural_search(array_keys($fieldstosearchall), $search_all);
// Add where from extra fields // Add where from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
// Add where from hooks // Add where from hooks
@ -238,13 +258,14 @@ $parameters = array();
$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook
$sql .= $hookmanager->resPrint; $sql .= $hookmanager->resPrint;
$sql .= " GROUP BY "; $sql .= " GROUP BY ";
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{
$sql .= 't.'.$key.', '; $sql .= 't.'.$key.', ';
} }
// Add fields from extrafields // Add fields from extrafields
if (!empty($extrafields->attributes[$object->table_element]['label'])) { if (!empty($extrafields->attributes[$object->table_element]['label'])) {
foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.', ' : ''); foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
$sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.', ' : '');
}
} }
// Add where from hooks // Add where from hooks
$parameters = array(); $parameters = array();
@ -253,13 +274,11 @@ $sql .= $hookmanager->resPrint;
$sql = preg_replace('/,\s*$/', '', $sql); $sql = preg_replace('/,\s*$/', '', $sql);
$totalnboflines = 0; $totalnboflines = 0;
$result = $db->query($sql); $result = $db->query($sql);
if ($result) if ($result) {
{
$totalnboflines = $db->num_rows($result); $totalnboflines = $db->num_rows($result);
// fetch totals // fetch totals
$line = $total = $totalsell = $totalStock = 0; $line = $total = $totalsell = $totalStock = 0;
while ($line < $totalnboflines) while ($line < $totalnboflines) {
{
$objp = $db->fetch_object($result); $objp = $db->fetch_object($result);
$total += price2num($objp->estimatedvalue, 'MU'); $total += price2num($objp->estimatedvalue, 'MU');
$totalsell += price2num($objp->sellvalue, 'MU'); $totalsell += price2num($objp->sellvalue, 'MU');
@ -274,26 +293,22 @@ $sql .= $db->order($sortfield, $sortorder);
// Count total nb of records // Count total nb of records
$nbtotalofrecords = ''; $nbtotalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
{
$resql = $db->query($sql); $resql = $db->query($sql);
$nbtotalofrecords = $db->num_rows($resql); $nbtotalofrecords = $db->num_rows($resql);
if (($page * $limit) > $nbtotalofrecords) // if total of record found is smaller than page * limit, goto and load page 0 if (($page * $limit) > $nbtotalofrecords) { // if total of record found is smaller than page * limit, goto and load page 0
{
$page = 0; $page = 0;
$offset = 0; $offset = 0;
} }
} }
// if total of record found is smaller than limit, no need to do paging and to restart another select with limits set. // if total of record found is smaller than limit, no need to do paging and to restart another select with limits set.
if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords) if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords) {
{
$num = $nbtotalofrecords; $num = $nbtotalofrecords;
} else { } else {
$sql .= $db->plimit($limit + 1, $offset); $sql .= $db->plimit($limit + 1, $offset);
$resql = $db->query($sql); $resql = $db->query($sql);
if (!$resql) if (!$resql) {
{
dol_print_error($db); dol_print_error($db);
exit; exit;
} }
@ -302,8 +317,7 @@ if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords)
} }
// Direct jump if only one record found // Direct jump if only one record found
if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
$id = $obj->rowid; $id = $obj->rowid;
header("Location: ".DOL_URL_ROOT.'/product/stock/card.php?id='.$id); header("Location: ".DOL_URL_ROOT.'/product/stock/card.php?id='.$id);
@ -319,14 +333,24 @@ llxHeader('', $title, $help_url);
$arrayofselected = is_array($toselect) ? $toselect : array(); $arrayofselected = is_array($toselect) ? $toselect : array();
$param = ''; $param = '';
if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); $param .= '&contextpage='.urlencode($contextpage);
foreach ($search as $key => $val) }
{ if ($limit > 0 && $limit != $conf->liste_limit) {
if (is_array($search[$key]) && count($search[$key])) foreach ($search[$key] as $skey) $param .= '&search_'.$key.'[]='.urlencode($skey); $param .= '&limit='.urlencode($limit);
else $param .= '&search_'.$key.'='.urlencode($search[$key]); }
foreach ($search as $key => $val) {
if (is_array($search[$key]) && count($search[$key])) {
foreach ($search[$key] as $skey) {
$param .= '&search_'.$key.'[]='.urlencode($skey);
}
} else {
$param .= '&search_'.$key.'='.urlencode($search[$key]);
}
}
if ($optioncss != '') {
$param .= '&optioncss='.urlencode($optioncss);
} }
if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss);
// Add $param from extra fields // Add $param from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
@ -336,12 +360,18 @@ $arrayofmassactions = array(
//'builddoc'=>$langs->trans("PDFMerge"), //'builddoc'=>$langs->trans("PDFMerge"),
); );
//if ($user->rights->stock->supprimer) $arrayofmassactions['predelete']='<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); //if ($user->rights->stock->supprimer) $arrayofmassactions['predelete']='<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete");
if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete','preaffecttag'))) $arrayofmassactions = array(); if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete','preaffecttag'))) {
if ($user->rights->stock->creer) $arrayofmassactions['preaffecttag'] = '<span class="fa fa-tag paddingrightonly"></span>'.$langs->trans("AffectTag"); $arrayofmassactions = array();
}
if ($user->rights->stock->creer) {
$arrayofmassactions['preaffecttag'] = '<span class="fa fa-tag paddingrightonly"></span>'.$langs->trans("AffectTag");
}
$massactionbutton = $form->selectMassAction('', $arrayofmassactions); $massactionbutton = $form->selectMassAction('', $arrayofmassactions);
print '<form action="'.$_SERVER["PHP_SELF"].'" id="searchFormList" method="POST" name="formulaire">'; print '<form action="'.$_SERVER["PHP_SELF"].'" id="searchFormList" method="POST" name="formulaire">';
if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; if ($optioncss != '') {
print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
}
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
print '<input type="hidden" name="action" value="list">'; print '<input type="hidden" name="action" value="list">';
@ -361,16 +391,16 @@ $trackid = 'ware'.$object->id;
include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';
if ($search_all) if ($search_all) {
{ foreach ($fieldstosearchall as $key => $val) {
foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); $fieldstosearchall[$key] = $langs->trans($val);
}
print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>'; print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>';
} }
$moreforfilter = ''; $moreforfilter = '';
if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) {
{
$formcategory = new FormCategory($db); $formcategory = new FormCategory($db);
$moreforfilter .= $formcategory->getFilterBox(Categorie::TYPE_WAREHOUSE, $search_category_list); $moreforfilter .= $formcategory->getFilterBox(Categorie::TYPE_WAREHOUSE, $search_category_list);
} }
@ -381,11 +411,13 @@ if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire)
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook
if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; if (empty($reshook)) {
else $moreforfilter = $hookmanager->resPrint; $moreforfilter .= $hookmanager->resPrint;
} else {
$moreforfilter = $hookmanager->resPrint;
}
if (!empty($moreforfilter)) if (!empty($moreforfilter)) {
{
print '<div class="liste_titre liste_titre_bydiv centpercent">'; print '<div class="liste_titre liste_titre_bydiv centpercent">';
print $moreforfilter; print $moreforfilter;
print '</div>'; print '</div>';
@ -402,21 +434,29 @@ print '<table class="tagtable nobottomiftotal liste'.($moreforfilter ? " listwit
// -------------------------------------------------------------------- // --------------------------------------------------------------------
print '<tr class="liste_titre_filter">'; print '<tr class="liste_titre_filter">';
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{ if ($key == 'statut') {
if ($key == 'statut') { continue; } continue;
}
$cssforfield = (empty($val['css']) ? '' : $val['css']); $cssforfield = (empty($val['css']) ? '' : $val['css']);
if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; if ($key == 'status') {
elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; $cssforfield .= ($cssforfield ? ' ' : '').'center';
elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right'; $cssforfield .= ($cssforfield ? ' ' : '').'center';
if (!empty($arrayfields['t.'.$key]['checked'])) } elseif (in_array($val['type'], array('timestamp'))) {
{ $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
} elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') {
$cssforfield .= ($cssforfield ? ' ' : '').'right';
}
if (!empty($arrayfields['t.'.$key]['checked'])) {
print '<td class="liste_titre'.($cssforfield ? ' '.$cssforfield : '').'">'; print '<td class="liste_titre'.($cssforfield ? ' '.$cssforfield : '').'">';
if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
elseif (strpos($val['type'], 'integer:') === 0 || strpos($val['type'], 'sellist:') === 0) { print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1);
} elseif (strpos($val['type'], 'integer:') === 0 || strpos($val['type'], 'sellist:') === 0) {
print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth150', 1); print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth150', 1);
} elseif (!preg_match('/^(date|timestamp)/', $val['type'])) print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'">'; } elseif (!preg_match('/^(date|timestamp)/', $val['type'])) {
print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'">';
}
print '</td>'; print '</td>';
} }
} }
@ -459,16 +499,21 @@ print '</tr>'."\n";
// -------------------------------------------------------------------- // --------------------------------------------------------------------
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{ if ($key == 'statut') {
if ($key == 'statut') { continue; } continue;
}
$cssforfield = (empty($val['css']) ? '' : $val['css']); $cssforfield = (empty($val['css']) ? '' : $val['css']);
if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; if ($key == 'status') {
elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; $cssforfield .= ($cssforfield ? ' ' : '').'center';
elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right'; $cssforfield .= ($cssforfield ? ' ' : '').'center';
if (!empty($arrayfields['t.'.$key]['checked'])) } elseif (in_array($val['type'], array('timestamp'))) {
{ $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
} elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') {
$cssforfield .= ($cssforfield ? ' ' : '').'right';
}
if (!empty($arrayfields['t.'.$key]['checked'])) {
print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n"; print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n";
} }
} }
@ -504,14 +549,14 @@ print '</tr>'."\n";
// Loop on record // Loop on record
// -------------------------------------------------------------------- // --------------------------------------------------------------------
$i = 0; $i = 0;
if ($num) if ($num) {
{
$warehouse = new Entrepot($db); $warehouse = new Entrepot($db);
while ($i < min($num, $limit)) while ($i < min($num, $limit)) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
if (empty($obj)) break; // Should not happen if (empty($obj)) {
break; // Should not happen
}
$warehouse->id = $obj->rowid; $warehouse->id = $obj->rowid;
$warehouse->ref = $obj->ref; $warehouse->ref = $obj->ref;
@ -527,22 +572,32 @@ if ($num)
// Show here line of result // Show here line of result
print '<tr class="oddeven">'; print '<tr class="oddeven">';
foreach ($warehouse->fields as $key => $val) foreach ($warehouse->fields as $key => $val) {
{ if ($key == 'statut') {
if ($key == 'statut') { continue; } continue;
}
$cssforfield = (empty($val['css']) ? '' : $val['css']); $cssforfield = (empty($val['css']) ? '' : $val['css']);
if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
elseif ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; $cssforfield .= ($cssforfield ? ' ' : '').'center';
} elseif ($key == 'status') {
$cssforfield .= ($cssforfield ? ' ' : '').'center';
}
if (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; if (in_array($val['type'], array('timestamp'))) {
elseif ($key == 'ref') $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
} elseif ($key == 'ref') {
$cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
}
if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $key != 'status') $cssforfield .= ($cssforfield ? ' ' : '').'right'; if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $key != 'status') {
$cssforfield .= ($cssforfield ? ' ' : '').'right';
}
if (!empty($arrayfields['t.'.$key]['checked'])) if (!empty($arrayfields['t.'.$key]['checked'])) {
{
print '<td'.($cssforfield ? ' class="'.$cssforfield.'"' : '').'>'; print '<td'.($cssforfield ? ' class="'.$cssforfield.'"' : '').'>';
if ($key == 'statut') print $warehouse->getLibStatut(5); if ($key == 'statut') {
print $warehouse->getLibStatut(5);
}
if ($key == 'phone') { if ($key == 'phone') {
print dol_print_phone($obj->phone, '', 0, $obj->rowid, 'AC_TEL'); print dol_print_phone($obj->phone, '', 0, $obj->rowid, 'AC_TEL');
} elseif ($key == 'fax') { } elseif ($key == 'fax') {
@ -551,10 +606,13 @@ if ($num)
print $warehouse->showOutputField($val, $key, $warehouse->$key, ''); print $warehouse->showOutputField($val, $key, $warehouse->$key, '');
} }
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
if (!empty($val['isameasure'])) $totalarray['nbfield']++;
{ }
if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; if (!empty($val['isameasure'])) {
if (!$i) {
$totalarray['pos'][$totalarray['nbfield']] = 't.'.$key;
}
$totalarray['val']['t.'.$key] += $warehouse->$key; $totalarray['val']['t.'.$key] += $warehouse->$key;
} }
} }
@ -563,31 +621,47 @@ if ($num)
// Stock qty // Stock qty
if (!empty($arrayfields["stockqty"]['checked'])) { if (!empty($arrayfields["stockqty"]['checked'])) {
print '<td class="right">'.price2num($obj->stockqty, 5).'</td>'; print '<td class="right">'.price2num($obj->stockqty, 5).'</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'stockqty'; $totalarray['nbfield']++;
}
if (!$i) {
$totalarray['pos'][$totalarray['nbfield']] = 'stockqty';
}
} }
// PMP value // PMP value
if (!empty($arrayfields["estimatedvalue"]['checked'])) { if (!empty($arrayfields["estimatedvalue"]['checked'])) {
print '<td class="right">'; print '<td class="right">';
if (price2num($obj->estimatedvalue, 'MT')) print price(price2num($obj->estimatedvalue, 'MT'), 1); if (price2num($obj->estimatedvalue, 'MT')) {
else print ''; print price(price2num($obj->estimatedvalue, 'MT'), 1);
} else {
print '';
}
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'estimatedvalue'; $totalarray['nbfield']++;
}
if (!$i) {
$totalarray['pos'][$totalarray['nbfield']] = 'estimatedvalue';
}
} }
// Selling value // Selling value
if (!empty($arrayfields["estimatedstockvaluesell"]['checked'])) { if (!empty($arrayfields["estimatedstockvaluesell"]['checked'])) {
print '<td class="right">'; print '<td class="right">';
if (empty($conf->global->PRODUIT_MULTIPRICES)) print price(price2num($obj->sellvalue, 'MT'), 1); if (empty($conf->global->PRODUIT_MULTIPRICES)) {
else { print price(price2num($obj->sellvalue, 'MT'), 1);
} else {
$htmltext = $langs->trans("OptionMULTIPRICESIsOn"); $htmltext = $langs->trans("OptionMULTIPRICESIsOn");
print $form->textwithtooltip($langs->trans("Variable"), $htmltext); print $form->textwithtooltip($langs->trans("Variable"), $htmltext);
} }
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'estimatedstockvaluesell'; $totalarray['nbfield']++;
}
if (!$i) {
$totalarray['pos'][$totalarray['nbfield']] = 'estimatedstockvaluesell';
}
} }
// Extra fields // Extra fields
@ -600,19 +674,24 @@ if ($num)
// Status // Status
if (!empty($arrayfields['t.statut']['checked'])) { if (!empty($arrayfields['t.statut']['checked'])) {
print '<td class="center">'.$warehouse->LibStatut($obj->statut, 5).'</td>'; print '<td class="center">'.$warehouse->LibStatut($obj->statut, 5).'</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Action column // Action column
print '<td class="nowrap center">'; print '<td class="nowrap center">';
if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
{
$selected = 0; $selected = 0;
if (in_array($obj->rowid, $arrayofselected)) $selected = 1; if (in_array($obj->rowid, $arrayofselected)) {
$selected = 1;
}
print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>'; print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>';
} }
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
print '</tr>'."\n"; print '</tr>'."\n";
@ -620,8 +699,7 @@ if ($num)
$i++; $i++;
} }
if ($totalnboflines - $offset <= $limit) if ($totalnboflines - $offset <= $limit) {
{
// Show total line // Show total line
include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php';
} }
@ -638,10 +716,11 @@ print '</div>'."\n";
print '</form>'."\n"; print '</form>'."\n";
if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) {
{
$hidegeneratedfilelistifempty = 1; $hidegeneratedfilelistifempty = 1;
if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) {
$hidegeneratedfilelistifempty = 0;
}
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
$formfile = new FormFile($db); $formfile = new FormFile($db);

View File

@ -56,7 +56,9 @@ $idline = GETPOST('idline');
$sortfield = GETPOST('sortfield', 'aZ09comma'); $sortfield = GETPOST('sortfield', 'aZ09comma');
$sortorder = GETPOST('sortorder', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
if (!$sortfield) { if (!$sortfield) {
$sortfield = 'p.ref'; $sortfield = 'p.ref';
@ -69,51 +71,44 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$offset = $limit * $page; $offset = $limit * $page;
$listofdata = array(); $listofdata = array();
if (!empty($_SESSION['massstockmove'])) $listofdata = json_decode($_SESSION['massstockmove'], true); if (!empty($_SESSION['massstockmove'])) {
$listofdata = json_decode($_SESSION['massstockmove'], true);
}
/* /*
* Actions * Actions
*/ */
if ($action == 'addline') if ($action == 'addline') {
{ if (!($id_product > 0)) {
if (!($id_product > 0))
{
$error++; $error++;
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Product")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Product")), null, 'errors');
} }
if (!($id_sw > 0)) if (!($id_sw > 0)) {
{
$error++; $error++;
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WarehouseSource")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WarehouseSource")), null, 'errors');
} }
if (!($id_tw > 0)) if (!($id_tw > 0)) {
{
$error++; $error++;
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WarehouseTarget")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WarehouseTarget")), null, 'errors');
} }
if ($id_sw > 0 && $id_tw == $id_sw) if ($id_sw > 0 && $id_tw == $id_sw) {
{
$error++; $error++;
$langs->load("errors"); $langs->load("errors");
setEventMessages($langs->trans("ErrorWarehouseMustDiffers"), null, 'errors'); setEventMessages($langs->trans("ErrorWarehouseMustDiffers"), null, 'errors');
} }
if (!$qty) if (!$qty) {
{
$error++; $error++;
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Qty")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Qty")), null, 'errors');
} }
// Check a batch number is provided if product need it // Check a batch number is provided if product need it
if (!$error) if (!$error) {
{
$producttmp = new Product($db); $producttmp = new Product($db);
$producttmp->fetch($id_product); $producttmp->fetch($id_product);
if ($producttmp->hasbatch()) if ($producttmp->hasbatch()) {
{ if (empty($batch)) {
if (empty($batch))
{
$error++; $error++;
$langs->load("errors"); $langs->load("errors");
setEventMessages($langs->trans("ErrorTryToMakeMoveOnProductRequiringBatchData", $producttmp->ref), null, 'errors'); setEventMessages($langs->trans("ErrorTryToMakeMoveOnProductRequiringBatchData", $producttmp->ref), null, 'errors');
@ -123,19 +118,19 @@ if ($action == 'addline')
// TODO Check qty is ok for stock move. Note qty may not be enough yet, but we make a check now to report a warning. // TODO Check qty is ok for stock move. Note qty may not be enough yet, but we make a check now to report a warning.
// What is more important is to have qty when doing action 'createmovements' // What is more important is to have qty when doing action 'createmovements'
if (!$error) if (!$error) {
{
// Warning, don't forget lines already added into the $_SESSION['massstockmove'] // Warning, don't forget lines already added into the $_SESSION['massstockmove']
if ($producttmp->hasbatch()) if ($producttmp->hasbatch()) {
{
} else { } else {
} }
} }
if (!$error) if (!$error) {
{ if (count(array_keys($listofdata)) > 0) {
if (count(array_keys($listofdata)) > 0) $id = max(array_keys($listofdata)) + 1; $id = max(array_keys($listofdata)) + 1;
else $id = 1; } else {
$id = 1;
}
$listofdata[$id] = array('id'=>$id, 'id_product'=>$id_product, 'qty'=>$qty, 'id_sw'=>$id_sw, 'id_tw'=>$id_tw, 'batch'=>$batch); $listofdata[$id] = array('id'=>$id, 'id_product'=>$id_product, 'qty'=>$qty, 'id_sw'=>$id_sw, 'id_tw'=>$id_tw, 'batch'=>$batch);
$_SESSION['massstockmove'] = json_encode($listofdata); $_SESSION['massstockmove'] = json_encode($listofdata);
@ -147,31 +142,31 @@ if ($action == 'addline')
} }
} }
if ($action == 'delline' && $idline != '') if ($action == 'delline' && $idline != '') {
{ if (!empty($listofdata[$idline])) {
if (!empty($listofdata[$idline])) unset($listofdata[$idline]); unset($listofdata[$idline]);
if (count($listofdata) > 0) $_SESSION['massstockmove'] = json_encode($listofdata); }
else unset($_SESSION['massstockmove']); if (count($listofdata) > 0) {
$_SESSION['massstockmove'] = json_encode($listofdata);
} else {
unset($_SESSION['massstockmove']);
}
} }
if ($action == 'createmovements') if ($action == 'createmovements') {
{
$error = 0; $error = 0;
if (!GETPOST("label")) if (!GETPOST("label")) {
{
$error++; $error++;
setEventMessages($langs->trans("ErrorFieldRequired"), $langs->transnoentitiesnoconv("MovementLabel"), null, 'errors'); setEventMessages($langs->trans("ErrorFieldRequired"), $langs->transnoentitiesnoconv("MovementLabel"), null, 'errors');
} }
$db->begin(); $db->begin();
if (!$error) if (!$error) {
{
$product = new Product($db); $product = new Product($db);
foreach ($listofdata as $key => $val) // Loop on each movement to do foreach ($listofdata as $key => $val) { // Loop on each movement to do
{
$id = $val['id']; $id = $val['id'];
$id_product = $val['id_product']; $id_product = $val['id_product'];
$id_sw = $val['id_sw']; $id_sw = $val['id_sw'];
@ -181,21 +176,21 @@ if ($action == 'createmovements')
$dlc = -1; // They are loaded later from serial $dlc = -1; // They are loaded later from serial
$dluo = -1; // They are loaded later from serial $dluo = -1; // They are loaded later from serial
if (!$error && $id_sw <> $id_tw && is_numeric($qty) && $id_product) if (!$error && $id_sw <> $id_tw && is_numeric($qty) && $id_product) {
{
$result = $product->fetch($id_product); $result = $product->fetch($id_product);
$product->load_stock('novirtual'); // Load array product->stock_warehouse $product->load_stock('novirtual'); // Load array product->stock_warehouse
// Define value of products moved // Define value of products moved
$pricesrc = 0; $pricesrc = 0;
if (!empty($product->pmp)) $pricesrc = $product->pmp; if (!empty($product->pmp)) {
$pricesrc = $product->pmp;
}
$pricedest = $pricesrc; $pricedest = $pricesrc;
//print 'price src='.$pricesrc.', price dest='.$pricedest;exit; //print 'price src='.$pricesrc.', price dest='.$pricedest;exit;
if (empty($conf->productbatch->enabled) || !$product->hasbatch()) // If product does not need lot/serial if (empty($conf->productbatch->enabled) || !$product->hasbatch()) { // If product does not need lot/serial
{
// Remove stock // Remove stock
$result1 = $product->correct_stock( $result1 = $product->correct_stock(
$user, $user,
@ -206,8 +201,7 @@ if ($action == 'createmovements')
$pricesrc, $pricesrc,
GETPOST("codemove") GETPOST("codemove")
); );
if ($result1 < 0) if ($result1 < 0) {
{
$error++; $error++;
setEventMessages($product->errors, $product->errorss, 'errors'); setEventMessages($product->errors, $product->errorss, 'errors');
} }
@ -222,15 +216,13 @@ if ($action == 'createmovements')
$pricedest, $pricedest,
GETPOST("codemove") GETPOST("codemove")
); );
if ($result2 < 0) if ($result2 < 0) {
{
$error++; $error++;
setEventMessages($product->errors, $product->errorss, 'errors'); setEventMessages($product->errors, $product->errorss, 'errors');
} }
} else { } else {
$arraybatchinfo = $product->loadBatchInfo($batch); $arraybatchinfo = $product->loadBatchInfo($batch);
if (count($arraybatchinfo) > 0) if (count($arraybatchinfo) > 0) {
{
$firstrecord = array_shift($arraybatchinfo); $firstrecord = array_shift($arraybatchinfo);
$dlc = $firstrecord['eatby']; $dlc = $firstrecord['eatby'];
$dluo = $firstrecord['sellby']; $dluo = $firstrecord['sellby'];
@ -253,8 +245,7 @@ if ($action == 'createmovements')
$batch, $batch,
GETPOST("codemove") GETPOST("codemove")
); );
if ($result1 < 0) if ($result1 < 0) {
{
$error++; $error++;
setEventMessages($product->errors, $product->errorss, 'errors'); setEventMessages($product->errors, $product->errorss, 'errors');
} }
@ -272,8 +263,7 @@ if ($action == 'createmovements')
$batch, $batch,
GETPOST("codemove") GETPOST("codemove")
); );
if ($result2 < 0) if ($result2 < 0) {
{
$error++; $error++;
setEventMessages($product->errors, $product->errorss, 'errors'); setEventMessages($product->errors, $product->errorss, 'errors');
} }
@ -285,8 +275,7 @@ if ($action == 'createmovements')
} }
} }
if (!$error) if (!$error) {
{
unset($_SESSION['massstockmove']); unset($_SESSION['massstockmove']);
$db->commit(); $db->commit();
@ -362,7 +351,9 @@ print '</td>';
// Product // Product
print '<td class="titlefield">'; print '<td class="titlefield">';
$filtertype = 0; $filtertype = 0;
if (!empty($conf->global->STOCK_SUPPORTS_SERVICES)) $filtertype = ''; if (!empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
$filtertype = '';
}
if ($conf->global->PRODUIT_LIMIT_SIZE <= 0) { if ($conf->global->PRODUIT_LIMIT_SIZE <= 0) {
$limit = ''; $limit = '';
} else { } else {
@ -372,8 +363,7 @@ if ($conf->global->PRODUIT_LIMIT_SIZE <= 0) {
$form->select_produits($id_product, 'productid', $filtertype, $limit, 0, -1, 2, '', 1, array(), 0, '1', 0, 'minwidth200imp maxwidth300', 1); $form->select_produits($id_product, 'productid', $filtertype, $limit, 0, -1, 2, '', 1, array(), 0, '1', 0, 'minwidth200imp maxwidth300', 1);
print '</td>'; print '</td>';
// Batch number // Batch number
if ($conf->productbatch->enabled) if ($conf->productbatch->enabled) {
{
print '<td>'; print '<td>';
print '<input type="text" name="batch" class="flat maxwidth50" value="'.$batch.'">'; print '<input type="text" name="batch" class="flat maxwidth50" value="'.$batch.'">';
print '</td>'; print '</td>';
@ -386,8 +376,7 @@ print '<td class="right"><input type="submit" class="button" name="addline" valu
print '</tr>'; print '</tr>';
foreach ($listofdata as $key => $val) foreach ($listofdata as $key => $val) {
{
$productstatic->fetch($val['id_product']); $productstatic->fetch($val['id_product']);
$warehousestatics->fetch($val['id_sw']); $warehousestatics->fetch($val['id_sw']);
$warehousestatict->fetch($val['id_tw']); $warehousestatict->fetch($val['id_tw']);
@ -402,8 +391,7 @@ foreach ($listofdata as $key => $val)
print '<td>'; print '<td>';
print $productstatic->getNomUrl(1).' - '.$productstatic->label; print $productstatic->getNomUrl(1).' - '.$productstatic->label;
print '</td>'; print '</td>';
if ($conf->productbatch->enabled) if ($conf->productbatch->enabled) {
{
print '<td>'; print '<td>';
print $val['batch']; print $val['batch'];
print '</td>'; print '</td>';

View File

@ -44,7 +44,9 @@ if (!empty($conf->projet->enabled)) {
// Load translation files required by the page // Load translation files required by the page
$langs->loadLangs(array('products', 'stocks', 'orders')); $langs->loadLangs(array('products', 'stocks', 'orders'));
if (!empty($conf->productbatch->enabled)) $langs->load("productbatch"); if (!empty($conf->productbatch->enabled)) {
$langs->load("productbatch");
}
// Security check // Security check
$result = restrictedArea($user, 'stock'); $result = restrictedArea($user, 'stock');
@ -75,10 +77,16 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
$sortfield = GETPOST("sortfield", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
if (!$sortfield) $sortfield = "m.datem"; if (!$sortfield) {
if (!$sortorder) $sortorder = "DESC"; $sortfield = "m.datem";
}
if (!$sortorder) {
$sortorder = "DESC";
}
$pdluoid = GETPOST('pdluoid', 'int'); $pdluoid = GETPOST('pdluoid', 'int');
@ -123,18 +131,23 @@ $usercandelete = (($user->rights->stock->mouvement->supprimer));
* Actions * Actions
*/ */
if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } if (GETPOST('cancel', 'alpha')) {
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } $action = 'list'; $massaction = '';
}
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
$massaction = '';
}
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
// Do we click on purge search criteria ? // Do we click on purge search criteria ?
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // Both test are required to be compatible with all browsers if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // Both test are required to be compatible with all browsers
{
$year = ''; $year = '';
$month = ''; $month = '';
$search_ref = ''; $search_ref = '';
@ -153,39 +166,35 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x'
} }
// Correct stock // Correct stock
if ($action == "correct_stock") if ($action == "correct_stock") {
{
$product = new Product($db); $product = new Product($db);
if (!empty($product_id)) $result = $product->fetch($product_id); if (!empty($product_id)) {
$result = $product->fetch($product_id);
}
$error = 0; $error = 0;
if (empty($product_id)) if (empty($product_id)) {
{
$error++; $error++;
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Product")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Product")), null, 'errors');
$action = 'correction'; $action = 'correction';
} }
if (!is_numeric($_POST["nbpiece"])) if (!is_numeric($_POST["nbpiece"])) {
{
$error++; $error++;
setEventMessages($langs->trans("ErrorFieldMustBeANumeric", $langs->transnoentitiesnoconv("NumberOfUnit")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldMustBeANumeric", $langs->transnoentitiesnoconv("NumberOfUnit")), null, 'errors');
$action = 'correction'; $action = 'correction';
} }
if (!$error) if (!$error) {
{
$origin_element = ''; $origin_element = '';
$origin_id = null; $origin_id = null;
if (GETPOST('projectid', 'int')) if (GETPOST('projectid', 'int')) {
{
$origin_element = 'project'; $origin_element = 'project';
$origin_id = GETPOST('projectid', 'int'); $origin_id = GETPOST('projectid', 'int');
} }
if ($product->hasbatch()) if ($product->hasbatch()) {
{
$batch = GETPOST('batch_number', 'alpha'); $batch = GETPOST('batch_number', 'alpha');
//$eatby=GETPOST('eatby'); //$eatby=GETPOST('eatby');
@ -221,8 +230,7 @@ if ($action == "correct_stock")
); // We do not change value of stock for a correction ); // We do not change value of stock for a correction
} }
if ($result > 0) if ($result > 0) {
{
header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
exit; exit;
} else { } else {
@ -232,57 +240,52 @@ if ($action == "correct_stock")
} }
} }
if (!$error) $action = ''; if (!$error) {
$action = '';
}
} }
// Transfer stock from a warehouse to another warehouse // Transfer stock from a warehouse to another warehouse
if ($action == "transfert_stock" && !$cancel) if ($action == "transfert_stock" && !$cancel) {
{
$product = new Product($db); $product = new Product($db);
if (!empty($product_id)) $result = $product->fetch($product_id); if (!empty($product_id)) {
$result = $product->fetch($product_id);
}
if (!(GETPOST("id_entrepot_destination", 'int') > 0)) if (!(GETPOST("id_entrepot_destination", 'int') > 0)) {
{
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
$error++; $error++;
$action = 'transfert'; $action = 'transfert';
} }
if (empty($product_id)) if (empty($product_id)) {
{
$error++; $error++;
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Product")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Product")), null, 'errors');
$action = 'transfert'; $action = 'transfert';
} }
if (!GETPOST("nbpiece", 'int')) if (!GETPOST("nbpiece", 'int')) {
{
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NumberOfUnit")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NumberOfUnit")), null, 'errors');
$error++; $error++;
$action = 'transfert'; $action = 'transfert';
} }
if ($id == GETPOST("id_entrepot_destination", 'int')) if ($id == GETPOST("id_entrepot_destination", 'int')) {
{
setEventMessages($langs->trans("ErrorSrcAndTargetWarehouseMustDiffers"), null, 'errors'); setEventMessages($langs->trans("ErrorSrcAndTargetWarehouseMustDiffers"), null, 'errors');
$error++; $error++;
$action = 'transfert'; $action = 'transfert';
} }
if (!empty($conf->productbatch->enabled)) if (!empty($conf->productbatch->enabled)) {
{
$product = new Product($db); $product = new Product($db);
$result = $product->fetch($product_id); $result = $product->fetch($product_id);
if ($product->hasbatch() && !GETPOST("batch_number", 'alpha')) if ($product->hasbatch() && !GETPOST("batch_number", 'alpha')) {
{
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("batch_number")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("batch_number")), null, 'errors');
$error++; $error++;
$action = 'transfert'; $action = 'transfert';
} }
} }
if (!$error) if (!$error) {
{ if ($id) {
if ($id)
{
$object = new Entrepot($db); $object = new Entrepot($db);
$result = $object->fetch($id); $result = $object->fetch($id);
@ -292,18 +295,17 @@ if ($action == "transfert_stock" && !$cancel)
// Define value of products moved // Define value of products moved
$pricesrc = 0; $pricesrc = 0;
if (isset($product->pmp)) $pricesrc = $product->pmp; if (isset($product->pmp)) {
$pricesrc = $product->pmp;
}
$pricedest = $pricesrc; $pricedest = $pricesrc;
if ($product->hasbatch()) if ($product->hasbatch()) {
{
$pdluo = new Productbatch($db); $pdluo = new Productbatch($db);
if ($pdluoid > 0) if ($pdluoid > 0) {
{
$result = $pdluo->fetch($pdluoid); $result = $pdluo->fetch($pdluoid);
if ($result) if ($result) {
{
$srcwarehouseid = $pdluo->warehouseid; $srcwarehouseid = $pdluo->warehouseid;
$batch = $pdluo->batch; $batch = $pdluo->batch;
$eatby = $pdluo->eatby; $eatby = $pdluo->eatby;
@ -319,8 +321,7 @@ if ($action == "transfert_stock" && !$cancel)
$sellby = $d_sellby; $sellby = $d_sellby;
} }
if (!$error) if (!$error) {
{
// Remove stock // Remove stock
$result1 = $product->correct_stock_batch( $result1 = $product->correct_stock_batch(
$user, $user,
@ -371,12 +372,10 @@ if ($action == "transfert_stock" && !$cancel)
GETPOST('inventorycode', 'alpha') GETPOST('inventorycode', 'alpha')
); );
} }
if (!$error && $result1 >= 0 && $result2 >= 0) if (!$error && $result1 >= 0 && $result2 >= 0) {
{
$db->commit(); $db->commit();
if ($backtopage) if ($backtopage) {
{
header("Location: ".$backtopage); header("Location: ".$backtopage);
exit; exit;
} else { } else {
@ -403,8 +402,7 @@ $permissiontoadd = $user->rights->stock->creer;
include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
if (empty($reshook) && $action != 'remove_file') if (empty($reshook) && $action != 'remove_file') {
{
$objectclass = 'MouvementStock'; $objectclass = 'MouvementStock';
$objectlabel = 'Movements'; $objectlabel = 'Movements';
$permissiontoread = $user->rights->stock->lire; $permissiontoread = $user->rights->stock->lire;
@ -427,7 +425,9 @@ $userstatic = new User($db);
$form = new Form($db); $form = new Form($db);
$formother = new FormOther($db); $formother = new FormOther($db);
$formproduct = new FormProduct($db); $formproduct = new FormProduct($db);
if (!empty($conf->projet->enabled)) $formproject = new FormProjets($db); if (!empty($conf->projet->enabled)) {
$formproject = new FormProjets($db);
}
$sql = "SELECT p.rowid, p.ref as product_ref, p.label as produit, p.tobatch, p.fk_product_type as type, p.entity,"; $sql = "SELECT p.rowid, p.ref as product_ref, p.label as produit, p.tobatch, p.fk_product_type as type, p.entity,";
$sql .= " e.ref as warehouse_ref, e.rowid as entrepot_id, e.lieu,"; $sql .= " e.ref as warehouse_ref, e.rowid as entrepot_id, e.lieu,";
@ -438,7 +438,9 @@ $sql .= " pl.rowid as lotid, pl.eatby, pl.sellby,";
$sql .= " u.login, u.photo, u.lastname, u.firstname"; $sql .= " u.login, u.photo, u.lastname, u.firstname";
// Add fields from extrafields // Add fields from extrafields
if (!empty($extrafields->attributes[$object->table_element]['label'])) { if (!empty($extrafields->attributes[$object->table_element]['label'])) {
foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
$sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : '');
}
} }
// Add fields from hooks // Add fields from hooks
$parameters = array(); $parameters = array();
@ -447,27 +449,57 @@ $sql .= $hookmanager->resPrint;
$sql .= " FROM ".MAIN_DB_PREFIX."entrepot as e,"; $sql .= " FROM ".MAIN_DB_PREFIX."entrepot as e,";
$sql .= " ".MAIN_DB_PREFIX."product as p,"; $sql .= " ".MAIN_DB_PREFIX."product as p,";
$sql .= " ".MAIN_DB_PREFIX."stock_mouvement as m"; $sql .= " ".MAIN_DB_PREFIX."stock_mouvement as m";
if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (m.rowid = ef.fk_object)"; if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) {
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (m.rowid = ef.fk_object)";
}
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u ON m.fk_user_author = u.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u ON m.fk_user_author = u.rowid";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_lot as pl ON m.batch = pl.batch AND m.fk_product = pl.fk_product"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_lot as pl ON m.batch = pl.batch AND m.fk_product = pl.fk_product";
$sql .= " WHERE m.fk_product = p.rowid"; $sql .= " WHERE m.fk_product = p.rowid";
if ($msid > 0) $sql .= " AND m.rowid = ".$msid; if ($msid > 0) {
$sql .= " AND m.rowid = ".$msid;
}
$sql .= " AND m.fk_entrepot = e.rowid"; $sql .= " AND m.fk_entrepot = e.rowid";
$sql .= " AND e.entity IN (".getEntity('stock').")"; $sql .= " AND e.entity IN (".getEntity('stock').")";
if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) $sql .= " AND p.fk_product_type = 0"; if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
if ($id > 0) $sql .= " AND e.rowid ='".$id."'"; $sql .= " AND p.fk_product_type = 0";
}
if ($id > 0) {
$sql .= " AND e.rowid ='".$id."'";
}
$sql .= dolSqlDateFilter('m.datem', 0, $month, $year); $sql .= dolSqlDateFilter('m.datem', 0, $month, $year);
if ($idproduct > 0) $sql .= " AND p.rowid = ".((int) $idproduct); if ($idproduct > 0) {
if (!empty($search_ref)) $sql .= natural_search('m.rowid', $search_ref, 1); $sql .= " AND p.rowid = ".((int) $idproduct);
if (!empty($search_movement)) $sql .= natural_search('m.label', $search_movement); }
if (!empty($search_inventorycode)) $sql .= natural_search('m.inventorycode', $search_inventorycode); if (!empty($search_ref)) {
if (!empty($search_product_ref)) $sql .= natural_search('p.ref', $search_product_ref); $sql .= natural_search('m.rowid', $search_ref, 1);
if (!empty($search_product)) $sql .= natural_search('p.label', $search_product); }
if ($search_warehouse != '' && $search_warehouse != '-1') $sql .= natural_search('e.rowid', $search_warehouse, 2); if (!empty($search_movement)) {
if (!empty($search_user)) $sql .= natural_search('u.login', $search_user); $sql .= natural_search('m.label', $search_movement);
if (!empty($search_batch)) $sql .= natural_search('m.batch', $search_batch); }
if ($search_qty != '') $sql .= natural_search('m.value', $search_qty, 1); if (!empty($search_inventorycode)) {
if ($search_type_mouvement != '' && $search_type_mouvement != '-1') $sql .= natural_search('m.type_mouvement', $search_type_mouvement, 2); $sql .= natural_search('m.inventorycode', $search_inventorycode);
}
if (!empty($search_product_ref)) {
$sql .= natural_search('p.ref', $search_product_ref);
}
if (!empty($search_product)) {
$sql .= natural_search('p.label', $search_product);
}
if ($search_warehouse != '' && $search_warehouse != '-1') {
$sql .= natural_search('e.rowid', $search_warehouse, 2);
}
if (!empty($search_user)) {
$sql .= natural_search('u.login', $search_user);
}
if (!empty($search_batch)) {
$sql .= natural_search('m.batch', $search_batch);
}
if ($search_qty != '') {
$sql .= natural_search('m.value', $search_qty, 1);
}
if ($search_type_mouvement != '' && $search_type_mouvement != '-1') {
$sql .= natural_search('m.type_mouvement', $search_type_mouvement, 2);
}
// Add where from extra fields // Add where from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
// Add where from hooks // Add where from hooks
@ -477,12 +509,10 @@ $sql .= $hookmanager->resPrint;
$sql .= $db->order($sortfield, $sortorder); $sql .= $db->order($sortfield, $sortorder);
$nbtotalofrecords = ''; $nbtotalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
{
$result = $db->query($sql); $result = $db->query($sql);
$nbtotalofrecords = $db->num_rows($result); $nbtotalofrecords = $db->num_rows($result);
if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0
{
$page = 0; $page = 0;
$offset = 0; $offset = 0;
} }
@ -492,20 +522,16 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$product = new Product($db); $product = new Product($db);
$object = new Entrepot($db); $object = new Entrepot($db);
if ($idproduct > 0) if ($idproduct > 0) {
{
$product->fetch($idproduct); $product->fetch($idproduct);
} }
if ($id > 0 || $ref) if ($id > 0 || $ref) {
{
$result = $object->fetch($id, $ref); $result = $object->fetch($id, $ref);
if ($result < 0) if ($result < 0) {
{
dol_print_error($db); dol_print_error($db);
} }
} }
@ -517,18 +543,20 @@ if ($resql)
$i = 0; $i = 0;
$help_url = 'EN:Module_Stocks_En|FR:Module_Stock|ES:M&oacute;dulo_Stocks'; $help_url = 'EN:Module_Stocks_En|FR:Module_Stock|ES:M&oacute;dulo_Stocks';
if ($msid) $texte = $langs->trans('StockMovementForId', $msid); if ($msid) {
else { $texte = $langs->trans('StockMovementForId', $msid);
} else {
$texte = $langs->trans("ListOfStockMovements"); $texte = $langs->trans("ListOfStockMovements");
if ($id) $texte .= ' ('.$langs->trans("ForThisWarehouse").')'; if ($id) {
$texte .= ' ('.$langs->trans("ForThisWarehouse").')';
}
} }
llxHeader("", $texte, $help_url); llxHeader("", $texte, $help_url);
/* /*
* Show tab only if we ask a particular warehouse * Show tab only if we ask a particular warehouse
*/ */
if ($object->id > 0) if ($object->id > 0) {
{
$head = stock_prepare_head($object); $head = stock_prepare_head($object);
print dol_get_fiche_head($head, 'movements', $langs->trans("Warehouse"), -1, 'stock'); print dol_get_fiche_head($head, 'movements', $langs->trans("Warehouse"), -1, 'stock');
@ -541,7 +569,9 @@ if ($resql)
$morehtmlref .= '</div>'; $morehtmlref .= '</div>';
$shownav = 1; $shownav = 1;
if ($user->socid && !in_array('stock', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; if ($user->socid && !in_array('stock', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) {
$shownav = 0;
}
dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref', 'ref', $morehtmlref); dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref', 'ref', $morehtmlref);
@ -590,8 +620,7 @@ if ($resql)
$sql .= " FROM ".MAIN_DB_PREFIX."stock_mouvement as m"; $sql .= " FROM ".MAIN_DB_PREFIX."stock_mouvement as m";
$sql .= " WHERE m.fk_entrepot = ".(int) $object->id; $sql .= " WHERE m.fk_entrepot = ".(int) $object->id;
$resqlbis = $db->query($sql); $resqlbis = $db->query($sql);
if ($resqlbis) if ($resqlbis) {
{
$obj = $db->fetch_object($resqlbis); $obj = $db->fetch_object($resqlbis);
$lastmovementdate = $db->jdate($obj->datem); $lastmovementdate = $db->jdate($obj->datem);
} else { } else {
@ -599,8 +628,7 @@ if ($resql)
} }
print '<tr><td>'.$langs->trans("LastMovement").'</td><td>'; print '<tr><td>'.$langs->trans("LastMovement").'</td><td>';
if ($lastmovementdate) if ($lastmovementdate) {
{
print dol_print_date($lastmovementdate, 'dayhour'); print dol_print_date($lastmovementdate, 'dayhour');
} else { } else {
print $langs->trans("None"); print $langs->trans("None");
@ -622,8 +650,7 @@ if ($resql)
/* /*
* Correct stock * Correct stock
*/ */
if ($action == "correction") if ($action == "correction") {
{
include DOL_DOCUMENT_ROOT.'/product/stock/tpl/stockcorrection.tpl.php'; include DOL_DOCUMENT_ROOT.'/product/stock/tpl/stockcorrection.tpl.php';
print '<br>'; print '<br>';
} }
@ -631,8 +658,7 @@ if ($resql)
/* /*
* Transfer of units * Transfer of units
*/ */
if ($action == "transfert") if ($action == "transfert") {
{
include DOL_DOCUMENT_ROOT.'/product/stock/tpl/stocktransfer.tpl.php'; include DOL_DOCUMENT_ROOT.'/product/stock/tpl/stocktransfer.tpl.php';
print '<br>'; print '<br>';
} }
@ -644,17 +670,14 @@ if ($resql)
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
if ((empty($action) || $action == 'list') && $id > 0) if ((empty($action) || $action == 'list') && $id > 0) {
{
print "<div class=\"tabsAction\">\n"; print "<div class=\"tabsAction\">\n";
if ($user->rights->stock->mouvement->creer) if ($user->rights->stock->mouvement->creer) {
{
print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$id.'&action=correction">'.$langs->trans("CorrectStock").'</a>'; print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$id.'&action=correction">'.$langs->trans("CorrectStock").'</a>';
} }
if ($user->rights->stock->mouvement->creer) if ($user->rights->stock->mouvement->creer) {
{
print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$id.'&action=transfert">'.$langs->trans("TransferStock").'</a>'; print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$id.'&action=transfert">'.$langs->trans("TransferStock").'</a>';
} }
@ -662,18 +685,42 @@ if ($resql)
} }
$param = ''; $param = '';
if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); $param .= '&contextpage='.urlencode($contextpage);
if ($id > 0) $param .= '&id='.urlencode($id); }
if ($search_movement) $param .= '&search_movement='.urlencode($search_movement); if ($limit > 0 && $limit != $conf->liste_limit) {
if ($search_inventorycode) $param .= '&search_inventorycode='.urlencode($search_inventorycode); $param .= '&limit='.urlencode($limit);
if ($search_type_mouvement) $param .= '&search_type_mouvement='.urlencode($search_type_mouvement); }
if ($search_product_ref) $param .= '&search_product_ref='.urlencode($search_product_ref); if ($id > 0) {
if ($search_product) $param .= '&search_product='.urlencode($search_product); $param .= '&id='.urlencode($id);
if ($search_batch) $param .= '&search_batch='.urlencode($search_batch); }
if ($search_warehouse > 0) $param .= '&search_warehouse='.urlencode($search_warehouse); if ($search_movement) {
if ($search_user) $param .= '&search_user='.urlencode($search_user); $param .= '&search_movement='.urlencode($search_movement);
if ($idproduct > 0) $param .= '&idproduct='.urlencode($idproduct); }
if ($search_inventorycode) {
$param .= '&search_inventorycode='.urlencode($search_inventorycode);
}
if ($search_type_mouvement) {
$param .= '&search_type_mouvement='.urlencode($search_type_mouvement);
}
if ($search_product_ref) {
$param .= '&search_product_ref='.urlencode($search_product_ref);
}
if ($search_product) {
$param .= '&search_product='.urlencode($search_product);
}
if ($search_batch) {
$param .= '&search_batch='.urlencode($search_batch);
}
if ($search_warehouse > 0) {
$param .= '&search_warehouse='.urlencode($search_warehouse);
}
if ($search_user) {
$param .= '&search_user='.urlencode($search_user);
}
if ($idproduct > 0) {
$param .= '&idproduct='.urlencode($idproduct);
}
// Add $param from extra fields // Add $param from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
@ -683,11 +730,15 @@ if ($resql)
// 'builddoc'=>$langs->trans("PDFMerge"), // 'builddoc'=>$langs->trans("PDFMerge"),
); );
//if ($user->rights->stock->supprimer) $arrayofmassactions['predelete']='<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); //if ($user->rights->stock->supprimer) $arrayofmassactions['predelete']='<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete");
if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); if (in_array($massaction, array('presend', 'predelete'))) {
$arrayofmassactions = array();
}
$massactionbutton = $form->selectMassAction('', $arrayofmassactions); $massactionbutton = $form->selectMassAction('', $arrayofmassactions);
print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; if ($optioncss != '') {
print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
}
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
print '<input type="hidden" name="action" value="list">'; print '<input type="hidden" name="action" value="list">';
@ -695,14 +746,20 @@ if ($resql)
print '<input type="hidden" name="sortorder" value="'.$sortorder.'">'; print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
print '<input type="hidden" name="page" value="'.$page.'">'; print '<input type="hidden" name="page" value="'.$page.'">';
print '<input type="hidden" name="contextpage" value="'.$contextpage.'">'; print '<input type="hidden" name="contextpage" value="'.$contextpage.'">';
if ($id > 0) print '<input type="hidden" name="id" value="'.$id.'">'; if ($id > 0) {
print '<input type="hidden" name="id" value="'.$id.'">';
}
if ($id > 0) print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, '', 0, '', '', $limit); if ($id > 0) {
else print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'generic', 0, '', '', $limit); print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, '', 0, '', '', $limit);
} else {
print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'generic', 0, '', '', $limit);
}
if ($sall) if ($sall) {
{ foreach ($fieldstosearchall as $key => $val) {
foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); $fieldstosearchall[$key] = $langs->trans($val);
}
print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>'; print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>';
} }
@ -710,11 +767,13 @@ if ($resql)
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook
if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; if (empty($reshook)) {
else $moreforfilter = $hookmanager->resPrint; $moreforfilter .= $hookmanager->resPrint;
} else {
$moreforfilter = $hookmanager->resPrint;
}
if (!empty($moreforfilter)) if (!empty($moreforfilter)) {
{
print '<div class="liste_titre liste_titre_bydiv centpercent">'; print '<div class="liste_titre liste_titre_bydiv centpercent">';
print $moreforfilter; print $moreforfilter;
print '</div>'; print '</div>';
@ -728,84 +787,74 @@ if ($resql)
// Fields title search // Fields title search
print '<tr class="liste_titre_filter">'; print '<tr class="liste_titre_filter">';
if (!empty($arrayfields['m.rowid']['checked'])) if (!empty($arrayfields['m.rowid']['checked'])) {
{
// Ref // Ref
print '<td class="liste_titre left">'; print '<td class="liste_titre left">';
print '<input class="flat maxwidth25" type="text" name="search_ref" value="'.dol_escape_htmltag($search_ref).'">'; print '<input class="flat maxwidth25" type="text" name="search_ref" value="'.dol_escape_htmltag($search_ref).'">';
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['m.datem']['checked'])) if (!empty($arrayfields['m.datem']['checked'])) {
{
print '<td class="liste_titre nowraponall">'; print '<td class="liste_titre nowraponall">';
print '<input class="flat" type="text" size="2" maxlength="2" placeholder="'.dol_escape_htmltag($langs->trans("Month")).'" name="month" value="'.$month.'">'; print '<input class="flat" type="text" size="2" maxlength="2" placeholder="'.dol_escape_htmltag($langs->trans("Month")).'" name="month" value="'.$month.'">';
if (empty($conf->productbatch->enabled)) print '&nbsp;'; if (empty($conf->productbatch->enabled)) {
print '&nbsp;';
}
//else print '<br>'; //else print '<br>';
$syear = $year ? $year : -1; $syear = $year ? $year : -1;
print '<input class="flat maxwidth50" type="text" maxlength="4" placeholder="'.dol_escape_htmltag($langs->trans("Year")).'" name="year" value="'.($syear > 0 ? $syear : '').'">'; print '<input class="flat maxwidth50" type="text" maxlength="4" placeholder="'.dol_escape_htmltag($langs->trans("Year")).'" name="year" value="'.($syear > 0 ? $syear : '').'">';
//print $formother->selectyear($syear,'year',1, 20, 5); //print $formother->selectyear($syear,'year',1, 20, 5);
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['p.ref']['checked'])) if (!empty($arrayfields['p.ref']['checked'])) {
{
// Product Ref // Product Ref
print '<td class="liste_titre left">'; print '<td class="liste_titre left">';
print '<input class="flat maxwidth75" type="text" name="search_product_ref" value="'.dol_escape_htmltag($idproduct ? $product->ref : $search_product_ref).'">'; print '<input class="flat maxwidth75" type="text" name="search_product_ref" value="'.dol_escape_htmltag($idproduct ? $product->ref : $search_product_ref).'">';
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['p.label']['checked'])) if (!empty($arrayfields['p.label']['checked'])) {
{
// Product label // Product label
print '<td class="liste_titre left">'; print '<td class="liste_titre left">';
print '<input class="flat maxwidth100" type="text" name="search_product" value="'.dol_escape_htmltag($idproduct ? $product->label : $search_product).'">'; print '<input class="flat maxwidth100" type="text" name="search_product" value="'.dol_escape_htmltag($idproduct ? $product->label : $search_product).'">';
print '</td>'; print '</td>';
} }
// Batch // Batch
if (!empty($arrayfields['m.batch']['checked'])) if (!empty($arrayfields['m.batch']['checked'])) {
{
print '<td class="liste_titre center"><input class="flat maxwidth75" type="text" name="search_batch" value="'.dol_escape_htmltag($search_batch).'"></td>'; print '<td class="liste_titre center"><input class="flat maxwidth75" type="text" name="search_batch" value="'.dol_escape_htmltag($search_batch).'"></td>';
} }
if (!empty($arrayfields['pl.eatby']['checked'])) if (!empty($arrayfields['pl.eatby']['checked'])) {
{
print '<td class="liste_titre left">'; print '<td class="liste_titre left">';
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['pl.sellby']['checked'])) if (!empty($arrayfields['pl.sellby']['checked'])) {
{
print '<td class="liste_titre left">'; print '<td class="liste_titre left">';
print '</td>'; print '</td>';
} }
// Warehouse // Warehouse
if (!empty($arrayfields['e.ref']['checked'])) if (!empty($arrayfields['e.ref']['checked'])) {
{
print '<td class="liste_titre maxwidthonsmartphone left">'; print '<td class="liste_titre maxwidthonsmartphone left">';
//print '<input class="flat" type="text" size="8" name="search_warehouse" value="'.($search_warehouse).'">'; //print '<input class="flat" type="text" size="8" name="search_warehouse" value="'.($search_warehouse).'">';
print $formproduct->selectWarehouses($search_warehouse, 'search_warehouse', 'warehouseopen,warehouseinternal', 1, 0, 0, '', 0, 0, null, 'maxwidth200'); print $formproduct->selectWarehouses($search_warehouse, 'search_warehouse', 'warehouseopen,warehouseinternal', 1, 0, 0, '', 0, 0, null, 'maxwidth200');
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['m.fk_user_author']['checked'])) if (!empty($arrayfields['m.fk_user_author']['checked'])) {
{
// Author // Author
print '<td class="liste_titre left">'; print '<td class="liste_titre left">';
print '<input class="flat" type="text" size="6" name="search_user" value="'.dol_escape_htmltag($search_user).'">'; print '<input class="flat" type="text" size="6" name="search_user" value="'.dol_escape_htmltag($search_user).'">';
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['m.inventorycode']['checked'])) if (!empty($arrayfields['m.inventorycode']['checked'])) {
{
// Inventory code // Inventory code
print '<td class="liste_titre left">'; print '<td class="liste_titre left">';
print '<input class="flat" type="text" size="4" name="search_inventorycode" value="'.dol_escape_htmltag($search_inventorycode).'">'; print '<input class="flat" type="text" size="4" name="search_inventorycode" value="'.dol_escape_htmltag($search_inventorycode).'">';
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['m.label']['checked'])) if (!empty($arrayfields['m.label']['checked'])) {
{
// Label of movement // Label of movement
print '<td class="liste_titre left">'; print '<td class="liste_titre left">';
print '<input class="flat" type="text" size="8" name="search_movement" value="'.dol_escape_htmltag($search_movement).'">'; print '<input class="flat" type="text" size="8" name="search_movement" value="'.dol_escape_htmltag($search_movement).'">';
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['m.type_mouvement']['checked'])) if (!empty($arrayfields['m.type_mouvement']['checked'])) {
{
// Type of movement // Type of movement
print '<td class="liste_titre center">'; print '<td class="liste_titre center">';
//print '<input class="flat" type="text" size="3" name="search_type_mouvement" value="'.dol_escape_htmltag($search_type_mouvement).'">'; //print '<input class="flat" type="text" size="3" name="search_type_mouvement" value="'.dol_escape_htmltag($search_type_mouvement).'">';
@ -821,22 +870,19 @@ if ($resql)
// print $formproduct->selectWarehouses($search_warehouse, 'search_warehouse', 'warehouseopen,warehouseinternal', 1, 0, 0, '', 0, 0, null, 'maxwidth200'); // print $formproduct->selectWarehouses($search_warehouse, 'search_warehouse', 'warehouseopen,warehouseinternal', 1, 0, 0, '', 0, 0, null, 'maxwidth200');
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['origin']['checked'])) if (!empty($arrayfields['origin']['checked'])) {
{
// Origin of movement // Origin of movement
print '<td class="liste_titre left">'; print '<td class="liste_titre left">';
print '&nbsp; '; print '&nbsp; ';
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['m.value']['checked'])) if (!empty($arrayfields['m.value']['checked'])) {
{
// Qty // Qty
print '<td class="liste_titre right">'; print '<td class="liste_titre right">';
print '<input class="flat" type="text" size="4" name="search_qty" value="'.dol_escape_htmltag($search_qty).'">'; print '<input class="flat" type="text" size="4" name="search_qty" value="'.dol_escape_htmltag($search_qty).'">';
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['m.price']['checked'])) if (!empty($arrayfields['m.price']['checked'])) {
{
// Price // Price
print '<td class="liste_titre left">'; print '<td class="liste_titre left">';
print '&nbsp; '; print '&nbsp; ';
@ -852,14 +898,12 @@ if ($resql)
$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint; print $hookmanager->resPrint;
// Date creation // Date creation
if (!empty($arrayfields['m.datec']['checked'])) if (!empty($arrayfields['m.datec']['checked'])) {
{
print '<td class="liste_titre">'; print '<td class="liste_titre">';
print '</td>'; print '</td>';
} }
// Date modification // Date modification
if (!empty($arrayfields['m.tms']['checked'])) if (!empty($arrayfields['m.tms']['checked'])) {
{
print '<td class="liste_titre">'; print '<td class="liste_titre">';
print '</td>'; print '</td>';
} }
@ -871,38 +915,52 @@ if ($resql)
print "</tr>\n"; print "</tr>\n";
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
if (!empty($arrayfields['m.rowid']['checked'])) if (!empty($arrayfields['m.rowid']['checked'])) {
print_liste_field_titre($arrayfields['m.rowid']['label'], $_SERVER["PHP_SELF"], 'm.rowid', '', $param, '', $sortfield, $sortorder); print_liste_field_titre($arrayfields['m.rowid']['label'], $_SERVER["PHP_SELF"], 'm.rowid', '', $param, '', $sortfield, $sortorder);
if (!empty($arrayfields['m.datem']['checked'])) }
if (!empty($arrayfields['m.datem']['checked'])) {
print_liste_field_titre($arrayfields['m.datem']['label'], $_SERVER["PHP_SELF"], 'm.datem', '', $param, '', $sortfield, $sortorder); print_liste_field_titre($arrayfields['m.datem']['label'], $_SERVER["PHP_SELF"], 'm.datem', '', $param, '', $sortfield, $sortorder);
if (!empty($arrayfields['p.ref']['checked'])) }
if (!empty($arrayfields['p.ref']['checked'])) {
print_liste_field_titre($arrayfields['p.ref']['label'], $_SERVER["PHP_SELF"], 'p.ref', '', $param, '', $sortfield, $sortorder); print_liste_field_titre($arrayfields['p.ref']['label'], $_SERVER["PHP_SELF"], 'p.ref', '', $param, '', $sortfield, $sortorder);
if (!empty($arrayfields['p.label']['checked'])) }
if (!empty($arrayfields['p.label']['checked'])) {
print_liste_field_titre($arrayfields['p.label']['label'], $_SERVER["PHP_SELF"], 'p.label', '', $param, '', $sortfield, $sortorder); print_liste_field_titre($arrayfields['p.label']['label'], $_SERVER["PHP_SELF"], 'p.label', '', $param, '', $sortfield, $sortorder);
if (!empty($arrayfields['m.batch']['checked'])) }
if (!empty($arrayfields['m.batch']['checked'])) {
print_liste_field_titre($arrayfields['m.batch']['label'], $_SERVER["PHP_SELF"], 'm.batch', '', $param, '', $sortfield, $sortorder, 'center '); print_liste_field_titre($arrayfields['m.batch']['label'], $_SERVER["PHP_SELF"], 'm.batch', '', $param, '', $sortfield, $sortorder, 'center ');
if (!empty($arrayfields['pl.eatby']['checked'])) }
if (!empty($arrayfields['pl.eatby']['checked'])) {
print_liste_field_titre($arrayfields['pl.eatby']['label'], $_SERVER["PHP_SELF"], 'pl.eatby', '', $param, '', $sortfield, $sortorder, 'center '); print_liste_field_titre($arrayfields['pl.eatby']['label'], $_SERVER["PHP_SELF"], 'pl.eatby', '', $param, '', $sortfield, $sortorder, 'center ');
if (!empty($arrayfields['pl.sellby']['checked'])) }
if (!empty($arrayfields['pl.sellby']['checked'])) {
print_liste_field_titre($arrayfields['pl.sellby']['label'], $_SERVER["PHP_SELF"], 'pl.sellby', '', $param, '', $sortfield, $sortorder, 'center '); print_liste_field_titre($arrayfields['pl.sellby']['label'], $_SERVER["PHP_SELF"], 'pl.sellby', '', $param, '', $sortfield, $sortorder, 'center ');
}
if (!empty($arrayfields['e.ref']['checked'])) { if (!empty($arrayfields['e.ref']['checked'])) {
// We are on a specific warehouse card, no filter on other should be possible // We are on a specific warehouse card, no filter on other should be possible
print_liste_field_titre($arrayfields['e.ref']['label'], $_SERVER["PHP_SELF"], "e.ref", "", $param, "", $sortfield, $sortorder); print_liste_field_titre($arrayfields['e.ref']['label'], $_SERVER["PHP_SELF"], "e.ref", "", $param, "", $sortfield, $sortorder);
} }
if (!empty($arrayfields['m.fk_user_author']['checked'])) if (!empty($arrayfields['m.fk_user_author']['checked'])) {
print_liste_field_titre($arrayfields['m.fk_user_author']['label'], $_SERVER["PHP_SELF"], "m.fk_user_author", "", $param, "", $sortfield, $sortorder); print_liste_field_titre($arrayfields['m.fk_user_author']['label'], $_SERVER["PHP_SELF"], "m.fk_user_author", "", $param, "", $sortfield, $sortorder);
if (!empty($arrayfields['m.inventorycode']['checked'])) }
if (!empty($arrayfields['m.inventorycode']['checked'])) {
print_liste_field_titre($arrayfields['m.inventorycode']['label'], $_SERVER["PHP_SELF"], "m.inventorycode", "", $param, "", $sortfield, $sortorder); print_liste_field_titre($arrayfields['m.inventorycode']['label'], $_SERVER["PHP_SELF"], "m.inventorycode", "", $param, "", $sortfield, $sortorder);
if (!empty($arrayfields['m.label']['checked'])) }
if (!empty($arrayfields['m.label']['checked'])) {
print_liste_field_titre($arrayfields['m.label']['label'], $_SERVER["PHP_SELF"], "m.label", "", $param, "", $sortfield, $sortorder); print_liste_field_titre($arrayfields['m.label']['label'], $_SERVER["PHP_SELF"], "m.label", "", $param, "", $sortfield, $sortorder);
if (!empty($arrayfields['m.type_mouvement']['checked'])) }
if (!empty($arrayfields['m.type_mouvement']['checked'])) {
print_liste_field_titre($arrayfields['m.type_mouvement']['label'], $_SERVER["PHP_SELF"], "m.type_mouvement", "", $param, '', $sortfield, $sortorder, 'center '); print_liste_field_titre($arrayfields['m.type_mouvement']['label'], $_SERVER["PHP_SELF"], "m.type_mouvement", "", $param, '', $sortfield, $sortorder, 'center ');
if (!empty($arrayfields['origin']['checked'])) }
if (!empty($arrayfields['origin']['checked'])) {
print_liste_field_titre($arrayfields['origin']['label'], $_SERVER["PHP_SELF"], "", "", $param, "", $sortfield, $sortorder); print_liste_field_titre($arrayfields['origin']['label'], $_SERVER["PHP_SELF"], "", "", $param, "", $sortfield, $sortorder);
if (!empty($arrayfields['m.value']['checked'])) }
if (!empty($arrayfields['m.value']['checked'])) {
print_liste_field_titre($arrayfields['m.value']['label'], $_SERVER["PHP_SELF"], "m.value", "", $param, '', $sortfield, $sortorder, 'right '); print_liste_field_titre($arrayfields['m.value']['label'], $_SERVER["PHP_SELF"], "m.value", "", $param, '', $sortfield, $sortorder, 'right ');
if (!empty($arrayfields['m.price']['checked'])) }
if (!empty($arrayfields['m.price']['checked'])) {
print_liste_field_titre($arrayfields['m.price']['label'], $_SERVER["PHP_SELF"], "m.price", "", $param, '', $sortfield, $sortorder, 'right '); print_liste_field_titre($arrayfields['m.price']['label'], $_SERVER["PHP_SELF"], "m.price", "", $param, '', $sortfield, $sortorder, 'right ');
}
// Extra fields // Extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
@ -956,25 +1014,21 @@ if ($resql)
print '<tr class="oddeven">'; print '<tr class="oddeven">';
// Id movement // Id movement
if (!empty($arrayfields['m.rowid']['checked'])) if (!empty($arrayfields['m.rowid']['checked'])) {
{
// This is primary not movement id // This is primary not movement id
print '<td>'.$objp->mid.'</td>'; print '<td>'.$objp->mid.'</td>';
} }
if (!empty($arrayfields['m.datem']['checked'])) if (!empty($arrayfields['m.datem']['checked'])) {
{
// Date // Date
print '<td>'.dol_print_date($db->jdate($objp->datem), 'dayhour').'</td>'; print '<td>'.dol_print_date($db->jdate($objp->datem), 'dayhour').'</td>';
} }
if (!empty($arrayfields['p.ref']['checked'])) if (!empty($arrayfields['p.ref']['checked'])) {
{
// Product ref // Product ref
print '<td class="nowraponall">'; print '<td class="nowraponall">';
print $productstatic->getNomUrl(1, 'stock', 16); print $productstatic->getNomUrl(1, 'stock', 16);
print "</td>\n"; print "</td>\n";
} }
if (!empty($arrayfields['p.label']['checked'])) if (!empty($arrayfields['p.label']['checked'])) {
{
// Product label // Product label
print '<td>'; print '<td>';
/*$productstatic->id=$objp->rowid; /*$productstatic->id=$objp->rowid;
@ -984,37 +1038,34 @@ if ($resql)
print $productstatic->label; print $productstatic->label;
print "</td>\n"; print "</td>\n";
} }
if (!empty($arrayfields['m.batch']['checked'])) if (!empty($arrayfields['m.batch']['checked'])) {
{
print '<td class="center nowraponall">'; print '<td class="center nowraponall">';
if ($productlot->id > 0) print $productlot->getNomUrl(1); if ($productlot->id > 0) {
else print $productlot->batch; // the id may not be defined if movement was entered when lot was not saved or if lot was removed after movement. print $productlot->getNomUrl(1);
} else {
print $productlot->batch; // the id may not be defined if movement was entered when lot was not saved or if lot was removed after movement.
}
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['pl.eatby']['checked'])) if (!empty($arrayfields['pl.eatby']['checked'])) {
{
print '<td class="center">'.dol_print_date($objp->eatby, 'day').'</td>'; print '<td class="center">'.dol_print_date($objp->eatby, 'day').'</td>';
} }
if (!empty($arrayfields['pl.sellby']['checked'])) if (!empty($arrayfields['pl.sellby']['checked'])) {
{
print '<td class="center">'.dol_print_date($objp->sellby, 'day').'</td>'; print '<td class="center">'.dol_print_date($objp->sellby, 'day').'</td>';
} }
// Warehouse // Warehouse
if (!empty($arrayfields['e.ref']['checked'])) if (!empty($arrayfields['e.ref']['checked'])) {
{
print '<td>'; print '<td>';
print $warehousestatic->getNomUrl(1); print $warehousestatic->getNomUrl(1);
print "</td>\n"; print "</td>\n";
} }
// Author // Author
if (!empty($arrayfields['m.fk_user_author']['checked'])) if (!empty($arrayfields['m.fk_user_author']['checked'])) {
{
print '<td class="tdoverflowmax100">'; print '<td class="tdoverflowmax100">';
print $userstatic->getNomUrl(-1); print $userstatic->getNomUrl(-1);
print "</td>\n"; print "</td>\n";
} }
if (!empty($arrayfields['m.inventorycode']['checked'])) if (!empty($arrayfields['m.inventorycode']['checked'])) {
{
// Inventory code // Inventory code
print '<td><a href="' print '<td><a href="'
.DOL_URL_ROOT.'/product/stock/movement_card.php?id='.urlencode($objp->entrepot_id) .DOL_URL_ROOT.'/product/stock/movement_card.php?id='.urlencode($objp->entrepot_id)
@ -1024,13 +1075,11 @@ if ($resql)
.$objp->inventorycode .$objp->inventorycode
.'</a></td>'; .'</a></td>';
} }
if (!empty($arrayfields['m.label']['checked'])) if (!empty($arrayfields['m.label']['checked'])) {
{
// Label of movement // Label of movement
print '<td class="tdoverflowmax100aaa">'.$objp->label.'</td>'; print '<td class="tdoverflowmax100aaa">'.$objp->label.'</td>';
} }
if (!empty($arrayfields['m.type_mouvement']['checked'])) if (!empty($arrayfields['m.type_mouvement']['checked'])) {
{
// Type of movement // Type of movement
switch ($objp->type_mouvement) { switch ($objp->type_mouvement) {
case "0": case "0":
@ -1047,36 +1096,40 @@ if ($resql)
break; break;
} }
} }
if (!empty($arrayfields['origin']['checked'])) if (!empty($arrayfields['origin']['checked'])) {
{
// Origin of movement // Origin of movement
print '<td class="nowraponall">'.$origin.'</td>'; print '<td class="nowraponall">'.$origin.'</td>';
} }
if (!empty($arrayfields['m.value']['checked'])) if (!empty($arrayfields['m.value']['checked'])) {
{
// Qty // Qty
print '<td class="right">'; print '<td class="right">';
if ($objp->qt > 0) print '+'; if ($objp->qt > 0) {
print '+';
}
print $objp->qty; print $objp->qty;
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['m.price']['checked'])) if (!empty($arrayfields['m.price']['checked'])) {
{
// Price // Price
print '<td class="right">'; print '<td class="right">';
if ($objp->price != 0) print price($objp->price); if ($objp->price != 0) {
print price($objp->price);
}
print '</td>'; print '</td>';
} }
// Action column // Action column
print '<td class="nowrap center">'; print '<td class="nowrap center">';
if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
{
$selected = 0; $selected = 0;
if (in_array($obj->rowid, $arrayofselected)) $selected = 1; if (in_array($obj->rowid, $arrayofselected)) {
$selected = 1;
}
print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>'; print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>';
} }
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
print "</tr>\n"; print "</tr>\n";
$i++; $i++;
@ -1088,8 +1141,7 @@ if ($resql)
print "</form>"; print "</form>";
// Add number of product when there is a filter on period // Add number of product when there is a filter on period
if (count($arrayofuniqueproduct) == 1 && is_numeric($year)) if (count($arrayofuniqueproduct) == 1 && is_numeric($year)) {
{
print "<br>"; print "<br>";
$productidselected = 0; $productidselected = 0;
@ -1129,8 +1181,7 @@ if ($resql)
//Area for doc and last events of warehouse are stored on the main card of warehouse //Area for doc and last events of warehouse are stored on the main card of warehouse
$modulepart = 'movement'; $modulepart = 'movement';
if ($action != 'create' && $action != 'edit' && $action != 'delete' && $id > 0) if ($action != 'create' && $action != 'edit' && $action != 'delete' && $id > 0) {
{
print '<br/>'; print '<br/>';
print '<div class="fichecenter"><div class="fichehalfleft">'; print '<div class="fichecenter"><div class="fichehalfleft">';
print '<a name="builddoc"></a>'; // ancre print '<a name="builddoc"></a>'; // ancre
@ -1138,8 +1189,12 @@ if ($action != 'create' && $action != 'edit' && $action != 'delete' && $id > 0)
// Documents // Documents
$objectref = dol_sanitizeFileName($object->ref); $objectref = dol_sanitizeFileName($object->ref);
// Add inventorycode & type_mouvement to filename of the pdf // Add inventorycode & type_mouvement to filename of the pdf
if (!empty($search_inventorycode)) $objectref .= "_".$id."_".$search_inventorycode; if (!empty($search_inventorycode)) {
if ($search_type_mouvement) $objectref .= "_".$search_type_mouvement; $objectref .= "_".$id."_".$search_inventorycode;
}
if ($search_type_mouvement) {
$objectref .= "_".$search_type_mouvement;
}
$relativepath = $comref.'/'.$objectref.'.pdf'; $relativepath = $comref.'/'.$objectref.'.pdf';
$filedir = $conf->stock->dir_output.'/movement/'.$objectref; $filedir = $conf->stock->dir_output.'/movement/'.$objectref;

View File

@ -45,7 +45,9 @@ if (!empty($conf->projet->enabled)) {
// Load translation files required by the page // Load translation files required by the page
$langs->loadLangs(array('products', 'stocks', 'orders')); $langs->loadLangs(array('products', 'stocks', 'orders'));
if (!empty($conf->productbatch->enabled)) $langs->load("productbatch"); if (!empty($conf->productbatch->enabled)) {
$langs->load("productbatch");
}
// Security check // Security check
$result = restrictedArea($user, 'stock'); $result = restrictedArea($user, 'stock');
@ -89,10 +91,16 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
$sortfield = GETPOST("sortfield", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
if (!$sortfield) $sortfield = "m.datem"; if (!$sortfield) {
if (!$sortorder) $sortorder = "DESC"; $sortfield = "m.datem";
}
if (!$sortorder) {
$sortorder = "DESC";
}
$pdluoid = GETPOST('pdluoid', 'int'); $pdluoid = GETPOST('pdluoid', 'int');
@ -154,20 +162,24 @@ $error = 0;
* Actions * Actions
*/ */
if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } if (GETPOST('cancel', 'alpha')) {
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } $action = 'list'; $massaction = '';
}
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
$massaction = '';
}
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if (empty($reshook)) if (empty($reshook)) {
{
include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
// Do we click on purge search criteria ? // Do we click on purge search criteria ?
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // Both test are required to be compatible with all browsers if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // Both test are required to be compatible with all browsers
{
$search_date_startday = ''; $search_date_startday = '';
$search_date_startmonth = ''; $search_date_startmonth = '';
$search_date_startyear = ''; $search_date_startyear = '';
@ -206,7 +218,9 @@ if ($action == 'update_extras') {
// Fill array 'array_options' with data from update form // Fill array 'array_options' with data from update form
$ret = $extrafields->setOptionalsFromPost(null, $tmpwarehouse, GETPOST('attribute', 'restricthtml')); $ret = $extrafields->setOptionalsFromPost(null, $tmpwarehouse, GETPOST('attribute', 'restricthtml'));
if ($ret < 0) $error++; if ($ret < 0) {
$error++;
}
if (!$error) { if (!$error) {
$result = $tmpwarehouse->insertExtraFields(); $result = $tmpwarehouse->insertExtraFields();
if ($result < 0) { if ($result < 0) {
@ -214,43 +228,41 @@ if ($action == 'update_extras') {
$error++; $error++;
} }
} }
if ($error) $action = 'edit_extras'; if ($error) {
$action = 'edit_extras';
}
} }
// Correct stock // Correct stock
if ($action == "correct_stock") if ($action == "correct_stock") {
{
$product = new Product($db); $product = new Product($db);
if (!empty($product_id)) $result = $product->fetch($product_id); if (!empty($product_id)) {
$result = $product->fetch($product_id);
}
$error = 0; $error = 0;
if (empty($product_id)) if (empty($product_id)) {
{
$error++; $error++;
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Product")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Product")), null, 'errors');
$action = 'correction'; $action = 'correction';
} }
if (!is_numeric($_POST["nbpiece"])) if (!is_numeric($_POST["nbpiece"])) {
{
$error++; $error++;
setEventMessages($langs->trans("ErrorFieldMustBeANumeric", $langs->transnoentitiesnoconv("NumberOfUnit")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldMustBeANumeric", $langs->transnoentitiesnoconv("NumberOfUnit")), null, 'errors');
$action = 'correction'; $action = 'correction';
} }
if (!$error) if (!$error) {
{
$origin_element = ''; $origin_element = '';
$origin_id = null; $origin_id = null;
if (GETPOST('projectid', 'int')) if (GETPOST('projectid', 'int')) {
{
$origin_element = 'project'; $origin_element = 'project';
$origin_id = GETPOST('projectid', 'int'); $origin_id = GETPOST('projectid', 'int');
} }
if ($product->hasbatch()) if ($product->hasbatch()) {
{
$batch = GETPOST('batch_number', 'alphanohtml'); $batch = GETPOST('batch_number', 'alphanohtml');
//$eatby=GETPOST('eatby'); //$eatby=GETPOST('eatby');
@ -265,7 +277,9 @@ if ($action == "correct_stock")
GETPOST("mouvement"), GETPOST("mouvement"),
GETPOST("label", 'san_alpha'), GETPOST("label", 'san_alpha'),
GETPOST('unitprice'), GETPOST('unitprice'),
$eatby, $sellby, $batch, $eatby,
$sellby,
$batch,
GETPOST('inventorycode', 'alphanohtml'), GETPOST('inventorycode', 'alphanohtml'),
$origin_element, $origin_element,
$origin_id $origin_id
@ -284,8 +298,7 @@ if ($action == "correct_stock")
); // We do not change value of stock for a correction ); // We do not change value of stock for a correction
} }
if ($result > 0) if ($result > 0) {
{
header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
exit; exit;
} else { } else {
@ -295,57 +308,52 @@ if ($action == "correct_stock")
} }
} }
if (!$error) $action = ''; if (!$error) {
$action = '';
}
} }
// Transfer stock from a warehouse to another warehouse // Transfer stock from a warehouse to another warehouse
if ($action == "transfert_stock" && !$cancel) if ($action == "transfert_stock" && !$cancel) {
{
$product = new Product($db); $product = new Product($db);
if (!empty($product_id)) $result = $product->fetch($product_id); if (!empty($product_id)) {
$result = $product->fetch($product_id);
}
if (!(GETPOST("id_entrepot_destination", 'int') > 0)) if (!(GETPOST("id_entrepot_destination", 'int') > 0)) {
{
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
$error++; $error++;
$action = 'transfert'; $action = 'transfert';
} }
if (empty($product_id)) if (empty($product_id)) {
{
$error++; $error++;
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Product")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Product")), null, 'errors');
$action = 'transfert'; $action = 'transfert';
} }
if (!GETPOST("nbpiece", 'int')) if (!GETPOST("nbpiece", 'int')) {
{
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NumberOfUnit")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NumberOfUnit")), null, 'errors');
$error++; $error++;
$action = 'transfert'; $action = 'transfert';
} }
if ($id == GETPOST("id_entrepot_destination", 'int')) if ($id == GETPOST("id_entrepot_destination", 'int')) {
{
setEventMessages($langs->trans("ErrorSrcAndTargetWarehouseMustDiffers"), null, 'errors'); setEventMessages($langs->trans("ErrorSrcAndTargetWarehouseMustDiffers"), null, 'errors');
$error++; $error++;
$action = 'transfert'; $action = 'transfert';
} }
if (!empty($conf->productbatch->enabled)) if (!empty($conf->productbatch->enabled)) {
{
$product = new Product($db); $product = new Product($db);
$result = $product->fetch($product_id); $result = $product->fetch($product_id);
if ($product->hasbatch() && !GETPOST("batch_number")) if ($product->hasbatch() && !GETPOST("batch_number")) {
{
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("batch_number")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("batch_number")), null, 'errors');
$error++; $error++;
$action = 'transfert'; $action = 'transfert';
} }
} }
if (!$error) if (!$error) {
{ if ($id) {
if ($id)
{
$object = new Entrepot($db); $object = new Entrepot($db);
$result = $object->fetch($id); $result = $object->fetch($id);
@ -355,18 +363,17 @@ if ($action == "transfert_stock" && !$cancel)
// Define value of products moved // Define value of products moved
$pricesrc = 0; $pricesrc = 0;
if (isset($product->pmp)) $pricesrc = $product->pmp; if (isset($product->pmp)) {
$pricesrc = $product->pmp;
}
$pricedest = $pricesrc; $pricedest = $pricesrc;
if ($product->hasbatch()) if ($product->hasbatch()) {
{
$pdluo = new Productbatch($db); $pdluo = new Productbatch($db);
if ($pdluoid > 0) if ($pdluoid > 0) {
{
$result = $pdluo->fetch($pdluoid); $result = $pdluo->fetch($pdluoid);
if ($result) if ($result) {
{
$srcwarehouseid = $pdluo->warehouseid; $srcwarehouseid = $pdluo->warehouseid;
$batch = $pdluo->batch; $batch = $pdluo->batch;
$eatby = $pdluo->eatby; $eatby = $pdluo->eatby;
@ -382,8 +389,7 @@ if ($action == "transfert_stock" && !$cancel)
$sellby = $d_sellby; $sellby = $d_sellby;
} }
if (!$error) if (!$error) {
{
// Remove stock // Remove stock
$result1 = $product->correct_stock_batch( $result1 = $product->correct_stock_batch(
$user, $user,
@ -392,7 +398,9 @@ if ($action == "transfert_stock" && !$cancel)
1, 1,
GETPOST("label", 'san_alpha'), GETPOST("label", 'san_alpha'),
$pricesrc, $pricesrc,
$eatby, $sellby, $batch, $eatby,
$sellby,
$batch,
GETPOST('inventorycode') GETPOST('inventorycode')
); );
// Add stock // Add stock
@ -403,7 +411,9 @@ if ($action == "transfert_stock" && !$cancel)
0, 0,
GETPOST("label", 'san_alpha'), GETPOST("label", 'san_alpha'),
$pricedest, $pricedest,
$eatby, $sellby, $batch, $eatby,
$sellby,
$batch,
GETPOST('inventorycode', 'alphanohtml') GETPOST('inventorycode', 'alphanohtml')
); );
} }
@ -430,12 +440,10 @@ if ($action == "transfert_stock" && !$cancel)
GETPOST('inventorycode', 'alphanohtml') GETPOST('inventorycode', 'alphanohtml')
); );
} }
if (!$error && $result1 >= 0 && $result2 >= 0) if (!$error && $result1 >= 0 && $result2 >= 0) {
{
$db->commit(); $db->commit();
if ($backtopage) if ($backtopage) {
{
header("Location: ".$backtopage); header("Location: ".$backtopage);
exit; exit;
} else { } else {
@ -464,7 +472,9 @@ $userstatic = new User($db);
$form = new Form($db); $form = new Form($db);
$formother = new FormOther($db); $formother = new FormOther($db);
$formproduct = new FormProduct($db); $formproduct = new FormProduct($db);
if (!empty($conf->projet->enabled)) $formproject = new FormProjets($db); if (!empty($conf->projet->enabled)) {
$formproject = new FormProjets($db);
}
$sql = "SELECT p.rowid, p.ref as product_ref, p.label as produit, p.tosell, p.tobuy, p.tobatch, p.fk_product_type as type, p.entity,"; $sql = "SELECT p.rowid, p.ref as product_ref, p.label as produit, p.tosell, p.tobuy, p.tobatch, p.fk_product_type as type, p.entity,";
$sql .= " e.ref as warehouse_ref, e.rowid as entrepot_id, e.lieu, e.fk_parent, e.statut,"; $sql .= " e.ref as warehouse_ref, e.rowid as entrepot_id, e.lieu, e.fk_parent, e.statut,";
@ -476,7 +486,9 @@ $sql .= " pl.rowid as lotid, pl.eatby, pl.sellby,";
$sql .= " u.login, u.photo, u.lastname, u.firstname, u.email as user_email, u.statut as user_status"; $sql .= " u.login, u.photo, u.lastname, u.firstname, u.email as user_email, u.statut as user_status";
// Add fields from extrafields // Add fields from extrafields
if (!empty($extrafields->attributes[$object->table_element]['label'])) { if (!empty($extrafields->attributes[$object->table_element]['label'])) {
foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
$sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : '');
}
} }
// Add fields from hooks // Add fields from hooks
$parameters = array(); $parameters = array();
@ -485,29 +497,65 @@ $sql .= $hookmanager->resPrint;
$sql .= " FROM ".MAIN_DB_PREFIX."entrepot as e,"; $sql .= " FROM ".MAIN_DB_PREFIX."entrepot as e,";
$sql .= " ".MAIN_DB_PREFIX."product as p,"; $sql .= " ".MAIN_DB_PREFIX."product as p,";
$sql .= " ".MAIN_DB_PREFIX."stock_mouvement as m"; $sql .= " ".MAIN_DB_PREFIX."stock_mouvement as m";
if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (m.rowid = ef.fk_object)"; if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) {
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (m.rowid = ef.fk_object)";
}
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u ON m.fk_user_author = u.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u ON m.fk_user_author = u.rowid";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_lot as pl ON m.batch = pl.batch AND m.fk_product = pl.fk_product"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_lot as pl ON m.batch = pl.batch AND m.fk_product = pl.fk_product";
$sql .= " WHERE m.fk_product = p.rowid"; $sql .= " WHERE m.fk_product = p.rowid";
if ($msid > 0) $sql .= " AND m.rowid = ".$msid; if ($msid > 0) {
$sql .= " AND m.rowid = ".$msid;
}
$sql .= " AND m.fk_entrepot = e.rowid"; $sql .= " AND m.fk_entrepot = e.rowid";
$sql .= " AND e.entity IN (".getEntity('stock').")"; $sql .= " AND e.entity IN (".getEntity('stock').")";
if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) $sql .= " AND p.fk_product_type = 0"; if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
if ($id > 0) $sql .= " AND e.rowid ='".$id."'"; $sql .= " AND p.fk_product_type = 0";
if (!empty($search_date_start)) $sql .= " AND m.datem >= '" . $db->idate($search_date_start) . "'"; }
if (!empty($search_date_end)) $sql .= " AND m.datem <= '" . $db->idate($search_date_end) . "'"; if ($id > 0) {
if ($idproduct > 0) $sql .= " AND p.rowid = ".((int) $idproduct); $sql .= " AND e.rowid ='".$id."'";
if (!empty($search_ref)) $sql .= natural_search('m.rowid', $search_ref, 1); }
if (!empty($search_movement)) $sql .= natural_search('m.label', $search_movement); if (!empty($search_date_start)) {
if (!empty($search_inventorycode)) $sql .= natural_search('m.inventorycode', $search_inventorycode); $sql .= " AND m.datem >= '" . $db->idate($search_date_start) . "'";
if (!empty($search_product_ref)) $sql .= natural_search('p.ref', $search_product_ref); }
if (!empty($search_product)) $sql .= natural_search('p.label', $search_product); if (!empty($search_date_end)) {
if ($search_warehouse != '' && $search_warehouse != '-1') $sql .= natural_search('e.rowid', $search_warehouse, 2); $sql .= " AND m.datem <= '" . $db->idate($search_date_end) . "'";
if (!empty($search_user)) $sql .= natural_search('u.login', $search_user); }
if (!empty($search_batch)) $sql .= natural_search('m.batch', $search_batch); if ($idproduct > 0) {
if (!empty($product_id)) $sql .= natural_search('p.rowid', $product_id); $sql .= " AND p.rowid = ".((int) $idproduct);
if ($search_qty != '') $sql .= natural_search('m.value', $search_qty, 1); }
if ($search_type_mouvement != '' && $search_type_mouvement != '-1') $sql .= natural_search('m.type_mouvement', $search_type_mouvement, 2); if (!empty($search_ref)) {
$sql .= natural_search('m.rowid', $search_ref, 1);
}
if (!empty($search_movement)) {
$sql .= natural_search('m.label', $search_movement);
}
if (!empty($search_inventorycode)) {
$sql .= natural_search('m.inventorycode', $search_inventorycode);
}
if (!empty($search_product_ref)) {
$sql .= natural_search('p.ref', $search_product_ref);
}
if (!empty($search_product)) {
$sql .= natural_search('p.label', $search_product);
}
if ($search_warehouse != '' && $search_warehouse != '-1') {
$sql .= natural_search('e.rowid', $search_warehouse, 2);
}
if (!empty($search_user)) {
$sql .= natural_search('u.login', $search_user);
}
if (!empty($search_batch)) {
$sql .= natural_search('m.batch', $search_batch);
}
if (!empty($product_id)) {
$sql .= natural_search('p.rowid', $product_id);
}
if ($search_qty != '') {
$sql .= natural_search('m.value', $search_qty, 1);
}
if ($search_type_mouvement != '' && $search_type_mouvement != '-1') {
$sql .= natural_search('m.type_mouvement', $search_type_mouvement, 2);
}
// Add where from extra fields // Add where from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
// Add where from hooks // Add where from hooks
@ -517,19 +565,16 @@ $sql .= $hookmanager->resPrint;
$sql .= $db->order($sortfield, $sortorder); $sql .= $db->order($sortfield, $sortorder);
$nbtotalofrecords = ''; $nbtotalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
{
$result = $db->query($sql); $result = $db->query($sql);
$nbtotalofrecords = $db->num_rows($result); $nbtotalofrecords = $db->num_rows($result);
if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0
{
$page = 0; $page = 0;
$offset = 0; $offset = 0;
} }
} }
if (empty($search_inventorycode)) if (empty($search_inventorycode)) {
{
$sql .= $db->plimit($limit + 1, $offset); $sql .= $db->plimit($limit + 1, $offset);
} else { } else {
$limit = 0; $limit = 0;
@ -539,22 +584,20 @@ if (empty($search_inventorycode))
$resql = $db->query($sql); $resql = $db->query($sql);
if (!empty($search_inventorycode)) $limit = $db->num_rows($resql); if (!empty($search_inventorycode)) {
$limit = $db->num_rows($resql);
}
if ($resql) if ($resql) {
{
$product = new Product($db); $product = new Product($db);
$object = new Entrepot($db); $object = new Entrepot($db);
if ($idproduct > 0) if ($idproduct > 0) {
{
$product->fetch($idproduct); $product->fetch($idproduct);
} }
if ($id > 0 || $ref) if ($id > 0 || $ref) {
{
$result = $object->fetch($id, $ref); $result = $object->fetch($id, $ref);
if ($result < 0) if ($result < 0) {
{
dol_print_error($db); dol_print_error($db);
} }
} }
@ -566,18 +609,20 @@ if ($resql)
$i = 0; $i = 0;
$help_url = 'EN:Module_Stocks_En|FR:Module_Stock|ES:M&oacute;dulo_Stocks'; $help_url = 'EN:Module_Stocks_En|FR:Module_Stock|ES:M&oacute;dulo_Stocks';
if ($msid) $texte = $langs->trans('StockMovementForId', $msid); if ($msid) {
else { $texte = $langs->trans('StockMovementForId', $msid);
} else {
$texte = $langs->trans("ListOfStockMovements"); $texte = $langs->trans("ListOfStockMovements");
if ($id) $texte .= ' ('.$langs->trans("ForThisWarehouse").')'; if ($id) {
$texte .= ' ('.$langs->trans("ForThisWarehouse").')';
}
} }
llxHeader("", $texte, $help_url); llxHeader("", $texte, $help_url);
/* /*
* Show tab only if we ask a particular warehouse * Show tab only if we ask a particular warehouse
*/ */
if ($object->id > 0) if ($object->id > 0) {
{
$head = stock_prepare_head($object); $head = stock_prepare_head($object);
print dol_get_fiche_head($head, 'movements', $langs->trans("Warehouse"), -1, 'stock'); print dol_get_fiche_head($head, 'movements', $langs->trans("Warehouse"), -1, 'stock');
@ -590,7 +635,9 @@ if ($resql)
$morehtmlref .= '</div>'; $morehtmlref .= '</div>';
$shownav = 1; $shownav = 1;
if ($user->socid && !in_array('stock', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; if ($user->socid && !in_array('stock', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) {
$shownav = 0;
}
dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref', 'ref', $morehtmlref); dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref', 'ref', $morehtmlref);
@ -639,8 +686,7 @@ if ($resql)
$sql .= " FROM ".MAIN_DB_PREFIX."stock_mouvement as m"; $sql .= " FROM ".MAIN_DB_PREFIX."stock_mouvement as m";
$sql .= " WHERE m.fk_entrepot = ".((int) $object->id); $sql .= " WHERE m.fk_entrepot = ".((int) $object->id);
$resqlbis = $db->query($sql); $resqlbis = $db->query($sql);
if ($resqlbis) if ($resqlbis) {
{
$objbis = $db->fetch_object($resqlbis); $objbis = $db->fetch_object($resqlbis);
$lastmovementdate = $db->jdate($objbis->datem); $lastmovementdate = $db->jdate($objbis->datem);
} else { } else {
@ -648,8 +694,7 @@ if ($resql)
} }
print '<tr><td>'.$langs->trans("LastMovement").'</td><td>'; print '<tr><td>'.$langs->trans("LastMovement").'</td><td>';
if ($lastmovementdate) if ($lastmovementdate) {
{
print dol_print_date($lastmovementdate, 'dayhour'); print dol_print_date($lastmovementdate, 'dayhour');
} else { } else {
print $langs->trans("None"); print $langs->trans("None");
@ -681,8 +726,7 @@ if ($resql)
/* /*
* Correct stock * Correct stock
*/ */
if ($action == "correction") if ($action == "correction") {
{
include DOL_DOCUMENT_ROOT.'/product/stock/tpl/stockcorrection.tpl.php'; include DOL_DOCUMENT_ROOT.'/product/stock/tpl/stockcorrection.tpl.php';
print '<br>'; print '<br>';
} }
@ -690,8 +734,7 @@ if ($resql)
/* /*
* Transfer of units * Transfer of units
*/ */
if ($action == "transfert") if ($action == "transfert") {
{
include DOL_DOCUMENT_ROOT.'/product/stock/tpl/stocktransfer.tpl.php'; include DOL_DOCUMENT_ROOT.'/product/stock/tpl/stocktransfer.tpl.php';
print '<br>'; print '<br>';
} }
@ -703,17 +746,14 @@ if ($resql)
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
if ((empty($action) || $action == 'list') && $id > 0) if ((empty($action) || $action == 'list') && $id > 0) {
{
print "<div class=\"tabsAction\">\n"; print "<div class=\"tabsAction\">\n";
if ($user->rights->stock->mouvement->creer) if ($user->rights->stock->mouvement->creer) {
{
print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$id.'&action=correction">'.$langs->trans("CorrectStock").'</a>'; print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$id.'&action=correction">'.$langs->trans("CorrectStock").'</a>';
} }
if ($user->rights->stock->mouvement->creer) if ($user->rights->stock->mouvement->creer) {
{
print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$id.'&action=transfert">'.$langs->trans("TransferStock").'</a>'; print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$id.'&action=transfert">'.$langs->trans("TransferStock").'</a>';
} }
@ -721,24 +761,60 @@ if ($resql)
} }
$param = ''; $param = '';
if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); $param .= '&contextpage='.urlencode($contextpage);
if ($id > 0) $param .= '&id='.urlencode($id); }
if ($search_date_startday) $param .= '&search_date_startday='.urlencode($search_date_startday); if ($limit > 0 && $limit != $conf->liste_limit) {
if ($search_date_startmonth) $param .= '&search_date_startmonth='.urlencode($search_date_startmonth); $param .= '&limit='.urlencode($limit);
if ($search_date_startyear) $param .= '&search_date_startyear='.urlencode($search_date_startyear); }
if ($search_date_endday) $param .= '&search_date_endday='.urlencode($search_date_endday); if ($id > 0) {
if ($search_date_endmonth) $param .= '&search_date_endmonth='.urlencode($search_date_endmonth); $param .= '&id='.urlencode($id);
if ($search_date_endyear) $param .= '&search_date_endyear='.urlencode($search_date_endyear); }
if ($search_movement) $param .= '&search_movement='.urlencode($search_movement); if ($search_date_startday) {
if ($search_inventorycode) $param .= '&search_inventorycode='.urlencode($search_inventorycode); $param .= '&search_date_startday='.urlencode($search_date_startday);
if ($search_type_mouvement) $param .= '&search_type_mouvement='.urlencode($search_type_mouvement); }
if ($search_product_ref) $param .= '&search_product_ref='.urlencode($search_product_ref); if ($search_date_startmonth) {
if ($search_product) $param .= '&search_product='.urlencode($search_product); $param .= '&search_date_startmonth='.urlencode($search_date_startmonth);
if ($search_batch) $param .= '&search_batch='.urlencode($search_batch); }
if ($search_warehouse > 0) $param .= '&search_warehouse='.urlencode($search_warehouse); if ($search_date_startyear) {
if ($search_user) $param .= '&search_user='.urlencode($search_user); $param .= '&search_date_startyear='.urlencode($search_date_startyear);
if ($idproduct > 0) $param .= '&idproduct='.urlencode($idproduct); }
if ($search_date_endday) {
$param .= '&search_date_endday='.urlencode($search_date_endday);
}
if ($search_date_endmonth) {
$param .= '&search_date_endmonth='.urlencode($search_date_endmonth);
}
if ($search_date_endyear) {
$param .= '&search_date_endyear='.urlencode($search_date_endyear);
}
if ($search_movement) {
$param .= '&search_movement='.urlencode($search_movement);
}
if ($search_inventorycode) {
$param .= '&search_inventorycode='.urlencode($search_inventorycode);
}
if ($search_type_mouvement) {
$param .= '&search_type_mouvement='.urlencode($search_type_mouvement);
}
if ($search_product_ref) {
$param .= '&search_product_ref='.urlencode($search_product_ref);
}
if ($search_product) {
$param .= '&search_product='.urlencode($search_product);
}
if ($search_batch) {
$param .= '&search_batch='.urlencode($search_batch);
}
if ($search_warehouse > 0) {
$param .= '&search_warehouse='.urlencode($search_warehouse);
}
if ($search_user) {
$param .= '&search_user='.urlencode($search_user);
}
if ($idproduct > 0) {
$param .= '&idproduct='.urlencode($idproduct);
}
// Add $param from extra fields // Add $param from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
@ -748,12 +824,18 @@ if ($resql)
// 'builddoc'=>$langs->trans("PDFMerge"), // 'builddoc'=>$langs->trans("PDFMerge"),
); );
// By default, we should never accept deletion of stock movement. // By default, we should never accept deletion of stock movement.
if (!empty($conf->global->STOCK_ALLOW_DELETE_OF_MOVEMENT) && $permissiontodelete) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); if (!empty($conf->global->STOCK_ALLOW_DELETE_OF_MOVEMENT) && $permissiontodelete) {
if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete");
}
if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) {
$arrayofmassactions = array();
}
$massactionbutton = $form->selectMassAction('', $arrayofmassactions); $massactionbutton = $form->selectMassAction('', $arrayofmassactions);
print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; if ($optioncss != '') {
print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
}
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
print '<input type="hidden" name="action" value="list">'; print '<input type="hidden" name="action" value="list">';
@ -761,10 +843,15 @@ if ($resql)
print '<input type="hidden" name="sortorder" value="'.$sortorder.'">'; print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
print '<input type="hidden" name="type" value="'.$type.'">'; print '<input type="hidden" name="type" value="'.$type.'">';
print '<input type="hidden" name="contextpage" value="'.$contextpage.'">'; print '<input type="hidden" name="contextpage" value="'.$contextpage.'">';
if ($id > 0) print '<input type="hidden" name="id" value="'.$id.'">'; if ($id > 0) {
print '<input type="hidden" name="id" value="'.$id.'">';
}
if ($id > 0) print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'stock', 0, '', '', $limit, 0, 0, 1); if ($id > 0) {
else print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'stock', 0, '', '', $limit, 0, 0, 1); print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'stock', 0, '', '', $limit, 0, 0, 1);
} else {
print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'stock', 0, '', '', $limit, 0, 0, 1);
}
// Add code for pre mass action (confirmation or email presend form) // Add code for pre mass action (confirmation or email presend form)
$topicmail = "SendStockMovement"; $topicmail = "SendStockMovement";
@ -773,9 +860,10 @@ if ($resql)
$trackid = 'mov'.$object->id; $trackid = 'mov'.$object->id;
include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';
if ($sall) if ($sall) {
{ foreach ($fieldstosearchall as $key => $val) {
foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); $fieldstosearchall[$key] = $langs->trans($val);
}
print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>'; print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>';
} }
@ -783,11 +871,13 @@ if ($resql)
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook
if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; if (empty($reshook)) {
else $moreforfilter = $hookmanager->resPrint; $moreforfilter .= $hookmanager->resPrint;
} else {
$moreforfilter = $hookmanager->resPrint;
}
if (!empty($moreforfilter)) if (!empty($moreforfilter)) {
{
print '<div class="liste_titre liste_titre_bydiv centpercent">'; print '<div class="liste_titre liste_titre_bydiv centpercent">';
print $moreforfilter; print $moreforfilter;
print '</div>'; print '</div>';
@ -801,15 +891,13 @@ if ($resql)
// Fields title search // Fields title search
print '<tr class="liste_titre_filter">'; print '<tr class="liste_titre_filter">';
if (!empty($arrayfields['m.rowid']['checked'])) if (!empty($arrayfields['m.rowid']['checked'])) {
{
// Ref // Ref
print '<td class="liste_titre left">'; print '<td class="liste_titre left">';
print '<input class="flat maxwidth25" type="text" name="search_ref" value="'.dol_escape_htmltag($search_ref).'">'; print '<input class="flat maxwidth25" type="text" name="search_ref" value="'.dol_escape_htmltag($search_ref).'">';
print '</td>'; print '</td>';
} }
if (! empty($arrayfields['m.datem']['checked'])) if (! empty($arrayfields['m.datem']['checked'])) {
{
print '<td class="liste_titre center">'; print '<td class="liste_titre center">';
print '<div class="nowrap">'; print '<div class="nowrap">';
print $form->selectDate($search_date_start?$search_date_start:-1, 'search_date_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From'), 'tzuserrel'); print $form->selectDate($search_date_start?$search_date_start:-1, 'search_date_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From'), 'tzuserrel');
@ -819,66 +907,56 @@ if ($resql)
print '</div>'; print '</div>';
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['p.ref']['checked'])) if (!empty($arrayfields['p.ref']['checked'])) {
{
// Product Ref // Product Ref
print '<td class="liste_titre left">'; print '<td class="liste_titre left">';
print '<input class="flat maxwidth75" type="text" name="search_product_ref" value="'.dol_escape_htmltag($idproduct ? $product->ref : $search_product_ref).'">'; print '<input class="flat maxwidth75" type="text" name="search_product_ref" value="'.dol_escape_htmltag($idproduct ? $product->ref : $search_product_ref).'">';
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['p.label']['checked'])) if (!empty($arrayfields['p.label']['checked'])) {
{
// Product label // Product label
print '<td class="liste_titre left">'; print '<td class="liste_titre left">';
print '<input class="flat maxwidth100" type="text" name="search_product" value="'.dol_escape_htmltag($idproduct ? $product->label : $search_product).'">'; print '<input class="flat maxwidth100" type="text" name="search_product" value="'.dol_escape_htmltag($idproduct ? $product->label : $search_product).'">';
print '</td>'; print '</td>';
} }
// Batch // Batch
if (!empty($arrayfields['m.batch']['checked'])) if (!empty($arrayfields['m.batch']['checked'])) {
{
print '<td class="liste_titre center"><input class="flat maxwidth75" type="text" name="search_batch" value="'.dol_escape_htmltag($search_batch).'"></td>'; print '<td class="liste_titre center"><input class="flat maxwidth75" type="text" name="search_batch" value="'.dol_escape_htmltag($search_batch).'"></td>';
} }
if (!empty($arrayfields['pl.eatby']['checked'])) if (!empty($arrayfields['pl.eatby']['checked'])) {
{
print '<td class="liste_titre left">'; print '<td class="liste_titre left">';
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['pl.sellby']['checked'])) if (!empty($arrayfields['pl.sellby']['checked'])) {
{
print '<td class="liste_titre left">'; print '<td class="liste_titre left">';
print '</td>'; print '</td>';
} }
// Warehouse // Warehouse
if (!empty($arrayfields['e.ref']['checked'])) if (!empty($arrayfields['e.ref']['checked'])) {
{
print '<td class="liste_titre maxwidthonsmartphone left">'; print '<td class="liste_titre maxwidthonsmartphone left">';
//print '<input class="flat" type="text" size="8" name="search_warehouse" value="'.($search_warehouse).'">'; //print '<input class="flat" type="text" size="8" name="search_warehouse" value="'.($search_warehouse).'">';
print $formproduct->selectWarehouses($search_warehouse, 'search_warehouse', 'warehouseopen,warehouseinternal', 1, 0, 0, '', 0, 0, null, 'maxwidth200'); print $formproduct->selectWarehouses($search_warehouse, 'search_warehouse', 'warehouseopen,warehouseinternal', 1, 0, 0, '', 0, 0, null, 'maxwidth200');
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['m.fk_user_author']['checked'])) if (!empty($arrayfields['m.fk_user_author']['checked'])) {
{
// Author // Author
print '<td class="liste_titre left">'; print '<td class="liste_titre left">';
print '<input class="flat" type="text" size="6" name="search_user" value="'.dol_escape_htmltag($search_user).'">'; print '<input class="flat" type="text" size="6" name="search_user" value="'.dol_escape_htmltag($search_user).'">';
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['m.inventorycode']['checked'])) if (!empty($arrayfields['m.inventorycode']['checked'])) {
{
// Inventory code // Inventory code
print '<td class="liste_titre left">'; print '<td class="liste_titre left">';
print '<input class="flat" type="text" size="4" name="search_inventorycode" value="'.dol_escape_htmltag($search_inventorycode).'">'; print '<input class="flat" type="text" size="4" name="search_inventorycode" value="'.dol_escape_htmltag($search_inventorycode).'">';
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['m.label']['checked'])) if (!empty($arrayfields['m.label']['checked'])) {
{
// Label of movement // Label of movement
print '<td class="liste_titre left">'; print '<td class="liste_titre left">';
print '<input class="flat" type="text" size="8" name="search_movement" value="'.dol_escape_htmltag($search_movement).'">'; print '<input class="flat" type="text" size="8" name="search_movement" value="'.dol_escape_htmltag($search_movement).'">';
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['m.type_mouvement']['checked'])) if (!empty($arrayfields['m.type_mouvement']['checked'])) {
{
// Type of movement // Type of movement
print '<td class="liste_titre center">'; print '<td class="liste_titre center">';
//print '<input class="flat" type="text" size="3" name="search_type_mouvement" value="'.dol_escape_htmltag($search_type_mouvement).'">'; //print '<input class="flat" type="text" size="3" name="search_type_mouvement" value="'.dol_escape_htmltag($search_type_mouvement).'">';
@ -894,29 +972,25 @@ if ($resql)
// print $formproduct->selectWarehouses($search_warehouse, 'search_warehouse', 'warehouseopen,warehouseinternal', 1, 0, 0, '', 0, 0, null, 'maxwidth200'); // print $formproduct->selectWarehouses($search_warehouse, 'search_warehouse', 'warehouseopen,warehouseinternal', 1, 0, 0, '', 0, 0, null, 'maxwidth200');
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['origin']['checked'])) if (!empty($arrayfields['origin']['checked'])) {
{
// Origin of movement // Origin of movement
print '<td class="liste_titre left">'; print '<td class="liste_titre left">';
print '&nbsp; '; print '&nbsp; ';
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['m.value']['checked'])) if (!empty($arrayfields['m.value']['checked'])) {
{
// Qty // Qty
print '<td class="liste_titre right">'; print '<td class="liste_titre right">';
print '<input class="flat" type="text" size="4" name="search_qty" value="'.dol_escape_htmltag($search_qty).'">'; print '<input class="flat" type="text" size="4" name="search_qty" value="'.dol_escape_htmltag($search_qty).'">';
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['m.price']['checked'])) if (!empty($arrayfields['m.price']['checked'])) {
{
// Price // Price
print '<td class="liste_titre" align="left">'; print '<td class="liste_titre" align="left">';
print '&nbsp; '; print '&nbsp; ';
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['m.fk_projet']['checked'])) if (!empty($arrayfields['m.fk_projet']['checked'])) {
{
// fk_project // fk_project
print '<td class="liste_titre" align="left">'; print '<td class="liste_titre" align="left">';
print '&nbsp; '; print '&nbsp; ';
@ -932,14 +1006,12 @@ if ($resql)
$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint; print $hookmanager->resPrint;
// Date creation // Date creation
if (!empty($arrayfields['m.datec']['checked'])) if (!empty($arrayfields['m.datec']['checked'])) {
{
print '<td class="liste_titre">'; print '<td class="liste_titre">';
print '</td>'; print '</td>';
} }
// Date modification // Date modification
if (!empty($arrayfields['m.tms']['checked'])) if (!empty($arrayfields['m.tms']['checked'])) {
{
print '<td class="liste_titre">'; print '<td class="liste_titre">';
print '</td>'; print '</td>';
} }
@ -1022,8 +1094,7 @@ if ($resql)
$i = 0; $i = 0;
$totalarray = array(); $totalarray = array();
while ($i < min($num, $limit)) while ($i < min($num, $limit)) {
{
$objp = $db->fetch_object($resql); $objp = $db->fetch_object($resql);
$userstatic->id = $objp->fk_user_author; $userstatic->id = $objp->fk_user_author;
@ -1064,60 +1135,53 @@ if ($resql)
print '<tr class="oddeven">'; print '<tr class="oddeven">';
// Id movement // Id movement
if (!empty($arrayfields['m.rowid']['checked'])) if (!empty($arrayfields['m.rowid']['checked'])) {
{
print '<td>'.$objp->mid.'</td>'; // This is primary not movement id print '<td>'.$objp->mid.'</td>'; // This is primary not movement id
} }
if (!empty($arrayfields['m.datem']['checked'])) if (!empty($arrayfields['m.datem']['checked'])) {
{
// Date // Date
print '<td class="nowraponall">'.dol_print_date($db->jdate($objp->datem), 'dayhour', 'tzuserrel').'</td>'; print '<td class="nowraponall">'.dol_print_date($db->jdate($objp->datem), 'dayhour', 'tzuserrel').'</td>';
} }
if (!empty($arrayfields['p.ref']['checked'])) if (!empty($arrayfields['p.ref']['checked'])) {
{
// Product ref // Product ref
print '<td class="nowraponall">'; print '<td class="nowraponall">';
print $productstatic->getNomUrl(1, 'stock', 16); print $productstatic->getNomUrl(1, 'stock', 16);
print "</td>\n"; print "</td>\n";
} }
if (!empty($arrayfields['p.label']['checked'])) if (!empty($arrayfields['p.label']['checked'])) {
{
// Product label // Product label
print '<td class="tdoverflowmax150" title="'.dol_escape_htmltag($productstatic->label).'">'; print '<td class="tdoverflowmax150" title="'.dol_escape_htmltag($productstatic->label).'">';
print $productstatic->label; print $productstatic->label;
print "</td>\n"; print "</td>\n";
} }
if (!empty($arrayfields['m.batch']['checked'])) if (!empty($arrayfields['m.batch']['checked'])) {
{
print '<td class="center nowraponall">'; print '<td class="center nowraponall">';
if ($productlot->id > 0) print $productlot->getNomUrl(1); if ($productlot->id > 0) {
else print $productlot->batch; // the id may not be defined if movement was entered when lot was not saved or if lot was removed after movement. print $productlot->getNomUrl(1);
} else {
print $productlot->batch; // the id may not be defined if movement was entered when lot was not saved or if lot was removed after movement.
}
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['pl.eatby']['checked'])) if (!empty($arrayfields['pl.eatby']['checked'])) {
{
print '<td class="center">'.dol_print_date($objp->eatby, 'day').'</td>'; print '<td class="center">'.dol_print_date($objp->eatby, 'day').'</td>';
} }
if (!empty($arrayfields['pl.sellby']['checked'])) if (!empty($arrayfields['pl.sellby']['checked'])) {
{
print '<td class="center">'.dol_print_date($objp->sellby, 'day').'</td>'; print '<td class="center">'.dol_print_date($objp->sellby, 'day').'</td>';
} }
// Warehouse // Warehouse
if (!empty($arrayfields['e.ref']['checked'])) if (!empty($arrayfields['e.ref']['checked'])) {
{
print '<td class="tdoverflowmax100">'; print '<td class="tdoverflowmax100">';
print $warehousestatic->getNomUrl(1); print $warehousestatic->getNomUrl(1);
print "</td>\n"; print "</td>\n";
} }
// Author // Author
if (!empty($arrayfields['m.fk_user_author']['checked'])) if (!empty($arrayfields['m.fk_user_author']['checked'])) {
{
print '<td class="tdoverflowmax100">'; print '<td class="tdoverflowmax100">';
print $userstatic->getNomUrl(-1); print $userstatic->getNomUrl(-1);
print "</td>\n"; print "</td>\n";
} }
if (!empty($arrayfields['m.inventorycode']['checked'])) if (!empty($arrayfields['m.inventorycode']['checked'])) {
{
// Inventory code // Inventory code
print '<td><a href="' print '<td><a href="'
.DOL_URL_ROOT.'/product/stock/movement_card.php?id='.urlencode($objp->entrepot_id) .DOL_URL_ROOT.'/product/stock/movement_card.php?id='.urlencode($objp->entrepot_id)
@ -1125,13 +1189,11 @@ if ($resql)
.'&search_type_mouvement='.urlencode($objp->type_mouvement) .'&search_type_mouvement='.urlencode($objp->type_mouvement)
.'">'.$objp->inventorycode.'</a></td>'; .'">'.$objp->inventorycode.'</a></td>';
} }
if (!empty($arrayfields['m.label']['checked'])) if (!empty($arrayfields['m.label']['checked'])) {
{
// Label of movement // Label of movement
print '<td class="tdoverflowmax100aaa">'.$objp->label.'</td>'; print '<td class="tdoverflowmax100aaa">'.$objp->label.'</td>';
} }
if (!empty($arrayfields['m.type_mouvement']['checked'])) if (!empty($arrayfields['m.type_mouvement']['checked'])) {
{
// Type of movement // Type of movement
switch ($objp->type_mouvement) { switch ($objp->type_mouvement) {
case "0": case "0":
@ -1148,43 +1210,48 @@ if ($resql)
break; break;
} }
} }
if (!empty($arrayfields['origin']['checked'])) if (!empty($arrayfields['origin']['checked'])) {
{
// Origin of movement // Origin of movement
print '<td class="nowraponall">'.$origin.'</td>'; print '<td class="nowraponall">'.$origin.'</td>';
} }
if (!empty($arrayfields['m.value']['checked'])) if (!empty($arrayfields['m.value']['checked'])) {
{
// Qty // Qty
print '<td class="right">'; print '<td class="right">';
if ($objp->qt > 0) print '+'; if ($objp->qt > 0) {
print '+';
}
print $objp->qty; print $objp->qty;
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['m.price']['checked'])) if (!empty($arrayfields['m.price']['checked'])) {
{
// Price // Price
print '<td class="right">'; print '<td class="right">';
if ($objp->price != 0) print price($objp->price); if ($objp->price != 0) {
print price($objp->price);
}
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['m.fk_projet']['checked'])) if (!empty($arrayfields['m.fk_projet']['checked'])) {
{
// fk_project // fk_project
print '<td align="right">'; print '<td align="right">';
if ($objp->fk_project != 0) print $movement->get_origin($objp->fk_project, 'project'); if ($objp->fk_project != 0) {
print $movement->get_origin($objp->fk_project, 'project');
}
print '</td>'; print '</td>';
} }
// Action column // Action column
print '<td class="nowrap center">'; print '<td class="nowrap center">';
if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
{
$selected = 0; $selected = 0;
if (in_array($objp->mid, $arrayofselected)) $selected = 1; if (in_array($objp->mid, $arrayofselected)) {
$selected = 1;
}
print '<input id="cb'.$objp->mid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$objp->mid.'"'.($selected ? ' checked="checked"' : '').'>'; print '<input id="cb'.$objp->mid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$objp->mid.'"'.($selected ? ' checked="checked"' : '').'>';
} }
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
print "</tr>\n"; print "</tr>\n";
$i++; $i++;
@ -1196,13 +1263,11 @@ if ($resql)
print "</form>"; print "</form>";
// Add number of product when there is a filter on period // Add number of product when there is a filter on period
if (count($arrayofuniqueproduct) == 1 && is_numeric($year)) if (count($arrayofuniqueproduct) == 1 && is_numeric($year)) {
{
print "<br>"; print "<br>";
$productidselected = 0; $productidselected = 0;
foreach ($arrayofuniqueproduct as $key => $val) foreach ($arrayofuniqueproduct as $key => $val) {
{
$productidselected = $key; $productidselected = $key;
$productlabelselected = $val; $productlabelselected = $val;
} }

View File

@ -55,7 +55,9 @@ if (!empty($conf->variants->enabled)) {
// Load translation files required by the page // Load translation files required by the page
$langs->loadlangs(array('products', 'suppliers', 'orders', 'bills', 'stocks', 'sendings', 'margins')); $langs->loadlangs(array('products', 'suppliers', 'orders', 'bills', 'stocks', 'sendings', 'margins'));
if (!empty($conf->productbatch->enabled)) $langs->load("productbatch"); if (!empty($conf->productbatch->enabled)) {
$langs->load("productbatch");
}
$backtopage = GETPOST('backtopage', 'alpha'); $backtopage = GETPOST('backtopage', 'alpha');
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
@ -76,7 +78,9 @@ if (!empty($batchnumber)) {
} }
// Security check // Security check
if ($user->socid) $socid = $user->socid; if ($user->socid) {
$socid = $user->socid;
}
$result = restrictedArea($user, 'produit&stock', $id, 'product&product', '', '', $fieldid); $result = restrictedArea($user, 'produit&stock', $id, 'product&product', '', '', $fieldid);
@ -86,20 +90,20 @@ $extrafields = new ExtraFields($db);
// fetch optionals attributes and labels // fetch optionals attributes and labels
$extrafields->fetch_name_optionals_label($object->table_element); $extrafields->fetch_name_optionals_label($object->table_element);
if ($id > 0 || !empty($ref)) if ($id > 0 || !empty($ref)) {
{
$result = $object->fetch($id, $ref); $result = $object->fetch($id, $ref);
} }
if (empty($id) && !empty($object->id)) $id = $object->id; if (empty($id) && !empty($object->id)) {
$id = $object->id;
}
$modulepart = 'product'; $modulepart = 'product';
// Get object canvas (By default, this is not defined, so standard usage of dolibarr) // Get object canvas (By default, this is not defined, so standard usage of dolibarr)
$canvas = !empty($object->canvas) ? $object->canvas : GETPOST("canvas"); $canvas = !empty($object->canvas) ? $object->canvas : GETPOST("canvas");
$objcanvas = null; $objcanvas = null;
if (!empty($canvas)) if (!empty($canvas)) {
{
require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php';
$objcanvas = new Canvas($db, $action); $objcanvas = new Canvas($db, $action);
$objcanvas->getCanvas('stockproduct', 'card', $canvas); $objcanvas->getCanvas('stockproduct', 'card', $canvas);
@ -115,14 +119,17 @@ $error = 0;
* Actions * Actions
*/ */
if ($cancel) $action = ''; if ($cancel) {
$action = '';
}
$parameters = array('id'=>$id, 'ref'=>$ref, 'objcanvas'=>$objcanvas); $parameters = array('id'=>$id, 'ref'=>$ref, 'objcanvas'=>$objcanvas);
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if ($action == 'addlimitstockwarehouse' && !empty($user->rights->produit->creer)) if ($action == 'addlimitstockwarehouse' && !empty($user->rights->produit->creer)) {
{
$seuil_stock_alerte = GETPOST('seuil_stock_alerte'); $seuil_stock_alerte = GETPOST('seuil_stock_alerte');
$desiredstock = GETPOST('desiredstock'); $desiredstock = GETPOST('desiredstock');
@ -142,14 +149,18 @@ if ($action == 'addlimitstockwarehouse' && !empty($user->rights->produit->creer)
// Update // Update
$pse->seuil_stock_alerte = $seuil_stock_alerte; $pse->seuil_stock_alerte = $seuil_stock_alerte;
$pse->desiredstock = $desiredstock; $pse->desiredstock = $desiredstock;
if ($pse->update($user) > 0) setEventMessages($langs->trans('ProductStockWarehouseUpdated'), null, 'mesgs'); if ($pse->update($user) > 0) {
setEventMessages($langs->trans('ProductStockWarehouseUpdated'), null, 'mesgs');
}
} else { } else {
// Create // Create
$pse->fk_entrepot = GETPOST('fk_entrepot', 'int'); $pse->fk_entrepot = GETPOST('fk_entrepot', 'int');
$pse->fk_product = $id; $pse->fk_product = $id;
$pse->seuil_stock_alerte = GETPOST('seuil_stock_alerte'); $pse->seuil_stock_alerte = GETPOST('seuil_stock_alerte');
$pse->desiredstock = GETPOST('desiredstock'); $pse->desiredstock = GETPOST('desiredstock');
if ($pse->create($user) > 0) setEventMessages($langs->trans('ProductStockWarehouseCreated'), null, 'mesgs'); if ($pse->create($user) > 0) {
setEventMessages($langs->trans('ProductStockWarehouseCreated'), null, 'mesgs');
}
} }
} }
@ -157,66 +168,62 @@ if ($action == 'addlimitstockwarehouse' && !empty($user->rights->produit->creer)
exit; exit;
} }
if ($action == 'delete_productstockwarehouse' && !empty($user->rights->produit->creer)) if ($action == 'delete_productstockwarehouse' && !empty($user->rights->produit->creer)) {
{
$pse = new ProductStockEntrepot($db); $pse = new ProductStockEntrepot($db);
$pse->fetch(GETPOST('fk_productstockwarehouse', 'int')); $pse->fetch(GETPOST('fk_productstockwarehouse', 'int'));
if ($pse->delete($user) > 0) setEventMessages($langs->trans('ProductStockWarehouseDeleted'), null, 'mesgs'); if ($pse->delete($user) > 0) {
setEventMessages($langs->trans('ProductStockWarehouseDeleted'), null, 'mesgs');
}
$action = ''; $action = '';
} }
// Set stock limit // Set stock limit
if ($action == 'setseuil_stock_alerte' && !empty($user->rights->produit->creer)) if ($action == 'setseuil_stock_alerte' && !empty($user->rights->produit->creer)) {
{
$object = new Product($db); $object = new Product($db);
$result = $object->fetch($id); $result = $object->fetch($id);
$object->seuil_stock_alerte = $stocklimit; $object->seuil_stock_alerte = $stocklimit;
$result = $object->update($object->id, $user, 0, 'update'); $result = $object->update($object->id, $user, 0, 'update');
if ($result < 0) if ($result < 0) {
setEventMessages($object->error, $object->errors, 'errors'); setEventMessages($object->error, $object->errors, 'errors');
}
//else //else
// setEventMessages($lans->trans("SavedRecordSuccessfully"), null, 'mesgs'); // setEventMessages($lans->trans("SavedRecordSuccessfully"), null, 'mesgs');
$action = ''; $action = '';
} }
// Set desired stock // Set desired stock
if ($action == 'setdesiredstock' && !empty($user->rights->produit->creer)) if ($action == 'setdesiredstock' && !empty($user->rights->produit->creer)) {
{
$object = new Product($db); $object = new Product($db);
$result = $object->fetch($id); $result = $object->fetch($id);
$object->desiredstock = $desiredstock; $object->desiredstock = $desiredstock;
$result = $object->update($object->id, $user, 0, 'update'); $result = $object->update($object->id, $user, 0, 'update');
if ($result < 0) if ($result < 0) {
setEventMessages($object->error, $object->errors, 'errors'); setEventMessages($object->error, $object->errors, 'errors');
}
$action = ''; $action = '';
} }
// Correct stock // Correct stock
if ($action == "correct_stock" && !$cancel) if ($action == "correct_stock" && !$cancel) {
{ if (!(GETPOST("id_entrepot", 'int') > 0)) {
if (!(GETPOST("id_entrepot", 'int') > 0))
{
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
$error++; $error++;
$action = 'correction'; $action = 'correction';
} }
if (!GETPOST("nbpiece")) if (!GETPOST("nbpiece")) {
{
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NumberOfUnit")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NumberOfUnit")), null, 'errors');
$error++; $error++;
$action = 'correction'; $action = 'correction';
} }
if (!empty($conf->productbatch->enabled)) if (!empty($conf->productbatch->enabled)) {
{
$object = new Product($db); $object = new Product($db);
$result = $object->fetch($id); $result = $object->fetch($id);
if ($object->hasbatch() && !$batchnumber) if ($object->hasbatch() && !$batchnumber) {
{
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("batch_number")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("batch_number")), null, 'errors');
$error++; $error++;
$action = 'correction'; $action = 'correction';
@ -293,43 +300,35 @@ if ($action == "correct_stock" && !$cancel)
} }
// Transfer stock from a warehouse to another warehouse // Transfer stock from a warehouse to another warehouse
if ($action == "transfert_stock" && !$cancel) if ($action == "transfert_stock" && !$cancel) {
{ if (!(GETPOST("id_entrepot", 'int') > 0) || !(GETPOST("id_entrepot_destination", 'int') > 0)) {
if (!(GETPOST("id_entrepot", 'int') > 0) || !(GETPOST("id_entrepot_destination", 'int') > 0))
{
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
$error++; $error++;
$action = 'transfert'; $action = 'transfert';
} }
if (!GETPOST("nbpiece", 'int')) if (!GETPOST("nbpiece", 'int')) {
{
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NumberOfUnit")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NumberOfUnit")), null, 'errors');
$error++; $error++;
$action = 'transfert'; $action = 'transfert';
} }
if (GETPOST("id_entrepot", 'int') == GETPOST("id_entrepot_destination", 'int')) if (GETPOST("id_entrepot", 'int') == GETPOST("id_entrepot_destination", 'int')) {
{
setEventMessages($langs->trans("ErrorSrcAndTargetWarehouseMustDiffers"), null, 'errors'); setEventMessages($langs->trans("ErrorSrcAndTargetWarehouseMustDiffers"), null, 'errors');
$error++; $error++;
$action = 'transfert'; $action = 'transfert';
} }
if (!empty($conf->productbatch->enabled)) if (!empty($conf->productbatch->enabled)) {
{
$object = new Product($db); $object = new Product($db);
$result = $object->fetch($id); $result = $object->fetch($id);
if ($object->hasbatch() && !$batchnumber) if ($object->hasbatch() && !$batchnumber) {
{
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("batch_number")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("batch_number")), null, 'errors');
$error++; $error++;
$action = 'transfert'; $action = 'transfert';
} }
} }
if (!$error) if (!$error) {
{ if ($id) {
if ($id)
{
$object = new Product($db); $object = new Product($db);
$result = $object->fetch($id); $result = $object->fetch($id);
@ -339,20 +338,19 @@ if ($action == "transfert_stock" && !$cancel)
// Define value of products moved // Define value of products moved
$pricesrc = 0; $pricesrc = 0;
if (isset($object->pmp)) $pricesrc = $object->pmp; if (isset($object->pmp)) {
$pricesrc = $object->pmp;
}
$pricedest = $pricesrc; $pricedest = $pricesrc;
$nbpiece = price2num(GETPOST("nbpiece", 'alphanohtml')); $nbpiece = price2num(GETPOST("nbpiece", 'alphanohtml'));
if ($object->hasbatch()) if ($object->hasbatch()) {
{
$pdluo = new Productbatch($db); $pdluo = new Productbatch($db);
if ($pdluoid > 0) if ($pdluoid > 0) {
{
$result = $pdluo->fetch($pdluoid); $result = $pdluo->fetch($pdluoid);
if ($result) if ($result) {
{
$srcwarehouseid = $pdluo->warehouseid; $srcwarehouseid = $pdluo->warehouseid;
$batch = $pdluo->batch; $batch = $pdluo->batch;
$eatby = $pdluo->eatby; $eatby = $pdluo->eatby;
@ -370,8 +368,7 @@ if ($action == "transfert_stock" && !$cancel)
$nbpiece = price2num(GETPOST("nbpiece", 'alphanohtml')); $nbpiece = price2num(GETPOST("nbpiece", 'alphanohtml'));
if (!$error) if (!$error) {
{
// Remove stock // Remove stock
$result1 = $object->correct_stock_batch( $result1 = $object->correct_stock_batch(
$user, $user,
@ -380,13 +377,16 @@ if ($action == "transfert_stock" && !$cancel)
1, 1,
GETPOST("label", 'alphanohtml'), GETPOST("label", 'alphanohtml'),
$pricesrc, $pricesrc,
$eatby, $sellby, $batch, $eatby,
$sellby,
$batch,
GETPOST('inventorycode', 'alphanohtml') GETPOST('inventorycode', 'alphanohtml')
); );
if ($result1 < 0) $error++; if ($result1 < 0) {
$error++;
} }
if (!$error) }
{ if (!$error) {
// Add stock // Add stock
$result2 = $object->correct_stock_batch( $result2 = $object->correct_stock_batch(
$user, $user,
@ -395,14 +395,17 @@ if ($action == "transfert_stock" && !$cancel)
0, 0,
GETPOST("label", 'alphanohtml'), GETPOST("label", 'alphanohtml'),
$pricedest, $pricedest,
$eatby, $sellby, $batch, $eatby,
$sellby,
$batch,
GETPOST('inventorycode', 'alphanohtml') GETPOST('inventorycode', 'alphanohtml')
); );
if ($result2 < 0) $error++; if ($result2 < 0) {
$error++;
}
} }
} else { } else {
if (!$error) if (!$error) {
{
// Remove stock // Remove stock
$result1 = $object->correct_stock( $result1 = $object->correct_stock(
$user, $user,
@ -413,10 +416,11 @@ if ($action == "transfert_stock" && !$cancel)
$pricesrc, $pricesrc,
GETPOST('inventorycode', 'alphanohtml') GETPOST('inventorycode', 'alphanohtml')
); );
if ($result1 < 0) $error++; if ($result1 < 0) {
$error++;
} }
if (!$error) }
{ if (!$error) {
// Add stock // Add stock
$result2 = $object->correct_stock( $result2 = $object->correct_stock(
$user, $user,
@ -427,17 +431,17 @@ if ($action == "transfert_stock" && !$cancel)
$pricedest, $pricedest,
GETPOST('inventorycode', 'alphanohtml') GETPOST('inventorycode', 'alphanohtml')
); );
if ($result2 < 0) $error++; if ($result2 < 0) {
$error++;
}
} }
} }
if (!$error && $result1 >= 0 && $result2 >= 0) if (!$error && $result1 >= 0 && $result2 >= 0) {
{
$db->commit(); $db->commit();
if ($backtopage) if ($backtopage) {
{
header("Location: ".$backtopage); header("Location: ".$backtopage);
exit; exit;
} else { } else {
@ -454,15 +458,12 @@ if ($action == "transfert_stock" && !$cancel)
} }
// Update batch information // Update batch information
if ($action == 'updateline' && GETPOST('save') == $langs->trans("Save")) if ($action == 'updateline' && GETPOST('save') == $langs->trans("Save")) {
{
$pdluo = new Productbatch($db); $pdluo = new Productbatch($db);
$result = $pdluo->fetch(GETPOST('pdluoid', 'int')); $result = $pdluo->fetch(GETPOST('pdluoid', 'int'));
if ($result > 0) if ($result > 0) {
{ if ($pdluo->id) {
if ($pdluo->id)
{
if ((!GETPOST("sellby")) && (!GETPOST("eatby")) && (!$batchnumber)) { if ((!GETPOST("sellby")) && (!GETPOST("eatby")) && (!$batchnumber)) {
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("atleast1batchfield")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("atleast1batchfield")), null, 'errors');
} else { } else {
@ -472,8 +473,7 @@ if ($action == 'updateline' && GETPOST('save') == $langs->trans("Save"))
$pdluo->eatby = $d_eatby; $pdluo->eatby = $d_eatby;
$pdluo->sellby = $d_sellby; $pdluo->sellby = $d_sellby;
$result = $pdluo->update($user); $result = $pdluo->update($user);
if ($result < 0) if ($result < 0) {
{
setEventMessages($pdluo->error, $pdluo->errors, 'errors'); setEventMessages($pdluo->error, $pdluo->errors, 'errors');
} }
} }
@ -495,10 +495,11 @@ if ($action == 'updateline' && GETPOST('save') == $langs->trans("Save"))
$form = new Form($db); $form = new Form($db);
$formproduct = new FormProduct($db); $formproduct = new FormProduct($db);
if (!empty($conf->projet->enabled)) $formproject = new FormProjets($db); if (!empty($conf->projet->enabled)) {
$formproject = new FormProjets($db);
}
if ($id > 0 || $ref) if ($id > 0 || $ref) {
{
$object = new Product($db); $object = new Product($db);
$result = $object->fetch($id, $ref); $result = $object->fetch($id, $ref);
@ -509,21 +510,18 @@ if ($id > 0 || $ref)
$title = $langs->trans('ProductServiceCard'); $title = $langs->trans('ProductServiceCard');
$helpurl = ''; $helpurl = '';
$shortlabel = dol_trunc($object->label, 16); $shortlabel = dol_trunc($object->label, 16);
if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) {
{
$title = $langs->trans('Product')." ".$shortlabel." - ".$langs->trans('Stock'); $title = $langs->trans('Product')." ".$shortlabel." - ".$langs->trans('Stock');
$helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos'; $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos';
} }
if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) {
{
$title = $langs->trans('Service')." ".$shortlabel." - ".$langs->trans('Stock'); $title = $langs->trans('Service')." ".$shortlabel." - ".$langs->trans('Stock');
$helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios'; $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios';
} }
llxHeader('', $title, $helpurl); llxHeader('', $title, $helpurl);
if ($result > 0) if ($result > 0) {
{
$head = product_prepare_head($object); $head = product_prepare_head($object);
$titre = $langs->trans("CardProduct".$object->type); $titre = $langs->trans("CardProduct".$object->type);
$picto = ($object->type == Product::TYPE_SERVICE ? 'service' : 'product'); $picto = ($object->type == Product::TYPE_SERVICE ? 'service' : 'product');
@ -535,7 +533,9 @@ if ($id > 0 || $ref)
$linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; $linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
$shownav = 1; $shownav = 1;
if ($user->socid && !in_array('stock', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; if ($user->socid && !in_array('stock', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) {
$shownav = 0;
}
dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref');
@ -566,7 +566,9 @@ if ($id > 0 || $ref)
// AWP // AWP
print '<tr><td class="titlefield">'.$form->textwithpicto($langs->trans("AverageUnitPricePMPShort"), $langs->trans("AverageUnitPricePMPDesc")).'</td>'; print '<tr><td class="titlefield">'.$form->textwithpicto($langs->trans("AverageUnitPricePMPShort"), $langs->trans("AverageUnitPricePMPDesc")).'</td>';
print '<td>'; print '<td>';
if ($object->pmp > 0) print price($object->pmp).' '.$langs->trans("HT"); if ($object->pmp > 0) {
print price($object->pmp).' '.$langs->trans("HT");
}
print '</td>'; print '</td>';
print '</tr>'; print '</tr>';
@ -575,8 +577,11 @@ if ($id > 0 || $ref)
print '<td>'; print '<td>';
$product_fourn = new ProductFournisseur($db); $product_fourn = new ProductFournisseur($db);
if ($product_fourn->find_min_price_product_fournisseur($object->id) > 0) { if ($product_fourn->find_min_price_product_fournisseur($object->id) > 0) {
if ($product_fourn->product_fourn_price_id > 0) print $product_fourn->display_price_product_fournisseur(); if ($product_fourn->product_fourn_price_id > 0) {
else print $langs->trans("NotDefined"); print $product_fourn->display_price_product_fournisseur();
} else {
print $langs->trans("NotDefined");
}
} }
print '</td></tr>'; print '</td></tr>';
@ -648,7 +653,9 @@ if ($id > 0 || $ref)
print $form->textwithpicto($langs->trans("PhysicalStock"), $text_stock_options, 1); print $form->textwithpicto($langs->trans("PhysicalStock"), $text_stock_options, 1);
print '</td>'; print '</td>';
print '<td>'.price2num($object->stock_reel, 'MS'); print '<td>'.price2num($object->stock_reel, 'MS');
if ($object->seuil_stock_alerte != '' && ($object->stock_reel < $object->seuil_stock_alerte)) print ' '.img_warning($langs->trans("StockLowerThanLimit", $object->seuil_stock_alerte)); if ($object->seuil_stock_alerte != '' && ($object->stock_reel < $object->seuil_stock_alerte)) {
print ' '.img_warning($langs->trans("StockLowerThanLimit", $object->seuil_stock_alerte));
}
print ' &nbsp; &nbsp;<a href="'.DOL_URL_ROOT.'/product/stock/stockatdate.php?productid='.$object->id.'">'.$langs->trans("StockAtDate").'</a>'; print ' &nbsp; &nbsp;<a href="'.DOL_URL_ROOT.'/product/stock/stockatdate.php?productid='.$object->id.'">'.$langs->trans("StockAtDate").'</a>';
print '</td>'; print '</td>';
@ -660,10 +667,16 @@ if ($id > 0 || $ref)
$helpondiff = '<strong>'.$langs->trans("StockDiffPhysicTeoric").':</strong><br>'; $helpondiff = '<strong>'.$langs->trans("StockDiffPhysicTeoric").':</strong><br>';
// Number of customer orders running // Number of customer orders running
if (!empty($conf->commande->enabled)) { if (!empty($conf->commande->enabled)) {
if ($found) $helpondiff .= '<br>'; else $found = 1; if ($found) {
$helpondiff .= '<br>';
} else {
$found = 1;
}
$helpondiff .= $langs->trans("ProductQtyInCustomersOrdersRunning").': '.$object->stats_commande['qty']; $helpondiff .= $langs->trans("ProductQtyInCustomersOrdersRunning").': '.$object->stats_commande['qty'];
$result = $object->load_stats_commande(0, '0', 1); $result = $object->load_stats_commande(0, '0', 1);
if ($result < 0) dol_print_error($db, $object->error); if ($result < 0) {
dol_print_error($db, $object->error);
}
$helpondiff .= ' ('.$langs->trans("ProductQtyInDraft").': '.$object->stats_commande['qty'].')'; $helpondiff .= ' ('.$langs->trans("ProductQtyInDraft").': '.$object->stats_commande['qty'].')';
} }
@ -676,31 +689,48 @@ if ($id > 0 || $ref)
} elseif (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) { } elseif (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) {
$filterShipmentStatus = Expedition::STATUS_CLOSED; $filterShipmentStatus = Expedition::STATUS_CLOSED;
} }
if ($found) $helpondiff .= '<br>'; else $found = 1; if ($found) {
$helpondiff .= '<br>';
} else {
$found = 1;
}
$result = $object->load_stats_sending(0, '2', 1, $filterShipmentStatus); $result = $object->load_stats_sending(0, '2', 1, $filterShipmentStatus);
$helpondiff .= $langs->trans("ProductQtyInShipmentAlreadySent").': '.$object->stats_expedition['qty']; $helpondiff .= $langs->trans("ProductQtyInShipmentAlreadySent").': '.$object->stats_expedition['qty'];
} }
// Number of supplier order running // Number of supplier order running
if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) {
{ if ($found) {
if ($found) $helpondiff .= '<br>'; else $found = 1; $helpondiff .= '<br>';
} else {
$found = 1;
}
$result = $object->load_stats_commande_fournisseur(0, '3,4', 1); $result = $object->load_stats_commande_fournisseur(0, '3,4', 1);
$helpondiff .= $langs->trans("ProductQtyInSuppliersOrdersRunning").': '.$object->stats_commande_fournisseur['qty']; $helpondiff .= $langs->trans("ProductQtyInSuppliersOrdersRunning").': '.$object->stats_commande_fournisseur['qty'];
$result = $object->load_stats_commande_fournisseur(0, '0,1,2', 1); $result = $object->load_stats_commande_fournisseur(0, '0,1,2', 1);
if ($result < 0) dol_print_error($db, $object->error); if ($result < 0) {
dol_print_error($db, $object->error);
}
$helpondiff .= ' ('.$langs->trans("ProductQtyInDraftOrWaitingApproved").': '.$object->stats_commande_fournisseur['qty'].')'; $helpondiff .= ' ('.$langs->trans("ProductQtyInDraftOrWaitingApproved").': '.$object->stats_commande_fournisseur['qty'].')';
} }
// Number of product from supplier order already received (partial receipt) // Number of product from supplier order already received (partial receipt)
if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) { if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) {
if ($found) $helpondiff .= '<br>'; else $found = 1; if ($found) {
$helpondiff .= '<br>';
} else {
$found = 1;
}
$helpondiff .= $langs->trans("ProductQtyInSuppliersShipmentAlreadyRecevied").': '.$object->stats_reception['qty']; $helpondiff .= $langs->trans("ProductQtyInSuppliersShipmentAlreadyRecevied").': '.$object->stats_reception['qty'];
} }
// Number of product in production // Number of product in production
if (!empty($conf->mrp->enabled)) { if (!empty($conf->mrp->enabled)) {
if ($found) $helpondiff .= '<br>'; else $found = 1; if ($found) {
$helpondiff .= '<br>';
} else {
$found = 1;
}
$helpondiff .= $langs->trans("ProductQtyToConsumeByMO").': '.$object->stats_mrptoconsume['qty'].'<br>'; $helpondiff .= $langs->trans("ProductQtyToConsumeByMO").': '.$object->stats_mrptoconsume['qty'].'<br>';
$helpondiff .= $langs->trans("ProductQtyToProduceByMO").': '.$object->stats_mrptoproduce['qty']; $helpondiff .= $langs->trans("ProductQtyToProduceByMO").': '.$object->stats_mrptoproduce['qty'];
} }
@ -713,14 +743,15 @@ if ($id > 0 || $ref)
print "<td>"; print "<td>";
//print (empty($stocktheo)?0:$stocktheo); //print (empty($stocktheo)?0:$stocktheo);
print $form->textwithpicto((empty($stocktheo) ? 0 : $stocktheo), $helpondiff); print $form->textwithpicto((empty($stocktheo) ? 0 : $stocktheo), $helpondiff);
if ($object->seuil_stock_alerte != '' && ($object->stock_theorique < $object->seuil_stock_alerte)) print ' '.img_warning($langs->trans("StockLowerThanLimit", $object->seuil_stock_alerte)); if ($object->seuil_stock_alerte != '' && ($object->stock_theorique < $object->seuil_stock_alerte)) {
print ' '.img_warning($langs->trans("StockLowerThanLimit", $object->seuil_stock_alerte));
}
print ' &nbsp; &nbsp;<a href="'.DOL_URL_ROOT.'/product/stock/stockatdate.php?mode=future&productid='.$object->id.'">'.$langs->trans("VirtualStockAtDate").'</a>'; print ' &nbsp; &nbsp;<a href="'.DOL_URL_ROOT.'/product/stock/stockatdate.php?mode=future&productid='.$object->id.'">'.$langs->trans("VirtualStockAtDate").'</a>';
print '</td>'; print '</td>';
print '</tr>'; print '</tr>';
// Last movement // Last movement
if (!empty($user->rights->stock->mouvement->lire)) if (!empty($user->rights->stock->mouvement->lire)) {
{
$sql = "SELECT max(m.datem) as datem"; $sql = "SELECT max(m.datem) as datem";
$sql .= " FROM ".MAIN_DB_PREFIX."stock_mouvement as m"; $sql .= " FROM ".MAIN_DB_PREFIX."stock_mouvement as m";
$sql .= " WHERE m.fk_product = ".((int) $object->id); $sql .= " WHERE m.fk_product = ".((int) $object->id);
@ -754,15 +785,13 @@ if ($id > 0 || $ref)
} }
// Correct stock // Correct stock
if ($action == "correction") if ($action == "correction") {
{
include DOL_DOCUMENT_ROOT.'/product/stock/tpl/stockcorrection.tpl.php'; include DOL_DOCUMENT_ROOT.'/product/stock/tpl/stockcorrection.tpl.php';
print '<br><br>'; print '<br><br>';
} }
// Transfer of units // Transfer of units
if ($action == "transfert") if ($action == "transfert") {
{
include DOL_DOCUMENT_ROOT.'/product/stock/tpl/stocktransfer.tpl.php'; include DOL_DOCUMENT_ROOT.'/product/stock/tpl/stocktransfer.tpl.php';
print '<br><br>'; print '<br><br>';
} }
@ -776,14 +805,11 @@ if ($id > 0 || $ref)
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
if (empty($reshook)) if (empty($reshook)) {
{ if (empty($action) && $object->id) {
if (empty($action) && $object->id)
{
print "<div class=\"tabsAction\">\n"; print "<div class=\"tabsAction\">\n";
if ($user->rights->stock->mouvement->creer) if ($user->rights->stock->mouvement->creer) {
{
if (!$variants || !empty($conf->global->VARIANT_ALLOW_STOCK_MOVEMENT_ON_VARIANT_PARENT)) { if (!$variants || !empty($conf->global->VARIANT_ALLOW_STOCK_MOVEMENT_ON_VARIANT_PARENT)) {
print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=correction">'.$langs->trans("CorrectStock").'</a>'; print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=correction">'.$langs->trans("CorrectStock").'</a>';
} else { } else {
@ -794,8 +820,7 @@ if (empty($reshook))
} }
//if (($user->rights->stock->mouvement->creer) && ! $object->hasbatch()) //if (($user->rights->stock->mouvement->creer) && ! $object->hasbatch())
if ($user->rights->stock->mouvement->creer) if ($user->rights->stock->mouvement->creer) {
{
if (!$variants || !empty($conf->global->VARIANT_ALLOW_STOCK_MOVEMENT_ON_VARIANT_PARENT)) { if (!$variants || !empty($conf->global->VARIANT_ALLOW_STOCK_MOVEMENT_ON_VARIANT_PARENT)) {
print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=transfert">'.$langs->trans("TransferStock").'</a>'; print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=transfert">'.$langs->trans("TransferStock").'</a>';
} else { } else {
@ -888,22 +913,32 @@ if (!$variants) {
print '<td class="right">'.(price2num($object->pmp) ? price(price2num($object->pmp * $obj->reel, 'MT')) : '').'</td>'; print '<td class="right">'.(price2num($object->pmp) ? price(price2num($object->pmp * $obj->reel, 'MT')) : '').'</td>';
// Sell price // Sell price
print '<td class="right">'; print '<td class="right">';
if (empty($conf->global->PRODUIT_MULTIPRICES)) print price(price2num($object->price, 'MU'), 1); if (empty($conf->global->PRODUIT_MULTIPRICES)) {
else print $langs->trans("Variable"); print price(price2num($object->price, 'MU'), 1);
} else {
print $langs->trans("Variable");
}
print '</td>'; print '</td>';
// Value sell // Value sell
print '<td class="right">'; print '<td class="right">';
if (empty($conf->global->PRODUIT_MULTIPRICES)) print price(price2num($object->price * $obj->reel, 'MT'), 1).'</td>'; if (empty($conf->global->PRODUIT_MULTIPRICES)) {
else print $langs->trans("Variable"); print price(price2num($object->price * $obj->reel, 'MT'), 1).'</td>';
} else {
print $langs->trans("Variable");
}
print '</tr>'; print '</tr>';
$total += $obj->reel; $total += $obj->reel;
if (price2num($object->pmp)) $totalwithpmp += $obj->reel; if (price2num($object->pmp)) {
$totalwithpmp += $obj->reel;
}
$totalvalue = $totalvalue + ($object->pmp * $obj->reel); $totalvalue = $totalvalue + ($object->pmp * $obj->reel);
$totalvaluesell = $totalvaluesell + ($object->price * $obj->reel); $totalvaluesell = $totalvaluesell + ($object->price * $obj->reel);
// Batch Detail // Batch Detail
if ((!empty($conf->productbatch->enabled)) && $object->hasbatch()) { if ((!empty($conf->productbatch->enabled)) && $object->hasbatch()) {
$details = Productbatch::findAll($db, $obj->product_stock_id, 0, $object->id); $details = Productbatch::findAll($db, $obj->product_stock_id, 0, $object->id);
if ($details < 0) dol_print_error($db); if ($details < 0) {
dol_print_error($db);
}
foreach ($details as $pdluo) { foreach ($details as $pdluo) {
$product_lot_static->id = $pdluo->lotid; $product_lot_static->id = $pdluo->lotid;
$product_lot_static->batch = $pdluo->batch; $product_lot_static->batch = $pdluo->batch;
@ -961,7 +996,9 @@ if (!$variants) {
} }
$i++; $i++;
} }
} else dol_print_error($db); } else {
dol_print_error($db);
}
// Total line // Total line
print '<tr class="liste_total"><td class="right liste_total" colspan="4">'.$langs->trans("Total").':</td>'; print '<tr class="liste_total"><td class="right liste_total" colspan="4">'.$langs->trans("Total").':</td>';
@ -974,13 +1011,19 @@ if (!$variants) {
print $totalvalue ? price(price2num($totalvalue, 'MT'), 1) : '&nbsp;'; print $totalvalue ? price(price2num($totalvalue, 'MT'), 1) : '&nbsp;';
print '</td>'; print '</td>';
print '<td class="liste_total right">'; print '<td class="liste_total right">';
if (empty($conf->global->PRODUIT_MULTIPRICES)) print ($total ? price($totalvaluesell / $total, 1) : '&nbsp;'); if (empty($conf->global->PRODUIT_MULTIPRICES)) {
else print $langs->trans("Variable"); print ($total ? price($totalvaluesell / $total, 1) : '&nbsp;');
} else {
print $langs->trans("Variable");
}
print '</td>'; print '</td>';
// Value to sell // Value to sell
print '<td class="liste_total right">'; print '<td class="liste_total right">';
if (empty($conf->global->PRODUIT_MULTIPRICES)) print price(price2num($totalvaluesell, 'MT'), 1); if (empty($conf->global->PRODUIT_MULTIPRICES)) {
else print $langs->trans("Variable"); print price(price2num($totalvaluesell, 'MT'), 1);
} else {
print $langs->trans("Variable");
}
print '</td>'; print '</td>';
print "</tr>"; print "</tr>";
@ -1068,11 +1111,9 @@ if (!$variants) {
</tr> </tr>
<?php <?php
if (count($productCombinations)) if (count($productCombinations)) {
{
$stock_total = 0; $stock_total = 0;
foreach ($productCombinations as $currcomb) foreach ($productCombinations as $currcomb) {
{
$prodstatic->fetch($currcomb->fk_product_child); $prodstatic->fetch($currcomb->fk_product_child);
$prodstatic->load_stock(); $prodstatic->load_stock();
$stock_total += $prodstatic->stock_reel; $stock_total += $prodstatic->stock_reel;

View File

@ -76,14 +76,14 @@ $search_fk_user_creat = GETPOST('search_fk_user_creat', 'int');
$search_fk_user_modif = GETPOST('search_fk_user_modif', 'int'); $search_fk_user_modif = GETPOST('search_fk_user_modif', 'int');
$search_import_key = GETPOST('search_import_key', 'int'); $search_import_key = GETPOST('search_import_key', 'int');
if (empty($action) && empty($id) && empty($ref)) $action = 'list'; if (empty($action) && empty($id) && empty($ref)) {
$action = 'list';
}
// Load object // Load object
//include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals //include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals
if ($id || $ref) if ($id || $ref) {
{ if ($ref) {
if ($ref)
{
$tmp = explode('_', $ref); $tmp = explode('_', $ref);
$productid = $tmp[0]; $productid = $tmp[0];
$batch = $tmp[1]; $batch = $tmp[1];
@ -93,8 +93,7 @@ if ($id || $ref)
} }
// Protection if external user // Protection if external user
if ($user->socid > 0) if ($user->socid > 0) {
{
//accessforbidden(); //accessforbidden();
} }
//$result = restrictedArea($user, 'mymodule', $id); //$result = restrictedArea($user, 'mymodule', $id);
@ -133,18 +132,20 @@ if (empty($reshook)) {
$backurlforlist = dol_buildpath('/product/stock/productlot_list.php', 1); $backurlforlist = dol_buildpath('/product/stock/productlot_list.php', 1);
if ($action == 'seteatby' && $user->rights->stock->creer) if ($action == 'seteatby' && $user->rights->stock->creer) {
{
$newvalue = dol_mktime(12, 0, 0, $_POST['eatbymonth'], $_POST['eatbyday'], $_POST['eatbyyear']); $newvalue = dol_mktime(12, 0, 0, $_POST['eatbymonth'], $_POST['eatbyday'], $_POST['eatbyyear']);
$result = $object->setValueFrom('eatby', $newvalue, '', null, 'date', '', $user, 'PRODUCTLOT_MODIFY'); $result = $object->setValueFrom('eatby', $newvalue, '', null, 'date', '', $user, 'PRODUCTLOT_MODIFY');
if ($result < 0) dol_print_error($db, $object->error); if ($result < 0) {
dol_print_error($db, $object->error);
}
} }
if ($action == 'setsellby' && $user->rights->stock->creer) if ($action == 'setsellby' && $user->rights->stock->creer) {
{
$newvalue = dol_mktime(12, 0, 0, $_POST['sellbymonth'], $_POST['sellbyday'], $_POST['sellbyyear']); $newvalue = dol_mktime(12, 0, 0, $_POST['sellbymonth'], $_POST['sellbyday'], $_POST['sellbyyear']);
$result = $object->setValueFrom('sellby', $newvalue, '', null, 'date', '', $user, 'PRODUCTLOT_MODIFY'); $result = $object->setValueFrom('sellby', $newvalue, '', null, 'date', '', $user, 'PRODUCTLOT_MODIFY');
if ($result < 0) dol_print_error($db, $object->error); if ($result < 0) {
dol_print_error($db, $object->error);
}
} }
$triggermodname = 'PRODUCT_LOT_MODIFY'; // Name of trigger action code to execute when we modify record $triggermodname = 'PRODUCT_LOT_MODIFY'; // Name of trigger action code to execute when we modify record
@ -375,7 +376,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
$linkback = '<a href="'.DOL_URL_ROOT.'/product/stock/productlot_list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; $linkback = '<a href="'.DOL_URL_ROOT.'/product/stock/productlot_list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
$shownav = 1; $shownav = 1;
if ($user->socid && !in_array('batch', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; if ($user->socid && !in_array('batch', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) {
$shownav = 0;
}
$morehtmlref = ''; $morehtmlref = '';
@ -436,7 +439,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
print '<div class="tabsAction">'."\n"; print '<div class="tabsAction">'."\n";
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if (empty($reshook)) { if (empty($reshook)) {
/*TODO if ($user->rights->stock->lire) /*TODO if ($user->rights->stock->lire)
@ -453,7 +458,6 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
print '</div>'."\n"; print '</div>'."\n";
} }
} }

View File

@ -48,7 +48,9 @@ $confirm = GETPOST('confirm', 'alpha');
// Security check // Security check
$fieldvalue = (!empty($id) ? $id : ''); $fieldvalue = (!empty($id) ? $id : '');
$fieldtype = 'rowid'; $fieldtype = 'rowid';
if ($user->socid) $socid = $user->socid; if ($user->socid) {
$socid = $user->socid;
}
$result = restrictedArea($user, 'produit|service'); $result = restrictedArea($user, 'produit|service');
// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
@ -59,19 +61,23 @@ $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST("sortfield", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if (!$sortorder) $sortorder = "ASC"; if (!$sortorder) {
if (!$sortfield) $sortfield = "position_name"; $sortorder = "ASC";
}
if (!$sortfield) {
$sortfield = "position_name";
}
$modulepart = 'product_batch'; $modulepart = 'product_batch';
$object = new Productlot($db); $object = new Productlot($db);
if ($id || $ref) if ($id || $ref) {
{ if ($ref) {
if ($ref)
{
$tmp = explode('_', $ref); $tmp = explode('_', $ref);
$productid = $tmp[0]; $productid = $tmp[0];
$batch = $tmp[1]; $batch = $tmp[1];
@ -79,7 +85,9 @@ if ($id || $ref)
$object->fetch($id, $productid, $batch); $object->fetch($id, $productid, $batch);
$object->ref = $object->batch; // For document management ( it use $object->ref) $object->ref = $object->batch; // For document management ( it use $object->ref)
if (!empty($conf->productbatch->enabled)) $upload_dir = $conf->productbatch->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, $modulepart); if (!empty($conf->productbatch->enabled)) {
$upload_dir = $conf->productbatch->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, $modulepart);
}
} }
@ -89,10 +97,11 @@ if ($id || $ref)
$parameters = array('id'=>$id); $parameters = array('id'=>$id);
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if (empty($reshook)) if (empty($reshook)) {
{
// Action submit/delete file/link // Action submit/delete file/link
include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php';
} }
@ -109,8 +118,7 @@ $form = new Form($db);
llxHeader('', $langs->trans('ProductLot'), ''); llxHeader('', $langs->trans('ProductLot'), '');
if ($object->id) if ($object->id) {
{
$head = productlot_prepare_head($object); $head = productlot_prepare_head($object);
print dol_get_fiche_head($head, 'documents', $langs->trans("Batch"), -1, 'barcode'); print dol_get_fiche_head($head, 'documents', $langs->trans("Batch"), -1, 'barcode');
@ -118,14 +126,15 @@ if ($object->id)
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $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 $hookmanager->resPrint;
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
// Build file list // Build file list
$filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
$totalsize = 0; $totalsize = 0;
foreach ($filearray as $key => $file) foreach ($filearray as $key => $file) {
{
$totalsize += $file['size']; $totalsize += $file['size'];
} }
@ -133,7 +142,9 @@ if ($object->id)
$linkback = '<a href="'.DOL_URL_ROOT.'/product/stock/productlot_list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; $linkback = '<a href="'.DOL_URL_ROOT.'/product/stock/productlot_list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
$shownav = 1; $shownav = 1;
if ($user->socid && !in_array('batch', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; if ($user->socid && !in_array('batch', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) {
$shownav = 0;
}
dol_banner_tab($object, 'id', $linkback, $shownav, 'rowid', 'batch'); dol_banner_tab($object, 'id', $linkback, $shownav, 'rowid', 'batch');

View File

@ -54,7 +54,9 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST('sortfield', 'aZ09comma'); $sortfield = GETPOST('sortfield', 'aZ09comma');
$sortorder = GETPOST('sortorder', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
@ -72,28 +74,33 @@ $extrafields->fetch_name_optionals_label($object->table_element);
$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
// Default sort order (if not yet defined by previous GETPOST) // Default sort order (if not yet defined by previous GETPOST)
if (!$sortfield) $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition. if (!$sortfield) {
if (!$sortorder) $sortorder = "ASC"; $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition.
}
if (!$sortorder) {
$sortorder = "ASC";
}
// Initialize array of search criterias // Initialize array of search criterias
$search_all = GETPOST('search_all', 'alphanohtml') ? GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml'); $search_all = GETPOST('search_all', 'alphanohtml') ? GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml');
$search = array(); $search = array();
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{ if (GETPOST('search_'.$key, 'alpha') !== '') {
if (GETPOST('search_'.$key, 'alpha') !== '') $search[$key] = GETPOST('search_'.$key, 'alpha'); $search[$key] = GETPOST('search_'.$key, 'alpha');
}
} }
// List of fields to search into when doing a "search in all" // List of fields to search into when doing a "search in all"
$fieldstosearchall = array(); $fieldstosearchall = array();
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{ if ($val['searchall']) {
if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label']; $fieldstosearchall['t.'.$key] = $val['label'];
}
} }
// Definition of array of fields for columns // Definition of array of fields for columns
$arrayfields = array(); $arrayfields = array();
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{
// If $val['visible']==0, then we never show the field // If $val['visible']==0, then we never show the field
if (!empty($val['visible'])) { if (!empty($val['visible'])) {
$visible = dol_eval($val['visible'], 1); $visible = dol_eval($val['visible'], 1);
@ -106,10 +113,8 @@ foreach ($object->fields as $key => $val)
} }
} }
// Extra fields // Extra fields
if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) {
{ foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val)
{
if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) { if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) {
$arrayfields["ef.".$key] = array( $arrayfields["ef.".$key] = array(
'label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'label'=>$extrafields->attributes[$object->table_element]['label'][$key],
@ -134,31 +139,33 @@ $permissiontoadd = $user->rights->stock->mouvement->creer;
* Actions * Actions
*/ */
if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } if (GETPOST('cancel', 'alpha')) {
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } $action = 'list'; $massaction = '';
}
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
$massaction = '';
}
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if (empty($reshook)) if (empty($reshook)) {
{
// Selection of new fields // Selection of new fields
include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
// Purge search criteria // Purge search criteria
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
{ foreach ($object->fields as $key => $val) {
foreach ($object->fields as $key => $val)
{
$search[$key] = ''; $search[$key] = '';
} }
$toselect = ''; $toselect = '';
$search_array_options = array(); $search_array_options = array();
} }
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') 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')) || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) {
{
$massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation
} }
@ -187,13 +194,14 @@ $title = $langs->trans('LotSerialList');
// Build and execute select // Build and execute select
// -------------------------------------------------------------------- // --------------------------------------------------------------------
$sql = 'SELECT '; $sql = 'SELECT ';
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{
$sql .= 't.'.$key.', '; $sql .= 't.'.$key.', ';
} }
// Add fields from extrafields // Add fields from extrafields
if (!empty($extrafields->attributes[$object->table_element]['label'])) { if (!empty($extrafields->attributes[$object->table_element]['label'])) {
foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.' as options_'.$key.', ' : ''); foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
$sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.' as options_'.$key.', ' : '');
}
} }
// Add fields from hooks // Add fields from hooks
$parameters = array(); $parameters = array();
@ -201,20 +209,32 @@ $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $obje
$sql .= preg_replace('/^,/', '', $hookmanager->resPrint); $sql .= preg_replace('/^,/', '', $hookmanager->resPrint);
$sql = preg_replace('/,\s*$/', '', $sql); $sql = preg_replace('/,\s*$/', '', $sql);
$sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t"; $sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t";
if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) {
if ($object->ismultientitymanaged == 1) $sql .= " WHERE t.entity IN (".getEntity($object->element).")"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)";
else $sql .= " WHERE 1 = 1"; }
foreach ($search as $key => $val) if ($object->ismultientitymanaged == 1) {
{ $sql .= " WHERE t.entity IN (".getEntity($object->element).")";
if ($key == 'status' && $search[$key] == -1) continue; } else {
$sql .= " WHERE 1 = 1";
}
foreach ($search as $key => $val) {
if ($key == 'status' && $search[$key] == -1) {
continue;
}
$mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0); $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0);
if (strpos($object->fields[$key]['type'], 'integer:') === 0) { if (strpos($object->fields[$key]['type'], 'integer:') === 0) {
if ($search[$key] == '-1') $search[$key] = ''; if ($search[$key] == '-1') {
$search[$key] = '';
}
$mode_search = 2; $mode_search = 2;
} }
if ($search[$key] != '') $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search)); if ($search[$key] != '') {
$sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search));
}
}
if ($search_all) {
$sql .= natural_search(array_keys($fieldstosearchall), $search_all);
} }
if ($search_all) $sql .= natural_search(array_keys($fieldstosearchall), $search_all);
//$sql.= dolSqlDateFilter("t.field", $search_xxxday, $search_xxxmonth, $search_xxxyear); //$sql.= dolSqlDateFilter("t.field", $search_xxxday, $search_xxxmonth, $search_xxxyear);
// Add where from extra fields // Add where from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
@ -244,26 +264,24 @@ $sql .= $db->order($sortfield, $sortorder);
// Count total nb of records // Count total nb of records
$nbtotalofrecords = ''; $nbtotalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
{
$resql = $db->query($sql); $resql = $db->query($sql);
$nbtotalofrecords = $db->num_rows($resql); $nbtotalofrecords = $db->num_rows($resql);
if (($page * $limit) > $nbtotalofrecords) // if total of record found is smaller than page * limit, goto and load page 0 if (($page * $limit) > $nbtotalofrecords) { // if total of record found is smaller than page * limit, goto and load page 0
{
$page = 0; $page = 0;
$offset = 0; $offset = 0;
} }
} }
// if total of record found is smaller than limit, no need to do paging and to restart another select with limits set. // if total of record found is smaller than limit, no need to do paging and to restart another select with limits set.
if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit))) if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit))) {
{
$num = $nbtotalofrecords; $num = $nbtotalofrecords;
} else { } else {
if ($limit) $sql .= $db->plimit($limit + 1, $offset); if ($limit) {
$sql .= $db->plimit($limit + 1, $offset);
}
$resql = $db->query($sql); $resql = $db->query($sql);
if (!$resql) if (!$resql) {
{
dol_print_error($db); dol_print_error($db);
exit; exit;
} }
@ -272,8 +290,7 @@ if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit
} }
// Direct jump if only one record found // Direct jump if only one record found
if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
$id = $obj->rowid; $id = $obj->rowid;
header("Location: ".dol_buildpath('/mymodule/myobject_card.php', 1).'?id='.$id); header("Location: ".dol_buildpath('/mymodule/myobject_card.php', 1).'?id='.$id);
@ -289,14 +306,24 @@ llxHeader('', $title, $help_url);
$arrayofselected = is_array($toselect) ? $toselect : array(); $arrayofselected = is_array($toselect) ? $toselect : array();
$param = ''; $param = '';
if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); $param .= '&contextpage='.urlencode($contextpage);
foreach ($search as $key => $val) }
{ if ($limit > 0 && $limit != $conf->liste_limit) {
if (is_array($search[$key]) && count($search[$key])) foreach ($search[$key] as $skey) $param .= '&search_'.$key.'[]='.urlencode($skey); $param .= '&limit='.urlencode($limit);
else $param .= '&search_'.$key.'='.urlencode($search[$key]); }
foreach ($search as $key => $val) {
if (is_array($search[$key]) && count($search[$key])) {
foreach ($search[$key] as $skey) {
$param .= '&search_'.$key.'[]='.urlencode($skey);
}
} else {
$param .= '&search_'.$key.'='.urlencode($search[$key]);
}
}
if ($optioncss != '') {
$param .= '&optioncss='.urlencode($optioncss);
} }
if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss);
// Add $param from extra fields // Add $param from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
@ -307,12 +334,18 @@ $arrayofmassactions = array(
//'builddoc'=>$langs->trans("PDFMerge"), //'builddoc'=>$langs->trans("PDFMerge"),
//'presend'=>$langs->trans("SendByMail"), //'presend'=>$langs->trans("SendByMail"),
); );
if ($permissiontodelete) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); if ($permissiontodelete) {
if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete");
}
if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) {
$arrayofmassactions = array();
}
$massactionbutton = $form->selectMassAction('', $arrayofmassactions); $massactionbutton = $form->selectMassAction('', $arrayofmassactions);
print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'."\n"; print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'."\n";
if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; if ($optioncss != '') {
print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
}
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
print '<input type="hidden" name="action" value="list">'; print '<input type="hidden" name="action" value="list">';
@ -332,9 +365,10 @@ $objecttmp = new Productlot($db);
$trackid = 'lot'.$object->id; $trackid = 'lot'.$object->id;
include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';
if ($search_all) if ($search_all) {
{ foreach ($fieldstosearchall as $key => $val) {
foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); $fieldstosearchall[$key] = $langs->trans($val);
}
print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'</div>'; print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'</div>';
} }
@ -345,11 +379,13 @@ $moreforfilter = '';
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook
if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; if (empty($reshook)) {
else $moreforfilter = $hookmanager->resPrint; $moreforfilter .= $hookmanager->resPrint;
} else {
$moreforfilter = $hookmanager->resPrint;
}
if (!empty($moreforfilter)) if (!empty($moreforfilter)) {
{
print '<div class="liste_titre liste_titre_bydiv centpercent">'; print '<div class="liste_titre liste_titre_bydiv centpercent">';
print $moreforfilter; print $moreforfilter;
print '</div>'; print '</div>';
@ -366,20 +402,26 @@ print '<table class="tagtable nobottomiftotal liste'.($moreforfilter ? " listwit
// Fields title search // Fields title search
// -------------------------------------------------------------------- // --------------------------------------------------------------------
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{
$cssforfield = (empty($val['css']) ? '' : $val['css']); $cssforfield = (empty($val['css']) ? '' : $val['css']);
if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; if ($key == 'status') {
elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; $cssforfield .= ($cssforfield ? ' ' : '').'center';
elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right'; $cssforfield .= ($cssforfield ? ' ' : '').'center';
if (!empty($arrayfields['t.'.$key]['checked'])) } elseif (in_array($val['type'], array('timestamp'))) {
{ $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
} elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') {
$cssforfield .= ($cssforfield ? ' ' : '').'right';
}
if (!empty($arrayfields['t.'.$key]['checked'])) {
print '<td class="liste_titre'.($cssforfield ? ' '.$cssforfield : '').'">'; print '<td class="liste_titre'.($cssforfield ? ' '.$cssforfield : '').'">';
if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
elseif (strpos($val['type'], 'integer:') === 0) { print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1);
} elseif (strpos($val['type'], 'integer:') === 0) {
print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth150', 1); print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth150', 1);
} elseif (!preg_match('/^(date|timestamp)/', $val['type'])) print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'">'; } elseif (!preg_match('/^(date|timestamp)/', $val['type'])) {
print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'">';
}
print '</td>'; print '</td>';
} }
} }
@ -401,15 +443,18 @@ print '</tr>'."\n";
// Fields title label // Fields title label
// -------------------------------------------------------------------- // --------------------------------------------------------------------
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{
$cssforfield = (empty($val['css']) ? '' : $val['css']); $cssforfield = (empty($val['css']) ? '' : $val['css']);
if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; if ($key == 'status') {
elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; $cssforfield .= ($cssforfield ? ' ' : '').'center';
elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right'; $cssforfield .= ($cssforfield ? ' ' : '').'center';
if (!empty($arrayfields['t.'.$key]['checked'])) } elseif (in_array($val['type'], array('timestamp'))) {
{ $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
} elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') {
$cssforfield .= ($cssforfield ? ' ' : '').'right';
}
if (!empty($arrayfields['t.'.$key]['checked'])) {
print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n"; print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n";
} }
} }
@ -426,11 +471,11 @@ print '</tr>'."\n";
// Detect if we need a fetch on each output line // Detect if we need a fetch on each output line
$needToFetchEachLine = 0; $needToFetchEachLine = 0;
if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) {
{ foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) {
foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) if (preg_match('/\$object/', $val)) {
{ $needToFetchEachLine++; // There is at least one compute field that use $object
if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object }
} }
} }
@ -439,34 +484,43 @@ if (is_array($extrafields->attributes[$object->table_element]['computed']) && co
// -------------------------------------------------------------------- // --------------------------------------------------------------------
$i = 0; $i = 0;
$totalarray = array(); $totalarray = array();
while ($i < ($limit ? min($num, $limit) : $num)) while ($i < ($limit ? min($num, $limit) : $num)) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
if (empty($obj)) break; // Should not happen if (empty($obj)) {
break; // Should not happen
}
// Store properties in $object // Store properties in $object
$object->setVarsFromFetchObj($obj); $object->setVarsFromFetchObj($obj);
// Show here line of result // Show here line of result
print '<tr class="oddeven">'; print '<tr class="oddeven">';
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{
$cssforfield = (empty($val['css']) ? '' : $val['css']); $cssforfield = (empty($val['css']) ? '' : $val['css']);
if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
elseif ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; $cssforfield .= ($cssforfield ? ' ' : '').'center';
} elseif ($key == 'status') {
$cssforfield .= ($cssforfield ? ' ' : '').'center';
}
if (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; if (in_array($val['type'], array('timestamp'))) {
elseif ($key == 'ref' || $key == 'batch') $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
} elseif ($key == 'ref' || $key == 'batch') {
$cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
}
if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && !in_array($key, array('rowid', 'status'))) $cssforfield .= ($cssforfield ? ' ' : '').'right'; if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && !in_array($key, array('rowid', 'status'))) {
$cssforfield .= ($cssforfield ? ' ' : '').'right';
}
//if (in_array($key, array('fk_soc', 'fk_user', 'fk_warehouse'))) $cssforfield = 'tdoverflowmax100'; //if (in_array($key, array('fk_soc', 'fk_user', 'fk_warehouse'))) $cssforfield = 'tdoverflowmax100';
if (!empty($arrayfields['t.'.$key]['checked'])) if (!empty($arrayfields['t.'.$key]['checked'])) {
{
print '<td'.($cssforfield ? ' class="'.$cssforfield.'"' : '').'>'; print '<td'.($cssforfield ? ' class="'.$cssforfield.'"' : '').'>';
if ($key == 'status') print $object->getLibStatut(5); if ($key == 'status') {
elseif ($key == 'rowid') print $object->id; print $object->getLibStatut(5);
else { } elseif ($key == 'rowid') {
print $object->id;
} else {
if ($key == 'batch') { if ($key == 'batch') {
print $object->getNomUrl(1); print $object->getNomUrl(1);
} else { } else {
@ -474,10 +528,13 @@ while ($i < ($limit ? min($num, $limit) : $num))
} }
} }
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
if (!empty($val['isameasure'])) $totalarray['nbfield']++;
{ }
if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; if (!empty($val['isameasure'])) {
if (!$i) {
$totalarray['pos'][$totalarray['nbfield']] = 't.'.$key;
}
$totalarray['val']['t.'.$key] += $object->$key; $totalarray['val']['t.'.$key] += $object->$key;
} }
} }
@ -490,14 +547,17 @@ while ($i < ($limit ? min($num, $limit) : $num))
print $hookmanager->resPrint; print $hookmanager->resPrint;
// Action column // Action column
print '<td class="nowrap center">'; print '<td class="nowrap center">';
if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
{
$selected = 0; $selected = 0;
if (in_array($object->id, $arrayofselected)) $selected = 1; if (in_array($object->id, $arrayofselected)) {
$selected = 1;
}
print '<input id="cb'.$object->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$object->id.'"'.($selected ? ' checked="checked"' : '').'>'; print '<input id="cb'.$object->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$object->id.'"'.($selected ? ' checked="checked"' : '').'>';
} }
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
print '</tr>'."\n"; print '</tr>'."\n";
@ -508,10 +568,13 @@ while ($i < ($limit ? min($num, $limit) : $num))
include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php';
// If no record found // If no record found
if ($num == 0) if ($num == 0) {
{
$colspan = 1; $colspan = 1;
foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; } foreach ($arrayfields as $key => $val) {
if (!empty($val['checked'])) {
$colspan++;
}
}
print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>'; print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>';
} }
@ -527,10 +590,11 @@ print '</div>'."\n";
print '</form>'."\n"; print '</form>'."\n";
if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) {
{
$hidegeneratedfilelistifempty = 1; $hidegeneratedfilelistifempty = 1;
if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) {
$hidegeneratedfilelistifempty = 0;
}
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
$formfile = new FormFile($db); $formfile = new FormFile($db);

View File

@ -68,7 +68,9 @@ $texte = '';
$sortfield = GETPOST('sortfield', 'aZ09comma'); $sortfield = GETPOST('sortfield', 'aZ09comma');
$sortorder = GETPOST('sortorder', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$offset = $limit * $page; $offset = $limit * $page;
@ -86,8 +88,7 @@ if (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT)
|| !empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE) || !empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)
|| !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION)
|| !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE)
|| !empty($conf->mrp->enabled)) || !empty($conf->mrp->enabled)) {
{
$virtualdiffersfromphysical = 1; // According to increase/decrease stock options, virtual and physical stock may differs. $virtualdiffersfromphysical = 1; // According to increase/decrease stock options, virtual and physical stock may differs.
} }
@ -96,20 +97,25 @@ if ($virtualdiffersfromphysical) {
} else { } else {
$usevirtualstock = 0; $usevirtualstock = 0;
} }
if ($mode == 'physical') $usevirtualstock = 0; if ($mode == 'physical') {
if ($mode == 'virtual') $usevirtualstock = 1; $usevirtualstock = 0;
}
if ($mode == 'virtual') {
$usevirtualstock = 1;
}
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
/* /*
* Actions * Actions
*/ */
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') || GETPOST('valid')) // Both test are required to be compatible with all browsers if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') || GETPOST('valid')) { // Both test are required to be compatible with all browsers
{
$search_ref = ''; $search_ref = '';
$search_label = ''; $search_label = '';
$sall = ''; $sall = '';
@ -117,26 +123,24 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x'
$includeproductswithoutdesiredqty = ''; $includeproductswithoutdesiredqty = '';
$draftorder = ''; $draftorder = '';
} }
if ($draftorder == 'on') $draftchecked = "checked"; if ($draftorder == 'on') {
$draftchecked = "checked";
}
// Create orders // Create orders
if ($action == 'order' && GETPOST('valid')) if ($action == 'order' && GETPOST('valid')) {
{
$linecount = GETPOST('linecount', 'int'); $linecount = GETPOST('linecount', 'int');
$box = 0; $box = 0;
$errorQty = 0; $errorQty = 0;
unset($_POST['linecount']); unset($_POST['linecount']);
if ($linecount > 0) if ($linecount > 0) {
{
$db->begin(); $db->begin();
$suppliers = array(); $suppliers = array();
require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
$productsupplier = new ProductFournisseur($db); $productsupplier = new ProductFournisseur($db);
for ($i = 0; $i < $linecount; $i++) for ($i = 0; $i < $linecount; $i++) {
{ if (GETPOST('choose'.$i, 'alpha') === 'on' && GETPOST('fourn'.$i, 'int') > 0) {
if (GETPOST('choose'.$i, 'alpha') === 'on' && GETPOST('fourn'.$i, 'int') > 0)
{
//one line //one line
$box = $i; $box = $i;
$supplierpriceid = GETPOST('fourn'.$i, 'int'); $supplierpriceid = GETPOST('fourn'.$i, 'int');
@ -144,10 +148,8 @@ if ($action == 'order' && GETPOST('valid'))
$qty = GETPOST('tobuy'.$i, 'int'); $qty = GETPOST('tobuy'.$i, 'int');
$idprod = $productsupplier->get_buyprice($supplierpriceid, $qty); $idprod = $productsupplier->get_buyprice($supplierpriceid, $qty);
$res = $productsupplier->fetch($idprod); $res = $productsupplier->fetch($idprod);
if ($res && $idprod > 0) if ($res && $idprod > 0) {
{ if ($qty) {
if ($qty)
{
//might need some value checks //might need some value checks
$line = new CommandeFournisseurLigne($db); $line = new CommandeFournisseurLigne($db);
$line->qty = $qty; $line->qty = $qty;
@ -155,8 +157,7 @@ if ($action == 'order' && GETPOST('valid'))
//$product = new Product($db); //$product = new Product($db);
//$product->fetch($obj->fk_product); //$product->fetch($obj->fk_product);
if (!empty($conf->global->MAIN_MULTILANGS)) if (!empty($conf->global->MAIN_MULTILANGS)) {
{
$productsupplier->getMultiLangs(); $productsupplier->getMultiLangs();
} }
@ -167,8 +168,7 @@ if ($action == 'order' && GETPOST('valid'))
$desc = $productsupplier->description; $desc = $productsupplier->description;
} }
$line->desc = $desc; $line->desc = $desc;
if (!empty($conf->global->MAIN_MULTILANGS)) if (!empty($conf->global->MAIN_MULTILANGS)) {
{
// TODO Get desc in language of thirdparty // TODO Get desc in language of thirdparty
} }
@ -184,8 +184,7 @@ if ($action == 'order' && GETPOST('valid'))
$line->fk_unit = $productsupplier->fk_unit; $line->fk_unit = $productsupplier->fk_unit;
$suppliers[$productsupplier->fourn_socid]['lines'][] = $line; $suppliers[$productsupplier->fourn_socid]['lines'][] = $line;
} }
} elseif ($idprod == -1) } elseif ($idprod == -1) {
{
$errorQty++; $errorQty++;
} else { } else {
$error = $db->lasterror(); $error = $db->lasterror();
@ -202,8 +201,7 @@ if ($action == 'order' && GETPOST('valid'))
$fail = 0; $fail = 0;
$orders = array(); $orders = array();
$suppliersid = array_keys($suppliers); $suppliersid = array_keys($suppliers);
foreach ($suppliers as $supplier) foreach ($suppliers as $supplier) {
{
$order = new CommandeFournisseur($db); $order = new CommandeFournisseur($db);
// Check if an order for the supplier exists // Check if an order for the supplier exists
$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."commande_fournisseur"; $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."commande_fournisseur";
@ -267,10 +265,11 @@ if ($action == 'order' && GETPOST('valid'))
} }
} }
if ($errorQty) setEventMessages($langs->trans('ErrorOrdersNotCreatedQtyTooLow'), null, 'warnings'); if ($errorQty) {
setEventMessages($langs->trans('ErrorOrdersNotCreatedQtyTooLow'), null, 'warnings');
}
if (!$fail && $id) if (!$fail && $id) {
{
$db->commit(); $db->commit();
setEventMessages($langs->trans('OrderCreated'), null, 'mesgs'); setEventMessages($langs->trans('OrderCreated'), null, 'mesgs');
@ -280,8 +279,7 @@ if ($action == 'order' && GETPOST('valid'))
$db->rollback(); $db->rollback();
} }
} }
if ($box == 0) if ($box == 0) {
{
setEventMessages($langs->trans('SelectProductWithNotNullQty'), null, 'warnings'); setEventMessages($langs->trans('SelectProductWithNotNullQty'), null, 'warnings');
} }
} }
@ -340,7 +338,9 @@ $reshook = $hookmanager->executeHooks('printFieldListJoin', $parameters); // Not
$sql .= $hookmanager->resPrint; $sql .= $hookmanager->resPrint;
$sql .= ' WHERE p.entity IN ('.getEntity('product').')'; $sql .= ' WHERE p.entity IN ('.getEntity('product').')';
if ($sall) $sql .= natural_search(array('p.ref', 'p.label', 'p.description', 'p.note'), $sall); if ($sall) {
$sql .= natural_search(array('p.ref', 'p.label', 'p.description', 'p.note'), $sall);
}
// if the type is not 1, we show all products (type = 0,2,3) // if the type is not 1, we show all products (type = 0,2,3)
if (dol_strlen($type)) { if (dol_strlen($type)) {
if ($type == 1) { if ($type == 1) {
@ -349,8 +349,12 @@ if (dol_strlen($type)) {
$sql .= ' AND p.fk_product_type <> 1'; $sql .= ' AND p.fk_product_type <> 1';
} }
} }
if ($search_ref) $sql .= natural_search('p.ref', $search_ref); if ($search_ref) {
if ($search_label) $sql .= natural_search('p.label', $search_label); $sql .= natural_search('p.ref', $search_ref);
}
if ($search_label) {
$sql .= natural_search('p.label', $search_label);
}
$sql .= ' AND p.tobuy = 1'; $sql .= ' AND p.tobuy = 1';
if (empty($conf->global->VARIANT_ALLOW_STOCK_MOVEMENT_ON_VARIANT_PARENT)) { // Add test to exclude products that has variants if (empty($conf->global->VARIANT_ALLOW_STOCK_MOVEMENT_ON_VARIANT_PARENT)) { // Add test to exclude products that has variants
$sql .= ' AND p.rowid NOT IN (SELECT pac.fk_product_parent FROM '.MAIN_DB_PREFIX.'product_attribute_combination as pac WHERE pac.entity IN ('.getEntity('product').'))'; $sql .= ' AND p.rowid NOT IN (SELECT pac.fk_product_parent FROM '.MAIN_DB_PREFIX.'product_attribute_combination as pac WHERE pac.entity IN ('.getEntity('product').'))';
@ -366,8 +370,7 @@ if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entre
} }
$sql .= ', s.fk_product'; $sql .= ', s.fk_product';
if ($usevirtualstock) if ($usevirtualstock) {
{
if (!empty($conf->commande->enabled)) { if (!empty($conf->commande->enabled)) {
$sqlCommandesCli = "(SELECT ".$db->ifsql("SUM(cd1.qty) IS NULL", "0", "SUM(cd1.qty)")." as qty"; // We need the ifsql because if result is 0 for product p.rowid, we must return 0 and not NULL $sqlCommandesCli = "(SELECT ".$db->ifsql("SUM(cd1.qty) IS NULL", "0", "SUM(cd1.qty)")." as qty"; // We need the ifsql because if result is 0 for product p.rowid, we must return 0 and not NULL
$sqlCommandesCli .= " FROM ".MAIN_DB_PREFIX."commandedet as cd1, ".MAIN_DB_PREFIX."commande as c1"; $sqlCommandesCli .= " FROM ".MAIN_DB_PREFIX."commandedet as cd1, ".MAIN_DB_PREFIX."commande as c1";
@ -446,8 +449,7 @@ if ($usevirtualstock)
$sql .= ' - ('.$sqlCommandesCli.' - '.$sqlExpeditionsCli.') + ('.$sqlCommandesFourn.' - '.$sqlReceptionFourn.') + ('.$sqlProductionToProduce.' - '.$sqlProductionToConsume.')))'; $sql .= ' - ('.$sqlCommandesCli.' - '.$sqlExpeditionsCli.') + ('.$sqlCommandesFourn.' - '.$sqlReceptionFourn.') + ('.$sqlProductionToProduce.' - '.$sqlProductionToConsume.')))';
$sql .= ')'; $sql .= ')';
if ($salert == 'on') // Option to see when stock is lower than alert if ($salert == 'on') { // Option to see when stock is lower than alert
{
$sql .= ' AND ('; $sql .= ' AND (';
if ($includeproductswithoutdesiredqty == 'on') { if ($includeproductswithoutdesiredqty == 'on') {
$sql .= '('.$sqlalertstock.' >= 0 OR '.$sqlalertstock.' IS NULL) AND ('.$db->ifsql("$sqlalertstock IS NULL", "0", $sqlalertstock).' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").')'; $sql .= '('.$sqlalertstock.' >= 0 OR '.$sqlalertstock.' IS NULL) AND ('.$db->ifsql("$sqlalertstock IS NULL", "0", $sqlalertstock).' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").')';
@ -469,8 +471,7 @@ if ($usevirtualstock)
} }
$sql .= ')'; $sql .= ')';
if ($salert == 'on') // Option to see when stock is lower than alert if ($salert == 'on') { // Option to see when stock is lower than alert
{
$sql .= ' AND ('; $sql .= ' AND (';
if ($includeproductswithoutdesiredqty == 'on') { if ($includeproductswithoutdesiredqty == 'on') {
$sql .= ' ('.$sqlalertstock.' >= 0 OR '.$sqlalertstock.' IS NULL) AND ('.$db->ifsql("$sqlalertstock IS NULL", "0", $sqlalertstock).' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").'))'; $sql .= ' ('.$sqlalertstock.' >= 0 OR '.$sqlalertstock.' IS NULL) AND ('.$db->ifsql("$sqlalertstock IS NULL", "0", $sqlalertstock).' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").'))';
@ -507,8 +508,7 @@ $sql .= $db->plimit($limit + 1, $offset);
//print $sql; //print $sql;
$resql = $db->query($sql); $resql = $db->query($sql);
if (empty($resql)) if (empty($resql)) {
{
dol_print_error($db); dol_print_error($db);
exit; exit;
} }
@ -541,15 +541,13 @@ if (empty($fk_warhouse) && !empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_
print '<span class="opacitymedium">'.$langs->trans("ReplenishmentStatusDescPerWarehouse").'</span>'."\n"; print '<span class="opacitymedium">'.$langs->trans("ReplenishmentStatusDescPerWarehouse").'</span>'."\n";
} }
print '<br><br>'; print '<br><br>';
if ($usevirtualstock == 1) if ($usevirtualstock == 1) {
{
print $langs->trans("CurentSelectionMode").': '; print $langs->trans("CurentSelectionMode").': ';
print '<span class="a-mesure">'.$langs->trans("UseVirtualStock").'</span>'; print '<span class="a-mesure">'.$langs->trans("UseVirtualStock").'</span>';
print ' <a class="a-mesure-disabled" href="'.$_SERVER["PHP_SELF"].'?mode=physical'.($fk_supplier > 0 ? '&fk_supplier='.$fk_supplier : '').($fk_entrepot > 0 ? '&fk_entrepot='.$fk_entrepot : '').'">'.$langs->trans("UsePhysicalStock").'</a>'; print ' <a class="a-mesure-disabled" href="'.$_SERVER["PHP_SELF"].'?mode=physical'.($fk_supplier > 0 ? '&fk_supplier='.$fk_supplier : '').($fk_entrepot > 0 ? '&fk_entrepot='.$fk_entrepot : '').'">'.$langs->trans("UsePhysicalStock").'</a>';
print '<br>'; print '<br>';
} }
if ($usevirtualstock == 0) if ($usevirtualstock == 0) {
{
print $langs->trans("CurentSelectionMode").': '; print $langs->trans("CurentSelectionMode").': ';
print '<a class="a-mesure-disabled" href="'.$_SERVER["PHP_SELF"].'?mode=virtual'.($fk_supplier > 0 ? '&fk_supplier='.$fk_supplier : '').($fk_entrepot > 0 ? '&fk_entrepot='.$fk_entrepot : '').'">'.$langs->trans("UseVirtualStock").'</a>'; print '<a class="a-mesure-disabled" href="'.$_SERVER["PHP_SELF"].'?mode=virtual'.($fk_supplier > 0 ? '&fk_supplier='.$fk_supplier : '').($fk_entrepot > 0 ? '&fk_entrepot='.$fk_entrepot : '').'">'.$langs->trans("UseVirtualStock").'</a>';
print ' <span class="a-mesure">'.$langs->trans("UsePhysicalStock").'</span>'; print ' <span class="a-mesure">'.$langs->trans("UsePhysicalStock").'</span>';
@ -569,8 +567,7 @@ print '<input type="hidden" name="mode" value="'.$mode.'">';
if ($limit > 0 && $limit != $conf->liste_limit) { if ($limit > 0 && $limit != $conf->liste_limit) {
print '<input type="hidden" name="limit" value="'.$limit.'">'; print '<input type="hidden" name="limit" value="'.$limit.'">';
} }
if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE)) if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE)) {
{
print '<div class="inline-block valignmiddle" style="padding-right: 20px;">'; print '<div class="inline-block valignmiddle" style="padding-right: 20px;">';
print $langs->trans('Warehouse').' '.$formproduct->selectWarehouses($fk_entrepot, 'fk_entrepot', '', 1); print $langs->trans('Warehouse').' '.$formproduct->selectWarehouses($fk_entrepot, 'fk_entrepot', '', 1);
print '</div>'; print '</div>';
@ -581,7 +578,9 @@ print '</div>';
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook
if (empty($reshook)) print $hookmanager->resPrint; if (empty($reshook)) {
print $hookmanager->resPrint;
}
print '<div class="inline-block valignmiddle">'; print '<div class="inline-block valignmiddle">';
print '<input class="button" type="submit" name="valid" value="'.$langs->trans('ToFilter').'">'; print '<input class="button" type="submit" name="valid" value="'.$langs->trans('ToFilter').'">';
@ -607,8 +606,12 @@ if ($search_ref || $search_label || $sall || $salert || $draftorder || GETPOST('
$filters .= '&salert='.urlencode($salert); $filters .= '&salert='.urlencode($salert);
$filters .= '&draftorder='.urlencode($draftorder); $filters .= '&draftorder='.urlencode($draftorder);
$filters .= '&mode='.urlencode($mode); $filters .= '&mode='.urlencode($mode);
if ($fk_supplier > 0) $filters .= '&fk_supplier='.urlencode($fk_supplier); if ($fk_supplier > 0) {
if ($fk_entrepot > 0) $filters .= '&fk_entrepot='.urlencode($fk_entrepot); $filters .= '&fk_supplier='.urlencode($fk_supplier);
}
if ($fk_entrepot > 0) {
$filters .= '&fk_entrepot='.urlencode($fk_entrepot);
}
} else { } else {
$filters = '&search_ref='.urlencode($search_ref).'&search_label='.urlencode($search_label); $filters = '&search_ref='.urlencode($search_ref).'&search_label='.urlencode($search_label);
$filters .= '&fourn_id='.urlencode($fourn_id); $filters .= '&fourn_id='.urlencode($fourn_id);
@ -616,8 +619,12 @@ if ($search_ref || $search_label || $sall || $salert || $draftorder || GETPOST('
$filters .= '&='.urlencode($salert); $filters .= '&='.urlencode($salert);
$filters .= '&draftorder='.urlencode($draftorder); $filters .= '&draftorder='.urlencode($draftorder);
$filters .= '&mode='.urlencode($mode); $filters .= '&mode='.urlencode($mode);
if ($fk_supplier > 0) $filters .= '&fk_supplier='.urlencode($fk_supplier); if ($fk_supplier > 0) {
if ($fk_entrepot > 0) $filters .= '&fk_entrepot='.urlencode($fk_entrepot); $filters .= '&fk_supplier='.urlencode($fk_supplier);
}
if ($fk_entrepot > 0) {
$filters .= '&fk_entrepot='.urlencode($fk_entrepot);
}
} }
if ($limit > 0 && $limit != $conf->liste_limit) { if ($limit > 0 && $limit != $conf->liste_limit) {
$filters .= '&limit='.urlencode($limit); $filters .= '&limit='.urlencode($limit);
@ -632,10 +639,13 @@ $param .= '&fk_entrepot='.urlencode($fk_entrepot);
$stocklabel = $langs->trans('Stock'); $stocklabel = $langs->trans('Stock');
$stocklabelbis = $langs->trans('Stock'); $stocklabelbis = $langs->trans('Stock');
if ($usevirtualstock == 1) $stocklabel = $langs->trans('VirtualStock'); if ($usevirtualstock == 1) {
if ($usevirtualstock == 0) $stocklabel = $langs->trans('PhysicalStock'); $stocklabel = $langs->trans('VirtualStock');
if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entrepot > 0) }
{ if ($usevirtualstock == 0) {
$stocklabel = $langs->trans('PhysicalStock');
}
if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entrepot > 0) {
$stocklabelbis = $stocklabel.' (Selected warehouse)'; $stocklabelbis = $stocklabel.' (Selected warehouse)';
$stocklabel .= ' ('.$langs->trans("AllWarehouses").')'; $stocklabel .= ' ('.$langs->trans("AllWarehouses").')';
} }
@ -684,12 +694,13 @@ print '<tr class="liste_titre_filter">';
print '<td class="liste_titre">&nbsp;</td>'; print '<td class="liste_titre">&nbsp;</td>';
print '<td class="liste_titre"><input class="flat" type="text" name="search_ref" size="8" value="'.dol_escape_htmltag($search_ref).'"></td>'; print '<td class="liste_titre"><input class="flat" type="text" name="search_ref" size="8" value="'.dol_escape_htmltag($search_ref).'"></td>';
print '<td class="liste_titre"><input class="flat" type="text" name="search_label" size="8" value="'.dol_escape_htmltag($search_label).'"></td>'; print '<td class="liste_titre"><input class="flat" type="text" name="search_label" size="8" value="'.dol_escape_htmltag($search_label).'"></td>';
if (!empty($conf->service->enabled) && $type == 1) print '<td class="liste_titre">&nbsp;</td>'; if (!empty($conf->service->enabled) && $type == 1) {
print '<td class="liste_titre">&nbsp;</td>';
}
print '<td class="liste_titre right">'.$form->textwithpicto($langs->trans('IncludeEmptyDesiredStock'), $langs->trans('IncludeProductWithUndefinedAlerts')).'&nbsp;<input type="checkbox" id="includeproductswithoutdesiredqty" name="includeproductswithoutdesiredqty" '.(!empty($includeproductswithoutdesiredqtychecked) ? $includeproductswithoutdesiredqtychecked : '').'></td>'; print '<td class="liste_titre right">'.$form->textwithpicto($langs->trans('IncludeEmptyDesiredStock'), $langs->trans('IncludeProductWithUndefinedAlerts')).'&nbsp;<input type="checkbox" id="includeproductswithoutdesiredqty" name="includeproductswithoutdesiredqty" '.(!empty($includeproductswithoutdesiredqtychecked) ? $includeproductswithoutdesiredqtychecked : '').'></td>';
print '<td class="liste_titre right"></td>'; print '<td class="liste_titre right"></td>';
print '<td class="liste_titre right">'.$langs->trans('AlertOnly').'&nbsp;<input type="checkbox" id="salert" name="salert" '.(!empty($alertchecked) ? $alertchecked : '').'></td>'; print '<td class="liste_titre right">'.$langs->trans('AlertOnly').'&nbsp;<input type="checkbox" id="salert" name="salert" '.(!empty($alertchecked) ? $alertchecked : '').'></td>';
if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entrepot > 0) if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entrepot > 0) {
{
print '<td class="liste_titre">&nbsp;</td>'; print '<td class="liste_titre">&nbsp;</td>';
} }
print '<td class="liste_titre right">'; print '<td class="liste_titre right">';
@ -714,12 +725,13 @@ print '<tr class="liste_titre">';
print_liste_field_titre('<input type="checkbox" onClick="toggle(this)" />', $_SERVER["PHP_SELF"], ''); print_liste_field_titre('<input type="checkbox" onClick="toggle(this)" />', $_SERVER["PHP_SELF"], '');
print_liste_field_titre('Ref', $_SERVER["PHP_SELF"], 'p.ref', $param, '', '', $sortfield, $sortorder); print_liste_field_titre('Ref', $_SERVER["PHP_SELF"], 'p.ref', $param, '', '', $sortfield, $sortorder);
print_liste_field_titre('Label', $_SERVER["PHP_SELF"], 'p.label', $param, '', '', $sortfield, $sortorder); print_liste_field_titre('Label', $_SERVER["PHP_SELF"], 'p.label', $param, '', '', $sortfield, $sortorder);
if (!empty($conf->service->enabled) && $type == 1) print_liste_field_titre('Duration', $_SERVER["PHP_SELF"], 'p.duration', $param, '', '', $sortfield, $sortorder, 'center '); if (!empty($conf->service->enabled) && $type == 1) {
print_liste_field_titre('Duration', $_SERVER["PHP_SELF"], 'p.duration', $param, '', '', $sortfield, $sortorder, 'center ');
}
print_liste_field_titre('DesiredStock', $_SERVER["PHP_SELF"], 'p.desiredstock', $param, '', '', $sortfield, $sortorder, 'right '); print_liste_field_titre('DesiredStock', $_SERVER["PHP_SELF"], 'p.desiredstock', $param, '', '', $sortfield, $sortorder, 'right ');
print_liste_field_titre('StockLimitShort', $_SERVER["PHP_SELF"], 'p.seuil_stock_alerte', $param, '', '', $sortfield, $sortorder, 'right '); print_liste_field_titre('StockLimitShort', $_SERVER["PHP_SELF"], 'p.seuil_stock_alerte', $param, '', '', $sortfield, $sortorder, 'right ');
print_liste_field_titre($stocklabel, $_SERVER["PHP_SELF"], 'stock_physique', $param, '', '', $sortfield, $sortorder, 'right '); print_liste_field_titre($stocklabel, $_SERVER["PHP_SELF"], 'stock_physique', $param, '', '', $sortfield, $sortorder, 'right ');
if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entrepot > 0) if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entrepot > 0) {
{
print_liste_field_titre($stocklabelbis, $_SERVER["PHP_SELF"], 'stock_real_warehouse', $param, '', '', $sortfield, $sortorder, 'right '); print_liste_field_titre($stocklabelbis, $_SERVER["PHP_SELF"], 'stock_real_warehouse', $param, '', '', $sortfield, $sortorder, 'right ');
} }
print_liste_field_titre('Ordered', $_SERVER["PHP_SELF"], '', $param, '', '', $sortfield, $sortorder, 'right '); print_liste_field_titre('Ordered', $_SERVER["PHP_SELF"], '', $param, '', '', $sortfield, $sortorder, 'right ');
@ -733,18 +745,15 @@ print $hookmanager->resPrint;
print "</tr>\n"; print "</tr>\n";
while ($i < ($limit ? min($num, $limit) : $num)) while ($i < ($limit ? min($num, $limit) : $num)) {
{
$objp = $db->fetch_object($resql); $objp = $db->fetch_object($resql);
if (!empty($conf->global->STOCK_SUPPORTS_SERVICES) || $objp->fk_product_type == 0) if (!empty($conf->global->STOCK_SUPPORTS_SERVICES) || $objp->fk_product_type == 0) {
{
$prod->fetch($objp->rowid); $prod->fetch($objp->rowid);
$prod->load_stock('warehouseopen, warehouseinternal', $draftchecked); $prod->load_stock('warehouseopen, warehouseinternal', $draftchecked);
// Multilangs // Multilangs
if (!empty($conf->global->MAIN_MULTILANGS)) if (!empty($conf->global->MAIN_MULTILANGS)) {
{
$sql = 'SELECT label,description'; $sql = 'SELECT label,description';
$sql .= ' FROM '.MAIN_DB_PREFIX.'product_lang'; $sql .= ' FROM '.MAIN_DB_PREFIX.'product_lang';
$sql .= ' WHERE fk_product = '.$objp->rowid; $sql .= ' WHERE fk_product = '.$objp->rowid;
@ -752,17 +761,19 @@ while ($i < ($limit ? min($num, $limit) : $num))
$sql .= ' LIMIT 1'; $sql .= ' LIMIT 1';
$resqlm = $db->query($sql); $resqlm = $db->query($sql);
if ($resqlm) if ($resqlm) {
{
$objtp = $db->fetch_object($resqlm); $objtp = $db->fetch_object($resqlm);
if (!empty($objtp->description)) $objp->description = $objtp->description; if (!empty($objtp->description)) {
if (!empty($objtp->label)) $objp->label = $objtp->label; $objp->description = $objtp->description;
}
if (!empty($objtp->label)) {
$objp->label = $objtp->label;
}
} }
} }
$stockwarehouse = 0; $stockwarehouse = 0;
if ($usevirtualstock) if ($usevirtualstock) {
{
// If option to increase/decrease is not on an object validation, virtual stock may differs from physical stock. // If option to increase/decrease is not on an object validation, virtual stock may differs from physical stock.
$stock = $prod->stock_theorique; $stock = $prod->stock_theorique;
//TODO $stockwarehouse = $prod->stock_warehouse[$fk_entrepot]->; //TODO $stockwarehouse = $prod->stock_warehouse[$fk_entrepot]->;
@ -790,27 +801,30 @@ while ($i < ($limit ? min($num, $limit) : $num))
$alertstockwarehouse = ($objp->seuil_stock_alertepse ? $objp->seuil_stock_alertepse : 0); $alertstockwarehouse = ($objp->seuil_stock_alertepse ? $objp->seuil_stock_alertepse : 0);
$warning = ''; $warning = '';
if ($alertstock && ($stock < $alertstock)) if ($alertstock && ($stock < $alertstock)) {
{
$warning = img_warning($langs->trans('StockTooLow')).' '; $warning = img_warning($langs->trans('StockTooLow')).' ';
} }
$warningwarehouse = ''; $warningwarehouse = '';
if ($alertstockwarehouse && ($stockwarehouse < $alertstockwarehouse)) if ($alertstockwarehouse && ($stockwarehouse < $alertstockwarehouse)) {
{
$warningwarehouse = img_warning($langs->trans('StockTooLow')).' '; $warningwarehouse = img_warning($langs->trans('StockTooLow')).' ';
} }
//depending on conf, use either physical stock or //depending on conf, use either physical stock or
//virtual stock to compute the stock to buy value //virtual stock to compute the stock to buy value
if (empty($usevirtualstock)) $stocktobuy = max(max($desiredstock, $alertstock) - $stock - $ordered, 0); if (empty($usevirtualstock)) {
else $stocktobuy = max(max($desiredstock, $alertstock) - $stock, 0); //ordered is already in $stock in virtual mode $stocktobuy = max(max($desiredstock, $alertstock) - $stock - $ordered, 0);
if (empty($usevirtualstock)) $stocktobuywarehouse = max(max($desiredstockwarehouse, $alertstockwarehouse) - $stockwarehouse - $ordered, 0); } else {
else $stocktobuywarehouse = max(max($desiredstockwarehouse, $alertstockwarehouse) - $stockwarehouse, 0); //ordered is already in $stock in virtual mode $stocktobuy = max(max($desiredstock, $alertstock) - $stock, 0); //ordered is already in $stock in virtual mode
}
if (empty($usevirtualstock)) {
$stocktobuywarehouse = max(max($desiredstockwarehouse, $alertstockwarehouse) - $stockwarehouse - $ordered, 0);
} else {
$stocktobuywarehouse = max(max($desiredstockwarehouse, $alertstockwarehouse) - $stockwarehouse, 0); //ordered is already in $stock in virtual mode
}
$picto = ''; $picto = '';
if ($ordered > 0) if ($ordered > 0) {
{
$stockforcompare = ($usevirtualstock ? $stock : $stock + $ordered); $stockforcompare = ($usevirtualstock ? $stock : $stock + $ordered);
/*if ($stockforcompare >= $desiredstock) /*if ($stockforcompare >= $desiredstock)
{ {
@ -833,8 +847,7 @@ while ($i < ($limit ? min($num, $limit) : $num))
print '<input type="hidden" name="desc'.$i.'" value="'.dol_escape_htmltag($objp->description).'">'; // TODO Remove this and make a fetch to get description when creating order instead of a GETPOST print '<input type="hidden" name="desc'.$i.'" value="'.dol_escape_htmltag($objp->description).'">'; // TODO Remove this and make a fetch to get description when creating order instead of a GETPOST
print '</td>'; print '</td>';
if (!empty($conf->service->enabled) && $type == 1) if (!empty($conf->service->enabled) && $type == 1) {
{
$regs = array(); $regs = array();
if (preg_match('/([0-9]+)y/i', $objp->duration, $regs)) { if (preg_match('/([0-9]+)y/i', $objp->duration, $regs)) {
$duration = $regs[1].' '.$langs->trans('DurationYear'); $duration = $regs[1].' '.$langs->trans('DurationYear');
@ -858,8 +871,7 @@ while ($i < ($limit ? min($num, $limit) : $num))
print '<td class="right">'.$warning.$stock.'</td>'; print '<td class="right">'.$warning.$stock.'</td>';
// Current stock (warehouse selected only) // Current stock (warehouse selected only)
if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entrepot > 0) if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entrepot > 0) {
{
print '<td class="right">'.$warningwarehouse.$stockwarehouse.'</td>'; print '<td class="right">'.$warningwarehouse.$stockwarehouse.'</td>';
} }

View File

@ -38,7 +38,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
$langs->loadLangs(array('products', 'stocks', 'orders')); $langs->loadLangs(array('products', 'stocks', 'orders'));
// Security check // Security check
if ($user->socid) $socid = $user->socid; if ($user->socid) {
$socid = $user->socid;
}
$result = restrictedArea($user, 'produit|service'); $result = restrictedArea($user, 'produit|service');
$sall = GETPOST('search_all', 'alphanohtml'); $sall = GETPOST('search_all', 'alphanohtml');
@ -56,10 +58,16 @@ $search_date = dol_mktime(0, 0, 0, $search_datemonth, $search_dateday, $search_d
$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST("sortfield", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha');
if (!$sortorder) $sortorder = 'DESC'; if (!$sortorder) {
if (!$sortfield) $sortfield = 'cf.date_creation'; $sortorder = 'DESC';
}
if (!$sortfield) {
$sortfield = 'cf.date_creation';
}
$page = GETPOST('page', 'int') ? GETPOST('page', 'int') : 0; $page = GETPOST('page', 'int') ? GETPOST('page', 'int') : 0;
if ($page < 0) $page = 0; if ($page < 0) {
$page = 0;
}
$offset = $limit * $page; $offset = $limit * $page;
@ -67,8 +75,7 @@ $offset = $limit * $page;
* Actions * Actions
*/ */
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // Both test are required to be compatible with all browsers if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // Both test are required to be compatible with all browsers
{
$sall = ""; $sall = "";
$sref = ""; $sref = "";
$snom = ""; $snom = "";
@ -130,13 +137,25 @@ if ($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) {
if (!$user->rights->societe->client->voir && !$socid) { if (!$user->rights->societe->client->voir && !$socid) {
$sql .= ' AND s.rowid = sc.fk_soc AND sc.fk_user = '.$user->id; $sql .= ' AND s.rowid = sc.fk_soc AND sc.fk_user = '.$user->id;
} }
if ($sref) $sql .= natural_search('cf.ref', $sref); if ($sref) {
if ($snom) $sql .= natural_search('s.nom', $snom); $sql .= natural_search('cf.ref', $sref);
if ($suser) $sql .= natural_search('u.login', $suser); }
if ($sttc) $sql .= natural_search('cf.total_ttc', $sttc, 1); if ($snom) {
$sql .= natural_search('s.nom', $snom);
}
if ($suser) {
$sql .= natural_search('u.login', $suser);
}
if ($sttc) {
$sql .= natural_search('cf.total_ttc', $sttc, 1);
}
$sql .= dolSqlDateFilter('cf.date_creation', $search_dateday, $search_datemonth, $search_dateyear); $sql .= dolSqlDateFilter('cf.date_creation', $search_dateday, $search_datemonth, $search_dateyear);
if ($sall) $sql .= natural_search(array('cf.ref', 'cf.note'), $sall); if ($sall) {
if (!empty($socid)) $sql .= ' AND s.rowid = '.$socid; $sql .= natural_search(array('cf.ref', 'cf.note'), $sall);
}
if (!empty($socid)) {
$sql .= ' AND s.rowid = '.$socid;
}
if (GETPOST('statut', 'int')) { if (GETPOST('statut', 'int')) {
$sql .= ' AND fk_statut = '.GETPOST('statut', 'int'); $sql .= ' AND fk_statut = '.GETPOST('statut', 'int');
} }
@ -148,8 +167,7 @@ if (!$search_product) {
} }
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
$i = 0; $i = 0;
@ -160,16 +178,36 @@ if ($resql)
print_barre_liste('', $page, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, '', $num, 0, ''); print_barre_liste('', $page, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, '', $num, 0, '');
$param = ''; $param = '';
if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); $param .= '&contextpage='.urlencode($contextpage);
if ($sref) $param .= '&search_ref='.urlencode($sref); }
if ($snom) $param .= '&search_nom='.urlencode($snom); if ($limit > 0 && $limit != $conf->liste_limit) {
if ($suser) $param .= '&search_user='.urlencode($suser); $param .= '&limit='.urlencode($limit);
if ($sttc) $param .= '&search_ttc='.urlencode($sttc); }
if ($search_dateyear) $param .= '&search_dateyear='.urlencode($search_dateyear); if ($sref) {
if ($search_datemonth) $param .= '&search_datemonth='.urlencode($search_datemonth); $param .= '&search_ref='.urlencode($sref);
if ($search_dateday) $param .= '&search_dateday='.urlencode($search_dateday); }
if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); if ($snom) {
$param .= '&search_nom='.urlencode($snom);
}
if ($suser) {
$param .= '&search_user='.urlencode($suser);
}
if ($sttc) {
$param .= '&search_ttc='.urlencode($sttc);
}
if ($search_dateyear) {
$param .= '&search_dateyear='.urlencode($search_dateyear);
}
if ($search_datemonth) {
$param .= '&search_datemonth='.urlencode($search_datemonth);
}
if ($search_dateday) {
$param .= '&search_dateday='.urlencode($search_dateday);
}
if ($optioncss != '') {
$param .= '&optioncss='.urlencode($optioncss);
}
print '<table class="noborder centpercent">'; print '<table class="noborder centpercent">';
@ -261,14 +299,12 @@ if ($resql)
$userstatic = new User($db); $userstatic = new User($db);
while ($i < min($num, $search_product ? $num : $conf->liste_limit)) while ($i < min($num, $search_product ? $num : $conf->liste_limit)) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
$showline = dolDispatchToDo($obj->rowid) && (!$search_product || in_array($search_product, getProducts($obj->rowid))); $showline = dolDispatchToDo($obj->rowid) && (!$search_product || in_array($search_product, getProducts($obj->rowid)));
if ($showline) if ($showline) {
{
$href = DOL_URL_ROOT.'/fourn/commande/card.php?id='.$obj->rowid; $href = DOL_URL_ROOT.'/fourn/commande/card.php?id='.$obj->rowid;
print '<tr>'; print '<tr>';

Some files were not shown because too many files have changed in this diff Show More