sellsjournal.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913
  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 <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. $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. $idpays = $mysoc->country_id;
  83. $sql = "SELECT f.rowid, f.ref, f.type, f.datef as df, f.ref_client, f.date_lim_reglement as dlr, f.close_code,";
  84. $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,";
  85. $sql .= " s.rowid as socid, s.nom as name, s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur,";
  86. $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";
  87. $sql .= " FROM " . MAIN_DB_PREFIX . "facturedet as fd";
  88. $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product as p ON p.rowid = fd.fk_product";
  89. $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_account as aa ON aa.rowid = fd.fk_code_ventilation";
  90. $sql .= " JOIN " . MAIN_DB_PREFIX . "facture as f ON f.rowid = fd.fk_facture";
  91. $sql .= " JOIN " . MAIN_DB_PREFIX . "societe as s ON s.rowid = f.fk_soc";
  92. $sql .= " WHERE fd.fk_code_ventilation > 0";
  93. $sql .= " AND f.entity IN (".getEntity('invoice', 0).')'; // We don't share object for accountancy, we use source object sharing
  94. $sql .= " AND f.fk_statut > 0";
  95. if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { // Non common setup
  96. $sql .= " AND f.type IN (" . Facture::TYPE_STANDARD . "," . Facture::TYPE_REPLACEMENT . "," . Facture::TYPE_CREDIT_NOTE . "," . Facture::TYPE_SITUATION . ")";
  97. } else {
  98. $sql .= " AND f.type IN (" . Facture::TYPE_STANDARD . "," . Facture::TYPE_REPLACEMENT . "," . Facture::TYPE_CREDIT_NOTE . "," . Facture::TYPE_DEPOSIT . "," . Facture::TYPE_SITUATION . ")";
  99. }
  100. $sql .= " AND fd.product_type IN (0,1)";
  101. if ($date_start && $date_end)
  102. $sql .= " AND f.datef >= '" . $db->idate($date_start) . "' AND f.datef <= '" . $db->idate($date_end) . "'";
  103. // Already in bookkeeping or not
  104. if ($in_bookkeeping == 'already')
  105. {
  106. $sql .= " AND f.rowid IN (SELECT fk_doc FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as ab WHERE ab.doc_type='customer_invoice')";
  107. // $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
  108. }
  109. if ($in_bookkeeping == 'notyet')
  110. {
  111. $sql .= " AND f.rowid NOT IN (SELECT fk_doc FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as ab WHERE ab.doc_type='customer_invoice')";
  112. // $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
  113. }
  114. $sql .= " ORDER BY f.datef";
  115. //print $sql;
  116. dol_syslog('accountancy/journal/sellsjournal.php', LOG_DEBUG);
  117. $result = $db->query($sql);
  118. if ($result) {
  119. $tabfac = array ();
  120. $tabht = array ();
  121. $tabtva = array ();
  122. $def_tva = array ();
  123. $tabttc = array ();
  124. $tablocaltax1 = array ();
  125. $tablocaltax2 = array ();
  126. $tabcompany = array ();
  127. $num = $db->num_rows($result);
  128. // Variables
  129. $cptcli = (! empty($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER)) ? $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER : 'NotDefined';
  130. $cpttva = (! empty($conf->global->ACCOUNTING_VAT_SOLD_ACCOUNT)) ? $conf->global->ACCOUNTING_VAT_SOLD_ACCOUNT : 'NotDefined';
  131. $i = 0;
  132. while ( $i < $num ) {
  133. $obj = $db->fetch_object($result);
  134. // Controls
  135. $compta_soc = (! empty($obj->code_compta)) ? $obj->code_compta : $cptcli;
  136. $compta_prod = $obj->compte;
  137. if (empty($compta_prod)) {
  138. if ($obj->product_type == 0)
  139. $compta_prod = (! empty($conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT)) ? $conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT : 'NotDefined';
  140. else
  141. $compta_prod = (! empty($conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT)) ? $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT : 'NotDefined';
  142. }
  143. $vatdata = getTaxesFromId($obj->tva_tx.($obj->vat_src_code?' ('.$obj->vat_src_code.')':''), $mysoc, $mysoc, 0);
  144. $compta_tva = (! empty($vatdata['accountancy_code_sell']) ? $vatdata['accountancy_code_sell'] : $cpttva);
  145. $compta_localtax1 = (! empty($vatdata['accountancy_code_sell']) ? $vatdata['accountancy_code_sell'] : $cpttva);
  146. $compta_localtax2 = (! empty($vatdata['accountancy_code_sell']) ? $vatdata['accountancy_code_sell'] : $cpttva);
  147. // Define array to display all VAT rates that use this accounting account $compta_tva
  148. if (price2num($obj->tva_tx) || ! empty($obj->vat_src_code))
  149. {
  150. $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.')':''));
  151. }
  152. $line = new FactureLigne($db);
  153. $line->fetch($obj->fdid);
  154. // Situation invoices handling
  155. $prev_progress = $line->get_prev_progress($obj->rowid);
  156. if ($obj->type == Facture::TYPE_SITUATION) {
  157. // Avoid divide by 0
  158. if ($obj->situation_percent == 0) {
  159. $situation_ratio = 0;
  160. } else {
  161. $situation_ratio = ($obj->situation_percent - $prev_progress) / $obj->situation_percent;
  162. }
  163. } else {
  164. $situation_ratio = 1;
  165. }
  166. // Invoice lines
  167. $tabfac[$obj->rowid]["date"] = $db->jdate($obj->df);
  168. $tabfac[$obj->rowid]["datereg"] = $db->jdate($obj->dlr);
  169. $tabfac[$obj->rowid]["ref"] = $obj->ref;
  170. $tabfac[$obj->rowid]["type"] = $obj->type;
  171. $tabfac[$obj->rowid]["description"] = $obj->label_compte;
  172. $tabfac[$obj->rowid]["close_code"] = $obj->close_code; // close_code = 'replaced' for replacement invoices (not used in most european countries)
  173. //$tabfac[$obj->rowid]["fk_facturedet"] = $obj->fdid;
  174. // Avoid warnings
  175. if (! isset($tabttc[$obj->rowid][$compta_soc])) $tabttc[$obj->rowid][$compta_soc] = 0;
  176. if (! isset($tabht[$obj->rowid][$compta_prod])) $tabht[$obj->rowid][$compta_prod] = 0;
  177. if (! isset($tabtva[$obj->rowid][$compta_tva])) $tabtva[$obj->rowid][$compta_tva] = 0;
  178. if (! isset($tablocaltax1[$obj->rowid][$compta_localtax1])) $tablocaltax1[$obj->rowid][$compta_localtax1] = 0;
  179. if (! isset($tablocaltax2[$obj->rowid][$compta_localtax2])) $tablocaltax2[$obj->rowid][$compta_localtax2] = 0;
  180. $tabttc[$obj->rowid][$compta_soc] += $obj->total_ttc * $situation_ratio;
  181. $tabht[$obj->rowid][$compta_prod] += $obj->total_ht * $situation_ratio;
  182. if (empty($line->tva_npr)) $tabtva[$obj->rowid][$compta_tva] += $obj->total_tva * $situation_ratio; // We ignore line if VAT is a NPR
  183. $tablocaltax1[$obj->rowid][$compta_localtax1] += $obj->total_localtax1 * $situation_ratio;
  184. $tablocaltax2[$obj->rowid][$compta_localtax2] += $obj->total_localtax2 * $situation_ratio;
  185. $tabcompany[$obj->rowid] = array (
  186. 'id' => $obj->socid,
  187. 'name' => $obj->name,
  188. 'code_client' => $obj->code_client,
  189. 'code_compta' => $compta_soc
  190. );
  191. $i ++;
  192. }
  193. } else {
  194. dol_print_error($db);
  195. }
  196. $errorforinvoice = array();
  197. // Loop in invoices to detect lines with not binding lines
  198. foreach ($tabfac as $key => $val) { // Loop on each invoice
  199. $sql = "SELECT COUNT(fd.rowid) as nb";
  200. $sql.= " FROM " . MAIN_DB_PREFIX . "facturedet as fd";
  201. $sql.= " WHERE fd.product_type <= 2 AND fd.fk_code_ventilation <= 0";
  202. $sql.= " AND fd.total_ttc <> 0 AND fk_facture = ".$key;
  203. $resql=$db->query($sql);
  204. if ($resql)
  205. {
  206. $obj = $db->fetch_object($resql);
  207. if ($obj->nb > 0)
  208. {
  209. $errorforinvoice[$key]='somelinesarenotbound';
  210. }
  211. }
  212. else dol_print_error($db);
  213. }
  214. //var_dump($errorforinvoice);exit;
  215. // Bookkeeping Write
  216. if ($action == 'writebookkeeping') {
  217. $now = dol_now();
  218. $error = 0;
  219. $companystatic = new Societe($db);
  220. $invoicestatic = new Facture($db);
  221. foreach ($tabfac as $key => $val) { // Loop on each invoice
  222. $errorforline = 0;
  223. $totalcredit = 0;
  224. $totaldebit = 0;
  225. $db->begin();
  226. $companystatic->id = $tabcompany[$key]['id'];
  227. $companystatic->name = $tabcompany[$key]['name'];
  228. $companystatic->code_compta = $tabcompany[$key]['code_compta'];
  229. $companystatic->code_compta_fournisseur = $tabcompany[$key]['code_compta_fournisseur'];
  230. $companystatic->code_client = $tabcompany[$key]['code_client'];
  231. $companystatic->code_fournisseur = $tabcompany[$key]['code_fournisseur'];
  232. $companystatic->client = 3;
  233. $invoicestatic->id = $key;
  234. $invoicestatic->ref = (string) $val["ref"];
  235. $invoicestatic->type = $val["type"];
  236. $invoicestatic->close_code = $val["close_code"];
  237. $date = dol_print_date($val["date"], 'day');
  238. // Is it a replaced invoice ? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
  239. $replacedinvoice = 0;
  240. if ($invoicestatic->close_code == Facture::CLOSECODE_REPLACED)
  241. {
  242. $replacedinvoice = 1;
  243. $alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
  244. if ($alreadydispatched) $replacedinvoice = 2;
  245. }
  246. // 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)
  247. if ($replacedinvoice == 1)
  248. {
  249. $db->rollback();
  250. continue;
  251. }
  252. // Error if some lines are not binded/ready to be journalized
  253. if ($errorforinvoice[$key] == 'somelinesarenotbound')
  254. {
  255. $error++;
  256. $errorforline++;
  257. setEventMessages($langs->trans('ErrorInvoiceContainsLinesNotYetBounded', $val['ref']), null, 'errors');
  258. }
  259. // Thirdparty
  260. if (! $errorforline)
  261. {
  262. foreach ( $tabttc[$key] as $k => $mt ) {
  263. //if ($mt) {
  264. $bookkeeping = new BookKeeping($db);
  265. $bookkeeping->doc_date = $val["date"];
  266. $bookkeeping->date_lim_reglement = $val["datereg"];
  267. $bookkeeping->doc_ref = $val["ref"];
  268. $bookkeeping->date_create = $now;
  269. $bookkeeping->doc_type = 'customer_invoice';
  270. $bookkeeping->fk_doc = $key;
  271. $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
  272. $bookkeeping->thirdparty_code = $companystatic->code_client;
  273. $bookkeeping->subledger_account = $tabcompany[$key]['code_compta'];
  274. $bookkeeping->subledger_label = $tabcompany[$key]['name'];
  275. $bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER;
  276. $accountingaccount->fetch(null, $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER, true);
  277. $bookkeeping->label_compte = $accountingaccount->label;
  278. $bookkeeping->label_operation = dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("SubledgerAccount");
  279. $bookkeeping->montant = $mt;
  280. $bookkeeping->sens = ($mt >= 0) ? 'D' : 'C';
  281. $bookkeeping->debit = ($mt >= 0) ? $mt : 0;
  282. $bookkeeping->credit = ($mt < 0) ? -$mt : 0;
  283. $bookkeeping->code_journal = $journal;
  284. $bookkeeping->journal_label = $journal_label;
  285. $bookkeeping->fk_user_author = $user->id;
  286. $bookkeeping->entity = $conf->entity;
  287. $totaldebit += $bookkeeping->debit;
  288. $totalcredit += $bookkeeping->credit;
  289. $result = $bookkeeping->create($user);
  290. if ($result < 0) {
  291. if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') // Already exists
  292. {
  293. $error++;
  294. $errorforline++;
  295. $errorforinvoice[$key]='alreadyjournalized';
  296. //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
  297. }
  298. else
  299. {
  300. $error++;
  301. $errorforline++;
  302. $errorforinvoice[$key]='other';
  303. setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
  304. }
  305. }
  306. //}
  307. }
  308. }
  309. // Product / Service
  310. if (! $errorforline)
  311. {
  312. foreach ( $tabht[$key] as $k => $mt ) {
  313. //if ($mt) {
  314. // get compte id and label
  315. if ($accountingaccount->fetch(null, $k, true)) {
  316. $bookkeeping = new BookKeeping($db);
  317. $bookkeeping->doc_date = $val["date"];
  318. $bookkeeping->date_lim_reglement = $val["datereg"];
  319. $bookkeeping->doc_ref = $val["ref"];
  320. $bookkeeping->date_create = $now;
  321. $bookkeeping->doc_type = 'customer_invoice';
  322. $bookkeeping->fk_doc = $key;
  323. $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
  324. $bookkeeping->thirdparty_code = $companystatic->code_client;
  325. $bookkeeping->subledger_account = '';
  326. $bookkeeping->subledger_label = '';
  327. $bookkeeping->numero_compte = $k;
  328. $bookkeeping->label_compte = $accountingaccount->label;
  329. $bookkeeping->label_operation = dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->ref . ' - ' . $accountingaccount->label;
  330. $bookkeeping->montant = $mt;
  331. $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
  332. $bookkeeping->debit = ($mt < 0) ? -$mt : 0;
  333. $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
  334. $bookkeeping->code_journal = $journal;
  335. $bookkeeping->journal_label = $journal_label;
  336. $bookkeeping->fk_user_author = $user->id;
  337. $bookkeeping->entity = $conf->entity;
  338. $totaldebit += $bookkeeping->debit;
  339. $totalcredit += $bookkeeping->credit;
  340. $result = $bookkeeping->create($user);
  341. if ($result < 0) {
  342. if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') // Already exists
  343. {
  344. $error++;
  345. $errorforline++;
  346. $errorforinvoice[$key]='alreadyjournalized';
  347. //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
  348. }
  349. else
  350. {
  351. $error++;
  352. $errorforline++;
  353. $errorforinvoice[$key]='other';
  354. setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
  355. }
  356. }
  357. }
  358. //}
  359. }
  360. }
  361. // VAT
  362. if (! $errorforline)
  363. {
  364. $listoftax=array(0, 1, 2);
  365. foreach($listoftax as $numtax)
  366. {
  367. $arrayofvat = $tabtva;
  368. if ($numtax == 1) $arrayofvat = $tablocaltax1;
  369. if ($numtax == 2) $arrayofvat = $tablocaltax2;
  370. foreach ( $arrayofvat[$key] as $k => $mt ) {
  371. if ($mt) {
  372. $bookkeeping = new BookKeeping($db);
  373. $bookkeeping->doc_date = $val["date"];
  374. $bookkeeping->date_lim_reglement = $val["datereg"];
  375. $bookkeeping->doc_ref = $val["ref"];
  376. $bookkeeping->date_create = $now;
  377. $bookkeeping->doc_type = 'customer_invoice';
  378. $bookkeeping->fk_doc = $key;
  379. $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
  380. $bookkeeping->thirdparty_code = $companystatic->code_client;
  381. $bookkeeping->subledger_account = '';
  382. $bookkeeping->subledger_label = '';
  383. $bookkeeping->numero_compte = $k;
  384. $accountingaccount->fetch($k, null, true);
  385. $bookkeeping->label_compte = $accountingaccount->label;
  386. $bookkeeping->label_operation = dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("VAT").' '.join(', ',$def_tva[$key][$k]) .' %' . ($numtax?' - Localtax '.$numtax:'');
  387. $bookkeeping->montant = $mt;
  388. $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
  389. $bookkeeping->debit = ($mt < 0) ? -$mt : 0;
  390. $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
  391. $bookkeeping->code_journal = $journal;
  392. $bookkeeping->journal_label = $journal_label;
  393. $bookkeeping->fk_user_author = $user->id;
  394. $bookkeeping->entity = $conf->entity;
  395. $totaldebit += $bookkeeping->debit;
  396. $totalcredit += $bookkeeping->credit;
  397. $result = $bookkeeping->create($user);
  398. if ($result < 0) {
  399. if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') // Already exists
  400. {
  401. $error++;
  402. $errorforline++;
  403. $errorforinvoice[$key]='alreadyjournalized';
  404. //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
  405. }
  406. else
  407. {
  408. $error++;
  409. $errorforline++;
  410. $errorforinvoice[$key]='other';
  411. setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
  412. }
  413. }
  414. }
  415. }
  416. }
  417. }
  418. // Protection against a bug on lines before
  419. if (! $errorforline && (price2num($totaldebit) != price2num($totalcredit)))
  420. {
  421. $error++;
  422. $errorforline++;
  423. $errorforinvoice[$key]='amountsnotbalanced';
  424. setEventMessages('Try to insert a non balanced transaction in book for '.$invoicestatic->ref.'. Canceled. Surely a bug.', null, 'errors');
  425. }
  426. if (! $errorforline)
  427. {
  428. $db->commit();
  429. }
  430. else
  431. {
  432. $db->rollback();
  433. if ($error >= 10)
  434. {
  435. setEventMessages($langs->trans("ErrorTooManyErrorsProcessStopped"), null, 'errors');
  436. break; // Break in the foreach
  437. }
  438. }
  439. }
  440. $tabpay = $tabfac;
  441. if (empty($error) && count($tabpay) > 0) {
  442. setEventMessages($langs->trans("GeneralLedgerIsWritten"), null, 'mesgs');
  443. }
  444. elseif (count($tabpay) == $error)
  445. {
  446. setEventMessages($langs->trans("NoNewRecordSaved"), null, 'warnings');
  447. }
  448. else
  449. {
  450. setEventMessages($langs->trans("GeneralLedgerSomeRecordWasNotRecorded"), null, 'warnings');
  451. }
  452. $action='';
  453. // Must reload data, so we make a redirect
  454. if (count($tabpay) != $error)
  455. {
  456. $param='id_journal='.$id_journal;
  457. $param.='&date_startday='.$date_startday;
  458. $param.='&date_startmonth='.$date_startmonth;
  459. $param.='&date_startyear='.$date_startyear;
  460. $param.='&date_endday='.$date_endday;
  461. $param.='&date_endmonth='.$date_endmonth;
  462. $param.='&date_endyear='.$date_endyear;
  463. $param.='&in_bookkeeping='.$in_bookkeeping;
  464. header("Location: ".$_SERVER['PHP_SELF'].($param?'?'.$param:''));
  465. exit;
  466. }
  467. }
  468. /*
  469. * View
  470. */
  471. $form = new Form($db);
  472. // Export
  473. if ($action == 'exportcsv') { // ISO and not UTF8 !
  474. $sep = $conf->global->ACCOUNTING_EXPORT_SEPARATORCSV;
  475. $filename = 'journal';
  476. $type_export = 'journal';
  477. include DOL_DOCUMENT_ROOT . '/accountancy/tpl/export_journal.tpl.php';
  478. $companystatic = new Client($db);
  479. $invoicestatic = new Facture($db);
  480. foreach ( $tabfac as $key => $val )
  481. {
  482. $companystatic->id = $tabcompany[$key]['id'];
  483. $companystatic->name = $tabcompany[$key]['name'];
  484. $companystatic->code_compta = $tabcompany[$key]['code_compta'];
  485. $companystatic->code_compta_fournisseur = $tabcompany[$key]['code_compta_fournisseur'];
  486. $companystatic->code_client = $tabcompany[$key]['code_client'];
  487. $companystatic->code_fournisseur = $tabcompany[$key]['code_fournisseur'];
  488. $companystatic->client = 3;
  489. $invoicestatic->id = $key;
  490. $invoicestatic->ref = (string) $val["ref"];
  491. $invoicestatic->type = $val["type"];
  492. $invoicestatic->close_code = $val["close_code"];
  493. $date = dol_print_date($val["date"], 'day');
  494. // Is it a replaced invoice ? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
  495. $replacedinvoice = 0;
  496. if ($invoicestatic->close_code == Facture::CLOSECODE_REPLACED)
  497. {
  498. $replacedinvoice = 1;
  499. $alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
  500. if ($alreadydispatched) $replacedinvoice = 2;
  501. }
  502. // 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)
  503. if ($replacedinvoice == 1)
  504. {
  505. continue;
  506. }
  507. // Third party
  508. foreach ($tabttc[$key] as $k => $mt) {
  509. //if ($mt) {
  510. print '"' . $key . '"' . $sep;
  511. print '"' . $date . '"' . $sep;
  512. print '"' . $val["ref"] . '"' . $sep;
  513. print '"' . utf8_decode(dol_trunc($companystatic->name, 32)) . '"' . $sep;
  514. print '"' . length_accounta(html_entity_decode($k)) . '"' . $sep;
  515. print '"' . $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER . '"' . $sep;
  516. print '"' . length_accounta(html_entity_decode($k)) . '"' . $sep;
  517. print '"' . $langs->trans("Thirdparty") . '"' . $sep;
  518. print '"' . utf8_decode(dol_trunc($companystatic->name, 16)) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("Thirdparty") . '"' . $sep;
  519. print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep;
  520. print '"' . ($mt < 0 ? price(- $mt) : '') . '"' . $sep;
  521. print '"' . $journal . '"';
  522. print "\n";
  523. //}
  524. }
  525. // Product / Service
  526. foreach ($tabht[$key] as $k => $mt) {
  527. $accountingaccount = new AccountingAccount($db);
  528. $accountingaccount->fetch(null, $k, true);
  529. //if ($mt) {
  530. print '"' . $key . '"' . $sep;
  531. print '"' . $date . '"' . $sep;
  532. print '"' . $val["ref"] . '"' . $sep;
  533. print '"' . utf8_decode(dol_trunc($companystatic->name, 32)) . '"' . $sep;
  534. print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep;
  535. print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep;
  536. print '""' . $sep;
  537. print '"' . utf8_decode(dol_trunc($accountingaccount->label, 32)) . '"' . $sep;
  538. print '"' . utf8_decode(dol_trunc($companystatic->name, 16)) . ' - ' . dol_trunc($accountingaccount->label, 32) . '"' . $sep;
  539. print '"' . ($mt < 0 ? price(- $mt) : '') . '"' . $sep;
  540. print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep;
  541. print '"' . $journal . '"';
  542. print "\n";
  543. //}
  544. }
  545. // VAT
  546. $listoftax = array(0, 1, 2);
  547. foreach ($listoftax as $numtax) {
  548. $arrayofvat = $tabtva;
  549. if ($numtax == 1) $arrayofvat = $tablocaltax1;
  550. if ($numtax == 2) $arrayofvat = $tablocaltax2;
  551. foreach ($arrayofvat[$key] as $k => $mt) {
  552. if ($mt) {
  553. print '"' . $key . '"' . $sep;
  554. print '"' . $date . '"' . $sep;
  555. print '"' . $val["ref"] . '"' . $sep;
  556. print '"' . utf8_decode(dol_trunc($companystatic->name, 32)) . '"' . $sep;
  557. print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep;
  558. print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep;
  559. print '""' . $sep;
  560. print '"' . $langs->trans("VAT") . ' - ' . $def_tva[$key] . ' %"' . $sep;
  561. print '"' . utf8_decode(dol_trunc($companystatic->name, 16)) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("VAT") . join(', ',$def_tva[$key][$k]) .' %' . ($numtax?' - Localtax '.$numtax:'') . '"' . $sep;
  562. print '"' . ($mt < 0 ? price(- $mt) : '') . '"' . $sep;
  563. print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep;
  564. print '"' . $journal . '"';
  565. print "\n";
  566. }
  567. }
  568. }
  569. }
  570. }
  571. if (empty($action) || $action == 'view') {
  572. llxHeader('', $langs->trans("SellsJournal"));
  573. $nom = $langs->trans("SellsJournal") . ' | ' . $accountingjournalstatic->getNomUrl(0,1,1,'',1);
  574. $nomlink = '';
  575. $periodlink = '';
  576. $exportlink = '';
  577. $builddate=dol_now();
  578. $description.= $langs->trans("DescJournalOnlyBindedVisible").'<br>';
  579. if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS))
  580. $description .= $langs->trans("DepositsAreNotIncluded");
  581. else
  582. $description .= $langs->trans("DepositsAreIncluded");
  583. $listofchoices=array('notyet'=>$langs->trans("NotYetInGeneralLedger"), 'already'=>$langs->trans("AlreadyInGeneralLedger"));
  584. $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);
  585. $period .= ' - ' .$langs->trans("JournalizationInLedgerStatus").' '. $form->selectarray('in_bookkeeping', $listofchoices, $in_bookkeeping, 1);
  586. $varlink = 'id_journal=' . $id_journal;
  587. journalHead($nom, $nomlink, $period, $periodlink, $description, $builddate, $exportlink, array('action' => ''), '', $varlink);
  588. // Button to write into Ledger
  589. if (empty($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER) || $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER == '-1') {
  590. print img_warning().' '.$langs->trans("SomeMandatoryStepsOfSetupWereNotDone");
  591. print ' : '.$langs->trans("AccountancyAreaDescMisc", 4, '<strong>'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$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 (empty($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></td>";
  627. print "<td>" . $langs->trans("Date") . "</td>";
  628. print "<td>" . $langs->trans("Piece") . ' (' . $langs->trans("InvoiceRef") . ")</td>";
  629. print "<td>" . $langs->trans("AccountAccounting") . "</td>";
  630. print "<td>" . $langs->trans("SubledgerAccount") . "</td>";
  631. print "<td>" . $langs->trans("LabelOperation") . "</td>";
  632. print "<td class='right'>" . $langs->trans("Debit") . "</td>";
  633. print "<td class='right'>" . $langs->trans("Credit") . "</td>";
  634. print "</tr>\n";
  635. $r = '';
  636. $companystatic = new Client($db);
  637. $invoicestatic = new Facture($db);
  638. foreach ( $tabfac as $key => $val )
  639. {
  640. $companystatic->id = $tabcompany[$key]['id'];
  641. $companystatic->name = $tabcompany[$key]['name'];
  642. $companystatic->code_compta = $tabcompany[$key]['code_compta'];
  643. $companystatic->code_compta_fournisseur = $tabcompany[$key]['code_compta_fournisseur'];
  644. $companystatic->code_client = $tabcompany[$key]['code_client'];
  645. $companystatic->code_fournisseur = $tabcompany[$key]['code_fournisseur'];
  646. $companystatic->client = 3;
  647. $invoicestatic->id = $key;
  648. $invoicestatic->ref = (string) $val["ref"];
  649. $invoicestatic->type = $val["type"];
  650. $invoicestatic->close_code = $val["close_code"];
  651. $date = dol_print_date($val["date"], 'day');
  652. // Is it a replaced invoice ? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
  653. $replacedinvoice = 0;
  654. if ($invoicestatic->close_code == Facture::CLOSECODE_REPLACED)
  655. {
  656. $replacedinvoice = 1;
  657. $alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
  658. if ($alreadydispatched) $replacedinvoice = 2;
  659. }
  660. // If not already into bookkeeping, we won't add it, if yes, add the counterpart ???.
  661. if ($replacedinvoice == 1)
  662. {
  663. print '<tr class="oddeven">';
  664. print "<td><!-- Replaced invoice --></td>";
  665. print "<td>" . $date . "</td>";
  666. print "<td><strike>" . $invoicestatic->getNomUrl(1) . "</strike></td>";
  667. // Account
  668. print "<td>";
  669. print $langs->trans("Replaced");
  670. print '</td>';
  671. // Subledger account
  672. print "<td>";
  673. print '</td>';
  674. print "<td>";
  675. print "</td>";
  676. print '<td class="right"></td>';
  677. print '<td class="right"></td>';
  678. print "</tr>";
  679. continue;
  680. }
  681. if ($errorforinvoice[$key] == 'somelinesarenotbound')
  682. {
  683. print '<tr class="oddeven">';
  684. print "<td><!-- Some lines are not bound --></td>";
  685. print "<td>" . $date . "</td>";
  686. print "<td>" . $invoicestatic->getNomUrl(1) . "</td>";
  687. // Account
  688. print "<td>";
  689. print '<span class="error">'.$langs->trans('ErrorInvoiceContainsLinesNotYetBoundedShort', $val['ref']).'</span>';
  690. print '</td>';
  691. // Subledger account
  692. print "<td>";
  693. print '</td>';
  694. print "<td>";
  695. print "</td>";
  696. print '<td class="right"></td>';
  697. print '<td class="right"></td>';
  698. print "</tr>";
  699. }
  700. // Third party
  701. foreach ($tabttc[$key] as $k => $mt)
  702. {
  703. //if ($mt) {
  704. print '<tr class="oddeven">';
  705. print "<td><!-- Thirdparty --></td>";
  706. print "<td>" . $date . "</td>";
  707. print "<td>" . $invoicestatic->getNomUrl(1) . "</td>";
  708. // Account
  709. print "<td>";
  710. $accountoshow = length_accounta($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER);
  711. if (empty($accountoshow) || $accountoshow == 'NotDefined')
  712. {
  713. print '<span class="error">'.$langs->trans("MainAccountForCustomersNotDefined").'</span>';
  714. }
  715. else print $accountoshow;
  716. print '</td>';
  717. // Subledger account
  718. print "<td>";
  719. $accountoshow = length_accounta($k);
  720. if (empty($accountoshow) || $accountoshow == 'NotDefined')
  721. {
  722. print '<span class="error">'.$langs->trans("ThirdpartyAccountNotDefined").'</span>';
  723. }
  724. else print $accountoshow;
  725. print '</td>';
  726. print "<td>" . $companystatic->getNomUrl(0, 'customer', 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("SubledgerAccount") . "</td>";
  727. print '<td class="right">' . ($mt >= 0 ? price($mt) : '') . "</td>";
  728. print '<td class="right">' . ($mt < 0 ? price(- $mt) : '') . "</td>";
  729. print "</tr>";
  730. //}
  731. }
  732. // Product / Service
  733. foreach ($tabht[$key] as $k => $mt)
  734. {
  735. $accountingaccount = new AccountingAccount($db);
  736. $accountingaccount->fetch(null, $k, true);
  737. //if ($mt) {
  738. print '<tr class="oddeven">';
  739. print "<td><!-- Product --></td>";
  740. print "<td>" . $date . "</td>";
  741. print "<td>" . $invoicestatic->getNomUrl(1) . "</td>";
  742. // Account
  743. print "<td>";
  744. $accountoshow = length_accountg($k);
  745. if (empty($accountoshow) || $accountoshow == 'NotDefined')
  746. {
  747. print '<span class="error">'.$langs->trans("ProductNotDefined").'</span>';
  748. }
  749. else print $accountoshow;
  750. print "</td>";
  751. // Subledger account
  752. print "<td>";
  753. print '</td>';
  754. $companystatic->id = $tabcompany[$key]['id'];
  755. $companystatic->name = $tabcompany[$key]['name'];
  756. print "<td>" . $companystatic->getNomUrl(0, 'customer', 16) . ' - ' . $invoicestatic->ref . ' - ' . $accountingaccount->label . "</td>";
  757. print "<td class='right'>" . ($mt < 0 ? price(- $mt) : '') . "</td>";
  758. print "<td class='right'>" . ($mt >= 0 ? price($mt) : '') . "</td>";
  759. print "</tr>";
  760. //}
  761. }
  762. // VAT
  763. $listoftax = array(0, 1, 2);
  764. foreach ($listoftax as $numtax)
  765. {
  766. $arrayofvat = $tabtva;
  767. if ($numtax == 1) $arrayofvat = $tablocaltax1;
  768. if ($numtax == 2) $arrayofvat = $tablocaltax2;
  769. foreach ( $arrayofvat[$key] as $k => $mt ) {
  770. if ($mt) {
  771. print '<tr class="oddeven">';
  772. print "<td><!-- VAT --></td>";
  773. print "<td>" . $date . "</td>";
  774. print "<td>" . $invoicestatic->getNomUrl(1) . "</td>";
  775. // Account
  776. print "<td>";
  777. $accountoshow = length_accountg($k);
  778. if (empty($accountoshow) || $accountoshow == 'NotDefined')
  779. {
  780. print '<span class="error">'.$langs->trans("VATAccountNotDefined").' ('.$langs->trans("Sale").')'.'</span>';
  781. }
  782. else print $accountoshow;
  783. print "</td>";
  784. // Subledger account
  785. print "<td>";
  786. print '</td>';
  787. print "<td>" . $companystatic->getNomUrl(0, 'customer', 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("VAT"). ' '.join(', ',$def_tva[$key][$k]).' %'.($numtax?' - Localtax '.$numtax:'');
  788. print "</td>";
  789. print '<td class="right">' . ($mt < 0 ? price(- $mt) : '') . "</td>";
  790. print '<td class="right">' . ($mt >= 0 ? price($mt) : '') . "</td>";
  791. print "</tr>";
  792. }
  793. }
  794. }
  795. }
  796. print "</table>";
  797. print '</div>';
  798. // End of page
  799. llxFooter();
  800. }
  801. $db->close();