email_expire_services_to_customers.php 12 KB

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