/** * Delete invoice * * @param int $id Invoice ID * @return type * * @url DELETE invoice/{id} */ function delete($id) { if (!DolibarrApiAccess::$user->rights->facture->supprimer) { throw new RestException(401); } $result = $this->invoice->fetch($id); if (!$result) { throw new RestException(404, 'Facture not found'); } if (!DolibarrApi::_checkAccessToResource('facture', $this->facture->id)) { throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login); } if (!$this->invoice->delete($id)) { throw new RestException(500); } return array('success' => array('code' => 200, 'message' => 'Facture deleted')); }
function generateCSV() { global $db, $conf; $TFactRef = $_REQUEST['toGenerate']; // Création et attribution droits fichier $dir = $conf->lcr->dir_output; $filename = 'lcr_' . date('YmdHis') . '.csv'; $f = fopen($dir . '/' . $filename, 'w+'); chmod($dir . '/' . $filename, 0777); $TTitle = array('Code client', 'Raison sociale', 'Adresse 1', 'Adresse 2', 'Code postal', 'Ville', 'Téléphone', 'Référence', 'SIREN', 'RIB', 'Agence', 'Montant', 'Monnaie', 'Accepté', 'Référence', 'Date de création', 'Date d\'échéance'); fputcsv($f, $TTitle, ';'); $fact = new Facture($db); $s = new Societe($db); foreach ($TFactRef as $ref_fact) { if ($fact->fetch('', $ref_fact) > 0 && $s->fetch($fact->socid) > 0) { $rib = $s->get_all_rib(); fputcsv($f, array($s->code_client, $s->name, $s->address, '', $s->zip, $s->town, $s->phone, $ref_fact, $s->idprof1, $rib[0]->iban, '', price($fact->total_ttc), 'E', 1, $ref_fact, date('d/m/Y', $fact->date), date('d/m/Y', $fact->date_lim_reglement)), ';'); } } fclose($f); }
print '<td align="right">' . $langs->trans('AmountTTC') . '</td>'; print '<td align="right">' . $langs->trans('Received') . '</td>'; print '<td align="right">' . $langs->trans('RemainderToPay') . '</td>'; print '<td align="right">' . $langs->trans('PaymentAmount') . '</td>'; print '<td align="right"> </td>'; print "</tr>\n"; $var = True; $total = 0; $totalrecu = 0; $totalrecucreditnote = 0; $totalrecudeposits = 0; while ($i < $num) { $objp = $db->fetch_object($resql); $var = !$var; $invoice = new Facture($db); $invoice->fetch($objp->facid); $paiement = $invoice->getSommePaiement(); $creditnotes = $invoice->getSumCreditNotesUsed(); $deposits = $invoice->getSumDepositsUsed(); $alreadypayed = price2num($paiement + $creditnotes + $deposits, 'MT'); $remaintopay = price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits, 'MT'); print '<tr ' . $bc[$var] . '>'; print '<td>'; print $invoice->getNomUrl(1, ''); print "</td>\n"; // Date print '<td align="center">' . dol_print_date($db->jdate($objp->df), 'day') . "</td>\n"; // Prix print '<td align="right">' . price($objp->total_ttc) . '</td>'; // Recu print '<td align="right">' . price($paiement);
// Si texte entoure de parenthese on tente recherche de traduction if ($reg[1] && $langs->transnoentitiesnoconv($reg[1]) != $reg[1]) { $description = $langs->transnoentitiesnoconv($reg[1]); } else { $description = $objp->label; } /* * Ajout les liens (societe, company...) */ $links = $acct->get_url($objp->rowid); foreach ($links as $key => $val) { if ($links[$key]['type'] == 'payment') { $paymentstatic->fetch($links[$key]['url_id']); $tmparray = $paymentstatic->getBillsArray(''); foreach ($tmparray as $key => $val) { $invoicestatic->fetch($val); if ($accountelem) { $accountelem .= ', '; } $accountelem .= $invoicestatic->ref; } } elseif ($links[$key]['type'] == 'payment_supplier') { $paymentsupplierstatic->fetch($links[$key]['url_id']); $tmparray = $paymentsupplierstatic->getBillsArray(''); foreach ($tmparray as $key => $val) { $invoicesupplierstatic->fetch($val); if ($accountelem) { $accountelem .= ', '; } $accountelem .= $invoicesupplierstatic->ref; }
/** * Add a record into bank for payment with links between this bank record and invoices of payment. * All payment properties (this->amount, this->amounts, ...) must have been set first like after a call to create(). * * @param User $user Object of user making payment * @param string $mode 'payment', 'payment_supplier' * @param string $label Label to use in bank record * @param int $accountid Id of bank account to do link with * @param string $emetteur_nom Name of transmitter * @param string $emetteur_banque Name of bank * @param int $notrigger No trigger * @return int <0 if KO, bank_line_id if OK */ function addPaymentToBank($user, $mode, $label, $accountid, $emetteur_nom, $emetteur_banque, $notrigger = 0) { global $conf, $langs, $user; $error = 0; $bank_line_id = 0; if (!empty($conf->banque->enabled)) { if ($accountid <= 0) { $this->error = 'Bad value for parameter accountid'; dol_syslog(get_class($this) . '::addPaymentToBank ' . $this->error, LOG_ERR); return -1; } $this->db->begin(); $this->fk_account = $accountid; require_once DOL_DOCUMENT_ROOT . '/compta/bank/class/account.class.php'; dol_syslog("{$user->id},{$mode},{$label},{$this->fk_account},{$emetteur_nom},{$emetteur_banque}"); $acc = new Account($this->db); $result = $acc->fetch($this->fk_account); $totalamount = $this->amount; if (empty($totalamount)) { $totalamount = $this->total; } // For backward compatibility if ($mode == 'payment_supplier') { $totalamount = -$totalamount; } // Insert payment into llx_bank $bank_line_id = $acc->addline($this->datepaye, $this->paiementid, $label, $totalamount, $this->num_paiement, '', $user, $emetteur_nom, $emetteur_banque); // Mise a jour fk_bank dans llx_paiement // On connait ainsi le paiement qui a genere l'ecriture bancaire if ($bank_line_id > 0) { $result = $this->update_fk_bank($bank_line_id); if ($result <= 0) { $error++; dol_print_error($this->db); } // Add link 'payment', 'payment_supplier' in bank_url between payment and bank transaction if (!$error) { $url = ''; if ($mode == 'payment') { $url = DOL_URL_ROOT . '/compta/paiement/card.php?id='; } if ($mode == 'payment_supplier') { $url = DOL_URL_ROOT . '/fourn/paiement/card.php?id='; } if ($url) { $result = $acc->add_url_line($bank_line_id, $this->id, $url, '(paiement)', $mode); if ($result <= 0) { $error++; dol_print_error($this->db); } } } // Add link 'company' in bank_url between invoice and bank transaction (for each invoice concerned by payment) if (!$error && $label != '(WithdrawalPayment)') { $linkaddedforthirdparty = array(); foreach ($this->amounts as $key => $value) { if ($mode == 'payment') { $fac = new Facture($this->db); $fac->fetch($key); $fac->fetch_thirdparty(); if (!in_array($fac->thirdparty->id, $linkaddedforthirdparty)) { $result = $acc->add_url_line($bank_line_id, $fac->thirdparty->id, DOL_URL_ROOT . '/comm/card.php?socid=', $fac->thirdparty->name, 'company'); if ($result <= 0) { dol_syslog(get_class($this) . '::addPaymentToBank ' . $this->db->lasterror()); } $linkaddedforthirdparty[$fac->thirdparty->id] = $fac->thirdparty->id; // Mark as done for this thirdparty } } if ($mode == 'payment_supplier') { $fac = new FactureFournisseur($this->db); $fac->fetch($key); $fac->fetch_thirdparty(); if (!in_array($fac->thirdparty->id, $linkaddedforthirdparty)) { $result = $acc->add_url_line($bank_line_id, $fac->thirdparty->id, DOL_URL_ROOT . '/fourn/card.php?socid=', $fac->thirdparty->name, 'company'); if ($result <= 0) { dol_syslog(get_class($this) . '::addPaymentToBank ' . $this->db->lasterror()); } $linkaddedforthirdparty[$fac->thirdparty->id] = $fac->thirdparty->id; // Mark as done for this thirdparty } } } } if (!$error && !$notrigger) { // Appel des triggers $result = $this->call_trigger('PAYMENT_ADD_TO_BANK', $user); if ($result < 0) { $error++; } // Fin appel triggers } } else { $this->error = $acc->error; $error++; } if (!$error) { $this->db->commit(); } else { $this->db->rollback(); } } if (!$error) { return $bank_line_id; } else { return -1; } }
$email=$order->client->email; $email=(GETPOST("email")?GETPOST("email"):(isValidEmail($email)?$email:'')); print '</td><td class="CTableRow'.($var?'1':'2').'"><input class="flat" type="text" name="email" size="48" value="'.$email.'"></td></tr>'."\n"; } // Payment on customer invoice if (GETPOST("source") == 'invoice') { $found=true; $langs->load("bills"); require_once(DOL_DOCUMENT_ROOT."/compta/facture/class/facture.class.php"); $invoice=new Facture($db); $result=$invoice->fetch('',$_REQUEST["ref"]); if ($result < 0) { $mesg=$invoice->error; $error++; } else { $result=$invoice->fetch_thirdparty($invoice->socid); } $amount=$invoice->total_ttc - $invoice->getSommePaiement(); if (GETPOST("amount",'int')) $amount=GETPOST("amount",'int'); $amount=price2num($amount); $fulltag='IR='.$invoice->ref.'.TPID='.$invoice->client->id.'.TP='.strtr($invoice->client->nom,"-"," ");
/** * Tag invoice as validated + call trigger BILL_VALIDATE * Object must have lines loaded with fetch_lines * * @param User $user Object user that validate * @param string $force_number Reference to force on invoice * @param int $idwarehouse Id of warehouse to use for stock decrease * @return int <0 if KO, >0 if OK */ function validate($user, $force_number = '', $idwarehouse = 0) { global $conf, $langs; require_once DOL_DOCUMENT_ROOT . "/core/lib/files.lib.php"; $now = dol_now(); $error = 0; dol_syslog(get_class($this) . '::validate user='******', force_number=' . $force_number . ', idwarehouse=' . $idwarehouse, LOG_WARNING); // Check parameters if (!$this->brouillon) { dol_syslog(get_class($this) . "::validate no draft status", LOG_WARNING); return 0; } if (!$user->rights->facture->valider) { $this->error = 'Permission denied'; dol_syslog(get_class($this) . "::validate " . $this->error, LOG_ERR); return -1; } $this->db->begin(); $this->fetch_thirdparty(); $this->fetch_lines(); // Check parameters if ($this->type == 1) { // Controle que facture source connue if ($this->fk_facture_source <= 0) { $this->error = $langs->trans("ErrorFieldRequired", $langs->trans("InvoiceReplacement")); $this->db->rollback(); return -10; } // Charge la facture source a remplacer $facreplaced = new Facture($this->db); $result = $facreplaced->fetch($this->fk_facture_source); if ($result <= 0) { $this->error = $langs->trans("ErrorBadInvoice"); $this->db->rollback(); return -11; } // Controle que facture source non deja remplacee par une autre $idreplacement = $facreplaced->getIdReplacingInvoice('validated'); if ($idreplacement && $idreplacement != $this->id) { $facreplacement = new Facture($this->db); $facreplacement->fetch($idreplacement); $this->error = $langs->trans("ErrorInvoiceAlreadyReplaced", $facreplaced->ref, $facreplacement->ref); $this->db->rollback(); return -12; } $result = $facreplaced->set_canceled($user, 'replaced', ''); if ($result < 0) { $this->error = $facreplaced->error; $this->db->rollback(); return -13; } } // Define new ref if ($force_number) { $num = $force_number; } else { if (preg_match('/^[\\(]?PROV/i', $this->ref)) { if (!empty($conf->global->FAC_FORCE_DATE_VALIDATION)) { $this->date = dol_now(); $this->date_lim_reglement = $this->calculate_date_lim_reglement(); } $num = $this->getNextNumRef($this->client); } else { $num = $this->ref; } } if ($num) { $this->update_price(1); // Validate $sql = 'UPDATE ' . MAIN_DB_PREFIX . 'facture'; $sql .= " SET facnumber='" . $num . "', fk_statut = 1, fk_user_valid = " . $user->id . ", date_valid = '" . $this->db->idate($now) . "'"; if (!empty($conf->global->FAC_FORCE_DATE_VALIDATION)) { $sql .= ', datef=' . $this->db->idate($this->date); $sql .= ', date_lim_reglement=' . $this->db->idate($this->date_lim_reglement); } $sql .= ' WHERE rowid = ' . $this->id; dol_syslog(get_class($this) . "::validate sql=" . $sql); $resql = $this->db->query($sql); if (!$resql) { dol_syslog(get_class($this) . "::validate Echec update - 10 - sql=" . $sql, LOG_ERR); dol_print_error($this->db); $error++; } // On verifie si la facture etait une provisoire if (!$error && preg_match('/^[\\(]?PROV/i', $this->ref)) { // La verif qu'une remise n'est pas utilisee 2 fois est faite au moment de l'insertion de ligne } if (!$error) { // Define third party as a customer $result = $this->client->set_as_client(); // Si active on decremente le produit principal et ses composants a la validation de facture if ($this->type != 3 && $result >= 0 && $conf->stock->enabled && $conf->global->STOCK_CALCULATE_ON_BILL) { require_once DOL_DOCUMENT_ROOT . "/product/stock/class/mouvementstock.class.php"; $langs->load("agenda"); // Loop on each line $cpt = count($this->lines); for ($i = 0; $i < $cpt; $i++) { if ($this->lines[$i]->fk_product > 0) { $mouvP = new MouvementStock($this->db); // We decrease stock for product if ($this->type == 2) { $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarr", $num)); } else { $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarr", $num)); } if ($result < 0) { $error++; } } } } } if (!$error) { $this->oldref = ''; // Rename directory if dir was a temporary ref if (preg_match('/^[\\(]?PROV/i', $this->ref)) { // On renomme repertoire facture ($this->ref = ancienne ref, $num = nouvelle ref) // afin de ne pas perdre les fichiers attaches $facref = dol_sanitizeFileName($this->ref); $snumfa = dol_sanitizeFileName($num); $dirsource = $conf->facture->dir_output . '/' . $facref; $dirdest = $conf->facture->dir_output . '/' . $snumfa; if (file_exists($dirsource)) { dol_syslog(get_class($this) . "::validate rename dir " . $dirsource . " into " . $dirdest); if (@rename($dirsource, $dirdest)) { $this->oldref = $facref; dol_syslog("Rename ok"); // Suppression ancien fichier PDF dans nouveau rep dol_delete_file($conf->facture->dir_output . '/' . $snumfa . '/' . $facref . '.*'); } } } } // Set new ref and define current statut if (!$error) { $this->ref = $num; $this->facnumber = $num; $this->statut = 1; $this->date_validation = $now; } // Trigger calls if (!$error) { // Appel des triggers include_once DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php"; $interface = new Interfaces($this->db); $result = $interface->run_triggers('BILL_VALIDATE', $this, $user, $langs, $conf); if ($result < 0) { $error++; $this->errors = $interface->errors; } // Fin appel triggers } } else { $error++; } if (!$error) { $this->db->commit(); return 1; } else { $this->db->rollback(); $this->error = $this->db->lasterror(); return -1; } }
print ' ('.$langs->transnoentities("InvoiceHasAvoir"); $i=0; foreach($facidavoir as $id) { if ($i==0) print ' '; else print ','; $facavoir=new Facture($db); $facavoir->fetch($id); print $facavoir->getNomUrl(1); } print ')'; } if ($facidnext > 0) { $facthatreplace=new Facture($db); $facthatreplace->fetch($facidnext); print ' ('.$langs->transnoentities("ReplacedByInvoice",$facthatreplace->getNomUrl(1)).')'; } print '</td></tr>'; // Discounts print '<tr><td>'.$langs->trans('Discounts').'</td><td colspan="5">'; if ($soc->remise_client) print $langs->trans("CompanyHasRelativeDiscount",$soc->remise_client); else print $langs->trans("CompanyHasNoRelativeDiscount"); print '. '; if ($absolute_discount > 0) { if ($fac->statut > 0 || $fac->type == 2 || $fac->type == 3) { if ($fac->statut == 0) {
/** * Get list of invoices for third party * * @param array $authentication Array of authentication information * @param int $idthirdparty Id thirdparty * @return array Array result */ function getInvoicesForThirdParty($authentication, $idthirdparty) { global $db, $conf, $langs; dol_syslog("Function: getInvoicesForThirdParty login="******" idthirdparty=" . $idthirdparty); if ($authentication['entity']) { $conf->entity = $authentication['entity']; } // Init and check authentication $objectresp = array(); $errorcode = ''; $errorlabel = ''; $error = 0; $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); if ($fuser->societe_id) { $socid = $fuser->societe_id; } // Check parameters if (!$error && empty($idthirdparty)) { $error++; $errorcode = 'BAD_PARAMETERS'; $errorlabel = 'Parameter id is not provided'; } if (!$error) { $linesinvoice = array(); $sql .= 'SELECT f.rowid as facid, facnumber as ref, ref_ext, type, fk_statut as status, total_ttc, total, tva'; $sql .= ' FROM ' . MAIN_DB_PREFIX . 'facture as f'; $sql .= " WHERE f.entity = " . $conf->entity; if ($idthirdparty != 'all') { $sql .= " AND f.fk_soc = " . $db->escape($idthirdparty); } $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); $i = 0; while ($i < $num) { // En attendant remplissage par boucle $obj = $db->fetch_object($resql); $invoice = new Facture($db); $invoice->fetch($obj->facid); // Sécurité pour utilisateur externe if ($socid && $socid != $invoice->socid) { $error++; $errorcode = 'PERMISSION_DENIED'; $errorlabel = $invoice->socid . ' User does not have permission for this request'; } if (!$error) { // Define lines of invoice $linesresp = array(); foreach ($invoice->lines as $line) { $linesresp[] = array('id' => $line->rowid, 'type' => $line->product_type, 'total_net' => $line->total_ht, 'total_vat' => $line->total_tva, 'total' => $line->total_ttc, 'vat_rate' => $line->tva_tx, 'qty' => $line->qty, 'product_ref' => $line->product_ref, 'product_label' => $line->product_label, 'product_desc' => $line->product_desc); } // Now define invoice $linesinvoice[] = array('id' => $invoice->id, 'ref' => $invoice->ref, 'ref_ext' => $invoice->ref_ext ? $invoice->ref_ext : '', 'fk_user_author' => $invoice->user_author ? $invoice->user_author : '', 'fk_user_valid' => $invoice->user_valid ? $invoice->user_valid : '', 'date' => $invoice->date ? dol_print_date($invoice->date, 'dayrfc') : '', 'date_due' => $invoice->date_lim_reglement ? dol_print_date($invoice->date_lim_reglement, 'dayrfc') : '', 'date_creation' => $invoice->date_creation ? dol_print_date($invoice->date_creation, 'dayhourrfc') : '', 'date_validation' => $invoice->date_validation ? dol_print_date($invoice->date_creation, 'dayhourrfc') : '', 'date_modification' => $invoice->datem ? dol_print_date($invoice->datem, 'dayhourrfc') : '', 'type' => $invoice->type, 'total_net' => $invoice->total_ht, 'total_vat' => $invoice->total_tva, 'total' => $invoice->total_ttc, 'note_private' => $invoice->note_private ? $invoice->note_private : '', 'note_public' => $invoice->note_public ? $invoice->note_public : '', 'status' => $invoice->statut, 'close_code' => $invoice->close_code ? $invoice->close_code : '', 'close_note' => $invoice->close_note ? $invoice->close_note : '', 'lines' => $linesresp); } $i++; } $objectresp = array('result' => array('result_code' => 'OK', 'result_label' => ''), 'invoices' => $linesinvoice); } else { $error++; $errorcode = $db->lasterrno(); $errorlabel = $db->lasterror(); } } if ($error) { $objectresp = array('result' => array('result_code' => $errorcode, 'result_label' => $errorlabel)); } return $objectresp; }
/** * Define array with couple substitution key => substitution value * * @param Object $object Main object to use as data source * @param Translate $outputlangs Lang object to use for output * @param array_key $array_key Name of the key for return array * @return array Array of substitution */ function get_substitutionarray_object($object, $outputlangs, $array_key = 'object') { global $conf; $sumpayed = ''; $alreadypayed = ''; if ($object->element == 'facture') { $invoice_source = new Facture($this->db); if ($object->fk_facture_source > 0) { $invoice_source->fetch($object->fk_facture_source); } $sumpayed = $object->getSommePaiement(); $alreadypayed = price($sumpayed, 0, $outputlangs); } $resarray = array($array_key . '_id' => $object->id, $array_key . '_ref' => $object->ref, $array_key . '_ref_ext' => $object->ref_ext, $array_key . '_ref_customer' => $object->ref_client, $array_key . '_ref_supplier' => !empty($object->ref_fournisseur) ? $object->ref_fournisseur : '', $array_key . '_source_invoice_ref' => $invoice_source->ref, $array_key . '_hour' => dol_print_date($object->date, 'hour'), $array_key . '_date' => dol_print_date($object->date, 'day'), $array_key . '_date_rfc' => dol_print_date($object->date, 'dayrfc'), $array_key . '_date_limit' => !empty($object->date_lim_reglement) ? dol_print_date($object->date_lim_reglement, 'day') : '', $array_key . '_date_end' => !empty($object->fin_validite) ? dol_print_date($object->fin_validite, 'day') : '', $array_key . '_date_creation' => dol_print_date($object->date_creation, 'day'), $array_key . '_date_modification' => !empty($object->date_modification) ? dol_print_date($object->date_modification, 'day') : '', $array_key . '_date_validation' => !empty($object->date_validation) ? dol_print_date($object->date_validation, 'dayhour') : '', $array_key . '_date_delivery_planed' => !empty($object->date_livraison) ? dol_print_date($object->date_livraison, 'day') : '', $array_key . '_date_close' => !empty($object->date_cloture) ? dol_print_date($object->date_cloture, 'dayhour') : '', $array_key . '_payment_mode_code' => $object->mode_reglement_code, $array_key . '_payment_mode' => $outputlangs->transnoentitiesnoconv('PaymentType' . $object->mode_reglement_code) != 'PaymentType' . $object->mode_reglement_code ? $outputlangs->transnoentitiesnoconv('PaymentType' . $object->mode_reglement_code) : $object->mode_reglement, $array_key . '_payment_term_code' => $object->cond_reglement_code, $array_key . '_payment_term' => $outputlangs->transnoentitiesnoconv('PaymentCondition' . $object->cond_reglement_code) != 'PaymentCondition' . $object->cond_reglement_code ? $outputlangs->transnoentitiesnoconv('PaymentCondition' . $object->cond_reglement_code) : $object->cond_reglement, $array_key . '_total_ht_locale' => price($object->total_ht, 0, $outputlangs), $array_key . '_total_vat_locale' => price($object->total_tva, 0, $outputlangs), $array_key . '_total_localtax1_locale' => price($object->total_localtax1, 0, $outputlangs), $array_key . '_total_localtax2_locale' => price($object->total_localtax2, 0, $outputlangs), $array_key . '_total_ttc_locale' => price($object->total_ttc, 0, $outputlangs), $array_key . '_total_discount_ht_locale' => price($object->getTotalDiscount(), 0, $outputlangs), $array_key . '_total_ht' => price2num($object->total_ht), $array_key . '_total_vat' => price2num($object->total_tva), $array_key . '_total_localtax1' => price2num($object->total_localtax1), $array_key . '_total_localtax2' => price2num($object->total_localtax2), $array_key . '_total_ttc' => price2num($object->total_ttc), $array_key . '_total_discount_ht' => price2num($object->getTotalDiscount()), $array_key . '_note_private' => $object->note, $array_key . '_note_public' => $object->note_public, $array_key . '_note' => $object->note_public, $array_key . '_already_payed_locale' => price($alreadypayed, 0, $outputlangs), $array_key . '_remain_to_pay_locale' => price($object->total_ttc - $sumpayed, 0, $outputlangs), $array_key . '_already_payed' => $alreadypayed, $array_key . '_remain_to_pay' => price2num($object->total_ttc - $sumpayed)); // Add vat by rates foreach ($object->lines as $line) { // $line->tva_tx format depends on database field accuraty, no reliable. This is kept for backward comaptibility if (empty($resarray[$array_key . '_total_vat_' . $line->tva_tx])) { $resarray[$array_key . '_total_vat_' . $line->tva_tx] = 0; } $resarray[$array_key . '_total_vat_' . $line->tva_tx] += $line->total_tva; $resarray[$array_key . '_total_vat_locale_' . $line->tva_tx] = price($resarray[$array_key . '_total_vat_' . $line->tva_tx]); // $vatformated is vat without not expected chars (so 20, or 8.5 or 5.99 for example) $vatformated = vatrate($line->tva_tx); if (empty($resarray[$array_key . '_total_vat_' . $vatformated])) { $resarray[$array_key . '_total_vat_' . $vatformated] = 0; } $resarray[$array_key . '_total_vat_' . $vatformated] += $line->total_tva; $resarray[$array_key . '_total_vat_locale_' . $vatformated] = price($resarray[$array_key . '_total_vat_' . $vatformated]); } // Retrieve extrafields if (is_array($object->array_options) && count($object->array_options)) { $extrafieldkey = $object->element; require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; $extrafields = new ExtraFields($this->db); $extralabels = $extrafields->fetch_name_optionals_label($extrafieldkey, true); $object->fetch_optionals($object->id, $extralabels); $resarray = $this->fill_substitutionarray_with_extrafields($object, $resarray, $extrafields, $array_key, $outputlangs); } return $resarray; }
$param .= 'search_paymentmode=' . $search_paymentmode; } $param .= !empty($option) ? "&option=" . $option : ""; $massactionbutton = $form->selectMassAction('', $massaction ? array() : array('presend' => $langs->trans("SendByMail"))); $i = 0; print '<form method="POST" name="searchFormList" action="' . $_SERVER["PHP_SELF"] . '">' . "\n"; print_barre_liste($langs->trans('BillsCustomers') . ' ' . ($socid ? ' ' . $soc->name : ''), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_accountancy.png'); if ($massaction == 'presend') { $langs->load("mails"); if (!GETPOST('cancel')) { $objecttmp = new Facture($db); $listofselectedid = array(); $listofselectedthirdparties = array(); $listofselectedref = array(); foreach ($arrayofselected as $toselectid) { $result = $objecttmp->fetch($toselectid); if ($result > 0) { $listofselectedid[$toselectid] = $toselectid; $thirdpartyid = $objecttmp->fk_soc ? $objecttmp->fk_soc : $objecttmp->socid; $listofselectedthirdparties[$thirdpartyid] = $thirdpartyid; $listofselectedref[$thirdpartyid][$toselectid] = $objecttmp->ref; } } } print '<input type="hidden" name="massaction" value="confirm_presend">'; include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php'; $formmail = new FormMail($db); dol_fiche_head(null, '', ''); $topicmail = "SendBillRef"; $modelmail = "facture_send"; // Cree l'objet formulaire mail
// For backward compatibility $ref = GETPOST('ref', 'alpha'); $lineid = GETPOST('lineid', 'int'); $socid = GETPOST('socid', 'int'); $action = GETPOST('action', 'alpha'); // Security check if ($user->societe_id) { $socid = $user->societe_id; } $result = restrictedArea($user, 'facture', $id); $object = new Facture($db); /* * Ajout d'un nouveau contact */ if ($action == 'addcontact' && $user->rights->facture->creer) { $result = $object->fetch($id); if ($result > 0 && $id > 0) { $contactid = GETPOST('userid') ? GETPOST('userid', 'int') : GETPOST('contactid', 'int'); $result = $object->add_contact($contactid, $_POST["type"], $_POST["source"]); } if ($result >= 0) { Header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $object->id); exit; } else { if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); $mesg = '<div class="error">' . $langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType") . '</div>'; } else { $mesg = '<div class="error">' . $object->error . '</div>'; } }
/** * Test function addline and update_price * * @return boolean * @see http://wiki.dolibarr.org/index.php/Draft:VAT_calculation_and_rounding#Standard_usage */ public function testUpdatePrice() { //$this->sharedFixture global $conf, $user, $langs, $db; $this->savconf = $conf; $this->savuser = $user; $this->savlangs = $langs; $this->savdb = $db; $conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND = 0; // Two lines of 1.24 give 2.48 HT and 2.72 TTC with standard vat rounding mode $localobject = new Facture($this->savdb); $localobject->initAsSpecimen('nolines'); $invoiceid = $localobject->create($user); $localobject->addline('Desc', 1.24, 1, 10, 0, 0, 0, 0, '', '', 0, 0, 0, 'HT'); $localobject->addline('Desc', 1.24, 1, 10, 0, 0, 0, 0, '', '', 0, 0, 0, 'HT'); $newlocalobject = new Facture($this->savdb); $newlocalobject->fetch($invoiceid); $this->assertEquals(2.48, $newlocalobject->total_ht, "testUpdatePrice test1"); $this->assertEquals(0.24, $newlocalobject->total_tva, "testUpdatePrice test2"); $this->assertEquals(2.72, $newlocalobject->total_ttc, "testUpdatePrice test3"); // Two lines of 1.24 give 2.48 HT and 2.73 TTC with global vat rounding mode $localobject = new Facture($this->savdb); $localobject->initAsSpecimen('nolines'); $invoiceid = $localobject->create($user); $localobject->addline('Desc', 1.24, 1, 10, 0, 0, 0, 0, '', '', 0, 0, 0, 'HT'); $localobject->addline('Desc', 1.24, 1, 10, 0, 0, 0, 0, '', '', 0, 0, 0, 'HT'); $newlocalobject = new Facture($this->savdb); $newlocalobject->fetch($invoiceid); $this->assertEquals(2.48, $newlocalobject->total_ht, "testUpdatePrice test4"); //$this->assertEquals(0.25,$newlocalobject->total_tva); //$this->assertEquals(2.73,$newlocalobject->total_ttc); }
$mesg = '<div class="error">' . $paiement->error . '</div>'; $db->rollback(); } } // Create payment if ($_REQUEST['action'] == 'confirm_valide' && $_REQUEST['confirm'] == 'yes' && $user->rights->tax->charges->creer) { $db->begin(); $paiement = new PaymentSocialContribution($db); $paiement->id = $_REQUEST['id']; if ($paiement->valide() > 0) { $db->commit(); $factures = array(); // TODO Get all id of invoices linked to this payment foreach ($factures as $id) { $fac = new Facture($db); $fac->fetch($id); $outputlangs = $langs; if (!empty($_REQUEST['lang_id'])) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($_REQUEST['lang_id']); } if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { facture_pdf_create($db, $fac, $fac->modelpdf, $outputlangs, $hookmanager); } } Header('Location: fiche.php?id=' . $paiement->id); exit; } else { $mesg = '<div class="error">' . $paiement->error . '</div>'; $db->rollback(); }
/** * Function to build a compiled PDF * * @param DoliDB $db Database handler * @param Translate $langs Object langs * @param Conf $conf Object conf * @param string $diroutputpdf Dir to output file * @param string $newlangid Lang id * @param array $filter Array with filters * @param date $dateafterdate Invoice after date * @param date $datebeforedate Invoice before date * @param date $paymentdateafter Payment after date (must includes hour) * @param date $paymentdatebefore Payment before date (must includes hour) * @param int $usestdout Add information onto standard output * @param int $regenerate ''=Use existing PDF files, 'nameofpdf'=Regenerate all PDF files using the template * @param string $filesuffix Suffix to add into file name of generated PDF * @param string $paymentbankid Only if payment on this bank account id * @param array $thirdpartiesid List of thirdparties id when using filter excludethirdpartiesid or onlythirdpartiesid * @param string $fileprefix Prefix to add into filename of generated PDF * @return int Error code */ function rebuild_merge_pdf($db, $langs, $conf, $diroutputpdf, $newlangid, $filter, $dateafterdate, $datebeforedate, $paymentdateafter, $paymentdatebefore, $usestdout, $regenerate = 0, $filesuffix = '', $paymentbankid = '', $thirdpartiesid = '', $fileprefix = 'mergedpdf') { $sql = "SELECT DISTINCT f.rowid, f.facnumber"; $sql .= " FROM " . MAIN_DB_PREFIX . "facture as f"; $sqlwhere = ''; $sqlorder = ''; if (in_array('all', $filter)) { $sqlorder = " ORDER BY f.facnumber ASC"; } if (in_array('date', $filter)) { if (empty($sqlwhere)) { $sqlwhere = ' WHERE '; } else { $sqlwhere .= " AND"; } $sqlwhere .= " f.fk_statut > 0"; $sqlwhere .= " AND f.datef >= '" . $db->idate($dateafterdate) . "'"; $sqlwhere .= " AND f.datef <= '" . $db->idate($datebeforedate) . "'"; $sqlorder = " ORDER BY f.datef ASC"; } if (in_array('nopayment', $filter)) { $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "paiement_facture as pf ON f.rowid = pf.fk_facture"; if (empty($sqlwhere)) { $sqlwhere = ' WHERE '; } else { $sqlwhere .= " AND"; } $sqlwhere .= " f.fk_statut > 0"; $sqlwhere .= " AND pf.fk_paiement IS NULL"; } if (in_array('payments', $filter) || in_array('bank', $filter)) { $sql .= ", " . MAIN_DB_PREFIX . "paiement_facture as pf, " . MAIN_DB_PREFIX . "paiement as p"; if (in_array('bank', $filter)) { $sql .= ", " . MAIN_DB_PREFIX . "bank as b"; } if (empty($sqlwhere)) { $sqlwhere = ' WHERE '; } else { $sqlwhere .= " AND"; } $sqlwhere .= " f.fk_statut > 0"; $sqlwhere .= " AND f.rowid = pf.fk_facture"; $sqlwhere .= " AND pf.fk_paiement = p.rowid"; if (in_array('payments', $filter)) { $sqlwhere .= " AND p.datep >= '" . $db->idate($paymentdateafter) . "'"; $sqlwhere .= " AND p.datep <= '" . $db->idate($paymentdatebefore) . "'"; } if (in_array('bank', $filter)) { $sqlwhere .= " AND p.fk_bank = b.rowid"; $sqlwhere .= " AND b.fk_account = " . $paymentbankid; } $sqlorder = " ORDER BY p.datep ASC"; } if (in_array('nodeposit', $filter)) { if (empty($sqlwhere)) { $sqlwhere = ' WHERE '; } else { $sqlwhere .= " AND"; } $sqlwhere .= ' type <> 3'; } if (in_array('noreplacement', $filter)) { if (empty($sqlwhere)) { $sqlwhere = ' WHERE '; } else { $sqlwhere .= " AND"; } $sqlwhere .= ' type <> 1'; } if (in_array('nocreditnote', $filter)) { if (empty($sqlwhere)) { $sqlwhere = ' WHERE '; } else { $sqlwhere .= " AND"; } $sqlwhere .= ' type <> 2'; } if (in_array('excludethirdparties', $filter) && is_array($thirdpartiesid)) { if (empty($sqlwhere)) { $sqlwhere = ' WHERE '; } else { $sqlwhere .= " AND"; } $sqlwhere .= ' f.fk_soc NOT IN (' . join(',', $thirdpartiesid) . ')'; } if (in_array('onlythirdparties', $filter) && is_array($thirdpartiesid)) { if (empty($sqlwhere)) { $sqlwhere = ' WHERE '; } else { $sqlwhere .= " AND"; } $sqlwhere .= ' f.fk_soc IN (' . join(',', $thirdpartiesid) . ')'; } if ($sqlwhere) { $sql .= $sqlwhere; } if ($sqlorder) { $sql .= $sqlorder; } //print $sql; exit; dol_syslog("scripts/invoices/rebuild_merge.php:", LOG_DEBUG); if ($usestdout) { print '--- start' . "\n"; } // Start of transaction //$db->begin(); $error = 0; $result = 0; $files = array(); // liste les fichiers dol_syslog("scripts/invoices/rebuild_merge.php", LOG_DEBUG); if ($resql = $db->query($sql)) { $num = $db->num_rows($resql); $cpt = 0; $oldemail = ''; $message = ''; $total = ''; if ($num) { // First loop on each resultset to build PDF // ----------------------------------------- while ($cpt < $num) { $obj = $db->fetch_object($resql); $fac = new Facture($db); $result = $fac->fetch($obj->rowid); if ($result > 0) { $outputlangs = $langs; if (!empty($newlangid)) { if ($outputlangs->defaultlang != $newlangid) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlangid); } } $filename = $conf->facture->dir_output . '/' . $fac->ref . '/' . $fac->ref . '.pdf'; if ($regenerate || !dol_is_file($filename)) { if ($usestdout) { print "Build PDF for invoice " . $obj->facnumber . " - Lang = " . $outputlangs->defaultlang . "\n"; } $result = $fac->generateDocument($regenerate ? $regenerate : $fac->modelpdf, $outputlangs); } else { if ($usestdout) { print "PDF for invoice " . $obj->facnumber . " already exists\n"; } } // Add file into files array $files[] = $filename; } if ($result <= 0) { $error++; if ($usestdout) { print "Error: Failed to build PDF for invoice " . ($fac->ref ? $fac->ref : ' id ' . $obj->rowid) . "\n"; } else { dol_syslog("Failed to build PDF for invoice " . ($fac->ref ? $fac->ref : ' id ' . $obj->rowid), LOG_ERR); } } $cpt++; } // Define format of output PDF $formatarray = pdf_getFormat($langs); $page_largeur = $formatarray['width']; $page_hauteur = $formatarray['height']; $format = array($page_largeur, $page_hauteur); if ($usestdout) { print "Using output PDF format " . join('x', $format) . "\n"; } else { dol_syslog("Using output PDF format " . join('x', $format), LOG_ERR); } // Now, build a merged files with all files in $files array //--------------------------------------------------------- // Create empty PDF $pdf = pdf_getInstance($format); if (class_exists('TCPDF')) { $pdf->setPrintHeader(false); $pdf->setPrintFooter(false); } $pdf->SetFont(pdf_getPDFFont($langs)); if ($conf->global->MAIN_DISABLE_PDF_COMPRESSION) { $pdf->SetCompression(false); } //$pdf->SetCompression(false); // Add all others foreach ($files as $file) { if ($usestdout) { print "Merge PDF file for invoice " . $file . "\n"; } else { dol_syslog("Merge PDF file for invoice " . $file); } // Charge un document PDF depuis un fichier. $pagecount = $pdf->setSourceFile($file); for ($i = 1; $i <= $pagecount; $i++) { $tplidx = $pdf->importPage($i); $s = $pdf->getTemplatesize($tplidx); $pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L'); $pdf->useTemplate($tplidx); } } // Create output dir if not exists dol_mkdir($diroutputpdf); // Save merged file $filename = $fileprefix; if (empty($filename)) { $filename = 'mergedpdf'; } if (!empty($filesuffix)) { $filename .= '_' . $filesuffix; } $file = $diroutputpdf . '/' . $filename . '.pdf'; if (!$error && $pagecount) { $pdf->Output($file, 'F'); if (!empty($conf->global->MAIN_UMASK)) { @chmod($file, octdec($conf->global->MAIN_UMASK)); } } if ($usestdout) { if (!$error) { print "Merged PDF has been built in " . $file . "\n"; } else { print "Can't build PDF " . $file . "\n"; } } $result = 1; } else { if ($usestdout) { print "No invoices found for criteria.\n"; } else { dol_syslog("No invoices found for criteria"); } $result = 0; } } else { dol_print_error($db); dol_syslog("scripts/invoices/rebuild_merge.php: Error"); $error++; } if ($error) { return -1; } else { return $result; } }
} /* * View */ llxHeader('', $langs->trans("RepeatableInvoices"), 'ch-facture.html#s-fac-facture-rec'); $form = new Form($db); $companystatic = new Societe($db); /* * Create mode */ if ($action == 'create') { print load_fiche_titre($langs->trans("CreateRepeatableInvoice"), '', 'title_accountancy.png'); $object = new Facture($db); // Source invoice $product_static = new Product($db); if ($object->fetch($id) > 0) { print '<form action="fiche-rec.php" method="post">'; print '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">'; print '<input type="hidden" name="action" value="add">'; print '<input type="hidden" name="facid" value="' . $object->id . '">'; dol_fiche_head(); $rowspan = 4; if (!empty($conf->projet->enabled) && $object->fk_project > 0) { $rowspan++; } print '<table class="border" width="100%">'; $object->fetch_thirdparty(); // Third party print '<tr><td>' . $langs->trans("Customer") . '</td><td>' . $object->client->getNomUrl(1, 'customer') . '</td>'; print '<td>'; print $langs->trans("Comment");
/** * Send mail with ticket data * @param $email * @return int <0 if KO; >0 if OK */ public static function sendMail($email) { global $db, $conf, $langs; $function = "sendMail"; require_once DOL_DOCUMENT_ROOT . '/core/class/CMailFile.class.php'; if ($email["idTicket"]) { $ticket = new Ticket($db); $ticket->fetch($email["idTicket"]); $subject = $conf->global->MAIN_INFO_SOCIETE_NOM . ': ' . $langs->trans("CopyOfTicket") . ' ' . $ticket->ticketnumber; $message = self::FillMailTicketBody($ticket->id); } if ($email["idFacture"]) { $facture = new Facture($db); $facture->fetch($email["idFacture"]); $subject = $conf->global->MAIN_INFO_SOCIETE_NOM . ': ' . $langs->trans("CopyOfFacture") . ' ' . $facture->ref; $message = self::FillMailFactureBody($facture->id); } if ($email["idCloseCash"]) { $subject = $conf->global->MAIN_INFO_SOCIETE_NOM . ': ' . $langs->trans("CopyOfCloseCash") . ' ' . $email["idCloseCash"]; $message = self::FillMailCloseCashBody($email["idCloseCash"]); } $from = $conf->global->MAIN_INFO_SOCIETE_NOM . "<" . $conf->global->MAIN_INFO_SOCIETE_MAIL . ">"; $mailfile = new CMailFile($subject, $email["mail_to"], $from, $message); if ($mailfile->error) { $mesg = '<div class="error">' . $mailfile->error . '</div>'; $res = -1; } else { $res = $mailfile->sendfile(); } return ErrorControl($res, $function); }
$cpt = 0; $oldemail = ''; $message = ''; $total = ''; if ($num) { // First loop on each resultset to build PDF // ----------------------------------------- while ($cpt < $num) { $obj = $db->fetch_object($resql); $fac = new Facture($db); $result=$fac->fetch($obj->rowid); if ($result > 0) { $outputlangs = $langs; if (! empty($newlangid)) { if ($outputlangs->defaultlang != $newlangid) { $outputlangs = new Translate("",$conf); $outputlangs->setDefaultLang($newlangid); } } print "Build PDF for invoice ".$obj->facnumber." - Lang = ".$outputlangs->defaultlang."\n"; $result=facture_pdf_create($db, $fac, '', $newmodel?$newmodel:$fac->modelpdf, $outputlangs); // Add file into files array
print '</tr>'; if (! $num > 0) { print '<tr><td colspan="7">'.$langs->trans("NoInvoice").'</td></tr>'; } $solde = 0; // Boucle sur chaque facture for ($i = 0 ; $i < $num ; $i++) { $objf = $db->fetch_object($resql); $fac = new Facture($db); $ret=$fac->fetch($objf->facid); if ($ret < 0) { print $fac->error."<br>"; continue; } $totalpaye = $fac->getSommePaiement(); $var=!$var; print "<tr $bc[$var]>"; print "<td align=\"center\">".dol_print_date($fac->date)."</td>\n"; print "<td><a href=\"../compta/facture.php?facid=$fac->id\">".img_object($langs->trans("ShowBill"),"bill")." ".$fac->ref."</a></td>\n"; print '<td aling="left">'.$fac->getLibStatut(2,$totalpaye).'</td>'; print '<td align="right">'.price($fac->total_ttc)."</td>\n";
/** * Create * * @param User $user User object * @param int $id Id * @param string $motif Motif * @param int $date_rejet Date rejet * @param int $bonid Bon id * @param int $facturation Facturation * @return void */ function create($user, $id, $motif, $date_rejet, $bonid, $facturation = 0) { global $langs, $conf; $error = 0; $this->id = $id; $this->bon_id = $bonid; $now = dol_now(); dol_syslog("RejetPrelevement::Create id {$id}"); $bankaccount = $conf->global->PRELEVEMENT_ID_BANKACCOUNT; $facs = $this->getListInvoices(1); $this->db->begin(); // Insert refused line into database $sql = "INSERT INTO " . MAIN_DB_PREFIX . "prelevement_rejet ("; $sql .= "fk_prelevement_lignes"; $sql .= ", date_rejet"; $sql .= ", motif"; $sql .= ", fk_user_creation"; $sql .= ", date_creation"; $sql .= ", afacturer"; $sql .= ") VALUES ("; $sql .= $id; $sql .= ", '" . $this->db->idate($date_rejet) . "'"; $sql .= ", " . $motif; $sql .= ", " . $user->id; $sql .= ", '" . $this->db->idate($now) . "'"; $sql .= ", " . $facturation; $sql .= ")"; $result = $this->db->query($sql); if (!$result) { dol_syslog("RejetPrelevement::create Erreur 4"); dol_syslog("RejetPrelevement::create Erreur 4 {$sql}"); $error++; } // Tag the line to refused $sql = " UPDATE " . MAIN_DB_PREFIX . "prelevement_lignes "; $sql .= " SET statut = 3"; $sql .= " WHERE rowid = " . $id; if (!$this->db->query($sql)) { dol_syslog("RejetPrelevement::create Erreur 5"); $error++; } $num = count($facs); for ($i = 0; $i < $num; $i++) { $fac = new Facture($this->db); $fac->fetch($facs[$i][0]); // Make a negative payment $pai = new Paiement($this->db); $pai->amounts = array(); /* * We replace the comma with a point otherwise some * PHP installs sends only the part integer negative */ $pai->amounts[$facs[$i][0]] = price2num($facs[$i][1] * -1); $pai->datepaye = $date_rejet; $pai->paiementid = 3; // type of payment: withdrawal $pai->num_paiement = $fac->ref; if ($pai->create($this->user) < 0) { $error++; dol_syslog("RejetPrelevement::Create Error creation payment invoice " . $facs[$i][0]); } else { $result = $pai->addPaymentToBank($user, 'payment', '(InvoiceRefused)', $bankaccount, '', ''); if ($result < 0) { dol_syslog("RejetPrelevement::Create AddPaymentToBan Error"); $error++; } // Payment validation if ($pai->valide() < 0) { $error++; dol_syslog("RejetPrelevement::Create Error payment validation"); } } //Tag invoice as unpaid dol_syslog("RejetPrelevement::Create set_unpaid fac " . $fac->ref); $fac->set_unpaid($user); //TODO: Must be managed by notifications module // Send email to sender of the standing order request $this->_send_email($fac); } if ($error == 0) { dol_syslog("RejetPrelevement::Create Commit"); $this->db->commit(); } else { dol_syslog("RejetPrelevement::Create Rollback"); $this->db->rollback(); } }
/** * Create a predefined invoice * * @param User $user User object * @param int $facid Id of source invoice * @return int <0 if KO, id of invoice if OK */ function create($user, $facid) { global $conf, $langs; $error = 0; $now = dol_now(); // Clean parameters $this->titre = trim($this->titre); // Validate parameters if (empty($this->titre)) { $this->error = $langs->trans("ErrorFieldRequired", $langs->trans("Title")); return -3; } $this->db->begin(); // Charge facture modele $facsrc = new Facture($this->db); $result = $facsrc->fetch($facid); if ($result > 0) { // On positionne en mode brouillon la facture $this->brouillon = 1; $sql = "INSERT INTO " . MAIN_DB_PREFIX . "facture_rec ("; $sql .= "titre"; $sql .= ", fk_soc"; $sql .= ", entity"; $sql .= ", datec"; $sql .= ", amount"; $sql .= ", remise"; $sql .= ", note"; $sql .= ", fk_user_author"; $sql .= ", fk_projet"; $sql .= ", fk_cond_reglement"; $sql .= ", fk_mode_reglement"; $sql .= ") VALUES ("; $sql .= "'" . $this->titre . "'"; $sql .= ", '" . $facsrc->socid . "'"; $sql .= ", " . $conf->entity; $sql .= ", " . $this->db->idate($now); $sql .= ", '" . $facsrc->amount . "'"; $sql .= ", '" . $facsrc->remise . "'"; $sql .= ", '" . $this->db->escape($this->note) . "'"; $sql .= ", '" . $user->id . "'"; $sql .= ", " . ($facsrc->fk_project ? "'" . $facsrc->fk_project . "'" : "null"); $sql .= ", '" . $facsrc->cond_reglement_id . "'"; $sql .= ", '" . $facsrc->mode_reglement_id . "'"; $sql .= ")"; if ($this->db->query($sql)) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . "facture_rec"); /* * Lines */ $num = count($facsrc->lines); for ($i = 0; $i < $num; $i++) { $result_insert = $this->addline($this->id, $facsrc->lines[$i]->desc, $facsrc->lines[$i]->subprice, $facsrc->lines[$i]->qty, $facsrc->lines[$i]->tva_tx, $facsrc->lines[$i]->fk_product, $facsrc->lines[$i]->remise_percent, 'HT', 0, '', 0, $facsrc->lines[$i]->product_type, $facsrc->lines[$i]->rang, $facsrc->lines[$i]->special_code); if ($result_insert < 0) { $error++; } } if ($error) { $this->db->rollback(); } else { $this->db->commit(); return $this->id; } } else { $this->error = $this->db->error() . ' sql=' . $sql; $this->db->rollback(); return -2; } } else { $this->db->rollback(); return -1; } }
); if ($result > 0) { Header("Location: ".DOL_URL_ROOT."/commande/fiche.php?id=".$commande->id); exit; } } /* * Ajout du produit dans une facture */ if ($action == 'addinfacture' && $user->rights->facture->creer) { $facture = New Facture($db); $result=$facture->fetch($_POST["factureid"]); if ($result <= 0) { dol_print_error($db,$facture->error); exit; } $soc = new Societe($db); $soc->fetch($facture->socid); if ($result <= 0) { dol_print_error($db,$soc->error); exit; } $prod = new Product($db);
/** * Returns an array containing the previous situations as Facture objects * * @return mixed -1 if error, array of previous situations */ function get_prev_sits() { $sql = 'SELECT rowid FROM ' . MAIN_DB_PREFIX . 'facture'; $sql .= ' where situation_cycle_ref = ' . $this->situation_cycle_ref; $sql .= ' and situation_counter < ' . $this->situation_counter; $resql = $this->db->query($sql); $res = array(); if ($resql && $resql->num_rows > 0) { while ($row = $this->db->fetch_object($resql)) { $id = $row->rowid; $situation = new Facture($this->db); $situation->fetch($id); $res[] = $situation; } } else { $this->error = $this->db->error(); dol_syslog("Error sql=" . $sql . ", error=" . $this->error, LOG_ERR); return -1; } return $res; }
if (!empty($object->fk_place)) { $place = new Place($db); $place->fetch($object->fk_place); print $langs->trans("Place") . ': ' . $place->name . "</p>"; } ?> </div> </div> <div><?php // Recuperation et affichage de la date et de l'heure $now = dol_now(); $label = $object->ref; $facture = new Facture($db); if ($object->fk_facture) { $facture->fetch($object->fk_facture); $label = $facture->ref; } print '<p class="date_heure" align="right">' . $label . " " . dol_print_date($object->date_closed, 'dayhour') . '</p>'; ?> </div> <?php if ($result) { if (!empty($object->lines)) { $onediscount = false; foreach ($object->lines as $line) { if ($line->remise_percent) { $onediscount = true; } }
print '<input type="hidden" name="shipToZip" value="' . $shipToZip . '">' . "\n"; print '<input type="hidden" name="shipToStreet2" value="' . $shipToStreet2 . '">' . "\n"; print '<input type="hidden" name="phoneNum" value="' . $phoneNum . '">' . "\n"; } else { print '<!-- Shipping address not complete, so we don t use it -->' . "\n"; } print '<input type="hidden" name="email" value="' . $order->thirdparty->email . '">' . "\n"; print '<input type="hidden" name="desc" value="' . $langs->trans("Order") . ' ' . $order->ref . '">' . "\n"; } // Payment on customer invoice if (GETPOST("source") == 'invoice' && $valid) { $found = true; $langs->load("bills"); require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php'; $invoice = new Facture($db); $result = $invoice->fetch('', $ref); if ($result < 0) { $mesg = $invoice->error; $error++; } else { $result = $invoice->fetch_thirdparty($invoice->socid); } $amount = price2num($invoice->total_ttc - $invoice->getSommePaiement()); if (GETPOST("amount", 'int')) { $amount = GETPOST("amount", 'int'); } $amount = price2num($amount); $fulltag = 'INV=' . $invoice->ref . '.CUS=' . $invoice->thirdparty->id; //$fulltag.='.NAM='.strtr($invoice->thirdparty->name,"-"," "); if (!empty($TAG)) { $tag = $TAG;
/** * Create a withdraw * TODO delete params banque and agence when not necesary * * @param int $banque dolibarr mysoc bank * @param int $agence dolibarr mysoc bank office (guichet) * @param string $mode real=do action, simu=test only * @return int <0 if KO, nbre of invoice withdrawed if OK */ function Create($banque = 0, $agence = 0, $mode = 'real') { global $conf, $langs; dol_syslog(get_class($this) . "::Create banque={$banque} agence={$agence}"); require_once DOL_DOCUMENT_ROOT . "/compta/facture/class/facture.class.php"; require_once DOL_DOCUMENT_ROOT . "/societe/class/societe.class.php"; $error = 0; $datetimeprev = time(); $month = strftime("%m", $datetimeprev); $year = strftime("%Y", $datetimeprev); $puser = new User($this->db, $conf->global->PRELEVEMENT_USER); /* * Read invoices */ $factures = array(); $factures_prev = array(); $factures_result = array(); if (!$error) { $sql = "SELECT f.rowid, pfd.rowid as pfdrowid, f.fk_soc"; $sql .= ", pfd.code_banque, pfd.code_guichet, pfd.number, pfd.cle_rib"; $sql .= ", pfd.amount"; $sql .= ", s.nom"; $sql .= " FROM " . MAIN_DB_PREFIX . "facture as f"; $sql .= ", " . MAIN_DB_PREFIX . "societe as s"; $sql .= ", " . MAIN_DB_PREFIX . "prelevement_facture_demande as pfd"; //if ($banque || $agence) $sql.= ", ".MAIN_DB_PREFIX."societe_rib as sr"; $sql .= " WHERE f.rowid = pfd.fk_facture"; $sql .= " AND f.entity = " . $conf->entity; $sql .= " AND s.rowid = f.fk_soc"; //if ($banque || $agence) $sql.= " AND s.rowid = sr.fk_soc"; $sql .= " AND f.fk_statut = 1"; $sql .= " AND f.paye = 0"; $sql .= " AND pfd.traite = 0"; $sql .= " AND f.total_ttc > 0"; //if ($banque) $sql.= " AND sr.code_banque = '".$conf->global->PRELEVEMENT_CODE_BANQUE."'"; //if ($agence) $sql.= " AND sr.code_guichet = '".$conf->global->PRELEVEMENT_CODE_GUICHET."'"; dol_syslog(get_class($this) . "::Create sql=" . $sql, LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { $num = $this->db->num_rows($resql); $i = 0; while ($i < $num) { $row = $this->db->fetch_row($resql); $factures[$i] = $row; // All fields $i++; } $this->db->free($resql); dol_syslog($i . " invoices to withdraw"); } else { $error = 1; dol_syslog("Erreur -1"); dol_syslog($this->db->error()); } } if (!$error) { require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php'; $soc = new Societe($this->db); // Check RIB $i = 0; dol_syslog("Start RIB check"); if (count($factures) > 0) { foreach ($factures as $key => $fac) { $fact = new Facture($this->db); if ($fact->fetch($fac[0]) >= 0) { if ($soc->fetch($fact->socid) >= 0) { $bac = new CompanyBankAccount($this->db); $bac->fetch(0, $soc->id); if ($bac->verif() >= 1) { $factures_prev[$i] = $fac; /* second tableau necessaire pour BonPrelevement */ $factures_prev_id[$i] = $fac[0]; $i++; } else { dol_syslog("Error on default bank number RIB/IBAN for thirdparty reported by verif() " . $fact->socid . " " . $soc->nom, LOG_ERR); $facture_errors[$fac[0]] = "Error on default bank number RIB/IBAN for thirdparty reported by function verif() " . $fact->socid . " " . $soc->nom; } } else { dol_syslog("Failed to read company", LOG_ERR); } } else { dol_syslog("Failed to read invoice", LOG_ERR); } } } else { dol_syslog("No invoice to process"); } } $ok = 0; // Withdraw invoices in factures_prev array $out = count($factures_prev) . " invoices will be withdrawn."; //print $out."\n"; dol_syslog($out); if (count($factures_prev) > 0) { if ($mode == 'real') { $ok = 1; } else { print $langs->trans("ModeWarning"); //"Option for real mode was not set, we stop after this simulation\n"; } } if ($ok) { /* * We are in real mode. * We create withdraw receipt and build withdraw into disk */ $this->db->begin(); $now = dol_now(); /* * Traitements */ if (!$error) { $ref = "T" . substr($year, -2) . $month; $sql = "SELECT count(*)"; $sql .= " FROM " . MAIN_DB_PREFIX . "prelevement_bons"; $sql .= " WHERE ref LIKE '" . $ref . "%'"; $sql .= " AND entity = " . $conf->entity; dol_syslog(get_class($this) . "::Create sql=" . $sql, LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { $row = $this->db->fetch_row($resql); } else { $error++; dol_syslog("Erreur recherche reference"); } $ref = $ref . substr("00" . ($row[0] + 1), -2); $filebonprev = $ref; // Create withdraw receipt in database $sql = "INSERT INTO " . MAIN_DB_PREFIX . "prelevement_bons ("; $sql .= " ref, entity, datec"; $sql .= ") VALUES ("; $sql .= "'" . $this->db->escape($ref) . "'"; $sql .= ", " . $conf->entity; $sql .= ", '" . $this->db->idate($now) . "'"; $sql .= ")"; dol_syslog(get_class($this) . "::Create sql=" . $sql, LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { $prev_id = $this->db->last_insert_id(MAIN_DB_PREFIX . "prelevement_bons"); $dir = $conf->prelevement->dir_output . '/receipts'; $file = $filebonprev; if (!is_dir($dir)) { dol_mkdir($dir); } $bonprev = new BonPrelevement($this->db, $dir . "/" . $file); $bonprev->id = $prev_id; } else { $error++; dol_syslog("Erreur creation du bon de prelevement"); } } /* * Create withdrawal receipt */ if (!$error) { if (count($factures_prev) > 0) { foreach ($factures_prev as $fac) { // Fetch invoice $fact = new Facture($this->db); $fact->fetch($fac[0]); /* * Add standing order * * * $fac[3] : banque * $fac[4] : guichet * $fac[5] : number * $fac[6] : cle rib * $fac[7] : amount * $fac[8] : client nom * $fac[2] : client id */ $ri = $bonprev->AddFacture($fac[0], $fac[2], $fac[8], $fac[7], $fac[3], $fac[4], $fac[5], $fac[6]); if ($ri != 0) { $error++; } /* * Update orders * */ $sql = "UPDATE " . MAIN_DB_PREFIX . "prelevement_facture_demande"; $sql .= " SET traite = 1"; $sql .= ", date_traite = '" . $this->db->idate($now) . "'"; $sql .= ", fk_prelevement_bons = " . $prev_id; $sql .= " WHERE rowid = " . $fac[1]; dol_syslog(get_class($this) . "::Create sql=" . $sql, LOG_DEBUG); $resql = $this->db->query($sql); if (!$resql) { $error++; dol_syslog("Erreur mise a jour des demandes"); dol_syslog($this->db->error()); } } } } if (!$error) { /* * Withdraw receipt */ dol_syslog("Debut prelevement - Nombre de factures " . count($factures_prev)); if (count($factures_prev) > 0) { $bonprev->date_echeance = $datetimeprev; $bonprev->reference_remise = $ref; $bonprev->numero_national_emetteur = $conf->global->PRELEVEMENT_NUMERO_NATIONAL_EMETTEUR; $bonprev->raison_sociale = $conf->global->PRELEVEMENT_RAISON_SOCIALE; $bonprev->emetteur_code_banque = $conf->global->PRELEVEMENT_CODE_BANQUE; $bonprev->emetteur_code_guichet = $conf->global->PRELEVEMENT_CODE_GUICHET; $bonprev->emetteur_numero_compte = $conf->global->PRELEVEMENT_NUMERO_COMPTE; $bonprev->emetteur_number_key = $conf->global->PRELEVEMENT_NUMBER_KEY; $bonprev->emetteur_iban = $conf->global->PRELEVEMENT_IBAN; $bonprev->emetteur_bic = $conf->global->PRELEVEMENT_BIC; $bonprev->emetteur_ics = $conf->global->PRELEVEMENT_ICS; // TODO Add this into setup of admin/prelevement.php. Ex: PRELEVEMENT_ICS = "FR78ZZZ123456"; $bonprev->factures = $factures_prev_id; //Build file $bonprev->generate(); } dol_syslog($filebonprev); dol_syslog("Fin prelevement"); } /* * Update total */ $sql = "UPDATE " . MAIN_DB_PREFIX . "prelevement_bons"; $sql .= " SET amount = " . price2num($bonprev->total); $sql .= " WHERE rowid = " . $prev_id; $sql .= " AND entity = " . $conf->entity; dol_syslog(get_class($this) . "::Create sql=" . $sql, LOG_DEBUG); $resql = $this->db->query($sql); if (!$resql) { $error++; dol_syslog("Erreur mise a jour du total - {$sql}"); } /* * Rollback or Commit */ if (!$error) { $this->db->commit(); } else { $this->db->rollback(); dol_syslog("Error", LOG_ERR); } return count($factures_prev); } else { return 0; } }
$resteapayeraffiche = $resteapayer; // Loop on each credit note or deposit amount applied $creditnoteamount = 0; $depositamount = 0; $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,"; $sql .= " re.description, re.fk_facture_source"; $sql .= " FROM " . MAIN_DB_PREFIX . "societe_remise_except as re"; $sql .= " WHERE fk_facture = " . $object->id; $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); $i = 0; $invoice = new Facture($db); while ($i < $num) { $obj = $db->fetch_object($resql); $invoice->fetch($obj->fk_facture_source); print '<tr><td colspan="' . $nbcols . '" align="right">'; if ($invoice->type == Facture::TYPE_CREDIT_NOTE) { print $langs->trans("CreditNote") . ' '; } if ($invoice->type == Facture::TYPE_DEPOSIT) { print $langs->trans("Deposit") . ' '; } print $invoice->getNomUrl(0); print ' :</td>'; print '<td align="right">' . price($obj->amount_ttc) . '</td>'; print '<td align="right">'; print '<a href="' . $_SERVER["PHP_SELF"] . '?facid=' . $object->id . '&action=unlinkdiscount&discountid=' . $obj->rowid . '">' . img_delete() . '</a>'; print '</td></tr>'; $i++; if ($invoice->type == Facture::TYPE_CREDIT_NOTE) {
/** * Function to build a document on disk using the generic odt module. * * @param Facture $object Object source to build document * @param Translate $outputlangs Lang output object * @param string $srctemplatepath Full path of source filename for generator using a template file * @param int $hidedetails Do not show line details * @param int $hidedesc Do not show desc * @param int $hideref Do not show ref * @return int 1 if OK, <=0 if KO */ function write_file($object, $outputlangs, $srctemplatepath, $hidedetails = 0, $hidedesc = 0, $hideref = 0) { global $user, $langs, $conf, $mysoc, $hookmanager; if (empty($srctemplatepath)) { dol_syslog("doc_generic_odt::write_file parameter srctemplatepath empty", LOG_WARNING); return -1; } // Add odtgeneration hook if (!is_object($hookmanager)) { include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php'; $hookmanager = new HookManager($this->db); } $hookmanager->initHooks(array('odtgeneration')); global $action; if (!is_object($outputlangs)) { $outputlangs = $langs; } $sav_charset_output = $outputlangs->charset_output; $outputlangs->charset_output = 'UTF-8'; $outputlangs->load("main"); $outputlangs->load("dict"); $outputlangs->load("companies"); $outputlangs->load("bills"); if ($conf->facture->dir_output) { // If $object is id instead of object if (!is_object($object)) { $id = $object; $object = new Facture($this->db); $result = $object->fetch($id); if ($result < 0) { dol_print_error($this->db, $object->error); return -1; } } $dir = $conf->facture->dir_output; $objectref = dol_sanitizeFileName($object->ref); if (!preg_match('/specimen/i', $objectref)) { $dir .= "/" . $objectref; } $file = $dir . "/" . $objectref . ".odt"; if (!file_exists($dir)) { if (dol_mkdir($dir) < 0) { $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); return -1; } } if (file_exists($dir)) { //print "srctemplatepath=".$srctemplatepath; // Src filename $newfile = basename($srctemplatepath); $newfiletmp = preg_replace('/\\.od(t|s)/i', '', $newfile); $newfiletmp = preg_replace('/template_/i', '', $newfiletmp); $newfiletmp = preg_replace('/modele_/i', '', $newfiletmp); $newfiletmp = $objectref . '_' . $newfiletmp; // Get extension (ods or odt) $newfileformat = substr($newfile, strrpos($newfile, '.') + 1); if (!empty($conf->global->MAIN_DOC_USE_TIMING)) { $filename = $newfiletmp . '.' . dol_print_date(dol_now(), '%Y%m%d%H%M%S') . '.' . $newfileformat; } else { $filename = $newfiletmp . '.' . $newfileformat; } $file = $dir . '/' . $filename; //$file=$dir.'/'.$newfiletmp.'.'.dol_print_date(dol_now(),'%Y%m%d%H%M%S').'.odt'; //print "newdir=".$dir; //print "newfile=".$newfile; //print "file=".$file; //print "conf->societe->dir_temp=".$conf->societe->dir_temp; dol_mkdir($conf->facture->dir_temp); // If BILLING contact defined on invoice, we use it $usecontact = false; $arrayidcontact = $object->getIdContact('external', 'BILLING'); if (count($arrayidcontact) > 0) { $usecontact = true; $result = $object->fetch_contact($arrayidcontact[0]); } // Recipient name if (!empty($usecontact)) { // On peut utiliser le nom de la societe du contact if (!empty($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT)) { $socobject = $object->contact; } else { $socobject = $object->client; // if we have a BILLING contact and we dont use it as recipient we store the contact object for later use $contactobject = $object->contact; } } else { $socobject = $object->client; } // Fetch info for linked propal $object->fetchObjectLinked('', '', '', ''); //print_r($object->linkedObjects['propal']); exit; $propal_object = $object->linkedObjects['propal'][0]; // Make substitution $substitutionarray = array('__FROM_NAME__' => $this->emetteur->name, '__FROM_EMAIL__' => $this->emetteur->email, '__TOTAL_TTC__' => $object->total_ttc, '__TOTAL_HT__' => $object->total_ht, '__TOTAL_VAT__' => $object->total_tva); complete_substitutions_array($substitutionarray, $langs, $object); // Call the ODTSubstitution hook $parameters = array('file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$substitutionarray); $reshook = $hookmanager->executeHooks('ODTSubstitution', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks // Line of free text $newfreetext = ''; $paramfreetext = 'INVOICE_FREE_TEXT'; if (!empty($conf->global->{$paramfreetext})) { $newfreetext = make_substitutions($conf->global->{$paramfreetext}, $substitutionarray); } // Open and load template require_once ODTPHP_PATH . 'odf.php'; try { $odfHandler = new odf($srctemplatepath, array('PATH_TO_TMP' => $conf->facture->dir_temp, 'ZIP_PROXY' => 'PclZipProxy', 'DELIMITER_LEFT' => '{', 'DELIMITER_RIGHT' => '}')); } catch (Exception $e) { $this->error = $e->getMessage(); return -1; } // After construction $odfHandler->contentXml contains content and // [!-- BEGIN row.lines --]*[!-- END row.lines --] has been replaced by // [!-- BEGIN lines --]*[!-- END lines --] //print html_entity_decode($odfHandler->__toString()); //print exit; // Make substitutions into odt of freetext try { $odfHandler->setVars('free_text', $newfreetext, true, 'UTF-8'); } catch (OdfException $e) { } // Make substitutions into odt $array_user = $this->get_substitutionarray_user($user, $outputlangs); $array_soc = $this->get_substitutionarray_mysoc($mysoc, $outputlangs); $array_thirdparty = $this->get_substitutionarray_thirdparty($socobject, $outputlangs); $array_objet = $this->get_substitutionarray_object($object, $outputlangs); $array_propal = is_object($propal_object) ? $this->get_substitutionarray_object($propal_object, $outputlangs, 'propal') : array(); $array_other = $this->get_substitutionarray_other($outputlangs); // retrieve contact information for use in invoice as contact_xxx tags $array_thirdparty_contact = array(); if ($usecontact) { $array_thirdparty_contact = $this->get_substitutionarray_contact($contactobject, $outputlangs, 'contact'); } $tmparray = array_merge($array_user, $array_soc, $array_thirdparty, $array_objet, $array_propal, $array_other, $array_thirdparty_contact); complete_substitutions_array($tmparray, $outputlangs, $object); // Call the ODTSubstitution hook $parameters = array('file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray); $reshook = $hookmanager->executeHooks('ODTSubstitution', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks //var_dump($tmparray); exit; foreach ($tmparray as $key => $value) { try { if (preg_match('/logo$/', $key)) { //var_dump($value);exit; if (file_exists($value)) { $odfHandler->setImage($key, $value); } else { $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8'); } } else { $odfHandler->setVars($key, $value, true, 'UTF-8'); } } catch (OdfException $e) { } } // Replace tags of lines try { $listlines = $odfHandler->setSegment('lines'); foreach ($object->lines as $line) { $tmparray = $this->get_substitutionarray_lines($line, $outputlangs); complete_substitutions_array($tmparray, $outputlangs, $object, $line, "completesubstitutionarray_lines"); // Call the ODTSubstitutionLine hook $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray, 'line' => $line); $reshook = $hookmanager->executeHooks('ODTSubstitutionLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks foreach ($tmparray as $key => $val) { try { $listlines->setVars($key, $val, true, 'UTF-8'); } catch (OdfException $e) { } catch (SegmentException $e) { } } $listlines->merge(); } $odfHandler->mergeSegment($listlines); } catch (OdfException $e) { $this->error = $e->getMessage(); dol_syslog($this->error, LOG_WARNING); return -1; } // Replace labels translated $tmparray = $outputlangs->get_translations_for_substitutions(); foreach ($tmparray as $key => $value) { try { $odfHandler->setVars($key, $value, true, 'UTF-8'); } catch (OdfException $e) { } } // Call the beforeODTSave hook $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs); $reshook = $hookmanager->executeHooks('beforeODTSave', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks // Write new file if (!empty($conf->global->MAIN_ODT_AS_PDF)) { try { $odfHandler->exportAsAttachedPDF($file); } catch (Exception $e) { $this->error = $e->getMessage(); return -1; } } else { try { $odfHandler->saveToDisk($file); } catch (Exception $e) { $this->error = $e->getMessage(); return -1; } } $reshook = $hookmanager->executeHooks('afterODTCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks if (!empty($conf->global->MAIN_UMASK)) { @chmod($file, octdec($conf->global->MAIN_UMASK)); } $odfHandler = null; // Destroy object return 1; // Success } else { $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); return -1; } } return -1; }
/** * Show top header of page. * * @param PDF $pdf Object PDF * @param Object $object Object to show * @param int $showaddress 0=no, 1=yes * @param Translate $outputlangs Object lang for output * @return void */ function _pagehead(&$pdf, $object, $showaddress, $outputlangs) { global $conf, $langs; $outputlangs->load("main"); $outputlangs->load("bills"); $outputlangs->load("propal"); $outputlangs->load("companies"); $default_font_size = pdf_getPDFFontSize($outputlangs); pdf_pagehead($pdf, $outputlangs, $this->page_hauteur); // Show Draft Watermark if ($object->statut == 0 && !empty($conf->global->FACTURE_DRAFT_WATERMARK)) { pdf_watermark($pdf, $outputlangs, $this->page_hauteur, $this->page_largeur, 'mm', $conf->global->FACTURE_DRAFT_WATERMARK); } $pdf->SetTextColor(0, 0, 60); $pdf->SetFont('', 'B', $default_font_size + 3); $w = 110; $posy = $this->marge_haute; $posx = $this->page_largeur - $this->marge_droite - $w; $pdf->SetXY($this->marge_gauche, $posy); // Logo $logo = $conf->mycompany->dir_output . '/logos/' . $this->emetteur->logo; if ($this->emetteur->logo) { if (is_readable($logo)) { $height = pdf_getHeightForLogo($logo); $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto) } else { $pdf->SetTextColor(200, 0, 0); $pdf->SetFont('', 'B', $default_font_size - 2); $pdf->MultiCell($w, 3, $outputlangs->transnoentities("ErrorLogoFileNotFound", $logo), 0, 'L'); $pdf->MultiCell($w, 3, $outputlangs->transnoentities("ErrorGoToGlobalSetup"), 0, 'L'); } } else { $text = $this->emetteur->name; $pdf->MultiCell($w, 4, $outputlangs->convToOutputCharset($text), 0, 'L'); } $pdf->SetFont('', 'B', $default_font_size + 3); $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); $title = $outputlangs->transnoentities("Invoice"); if ($object->type == 1) { $title = $outputlangs->transnoentities("InvoiceReplacement"); } if ($object->type == 2) { $title = $outputlangs->transnoentities("InvoiceAvoir"); } if ($object->type == 3) { $title = $outputlangs->transnoentities("InvoiceDeposit"); } if ($object->type == 4) { $title = $outputlangs->transnoentities("InvoiceProFormat"); } $pdf->MultiCell($w, 3, $title, '', 'R'); $pdf->SetFont('', 'B', $default_font_size); $posy += 5; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); $pdf->MultiCell($w, 4, $outputlangs->transnoentities("Ref") . " : " . $outputlangs->convToOutputCharset($object->ref), '', 'R'); $posy += 1; $pdf->SetFont('', '', $default_font_size - 2); if ($object->ref_client) { $posy += 4; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); $pdf->MultiCell($w, 3, $outputlangs->transnoentities("RefCustomer") . " : " . $outputlangs->convToOutputCharset($object->ref_client), '', 'R'); } $objectidnext = $object->getIdReplacingInvoice('validated'); if ($object->type == 0 && $objectidnext) { $objectreplacing = new Facture($this->db); $objectreplacing->fetch($objectidnext); $posy += 3; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); $pdf->MultiCell($w, 3, $outputlangs->transnoentities("ReplacementByInvoice") . ' : ' . $outputlangs->convToOutputCharset($objectreplacing->ref), '', 'R'); } if ($object->type == 1) { $objectreplaced = new Facture($this->db); $objectreplaced->fetch($object->fk_facture_source); $posy += 4; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); $pdf->MultiCell($w, 3, $outputlangs->transnoentities("ReplacementInvoice") . ' : ' . $outputlangs->convToOutputCharset($objectreplaced->ref), '', 'R'); } if ($object->type == 2 && !empty($object->fk_facture_source)) { $objectreplaced = new Facture($this->db); $objectreplaced->fetch($object->fk_facture_source); $posy += 3; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); $pdf->MultiCell($w, 3, $outputlangs->transnoentities("CorrectionInvoice") . ' : ' . $outputlangs->convToOutputCharset($objectreplaced->ref), '', 'R'); } $posy += 4; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); $pdf->MultiCell($w, 3, $outputlangs->transnoentities("DateInvoice") . " : " . dol_print_date($object->date, "day", false, $outputlangs), '', 'R'); if ($object->type != 2) { $posy += 3; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); $pdf->MultiCell($w, 3, $outputlangs->transnoentities("DateEcheance") . " : " . dol_print_date($object->date_lim_reglement, "day", false, $outputlangs, true), '', 'R'); } if ($object->thirdparty->code_client) { $posy += 3; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); $pdf->MultiCell($w, 3, $outputlangs->transnoentities("CustomerCode") . " : " . $outputlangs->transnoentities($object->thirdparty->code_client), '', 'R'); } $posy += 1; // Show list of linked objects $posy = pdf_writeLinkedObjects($pdf, $object, $outputlangs, $posx, $posy, $w, 3, 'R', $default_font_size); if ($showaddress) { // Sender properties $carac_emetteur = pdf_build_address($outputlangs, $this->emetteur, $object->client); // Show sender $posy = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 40 : 42; $posx = $this->marge_gauche; if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) { $posx = $this->page_largeur - $this->marge_droite - 80; } $hautcadre = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 38 : 40; $widthrecbox = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 92 : 82; // Show sender frame $pdf->SetTextColor(0, 0, 0); $pdf->SetFont('', '', $default_font_size - 2); $pdf->SetXY($posx, $posy - 5); $pdf->MultiCell(66, 5, $outputlangs->transnoentities("BillFrom") . ":", 0, 'L'); $pdf->SetXY($posx, $posy); $pdf->SetFillColor(230, 230, 230); $pdf->MultiCell($widthrecbox, $hautcadre, "", 0, 'R', 1); $pdf->SetTextColor(0, 0, 60); // Show sender name $pdf->SetXY($posx + 2, $posy + 3); $pdf->SetFont('', 'B', $default_font_size); $pdf->MultiCell($widthrecbox - 2, 4, $outputlangs->convToOutputCharset($this->emetteur->name), 0, 'L'); $posy = $pdf->getY(); // Show sender information $pdf->SetXY($posx + 2, $posy); $pdf->SetFont('', '', $default_font_size - 1); $pdf->MultiCell($widthrecbox - 2, 4, $carac_emetteur, 0, 'L'); // If BILLING contact defined on invoice, we use it $usecontact = false; $arrayidcontact = $object->getIdContact('external', 'BILLING'); if (count($arrayidcontact) > 0) { $usecontact = true; $result = $object->fetch_contact($arrayidcontact[0]); } //Recipient name // On peut utiliser le nom de la societe du contact if ($usecontact && !empty($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT)) { $thirdparty = $object->contact; } else { $thirdparty = $object->client; } $carac_client_name = pdfBuildThirdpartyName($thirdparty, $outputlangs); $carac_client = pdf_build_address($outputlangs, $this->emetteur, $object->client, $usecontact ? $object->contact : '', $usecontact, 'target'); // Show recipient $widthrecbox = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 92 : 100; if ($this->page_largeur < 210) { $widthrecbox = 84; } // To work with US executive format $posy = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 40 : 42; $posx = $this->page_largeur - $this->marge_droite - $widthrecbox; if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) { $posx = $this->marge_gauche; } // Show recipient frame $pdf->SetTextColor(0, 0, 0); $pdf->SetFont('', '', $default_font_size - 2); $pdf->SetXY($posx + 2, $posy - 5); $pdf->MultiCell($widthrecbox, 5, $outputlangs->transnoentities("BillTo") . ":", 0, 'L'); $pdf->Rect($posx, $posy, $widthrecbox, $hautcadre); // Show recipient name $pdf->SetXY($posx + 2, $posy + 3); $pdf->SetFont('', 'B', $default_font_size); $pdf->MultiCell($widthrecbox, 2, $carac_client_name, 0, 'L'); $posy = $pdf->getY(); // Show recipient information $pdf->SetFont('', '', $default_font_size - 1); $pdf->SetXY($posx + 2, $posy); $pdf->MultiCell($widthrecbox, 4, $carac_client, 0, 'L'); } $pdf->SetTextColor(0, 0, 0); }
if ($result <= 0) { dol_print_error($db, $propal->error); exit; } $thirpdartyid = $propal->socid; } elseif (GETPOST('commandeid') > 0) { $commande = new Commande($db); $result = $commande->fetch(GETPOST('commandeid')); if ($result <= 0) { dol_print_error($db, $commande->error); exit; } $thirpdartyid = $commande->socid; } elseif (GETPOST('factureid') > 0) { $facture = new Facture($db); $result = $facture->fetch(GETPOST('factureid')); if ($result <= 0) { dol_print_error($db, $facture->error); exit; } $thirpdartyid = $facture->socid; } if ($thirpdartyid > 0) { $soc = new Societe($db); $result = $soc->fetch($thirpdartyid); if ($result <= 0) { dol_print_error($db, $soc->error); exit; } $desc = $object->description; $tva_tx = get_default_tva($mysoc, $soc, $object->id);