dolibarr 21.0.0-beta
email_expire_services_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[1]) || !$argv[1] || !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 contracts services to expire or expired.\n";
49 print "If you choose 'test' mode, no emails are sent.\n";
50 print "If you add param delay (nb of days), only services with expired date < today + delay are included.\n";
51 print "If you add param after (nb of days), only services with expired 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";
68$langs->loadLangs(array('main', 'contracts'));
69
70// Global variables
71$version = DOL_VERSION;
72$error = 0;
73
74$hookmanager->initHooks(array('cli'));
75
76
77/*
78 * Main
79 */
80
81@set_time_limit(0);
82print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n";
83dol_syslog($script_file." launched with arg ".join(',', $argv));
84
85$now = dol_now('tzserver');
86$duration_value = isset($argv[3]) ? $argv[3] : 'none';
87$duration_value2 = isset($argv[4]) ? $argv[4] : 'none';
88
89$error = 0;
90print $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";
91
92if ($mode != 'confirm') {
93 $conf->global->MAIN_DISABLE_ALL_MAILS = 1;
94}
95
96$sql = "SELECT c.ref, cd.date_fin_validite, cd.total_ttc, cd.description as description, p.label as plabel,";
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."societe AS s";
102if ($targettype == 'contacts') {
103 $sql .= ", ".MAIN_DB_PREFIX."socpeople as sp";
104}
105$sql .= ", ".MAIN_DB_PREFIX."contrat AS c";
106$sql .= ", ".MAIN_DB_PREFIX."contratdet AS cd";
107$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product AS p ON p.rowid = cd.fk_product";
108$sql .= " WHERE s.rowid = c.fk_soc AND c.rowid = cd.fk_contrat AND c.statut > 0 AND cd.statut < 5";
109if (is_numeric($duration_value2)) {
110 $sql .= " AND cd.date_fin_validite >= '".$db->idate(dol_time_plus_duree($now, (int) $duration_value2, "d"))."'";
111}
112if (is_numeric($duration_value)) {
113 $sql .= " AND cd.date_fin_validite < '".$db->idate(dol_time_plus_duree($now, (int) $duration_value, "d"))."'";
114}
115if ($targettype == 'contacts') {
116 $sql .= " AND s.rowid = sp.fk_soc";
117}
118$sql .= " ORDER BY";
119if ($targettype == 'contacts') {
120 $sql .= " sp.email, sp.rowid,";
121}
122$sql .= " s.email ASC, s.rowid ASC, cd.date_fin_validite ASC"; // Order by email to allow one message per email
123
124// print $sql;
125$resql = $db->query($sql);
126if ($resql) {
127 $num = $db->num_rows($resql);
128 $i = 0;
129 $oldemail = 'none';
130 $oldsid = 0;
131 $oldcid = 0;
132 $oldlang = '';
133 $total = 0;
134 $foundtoprocess = 0;
135 $trackthirdpartiessent = array();
136
137 print "We found ".$num." couples (services to expire-".$targettype.") qualified\n";
138 dol_syslog("We found ".$num." couples (services to expire-".$targettype.") qualified");
139 $message = '';
140 $oldtarget = '';
141
142 if ($num) {
143 while ($i < $num) {
144 $obj = $db->fetch_object($resql);
145
146 $newemail = empty($obj->cemail) ? $obj->email : $obj->cemail;
147
148 // Check if this record is a break after previous one
149 $startbreak = false;
150 if ($newemail != $oldemail || $oldemail == 'none') {
151 $startbreak = true;
152 }
153 if ($obj->sid && $obj->sid != $oldsid) {
154 $startbreak = true;
155 }
156 if ($targettype == 'contacts') {
157 if ($obj->cid && $obj->cid != $oldcid) {
158 $startbreak = true;
159 }
160 }
161
162 if ($startbreak) {
163 // Break onto sales representative (new email or cid)
164 if (dol_strlen($oldemail) && $oldemail != 'none' && empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) {
165 sendEmailTo($mode, $oldemail, $message, price2num($total), $oldlang, $oldtarget, (int) $duration_value);
166 $trackthirdpartiessent[$oldsid.'|'.$oldemail] = 'contact id '.$oldcid;
167 } else {
168 if ($oldemail != 'none') {
169 if (empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) {
170 print "- No email sent for '".$oldtarget."', total: ".$total."\n";
171 } else {
172 print "- No email sent for '".$oldtarget."', total: ".$total." (already sent to ".$trackthirdpartiessent[$oldsid.'|'.$oldemail].")\n";
173 }
174 }
175 }
176 $oldemail = $newemail;
177 $oldsid = $obj->sid;
178 if ($targettype == 'contacts') {
179 $oldcid = $obj->cid;
180 }
181 $oldlang = $obj->default_lang;
182 $oldtarget = (empty($obj->cfirstname) && empty($obj->clastname)) ? $obj->name : ($obj->clastname." ".$obj->cfirstname);
183 $message = '';
184 $total = 0;
185 $foundtoprocess = 0;
186 // if (empty($newemail)) print "Warning: Customer ".$target." has no email. Notice disabled.\n";
187 }
188
189 // Define line content
190 $outputlangs = new Translate('', $conf);
191 $outputlangs->setDefaultLang(empty($obj->default_lang) ? $langs->defaultlang : $obj->default_lang); // By default language of customer
192
193 // Load translation files required by the page
194 $outputlangs->loadLangs(array("main", "contracts", "bills", "products"));
195
196 if (dol_strlen($newemail)) {
197 $message .= $outputlangs->trans("Contract")." ".$obj->ref.": ".$outputlangs->trans("Service")." ".dol_concatdesc($obj->plabel, $obj->description)." (".price($obj->total_ttc, 0, $outputlangs, 0, 0, -1, $conf->currency)."), ".$outputlangs->trans("DateEndPlannedShort")." ".dol_print_date($db->jdate($obj->date_fin_validite), 'day')."\n\n";
198 dol_syslog("email_expire_services_to_customers.php: ".$newemail." ".$message);
199 $foundtoprocess++;
200 }
201 print "Service to expire ".$obj->ref.", label ".dol_concatdesc($obj->plabel, $obj->description).", due date ".dol_print_date($db->jdate($obj->date_fin_validite), 'day').", customer id ".$obj->sid." ".$obj->name.", ".(isset($obj->cid) ? "contact id ".$obj->cid." ".$obj->clastname." ".$obj->cfirstname.", " : "")."email ".$newemail.", lang ".$outputlangs->defaultlang.": ";
202 if (dol_strlen($newemail)) {
203 print "qualified.";
204 } else {
205 print "disqualified (no email).";
206 }
207 print "\n";
208
209 unset($outputlangs);
210
211 $total += $obj->total_ttc;
212
213 $i++;
214 }
215
216 // If there are remaining messages to send in the buffer
217 if ($foundtoprocess) {
218 if (dol_strlen($oldemail) && $oldemail != 'none' && empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) { // Break onto email (new email)
219 sendEmailTo($mode, $oldemail, $message, price2num($total), $oldlang, $oldtarget, (int) $duration_value);
220 $trackthirdpartiessent[$oldsid.'|'.$oldemail] = 'contact id '.$oldcid;
221 } else {
222 if ($oldemail != 'none') {
223 if (empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) {
224 print "- No email sent for '".$oldtarget."', total: ".$total."\n";
225 } else {
226 print "- No email sent for '".$oldtarget."', total: ".$total." (already sent to ".$trackthirdpartiessent[$oldsid.'|'.$oldemail].")\n";
227 }
228 }
229 }
230 }
231 } else {
232 print "No services to expire found\n";
233 }
234
235 exit(0);
236} else {
237 dol_print_error($db);
238 dol_syslog("email_expire_services_to_customers.php: Error");
239
240 exit(1);
241}
242
255function sendEmailTo($mode, $oldemail, $message, $total, $userlang, $oldtarget, $duration_value)
256{
257 global $conf, $langs;
258
259 if (getenv('DOL_FORCE_EMAIL_TO')) {
260 $oldemail = getenv('DOL_FORCE_EMAIL_TO');
261 }
262
263 $newlangs = new Translate('', $conf);
264 $newlangs->setDefaultLang(empty($userlang) ? getDolGlobalString('MAIN_LANG_DEFAULT', 'auto') : $userlang);
265 $newlangs->load("main");
266 $newlangs->load("contracts");
267
268 if ($duration_value) {
269 if ($duration_value > 0) {
270 $title = $newlangs->transnoentities("ListOfServicesToExpireWithDuration", $duration_value);
271 } else {
272 $title = $newlangs->transnoentities("ListOfServicesToExpireWithDurationNeg", $duration_value);
273 }
274 } else {
275 $title = $newlangs->transnoentities("ListOfServicesToExpire");
276 }
277
278 $subject = getDolGlobalString('SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_SUBJECT', $title);
279 $sendto = $oldemail;
280 $from = getDolGlobalString('MAIN_MAIL_EMAIL_FROM');
281 $errorsto = getDolGlobalString('MAIN_MAIL_ERRORS_TO');
282 $msgishtml = -1;
283
284 print "- Send email to '".$oldtarget."' (".$oldemail."), total: ".$total."\n";
285 dol_syslog("email_expire_services_to_customers.php: send mail to ".$oldemail);
286
287 $usehtml = 0;
288 if (dol_textishtml(getDolGlobalString('SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_FOOTER'))) {
289 $usehtml += 1;
290 }
291 if (dol_textishtml(getDolGlobalString('SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_HEADER'))) {
292 $usehtml += 1;
293 }
294
295 $allmessage = '';
296 if (getDolGlobalString('SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_HEADER')) {
297 $allmessage .= getDolGlobalString('SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_HEADER');
298 } else {
299 $allmessage .= "Dear customer".($usehtml ? "<br>\n" : "\n").($usehtml ? "<br>\n" : "\n");
300 $allmessage .= "Please, find a summary of the services contracted by you that are about to expire.".($usehtml ? "<br>\n" : "\n").($usehtml ? "<br>\n" : "\n");
301 }
302 $allmessage .= $message.($usehtml ? "<br>\n" : "\n");
303 // $allmessage.= $langs->trans("Total")." = ".price($total,0,$userlang,0,0,-1,$conf->currency).($usehtml?"<br>\n":"\n");
304 if (getDolGlobalString('SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_FOOTER')) {
305 $allmessage .= getDolGlobalString('SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_FOOTER');
306 if (dol_textishtml(getDolGlobalString('SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_FOOTER'))) {
307 $usehtml += 1;
308 }
309 }
310
311 $mail = new CMailFile($subject, $sendto, $from, $allmessage, array(), array(), array(), '', '', 0, $msgishtml);
312
313 $mail->errors_to = $errorsto;
314
315 // Send or not email
316 if ($mode == 'confirm') {
317 $result = $mail->sendfile();
318 if (!$result) {
319 print "Error sending email ".$mail->error."\n";
320 dol_syslog("Error sending email ".$mail->error."\n");
321 }
322 } else {
323 print "No email sent (test mode)\n";
324 dol_syslog("No email sent (test mode)");
325 $mail->dump_mail();
326 $result = 1;
327 }
328
329 unset($newlangs);
330 if ($result) {
331 return 1;
332 } else {
333 return -1;
334 }
335}
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
sendEmailTo($mode, $oldemail, $message, $total, $userlang, $oldtarget, $duration_value)
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_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
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