email_expire_services_to_customers.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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. /**
  22. * \file scripts/contracts/email_expire_services_to_customers.php
  23. * \ingroup facture
  24. * \brief Script to send a mail to customers with services to expire
  25. */
  26. if (!defined('NOSESSION')) define('NOSESSION', '1');
  27. $sapi_type = php_sapi_name();
  28. $script_file = basename(__FILE__);
  29. $path = __DIR__.'/';
  30. // Test si mode batch
  31. $sapi_type = php_sapi_name();
  32. if (substr($sapi_type, 0, 3) == 'cgi') {
  33. echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
  34. exit(-1);
  35. }
  36. if (!isset($argv[1]) || !$argv[1] || !in_array($argv[1], array('test', 'confirm')) || !in_array($argv[2], array('thirdparties', 'contacts'))) {
  37. print "Usage: $script_file (test|confirm) (thirdparties|contacts) [delay] [after]\n";
  38. print "\n";
  39. print "Send an email to customers to remind all contracts services to expire or expired.\n";
  40. print "If you choose 'test' mode, no emails are sent.\n";
  41. print "If you add param delay (nb of days), only services with expired date < today + delay are included.\n";
  42. print "If you add param after (nb of days), only services with expired date >= today + delay are included.\n";
  43. exit(-1);
  44. }
  45. $mode = $argv[1];
  46. $targettype = $argv[2];
  47. require $path."../../htdocs/master.inc.php";
  48. require_once DOL_DOCUMENT_ROOT."/core/class/CMailFile.class.php";
  49. $langs->loadLangs(array('main', 'contracts'));
  50. // Global variables
  51. $version = DOL_VERSION;
  52. $error = 0;
  53. /*
  54. * Main
  55. */
  56. @set_time_limit(0);
  57. print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n";
  58. dol_syslog($script_file." launched with arg ".join(',', $argv));
  59. $now = dol_now('tzserver');
  60. $duration_value = isset($argv[3]) ? $argv[3] : 'none';
  61. $duration_value2 = isset($argv[4]) ? $argv[4] : 'none';
  62. $error = 0;
  63. print $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";
  64. if ($mode != 'confirm') {
  65. $conf->global->MAIN_DISABLE_ALL_MAILS = 1;
  66. }
  67. $sql = "SELECT c.ref, cd.date_fin_validite, cd.total_ttc, cd.description as description, p.label as plabel,";
  68. $sql .= " s.rowid as sid, s.nom as name, s.email, s.default_lang";
  69. if ($targettype == 'contacts')
  70. $sql .= ", sp.rowid as cid, sp.firstname as cfirstname, sp.lastname as clastname, sp.email as cemail";
  71. $sql .= " FROM ".MAIN_DB_PREFIX."societe AS s";
  72. if ($targettype == 'contacts')
  73. $sql .= ", ".MAIN_DB_PREFIX."socpeople as sp";
  74. $sql .= ", ".MAIN_DB_PREFIX."contrat AS c";
  75. $sql .= ", ".MAIN_DB_PREFIX."contratdet AS cd";
  76. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product AS p ON p.rowid = cd.fk_product";
  77. $sql .= " WHERE s.rowid = c.fk_soc AND c.rowid = cd.fk_contrat AND c.statut > 0 AND cd.statut < 5";
  78. if (is_numeric($duration_value2))
  79. $sql .= " AND cd.date_fin_validite >= '".$db->idate(dol_time_plus_duree($now, $duration_value2, "d"))."'";
  80. if (is_numeric($duration_value))
  81. $sql .= " AND cd.date_fin_validite < '".$db->idate(dol_time_plus_duree($now, $duration_value, "d"))."'";
  82. if ($targettype == 'contacts')
  83. $sql .= " AND s.rowid = sp.fk_soc";
  84. $sql .= " ORDER BY";
  85. if ($targettype == 'contacts')
  86. $sql .= " sp.email, sp.rowid,";
  87. $sql .= " s.email ASC, s.rowid ASC, cd.date_fin_validite ASC"; // Order by email to allow one message per email
  88. // print $sql;
  89. $resql = $db->query($sql);
  90. if ($resql) {
  91. $num = $db->num_rows($resql);
  92. $i = 0;
  93. $oldemail = 'none';
  94. $oldsid = 0;
  95. $oldcid = 0;
  96. $oldlang = '';
  97. $total = 0;
  98. $foundtoprocess = 0;
  99. $trackthirdpartiessent = array();
  100. print "We found ".$num." couples (services to expire-".$targettype.") qualified\n";
  101. dol_syslog("We found ".$num." couples (services to expire-".$targettype.") qualified");
  102. $message = '';
  103. $oldtarget = '';
  104. if ($num) {
  105. while ($i < $num) {
  106. $obj = $db->fetch_object($resql);
  107. $newemail = empty($obj->cemail) ? $obj->email : $obj->cemail;
  108. // Check if this record is a break after previous one
  109. $startbreak = false;
  110. if ($newemail != $oldemail || $oldemail == 'none') {
  111. $startbreak = true;
  112. }
  113. if ($obj->sid && $obj->sid != $oldsid) {
  114. $startbreak = true;
  115. }
  116. if ($targettype == 'contacts') {
  117. if ($obj->cid && $obj->cid != $oldcid) {
  118. $startbreak = true;
  119. }
  120. }
  121. if ($startbreak) {
  122. // Break onto sales representative (new email or cid)
  123. if (dol_strlen($oldemail) && $oldemail != 'none' && empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) {
  124. envoi_mail($mode, $oldemail, $message, $total, $oldlang, $oldtarget, $duration_value);
  125. $trackthirdpartiessent[$oldsid.'|'.$oldemail] = 'contact id '.$oldcid;
  126. } else {
  127. if ($oldemail != 'none') {
  128. if (empty($trackthirdpartiessent[$oldsid.'|'.$oldemail]))
  129. print "- No email sent for '".$oldtarget."', total: ".$total."\n";
  130. else print "- No email sent for '".$oldtarget."', total: ".$total." (already sent to ".$trackthirdpartiessent[$oldsid.'|'.$oldemail].")\n";
  131. }
  132. }
  133. $oldemail = $newemail;
  134. $oldsid = $obj->sid;
  135. if ($targettype == 'contacts') {
  136. $oldcid = $obj->cid;
  137. }
  138. $oldlang = $obj->lang;
  139. $oldtarget = (empty($obj->cfirstname) && empty($obj->clastname)) ? $obj->name : ($obj->clastname." ".$obj->cfirstname);
  140. $message = '';
  141. $total = 0;
  142. $foundtoprocess = 0;
  143. // if (empty($newemail)) print "Warning: Customer ".$target." has no email. Notice disabled.\n";
  144. }
  145. // Define line content
  146. $outputlangs = new Translate('', $conf);
  147. $outputlangs->setDefaultLang(empty($obj->default_lang) ? $langs->defaultlang : $obj->default_lang); // By default language of customer
  148. // Load translation files required by the page
  149. $outputlangs->loadLangs(array("main", "contracts", "bills", "products"));
  150. if (dol_strlen($newemail)) {
  151. $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";
  152. dol_syslog("email_expire_services_to_customers.php: ".$newemail." ".$message);
  153. $foundtoprocess++;
  154. }
  155. 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.": ";
  156. if (dol_strlen($newemail))
  157. print "qualified.";
  158. else print "disqualified (no email).";
  159. print "\n";
  160. unset($outputlangs);
  161. $total += $obj->total_ttc;
  162. $i++;
  163. }
  164. // Si il reste des envois en buffer
  165. if ($foundtoprocess) {
  166. if (dol_strlen($oldemail) && $oldemail != 'none' && empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) // Break onto email (new email)
  167. {
  168. envoi_mail($mode, $oldemail, $message, $total, $oldlang, $oldtarget, $duration_value);
  169. $trackthirdpartiessent[$oldsid.'|'.$oldemail] = 'contact id '.$oldcid;
  170. } else {
  171. if ($oldemail != 'none') {
  172. if (empty($trackthirdpartiessent[$oldsid.'|'.$oldemail]))
  173. print "- No email sent for '".$oldtarget."', total: ".$total."\n";
  174. else print "- No email sent for '".$oldtarget."', total: ".$total." (already sent to ".$trackthirdpartiessent[$oldsid.'|'.$oldemail].")\n";
  175. }
  176. }
  177. }
  178. } else {
  179. print "No services to expire found\n";
  180. }
  181. exit(0);
  182. } else {
  183. dol_print_error($db);
  184. dol_syslog("email_expire_services_to_customers.php: Error");
  185. exit(-1);
  186. }
  187. /**
  188. * Send email
  189. *
  190. * @param string $mode Mode (test | confirm)
  191. * @param string $oldemail Target email
  192. * @param string $message Message to send
  193. * @param string $total Total amount of unpayed invoices
  194. * @param string $userlang Code lang to use for email output.
  195. * @param string $oldtarget Target name
  196. * @param int $duration_value duration value
  197. * @return int <0 if KO, >0 if OK
  198. */
  199. function envoi_mail($mode, $oldemail, $message, $total, $userlang, $oldtarget, $duration_value)
  200. {
  201. global $conf, $langs;
  202. if (getenv('DOL_FORCE_EMAIL_TO'))
  203. $oldemail = getenv('DOL_FORCE_EMAIL_TO');
  204. $newlangs = new Translate('', $conf);
  205. $newlangs->setDefaultLang(empty($userlang) ? (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT) : $userlang);
  206. $newlangs->load("main");
  207. $newlangs->load("contracts");
  208. if ($duration_value) {
  209. if ($duration_value > 0)
  210. $title = $newlangs->transnoentities("ListOfServicesToExpireWithDuration", $duration_value);
  211. else $title = $newlangs->transnoentities("ListOfServicesToExpireWithDurationNeg", $duration_value);
  212. } else $title = $newlangs->transnoentities("ListOfServicesToExpire");
  213. $subject = (empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_SUBJECT) ? $title : $conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_SUBJECT);
  214. $sendto = $oldemail;
  215. $from = $conf->global->MAIN_MAIL_EMAIL_FROM;
  216. $errorsto = $conf->global->MAIN_MAIL_ERRORS_TO;
  217. $msgishtml = - 1;
  218. print "- Send email to '".$oldtarget."' (".$oldemail."), total: ".$total."\n";
  219. dol_syslog("email_expire_services_to_customers.php: send mail to ".$oldemail);
  220. $usehtml = 0;
  221. if (dol_textishtml($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_FOOTER))
  222. $usehtml += 1;
  223. if (dol_textishtml($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_HEADER))
  224. $usehtml += 1;
  225. $allmessage = '';
  226. if (!empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_HEADER)) {
  227. $allmessage .= $conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_HEADER;
  228. } else {
  229. $allmessage .= "Dear customer".($usehtml ? "<br>\n" : "\n").($usehtml ? "<br>\n" : "\n");
  230. $allmessage .= "Please, find a summary of the services contracted by you that are about to expire.".($usehtml ? "<br>\n" : "\n").($usehtml ? "<br>\n" : "\n");
  231. }
  232. $allmessage .= $message.($usehtml ? "<br>\n" : "\n");
  233. // $allmessage.= $langs->trans("Total")." = ".price($total,0,$userlang,0,0,-1,$conf->currency).($usehtml?"<br>\n":"\n");
  234. if (!empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_FOOTER)) {
  235. $allmessage .= $conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_FOOTER;
  236. if (dol_textishtml($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_FOOTER))
  237. $usehtml += 1;
  238. }
  239. $mail = new CMailFile($subject, $sendto, $from, $allmessage, array(), array(), array(), '', '', 0, $msgishtml);
  240. $mail->errors_to = $errorsto;
  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. unset($newlangs);
  255. if ($result) {
  256. return 1;
  257. } else {
  258. return -1;
  259. }
  260. }