email_expire_services_to_customers.php 12 KB

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