dolibarr  18.0.0
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  *
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 
28 if (!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();
38 if (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 
43 if (!isset($argv[1]) || !$argv[1] || !in_array($argv[1], array('test', 'confirm'))) {
44  print "Usage: $script_file (test|confirm) [delay]\n";
45  print "\n";
46  print "Send an email to remind all contracts services to expire, to users that are sale representative for.\n";
47  print "If you choose 'test' mode, no emails are sent.\n";
48  print "If you add a delay (nb of days), only services with expired date < today + delay are included.\n";
49  exit(-1);
50 }
51 $mode = $argv[1];
52 
53 require $path."../../htdocs/master.inc.php";
54 require_once DOL_DOCUMENT_ROOT."/core/class/CMailFile.class.php";
55 
56 $langs->loadLangs(array('main', 'contracts'));
57 
58 // Global variables
59 $version = DOL_VERSION;
60 $error = 0;
61 
62 /*
63  * Main
64  */
65 
66 @set_time_limit(0);
67 print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n";
68 dol_syslog($script_file." launched with arg ".join(',', $argv));
69 
70 $now = dol_now('tzserver');
71 $duration_value = isset($argv[2]) ? $argv[2] : 'none';
72 
73 print $script_file." launched with mode ".$mode." default lang=".$langs->defaultlang.(is_numeric($duration_value) ? " delay=".$duration_value : "")."\n";
74 
75 if ($mode != 'confirm') {
76  $conf->global->MAIN_DISABLE_ALL_MAILS = 1;
77 }
78 
79 $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,";
80 $sql .= " u.rowid as uid, u.lastname, u.firstname, u.email, u.lang";
81 $sql .= " FROM ".MAIN_DB_PREFIX."societe AS s, ".MAIN_DB_PREFIX."contrat AS c, ".MAIN_DB_PREFIX."contratdet AS cd";
82 $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";
83 $sql .= " WHERE s.rowid = c.fk_soc AND c.rowid = cd.fk_contrat AND c.statut > 0 AND cd.statut<5";
84 if (is_numeric($duration_value)) {
85  $sql .= " AND cd.date_fin_validite < '".$db->idate(dol_time_plus_duree($now, $duration_value, "d"))."'";
86 }
87 $sql .= " AND sc.fk_soc = s.rowid AND sc.fk_user = u.rowid";
88 $sql .= " ORDER BY u.email ASC, s.rowid ASC, c.ref ASC"; // Order by email to allow one message per email
89 
90 // print $sql;
91 $resql = $db->query($sql);
92 if ($resql) {
93  $num = $db->num_rows($resql);
94  $i = 0;
95  $oldemail = 'none';
96  $oldsalerepresentative = '';
97  $olduid = 0;
98  $oldlang = '';
99  $total = 0;
100  $foundtoprocess = 0;
101  print "We found ".$num." couples (services to expire - sale representative) qualified\n";
102  dol_syslog("We found ".$num." couples (services to expire - sale representative) qualified");
103  $message = '';
104 
105  if ($num) {
106  while ($i < $num) {
107  $obj = $db->fetch_object($resql);
108 
109  if (($obj->email != $oldemail || $obj->uid != $olduid) || $oldemail == 'none') {
110  // Break onto sales representative (new email or uid)
111  if (dol_strlen($oldemail) && $oldemail != 'none') {
112  sendEmailTo($mode, $oldemail, $message, $total, $oldlang, $oldsalerepresentative, $duration_value);
113  } else {
114  if ($oldemail != 'none') {
115  print "- No email sent for ".$oldsalerepresentative.", total: ".$total."\n";
116  }
117  }
118  $oldemail = $obj->email;
119  $olduid = $obj->uid;
120  $oldlang = $obj->lang;
121  $oldsalerepresentative = dolGetFirstLastname($obj->firstname, $obj->lastname);
122  $message = '';
123  $total = 0;
124  $foundtoprocess = 0;
125  $salerepresentative = dolGetFirstLastname($obj->firstname, $obj->lastname);
126  if (empty($obj->email)) {
127  print "Warning: Sale representative ".$salerepresentative." has no email. Notice disabled.\n";
128  }
129  }
130 
131  // Define line content
132  $outputlangs = new Translate('', $conf);
133  $outputlangs->setDefaultLang(empty($obj->lang) ? $langs->defaultlang : $obj->lang); // By default language of sale representative
134 
135  // Load translation files required by the page
136  $outputlangs->loadLangs(array("main", "contracts", "bills", "products"));
137 
138  if (dol_strlen($obj->email)) {
139  $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";
140  dol_syslog("email_expire_services_to_representatives.php: ".$obj->email);
141  $foundtoprocess++;
142  }
143  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."): ";
144  if (dol_strlen($obj->email)) {
145  print "qualified.";
146  } else {
147  print "disqualified (no email).";
148  }
149  print "\n";
150 
151  unset($outputlangs);
152 
153  $total += $obj->total_ttc;
154  $i++;
155  }
156 
157  // Si il reste des envois en buffer
158  if ($foundtoprocess) {
159  if (dol_strlen($oldemail) && $oldemail != 'none') { // Break onto email (new email)
160  sendEmailTo($mode, $oldemail, $message, $total, $oldlang, $oldsalerepresentative, $duration_value);
161  } else {
162  if ($oldemail != 'none') {
163  print "- No email sent for ".$oldsalerepresentative.", total: ".$total."\n";
164  }
165  }
166  }
167  } else {
168  print "No services to expire (for companies linked to a particular commercial dolibarr user) found\n";
169  }
170 
171  exit(0);
172 } else {
173  dol_print_error($db);
174  dol_syslog("email_expire_services_to_representatives.php: Error");
175 
176  exit(-1);
177 }
178 
191 function sendEmailTo($mode, $oldemail, $message, $total, $userlang, $oldtarget, $duration_value)
192 {
193  global $conf, $langs;
194 
195  if (getenv('DOL_FORCE_EMAIL_TO')) {
196  $oldemail = getenv('DOL_FORCE_EMAIL_TO');
197  }
198 
199  $newlangs = new Translate('', $conf);
200  $newlangs->setDefaultLang(empty($userlang) ? (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT) : $userlang);
201  $newlangs->load("main");
202  $newlangs->load("contracts");
203 
204  if ($duration_value) {
205  if ($duration_value > 0) {
206  $title = $newlangs->transnoentities("ListOfServicesToExpireWithDuration", $duration_value);
207  } else {
208  $title = $newlangs->transnoentities("ListOfServicesToExpireWithDurationNeg", $duration_value);
209  }
210  } else {
211  $title = $newlangs->transnoentities("ListOfServicesToExpire");
212  }
213 
214  $subject = (empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_SUBJECT) ? $title : $conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_SUBJECT);
215  $sendto = $oldemail;
216  $from = empty($conf->global->MAIN_MAIL_EMAIL_FROM) ? '' : $conf->global->MAIN_MAIL_EMAIL_FROM;
217  $errorsto = empty($conf->global->MAIN_MAIL_ERRORS_TO) ? '' : $conf->global->MAIN_MAIL_ERRORS_TO;
218  $msgishtml = - 1;
219 
220  print "- Send email for ".$oldtarget." (".$oldemail."), total: ".$total."\n";
221  dol_syslog("email_expire_services_to_representatives.php: send mail to ".$oldemail);
222 
223  $usehtml = 0;
224  if (!empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_FOOTER) && dol_textishtml($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_FOOTER)) {
225  $usehtml += 1;
226  }
227  if (!empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_HEADER) && dol_textishtml($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_HEADER)) {
228  $usehtml += 1;
229  }
230 
231  $allmessage = '';
232  if (!empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_HEADER)) {
233  $allmessage .= $conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_HEADER;
234  } else {
235  $allmessage .= $title.($usehtml ? "<br>\n" : "\n").($usehtml ? "<br>\n" : "\n");
236  $allmessage .= $newlangs->transnoentities("NoteListOfYourExpiredServices").($usehtml ? "<br>\n" : "\n").($usehtml ? "<br>\n" : "\n");
237  }
238  $allmessage .= $message.($usehtml ? "<br>\n" : "\n");
239  $allmessage .= $langs->trans("Total")." = ".price($total, 0, $userlang, 0, 0, - 1, $conf->currency).($usehtml ? "<br>\n" : "\n");
240  if (!empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_FOOTER)) {
241  $allmessage .= $conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_FOOTER;
242  if (dol_textishtml($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_FOOTER)) {
243  $usehtml += 1;
244  }
245  }
246 
247  $mail = new CMailFile($subject, $sendto, $from, $allmessage, array(), array(), array(), '', '', 0, $msgishtml);
248 
249  $mail->errors_to = $errorsto;
250 
251  // Send or not email
252  if ($mode == 'confirm') {
253  $result = $mail->sendfile();
254  if (!$result) {
255  print "Error sending email ".$mail->error."\n";
256  dol_syslog("Error sending email ".$mail->error."\n");
257  }
258  } else {
259  print "No email sent (test mode)\n";
260  dol_syslog("No email sent (test mode)");
261  $mail->dump_mail();
262  $result = 1;
263  }
264 
265  if ($result) {
266  return 1;
267  } else {
268  return -1;
269  }
270 }
dol_print_error
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
Definition: functions.lib.php:5107
dol_getmypid
dol_getmypid()
Return getmypid() or random PID when function is disabled Some web hosts disable this php function fo...
Definition: functions.lib.php:9997
Translate
Class to manage translations.
Definition: translate.class.php:30
CMailFile
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Definition: CMailFile.class.php:41
dol_print_date
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
Definition: functions.lib.php:2675
dol_concatdesc
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...
Definition: functions.lib.php:7734
dol_syslog
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
Definition: functions.lib.php:1741
$sql
if(isModEnabled('facture') && $user->hasRight('facture', 'lire')) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') && $user->hasRight('don', 'lire')) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $sql
Social contributions to pay.
Definition: index.php:746
dol_strlen
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
Definition: functions.lib.php:3997
dolGetFirstLastname
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
Definition: functions.lib.php:8590
dol_time_plus_duree
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition: date.lib.php:122
dol_now
dol_now($mode='auto')
Return date for now.
Definition: functions.lib.php:3056
price
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.
Definition: functions.lib.php:5829
dol_textishtml
dol_textishtml($msg, $option=0)
Return if a text is a html content.
Definition: functions.lib.php:7667
sendEmailTo
sendEmailTo($mode, $oldemail, $message, $total, $userlang, $oldtarget, $duration_value)
Send email.
Definition: email_expire_services_to_representatives.php:191