sellsjournal.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  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@inodbox.com>
  6. * Copyright (C) 2013 Christophe Battarel <christophe.battarel@altairis.fr>
  7. * Copyright (C) 2013-2018 Alexandre Spangaro <aspangaro@open-dsi.fr>
  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 <https://www.gnu.org/licenses/>.
  25. */
  26. /**
  27. * \file htdocs/accountancy/journal/sellsjournal.php
  28. * \ingroup Accountancy (Double entries)
  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. $accountingaccount = new AccountingAccount($db);
  63. // Get informations of journal
  64. $accountingjournalstatic = new AccountingJournal($db);
  65. $accountingjournalstatic->fetch($id_journal);
  66. $journal = $accountingjournalstatic->code;
  67. $journal_label = $accountingjournalstatic->label;
  68. $year_current = strftime("%Y", dol_now());
  69. $pastmonth = strftime("%m", dol_now()) - 1;
  70. $pastmonthyear = $year_current;
  71. if ($pastmonth == 0) {
  72. $pastmonth = 12;
  73. $pastmonthyear --;
  74. }
  75. $date_start = dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_startyear);
  76. $date_end = dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear);
  77. 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
  78. {
  79. $date_start = dol_get_first_day($pastmonthyear, $pastmonth, false);
  80. $date_end = dol_get_last_day($pastmonthyear, $pastmonth, false);
  81. }
  82. $sql = "SELECT f.rowid, f.ref, 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('invoice', 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 = (($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->ref;
  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_creation = $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. $accountingaccount->fetch(null, $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER, true);
  276. $bookkeeping->label_compte = $accountingaccount->label;
  277. $bookkeeping->label_operation = dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("SubledgerAccount");
  278. $bookkeeping->montant = $mt;
  279. $bookkeeping->sens = ($mt >= 0) ? 'D' : 'C';
  280. $bookkeeping->debit = ($mt >= 0) ? $mt : 0;
  281. $bookkeeping->credit = ($mt < 0) ? -$mt : 0;
  282. $bookkeeping->code_journal = $journal;
  283. $bookkeeping->journal_label = $journal_label;
  284. $bookkeeping->fk_user_author = $user->id;
  285. $bookkeeping->entity = $conf->entity;
  286. $totaldebit += $bookkeeping->debit;
  287. $totalcredit += $bookkeeping->credit;
  288. $result = $bookkeeping->create($user);
  289. if ($result < 0) {
  290. if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') // Already exists
  291. {
  292. $error++;
  293. $errorforline++;
  294. $errorforinvoice[$key]='alreadyjournalized';
  295. //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
  296. }
  297. else
  298. {
  299. $error++;
  300. $errorforline++;
  301. $errorforinvoice[$key]='other';
  302. setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
  303. }
  304. }
  305. //}
  306. }
  307. }
  308. // Product / Service
  309. if (! $errorforline)
  310. {
  311. foreach ($tabht[$key] as $k => $mt) {
  312. //if ($mt) {
  313. // get compte id and label
  314. if ($accountingaccount->fetch(null, $k, true)) {
  315. $bookkeeping = new BookKeeping($db);
  316. $bookkeeping->doc_date = $val["date"];
  317. $bookkeeping->date_lim_reglement = $val["datereg"];
  318. $bookkeeping->doc_ref = $val["ref"];
  319. $bookkeeping->date_creation = $now;
  320. $bookkeeping->doc_type = 'customer_invoice';
  321. $bookkeeping->fk_doc = $key;
  322. $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
  323. $bookkeeping->thirdparty_code = $companystatic->code_client;
  324. $bookkeeping->subledger_account = '';
  325. $bookkeeping->subledger_label = '';
  326. $bookkeeping->numero_compte = $k;
  327. $bookkeeping->label_compte = $accountingaccount->label;
  328. $bookkeeping->label_operation = dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->ref . ' - ' . $accountingaccount->label;
  329. $bookkeeping->montant = $mt;
  330. $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
  331. $bookkeeping->debit = ($mt < 0) ? -$mt : 0;
  332. $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
  333. $bookkeeping->code_journal = $journal;
  334. $bookkeeping->journal_label = $journal_label;
  335. $bookkeeping->fk_user_author = $user->id;
  336. $bookkeeping->entity = $conf->entity;
  337. $totaldebit += $bookkeeping->debit;
  338. $totalcredit += $bookkeeping->credit;
  339. $result = $bookkeeping->create($user);
  340. if ($result < 0) {
  341. if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') // Already exists
  342. {
  343. $error++;
  344. $errorforline++;
  345. $errorforinvoice[$key]='alreadyjournalized';
  346. //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
  347. }
  348. else
  349. {
  350. $error++;
  351. $errorforline++;
  352. $errorforinvoice[$key]='other';
  353. setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
  354. }
  355. }
  356. }
  357. //}
  358. }
  359. }
  360. // VAT
  361. if (! $errorforline)
  362. {
  363. $listoftax=array(0, 1, 2);
  364. foreach($listoftax as $numtax)
  365. {
  366. $arrayofvat = $tabtva;
  367. if ($numtax == 1) $arrayofvat = $tablocaltax1;
  368. if ($numtax == 2) $arrayofvat = $tablocaltax2;
  369. foreach ($arrayofvat[$key] as $k => $mt) {
  370. if ($mt) {
  371. $bookkeeping = new BookKeeping($db);
  372. $bookkeeping->doc_date = $val["date"];
  373. $bookkeeping->date_lim_reglement = $val["datereg"];
  374. $bookkeeping->doc_ref = $val["ref"];
  375. $bookkeeping->date_creation = $now;
  376. $bookkeeping->doc_type = 'customer_invoice';
  377. $bookkeeping->fk_doc = $key;
  378. $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
  379. $bookkeeping->thirdparty_code = $companystatic->code_client;
  380. $bookkeeping->subledger_account = '';
  381. $bookkeeping->subledger_label = '';
  382. $bookkeeping->numero_compte = $k;
  383. $accountingaccount->fetch($k, null, true);
  384. $bookkeeping->label_compte = $accountingaccount->label;
  385. $bookkeeping->label_operation = dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("VAT").' '.join(', ', $def_tva[$key][$k]) .' %' . ($numtax?' - Localtax '.$numtax:'');
  386. $bookkeeping->montant = $mt;
  387. $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
  388. $bookkeeping->debit = ($mt < 0) ? -$mt : 0;
  389. $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
  390. $bookkeeping->code_journal = $journal;
  391. $bookkeeping->journal_label = $journal_label;
  392. $bookkeeping->fk_user_author = $user->id;
  393. $bookkeeping->entity = $conf->entity;
  394. $totaldebit += $bookkeeping->debit;
  395. $totalcredit += $bookkeeping->credit;
  396. $result = $bookkeeping->create($user);
  397. if ($result < 0) {
  398. if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') // Already exists
  399. {
  400. $error++;
  401. $errorforline++;
  402. $errorforinvoice[$key]='alreadyjournalized';
  403. //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
  404. }
  405. else
  406. {
  407. $error++;
  408. $errorforline++;
  409. $errorforinvoice[$key]='other';
  410. setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
  411. }
  412. }
  413. }
  414. }
  415. }
  416. }
  417. // Protection against a bug on lines before
  418. if (! $errorforline && (price2num($totaldebit) != price2num($totalcredit)))
  419. {
  420. $error++;
  421. $errorforline++;
  422. $errorforinvoice[$key]='amountsnotbalanced';
  423. setEventMessages('Try to insert a non balanced transaction in book for '.$invoicestatic->ref.'. Canceled. Surely a bug.', null, 'errors');
  424. }
  425. if (! $errorforline)
  426. {
  427. $db->commit();
  428. }
  429. else
  430. {
  431. $db->rollback();
  432. if ($error >= 10)
  433. {
  434. setEventMessages($langs->trans("ErrorTooManyErrorsProcessStopped"), null, 'errors');
  435. break; // Break in the foreach
  436. }
  437. }
  438. }
  439. $tabpay = $tabfac;
  440. if (empty($error) && count($tabpay) > 0) {
  441. setEventMessages($langs->trans("GeneralLedgerIsWritten"), null, 'mesgs');
  442. }
  443. elseif (count($tabpay) == $error)
  444. {
  445. setEventMessages($langs->trans("NoNewRecordSaved"), null, 'warnings');
  446. }
  447. else
  448. {
  449. setEventMessages($langs->trans("GeneralLedgerSomeRecordWasNotRecorded"), null, 'warnings');
  450. }
  451. $action='';
  452. // Must reload data, so we make a redirect
  453. if (count($tabpay) != $error)
  454. {
  455. $param='id_journal='.$id_journal;
  456. $param.='&date_startday='.$date_startday;
  457. $param.='&date_startmonth='.$date_startmonth;
  458. $param.='&date_startyear='.$date_startyear;
  459. $param.='&date_endday='.$date_endday;
  460. $param.='&date_endmonth='.$date_endmonth;
  461. $param.='&date_endyear='.$date_endyear;
  462. $param.='&in_bookkeeping='.$in_bookkeeping;
  463. header("Location: ".$_SERVER['PHP_SELF'].($param?'?'.$param:''));
  464. exit;
  465. }
  466. }
  467. /*
  468. * View
  469. */
  470. $form = new Form($db);
  471. // Export
  472. if ($action == 'exportcsv') { // ISO and not UTF8 !
  473. $sep = $conf->global->ACCOUNTING_EXPORT_SEPARATORCSV;
  474. $filename = 'journal';
  475. $type_export = 'journal';
  476. include DOL_DOCUMENT_ROOT . '/accountancy/tpl/export_journal.tpl.php';
  477. $companystatic = new Client($db);
  478. $invoicestatic = new Facture($db);
  479. foreach ($tabfac as $key => $val)
  480. {
  481. $companystatic->id = $tabcompany[$key]['id'];
  482. $companystatic->name = $tabcompany[$key]['name'];
  483. $companystatic->code_compta = $tabcompany[$key]['code_compta'];
  484. $companystatic->code_compta_fournisseur = $tabcompany[$key]['code_compta_fournisseur'];
  485. $companystatic->code_client = $tabcompany[$key]['code_client'];
  486. $companystatic->code_fournisseur = $tabcompany[$key]['code_fournisseur'];
  487. $companystatic->client = 3;
  488. $invoicestatic->id = $key;
  489. $invoicestatic->ref = (string) $val["ref"];
  490. $invoicestatic->type = $val["type"];
  491. $invoicestatic->close_code = $val["close_code"];
  492. $date = dol_print_date($val["date"], 'day');
  493. // Is it a replaced invoice ? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
  494. $replacedinvoice = 0;
  495. if ($invoicestatic->close_code == Facture::CLOSECODE_REPLACED)
  496. {
  497. $replacedinvoice = 1;
  498. $alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
  499. if ($alreadydispatched) $replacedinvoice = 2;
  500. }
  501. // 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)
  502. if ($replacedinvoice == 1)
  503. {
  504. continue;
  505. }
  506. // Third party
  507. foreach ($tabttc[$key] as $k => $mt) {
  508. //if ($mt) {
  509. print '"' . $key . '"' . $sep;
  510. print '"' . $date . '"' . $sep;
  511. print '"' . $val["ref"] . '"' . $sep;
  512. print '"' . utf8_decode(dol_trunc($companystatic->name, 32)) . '"' . $sep;
  513. print '"' . length_accounta(html_entity_decode($k)) . '"' . $sep;
  514. print '"' . $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER . '"' . $sep;
  515. print '"' . length_accounta(html_entity_decode($k)) . '"' . $sep;
  516. print '"' . $langs->trans("Thirdparty") . '"' . $sep;
  517. print '"' . utf8_decode(dol_trunc($companystatic->name, 16)) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("Thirdparty") . '"' . $sep;
  518. print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep;
  519. print '"' . ($mt < 0 ? price(- $mt) : '') . '"' . $sep;
  520. print '"' . $journal . '"';
  521. print "\n";
  522. //}
  523. }
  524. // Product / Service
  525. foreach ($tabht[$key] as $k => $mt) {
  526. $accountingaccount = new AccountingAccount($db);
  527. $accountingaccount->fetch(null, $k, true);
  528. //if ($mt) {
  529. print '"' . $key . '"' . $sep;
  530. print '"' . $date . '"' . $sep;
  531. print '"' . $val["ref"] . '"' . $sep;
  532. print '"' . utf8_decode(dol_trunc($companystatic->name, 32)) . '"' . $sep;
  533. print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep;
  534. print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep;
  535. print '""' . $sep;
  536. print '"' . utf8_decode(dol_trunc($accountingaccount->label, 32)) . '"' . $sep;
  537. print '"' . utf8_decode(dol_trunc($companystatic->name, 16)) . ' - ' . dol_trunc($accountingaccount->label, 32) . '"' . $sep;
  538. print '"' . ($mt < 0 ? price(- $mt) : '') . '"' . $sep;
  539. print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep;
  540. print '"' . $journal . '"';
  541. print "\n";
  542. //}
  543. }
  544. // VAT
  545. $listoftax = array(0, 1, 2);
  546. foreach ($listoftax as $numtax) {
  547. $arrayofvat = $tabtva;
  548. if ($numtax == 1) $arrayofvat = $tablocaltax1;
  549. if ($numtax == 2) $arrayofvat = $tablocaltax2;
  550. foreach ($arrayofvat[$key] as $k => $mt) {
  551. if ($mt) {
  552. print '"' . $key . '"' . $sep;
  553. print '"' . $date . '"' . $sep;
  554. print '"' . $val["ref"] . '"' . $sep;
  555. print '"' . utf8_decode(dol_trunc($companystatic->name, 32)) . '"' . $sep;
  556. print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep;
  557. print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep;
  558. print '""' . $sep;
  559. print '"' . $langs->trans("VAT") . ' - ' . $def_tva[$key] . ' %"' . $sep;
  560. print '"' . utf8_decode(dol_trunc($companystatic->name, 16)) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("VAT") . join(', ', $def_tva[$key][$k]) .' %' . ($numtax?' - Localtax '.$numtax:'') . '"' . $sep;
  561. print '"' . ($mt < 0 ? price(- $mt) : '') . '"' . $sep;
  562. print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep;
  563. print '"' . $journal . '"';
  564. print "\n";
  565. }
  566. }
  567. }
  568. }
  569. }
  570. if (empty($action) || $action == 'view') {
  571. llxHeader('', $langs->trans("SellsJournal"));
  572. $nom = $langs->trans("SellsJournal") . ' | ' . $accountingjournalstatic->getNomUrl(0, 1, 1, '', 1);
  573. $nomlink = '';
  574. $periodlink = '';
  575. $exportlink = '';
  576. $builddate=dol_now();
  577. $description.= $langs->trans("DescJournalOnlyBindedVisible").'<br>';
  578. if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS))
  579. $description .= $langs->trans("DepositsAreNotIncluded");
  580. else
  581. $description .= $langs->trans("DepositsAreIncluded");
  582. $listofchoices=array('notyet'=>$langs->trans("NotYetInGeneralLedger"), 'already'=>$langs->trans("AlreadyInGeneralLedger"));
  583. $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);
  584. $period .= ' - ' .$langs->trans("JournalizationInLedgerStatus").' '. $form->selectarray('in_bookkeeping', $listofchoices, $in_bookkeeping, 1);
  585. $varlink = 'id_journal=' . $id_journal;
  586. journalHead($nom, $nomlink, $period, $periodlink, $description, $builddate, $exportlink, array('action' => ''), '', $varlink);
  587. // Button to write into Ledger
  588. if (($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER == "") || $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER == '-1') {
  589. print '<br>';
  590. print img_warning().' '.$langs->trans("SomeMandatoryStepsOfSetupWereNotDone");
  591. print ' : '.$langs->trans("AccountancyAreaDescMisc", 4, '<strong>'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("MenuDefaultAccounts").'</strong>');
  592. }
  593. print '<div class="tabsAction tabsActionNoBottom">';
  594. if (! empty($conf->global->ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL)) print '<input type="button" class="butAction" name="exportcsv" value="' . $langs->trans("ExportDraftJournal") . '" onclick="launch_export();" />';
  595. if (($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER == "") || $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER == '-1') {
  596. print '<input type="button" class="butActionRefused classfortooltip" title="'.dol_escape_htmltag($langs->trans("SomeMandatoryStepsOfSetupWereNotDone")).'" value="' . $langs->trans("WriteBookKeeping") . '" />';
  597. }
  598. else {
  599. if ($in_bookkeeping == 'notyet') print '<input type="button" class="butAction" name="writebookkeeping" value="' . $langs->trans("WriteBookKeeping") . '" onclick="writebookkeeping();" />';
  600. else print '<a href="#" class="butActionRefused classfortooltip" name="writebookkeeping">' . $langs->trans("WriteBookKeeping") . '</a>';
  601. }
  602. print '</div>';
  603. // TODO Avoid using js. We can use a direct link with $param
  604. print '
  605. <script type="text/javascript">
  606. function launch_export() {
  607. $("div.fiche form input[name=\"action\"]").val("exportcsv");
  608. $("div.fiche form input[type=\"submit\"]").click();
  609. $("div.fiche form input[name=\"action\"]").val("");
  610. }
  611. function writebookkeeping() {
  612. console.log("click on writebookkeeping");
  613. $("div.fiche form input[name=\"action\"]").val("writebookkeeping");
  614. $("div.fiche form input[type=\"submit\"]").click();
  615. $("div.fiche form input[name=\"action\"]").val("");
  616. }
  617. </script>';
  618. /*
  619. * Show result array
  620. */
  621. print '<br>';
  622. $i = 0;
  623. print '<div class="div-table-responsive">';
  624. print "<table class=\"noborder\" width=\"100%\">";
  625. print "<tr class=\"liste_titre\">";
  626. print "<td>" . $langs->trans("Date") . "</td>";
  627. print "<td>" . $langs->trans("Piece") . ' (' . $langs->trans("InvoiceRef") . ")</td>";
  628. print "<td>" . $langs->trans("AccountAccounting") . "</td>";
  629. print "<td>" . $langs->trans("SubledgerAccount") . "</td>";
  630. print "<td>" . $langs->trans("LabelOperation") . "</td>";
  631. print '<td class="center">' . $langs->trans("Debit") . "</td>";
  632. print '<td class="center">' . $langs->trans("Credit") . "</td>";
  633. print "</tr>\n";
  634. $r = '';
  635. $companystatic = new Client($db);
  636. $invoicestatic = new Facture($db);
  637. foreach ($tabfac as $key => $val)
  638. {
  639. $companystatic->id = $tabcompany[$key]['id'];
  640. $companystatic->name = $tabcompany[$key]['name'];
  641. $companystatic->code_compta = $tabcompany[$key]['code_compta'];
  642. $companystatic->code_compta_fournisseur = $tabcompany[$key]['code_compta_fournisseur'];
  643. $companystatic->code_client = $tabcompany[$key]['code_client'];
  644. $companystatic->code_fournisseur = $tabcompany[$key]['code_fournisseur'];
  645. $companystatic->client = 3;
  646. $invoicestatic->id = $key;
  647. $invoicestatic->ref = (string) $val["ref"];
  648. $invoicestatic->type = $val["type"];
  649. $invoicestatic->close_code = $val["close_code"];
  650. $date = dol_print_date($val["date"], 'day');
  651. // Is it a replaced invoice ? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
  652. $replacedinvoice = 0;
  653. if ($invoicestatic->close_code == Facture::CLOSECODE_REPLACED)
  654. {
  655. $replacedinvoice = 1;
  656. $alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
  657. if ($alreadydispatched) $replacedinvoice = 2;
  658. }
  659. // If not already into bookkeeping, we won't add it, if yes, add the counterpart ???.
  660. if ($replacedinvoice == 1)
  661. {
  662. print '<tr class="oddeven">';
  663. print "<!-- Replaced invoice -->";
  664. print "<td>" . $date . "</td>";
  665. print "<td><strike>" . $invoicestatic->getNomUrl(1) . "</strike></td>";
  666. // Account
  667. print "<td>";
  668. print $langs->trans("Replaced");
  669. print '</td>';
  670. // Subledger account
  671. print "<td>";
  672. print '</td>';
  673. print "<td>";
  674. print "</td>";
  675. print '<td class="right"></td>';
  676. print '<td class="right"></td>';
  677. print "</tr>";
  678. continue;
  679. }
  680. if ($errorforinvoice[$key] == 'somelinesarenotbound')
  681. {
  682. print '<tr class="oddeven">';
  683. print "<!-- Some lines are not bound -->";
  684. print "<td>" . $date . "</td>";
  685. print "<td>" . $invoicestatic->getNomUrl(1) . "</td>";
  686. // Account
  687. print "<td>";
  688. print '<span class="error">'.$langs->trans('ErrorInvoiceContainsLinesNotYetBoundedShort', $val['ref']).'</span>';
  689. print '</td>';
  690. // Subledger account
  691. print "<td>";
  692. print '</td>';
  693. print "<td>";
  694. print "</td>";
  695. print '<td class="right"></td>';
  696. print '<td class="right"></td>';
  697. print "</tr>";
  698. }
  699. // Third party
  700. foreach ($tabttc[$key] as $k => $mt)
  701. {
  702. //if ($mt) {
  703. print '<tr class="oddeven">';
  704. print "<!-- Thirdparty -->";
  705. print "<td>" . $date . "</td>";
  706. print "<td>" . $invoicestatic->getNomUrl(1) . "</td>";
  707. // Account
  708. print "<td>";
  709. $accountoshow = length_accounta($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER);
  710. if (($accountoshow == "") || $accountoshow == 'NotDefined')
  711. {
  712. print '<span class="error">'.$langs->trans("MainAccountForCustomersNotDefined").'</span>';
  713. }
  714. else print $accountoshow;
  715. print '</td>';
  716. // Subledger account
  717. print "<td>";
  718. $accountoshow = length_accounta($k);
  719. if (($accountoshow == "") || $accountoshow == 'NotDefined')
  720. {
  721. print '<span class="error">'.$langs->trans("ThirdpartyAccountNotDefined").'</span>';
  722. }
  723. else print $accountoshow;
  724. print '</td>';
  725. print "<td>" . $companystatic->getNomUrl(0, 'customer', 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("SubledgerAccount") . "</td>";
  726. print '<td class="right nowraponall">' . ($mt >= 0 ? price($mt) : '') . "</td>";
  727. print '<td class="right nowraponall">' . ($mt < 0 ? price(- $mt) : '') . "</td>";
  728. print "</tr>";
  729. //}
  730. }
  731. // Product / Service
  732. foreach ($tabht[$key] as $k => $mt)
  733. {
  734. $accountingaccount = new AccountingAccount($db);
  735. $accountingaccount->fetch(null, $k, true);
  736. //if ($mt) {
  737. print '<tr class="oddeven">';
  738. print "<!-- Product -->";
  739. print "<td>" . $date . "</td>";
  740. print "<td>" . $invoicestatic->getNomUrl(1) . "</td>";
  741. // Account
  742. print "<td>";
  743. $accountoshow = length_accountg($k);
  744. if (($accountoshow == "") || $accountoshow == 'NotDefined')
  745. {
  746. print '<span class="error">'.$langs->trans("ProductNotDefined").'</span>';
  747. }
  748. else print $accountoshow;
  749. print "</td>";
  750. // Subledger account
  751. print "<td>";
  752. print '</td>';
  753. $companystatic->id = $tabcompany[$key]['id'];
  754. $companystatic->name = $tabcompany[$key]['name'];
  755. print "<td>" . $companystatic->getNomUrl(0, 'customer', 16) . ' - ' . $invoicestatic->ref . ' - ' . $accountingaccount->label . "</td>";
  756. print '<td class="right nowraponall">' . ($mt < 0 ? price(- $mt) : '') . "</td>";
  757. print '<td class="right nowraponall">' . ($mt >= 0 ? price($mt) : '') . "</td>";
  758. print "</tr>";
  759. //}
  760. }
  761. // VAT
  762. $listoftax = array(0, 1, 2);
  763. foreach ($listoftax as $numtax)
  764. {
  765. $arrayofvat = $tabtva;
  766. if ($numtax == 1) $arrayofvat = $tablocaltax1;
  767. if ($numtax == 2) $arrayofvat = $tablocaltax2;
  768. foreach ($arrayofvat[$key] as $k => $mt) {
  769. if ($mt) {
  770. print '<tr class="oddeven">';
  771. print "<!-- VAT -->";
  772. print "<td>" . $date . "</td>";
  773. print "<td>" . $invoicestatic->getNomUrl(1) . "</td>";
  774. // Account
  775. print "<td>";
  776. $accountoshow = length_accountg($k);
  777. if (($accountoshow == "") || $accountoshow == 'NotDefined')
  778. {
  779. print '<span class="error">'.$langs->trans("VATAccountNotDefined").' ('.$langs->trans("Sale").')'.'</span>';
  780. }
  781. else print $accountoshow;
  782. print "</td>";
  783. // Subledger account
  784. print "<td>";
  785. print '</td>';
  786. print "<td>" . $companystatic->getNomUrl(0, 'customer', 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("VAT"). ' '.join(', ', $def_tva[$key][$k]).' %'.($numtax?' - Localtax '.$numtax:'');
  787. print "</td>";
  788. print '<td class="right nowraponall">' . ($mt < 0 ? price(- $mt) : '') . "</td>";
  789. print '<td class="right nowraponall">' . ($mt >= 0 ? price($mt) : '') . "</td>";
  790. print "</tr>";
  791. }
  792. }
  793. }
  794. }
  795. print "</table>";
  796. print '</div>';
  797. // End of page
  798. llxFooter();
  799. }
  800. $db->close();