email_unpaid_invoices_to_customers.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. #!/usr/bin/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/invoices/email_unpaid_invoices_to_customers.php
  23. * \ingroup facture
  24. * \brief Script to send a mail to customers with unpaid invoices
  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[2]) || ! $argv[2] || ! 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 unpaid customer invoices.\n";
  40. print "If you choose 'test' mode, no emails are sent.\n";
  41. print "If you add param delay (nb of days), only invoice with due date < today + delay are included.\n";
  42. print "If you add param after (nb of days), only invoice with due 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. // Global variables
  51. $version=DOL_VERSION;
  52. $error=0;
  53. /*
  54. * Main
  55. */
  56. @set_time_limit(0);
  57. print "***** ".$script_file." (".$version.") pid=".getmypid()." *****\n";
  58. $now=dol_now('tzserver');
  59. $duration_value=isset($argv[3])?$argv[3]:'none';
  60. $duration_value2=isset($argv[4])?$argv[4]:'none';
  61. $error = 0;
  62. 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";
  63. if ($mode != 'confirm') $conf->global->MAIN_DISABLE_ALL_MAILS=1;
  64. $sql = "SELECT f.facnumber, f.total_ttc, f.date_lim_reglement as due_date,";
  65. $sql.= " s.rowid as sid, s.nom as name, s.email, s.default_lang";
  66. if ($targettype == 'contacts') $sql.= ", sp.rowid as cid, sp.firstname as cfirstname, sp.lastname as clastname, sp.email as cemail";
  67. $sql.= " FROM ".MAIN_DB_PREFIX."facture as f, ".MAIN_DB_PREFIX."societe as s";
  68. if ($targettype == 'contacts') $sql.= ", ".MAIN_DB_PREFIX."socpeople as sp";
  69. $sql.= " WHERE f.fk_statut = 1 AND f.paye = 0";
  70. $sql.= " AND f.fk_soc = s.rowid";
  71. if (is_numeric($duration_value2)) $sql.= " AND f.date_lim_reglement >= '".$db->idate(dol_time_plus_duree($now, $duration_value2, "d"))."'";
  72. if (is_numeric($duration_value)) $sql.= " AND f.date_lim_reglement < '".$db->idate(dol_time_plus_duree($now, $duration_value, "d"))."'";
  73. if ($targettype == 'contacts') $sql.= " AND s.rowid = sp.fk_soc";
  74. $sql.= " ORDER BY";
  75. if ($targettype == 'contacts') $sql.= " sp.email, sp.rowid,";
  76. $sql.= " s.email ASC, s.rowid ASC, f.facnumber ASC"; // Order by email to allow one message per email
  77. //print $sql;
  78. $resql=$db->query($sql);
  79. if ($resql)
  80. {
  81. $num = $db->num_rows($resql);
  82. $i = 0;
  83. $oldemail = 'none'; $oldsid = 0; $oldcid = 0; $oldlang='';
  84. $total = 0; $foundtoprocess = 0;
  85. $trackthirdpartiessent = array();
  86. print "We found ".$num." couples (unpayed validated invoices-".$targettype.") qualified\n";
  87. dol_syslog("We found ".$num." couples (unpayed validated invoices-".$targettype.") qualified");
  88. $message='';
  89. if ($num)
  90. {
  91. while ($i < $num)
  92. {
  93. $obj = $db->fetch_object($resql);
  94. $newemail=empty($obj->cemail)?$obj->email:$obj->cemail;
  95. // Check if this record is a break after previous one
  96. $startbreak=false;
  97. if ($newemail <> $oldemail || $oldemail == 'none') $startbreak=true;
  98. if ($obj->sid && $obj->sid <> $oldsid) $startbreak=true;
  99. if ($obj->cid && $obj->cid <> $oldcid) $startbreak=true;
  100. if ($startbreak)
  101. {
  102. // Break onto sales representative (new email or cid)
  103. if (dol_strlen($oldemail) && $oldemail != 'none' && empty($trackthirdpartiessent[$oldsid.'|'.$oldemail]))
  104. {
  105. envoi_mail($mode,$oldemail,$message,$total,$oldlang,$oldtarget);
  106. $trackthirdpartiessent[$oldsid.'|'.$oldemail]='contact id '.$oldcid;
  107. }
  108. else
  109. {
  110. if ($oldemail != 'none')
  111. {
  112. if (empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) print "- No email sent for '".$oldtarget."', total: ".$total."\n";
  113. else print "- No email sent for '".$oldtarget."', total: ".$total." (already sent to ".$trackthirdpartiessent[$oldsid.'|'.$oldemail].")\n";
  114. }
  115. }
  116. $oldemail = $newemail;
  117. $oldsid = $obj->sid;
  118. $oldcid = $obj->cid;
  119. $oldlang = $obj->lang;
  120. $oldtarget=(empty($obj->cfirstname) && empty($obj->clastname))?$obj->name:($obj->clastname." ".$obj->cfirstname);
  121. $message = '';
  122. $total = 0;
  123. $foundtoprocess = 0;
  124. $target=(empty($obj->cfirstname) && empty($obj->clastname))?$obj->name:($obj->clastname." ".$obj->cfirstname);
  125. //if (empty($newemail)) print "Warning: Customer ".$target." has no email. Notice disabled.\n";
  126. }
  127. // Define line content
  128. $outputlangs=new Translate('',$conf);
  129. $outputlangs->setDefaultLang(empty($obj->default_lang)?$langs->defaultlang:$obj->default_lang); // By default language of customer
  130. $outputlangs->load("bills");
  131. $outputlangs->load("main");
  132. if (dol_strlen($newemail))
  133. {
  134. $message .= $outputlangs->trans("Invoice")." ".$obj->facnumber." : ".price($obj->total_ttc,0,$outputlangs,0,0,-1,$conf->currency)."\n";
  135. dol_syslog("email_unpaid_invoices_to_customers.php: ".$newemail." ".$message);
  136. $foundtoprocess++;
  137. }
  138. print "Unpaid invoice ".$obj->facnumber.", price ".price2num($obj->total_ttc).", due date ".dol_print_date($db->jdate($obj->due_date),'day')." customer id ".$obj->sid." ".$obj->name.", ".($obj->cid?"contact id ".$obj->cid." ".$obj->clastname." ".$obj->cfirstname.",":"")." email ".$newemail." lang ".$outputlangs->defaultlang.": ";
  139. if (dol_strlen($newemail)) print "qualified.";
  140. else print "disqualified (no email).";
  141. print "\n";
  142. unset($outputlangs);
  143. $total += $obj->total_ttc;
  144. $i++;
  145. }
  146. // Si il reste des envois en buffer
  147. if ($foundtoprocess)
  148. {
  149. if (dol_strlen($oldemail) && $oldemail != 'none' && empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) // Break onto email (new email)
  150. {
  151. envoi_mail($mode,$oldemail,$message,$total,$oldlang,$oldtarget);
  152. $trackthirdpartiessent[$oldsid.'|'.$oldemail]='contact id '.$oldcid;
  153. }
  154. else
  155. {
  156. if ($oldemail != 'none')
  157. {
  158. if (empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) print "- No email sent for '".$oldtarget."', total: ".$total."\n";
  159. else print "- No email sent for '".$oldtarget."', total: ".$total." (already sent to ".$trackthirdpartiessent[$oldsid.'|'.$oldemail].")\n";
  160. }
  161. }
  162. }
  163. }
  164. else
  165. {
  166. print "No unpaid invoices found\n";
  167. }
  168. exit(0);
  169. }
  170. else
  171. {
  172. dol_print_error($db);
  173. dol_syslog("email_unpaid_invoices_to_customers.php: Error");
  174. exit(-1);
  175. }
  176. /**
  177. * Send email
  178. *
  179. * @param string $mode Mode (test | confirm)
  180. * @param string $oldemail Target email
  181. * @param string $message Message to send
  182. * @param string $total Total amount of unpayed invoices
  183. * @param string $userlang Code lang to use for email output.
  184. * @param string $oldtarget Target name
  185. * @return int <0 if KO, >0 if OK
  186. */
  187. function envoi_mail($mode,$oldemail,$message,$total,$userlang,$oldtarget)
  188. {
  189. global $conf,$langs;
  190. if (getenv('DOL_FORCE_EMAIL_TO')) $oldemail=getenv('DOL_FORCE_EMAIL_TO');
  191. $newlangs=new Translate('',$conf);
  192. $newlangs->setDefaultLang(empty($userlang)?(empty($conf->global->MAIN_LANG_DEFAULT)?'auto':$conf->global->MAIN_LANG_DEFAULT):$userlang);
  193. $newlangs->load("main");
  194. $newlangs->load("bills");
  195. $subject = (empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_SUBJECT)?$newlangs->trans("ListOfYourUnpaidInvoices"):$conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_SUBJECT);
  196. $sendto = $oldemail;
  197. $from = $conf->global->MAIN_MAIL_EMAIL_FROM;
  198. $errorsto = $conf->global->MAIN_MAIL_ERRORS_TO;
  199. $msgishtml = -1;
  200. print "- Send email to '".$oldtarget."' (".$oldemail."), total: ".$total."\n";
  201. dol_syslog("email_unpaid_invoices_to_customers.php: send mail to ".$oldemail);
  202. $usehtml=0;
  203. if (dol_textishtml($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_FOOTER)) $usehtml+=1;
  204. if (dol_textishtml($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_HEADER)) $usehtml+=1;
  205. $allmessage='';
  206. if (! empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_HEADER))
  207. {
  208. $allmessage.=$conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_HEADER;
  209. }
  210. else
  211. {
  212. $allmessage.= "Dear customer".($usehtml?"<br>\n":"\n").($usehtml?"<br>\n":"\n");
  213. $allmessage.= "Please, find a summary of the bills with pending payments from you.".($usehtml?"<br>\n":"\n").($usehtml?"<br>\n":"\n");
  214. $allmessage.= "Note: This list contains only unpaid invoices.".($usehtml?"<br>\n":"\n");
  215. }
  216. $allmessage.= $message.($usehtml?"<br>\n":"\n");
  217. $allmessage.= $langs->trans("Total")." = ".price($total,0,$userlang,0,0,-1,$conf->currency).($usehtml?"<br>\n":"\n");
  218. if (! empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_FOOTER))
  219. {
  220. $allmessage.=$conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_FOOTER;
  221. if (dol_textishtml($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_FOOTER)) $usehtml+=1;
  222. }
  223. $mail = new CMailFile(
  224. $subject,
  225. $sendto,
  226. $from,
  227. $allmessage,
  228. array(),
  229. array(),
  230. array(),
  231. '',
  232. '',
  233. 0,
  234. $msgishtml
  235. );
  236. $mail->errors_to = $errorsto;
  237. // Send or not email
  238. if ($mode == 'confirm')
  239. {
  240. $result=$mail->sendfile();
  241. if (! $result)
  242. {
  243. print "Error sending email ".$mail->error."\n";
  244. dol_syslog("Error sending email ".$mail->error."\n");
  245. }
  246. }
  247. else
  248. {
  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. {
  257. return 1;
  258. }
  259. else
  260. {
  261. return -1;
  262. }
  263. }
  264. ?>