dolibarr 20.0.0
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 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
28if (!defined('NOSESSION')) {
29 define('NOSESSION', '1');
30}
31
32$sapi_type = php_sapi_name();
33$script_file = basename(__FILE__);
34$path = __DIR__.'/';
35
36// Test si mode batch
37$sapi_type = php_sapi_name();
38if (substr($sapi_type, 0, 3) == 'cgi') {
39 echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
40 exit(1);
41}
42
43if (!isset($argv[2]) || !$argv[2] || !in_array($argv[1], array('test', 'confirm')) || !in_array($argv[2], array('thirdparties', 'contacts'))) {
44 print "Usage: $script_file (test|confirm) (thirdparties|contacts) [delay] [after]\n";
45 print "\n";
46 print "Send an email to customers to remind all unpaid customer invoices.\n";
47 print "If you choose 'test' mode, no emails are sent.\n";
48 print "If you add param delay (nb of days), only invoice with due date < today + delay are included.\n";
49 print "If you add param after (nb of days), only invoice with due date >= today + delay are included.\n";
50 exit(1);
51}
52$mode = $argv[1];
53$targettype = $argv[2];
54
55require $path."../../htdocs/master.inc.php";
56require_once DOL_DOCUMENT_ROOT."/core/class/CMailFile.class.php";
57
58$langs->load('main');
59
60// Global variables
61$version = DOL_VERSION;
62$error = 0;
63
64$hookmanager->initHooks(array('cli'));
65
66
67/*
68 * Main
69 */
70
71@set_time_limit(0);
72print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n";
73dol_syslog($script_file." launched with arg ".join(',', $argv));
74
75$now = dol_now('tzserver');
76$duration_value = isset($argv[3]) ? $argv[3] : 'none';
77$duration_value2 = isset($argv[4]) ? $argv[4] : 'none';
78
79$error = 0;
80print $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";
81
82if ($mode != 'confirm') {
83 $conf->global->MAIN_DISABLE_ALL_MAILS = 1;
84}
85
86if (!empty($dolibarr_main_db_readonly)) {
87 print "Error: instance in read-onyl mode\n";
88 exit(1);
89}
90
91$sql = "SELECT f.ref, f.total_ttc, f.date_lim_reglement as due_date,";
92$sql .= " s.rowid as sid, s.nom as name, s.email, s.default_lang";
93if ($targettype == 'contacts') {
94 $sql .= ", sp.rowid as cid, sp.firstname as cfirstname, sp.lastname as clastname, sp.email as cemail";
95}
96$sql .= " FROM ".MAIN_DB_PREFIX."facture as f, ".MAIN_DB_PREFIX."societe as s";
97if ($targettype == 'contacts') {
98 $sql .= ", ".MAIN_DB_PREFIX."socpeople as sp";
99}
100$sql .= " WHERE f.fk_statut = 1 AND f.paye = 0";
101$sql .= " AND f.fk_soc = s.rowid";
102if (is_numeric($duration_value2)) {
103 $sql .= " AND f.date_lim_reglement >= '".$db->idate(dol_time_plus_duree($now, $duration_value2, "d"))."'";
104}
105if (is_numeric($duration_value)) {
106 $sql .= " AND f.date_lim_reglement < '".$db->idate(dol_time_plus_duree($now, $duration_value, "d"))."'";
107}
108if ($targettype == 'contacts') {
109 $sql .= " AND s.rowid = sp.fk_soc";
110}
111$sql .= " ORDER BY";
112if ($targettype == 'contacts') {
113 $sql .= " sp.email, sp.rowid,";
114}
115$sql .= " s.email ASC, s.rowid ASC, f.ref ASC"; // Order by email to allow one message per email
116
117// print $sql;
118$resql = $db->query($sql);
119if ($resql) {
120 $num = $db->num_rows($resql);
121 $i = 0;
122 $oldemail = 'none';
123 $oldsid = 0;
124 $oldcid = 0;
125 $oldlang = '';
126 $total = 0;
127 $foundtoprocess = 0;
128 $trackthirdpartiessent = array();
129
130 print "We found ".$num." couples (unpayed validated invoices-".$targettype.") qualified\n";
131 dol_syslog("We found ".$num." couples (unpayed validated invoices-".$targettype.") qualified");
132 $message = '';
133 $oldtarget = '';
134
135 if ($num) {
136 while ($i < $num) {
137 $obj = $db->fetch_object($resql);
138
139 $newemail = empty($obj->cemail) ? $obj->email : $obj->cemail;
140
141 // Check if this record is a break after previous one
142 $startbreak = false;
143 if ($newemail != $oldemail || $oldemail == 'none') {
144 $startbreak = true;
145 }
146 if ($obj->sid && $obj->sid != $oldsid) {
147 $startbreak = true;
148 }
149 if ($targettype == 'contacts') {
150 if ($obj->cid && $obj->cid != $oldcid) {
151 $startbreak = true;
152 }
153 }
154
155 if ($startbreak) {
156 // Break onto sales representative (new email or cid)
157 if (dol_strlen($oldemail) && $oldemail != 'none' && empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) {
158 envoi_mail($mode, $oldemail, $message, $total, $oldlang, $oldtarget);
159 $trackthirdpartiessent[$oldsid.'|'.$oldemail] = 'contact id '.$oldcid;
160 } else {
161 if ($oldemail != 'none') {
162 if (empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) {
163 print "- No email sent for '".$oldtarget."', total: ".$total."\n";
164 } else {
165 print "- No email sent for '".$oldtarget."', total: ".$total." (already sent to ".$trackthirdpartiessent[$oldsid.'|'.$oldemail].")\n";
166 }
167 }
168 }
169 $oldemail = $newemail;
170 $oldsid = $obj->sid;
171 if ($targettype == 'contacts') {
172 $oldcid = $obj->cid;
173 }
174 $oldlang = $obj->default_lang;
175 $oldtarget = (empty($obj->cfirstname) && empty($obj->clastname)) ? $obj->name : ($obj->clastname." ".$obj->cfirstname);
176 $message = '';
177 $total = 0;
178 $foundtoprocess = 0;
179 // if (empty($newemail)) print "Warning: Customer ".$target." has no email. Notice disabled.\n";
180 }
181
182 // Define line content
183 $outputlangs = new Translate('', $conf);
184 $outputlangs->setDefaultLang(empty($obj->default_lang) ? $langs->defaultlang : $obj->default_lang); // By default language of customer
185
186 // Load translation files required by the page
187 $outputlangs->loadLangs(array("main", "bills"));
188
189 if (dol_strlen($newemail)) {
190 $message .= $outputlangs->trans("Invoice")." ".$obj->ref." : ".price($obj->total_ttc, 0, $outputlangs, 0, 0, -1, $conf->currency)."\n";
191 dol_syslog("email_unpaid_invoices_to_customers.php: ".$newemail." ".$message);
192 $foundtoprocess++;
193 }
194 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.": ";
195 if (dol_strlen($newemail)) {
196 print "qualified.";
197 } else {
198 print "disqualified (no email).";
199 }
200 print "\n";
201
202 unset($outputlangs);
203
204 $total += $obj->total_ttc;
205
206 $i++;
207 }
208
209 // Si il reste des envois en buffer
210 if ($foundtoprocess) {
211 if (dol_strlen($oldemail) && $oldemail != 'none' && empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) { // Break onto email (new email)
212 envoi_mail($mode, $oldemail, $message, $total, $oldlang, $oldtarget);
213 $trackthirdpartiessent[$oldsid.'|'.$oldemail] = 'contact id '.$oldcid;
214 } else {
215 if ($oldemail != 'none') {
216 if (empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) {
217 print "- No email sent for '".$oldtarget."', total: ".$total."\n";
218 } else {
219 print "- No email sent for '".$oldtarget."', total: ".$total." (already sent to ".$trackthirdpartiessent[$oldsid.'|'.$oldemail].")\n";
220 }
221 }
222 }
223 }
224 } else {
225 print "No unpaid invoices found\n";
226 }
227
228 exit(0);
229} else {
230 dol_print_error($db);
231 dol_syslog("email_unpaid_invoices_to_customers.php: Error");
232
233 exit(1);
234}
235
247function envoi_mail($mode, $oldemail, $message, $total, $userlang, $oldtarget)
248{
249 global $conf, $langs;
250
251 if (getenv('DOL_FORCE_EMAIL_TO')) {
252 $oldemail = getenv('DOL_FORCE_EMAIL_TO');
253 }
254
255 $newlangs = new Translate('', $conf);
256 $newlangs->setDefaultLang(empty($userlang) ? getDolGlobalString('MAIN_LANG_DEFAULT', 'auto') : $userlang);
257 $newlangs->load("main");
258 $newlangs->load("bills");
259
260 $subject = getDolGlobalString('SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_SUBJECT', $newlangs->trans("ListOfYourUnpaidInvoices"));
261 $sendto = $oldemail;
262 $from = getDolGlobalString('MAIN_MAIL_EMAIL_FROM');
263 $errorsto = getDolGlobalString('MAIN_MAIL_ERRORS_TO');
264 $msgishtml = -1;
265
266 print "- Send email to '".$oldtarget."' (".$oldemail."), total: ".$total."\n";
267 dol_syslog("email_unpaid_invoices_to_customers.php: send mail to ".$oldemail);
268
269 $usehtml = 0;
270 if (getDolGlobalString('SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_FOOTER') && dol_textishtml(getDolGlobalString('SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_FOOTER'))) {
271 $usehtml += 1;
272 }
273 if (getDolGlobalString('SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_HEADER') && dol_textishtml(getDolGlobalString('SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_HEADER'))) {
274 $usehtml += 1;
275 }
276
277 $allmessage = '';
278 if (getDolGlobalString('SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_HEADER')) {
279 $allmessage .= $conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_HEADER;
280 } else {
281 $allmessage .= "Dear customer".($usehtml ? "<br>\n" : "\n").($usehtml ? "<br>\n" : "\n");
282 $allmessage .= "Please, find a summary of the bills with pending payments from you.".($usehtml ? "<br>\n" : "\n").($usehtml ? "<br>\n" : "\n");
283 $allmessage .= "Note: This list contains only unpaid invoices.".($usehtml ? "<br>\n" : "\n");
284 }
285 $allmessage .= $message.($usehtml ? "<br>\n" : "\n");
286 $allmessage .= $langs->trans("Total")." = ".price($total, 0, $userlang, 0, 0, -1, $conf->currency).($usehtml ? "<br>\n" : "\n");
287 if (getDolGlobalString('SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_FOOTER')) {
288 $allmessage .= getDolGlobalString('SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_FOOTER');
289 if (dol_textishtml(getDolGlobalString('SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_FOOTER'))) {
290 $usehtml += 1;
291 }
292 }
293
294 $mail = new CMailFile($subject, $sendto, $from, $allmessage, array(), array(), array(), '', '', 0, $msgishtml);
295
296 $mail->errors_to = $errorsto;
297
298 // Send or not email
299 if ($mode == 'confirm') {
300 $result = $mail->sendfile();
301 if (!$result) {
302 print "Error sending email ".$mail->error."\n";
303 dol_syslog("Error sending email ".$mail->error."\n");
304 }
305 } else {
306 print "No email sent (test mode)\n";
307 dol_syslog("No email sent (test mode)");
308 $mail->dump_mail();
309 $result = 1;
310 }
311
312 unset($newlangs);
313 if ($result) {
314 return 1;
315 } else {
316 return -1;
317 }
318}
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 dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.