dolibarr 21.0.0-alpha
email_expire_services_to_representatives.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'))) {
46 print "Usage: $script_file (test|confirm) [delay]\n";
47 print "\n";
48 print "Send an email to remind all contracts services to expire, to users that are sale representative for.\n";
49 print "If you choose 'test' mode, no emails are sent.\n";
50 print "If you add a delay (nb of days), only services with expired date < today + delay are included.\n";
51 exit(1);
52}
53$mode = $argv[1];
54
55require $path."../../htdocs/master.inc.php";
56require_once DOL_DOCUMENT_ROOT.'/core/lib/functionscli.lib.php';
57require_once DOL_DOCUMENT_ROOT."/core/class/CMailFile.class.php";
58
59$langs->loadLangs(array('main', 'contracts'));
60
61// Global variables
62$version = DOL_VERSION;
63$error = 0;
64
65$hookmanager->initHooks(array('cli'));
66
67
68/*
69 * Main
70 */
71
72@set_time_limit(0);
73print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n";
74dol_syslog($script_file." launched with arg ".join(',', $argv));
75
76$now = dol_now('tzserver');
77$duration_value = isset($argv[2]) ? $argv[2] : 'none';
78
79print $script_file." launched with mode ".$mode." default lang=".$langs->defaultlang.(is_numeric($duration_value) ? " delay=".$duration_value : "")."\n";
80
81if ($mode != 'confirm') {
82 $conf->global->MAIN_DISABLE_ALL_MAILS = 1;
83}
84
87$sql = "SELECT DISTINCT c.ref, c.fk_soc, cd.date_fin_validite, cd.total_ttc, cd.description as description, p.label as plabel, s.rowid, s.nom as name, s.email, s.default_lang,";
88$sql .= " u.rowid as uid, u.lastname, u.firstname, u.email, u.lang";
89$sql .= " FROM ".MAIN_DB_PREFIX."societe AS s, ".MAIN_DB_PREFIX."contrat AS c, ".MAIN_DB_PREFIX."contratdet AS cd";
90$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product AS p ON p.rowid = cd.fk_product, ".MAIN_DB_PREFIX."societe_commerciaux AS sc, ".MAIN_DB_PREFIX."user AS u";
91$sql .= " WHERE s.rowid = c.fk_soc AND c.rowid = cd.fk_contrat AND c.statut > 0 AND cd.statut<5";
92if (is_numeric($duration_value)) {
93 $sql .= " AND cd.date_fin_validite < '".$db->idate(dol_time_plus_duree($now, (int) $duration_value, "d"))."'";
94}
95$sql .= " AND sc.fk_soc = s.rowid AND sc.fk_user = u.rowid";
96$sql .= " ORDER BY u.email ASC, s.rowid ASC, c.ref ASC"; // Order by email to allow one message per email
97
98$resql = $db->query($sql);
99if ($resql) {
100 $num = $db->num_rows($resql);
101 $i = 0;
102 $oldemail = 'none';
103 $oldsalerepresentative = '';
104 $olduid = 0;
105 $oldlang = '';
106 $total = 0;
107 $foundtoprocess = 0;
108 print "We found ".$num." couples (services to expire - sale representative) qualified\n";
109 dol_syslog("We found ".$num." couples (services to expire - sale representative) qualified");
110 $message = '';
111
112 if ($num) {
113 while ($i < $num) {
114 $obj = $db->fetch_object($resql);
115
116 if (($obj->email != $oldemail || $obj->uid != $olduid) || $oldemail == 'none') {
117 // Break onto sales representative (new email or uid)
118 if (dol_strlen($oldemail) && $oldemail != 'none') {
119 sendEmailTo($mode, $oldemail, $message, price2num($total), $oldlang, $oldsalerepresentative, (int) $duration_value);
120 } else {
121 if ($oldemail != 'none') {
122 print "- No email sent for ".$oldsalerepresentative.", total: ".$total."\n";
123 }
124 }
125 $oldemail = $obj->email;
126 $olduid = $obj->uid;
127 $oldlang = $obj->lang;
128 $oldsalerepresentative = dolGetFirstLastname($obj->firstname, $obj->lastname);
129 $message = '';
130 $total = 0;
131 $foundtoprocess = 0;
132 $salerepresentative = dolGetFirstLastname($obj->firstname, $obj->lastname);
133 if (empty($obj->email)) {
134 print "Warning: Sale representative ".$salerepresentative." has no email. Notice disabled.\n";
135 }
136 }
137
138 // Define line content
139 $outputlangs = new Translate('', $conf);
140 $outputlangs->setDefaultLang(empty($obj->lang) ? $langs->defaultlang : $obj->lang); // By default language of sale representative
141
142 // Load translation files required by the page
143 $outputlangs->loadLangs(array("main", "contracts", "bills", "products"));
144
145 if (dol_strlen($obj->email)) {
146 $message .= $outputlangs->trans("Contract")." ".$obj->ref.": ".$langs->trans("Service")." ".dol_concatdesc($obj->plabel, $obj->description)." (".price($obj->total_ttc, 0, $outputlangs, 0, 0, -1, $conf->currency).") ".$obj->name.", ".$outputlangs->trans("DateEndPlannedShort")." ".dol_print_date($db->jdate($obj->date_fin_validite), 'day')."\n\n";
147 dol_syslog("email_expire_services_to_representatives.php: ".$obj->email);
148 $foundtoprocess++;
149 }
150 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')." (linked to company ".$obj->name.", sale representative ".dolGetFirstLastname($obj->firstname, $obj->lastname).", email ".$obj->email."): ";
151 if (dol_strlen($obj->email)) {
152 print "qualified.";
153 } else {
154 print "disqualified (no email).";
155 }
156 print "\n";
157
158 unset($outputlangs);
159
160 $total += $obj->total_ttc;
161 $i++;
162 }
163
164 // If there are remaining messages to send in the buffer
165 if ($foundtoprocess) {
166 if (dol_strlen($oldemail) && $oldemail != 'none') { // Break onto email (new email)
167 sendEmailTo($mode, $oldemail, $message, price2num($total), $oldlang, $oldsalerepresentative, (int) $duration_value);
168 } else {
169 if ($oldemail != 'none') {
170 print "- No email sent for ".$oldsalerepresentative.", total: ".$total."\n";
171 }
172 }
173 }
174 } else {
175 print "No services to expire (for companies linked to a particular commercial dolibarr user) found\n";
176 }
177
178 exit(0);
179} else {
180 dol_print_error($db);
181 dol_syslog("email_expire_services_to_representatives.php: Error");
182
183 exit(1);
184}
185
198function sendEmailTo($mode, $oldemail, $message, $total, $userlang, $oldtarget, $duration_value)
199{
200 global $conf, $langs;
201
202 if (getenv('DOL_FORCE_EMAIL_TO')) {
203 $oldemail = getenv('DOL_FORCE_EMAIL_TO');
204 }
205
206 $newlangs = new Translate('', $conf);
207 $newlangs->setDefaultLang(empty($userlang) ? getDolGlobalString('MAIN_LANG_DEFAULT', 'auto') : $userlang);
208 $newlangs->load("main");
209 $newlangs->load("contracts");
210
211 if ($duration_value) {
212 if ($duration_value > 0) {
213 $title = $newlangs->transnoentities("ListOfServicesToExpireWithDuration", $duration_value);
214 } else {
215 $title = $newlangs->transnoentities("ListOfServicesToExpireWithDurationNeg", $duration_value);
216 }
217 } else {
218 $title = $newlangs->transnoentities("ListOfServicesToExpire");
219 }
220
221 $subject = getDolGlobalString('SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_SUBJECT', $title);
222 $sendto = $oldemail;
223 $from = getDolGlobalString('MAIN_MAIL_EMAIL_FROM');
224 $errorsto = getDolGlobalString('MAIN_MAIL_ERRORS_TO');
225 $msgishtml = -1;
226
227 print "- Send email for ".$oldtarget." (".$oldemail."), total: ".$total."\n";
228 dol_syslog("email_expire_services_to_representatives.php: send mail to ".$oldemail);
229
230 $usehtml = 0;
231 if (getDolGlobalString('SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_FOOTER') && dol_textishtml(getDolGlobalString('SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_FOOTER'))) {
232 $usehtml += 1;
233 }
234 if (getDolGlobalString('SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_HEADER') && dol_textishtml(getDolGlobalString('SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_HEADER'))) {
235 $usehtml += 1;
236 }
237
238 $allmessage = '';
239 if (getDolGlobalString('SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_HEADER')) {
240 $allmessage .= getDolGlobalString('SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_HEADER');
241 } else {
242 $allmessage .= $title.($usehtml ? "<br>\n" : "\n").($usehtml ? "<br>\n" : "\n");
243 $allmessage .= $newlangs->transnoentities("NoteListOfYourExpiredServices").($usehtml ? "<br>\n" : "\n").($usehtml ? "<br>\n" : "\n");
244 }
245 $allmessage .= $message.($usehtml ? "<br>\n" : "\n");
246 $allmessage .= $langs->trans("Total")." = ".price($total, 0, $userlang, 0, 0, -1, $conf->currency).($usehtml ? "<br>\n" : "\n");
247 if (getDolGlobalString('SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_FOOTER')) {
248 $allmessage .= getDolGlobalString('SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_FOOTER');
249 if (dol_textishtml(getDolGlobalString('SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_FOOTER'))) {
250 $usehtml += 1;
251 }
252 }
253
254 $mail = new CMailFile($subject, $sendto, $from, $allmessage, array(), array(), array(), '', '', 0, $msgishtml);
255
256 $mail->errors_to = $errorsto;
257
258 // Send or not email
259 if ($mode == 'confirm') {
260 $result = $mail->sendfile();
261 if (!$result) {
262 print "Error sending email ".$mail->error."\n";
263 dol_syslog("Error sending email ".$mail->error."\n");
264 }
265 } else {
266 print "No email sent (test mode)\n";
267 dol_syslog("No email sent (test mode)");
268 $mail->dump_mail();
269 $result = 1;
270 }
271
272 if ($result) {
273 return 1;
274 } else {
275 return -1;
276 }
277}
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).
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
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.