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