dolibarr 18.0.6
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 *
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[1]) || !$argv[1] || !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 contracts services to expire or expired.\n";
47 print "If you choose 'test' mode, no emails are sent.\n";
48 print "If you add param delay (nb of days), only services with expired date < today + delay are included.\n";
49 print "If you add param after (nb of days), only services with expired 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->loadLangs(array('main', 'contracts'));
59
60// Global variables
61$version = DOL_VERSION;
62$error = 0;
63
64/*
65 * Main
66 */
67
68@set_time_limit(0);
69print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n";
70dol_syslog($script_file." launched with arg ".join(',', $argv));
71
72$now = dol_now('tzserver');
73$duration_value = isset($argv[3]) ? $argv[3] : 'none';
74$duration_value2 = isset($argv[4]) ? $argv[4] : 'none';
75
76$error = 0;
77print $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";
78
79if ($mode != 'confirm') {
80 $conf->global->MAIN_DISABLE_ALL_MAILS = 1;
81}
82
83$sql = "SELECT c.ref, cd.date_fin_validite, cd.total_ttc, cd.description as description, p.label as plabel,";
84$sql .= " s.rowid as sid, s.nom as name, s.email, s.default_lang";
85if ($targettype == 'contacts') {
86 $sql .= ", sp.rowid as cid, sp.firstname as cfirstname, sp.lastname as clastname, sp.email as cemail";
87}
88$sql .= " FROM ".MAIN_DB_PREFIX."societe AS s";
89if ($targettype == 'contacts') {
90 $sql .= ", ".MAIN_DB_PREFIX."socpeople as sp";
91}
92$sql .= ", ".MAIN_DB_PREFIX."contrat AS c";
93$sql .= ", ".MAIN_DB_PREFIX."contratdet AS cd";
94$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product AS p ON p.rowid = cd.fk_product";
95$sql .= " WHERE s.rowid = c.fk_soc AND c.rowid = cd.fk_contrat AND c.statut > 0 AND cd.statut < 5";
96if (is_numeric($duration_value2)) {
97 $sql .= " AND cd.date_fin_validite >= '".$db->idate(dol_time_plus_duree($now, $duration_value2, "d"))."'";
98}
99if (is_numeric($duration_value)) {
100 $sql .= " AND cd.date_fin_validite < '".$db->idate(dol_time_plus_duree($now, $duration_value, "d"))."'";
101}
102if ($targettype == 'contacts') {
103 $sql .= " AND s.rowid = sp.fk_soc";
104}
105$sql .= " ORDER BY";
106if ($targettype == 'contacts') {
107 $sql .= " sp.email, sp.rowid,";
108}
109$sql .= " s.email ASC, s.rowid ASC, cd.date_fin_validite ASC"; // Order by email to allow one message per email
110
111// print $sql;
112$resql = $db->query($sql);
113if ($resql) {
114 $num = $db->num_rows($resql);
115 $i = 0;
116 $oldemail = 'none';
117 $oldsid = 0;
118 $oldcid = 0;
119 $oldlang = '';
120 $total = 0;
121 $foundtoprocess = 0;
122 $trackthirdpartiessent = array();
123
124 print "We found ".$num." couples (services to expire-".$targettype.") qualified\n";
125 dol_syslog("We found ".$num." couples (services to expire-".$targettype.") qualified");
126 $message = '';
127 $oldtarget = '';
128
129 if ($num) {
130 while ($i < $num) {
131 $obj = $db->fetch_object($resql);
132
133 $newemail = empty($obj->cemail) ? $obj->email : $obj->cemail;
134
135 // Check if this record is a break after previous one
136 $startbreak = false;
137 if ($newemail != $oldemail || $oldemail == 'none') {
138 $startbreak = true;
139 }
140 if ($obj->sid && $obj->sid != $oldsid) {
141 $startbreak = true;
142 }
143 if ($targettype == 'contacts') {
144 if ($obj->cid && $obj->cid != $oldcid) {
145 $startbreak = true;
146 }
147 }
148
149 if ($startbreak) {
150 // Break onto sales representative (new email or cid)
151 if (dol_strlen($oldemail) && $oldemail != 'none' && empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) {
152 sendEmailTo($mode, $oldemail, $message, $total, $oldlang, $oldtarget, $duration_value);
153 $trackthirdpartiessent[$oldsid.'|'.$oldemail] = 'contact id '.$oldcid;
154 } else {
155 if ($oldemail != 'none') {
156 if (empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) {
157 print "- No email sent for '".$oldtarget."', total: ".$total."\n";
158 } else {
159 print "- No email sent for '".$oldtarget."', total: ".$total." (already sent to ".$trackthirdpartiessent[$oldsid.'|'.$oldemail].")\n";
160 }
161 }
162 }
163 $oldemail = $newemail;
164 $oldsid = $obj->sid;
165 if ($targettype == 'contacts') {
166 $oldcid = $obj->cid;
167 }
168 $oldlang = $obj->default_lang;
169 $oldtarget = (empty($obj->cfirstname) && empty($obj->clastname)) ? $obj->name : ($obj->clastname." ".$obj->cfirstname);
170 $message = '';
171 $total = 0;
172 $foundtoprocess = 0;
173 // if (empty($newemail)) print "Warning: Customer ".$target." has no email. Notice disabled.\n";
174 }
175
176 // Define line content
177 $outputlangs = new Translate('', $conf);
178 $outputlangs->setDefaultLang(empty($obj->default_lang) ? $langs->defaultlang : $obj->default_lang); // By default language of customer
179
180 // Load translation files required by the page
181 $outputlangs->loadLangs(array("main", "contracts", "bills", "products"));
182
183 if (dol_strlen($newemail)) {
184 $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";
185 dol_syslog("email_expire_services_to_customers.php: ".$newemail." ".$message);
186 $foundtoprocess++;
187 }
188 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.": ";
189 if (dol_strlen($newemail)) {
190 print "qualified.";
191 } else {
192 print "disqualified (no email).";
193 }
194 print "\n";
195
196 unset($outputlangs);
197
198 $total += $obj->total_ttc;
199
200 $i++;
201 }
202
203 // Si il reste des envois en buffer
204 if ($foundtoprocess) {
205 if (dol_strlen($oldemail) && $oldemail != 'none' && empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) { // Break onto email (new email)
206 sendEmailTo($mode, $oldemail, $message, $total, $oldlang, $oldtarget, $duration_value);
207 $trackthirdpartiessent[$oldsid.'|'.$oldemail] = 'contact id '.$oldcid;
208 } else {
209 if ($oldemail != 'none') {
210 if (empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) {
211 print "- No email sent for '".$oldtarget."', total: ".$total."\n";
212 } else {
213 print "- No email sent for '".$oldtarget."', total: ".$total." (already sent to ".$trackthirdpartiessent[$oldsid.'|'.$oldemail].")\n";
214 }
215 }
216 }
217 }
218 } else {
219 print "No services to expire found\n";
220 }
221
222 exit(0);
223} else {
224 dol_print_error($db);
225 dol_syslog("email_expire_services_to_customers.php: Error");
226
227 exit(-1);
228}
229
242function sendEmailTo($mode, $oldemail, $message, $total, $userlang, $oldtarget, $duration_value)
243{
244 global $conf, $langs;
245
246 if (getenv('DOL_FORCE_EMAIL_TO')) {
247 $oldemail = getenv('DOL_FORCE_EMAIL_TO');
248 }
249
250 $newlangs = new Translate('', $conf);
251 $newlangs->setDefaultLang(empty($userlang) ? (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT) : $userlang);
252 $newlangs->load("main");
253 $newlangs->load("contracts");
254
255 if ($duration_value) {
256 if ($duration_value > 0) {
257 $title = $newlangs->transnoentities("ListOfServicesToExpireWithDuration", $duration_value);
258 } else {
259 $title = $newlangs->transnoentities("ListOfServicesToExpireWithDurationNeg", $duration_value);
260 }
261 } else {
262 $title = $newlangs->transnoentities("ListOfServicesToExpire");
263 }
264
265 $subject = (empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_SUBJECT) ? $title : $conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_SUBJECT);
266 $sendto = $oldemail;
267 $from = $conf->global->MAIN_MAIL_EMAIL_FROM;
268 $errorsto = $conf->global->MAIN_MAIL_ERRORS_TO;
269 $msgishtml = - 1;
270
271 print "- Send email to '".$oldtarget."' (".$oldemail."), total: ".$total."\n";
272 dol_syslog("email_expire_services_to_customers.php: send mail to ".$oldemail);
273
274 $usehtml = 0;
275 if (dol_textishtml($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_FOOTER)) {
276 $usehtml += 1;
277 }
278 if (dol_textishtml($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_HEADER)) {
279 $usehtml += 1;
280 }
281
282 $allmessage = '';
283 if (!empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_HEADER)) {
284 $allmessage .= $conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_HEADER;
285 } else {
286 $allmessage .= "Dear customer".($usehtml ? "<br>\n" : "\n").($usehtml ? "<br>\n" : "\n");
287 $allmessage .= "Please, find a summary of the services contracted by you that are about to expire.".($usehtml ? "<br>\n" : "\n").($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 (!empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_FOOTER)) {
292 $allmessage .= $conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_FOOTER;
293 if (dol_textishtml($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_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:122
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...
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
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_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_now($mode='auto')
Return date for now.
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_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.