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