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