email_unpaid_invoices_to_customers.php 11 KB

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