dolibarr 21.0.0-alpha
email_unpaid_invoices_to_customers.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 Frédéric France <frederic.france@free.fr>
8 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
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[2]) || !$argv[2] || !in_array($argv[1], array('test', 'confirm')) || !in_array($argv[2], array('thirdparties', 'contacts'))) {
46 print "Usage: $script_file (test|confirm) (thirdparties|contacts) [delay] [after]\n";
47 print "\n";
48 print "Send an email to customers to remind all unpaid customer invoices.\n";
49 print "If you choose 'test' mode, no emails are sent.\n";
50 print "If you add param delay (nb of days), only invoice with due date < today + delay are included.\n";
51 print "If you add param after (nb of days), only invoice with due date >= today + delay are included.\n";
52 exit(1);
53}
54$mode = $argv[1];
55$targettype = $argv[2];
56
57require $path."../../htdocs/master.inc.php";
58require_once DOL_DOCUMENT_ROOT.'/core/lib/functionscli.lib.php';
59require_once DOL_DOCUMENT_ROOT."/core/class/CMailFile.class.php";
60
61$langs->load('main');
62
63// Global variables
64$version = DOL_VERSION;
65$error = 0;
66
67$hookmanager->initHooks(array('cli'));
68
69
70/*
71 * Main
72 */
73
74@set_time_limit(0);
75print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n";
76dol_syslog($script_file." launched with arg ".join(',', $argv));
77
78$now = dol_now('tzserver');
79$duration_value = isset($argv[3]) ? $argv[3] : 'none';
80$duration_value2 = isset($argv[4]) ? $argv[4] : 'none';
81
82$error = 0;
83print $script_file." launched with mode ".$mode." default lang=".$langs->defaultlang.(is_numeric($duration_value) ? " delay=".$duration_value : "").(is_numeric($duration_value2) ? " after=".$duration_value2 : "")."\n";
84
85if ($mode != 'confirm') {
86 $conf->global->MAIN_DISABLE_ALL_MAILS = 1;
87}
88
89if (!empty($dolibarr_main_db_readonly)) {
90 print "Error: instance in read-onyl mode\n";
91 exit(1);
92}
93
96$sql = "SELECT f.ref, f.total_ttc, f.date_lim_reglement as due_date,";
97$sql .= " s.rowid as sid, s.nom as name, s.email, s.default_lang";
98if ($targettype == 'contacts') {
99 $sql .= ", sp.rowid as cid, sp.firstname as cfirstname, sp.lastname as clastname, sp.email as cemail";
100}
101$sql .= " FROM ".MAIN_DB_PREFIX."facture as f, ".MAIN_DB_PREFIX."societe as s";
102if ($targettype == 'contacts') {
103 $sql .= ", ".MAIN_DB_PREFIX."socpeople as sp";
104}
105$sql .= " WHERE f.fk_statut = 1 AND f.paye = 0";
106$sql .= " AND f.fk_soc = s.rowid";
107if (is_numeric($duration_value2)) {
108 $sql .= " AND f.date_lim_reglement >= '".$db->idate(dol_time_plus_duree($now, (int) $duration_value2, "d"))."'";
109}
110if (is_numeric($duration_value)) {
111 $sql .= " AND f.date_lim_reglement < '".$db->idate(dol_time_plus_duree($now, (int) $duration_value, "d"))."'";
112}
113if ($targettype == 'contacts') {
114 $sql .= " AND s.rowid = sp.fk_soc";
115}
116$sql .= " ORDER BY";
117if ($targettype == 'contacts') {
118 $sql .= " sp.email, sp.rowid,";
119}
120$sql .= " s.email ASC, s.rowid ASC, f.ref ASC"; // Order by email to allow one message per email
121
122// print $sql;
123$resql = $db->query($sql);
124if ($resql) {
125 $num = $db->num_rows($resql);
126 $i = 0;
127 $oldemail = 'none';
128 $oldsid = 0;
129 $oldcid = 0;
130 $oldlang = '';
131 $total = 0;
132 $foundtoprocess = 0;
133 $trackthirdpartiessent = array();
134
135 print "We found ".$num." couples (unpayed validated invoices-".$targettype.") qualified\n";
136 dol_syslog("We found ".$num." couples (unpayed validated invoices-".$targettype.") qualified");
137 $message = '';
138 $oldtarget = '';
139
140 if ($num) {
141 while ($i < $num) {
142 $obj = $db->fetch_object($resql);
143
144 $newemail = empty($obj->cemail) ? $obj->email : $obj->cemail;
145
146 // Check if this record is a break after previous one
147 $startbreak = false;
148 if ($newemail != $oldemail || $oldemail == 'none') {
149 $startbreak = true;
150 }
151 if ($obj->sid && $obj->sid != $oldsid) {
152 $startbreak = true;
153 }
154 if ($targettype == 'contacts') {
155 if ($obj->cid && $obj->cid != $oldcid) {
156 $startbreak = true;
157 }
158 }
159
160 if ($startbreak) {
161 // Break onto sales representative (new email or cid)
162 if (dol_strlen($oldemail) && $oldemail != 'none' && empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) {
163 envoi_mail($mode, $oldemail, $message, price2num($total), $oldlang, $oldtarget);
164 $trackthirdpartiessent[$oldsid.'|'.$oldemail] = 'contact id '.$oldcid;
165 } else {
166 if ($oldemail != 'none') {
167 if (empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) {
168 print "- No email sent for '".$oldtarget."', total: ".$total."\n";
169 } else {
170 print "- No email sent for '".$oldtarget."', total: ".$total." (already sent to ".$trackthirdpartiessent[$oldsid.'|'.$oldemail].")\n";
171 }
172 }
173 }
174 $oldemail = $newemail;
175 $oldsid = $obj->sid;
176 if ($targettype == 'contacts') {
177 $oldcid = $obj->cid;
178 }
179 $oldlang = $obj->default_lang;
180 $oldtarget = (empty($obj->cfirstname) && empty($obj->clastname)) ? $obj->name : ($obj->clastname." ".$obj->cfirstname);
181 $message = '';
182 $total = 0;
183 $foundtoprocess = 0;
184 // if (empty($newemail)) print "Warning: Customer ".$target." has no email. Notice disabled.\n";
185 }
186
187 // Define line content
188 $outputlangs = new Translate('', $conf);
189 $outputlangs->setDefaultLang(empty($obj->default_lang) ? $langs->defaultlang : $obj->default_lang); // By default language of customer
190
191 // Load translation files required by the page
192 $outputlangs->loadLangs(array("main", "bills"));
193
194 if (dol_strlen($newemail)) {
195 $message .= $outputlangs->trans("Invoice")." ".$obj->ref." : ".price($obj->total_ttc, 0, $outputlangs, 0, 0, -1, $conf->currency)."\n";
196 dol_syslog("email_unpaid_invoices_to_customers.php: ".$newemail." ".$message);
197 $foundtoprocess++;
198 }
199 print "Unpaid invoice ".$obj->ref.", price ".price2num($obj->total_ttc).", due date ".dol_print_date($db->jdate($obj->due_date), 'day').", customer id ".$obj->sid." ".$obj->name.", ".(isset($obj->cid) ? "contact id ".$obj->cid." ".$obj->clastname." ".$obj->cfirstname.", " : "")."email ".$newemail.", lang ".$outputlangs->defaultlang.": ";
200 if (dol_strlen($newemail)) {
201 print "qualified.";
202 } else {
203 print "disqualified (no email).";
204 }
205 print "\n";
206
207 unset($outputlangs);
208
209 $total += $obj->total_ttc;
210
211 $i++;
212 }
213
214 // If there are remaining messages to send in the buffer
215 if ($foundtoprocess) {
216 if (dol_strlen($oldemail) && $oldemail != 'none' && empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) { // Break onto email (new email)
217 envoi_mail($mode, $oldemail, $message, price2num($total), $oldlang, $oldtarget);
218 $trackthirdpartiessent[$oldsid.'|'.$oldemail] = 'contact id '.$oldcid;
219 } else {
220 if ($oldemail != 'none') {
221 if (empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) {
222 print "- No email sent for '".$oldtarget."', total: ".$total."\n";
223 } else {
224 print "- No email sent for '".$oldtarget."', total: ".$total." (already sent to ".$trackthirdpartiessent[$oldsid.'|'.$oldemail].")\n";
225 }
226 }
227 }
228 }
229 } else {
230 print "No unpaid invoices found\n";
231 }
232
233 exit(0);
234} else {
235 dol_print_error($db);
236 dol_syslog("email_unpaid_invoices_to_customers.php: Error");
237
238 exit(1);
239}
240
252function envoi_mail($mode, $oldemail, $message, $total, $userlang, $oldtarget)
253{
254 global $conf, $langs;
255
256 if (getenv('DOL_FORCE_EMAIL_TO')) {
257 $oldemail = getenv('DOL_FORCE_EMAIL_TO');
258 }
259
260 $newlangs = new Translate('', $conf);
261 $newlangs->setDefaultLang(empty($userlang) ? getDolGlobalString('MAIN_LANG_DEFAULT', 'auto') : $userlang);
262 $newlangs->load("main");
263 $newlangs->load("bills");
264
265 $subject = getDolGlobalString('SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_SUBJECT', $newlangs->trans("ListOfYourUnpaidInvoices"));
266 $sendto = $oldemail;
267 $from = getDolGlobalString('MAIN_MAIL_EMAIL_FROM');
268 $errorsto = getDolGlobalString('MAIN_MAIL_ERRORS_TO');
269 $msgishtml = -1;
270
271 print "- Send email to '".$oldtarget."' (".$oldemail."), total: ".$total."\n";
272 dol_syslog("email_unpaid_invoices_to_customers.php: send mail to ".$oldemail);
273
274 $usehtml = 0;
275 if (getDolGlobalString('SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_FOOTER') && dol_textishtml(getDolGlobalString('SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_FOOTER'))) {
276 $usehtml += 1;
277 }
278 if (getDolGlobalString('SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_HEADER') && dol_textishtml(getDolGlobalString('SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_HEADER'))) {
279 $usehtml += 1;
280 }
281
282 $allmessage = '';
283 if (getDolGlobalString('SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_HEADER')) {
284 $allmessage .= $conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_HEADER;
285 } else {
286 $allmessage .= "Dear customer".($usehtml ? "<br>\n" : "\n").($usehtml ? "<br>\n" : "\n");
287 $allmessage .= "Please, find a summary of the bills with pending payments from you.".($usehtml ? "<br>\n" : "\n").($usehtml ? "<br>\n" : "\n");
288 $allmessage .= "Note: This list contains only unpaid invoices.".($usehtml ? "<br>\n" : "\n");
289 }
290 $allmessage .= $message.($usehtml ? "<br>\n" : "\n");
291 $allmessage .= $langs->trans("Total")." = ".price($total, 0, $userlang, 0, 0, -1, $conf->currency).($usehtml ? "<br>\n" : "\n");
292 if (getDolGlobalString('SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_FOOTER')) {
293 $allmessage .= getDolGlobalString('SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_FOOTER');
294 if (dol_textishtml(getDolGlobalString('SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_FOOTER'))) {
295 $usehtml += 1;
296 }
297 }
298
299 $mail = new CMailFile($subject, $sendto, $from, $allmessage, array(), array(), array(), '', '', 0, $msgishtml);
300
301 $mail->errors_to = $errorsto;
302
303 // Send or not email
304 if ($mode == 'confirm') {
305 $result = $mail->sendfile();
306 if (!$result) {
307 print "Error sending email ".$mail->error."\n";
308 dol_syslog("Error sending email ".$mail->error."\n");
309 }
310 } else {
311 print "No email sent (test mode)\n";
312 dol_syslog("No email sent (test mode)");
313 $mail->dump_mail();
314 $result = 1;
315 }
316
317 unset($newlangs);
318 if ($result) {
319 return 1;
320 } else {
321 return -1;
322 }
323}
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).
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.