dolibarr 21.0.0-beta
email_unpaid_invoices_to_representatives.php
Go to the documentation of this file.
1#!/usr/bin/env php
2<?php
3/*
4 * Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
5 * Copyright (C) 2005-2013 Laurent Destailleur <eldy@users.sourceforge.net>
6 * Copyright (C) 2013 Juanjo Menent <jmenent@2byte.es>
7 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
8 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 3 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 */
23
30if (!defined('NOSESSION')) {
31 define('NOSESSION', '1');
32}
33
34$sapi_type = php_sapi_name();
35$script_file = basename(__FILE__);
36$path = __DIR__.'/';
37
38// Test si mode batch
39$sapi_type = php_sapi_name();
40if (substr($sapi_type, 0, 3) == 'cgi') {
41 echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
42 exit(1);
43}
44
45if (!isset($argv[1]) || !$argv[1] || !in_array($argv[1], array('test', 'confirm'))) {
46 print "Usage: $script_file (test|confirm) [delay]\n";
47 print "\n";
48 print "Send an email to users to remind all unpaid customer invoices user is sale representative for.\n";
49 print "If you choose 'test' mode, no emails are sent.\n";
50 print "If you add a delay (nb of days), only invoice with due date < today + delay are included.\n";
51 exit(1);
52}
53$mode = $argv[1];
54
55require $path."../../htdocs/master.inc.php";
56require_once DOL_DOCUMENT_ROOT.'/core/lib/functionscli.lib.php';
57require_once DOL_DOCUMENT_ROOT."/core/class/CMailFile.class.php";
58
59$langs->load('main');
60
61// Global variables
62$version = DOL_VERSION;
63$error = 0;
64
65$hookmanager->initHooks(array('cli'));
66
67
68/*
69 * Main
70 */
71
72@set_time_limit(0);
73print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n";
74dol_syslog($script_file." launched with arg ".join(',', $argv));
75
76$now = dol_now('tzserver');
77$duration_value = isset($argv[2]) ? $argv[2] : 'none';
78
79print $script_file." launched with mode ".$mode." default lang=".$langs->defaultlang.(is_numeric($duration_value) ? " delay=".$duration_value : "")."\n";
80
81if ($mode != 'confirm') {
82 $conf->global->MAIN_DISABLE_ALL_MAILS = 1;
83}
84
85if (!empty($dolibarr_main_db_readonly)) {
86 print "Error: instance in read-onyl mode\n";
87 exit(1);
88}
89
90$sql = "SELECT f.ref, f.total_ttc, f.date_lim_reglement as due_date, s.nom as name, s.email, s.default_lang,";
91$sql .= " u.rowid as uid, u.lastname, u.firstname, u.email, u.lang";
92$sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
93$sql .= " , ".MAIN_DB_PREFIX."societe as s";
94$sql .= " , ".MAIN_DB_PREFIX."societe_commerciaux as sc";
95$sql .= " , ".MAIN_DB_PREFIX."user as u";
96$sql .= " WHERE f.fk_statut = 1 AND f.paye = 0";
97$sql .= " AND f.fk_soc = s.rowid";
98if (is_numeric($duration_value)) {
99 $sql .= " AND f.date_lim_reglement < '".$db->idate(dol_time_plus_duree($now, (int) $duration_value, "d"))."'";
100}
101$sql .= " AND sc.fk_soc = s.rowid";
102$sql .= " AND sc.fk_user = u.rowid";
103$sql .= " ORDER BY u.email ASC, s.rowid ASC, f.ref ASC"; // Order by email to allow one message per email
104
105// print $sql;
106$resql = $db->query($sql);
107if ($resql) {
108 $num = $db->num_rows($resql);
109 $i = 0;
110 $oldemail = 'none';
111 $olduid = 0;
112 $oldlang = '';
113 $total = 0;
114 $foundtoprocess = 0;
115
116 print "We found ".$num." couples (unpayed validated invoice - sale representative) qualified\n";
117 dol_syslog("We found ".$num." couples (unpayed validated invoice - sale representative) qualified");
118 $message = '';
119 $oldsalerepresentative = 0;
120
121 if ($num) {
122 while ($i < $num) {
123 $obj = $db->fetch_object($resql);
124
125 if (($obj->email != $oldemail || $obj->uid != $olduid) || $oldemail == 'none') {
126 // Break onto sales representative (new email or uid)
127 if (dol_strlen($oldemail) && $oldemail != 'none') {
128 envoi_mail($mode, $oldemail, $message, price2num($total), $oldlang, $oldsalerepresentative);
129 } else {
130 if ($oldemail != 'none') {
131 print "- No email sent for ".$oldsalerepresentative.", total: ".$total."\n";
132 }
133 }
134 $oldemail = $obj->email;
135 $olduid = $obj->uid;
136 $oldlang = $obj->lang;
137 $oldsalerepresentative = dolGetFirstLastname($obj->firstname, $obj->lastname);
138 $message = '';
139 $total = 0;
140 $foundtoprocess = 0;
141 $salerepresentative = dolGetFirstLastname($obj->firstname, $obj->lastname);
142 if (empty($obj->email)) {
143 print "Warning: Sale representative ".$salerepresentative." has no email. Notice disabled.\n";
144 }
145 }
146
147 // Define line content
148 $outputlangs = new Translate('', $conf);
149 $outputlangs->setDefaultLang(empty($obj->lang) ? $langs->defaultlang : $obj->lang); // By default language of sale representative
150
151 // Load translation files required by the page
152 $outputlangs->loadLangs(array("main", "bills"));
153
154 if (dol_strlen($obj->email)) {
155 $message .= $outputlangs->trans("Invoice")." ".$obj->ref." : ".price($obj->total_ttc, 0, $outputlangs, 0, 0, -1, $conf->currency)." : ".$obj->name."\n";
156 dol_syslog("email_unpaid_invoices_to_representatives.php: ".$obj->email);
157 $foundtoprocess++;
158 }
159 print "Unpaid invoice ".$obj->ref.", price ".price2num($obj->total_ttc).", due date ".dol_print_date($db->jdate($obj->due_date), 'day')." (linked to company ".$obj->name.", sale representative ".dolGetFirstLastname($obj->firstname, $obj->lastname).", email ".$obj->email.", lang ".$outputlangs->defaultlang."): ";
160 if (dol_strlen($obj->email)) {
161 print "qualified.";
162 } else {
163 print "disqualified (no email).";
164 }
165 print "\n";
166
167 unset($outputlangs);
168
169 $total += $obj->total_ttc;
170 $i++;
171 }
172
173 // If there are remaining messages to send in the buffer
174 if ($foundtoprocess) {
175 if (dol_strlen($oldemail) && $oldemail != 'none') { // Break onto email (new email)
176 envoi_mail($mode, $oldemail, $message, price2num($total), $oldlang, $oldsalerepresentative);
177 } else {
178 if ($oldemail != 'none') {
179 print "- No email sent for ".$oldsalerepresentative.", total: ".$total."\n";
180 }
181 }
182 }
183 } else {
184 print "No unpaid invoices (for companies linked to a particular commercial dolibarr user) found\n";
185 }
186
187 exit(0);
188} else {
189 dol_print_error($db);
190 dol_syslog("email_unpaid_invoices_to_representatives.php: Error");
191
192 exit(1);
193}
194
206function envoi_mail($mode, $oldemail, $message, $total, $userlang, $oldtarget)
207{
208 global $conf, $langs;
209
210 if (getenv('DOL_FORCE_EMAIL_TO')) {
211 $oldemail = getenv('DOL_FORCE_EMAIL_TO');
212 }
213
214 $newlangs = new Translate('', $conf);
215 $newlangs->setDefaultLang(empty($userlang) ? getDolGlobalString('MAIN_LANG_DEFAULT', 'auto') : $userlang);
216 $newlangs->load("main");
217 $newlangs->load("bills");
218
219 $subject = getDolGlobalString('SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_SUBJECT', $newlangs->trans("ListOfYourUnpaidInvoices"));
220 $sendto = $oldemail;
221 $from = getDolGlobalString('MAIN_MAIL_EMAIL_FROM');
222 $errorsto = getDolGlobalString('MAIN_MAIL_ERRORS_TO');
223 $msgishtml = -1;
224
225 print "- Send email for ".$oldtarget." (".$oldemail."), total: ".$total."\n";
226 dol_syslog("email_unpaid_invoices_to_representatives.php: send mail to ".$oldemail);
227
228 $usehtml = 0;
229 if (getDolGlobalString('SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_FOOTER') && dol_textishtml(getDolGlobalString('SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_FOOTER'))) {
230 $usehtml += 1;
231 }
232 if (getDolGlobalString('SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_HEADER') && dol_textishtml(getDolGlobalString('SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_HEADER'))) {
233 $usehtml += 1;
234 }
235
236 $allmessage = '';
237 if (getDolGlobalString('SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_HEADER')) {
238 $allmessage .= getDolGlobalString('SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_HEADER');
239 } else {
240 $allmessage .= $newlangs->transnoentities("ListOfYourUnpaidInvoices").($usehtml ? "<br>\n" : "\n").($usehtml ? "<br>\n" : "\n");
241 $allmessage .= $newlangs->transnoentities("NoteListOfYourUnpaidInvoices").($usehtml ? "<br>\n" : "\n");
242 }
243 $allmessage .= $message.($usehtml ? "<br>\n" : "\n");
244 $allmessage .= $langs->trans("Total")." = ".price($total, 0, $newlangs, 0, 0, -1, $conf->currency).($usehtml ? "<br>\n" : "\n");
245 if (getDolGlobalString('SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_FOOTER')) {
246 $allmessage .= getDolGlobalString('SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_FOOTER');
247 if (dol_textishtml(getDolGlobalString('SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_FOOTER'))) {
248 $usehtml += 1;
249 }
250 }
251
252 $mail = new CMailFile($subject, $sendto, $from, $allmessage, array(), array(), array(), '', '', 0, $msgishtml);
253
254 $mail->errors_to = $errorsto;
255
256 // Send or not email
257 if ($mode == 'confirm') {
258 $result = $mail->sendfile();
259 if (!$result) {
260 print "Error sending email ".$mail->error."\n";
261 dol_syslog("Error sending email ".$mail->error."\n");
262 }
263 } else {
264 print "No email sent (test mode)\n";
265 dol_syslog("No email sent (test mode)");
266 $mail->dump_mail();
267 $result = 1;
268 }
269
270 if ($result) {
271 return 1;
272 } else {
273 return -1;
274 }
275}
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Class to manage translations.
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition date.lib.php:125
envoi_mail($mode, $oldemail, $message, $total, $userlang, $oldtarget)
Send email.
dol_getmypid()
Return getmypid() or random PID when function is disabled Some web hosts disable this php function fo...
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
dol_now($mode='auto')
Return date for now.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
dol_textishtml($msg, $option=0)
Return if a text is a html content.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79