function loadLines(&$PDOdb, $id_expeditionLine)
 {
     $sql = "SELECT rowid FROM " . $this->get_table() . " WHERE fk_expeditiondet = " . $id_expeditionLine . " ORDER BY rang";
     $TIdExpedet = TRequeteCore::_get_id_by_sql($PDOdb, $sql);
     foreach ($TIdExpedet as $idexpedet) {
         $dispatchdetail_temp = new TDispatchDetail();
         $dispatchdetail_temp->load($PDOdb, $idexpedet);
         $this->lines[] = $dispatchdetail_temp;
         $this->nbLines = $this->nbLines + 1;
     }
 }
 static function getDashboard(&$PDOdb, $hook = '', $fk_user = 0, $withTitle = false)
 {
     $Tab = array();
     $sql = "SELECT rowid, uid, title, refresh_dashboard FROM " . MAIN_DB_PREFIX . "qdashboard qd \n\t\tWHERE 1 ";
     if ($hook) {
         $sql .= " AND qd.hook='" . $hook . "'";
     }
     if ($fk_user > 0) {
         $sql .= " AND (qd.fk_user_author=" . $fk_user . " OR  qd.fk_usergroup IN (SELECT fk_usergroup FROM " . MAIN_DB_PREFIX . "usergroup_user WHERE fk_user="******" ) )";
     }
     $sql .= " ORDER BY title";
     $Tab = TRequeteCore::_get_id_by_sql($PDOdb, $sql, $withTitle ? 'title' : 'uid', 'rowid');
     return $Tab;
 }
 static function getMenu(&$PDOdb, $type)
 {
     global $langs;
     if ($type == 'main') {
         $Tab = TRequeteCore::_get_id_by_sql($PDOdb, "SELECT DISTINCT mainmenu FROM " . MAIN_DB_PREFIX . "menu WHERE 1 ORDER BY mainmenu", 'mainmenu', 'mainmenu');
         $Tab['companies'] = 'companies';
     } else {
         $Tab = TRequeteCore::_get_id_by_sql($PDOdb, "SELECT DISTINCT leftmenu FROM " . MAIN_DB_PREFIX . "menu WHERE 1 ORDER BY leftmenu", 'leftmenu', 'leftmenu');
         $Tab['thirdparties'] = 'thirdparties';
         $Tab['query'] = 'query';
         $Tab['projects'] = 'projects';
         $Tab['customers_bills'] = 'customers_bills';
     }
     return $Tab;
 }
    /**
     * Overloading the doActions function : replacing the parent's function with the one below
     *
     * @param   array()         $parameters     Hook metadatas (context, etc...)
     * @param   CommonObject    &$object        The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
     * @param   string          &$action        Current action (if set). Generally create or edit or null
     * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
     * @return  int                             < 0 on error, 0 on success, 1 to replace standard code
     */
    function blockRelated($parameters, &$object, &$action, $hookmanager, $moreStyle = '')
    {
        global $langs, $db, $user, $conf, $related_link_added;
        $error = 0;
        // Error counter
        //var_dump($objet);
        define('INC_FROM_DOLIBARR', true);
        dol_include_once('/related/config.php');
        $PDOdb = new TPDOdb();
        $langs->load('related@related');
        if (GETPOST('action') == 'add_related_link' && !$related_link_added) {
            $type = GETPOST('type_related_object');
            //var_dump($type);exit;
            if ($type == 'projet') {
                $type = 'project';
            } else {
                if ($type == 'invoice') {
                    $type = 'facture';
                } else {
                    if ($type == 'company') {
                        $type = 'societe';
                    } else {
                        if ($type == 'facture_fournisseur') {
                            $type = 'invoice_supplier';
                        } else {
                            if ($type == 'commande_fournisseur') {
                                $type = 'order_supplier';
                            }
                        }
                    }
                }
            }
            $res = $object->add_object_linked($type, GETPOST('id_related_object'));
            $object->fetchObjectLinked();
            if (empty($res)) {
                setEventMessage($langs->trans('RelationCantBeAdded'), 'errors');
            } else {
                $related_link_added = true;
                global $langs, $conf;
                dol_include_once('/core/class/interfaces.class.php');
                $interface = new Interfaces($db);
                $object->id_related_object = GETPOST('id_related_object');
                $object->type_related_object = $type;
                $result = $interface->run_triggers('RELATED_ADD_LINK', $object, $user, $langs, $conf);
                if ($result < 0) {
                    if (!empty($this->errors)) {
                        $this->errors = array_merge($this->errors, $interface->errors);
                    } else {
                        $this->errors = $interface->errors;
                    }
                }
                setEventMessage($langs->trans('RelationAdded'));
            }
        } elseif (GETPOST('action') == 'delete_related_link') {
            $idLink = GETPOST('id_link');
            if ($idLink) {
                $PDOdb->Execute("DELETE FROM " . MAIN_DB_PREFIX . "element_element WHERE rowid = " . $idLink);
                $object->fetchObjectLinked();
            }
        } else {
            //var_dump($object);
            if (empty($object->linkedObjects)) {
                $object->fetchObjectLinked();
            }
        }
        //var_dump($object->linkedObjectsIds);
        ?>
		 	<div class="blockrelated_content" style="<?php 
        echo $moreStyle;
        ?>
">
		 		<form name="formLinkObj" action="<?php 
        echo $_SERVER['PHP_SELF'];
        ?>
" method="post">
		 			<input type="hidden" name="action" value="add_related_link"  />
		 			<input type="hidden" name="id" value="<?php 
        echo GETPOST('id');
        ?>
"  />
		 			<input type="hidden" name="facid" value="<?php 
        echo GETPOST('facid');
        ?>
"  />
		 			<br>
					<div class="titre"><?php 
        echo $langs->trans('ElementToLink');
        ?>
</div>

			 		<input type="hidden" id="id_related_object" name="id_related_object" value=""  />
			 		<input type="hidden" id="type_related_object" name="type_related_object" value=""  />


			 		<table class="noborder allwidth">
						<tr class="liste_titre">
							<td><?php 
        echo $langs->trans("Ref");
        ?>
 <input type="text" id="add_related_object" name="add_related_object" value="" class="flat" /> <input type="submit" id="bt_add_related_object" name="bt_add_related_object" class="button" value="<?php 
        echo $langs->trans('AddRelated');
        ?>
" style="display:none" /></td>
							<td align="center"><?php 
        echo $langs->trans("Date");
        ?>
</td>
							<td align="center"><?php 
        echo $langs->trans("Status");
        ?>
</td>
							<td align="center"><?php 
        echo $langs->trans("Action");
        ?>
</td>
						</tr>
						<?php 
        $class = 'pair';
        foreach ($object->linkedObjectsIds as $objecttype => &$TSubIdObject) {
            //var_dump($objecttype);
            if (isset($object->linkedObjects[$objecttype]) && $objecttype != 'societe' && $objecttype != 'product' && $object->element != 'project') {
                continue;
            }
            // on affiche ici que les objects non géré en natif
            foreach ($TSubIdObject as $id_object) {
                $date_create = 0;
                $classname = ucfirst($objecttype);
                $statut = 'N/A';
                if ($objecttype == 'task') {
                    dol_include_once('/projet/class/task.class.php');
                } else {
                    if ($objecttype == 'event' || $objecttype == 'action') {
                        dol_include_once('/comm/action/class/actioncomm.class.php');
                        $classname = 'ActionComm';
                    } else {
                        if ($objecttype == 'project') {
                            dol_include_once('/projet/class/project.class.php');
                        } else {
                            if ($objecttype == 'ordre_fabrication') {
                                dol_include_once('/of/class/ordre_fabrication_asset.class.php');
                                $classname = 'TAssetOf';
                                $abricot = true;
                            }
                        }
                    }
                }
                if (!class_exists($classname)) {
                    $link = 'CantInstanciateClass ' . $classname;
                } else {
                    if (!empty($abricot)) {
                        if (empty($PDOdb)) {
                            $PDOdb = new TPDOdb();
                        }
                        $subobject = new $classname();
                        $subobject->load($PDOdb, $id_object);
                        if (method_exists($subobject, 'getNomUrl')) {
                            $link = $subobject->getNomUrl(1);
                        } else {
                            $link = $id_object . '/' . $classname;
                        }
                        $class = $class == 'impair' ? 'pair' : 'impair';
                        $date_create = $subobject->date_cre;
                        if (method_exists($subobject, 'getLibStatut')) {
                            $statut = $subobject->getLibStatut(3);
                        }
                    } else {
                        $subobject = new $classname($db);
                        $subobject->fetch($id_object);
                        if (method_exists($subobject, 'getNomUrl')) {
                            $link = $subobject->getNomUrl(1);
                        } else {
                            $link = $id_object . '/' . $classname;
                        }
                        $class = $class == 'impair' ? 'pair' : 'impair';
                        if (!empty($subobject->date_creation)) {
                            $date_create = $subobject->date_creation;
                        }
                        if (empty($date_create) && !empty($subobject->date_create)) {
                            $date_create = $subobject->date_create;
                        }
                        if (empty($date_create) && !empty($subobject->date_c)) {
                            $date_create = $subobject->date_c;
                        }
                        if (method_exists($subobject, 'getLibStatut')) {
                            $statut = $subobject->getLibStatut(3);
                        }
                    }
                }
                $Tids = TRequeteCore::get_id_from_what_you_want($PDOdb, MAIN_DB_PREFIX . "element_element", array('fk_source' => $id_object, 'fk_target' => $object->id, 'sourcetype' => $objecttype, 'targettype' => $object->element));
                ?>
									<tr class="<?php 
                echo $class;
                ?>
">
										<td><?php 
                echo $link;
                ?>
</td>
										<td align="center"><?php 
                echo !empty($date_create) ? dol_print_date($date_create, 'day') : '';
                ?>
</td>
										<td align="center"><?php 
                echo $statut;
                ?>
</td>
										<td align="center"><a href="?id=<?php 
                echo $object->id;
                ?>
&action=delete_related_link&id_link=<?php 
                echo $Tids[0];
                ?>
"><?php 
                print img_picto($langs->trans("Delete"), 'delete.png');
                ?>
</a></td>
									</tr>
									<?php 
            }
        }
        ?>
						</table>


		 		</form>
		 	</div>
		 		<script type="text/javascript">

		 			$(document).ready(function() {

		 				$('#add_related_object').autocomplete({
					      source: function( request, response ) {
					        $.ajax({
					          url: "<?php 
        echo dol_buildpath('/related/script/interface.php', 1);
        ?>
",
					          dataType: "json",
					          data: {
					              key: request.term
					            ,get:'search'
					          }
					          ,success: function( data ) {
					          	  var c = [];
					              $.each(data, function (i, cat) {

					              	var first = true;
					              	$.each(cat, function(j, label) {

					              		if(first) {
					              			c.push({value:i, label:i, object:'title'});
					              			first = false;
					              		}

					              		c.push({ value: j, label:'  '+label, object:i});

					              	});


					              });

					              response(c);



					          }
					        });
					      },
					      minLength: 1,
					      select: function( event, ui ) {

					       	if(ui.item.object == 'title') return false;
					       	else {
					       		$('#id_related_object').val(ui.item.value);
					       		$('#add_related_object').val(ui.item.label.trim());
					       		$('#type_related_object').val(ui.item.object);

					       		$('#bt_add_related_object').css('display','inline');

					       		return false;
					       	}

					      },
					      open: function( event, ui ) {
					        $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
					      },
					      close: function() {
					        $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
					      }
					    });

		 				$( "#add_related_object" ).autocomplete( "instance" )._renderItem = function( ul, item ) {

					      	  $li = $( "<li />" )
								    .attr( "data-value", item.value )
								    .append( item.label )
								    .appendTo( ul );

							  if(item.object=="title") $li.css("font-weight","bold");

							  return $li;
					    };


		 				var blockrelated = $('div.tabsAction .blockrelated_content');
		 				if (blockrelated.length == 1)
		 				{
		 					if ($('.blockrelated_content').length > 1)
		 					{
		 						blockrelated.remove();
		 					}
		 					else
		 					{
			 					$('div.tabsAction').after(blockrelated.clone());
			 					blockrelated.remove();
		 					}
		 				}

		 			});

		 		</script>

		 	<?php 
        if (!$error) {
            return 0;
            // or return 1 to replace standard code
        } else {
            $this->errors[] = 'Cant link related';
            return -1;
        }
    }
function tabImport(&$TImport, &$expedition)
{
    global $langs, $db;
    $form = new TFormCore();
    $formDoli = new Form($db);
    $formproduct = new FormProduct($db);
    $PDOdb = new TPDOdb();
    print count($TImport) . ' équipement(s) dans votre expédition';
    ?>
	<table width="100%" class="border">
		<tr class="liste_titre">
			<td>Produit</td>
			<td>Numéro de série</td>
			<td>Numéro de Lot</td>
			<td>Quantité</td>
			<td>&nbsp;</td>
		</tr>
		
	<?php 
    $prod = new Product($db);
    $form->Set_typeaff('view');
    if (is_array($TImport)) {
        foreach ($TImport as $k => $line) {
            if ($prod->id == 0 || $line['ref'] != $prod->ref) {
                if (!empty($line['fk_product'])) {
                    $prod->fetch($line['fk_product']);
                } else {
                    $prod->fetch('', $line['ref']);
                }
            }
            $asset = new TAsset();
            $asset->loadBy($PDOdb, $line['numserie'], 'serial_number');
            $asset->load_asset_type($PDOdb);
            $assetLot = new TAssetLot();
            $assetLot->loadBy($PDOdb, $line['lot_number'], 'lot_number');
            $Trowid = TRequeteCore::get_id_from_what_you_want($PDOdb, MAIN_DB_PREFIX . "expeditiondet_asset", array('fk_asset' => $asset->rowid, 'fk_expeditiondet' => $line['fk_expeditiondet']));
            ?>
<tr>
					<td><?php 
            echo $prod->getNomUrl(1) . $form->hidden('TLine[' . $k . '][fk_product]', $prod->id) . $form->hidden('TLine[' . $k . '][ref]', $prod->ref);
            ?>
</td>
					<td><a href="<?php 
            echo dol_buildpath('/asset/fiche.php?id=' . $asset->rowid, 1);
            ?>
"><?php 
            echo $form->texte('', 'TLine[' . $k . '][numserie]', $line['numserie'], 30);
            ?>
</a></td>
					<td><a href="<?php 
            echo dol_buildpath('/asset/fiche_lot.php?id=' . $assetLot->rowid, 1);
            ?>
"><?php 
            echo $form->texte('', 'TLine[' . $k . '][lot_number]', $line['lot_number'], 30);
            ?>
</a></td>
					<td><?php 
            echo $line['quantity'] . " " . ($asset->assetType->measuring_units == 'unit' ? 'unité(s)' : measuring_units_string($line['quantity_unit'], $asset->assetType->measuring_units));
            ?>
</td>
					<td>
						<?php 
            if ($expedition->statut != 1) {
                echo '<a href="?action=DELETE_LINE&k=' . $k . '&id=' . $expedition->id . '&rowid=' . $Trowid[0] . '">' . img_delete() . '</a>';
            }
            ?>
					</td>
				</tr>
				
				<?php 
        }
    }
    ?>
			
		
	</table>
	<br>
	<?php 
}
 static function getCombo(&$PDOdb)
 {
     global $langs;
     return array(0 => $langs->trans('DolibarrDB')) + TRequeteCore::get_keyval_by_sql($PDOdb, "SELECT rowid,CONCAT(login,'@', host,':',db_name) as host FROM " . MAIN_DB_PREFIX . 'query_bdd_connector', 'rowid', 'host');
 }
 function loadChild(&$db)
 {
     if ($this->withChild) {
         foreach ($this->TChildObjetStd as $child) {
             $className = $child['class'];
             $foreignKey = $child['foreignKey'];
             //print $className;print_r($foreignKey);print '<br>';
             if (is_array($foreignKey)) {
                 $keys = array($foreignKey[0] => $this->getId(), 'objectType' => $foreignKey[1]);
                 $tabName = $className . '_' . $foreignKey[1];
             } else {
                 $keys = array($foreignKey => $this->getId());
                 $tabName = $className;
             }
             $this->{$tabName} = array();
             $o = new $className();
             $TId = TRequeteCore::get_id_from_what_you_want($db, $o->get_table(), $keys);
             foreach ($TId as $k => $id) {
                 $this->{$tabName}[$k] = new $className();
                 $this->{$tabName}[$k]->load($db, $id);
             }
         }
     }
 }
 /**
  *      Function called when a Dolibarrr business event is done.
  *      All functions "run_trigger" are triggered if file is inside directory htdocs/core/triggers
  *
  *      @param	string		$action		Event action code
  *      @param  Object		$object     Object
  *      @param  User		$user       Object user
  *      @param  Translate	$langs      Object langs
  *      @param  conf		$conf       Object conf
  *      @return int         			<0 if KO, 0 if no triggered ran, >0 if OK
  */
 function run_trigger($action, $object, $user, $langs, $conf)
 {
     global $conf, $db;
     if (!defined('INC_FROM_DOLIBARR')) {
         define('INC_FROM_DOLIBARR', true);
     }
     if ($action == 'SHIPPING_VALIDATE') {
         dol_include_once('/dispatch/config.php');
         dol_include_once('/dispatch/class/dispatchdetail.class.php');
         $PDOdb = new TPDOdb();
         // Pour chaque ligne de l'expédition
         foreach ($object->lines as $line) {
             // Chargement de l'objet detail dispatch relié à la ligne d'expédition
             $dd = new TDispatchDetail();
             $TIdExpeditionDet = TRequeteCore::get_id_from_what_you_want($PDOdb, MAIN_DB_PREFIX . 'expeditiondet', array('fk_expedition' => $object->id, 'fk_origin_line' => $line->fk_origin_line));
             $idExpeditionDet = $TIdExpeditionDet[0];
             //if(!empty($idExpeditionDet) && $dd->loadBy($PDOdb, $idExpeditionDet, 'fk_expeditiondet')) {
             if (!empty($idExpeditionDet)) {
                 $dd->loadLines($PDOdb, $idExpeditionDet);
                 if ($conf->asset->enabled) {
                     // Création des mouvements de stock de flacon
                     foreach ($dd->lines as $detail) {
                         // Création du mouvement de stock standard
                         $poids_destocke = $this->create_flacon_stock_mouvement($PDOdb, $detail, $object->ref, empty($object->fk_soc) ? $object->socid : $object->fk_soc);
                         //$this->create_standard_stock_mouvement($line, $poids_destocke, $object->ref);
                         if ($conf->clinomadic->enabled) {
                             $asset = new TAsset();
                             $asset->load($PDOdb, $detail->fk_asset);
                             $prod = new Product($db);
                             $prod->fetch($asset->fk_product);
                             //Affectation du type d'équipement pour avoir accès aux extrafields équipement
                             $asset->fk_asset_type = $asset->get_asset_type($PDOdb, $prod->id);
                             $asset->load_asset_type($PDOdb);
                             //Localisation client
                             $asset->fk_societe_localisation = $object->socid;
                             if (!empty($object->linkedObjects['commande'][0]->array_options['options_duree_pret'])) {
                                 $asset->etat = 2;
                                 //Prêté
                                 $asset->set_date('date_deb_pret', $object->date_valid);
                                 $asset->set_date('date_fin_pret', strtotime('+' . $object->commande[0]->array_options['options_duree_pret'] . 'year', $object->date_valid));
                             } else {
                                 $asset->etat = 1;
                                 //Vendu
                             }
                             foreach ($object->linkedObjects['commande'][0]->lines as $line) {
                                 if ($line->fk_product == $asset->fk_product) {
                                     $extension_garantie = $line->array_options['options_extension_garantie'];
                                 }
                             }
                             $nb_year_garantie += $prod->array_options['options_duree_garantie_client'];
                             $asset->date_fin_garantie_cli = strtotime('+' . $nb_year_garantie . 'year', $object->date_valid);
                             $asset->date_fin_garantie_cli = strtotime('+' . $extension_garantie . 'year', $asset->date_fin_garantie_cli);
                             $asset->save($PDOdb);
                         }
                     }
                 }
                 //exit;
             }
             /* else { // Pas de détail, on déstocke la quantité comme Dolibarr standard
             				$this->create_standard_stock_mouvement($line, $line->qty, $object->ref);
             			}*/
         }
         dol_syslog("Trigger '" . $this->name . "' for action '{$action}' launched by " . __FILE__ . ". id=" . $object->id);
     }
     return 0;
 }
 static function get_keyval_by_sql(&$db, $sql, $fieldkey, $fieldval)
 {
     return TRequeteCore::_get_id_by_sql($db, $sql, $fieldval, $fieldkey);
 }