NEW #25829 Automatically send the invoice generated from a template (#36967)

* Update DB

* ADD email template

* Ajout d'une clé de trad

* Ajout des traductions

* Suppression des traductions, sauf en_US

* Add flag auto send

* Modif form + cron auto send

* Suppression auto_send

* correction loopError

* ajout du selected au model de mail

* Prise en compte default model

* Fix pre-commit

* ménage

* precommit

* Correction Phan

* Correction Phan

* Correction, double cal du trigger

---------

Co-authored-by: Laurent Destailleur <eldy@destailleur.fr>
This commit is contained in:
Vincent Penel 2026-02-11 03:14:18 +01:00 committed by GitHub
parent 3623872851
commit 8a8a7f4e95
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 342 additions and 21 deletions

View file

@ -270,6 +270,7 @@ if (empty($reshook)) {
$object->unit_frequency = GETPOST('unit_frequency', 'alpha');
$object->nb_gen_max = $nb_gen_max;
$object->auto_validate = GETPOSTINT('auto_validate');
$object->fk_email_template = GETPOSTINT('auto_send_model_mail');
$object->generate_pdf = GETPOSTINT('generate_pdf');
$object->fk_project = $projectid;
@ -407,6 +408,9 @@ if (empty($reshook)) {
} elseif ($action == 'setauto_validate' && $usercancreate) {
// Set auto validate
$object->setAutoValidate(GETPOSTINT('auto_validate'));
} elseif ($action == 'setEmailTemplate' && $usercancreate) {
// Set Email Template
$object->setMailTemplate(GETPOSTINT('auto_send_model_mail'));
} elseif ($action == 'setgenerate_pdf' && $usercancreate) {
// Set generate pdf
$object->setGeneratepdf(GETPOSTINT('generate_pdf'));
@ -1450,10 +1454,27 @@ if ($action == 'create') {
// Auto validate the invoice
print "<tr><td>".$langs->trans("StatusOfAutoGeneratedInvoices")."</td><td>";
$select = array('0' => $langs->trans('BillStatusDraft'), '1' => $langs->trans('BillStatusValidated'));
$select = array('0' => $langs->trans('BillStatusDraft'), '1' => $langs->trans('BillStatusValidated'), '2' => $langs->trans('BillStatusValidatedWithSendind'));
print $form->selectarray('auto_validate', $select, GETPOSTINT('auto_validate'));
print "</td></tr>";
// Email template for auto sending invoices
print "<tr id='col_auto_send_model_mail' class='".(GETPOSTINT('auto_validate') != 2 ? 'hidden' : '')."'><td>" . $langs->trans("EmailTemplateForAutoSend") . "</td><td>";
print $form->selectModelMail("auto_send_", "facture_send", 1, 0, GETPOSTINT('auto_send_model_mail'));
print "</td></tr>";
print " <script>
$(document).ready(function() {
$('#auto_validate').on('change', function () {
if(+$(this).val() === 2) {
$('#col_auto_send_model_mail').show();
} else {
$('#col_auto_send_model_mail').hide();
$('#select_auto_send_model_mail').val(0);
}
});
});
</script>";
// Auto generate document
if (getDolGlobalString('INVOICE_REC_CAN_DISABLE_DOCUMENT_FILE_GENERATION')) {
print "<tr><td>".$langs->trans("StatusOfGeneratedDocuments")."</td><td>";
@ -1982,7 +2003,7 @@ if ($action == 'create') {
print $langs->trans("StatusOfAutoGeneratedInvoices");
}
print '</td><td>';
$select = 'select;0:'.$langs->trans('BillStatusDraft').',1:'.$langs->trans('BillStatusValidated');
$select = 'select;0:' . $langs->trans('BillStatusDraft') . ',1:' . $langs->trans('BillStatusValidated') . ',2:' . $langs->trans('BillStatusValidatedWithSendind');
if ($action == 'auto_validate' || $object->frequency > 0) {
print $form->editfieldval($langs->trans("StatusOfAutoGeneratedInvoices"), 'auto_validate', $object->auto_validate, $object, $user->hasRight('facture', 'creer'), $select);
}
@ -1991,6 +2012,49 @@ if ($action == 'create') {
print '<td></td>';
}
print '</tr>';
// Email template for auto sending invoices
if ($object->frequency > 0 && $object->auto_validate == 2) {
print '<tr><td style="width: 50%">';
print '<table class="nobordernopadding" width="100%"><tr><td>';
print $langs->trans("EmailTemplateForAutoSend");
print '</td>';
if ($action != 'editEmailTemplate' && $user->hasRight('facture', 'creer')) {
print '<td class="right"><a class="editfielda" href="' . $_SERVER["PHP_SELF"] . '?action=editEmailTemplate&token=' . newToken() . '&facid=' . $object->id . '">' . img_edit($langs->trans('Edit'), 1) . '</a></td>';
}
print '</tr></table>';
print '</td><td>';
if ($action == 'editEmailTemplate') {
// Edit
print '<form method="POST" action="' . $_SERVER['PHP_SELF'] . '?id=' . $object->id . '">';
print '<input type="hidden" name="token" value="' . newToken() . '">';
print '<input type="hidden" name="action" value="setEmailTemplate">';
print $form->selectModelMail("auto_send_", "facture_send", 1, 0, $object->fk_email_template);
print '<input type="submit" class="button valignmiddle smallpaddingimp" name="modify" value="' . $langs->trans("Modify") . '">';
print '<input type="submit" class="button button-cancel valignmiddle smallpaddingimp" name="cancel" value="' . $langs->trans("Cancel") . '">';
print '</form>';
} else {
// Show
if (!empty($object->fk_email_template)) {
$sql = "SELECT label
FROM ".$db->prefix()."c_email_templates
WHERE rowid = ".((int) $object->fk_email_template);
$result = $db->query($sql);
if ($result) {
if ($obj = $db->fetch_object($result)) {
print $obj->label;
}
}
} else {
print $langs->trans('DefaultMailModel');
}
}
print '</td>';
print '</tr>';
}
// Auto generate documents
if (getDolGlobalString('INVOICE_REC_CAN_DISABLE_DOCUMENT_FILE_GENERATION')) {
print '<tr>';

View file

@ -203,9 +203,14 @@ class FactureRec extends CommonInvoice
public $suspended; // status
/**
* @var int<0,1>
* @var int<0,2>
*/
public $auto_validate; // 0 to create in draft, 1 to create and validate the new invoice
public $auto_validate; // 0 to create in draft, 1 to create and validate the new invoice, 2 to create, validate and sending the new invoice
/**
* @var ?int
*/
public $fk_email_template; // Email template for auto sending invoices
/**
* @var int<0,1>
@ -280,6 +285,7 @@ class FactureRec extends CommonInvoice
'usenewprice' => array('type' => 'integer', 'label' => 'UseNewPrice', 'enabled' => 1, 'visible' => 0, 'position' => 155),
'revenuestamp' => array('type' => 'double(24,8)', 'label' => 'RevenueStamp', 'enabled' => 1, 'visible' => -1, 'position' => 160, 'isameasure' => 1),
'auto_validate' => array('type' => 'integer', 'label' => 'Auto validate', 'enabled' => 1, 'visible' => -1, 'position' => 165),
'fk_email_template' => array('type' => 'integer:CEmailTemplate:core/class/cemailtemplate.class.php', 'label' => "Modèle d'e-mail pour l'envoi automatique", 'enabled' => 1, 'visible' => -1, 'position' => 167),
'generate_pdf' => array('type' => 'integer', 'label' => 'Generate pdf', 'enabled' => 1, 'visible' => -1, 'position' => 170),
'fk_account' => array('type' => 'integer', 'label' => 'Fk account', 'enabled' => 'isModEnabled("bank")', 'visible' => -1, 'position' => 175),
'fk_multicurrency' => array('type' => 'integer', 'label' => 'Fk multicurrency', 'enabled' => 1, 'visible' => -1, 'position' => 180),
@ -381,6 +387,7 @@ class FactureRec extends CommonInvoice
$sql .= ", nb_gen_done";
$sql .= ", nb_gen_max";
$sql .= ", auto_validate";
$sql .= ", fk_email_template";
$sql .= ", generate_pdf";
$sql .= ", fk_multicurrency";
$sql .= ", multicurrency_code";
@ -412,6 +419,7 @@ class FactureRec extends CommonInvoice
$sql .= ", ".((int) $this->nb_gen_done);
$sql .= ", ".((int) $this->nb_gen_max);
$sql .= ", ".((int) $this->auto_validate);
$sql .= ", ".((int) $this->fk_email_template);
$sql .= ", ".((int) $this->generate_pdf);
$sql .= ", ".((int) $facsrc->fk_multicurrency);
$sql .= ", '".$this->db->escape($facsrc->multicurrency_code)."'";
@ -587,7 +595,7 @@ class FactureRec extends CommonInvoice
{
$error = 0;
$sql = "UPDATE ".MAIN_DB_PREFIX."facture_rec SET";
$sql = "UPDATE ".$this->db->prefix()."facture_rec SET";
$sql .= " entity = ".((int) $this->entity).",";
$sql .= " titre = '".$this->db->escape($this->title)."',";
$sql .= " suspended = ".((int) $this->suspended).",";
@ -597,7 +605,9 @@ class FactureRec extends CommonInvoice
$sql .= " localtax2 = ".((float) $this->total_localtax2).",";
$sql .= " total_ht = ".((float) $this->total_ht).",";
$sql .= " total_ttc = ".((float) $this->total_ttc).",";
$sql .= " fk_societe_rib = ".(!empty($this->fk_societe_rib) ? ((int) $this->fk_societe_rib) : 'NULL');
$sql .= " fk_societe_rib = ".(!empty($this->fk_societe_rib) ? ((int) $this->fk_societe_rib) : 'NULL').",";
$sql .= " auto_validate = ".((int) $this->auto_validate).",";
$sql .= " fk_email_template = ".((int) $this->fk_email_template);
// TODO Add missing fields
$sql .= " WHERE rowid = ".((int) $this->id);
@ -654,6 +664,7 @@ class FactureRec extends CommonInvoice
$sql .= ', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet as fk_project';
$sql .= ', f.fk_account, f.fk_societe_rib';
$sql .= ', f.frequency, f.unit_frequency, f.rule_for_lines_dates, f.date_when, f.date_last_gen, f.nb_gen_done, f.nb_gen_max, f.usenewprice, f.auto_validate';
$sql .= ', f.fk_email_template';
$sql .= ', f.generate_pdf';
$sql .= ", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc";
$sql .= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
@ -718,6 +729,7 @@ class FactureRec extends CommonInvoice
$this->nb_gen_max = $obj->nb_gen_max;
$this->usenewprice = $obj->usenewprice;
$this->auto_validate = $obj->auto_validate;
$this->fk_email_template = $obj->fk_email_template;
$this->generate_pdf = $obj->generate_pdf;
// Multicurrency
@ -1433,6 +1445,9 @@ class FactureRec extends CommonInvoice
$errorforinvoice = 0;
$invoiceidgenerated = 0;
$mailHasSent = false;
// Create a loopError that is reset at each loop, this counter is added to the global counter at the end of loop
$loopError = 0;
$facture = null;
$facturerec = new FactureRec($this->db);
@ -1498,6 +1513,207 @@ class FactureRec extends CommonInvoice
$error++;
$errorforinvoice++;
}
// Auto sending of the invoice
if ($result > 0 && $facture->status == Facture::STATUS_VALIDATED && $facturerec->auto_validate == 2) {
require_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php';
require_once DOL_DOCUMENT_ROOT . '/core/class/CMailFile.class.php';
$formmail = new FormMail($this->db);
$outputlangs = new Translate('', $conf);
if ($facture->thirdparty->default_lang) {
$outputlangs->setDefaultLang($facture->thirdparty->default_lang);
$outputlangs->loadLangs(array("main", "bills"));
} else {
$outputlangs = $langs;
}
// Select email template according to language of recipient
$template = $facturerec->fk_email_template;
$arraymessage = $formmail->getEMailTemplate($this->db, 'facture_send', $user, $outputlangs, (is_numeric($template) ? $template : 0), 1, (is_numeric($template) ? '' : $template), (($template != 0) ? -1 : 1));
if (is_numeric($arraymessage) && $arraymessage <= 0) {
$langs->load("errors");
$this->output .= $langs->trans('ErrorFailedToFindEmailTemplate', $template ?? '');
return 0;
}
// PREPARE EMAIL
$errormesg = '';
// Make substitution in email content
$substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $facture);
complete_substitutions_array($substitutionarray, $outputlangs, $facture);
// Topic
$sendTopic = make_substitutions(empty($arraymessage->topic) ? $outputlangs->transnoentitiesnoconv('InformationMessage') : $arraymessage->topic, $substitutionarray, $outputlangs, 1);
// Content
$content = $outputlangs->transnoentitiesnoconv($arraymessage->content);
$sendContent = make_substitutions($content, $substitutionarray, $outputlangs, 1);
// Recipient
$to = array();
$res = $facture->fetch_thirdparty();
$recipient = $facture->thirdparty;
if ($res > 0) {
$tmparraycontact = $facture->liste_contact(-1, 'external', 0, 'BILLING');
if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
foreach ($tmparraycontact as $data_email) {
if (!empty($data_email['email'])) {
$to[] = $facture->thirdparty->contact_get_property($data_email['id'], 'email');
}
}
}
if (empty($to) && !empty($recipient->email)) {
$to[] = $recipient->email;
}
if (empty($to)) {
$errormesg = "Failed to send invoice to thirdparty id=".$facture->socid.". No email defined for invoice or customer.";
$loopError++;
}
} else {
$errormesg = "Failed to load recipient with thirdparty id=".$facture->socid;
$loopError++;
}
// Sender
$from = getDolGlobalString('MAIN_MAIL_EMAIL_FROM');
if (!empty($arraymessage->email_from)) { // If a sender is defined into template, we use it in priority
$from = (string) $arraymessage->email_from;
}
if (empty($from)) {
$errormesg = "Failed to get sender into global setup MAIN_MAIL_EMAIL_FROM";
$loopError++;
}
if (!$loopError && !empty($to)) {
$to = implode(',', $to);
if (!empty($arraymessage->email_to)) { // If a recipient is defined into template, we add it
$to = $to . ',' . $arraymessage->email_to;
}
// Errors Recipient
$errors_to = getDolGlobalString('MAIN_MAIL_ERRORS_TO');
$trackid = 'inv'.$facture->id;
$sendcontext = 'standard';
// CC
$email_tocc = '';
if (!empty($arraymessage->email_tocc)) { // If a CC is defined into template, we use it
$email_tocc = (string) $arraymessage->email_tocc;
}
// BCC
$email_tobcc = '';
if (!empty($arraymessage->email_tobcc)) { // If a BCC is defined into template, we use it
$email_tobcc = (string) $arraymessage->email_tobcc;
}
//join file is asked
$joinFile = [];
$joinFileName = [];
$joinFileMime = [];
if ($arraymessage->joinfiles == 1 && !empty($facture->last_main_doc)) {
$joinFile[] = DOL_DATA_ROOT.'/'.$facture->last_main_doc;
$joinFileName[] = basename($facture->last_main_doc);
$joinFileMime[] = dol_mimetype(DOL_DATA_ROOT.'/'.$facture->last_main_doc);
}
// Mail Creation
$cMailFile = new CMailFile($sendTopic, $to, $from, $sendContent, $joinFile, $joinFileMime, $joinFileName, $email_tocc, $email_tobcc, 0, 1, $errors_to, '', $trackid, '', $sendcontext, '');
$resultsendmail = $cMailFile->sendfile();
$this->db->begin();
// Sending Mail
if ($resultsendmail) {
$mailHasSent = true;
// Add a line into event table
require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
// Insert record of emails sent
$actioncomm = new ActionComm($this->db);
$actioncomm->type_code = 'AC_OTH_AUTO'; // Event insert into agenda automatically
$actioncomm->socid = $facture->thirdparty->id; // To link to a company
$actioncomm->contact_id = 0;
$actioncomm->code = 'AC_EMAIL';
$actioncomm->label = $langs->trans('MailSentByTo', $from, $to);
$actioncomm->note_private = $sendContent;
$actioncomm->fk_project = $facture->fk_project;
$actioncomm->datep = dol_now();
$actioncomm->datef = $actioncomm->datep;
$actioncomm->percentage = -1; // Not applicable
$actioncomm->authorid = $user->id; // User saving action
$actioncomm->userownerid = $user->id; // Owner of action
// Fields when action is an email (content should be added into note)
$actioncomm->email_msgid = $cMailFile->msgid;
$actioncomm->email_subject = $sendTopic;
$actioncomm->email_from = $from;
$actioncomm->email_sender = '';
$actioncomm->email_to = $to;
//$actioncomm->email_tocc = $sendtocc;
//$actioncomm->email_tobcc = $sendtobcc;
//$actioncomm->email_subject = $subject;
$actioncomm->errors_to = $errors_to;
$actioncomm->elementtype = 'invoice';
$actioncomm->elementid = $facture->id;
//$actioncomm->extraparams = $extraparams;
$actioncomm->create($user);
} else {
$errormesg = $cMailFile->error.' : '.$to;
$loopError++;
// Add a line into event table
require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
// Insert record of emails sent
$actioncomm = new ActionComm($this->db);
$actioncomm->type_code = 'AC_OTH_AUTO'; // Event insert into agenda automatically
$actioncomm->socid = $facture->thirdparty->id; // To link to a company
$actioncomm->contact_id = 0;
$actioncomm->code = 'AC_EMAIL';
$actioncomm->label = $langs->trans('sendAutoEmailInvoiceKO', $from, $to);
$actioncomm->note_private = $errormesg;
$actioncomm->fk_project = $facture->fk_project;
$actioncomm->datep = dol_now();
$actioncomm->datef = $actioncomm->datep;
$actioncomm->percentage = -1; // Not applicable
$actioncomm->authorid = $user->id; // User saving action
$actioncomm->userownerid = $user->id; // Owner of action
// Fields when action is an email (content should be added into note)
$actioncomm->email_msgid = $cMailFile->msgid;
$actioncomm->email_subject = $sendTopic;
$actioncomm->email_from = $from;
$actioncomm->email_sender = '';
$actioncomm->email_to = $to;
//$actioncomm->email_tocc = $sendtocc;
//$actioncomm->email_tobcc = $sendtobcc;
//$actioncomm->email_subject = $subject;
$actioncomm->errors_to = $errors_to;
$actioncomm->elementtype = 'invoice';
$actioncomm->elementid = $facture->id;
//$actioncomm->extraparams = $extraparams;
$actioncomm->create($user);
}
$this->db->commit(); // We always commit
}
}
}
} else {
$error++;
@ -1512,6 +1728,16 @@ class FactureRec extends CommonInvoice
dol_syslog("createRecurringInvoices Process invoice template ".$facturerec->ref." is finished with a success generation");
$nb_create++;
$this->output .= $langs->trans("InvoiceGeneratedFromTemplate", $facture->ref, $facturerec->ref)."\n";
// Mail error
if ($loopError > 0) {
$this->output .= $langs->trans("InvoiceSentFromTemplateError", $facture->ref, $facturerec->ref, $errormesg ?? '')."\n";
}
// Mail sent
if ($mailHasSent) {
$this->output .= $langs->trans("InvoiceSentFromTemplate", $facture->ref, $facturerec->ref)."\n";
}
} else {
$this->output .= $langs->trans("InvoiceGeneratedFromTemplateError", $facture->ref, $facturerec->ref, $this->error)."\n";
$this->db->rollback("createRecurringInvoices Process invoice template id=".$facturerec->id.", ref=".$facturerec->ref);
@ -2145,23 +2371,12 @@ class FactureRec extends CommonInvoice
return -1;
}
$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
$sql .= ' SET auto_validate = '.((int) $validate);
$sql .= " WHERE rowid = ".((int) $this->id);
$this->auto_validate = $validate;
$result = $this->update($user);
dol_syslog(get_class($this)."::setAutoValidate", LOG_DEBUG);
if ($this->db->query($sql)) {
$this->auto_validate = $validate;
if (!$notrigger) {
// Call trigger
$result = $this->call_trigger('BILLREC_MODIFY', $user);
if ($result < 0) {
return $result;
}
// End call triggers
}
if ($result > 0) {
return 1;
} else {
dol_print_error($this->db);
@ -2247,6 +2462,42 @@ class FactureRec extends CommonInvoice
return -1;
}
}
/**
* Update the email template
*
* @param int $idEmailTemplate Email template
* @param int<0,1> $notrigger Disable the trigger
* @return int Return integer <0 if KO, >0 if OK
*/
public function setMailTemplate($idEmailTemplate, $notrigger = 0): int
{
global $user;
if (!$this->table_element) {
dol_syslog(get_class($this)."::setMailTemplate was called on object with property table_element not defined", LOG_ERR);
return -1;
}
$this->fk_email_template = $idEmailTemplate;
$result = $this->update($user);
dol_syslog(get_class($this)."::setMailTemplate", LOG_DEBUG);
if ($result > 0) {
if (!$notrigger) {
// Call trigger
$result = $this->call_trigger('BILLREC_MODIFY', $user);
if ($result < 0) {
return $result;
}
// End call triggers
}
return 1;
} else {
dol_print_error($this->db);
return -1;
}
}
}

View file

@ -714,3 +714,9 @@ DisputeWon=Dispute won
DisputeClosed=Dispute closed
Dispute=Dispute
Sales=Sales
AutoSendEmail=Automatic email sending
EmailTemplateForAutoSend=Email template for automatic sending
InvoiceSentFromTemplate=Invoice %s sent from recurring invoice template %s
InvoiceSentFromTemplateError=Failed to send invoice %s from recurring invoice template %s : %s
BillStatusValidatedWithSendind=Validated (needs to be paid) and sending
sendAutoEmailInvoiceKO=Failed to send email from %s to %s