sellsjournal.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  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->socid > 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. $bookkeeping = new BookKeeping($db);
  263. $bookkeeping->doc_date = $val["date"];
  264. $bookkeeping->date_lim_reglement = $val["datereg"];
  265. $bookkeeping->doc_ref = $val["ref"];
  266. $bookkeeping->date_creation = $now;
  267. $bookkeeping->doc_type = 'customer_invoice';
  268. $bookkeeping->fk_doc = $key;
  269. $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
  270. $bookkeeping->thirdparty_code = $companystatic->code_client;
  271. $bookkeeping->subledger_account = $tabcompany[$key]['code_compta'];
  272. $bookkeeping->subledger_label = $tabcompany[$key]['name'];
  273. $bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER;
  274. $accountingaccount->fetch(null, $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER, true);
  275. $bookkeeping->label_compte = $accountingaccount->label;
  276. $bookkeeping->label_operation = dol_trunc($companystatic->name, 16).' - '.$invoicestatic->ref.' - '.$langs->trans("SubledgerAccount");
  277. $bookkeeping->montant = $mt;
  278. $bookkeeping->sens = ($mt >= 0) ? 'D' : 'C';
  279. $bookkeeping->debit = ($mt >= 0) ? $mt : 0;
  280. $bookkeeping->credit = ($mt < 0) ? -$mt : 0;
  281. $bookkeeping->code_journal = $journal;
  282. $bookkeeping->journal_label = $journal_label;
  283. $bookkeeping->fk_user_author = $user->id;
  284. $bookkeeping->entity = $conf->entity;
  285. $totaldebit += $bookkeeping->debit;
  286. $totalcredit += $bookkeeping->credit;
  287. $result = $bookkeeping->create($user);
  288. if ($result < 0) {
  289. if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') // Already exists
  290. {
  291. $error++;
  292. $errorforline++;
  293. $errorforinvoice[$key] = 'alreadyjournalized';
  294. //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
  295. }
  296. else
  297. {
  298. $error++;
  299. $errorforline++;
  300. $errorforinvoice[$key] = 'other';
  301. setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
  302. }
  303. }
  304. }
  305. }
  306. // Product / Service
  307. if (!$errorforline)
  308. {
  309. foreach ($tabht[$key] as $k => $mt) {
  310. // get compte id and label
  311. if ($accountingaccount->fetch(null, $k, true)) {
  312. $bookkeeping = new BookKeeping($db);
  313. $bookkeeping->doc_date = $val["date"];
  314. $bookkeeping->date_lim_reglement = $val["datereg"];
  315. $bookkeeping->doc_ref = $val["ref"];
  316. $bookkeeping->date_creation = $now;
  317. $bookkeeping->doc_type = 'customer_invoice';
  318. $bookkeeping->fk_doc = $key;
  319. $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
  320. $bookkeeping->thirdparty_code = $companystatic->code_client;
  321. $bookkeeping->subledger_account = '';
  322. $bookkeeping->subledger_label = '';
  323. $bookkeeping->numero_compte = $k;
  324. $bookkeeping->label_compte = $accountingaccount->label;
  325. $bookkeeping->label_operation = dol_trunc($companystatic->name, 16).' - '.$invoicestatic->ref.' - '.$accountingaccount->label;
  326. $bookkeeping->montant = $mt;
  327. $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
  328. $bookkeeping->debit = ($mt < 0) ? -$mt : 0;
  329. $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
  330. $bookkeeping->code_journal = $journal;
  331. $bookkeeping->journal_label = $journal_label;
  332. $bookkeeping->fk_user_author = $user->id;
  333. $bookkeeping->entity = $conf->entity;
  334. $totaldebit += $bookkeeping->debit;
  335. $totalcredit += $bookkeeping->credit;
  336. $result = $bookkeeping->create($user);
  337. if ($result < 0) {
  338. if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') // Already exists
  339. {
  340. $error++;
  341. $errorforline++;
  342. $errorforinvoice[$key] = 'alreadyjournalized';
  343. //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
  344. }
  345. else
  346. {
  347. $error++;
  348. $errorforline++;
  349. $errorforinvoice[$key] = 'other';
  350. setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
  351. }
  352. }
  353. }
  354. }
  355. }
  356. // VAT
  357. if (!$errorforline)
  358. {
  359. $listoftax = array(0, 1, 2);
  360. foreach ($listoftax as $numtax)
  361. {
  362. $arrayofvat = $tabtva;
  363. if ($numtax == 1) $arrayofvat = $tablocaltax1;
  364. if ($numtax == 2) $arrayofvat = $tablocaltax2;
  365. foreach ($arrayofvat[$key] as $k => $mt) {
  366. if ($mt) {
  367. $bookkeeping = new BookKeeping($db);
  368. $bookkeeping->doc_date = $val["date"];
  369. $bookkeeping->date_lim_reglement = $val["datereg"];
  370. $bookkeeping->doc_ref = $val["ref"];
  371. $bookkeeping->date_creation = $now;
  372. $bookkeeping->doc_type = 'customer_invoice';
  373. $bookkeeping->fk_doc = $key;
  374. $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
  375. $bookkeeping->thirdparty_code = $companystatic->code_client;
  376. $bookkeeping->subledger_account = '';
  377. $bookkeeping->subledger_label = '';
  378. $bookkeeping->numero_compte = $k;
  379. $accountingaccount->fetch($k, null, true);
  380. $bookkeeping->label_compte = $accountingaccount->label;
  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, 'MT') != price2num($totalcredit, 'MT')))
  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. $type_export = 'journal';
  472. include DOL_DOCUMENT_ROOT.'/accountancy/tpl/export_journal.tpl.php';
  473. $companystatic = new Client($db);
  474. $invoicestatic = new Facture($db);
  475. foreach ($tabfac as $key => $val)
  476. {
  477. $companystatic->id = $tabcompany[$key]['id'];
  478. $companystatic->name = $tabcompany[$key]['name'];
  479. $companystatic->code_compta = $tabcompany[$key]['code_compta'];
  480. $companystatic->code_compta_fournisseur = $tabcompany[$key]['code_compta_fournisseur'];
  481. $companystatic->code_client = $tabcompany[$key]['code_client'];
  482. $companystatic->code_fournisseur = $tabcompany[$key]['code_fournisseur'];
  483. $companystatic->client = 3;
  484. $invoicestatic->id = $key;
  485. $invoicestatic->ref = (string) $val["ref"];
  486. $invoicestatic->type = $val["type"];
  487. $invoicestatic->close_code = $val["close_code"];
  488. $date = dol_print_date($val["date"], 'day');
  489. // Is it a replaced invoice ? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
  490. $replacedinvoice = 0;
  491. if ($invoicestatic->close_code == Facture::CLOSECODE_REPLACED)
  492. {
  493. $replacedinvoice = 1;
  494. $alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
  495. if ($alreadydispatched) $replacedinvoice = 2;
  496. }
  497. // 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)
  498. if ($replacedinvoice == 1)
  499. {
  500. continue;
  501. }
  502. // Third party
  503. foreach ($tabttc[$key] as $k => $mt) {
  504. //if ($mt) {
  505. print '"'.$key.'"'.$sep;
  506. print '"'.$date.'"'.$sep;
  507. print '"'.$val["ref"].'"'.$sep;
  508. print '"'.utf8_decode(dol_trunc($companystatic->name, 32)).'"'.$sep;
  509. print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
  510. print '"'.$conf->global->ACCOUNTING_ACCOUNT_CUSTOMER.'"'.$sep;
  511. print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
  512. print '"'.$langs->trans("Thirdparty").'"'.$sep;
  513. print '"'.utf8_decode(dol_trunc($companystatic->name, 16)).' - '.$invoicestatic->ref.' - '.$langs->trans("Thirdparty").'"'.$sep;
  514. print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
  515. print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
  516. print '"'.$journal.'"';
  517. print "\n";
  518. //}
  519. }
  520. // Product / Service
  521. foreach ($tabht[$key] as $k => $mt) {
  522. $accountingaccount = new AccountingAccount($db);
  523. $accountingaccount->fetch(null, $k, true);
  524. //if ($mt) {
  525. print '"'.$key.'"'.$sep;
  526. print '"'.$date.'"'.$sep;
  527. print '"'.$val["ref"].'"'.$sep;
  528. print '"'.utf8_decode(dol_trunc($companystatic->name, 32)).'"'.$sep;
  529. print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
  530. print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
  531. print '""'.$sep;
  532. print '"'.utf8_decode(dol_trunc($accountingaccount->label, 32)).'"'.$sep;
  533. print '"'.utf8_decode(dol_trunc($companystatic->name, 16)).' - '.dol_trunc($accountingaccount->label, 32).'"'.$sep;
  534. print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
  535. print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
  536. print '"'.$journal.'"';
  537. print "\n";
  538. //}
  539. }
  540. // VAT
  541. $listoftax = array(0, 1, 2);
  542. foreach ($listoftax as $numtax) {
  543. $arrayofvat = $tabtva;
  544. if ($numtax == 1) $arrayofvat = $tablocaltax1;
  545. if ($numtax == 2) $arrayofvat = $tablocaltax2;
  546. foreach ($arrayofvat[$key] as $k => $mt) {
  547. if ($mt) {
  548. print '"'.$key.'"'.$sep;
  549. print '"'.$date.'"'.$sep;
  550. print '"'.$val["ref"].'"'.$sep;
  551. print '"'.utf8_decode(dol_trunc($companystatic->name, 32)).'"'.$sep;
  552. print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
  553. print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
  554. print '""'.$sep;
  555. print '"'.$langs->trans("VAT").' - '.$def_tva[$key].' %"'.$sep;
  556. print '"'.utf8_decode(dol_trunc($companystatic->name, 16)).' - '.$invoicestatic->ref.' - '.$langs->trans("VAT").join(', ', $def_tva[$key][$k]).' %'.($numtax ? ' - Localtax '.$numtax : '').'"'.$sep;
  557. print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
  558. print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
  559. print '"'.$journal.'"';
  560. print "\n";
  561. }
  562. }
  563. }
  564. }
  565. }
  566. if (empty($action) || $action == 'view') {
  567. llxHeader('', $langs->trans("SellsJournal"));
  568. $nom = $langs->trans("SellsJournal").' | '.$accountingjournalstatic->getNomUrl(0, 1, 1, '', 1);
  569. $nomlink = '';
  570. $periodlink = '';
  571. $exportlink = '';
  572. $builddate = dol_now();
  573. $description .= $langs->trans("DescJournalOnlyBindedVisible").'<br>';
  574. if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS))
  575. $description .= $langs->trans("DepositsAreNotIncluded");
  576. else
  577. $description .= $langs->trans("DepositsAreIncluded");
  578. $listofchoices = array('notyet'=>$langs->trans("NotYetInGeneralLedger"), 'already'=>$langs->trans("AlreadyInGeneralLedger"));
  579. $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);
  580. $period .= ' - '.$langs->trans("JournalizationInLedgerStatus").' '.$form->selectarray('in_bookkeeping', $listofchoices, $in_bookkeeping, 1);
  581. $varlink = 'id_journal='.$id_journal;
  582. journalHead($nom, $nomlink, $period, $periodlink, $description, $builddate, $exportlink, array('action' => ''), '', $varlink);
  583. // Button to write into Ledger
  584. if (($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER == "") || $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER == '-1') {
  585. print '<br>';
  586. print img_warning().' '.$langs->trans("SomeMandatoryStepsOfSetupWereNotDone");
  587. print ' : '.$langs->trans("AccountancyAreaDescMisc", 4, '<strong>'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("MenuDefaultAccounts").'</strong>');
  588. }
  589. print '<div class="tabsAction tabsActionNoBottom">';
  590. if (!empty($conf->global->ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL)) print '<input type="button" class="butAction" name="exportcsv" value="'.$langs->trans("ExportDraftJournal").'" onclick="launch_export();" />';
  591. if (($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER == "") || $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER == '-1') {
  592. print '<input type="button" class="butActionRefused classfortooltip" title="'.dol_escape_htmltag($langs->trans("SomeMandatoryStepsOfSetupWereNotDone")).'" value="'.$langs->trans("WriteBookKeeping").'" />';
  593. }
  594. else {
  595. if ($in_bookkeeping == 'notyet') print '<input type="button" class="butAction" name="writebookkeeping" value="'.$langs->trans("WriteBookKeeping").'" onclick="writebookkeeping();" />';
  596. else print '<a href="#" class="butActionRefused classfortooltip" name="writebookkeeping">'.$langs->trans("WriteBookKeeping").'</a>';
  597. }
  598. print '</div>';
  599. // TODO Avoid using js. We can use a direct link with $param
  600. print '
  601. <script type="text/javascript">
  602. function launch_export() {
  603. $("div.fiche form input[name=\"action\"]").val("exportcsv");
  604. $("div.fiche form input[type=\"submit\"]").click();
  605. $("div.fiche form input[name=\"action\"]").val("");
  606. }
  607. function writebookkeeping() {
  608. console.log("click on writebookkeeping");
  609. $("div.fiche form input[name=\"action\"]").val("writebookkeeping");
  610. $("div.fiche form input[type=\"submit\"]").click();
  611. $("div.fiche form input[name=\"action\"]").val("");
  612. }
  613. </script>';
  614. /*
  615. * Show result array
  616. */
  617. print '<br>';
  618. $i = 0;
  619. print '<div class="div-table-responsive">';
  620. print "<table class=\"noborder\" width=\"100%\">";
  621. print "<tr class=\"liste_titre\">";
  622. print "<td>".$langs->trans("Date")."</td>";
  623. print "<td>".$langs->trans("Piece").' ('.$langs->trans("InvoiceRef").")</td>";
  624. print "<td>".$langs->trans("AccountAccounting")."</td>";
  625. print "<td>".$langs->trans("SubledgerAccount")."</td>";
  626. print "<td>".$langs->trans("LabelOperation")."</td>";
  627. print '<td class="center">'.$langs->trans("Debit")."</td>";
  628. print '<td class="center">'.$langs->trans("Credit")."</td>";
  629. print "</tr>\n";
  630. $r = '';
  631. $companystatic = new Client($db);
  632. $invoicestatic = new Facture($db);
  633. foreach ($tabfac as $key => $val)
  634. {
  635. $companystatic->id = $tabcompany[$key]['id'];
  636. $companystatic->name = $tabcompany[$key]['name'];
  637. $companystatic->code_compta = $tabcompany[$key]['code_compta'];
  638. $companystatic->code_compta_fournisseur = $tabcompany[$key]['code_compta_fournisseur'];
  639. $companystatic->code_client = $tabcompany[$key]['code_client'];
  640. $companystatic->code_fournisseur = $tabcompany[$key]['code_fournisseur'];
  641. $companystatic->client = 3;
  642. $invoicestatic->id = $key;
  643. $invoicestatic->ref = (string) $val["ref"];
  644. $invoicestatic->type = $val["type"];
  645. $invoicestatic->close_code = $val["close_code"];
  646. $date = dol_print_date($val["date"], 'day');
  647. // Is it a replaced invoice ? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
  648. $replacedinvoice = 0;
  649. if ($invoicestatic->close_code == Facture::CLOSECODE_REPLACED)
  650. {
  651. $replacedinvoice = 1;
  652. $alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
  653. if ($alreadydispatched) $replacedinvoice = 2;
  654. }
  655. // If not already into bookkeeping, we won't add it, if yes, add the counterpart ???.
  656. if ($replacedinvoice == 1)
  657. {
  658. print '<tr class="oddeven">';
  659. print "<!-- Replaced invoice -->";
  660. print "<td>".$date."</td>";
  661. print "<td><strike>".$invoicestatic->getNomUrl(1)."</strike></td>";
  662. // Account
  663. print "<td>";
  664. print $langs->trans("Replaced");
  665. print '</td>';
  666. // Subledger account
  667. print "<td>";
  668. print '</td>';
  669. print "<td>";
  670. print "</td>";
  671. print '<td class="right"></td>';
  672. print '<td class="right"></td>';
  673. print "</tr>";
  674. continue;
  675. }
  676. if ($errorforinvoice[$key] == 'somelinesarenotbound')
  677. {
  678. print '<tr class="oddeven">';
  679. print "<!-- Some lines are not bound -->";
  680. print "<td>".$date."</td>";
  681. print "<td>".$invoicestatic->getNomUrl(1)."</td>";
  682. // Account
  683. print "<td>";
  684. print '<span class="error">'.$langs->trans('ErrorInvoiceContainsLinesNotYetBoundedShort', $val['ref']).'</span>';
  685. print '</td>';
  686. // Subledger account
  687. print "<td>";
  688. print '</td>';
  689. print "<td>";
  690. print "</td>";
  691. print '<td class="right"></td>';
  692. print '<td class="right"></td>';
  693. print "</tr>";
  694. }
  695. // Third party
  696. foreach ($tabttc[$key] as $k => $mt)
  697. {
  698. print '<tr class="oddeven">';
  699. print "<!-- Thirdparty -->";
  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 (($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 (($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 class="right nowraponall">'.($mt >= 0 ? price($mt) : '')."</td>";
  722. print '<td class="right nowraponall">'.($mt < 0 ? price(-$mt) : '')."</td>";
  723. print "</tr>";
  724. }
  725. // Product / Service
  726. foreach ($tabht[$key] as $k => $mt)
  727. {
  728. $accountingaccount = new AccountingAccount($db);
  729. $accountingaccount->fetch(null, $k, true);
  730. print '<tr class="oddeven">';
  731. print "<!-- Product -->";
  732. print "<td>".$date."</td>";
  733. print "<td>".$invoicestatic->getNomUrl(1)."</td>";
  734. // Account
  735. print "<td>";
  736. $accountoshow = length_accountg($k);
  737. if (($accountoshow == "") || $accountoshow == 'NotDefined')
  738. {
  739. print '<span class="error">'.$langs->trans("ProductNotDefined").'</span>';
  740. }
  741. else print $accountoshow;
  742. print "</td>";
  743. // Subledger account
  744. print "<td>";
  745. print '</td>';
  746. $companystatic->id = $tabcompany[$key]['id'];
  747. $companystatic->name = $tabcompany[$key]['name'];
  748. print "<td>".$companystatic->getNomUrl(0, 'customer', 16).' - '.$invoicestatic->ref.' - '.$accountingaccount->label."</td>";
  749. print '<td class="right nowraponall">'.($mt < 0 ? price(-$mt) : '')."</td>";
  750. print '<td class="right nowraponall">'.($mt >= 0 ? price($mt) : '')."</td>";
  751. print "</tr>";
  752. }
  753. // VAT
  754. $listoftax = array(0, 1, 2);
  755. foreach ($listoftax as $numtax)
  756. {
  757. $arrayofvat = $tabtva;
  758. if ($numtax == 1) $arrayofvat = $tablocaltax1;
  759. if ($numtax == 2) $arrayofvat = $tablocaltax2;
  760. foreach ($arrayofvat[$key] as $k => $mt) {
  761. if ($mt) {
  762. print '<tr class="oddeven">';
  763. print "<!-- VAT -->";
  764. print "<td>".$date."</td>";
  765. print "<td>".$invoicestatic->getNomUrl(1)."</td>";
  766. // Account
  767. print "<td>";
  768. $accountoshow = length_accountg($k);
  769. if (($accountoshow == "") || $accountoshow == 'NotDefined')
  770. {
  771. print '<span class="error">'.$langs->trans("VATAccountNotDefined").' ('.$langs->trans("Sale").')'.'</span>';
  772. }
  773. else print $accountoshow;
  774. print "</td>";
  775. // Subledger account
  776. print "<td>";
  777. print '</td>';
  778. print "<td>".$companystatic->getNomUrl(0, 'customer', 16).' - '.$invoicestatic->ref.' - '.$langs->trans("VAT").' '.join(', ', $def_tva[$key][$k]).' %'.($numtax ? ' - Localtax '.$numtax : '');
  779. print "</td>";
  780. print '<td class="right nowraponall">'.($mt < 0 ? price(-$mt) : '')."</td>";
  781. print '<td class="right nowraponall">'.($mt >= 0 ? price($mt) : '')."</td>";
  782. print "</tr>";
  783. }
  784. }
  785. }
  786. }
  787. print "</table>";
  788. print '</div>';
  789. // End of page
  790. llxFooter();
  791. }
  792. $db->close();