sellsjournal.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903
  1. <?php
  2. /* Copyright (C) 2007-2010 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2007-2010 Jean Heimburger <jean@tiaris.info>
  4. * Copyright (C) 2011 Juanjo Menent <jmenent@2byte.es>
  5. * Copyright (C) 2012 Regis Houssin <regis.houssin@capnetworks.com>
  6. * Copyright (C) 2013 Christophe Battarel <christophe.battarel@altairis.fr>
  7. * Copyright (C) 2013-2018 Alexandre Spangaro <aspangaro@zendsi.com>
  8. * Copyright (C) 2013-2016 Florian Henry <florian.henry@open-concept.pro>
  9. * Copyright (C) 2013-2016 Olivier Geffroy <jeff@jeffinfo.com>
  10. * Copyright (C) 2014 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  11. * Copyright (C) 2018 Frédéric France <frederic.france@netlogic.fr>
  12. *
  13. * This program is free software; you can redistribute it and/or modify
  14. * it under the terms of the GNU General Public License as published by
  15. * the Free Software Foundation; either version 3 of the License, or
  16. * (at your option) any later version.
  17. *
  18. * This program is distributed in the hope that it will be useful,
  19. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. * GNU General Public License for more details.
  22. *
  23. * You should have received a copy of the GNU General Public License
  24. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  25. */
  26. /**
  27. * \file htdocs/accountancy/journal/sellsjournal.php
  28. * \ingroup Advanced accountancy
  29. * \brief Page with sells journal
  30. */
  31. require '../../main.inc.php';
  32. require_once DOL_DOCUMENT_ROOT . '/core/lib/report.lib.php';
  33. require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
  34. require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php';
  35. require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingjournal.class.php';
  36. require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingaccount.class.php';
  37. require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
  38. require_once DOL_DOCUMENT_ROOT . '/societe/class/client.class.php';
  39. require_once DOL_DOCUMENT_ROOT . '/accountancy/class/bookkeeping.class.php';
  40. // Load translation files required by the page
  41. $langs->loadLangs(array("commercial", "compta","bills","other","accountancy","errors"));
  42. $id_journal = GETPOST('id_journal', 'int');
  43. $action = GETPOST('action','aZ09');
  44. $date_startmonth = GETPOST('date_startmonth');
  45. $date_startday = GETPOST('date_startday');
  46. $date_startyear = GETPOST('date_startyear');
  47. $date_endmonth = GETPOST('date_endmonth');
  48. $date_endday = GETPOST('date_endday');
  49. $date_endyear = GETPOST('date_endyear');
  50. $in_bookkeeping = GETPOST('in_bookkeeping');
  51. if ($in_bookkeeping == '') $in_bookkeeping = 'notyet';
  52. $now = dol_now();
  53. // Security check
  54. if ($user->societe_id > 0)
  55. accessforbidden();
  56. $hookmanager->initHooks(array('sellsjournal'));
  57. $parameters=array();
  58. /*
  59. * Actions
  60. */
  61. $reshook=$hookmanager->executeHooks('doActions',$parameters,$user,$action); // Note that $action and $object may have been modified by some hooks
  62. // Get informations of journal
  63. $accountingjournalstatic = new AccountingJournal($db);
  64. $accountingjournalstatic->fetch($id_journal);
  65. $journal = $accountingjournalstatic->code;
  66. $journal_label = $accountingjournalstatic->label;
  67. $year_current = strftime("%Y", dol_now());
  68. $pastmonth = strftime("%m", dol_now()) - 1;
  69. $pastmonthyear = $year_current;
  70. if ($pastmonth == 0) {
  71. $pastmonth = 12;
  72. $pastmonthyear --;
  73. }
  74. $date_start = dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_startyear);
  75. $date_end = dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear);
  76. if (! GETPOSTISSET('date_startmonth') && (empty($date_start) || empty($date_end))) // We define date_start and date_end, only if we did not submit the form
  77. {
  78. $date_start = dol_get_first_day($pastmonthyear, $pastmonth, false);
  79. $date_end = dol_get_last_day($pastmonthyear, $pastmonth, false);
  80. }
  81. $idpays = $mysoc->country_id;
  82. $sql = "SELECT f.rowid, f.facnumber, f.type, f.datef as df, f.ref_client, f.date_lim_reglement as dlr, f.close_code,";
  83. $sql .= " fd.rowid as fdid, fd.description, fd.product_type, fd.total_ht, fd.total_tva, fd.total_localtax1, fd.total_localtax2, fd.tva_tx, fd.total_ttc, fd.situation_percent, fd.vat_src_code,";
  84. $sql .= " s.rowid as socid, s.nom as name, s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur,";
  85. $sql .= " p.rowid as pid, p.ref as pref, p.accountancy_code_sell, aa.rowid as fk_compte, aa.account_number as compte, aa.label as label_compte";
  86. $sql .= " FROM " . MAIN_DB_PREFIX . "facturedet as fd";
  87. $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product as p ON p.rowid = fd.fk_product";
  88. $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_account as aa ON aa.rowid = fd.fk_code_ventilation";
  89. $sql .= " JOIN " . MAIN_DB_PREFIX . "facture as f ON f.rowid = fd.fk_facture";
  90. $sql .= " JOIN " . MAIN_DB_PREFIX . "societe as s ON s.rowid = f.fk_soc";
  91. $sql .= " WHERE fd.fk_code_ventilation > 0";
  92. $sql .= " AND f.entity IN (".getEntity('facture', 0).')'; // We don't share object for accountancy, we use source object sharing
  93. $sql .= " AND f.fk_statut > 0";
  94. if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { // Non common setup
  95. $sql .= " AND f.type IN (" . Facture::TYPE_STANDARD . "," . Facture::TYPE_REPLACEMENT . "," . Facture::TYPE_CREDIT_NOTE . "," . Facture::TYPE_SITUATION . ")";
  96. } else {
  97. $sql .= " AND f.type IN (" . Facture::TYPE_STANDARD . "," . Facture::TYPE_REPLACEMENT . "," . Facture::TYPE_CREDIT_NOTE . "," . Facture::TYPE_DEPOSIT . "," . Facture::TYPE_SITUATION . ")";
  98. }
  99. $sql .= " AND fd.product_type IN (0,1)";
  100. if ($date_start && $date_end)
  101. $sql .= " AND f.datef >= '" . $db->idate($date_start) . "' AND f.datef <= '" . $db->idate($date_end) . "'";
  102. // Already in bookkeeping or not
  103. if ($in_bookkeeping == 'already')
  104. {
  105. $sql .= " AND f.rowid IN (SELECT fk_doc FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as ab WHERE ab.doc_type='customer_invoice')";
  106. // $sql .= " AND fd.rowid IN (SELECT fk_docdet FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as ab WHERE ab.doc_type='customer_invoice')"; // Useless, we save one line for all products with same account
  107. }
  108. if ($in_bookkeeping == 'notyet')
  109. {
  110. $sql .= " AND f.rowid NOT IN (SELECT fk_doc FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as ab WHERE ab.doc_type='customer_invoice')";
  111. // $sql .= " AND fd.rowid NOT IN (SELECT fk_docdet FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as ab WHERE ab.doc_type='customer_invoice')"; // Useless, we save one line for all products with same account
  112. }
  113. $sql .= " ORDER BY f.datef";
  114. //print $sql;
  115. dol_syslog('accountancy/journal/sellsjournal.php', LOG_DEBUG);
  116. $result = $db->query($sql);
  117. if ($result) {
  118. $tabfac = array ();
  119. $tabht = array ();
  120. $tabtva = array ();
  121. $def_tva = array ();
  122. $tabttc = array ();
  123. $tablocaltax1 = array ();
  124. $tablocaltax2 = array ();
  125. $tabcompany = array ();
  126. $num = $db->num_rows($result);
  127. // Variables
  128. $cptcli = (! empty($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER)) ? $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER : 'NotDefined';
  129. $cpttva = (! empty($conf->global->ACCOUNTING_VAT_SOLD_ACCOUNT)) ? $conf->global->ACCOUNTING_VAT_SOLD_ACCOUNT : 'NotDefined';
  130. $i = 0;
  131. while ( $i < $num ) {
  132. $obj = $db->fetch_object($result);
  133. // Controls
  134. $compta_soc = (! empty($obj->code_compta)) ? $obj->code_compta : $cptcli;
  135. $compta_prod = $obj->compte;
  136. if (empty($compta_prod)) {
  137. if ($obj->product_type == 0)
  138. $compta_prod = (! empty($conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT)) ? $conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT : 'NotDefined';
  139. else
  140. $compta_prod = (! empty($conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT)) ? $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT : 'NotDefined';
  141. }
  142. $vatdata = getTaxesFromId($obj->tva_tx.($obj->vat_src_code?' ('.$obj->vat_src_code.')':''), $mysoc, $mysoc, 0);
  143. $compta_tva = (! empty($vatdata['accountancy_code_sell']) ? $vatdata['accountancy_code_sell'] : $cpttva);
  144. $compta_localtax1 = (! empty($vatdata['accountancy_code_sell']) ? $vatdata['accountancy_code_sell'] : $cpttva);
  145. $compta_localtax2 = (! empty($vatdata['accountancy_code_sell']) ? $vatdata['accountancy_code_sell'] : $cpttva);
  146. // Define array to display all VAT rates that use this accounting account $compta_tva
  147. if (price2num($obj->tva_tx) || ! empty($obj->vat_src_code))
  148. {
  149. $def_tva[$obj->rowid][$compta_tva][vatrate($obj->tva_tx).($obj->vat_src_code?' ('.$obj->vat_src_code.')':'')]=(vatrate($obj->tva_tx).($obj->vat_src_code?' ('.$obj->vat_src_code.')':''));
  150. }
  151. $line = new FactureLigne($db);
  152. $line->fetch($obj->fdid);
  153. // Situation invoices handling
  154. $prev_progress = $line->get_prev_progress($obj->rowid);
  155. if ($obj->type == Facture::TYPE_SITUATION) {
  156. // Avoid divide by 0
  157. if ($obj->situation_percent == 0) {
  158. $situation_ratio = 0;
  159. } else {
  160. $situation_ratio = ($obj->situation_percent - $prev_progress) / $obj->situation_percent;
  161. }
  162. } else {
  163. $situation_ratio = 1;
  164. }
  165. // Invoice lines
  166. $tabfac[$obj->rowid]["date"] = $db->jdate($obj->df);
  167. $tabfac[$obj->rowid]["datereg"] = $db->jdate($obj->dlr);
  168. $tabfac[$obj->rowid]["ref"] = $obj->facnumber;
  169. $tabfac[$obj->rowid]["type"] = $obj->type;
  170. $tabfac[$obj->rowid]["description"] = $obj->label_compte;
  171. $tabfac[$obj->rowid]["close_code"] = $obj->close_code; // close_code = 'replaced' for replacement invoices (not used in most european countries)
  172. //$tabfac[$obj->rowid]["fk_facturedet"] = $obj->fdid;
  173. // Avoid warnings
  174. if (! isset($tabttc[$obj->rowid][$compta_soc])) $tabttc[$obj->rowid][$compta_soc] = 0;
  175. if (! isset($tabht[$obj->rowid][$compta_prod])) $tabht[$obj->rowid][$compta_prod] = 0;
  176. if (! isset($tabtva[$obj->rowid][$compta_tva])) $tabtva[$obj->rowid][$compta_tva] = 0;
  177. if (! isset($tablocaltax1[$obj->rowid][$compta_localtax1])) $tablocaltax1[$obj->rowid][$compta_localtax1] = 0;
  178. if (! isset($tablocaltax2[$obj->rowid][$compta_localtax2])) $tablocaltax2[$obj->rowid][$compta_localtax2] = 0;
  179. $tabttc[$obj->rowid][$compta_soc] += $obj->total_ttc * $situation_ratio;
  180. $tabht[$obj->rowid][$compta_prod] += $obj->total_ht * $situation_ratio;
  181. if (empty($line->tva_npr)) $tabtva[$obj->rowid][$compta_tva] += $obj->total_tva * $situation_ratio; // We ignore line if VAT is a NPR
  182. $tablocaltax1[$obj->rowid][$compta_localtax1] += $obj->total_localtax1 * $situation_ratio;
  183. $tablocaltax2[$obj->rowid][$compta_localtax2] += $obj->total_localtax2 * $situation_ratio;
  184. $tabcompany[$obj->rowid] = array (
  185. 'id' => $obj->socid,
  186. 'name' => $obj->name,
  187. 'code_client' => $obj->code_client,
  188. 'code_compta' => $compta_soc
  189. );
  190. $i ++;
  191. }
  192. } else {
  193. dol_print_error($db);
  194. }
  195. $errorforinvoice = array();
  196. // Loop in invoices to detect lines with not binding lines
  197. foreach ($tabfac as $key => $val) { // Loop on each invoice
  198. $sql = "SELECT COUNT(fd.rowid) as nb";
  199. $sql.= " FROM " . MAIN_DB_PREFIX . "facturedet as fd";
  200. $sql.= " WHERE fd.product_type <= 2 AND fd.fk_code_ventilation <= 0";
  201. $sql.= " AND fd.total_ttc <> 0 AND fk_facture = ".$key;
  202. $resql=$db->query($sql);
  203. if ($resql)
  204. {
  205. $obj = $db->fetch_object($resql);
  206. if ($obj->nb > 0)
  207. {
  208. $errorforinvoice[$key]='somelinesarenotbound';
  209. }
  210. }
  211. else dol_print_error($db);
  212. }
  213. //var_dump($errorforinvoice);exit;
  214. // Bookkeeping Write
  215. if ($action == 'writebookkeeping') {
  216. $now = dol_now();
  217. $error = 0;
  218. $companystatic = new Societe($db);
  219. $invoicestatic = new Facture($db);
  220. foreach ($tabfac as $key => $val) { // Loop on each invoice
  221. $errorforline = 0;
  222. $totalcredit = 0;
  223. $totaldebit = 0;
  224. $db->begin();
  225. $companystatic->id = $tabcompany[$key]['id'];
  226. $companystatic->name = $tabcompany[$key]['name'];
  227. $companystatic->code_compta = $tabcompany[$key]['code_compta'];
  228. $companystatic->code_compta_fournisseur = $tabcompany[$key]['code_compta_fournisseur'];
  229. $companystatic->code_client = $tabcompany[$key]['code_client'];
  230. $companystatic->code_fournisseur = $tabcompany[$key]['code_fournisseur'];
  231. $companystatic->client = 3;
  232. $invoicestatic->id = $key;
  233. $invoicestatic->ref = (string) $val["ref"];
  234. $invoicestatic->type = $val["type"];
  235. $invoicestatic->close_code = $val["close_code"];
  236. $date = dol_print_date($val["date"], 'day');
  237. // Is it a replaced invoice ? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
  238. $replacedinvoice = 0;
  239. if ($invoicestatic->close_code == Facture::CLOSECODE_REPLACED)
  240. {
  241. $replacedinvoice = 1;
  242. $alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
  243. if ($alreadydispatched) $replacedinvoice = 2;
  244. }
  245. // If not already into bookkeeping, we won't add it. If yes, do nothing (should not happen because creating replacement not possible if invoice is accounted)
  246. if ($replacedinvoice == 1)
  247. {
  248. $db->rollback();
  249. continue;
  250. }
  251. // Error if some lines are not binded/ready to be journalized
  252. if ($errorforinvoice[$key] == 'somelinesarenotbound')
  253. {
  254. $error++;
  255. $errorforline++;
  256. setEventMessages($langs->trans('ErrorInvoiceContainsLinesNotYetBounded', $val['ref']), null, 'errors');
  257. }
  258. // Thirdparty
  259. if (! $errorforline)
  260. {
  261. foreach ( $tabttc[$key] as $k => $mt ) {
  262. //if ($mt) {
  263. $bookkeeping = new BookKeeping($db);
  264. $bookkeeping->doc_date = $val["date"];
  265. $bookkeeping->date_lim_reglement = $val["datereg"];
  266. $bookkeeping->doc_ref = $val["ref"];
  267. $bookkeeping->date_create = $now;
  268. $bookkeeping->doc_type = 'customer_invoice';
  269. $bookkeeping->fk_doc = $key;
  270. $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
  271. $bookkeeping->thirdparty_code = $companystatic->code_client;
  272. $bookkeeping->subledger_account = $tabcompany[$key]['code_compta'];
  273. $bookkeeping->subledger_label = $tabcompany[$key]['name'];
  274. $bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER;
  275. $bookkeeping->label_operation = dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("SubledgerAccount");
  276. $bookkeeping->montant = $mt;
  277. $bookkeeping->sens = ($mt >= 0) ? 'D' : 'C';
  278. $bookkeeping->debit = ($mt >= 0) ? $mt : 0;
  279. $bookkeeping->credit = ($mt < 0) ? -$mt : 0;
  280. $bookkeeping->code_journal = $journal;
  281. $bookkeeping->journal_label = $journal_label;
  282. $bookkeeping->fk_user_author = $user->id;
  283. $bookkeeping->entity = $conf->entity;
  284. $totaldebit += $bookkeeping->debit;
  285. $totalcredit += $bookkeeping->credit;
  286. $result = $bookkeeping->create($user);
  287. if ($result < 0) {
  288. if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') // Already exists
  289. {
  290. $error++;
  291. $errorforline++;
  292. $errorforinvoice[$key]='alreadyjournalized';
  293. //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
  294. }
  295. else
  296. {
  297. $error++;
  298. $errorforline++;
  299. $errorforinvoice[$key]='other';
  300. setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
  301. }
  302. }
  303. //}
  304. }
  305. }
  306. // Product / Service
  307. if (! $errorforline)
  308. {
  309. foreach ( $tabht[$key] as $k => $mt ) {
  310. //if ($mt) {
  311. // get compte id and label
  312. $accountingaccount = new AccountingAccount($db);
  313. if ($accountingaccount->fetch(null, $k, true)) {
  314. $bookkeeping = new BookKeeping($db);
  315. $bookkeeping->doc_date = $val["date"];
  316. $bookkeeping->date_lim_reglement = $val["datereg"];
  317. $bookkeeping->doc_ref = $val["ref"];
  318. $bookkeeping->date_create = $now;
  319. $bookkeeping->doc_type = 'customer_invoice';
  320. $bookkeeping->fk_doc = $key;
  321. $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
  322. $bookkeeping->thirdparty_code = $companystatic->code_client;
  323. $bookkeeping->subledger_account = '';
  324. $bookkeeping->subledger_label = '';
  325. $bookkeeping->numero_compte = $k;
  326. $bookkeeping->label_operation = dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->ref . ' - ' . $accountingaccount->label;
  327. $bookkeeping->montant = $mt;
  328. $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
  329. $bookkeeping->debit = ($mt < 0) ? -$mt : 0;
  330. $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
  331. $bookkeeping->code_journal = $journal;
  332. $bookkeeping->journal_label = $journal_label;
  333. $bookkeeping->fk_user_author = $user->id;
  334. $bookkeeping->entity = $conf->entity;
  335. $totaldebit += $bookkeeping->debit;
  336. $totalcredit += $bookkeeping->credit;
  337. $result = $bookkeeping->create($user);
  338. if ($result < 0) {
  339. if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') // Already exists
  340. {
  341. $error++;
  342. $errorforline++;
  343. $errorforinvoice[$key]='alreadyjournalized';
  344. //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
  345. }
  346. else
  347. {
  348. $error++;
  349. $errorforline++;
  350. $errorforinvoice[$key]='other';
  351. setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
  352. }
  353. }
  354. }
  355. //}
  356. }
  357. }
  358. // VAT
  359. if (! $errorforline)
  360. {
  361. $listoftax=array(0, 1, 2);
  362. foreach($listoftax as $numtax)
  363. {
  364. $arrayofvat = $tabtva;
  365. if ($numtax == 1) $arrayofvat = $tablocaltax1;
  366. if ($numtax == 2) $arrayofvat = $tablocaltax2;
  367. foreach ( $arrayofvat[$key] as $k => $mt ) {
  368. if ($mt) {
  369. $bookkeeping = new BookKeeping($db);
  370. $bookkeeping->doc_date = $val["date"];
  371. $bookkeeping->date_lim_reglement = $val["datereg"];
  372. $bookkeeping->doc_ref = $val["ref"];
  373. $bookkeeping->date_create = $now;
  374. $bookkeeping->doc_type = 'customer_invoice';
  375. $bookkeeping->fk_doc = $key;
  376. $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
  377. $bookkeeping->thirdparty_code = $companystatic->code_client;
  378. $bookkeeping->subledger_account = '';
  379. $bookkeeping->subledger_label = '';
  380. $bookkeeping->numero_compte = $k;
  381. $bookkeeping->label_operation = dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("VAT").' '.join(', ',$def_tva[$key][$k]) .' %' . ($numtax?' - Localtax '.$numtax:'');
  382. $bookkeeping->montant = $mt;
  383. $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
  384. $bookkeeping->debit = ($mt < 0) ? -$mt : 0;
  385. $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
  386. $bookkeeping->code_journal = $journal;
  387. $bookkeeping->journal_label = $journal_label;
  388. $bookkeeping->fk_user_author = $user->id;
  389. $bookkeeping->entity = $conf->entity;
  390. $totaldebit += $bookkeeping->debit;
  391. $totalcredit += $bookkeeping->credit;
  392. $result = $bookkeeping->create($user);
  393. if ($result < 0) {
  394. if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') // Already exists
  395. {
  396. $error++;
  397. $errorforline++;
  398. $errorforinvoice[$key]='alreadyjournalized';
  399. //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
  400. }
  401. else
  402. {
  403. $error++;
  404. $errorforline++;
  405. $errorforinvoice[$key]='other';
  406. setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
  407. }
  408. }
  409. }
  410. }
  411. }
  412. }
  413. // Protection against a bug on lines before
  414. if (! $errorforline && (price2num($totaldebit) != price2num($totalcredit)))
  415. {
  416. $error++;
  417. $errorforline++;
  418. $errorforinvoice[$key]='amountsnotbalanced';
  419. setEventMessages('Try to insert a non balanced transaction in book for '.$invoicestatic->ref.'. Canceled. Surely a bug.', null, 'errors');
  420. }
  421. if (! $errorforline)
  422. {
  423. $db->commit();
  424. }
  425. else
  426. {
  427. $db->rollback();
  428. if ($error >= 10)
  429. {
  430. setEventMessages($langs->trans("ErrorTooManyErrorsProcessStopped"), null, 'errors');
  431. break; // Break in the foreach
  432. }
  433. }
  434. }
  435. $tabpay = $tabfac;
  436. if (empty($error) && count($tabpay) > 0) {
  437. setEventMessages($langs->trans("GeneralLedgerIsWritten"), null, 'mesgs');
  438. }
  439. elseif (count($tabpay) == $error)
  440. {
  441. setEventMessages($langs->trans("NoNewRecordSaved"), null, 'warnings');
  442. }
  443. else
  444. {
  445. setEventMessages($langs->trans("GeneralLedgerSomeRecordWasNotRecorded"), null, 'warnings');
  446. }
  447. $action='';
  448. // Must reload data, so we make a redirect
  449. if (count($tabpay) != $error)
  450. {
  451. $param='id_journal='.$id_journal;
  452. $param.='&date_startday='.$date_startday;
  453. $param.='&date_startmonth='.$date_startmonth;
  454. $param.='&date_startyear='.$date_startyear;
  455. $param.='&date_endday='.$date_endday;
  456. $param.='&date_endmonth='.$date_endmonth;
  457. $param.='&date_endyear='.$date_endyear;
  458. $param.='&in_bookkeeping='.$in_bookkeeping;
  459. header("Location: ".$_SERVER['PHP_SELF'].($param?'?'.$param:''));
  460. exit;
  461. }
  462. }
  463. /*
  464. * View
  465. */
  466. $form = new Form($db);
  467. // Export
  468. if ($action == 'exportcsv') { // ISO and not UTF8 !
  469. $sep = $conf->global->ACCOUNTING_EXPORT_SEPARATORCSV;
  470. $filename = 'journal';
  471. include DOL_DOCUMENT_ROOT . '/accountancy/tpl/export_journal.tpl.php';
  472. $companystatic = new Client($db);
  473. $invoicestatic = new Facture($db);
  474. foreach ( $tabfac as $key => $val )
  475. {
  476. $companystatic->id = $tabcompany[$key]['id'];
  477. $companystatic->name = $tabcompany[$key]['name'];
  478. $companystatic->code_compta = $tabcompany[$key]['code_compta'];
  479. $companystatic->code_compta_fournisseur = $tabcompany[$key]['code_compta_fournisseur'];
  480. $companystatic->code_client = $tabcompany[$key]['code_client'];
  481. $companystatic->code_fournisseur = $tabcompany[$key]['code_fournisseur'];
  482. $companystatic->client = 3;
  483. $invoicestatic->id = $key;
  484. $invoicestatic->ref = (string) $val["ref"];
  485. $invoicestatic->type = $val["type"];
  486. $invoicestatic->close_code = $val["close_code"];
  487. $date = dol_print_date($val["date"], 'day');
  488. // Is it a replaced invoice ? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
  489. $replacedinvoice = 0;
  490. if ($invoicestatic->close_code == Facture::CLOSECODE_REPLACED)
  491. {
  492. $replacedinvoice = 1;
  493. $alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
  494. if ($alreadydispatched) $replacedinvoice = 2;
  495. }
  496. // If not already into bookkeeping, we won't add it. If yes, do nothing (should not happen because creating replacement not possible if invoice is accounted)
  497. if ($replacedinvoice == 1)
  498. {
  499. continue;
  500. }
  501. // Third party
  502. foreach ($tabttc[$key] as $k => $mt) {
  503. //if ($mt) {
  504. print '"' . $key . '"' . $sep;
  505. print '"' . $date . '"' . $sep;
  506. print '"' . $val["ref"] . '"' . $sep;
  507. print '"' . utf8_decode(dol_trunc($companystatic->name, 32)) . '"' . $sep;
  508. print '"' . length_accounta(html_entity_decode($k)) . '"' . $sep;
  509. print '"' . $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER . '"' . $sep;
  510. print '"' . length_accounta(html_entity_decode($k)) . '"' . $sep;
  511. print '"' . $langs->trans("Thirdparty") . '"' . $sep;
  512. print '"' . utf8_decode(dol_trunc($companystatic->name, 16)) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("Thirdparty") . '"' . $sep;
  513. print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep;
  514. print '"' . ($mt < 0 ? price(- $mt) : '') . '"' . $sep;
  515. print '"' . $journal . '"';
  516. print "\n";
  517. //}
  518. }
  519. // Product / Service
  520. foreach ($tabht[$key] as $k => $mt) {
  521. $accountingaccount = new AccountingAccount($db);
  522. $accountingaccount->fetch(null, $k, true);
  523. //if ($mt) {
  524. print '"' . $key . '"' . $sep;
  525. print '"' . $date . '"' . $sep;
  526. print '"' . $val["ref"] . '"' . $sep;
  527. print '"' . utf8_decode(dol_trunc($companystatic->name, 32)) . '"' . $sep;
  528. print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep;
  529. print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep;
  530. print '""' . $sep;
  531. print '"' . utf8_decode(dol_trunc($accountingaccount->label, 32)) . '"' . $sep;
  532. print '"' . utf8_decode(dol_trunc($companystatic->name, 16)) . ' - ' . dol_trunc($accountingaccount->label, 32) . '"' . $sep;
  533. print '"' . ($mt < 0 ? price(- $mt) : '') . '"' . $sep;
  534. print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep;
  535. print '"' . $journal . '"';
  536. print "\n";
  537. //}
  538. }
  539. // VAT
  540. $listoftax = array(0, 1, 2);
  541. foreach ($listoftax as $numtax) {
  542. $arrayofvat = $tabtva;
  543. if ($numtax == 1) $arrayofvat = $tablocaltax1;
  544. if ($numtax == 2) $arrayofvat = $tablocaltax2;
  545. foreach ($arrayofvat[$key] as $k => $mt) {
  546. if ($mt) {
  547. print '"' . $key . '"' . $sep;
  548. print '"' . $date . '"' . $sep;
  549. print '"' . $val["ref"] . '"' . $sep;
  550. print '"' . utf8_decode(dol_trunc($companystatic->name, 32)) . '"' . $sep;
  551. print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep;
  552. print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep;
  553. print '""' . $sep;
  554. print '"' . $langs->trans("VAT") . ' - ' . $def_tva[$key] . ' %"' . $sep;
  555. print '"' . utf8_decode(dol_trunc($companystatic->name, 16)) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("VAT") . join(', ',$def_tva[$key][$k]) .' %' . ($numtax?' - Localtax '.$numtax:'') . '"' . $sep;
  556. print '"' . ($mt < 0 ? price(- $mt) : '') . '"' . $sep;
  557. print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep;
  558. print '"' . $journal . '"';
  559. print "\n";
  560. }
  561. }
  562. }
  563. }
  564. }
  565. if (empty($action) || $action == 'view') {
  566. llxHeader('', $langs->trans("SellsJournal"));
  567. $nom = $langs->trans("SellsJournal") . ' | ' . $accountingjournalstatic->getNomUrl(0,1,1,'',1);
  568. $nomlink = '';
  569. $periodlink = '';
  570. $exportlink = '';
  571. $builddate=dol_now();
  572. $description.= $langs->trans("DescJournalOnlyBindedVisible").'<br>';
  573. if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS))
  574. $description .= $langs->trans("DepositsAreNotIncluded");
  575. else
  576. $description .= $langs->trans("DepositsAreIncluded");
  577. $listofchoices=array('notyet'=>$langs->trans("NotYetInGeneralLedger"), 'already'=>$langs->trans("AlreadyInGeneralLedger"));
  578. $period = $form->selectDate($date_start?$date_start:-1, 'date_start', 0, 0, 0, '', 1, 0) . ' - ' . $form->selectDate($date_end?$date_end:-1, 'date_end', 0, 0, 0, '', 1, 0);
  579. $period .= ' - ' .$langs->trans("JournalizationInLedgerStatus").' '. $form->selectarray('in_bookkeeping', $listofchoices, $in_bookkeeping, 1);
  580. $varlink = 'id_journal=' . $id_journal;
  581. journalHead($nom, $nomlink, $period, $periodlink, $description, $builddate, $exportlink, array('action' => ''), '', $varlink);
  582. // Button to write into Ledger
  583. if (empty($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER) || $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER == '-1') {
  584. print img_warning().' '.$langs->trans("SomeMandatoryStepsOfSetupWereNotDone");
  585. print ' : '.$langs->trans("AccountancyAreaDescMisc", 4, '<strong>'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("MenuDefaultAccounts").'</strong>');
  586. }
  587. print '<div class="tabsAction tabsActionNoBottom">';
  588. if (! empty($conf->global->ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL)) print '<input type="button" class="butAction" name="exportcsv" value="' . $langs->trans("ExportDraftJournal") . '" onclick="launch_export();" />';
  589. if (empty($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER) || $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER == '-1') {
  590. print '<input type="button" class="butActionRefused" title="'.dol_escape_htmltag($langs->trans("SomeMandatoryStepsOfSetupWereNotDone")).'" value="' . $langs->trans("WriteBookKeeping") . '" />';
  591. }
  592. else {
  593. if ($in_bookkeeping == 'notyet') print '<input type="button" class="butAction" name="writebookkeeping" value="' . $langs->trans("WriteBookKeeping") . '" onclick="writebookkeeping();" />';
  594. else print '<a href="#" class="butActionRefused" name="writebookkeeping">' . $langs->trans("WriteBookKeeping") . '</a>';
  595. }
  596. print '</div>';
  597. // TODO Avoid using js. We can use a direct link with $param
  598. print '
  599. <script type="text/javascript">
  600. function launch_export() {
  601. $("div.fiche form input[name=\"action\"]").val("exportcsv");
  602. $("div.fiche form input[type=\"submit\"]").click();
  603. $("div.fiche form input[name=\"action\"]").val("");
  604. }
  605. function writebookkeeping() {
  606. console.log("click on writebookkeeping");
  607. $("div.fiche form input[name=\"action\"]").val("writebookkeeping");
  608. $("div.fiche form input[type=\"submit\"]").click();
  609. $("div.fiche form input[name=\"action\"]").val("");
  610. }
  611. </script>';
  612. /*
  613. * Show result array
  614. */
  615. print '<br>';
  616. $i = 0;
  617. print '<div class="div-table-responsive">';
  618. print "<table class=\"noborder\" width=\"100%\">";
  619. print "<tr class=\"liste_titre\">";
  620. print "<td></td>";
  621. print "<td>" . $langs->trans("Date") . "</td>";
  622. print "<td>" . $langs->trans("Piece") . ' (' . $langs->trans("InvoiceRef") . ")</td>";
  623. print "<td>" . $langs->trans("AccountAccounting") . "</td>";
  624. print "<td>" . $langs->trans("SubledgerAccount") . "</td>";
  625. print "<td>" . $langs->trans("LabelOperation") . "</td>";
  626. print "<td align='right'>" . $langs->trans("Debit") . "</td>";
  627. print "<td align='right'>" . $langs->trans("Credit") . "</td>";
  628. print "</tr>\n";
  629. $r = '';
  630. $companystatic = new Client($db);
  631. $invoicestatic = new Facture($db);
  632. foreach ( $tabfac as $key => $val )
  633. {
  634. $companystatic->id = $tabcompany[$key]['id'];
  635. $companystatic->name = $tabcompany[$key]['name'];
  636. $companystatic->code_compta = $tabcompany[$key]['code_compta'];
  637. $companystatic->code_compta_fournisseur = $tabcompany[$key]['code_compta_fournisseur'];
  638. $companystatic->code_client = $tabcompany[$key]['code_client'];
  639. $companystatic->code_fournisseur = $tabcompany[$key]['code_fournisseur'];
  640. $companystatic->client = 3;
  641. $invoicestatic->id = $key;
  642. $invoicestatic->ref = (string) $val["ref"];
  643. $invoicestatic->type = $val["type"];
  644. $invoicestatic->close_code = $val["close_code"];
  645. $date = dol_print_date($val["date"], 'day');
  646. // Is it a replaced invoice ? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
  647. $replacedinvoice = 0;
  648. if ($invoicestatic->close_code == Facture::CLOSECODE_REPLACED)
  649. {
  650. $replacedinvoice = 1;
  651. $alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
  652. if ($alreadydispatched) $replacedinvoice = 2;
  653. }
  654. // If not already into bookkeeping, we won't add it, if yes, add the counterpart ???.
  655. if ($replacedinvoice == 1)
  656. {
  657. print '<tr class="oddeven">';
  658. print "<td><!-- Replaced invoice --></td>";
  659. print "<td>" . $date . "</td>";
  660. print "<td><strike>" . $invoicestatic->getNomUrl(1) . "</strike></td>";
  661. // Account
  662. print "<td>";
  663. print $langs->trans("Replaced");
  664. print '</td>';
  665. // Subledger account
  666. print "<td>";
  667. print '</td>';
  668. print "<td>";
  669. print "</td>";
  670. print '<td align="right"></td>';
  671. print '<td align="right"></td>';
  672. print "</tr>";
  673. continue;
  674. }
  675. if ($errorforinvoice[$key] == 'somelinesarenotbound')
  676. {
  677. print '<tr class="oddeven">';
  678. print "<td><!-- Some lines are not bound --></td>";
  679. print "<td>" . $date . "</td>";
  680. print "<td>" . $invoicestatic->getNomUrl(1) . "</td>";
  681. // Account
  682. print "<td>";
  683. print '<span class="error">'.$langs->trans('ErrorInvoiceContainsLinesNotYetBoundedShort', $val['ref']).'</span>';
  684. print '</td>';
  685. // Subledger account
  686. print "<td>";
  687. print '</td>';
  688. print "<td>";
  689. print "</td>";
  690. print '<td align="right"></td>';
  691. print '<td align="right"></td>';
  692. print "</tr>";
  693. }
  694. // Third party
  695. foreach ($tabttc[$key] as $k => $mt)
  696. {
  697. //if ($mt) {
  698. print '<tr class="oddeven">';
  699. print "<td><!-- Thirdparty --></td>";
  700. print "<td>" . $date . "</td>";
  701. print "<td>" . $invoicestatic->getNomUrl(1) . "</td>";
  702. // Account
  703. print "<td>";
  704. $accountoshow = length_accounta($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER);
  705. if (empty($accountoshow) || $accountoshow == 'NotDefined')
  706. {
  707. print '<span class="error">'.$langs->trans("MainAccountForCustomersNotDefined").'</span>';
  708. }
  709. else print $accountoshow;
  710. print '</td>';
  711. // Subledger account
  712. print "<td>";
  713. $accountoshow = length_accounta($k);
  714. if (empty($accountoshow) || $accountoshow == 'NotDefined')
  715. {
  716. print '<span class="error">'.$langs->trans("ThirdpartyAccountNotDefined").'</span>';
  717. }
  718. else print $accountoshow;
  719. print '</td>';
  720. print "<td>" . $companystatic->getNomUrl(0, 'customer', 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("SubledgerAccount") . "</td>";
  721. print '<td align="right">' . ($mt >= 0 ? price($mt) : '') . "</td>";
  722. print '<td align="right">' . ($mt < 0 ? price(- $mt) : '') . "</td>";
  723. print "</tr>";
  724. //}
  725. }
  726. // Product / Service
  727. foreach ($tabht[$key] as $k => $mt)
  728. {
  729. $accountingaccount = new AccountingAccount($db);
  730. $accountingaccount->fetch(null, $k, true);
  731. //if ($mt) {
  732. print '<tr class="oddeven">';
  733. print "<td><!-- Product --></td>";
  734. print "<td>" . $date . "</td>";
  735. print "<td>" . $invoicestatic->getNomUrl(1) . "</td>";
  736. // Account
  737. print "<td>";
  738. $accountoshow = length_accountg($k);
  739. if (empty($accountoshow) || $accountoshow == 'NotDefined')
  740. {
  741. print '<span class="error">'.$langs->trans("ProductNotDefined").'</span>';
  742. }
  743. else print $accountoshow;
  744. print "</td>";
  745. // Subledger account
  746. print "<td>";
  747. print '</td>';
  748. $companystatic->id = $tabcompany[$key]['id'];
  749. $companystatic->name = $tabcompany[$key]['name'];
  750. print "<td>" . $companystatic->getNomUrl(0, 'customer', 16) . ' - ' . $invoicestatic->ref . ' - ' . $accountingaccount->label . "</td>";
  751. print "<td align='right'>" . ($mt < 0 ? price(- $mt) : '') . "</td>";
  752. print "<td align='right'>" . ($mt >= 0 ? price($mt) : '') . "</td>";
  753. print "</tr>";
  754. //}
  755. }
  756. // VAT
  757. $listoftax = array(0, 1, 2);
  758. foreach ($listoftax as $numtax)
  759. {
  760. $arrayofvat = $tabtva;
  761. if ($numtax == 1) $arrayofvat = $tablocaltax1;
  762. if ($numtax == 2) $arrayofvat = $tablocaltax2;
  763. foreach ( $arrayofvat[$key] as $k => $mt ) {
  764. if ($mt) {
  765. print '<tr class="oddeven">';
  766. print "<td><!-- VAT --></td>";
  767. print "<td>" . $date . "</td>";
  768. print "<td>" . $invoicestatic->getNomUrl(1) . "</td>";
  769. // Account
  770. print "<td>";
  771. $accountoshow = length_accountg($k);
  772. if (empty($accountoshow) || $accountoshow == 'NotDefined')
  773. {
  774. print '<span class="error">'.$langs->trans("VATAccountNotDefined").' ('.$langs->trans("Sale").')'.'</span>';
  775. }
  776. else print $accountoshow;
  777. print "</td>";
  778. // Subledger account
  779. print "<td>";
  780. print '</td>';
  781. print "<td>" . $companystatic->getNomUrl(0, 'customer', 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("VAT"). ' '.join(', ',$def_tva[$key][$k]).' %'.($numtax?' - Localtax '.$numtax:'');
  782. print "</td>";
  783. print '<td align="right">' . ($mt < 0 ? price(- $mt) : '') . "</td>";
  784. print '<td align="right">' . ($mt >= 0 ? price($mt) : '') . "</td>";
  785. print "</tr>";
  786. }
  787. }
  788. }
  789. }
  790. print "</table>";
  791. print '</div>';
  792. // End of page
  793. llxFooter();
  794. }
  795. $db->close();