apiinvoicehelper.class.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. <?php
  2. use Luracast\Restler\RestException;
  3. require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
  4. require_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php';
  5. /**
  6. *
  7. *
  8. */
  9. class ApiInvoiceHelper
  10. {
  11. private ApiInvoice $apiInvoice;
  12. public $db;
  13. /**
  14. *
  15. */
  16. public function __construct()
  17. {
  18. global $db;
  19. $this->db = $db;
  20. }
  21. /**
  22. * Generate invoice with basic data
  23. */
  24. public function createInvoice(array $invoice, $sendId, $company_invoice = []): Facture
  25. {
  26. global $user;
  27. ApiBbusLog::appLog("{$sendId} - createInvoice_________START - " . microtime(true));
  28. $invoice['multicurrency_tx'] = $invoice['multicurrency_code'] === 'HUF' ? 1.00000000 : $invoice['multicurrency_tx'];
  29. $invoice['array_options_sales_group'] = $this->getGroupId();
  30. $this->apiInvoice = new ApiInvoice;
  31. $this->apiInvoice->loadData($invoice);
  32. $this->apiInvoice->prepareData($invoice['fk_multicurrency']);
  33. $this->apiInvoice->validate();
  34. ApiBbusLog::appLog("{$sendId} - createInvoice_________END - " . microtime(true));
  35. return $this->apiInvoice->create($company_invoice);
  36. }
  37. function getGroupId()
  38. {
  39. global $user;
  40. $sql = "SELECT fk_settlements_group FROM llx_settlements_groupusers WHERE fk_user = {$user->id}";
  41. $result = $this->db->query($sql);
  42. if ($this->db->num_rows($result) > 0) {
  43. while ($row = $this->db->fetch_object($result)) {
  44. return $row->fk_settlements_group;
  45. }
  46. }
  47. return null;
  48. }
  49. function increaseParticipant($fk_event)
  50. {
  51. global $user;
  52. $actionComObj = new ActionComm($this->db);
  53. $actionComObj->fetch($fk_event);
  54. $participants = (int) $actionComObj->array_options['options_participants'];
  55. $increasedParticipants = $participants + 1;
  56. $actionComObj->array_options['options_participants'] = (int) $increasedParticipants;
  57. $actionComObj->label = $fk_event;
  58. $actionComObj->update($user);
  59. }
  60. /**
  61. * GEnerate PROV invoice
  62. */
  63. public function createInvoicePROV(array $invoice, $sendId): Facture
  64. {
  65. ApiBbusLog::eventLog("{$sendId} - createInvoice_________START - " . microtime(true));
  66. $this->apiInvoice = new ApiInvoice;
  67. $invoice['multicurrency_tx'] = $invoice['multicurrency_code'] === 'HUF' ? 1.00000000 : $invoice['multicurrency_tx'];
  68. $invoice['array_options_sales_group'] = $this->getGroupId();
  69. //print_r($invoice);exit;
  70. $this->apiInvoice->loadData($invoice);
  71. $this->apiInvoice->prepareData($invoice['fk_multicurrency']);
  72. $this->apiInvoice->validate();
  73. return $this->apiInvoice->create();
  74. }
  75. /**
  76. * Add product to invoice
  77. */
  78. public function addLineToInvoice(Facture $invoice, array $line, $sendId): Facture
  79. {
  80. ApiBbusLog::appLog("{$sendId} addLineToInvoice: START");
  81. $tva_tx_array = explode('.', $line['tva_tx']);
  82. $line['tva_tx'] = $line['tva_tx'] . '000 (' . $tva_tx_array[0] . ')';
  83. //ApiBbusLog::appLog("{$sendId} - createInvoiceLINE_________START - " . microtime(true));
  84. $apiInvoiceLine = new ApiInvoiceLine;
  85. $apiInvoiceLine->setInvoice($invoice);
  86. $apiInvoiceLine->loadData($line);
  87. $apiInvoiceLine->prepareData();
  88. $invoice = $apiInvoiceLine->create();
  89. return $invoice;
  90. }
  91. function getProductLines($product_id)
  92. {
  93. $productObj = new Product($this->db);
  94. $result = $productObj->fetch($product_id);
  95. $productObj->fk_product = $product_id;
  96. $productObj->subprice = $productObj->price_ttc;
  97. $productObj->qty = 1;
  98. $lines[] = (array) $productObj;
  99. return $lines;
  100. }
  101. function getProductLinesWithoutDiscount($product_id)
  102. {
  103. ApiBbusLog::appLog("getProductLinesWithoutDiscount: {$product_id}");
  104. $productObj = new Product($this->db);
  105. $result = $productObj->fetch($product_id);
  106. $productObj->fk_product = $product_id;
  107. if ($productObj->price_base_type == 'HT') {
  108. $productObj->subprice = $productObj->price;
  109. } else {
  110. $productObj->subprice = $productObj->price_ttc;
  111. }
  112. $productObj->qty = 1;
  113. $productObj->array_options['options_discount_hours'] = null;
  114. $productObj->array_options['options_discount_percent'] = null;
  115. $lines[] = (array) $productObj;
  116. return $lines;
  117. }
  118. /**
  119. * Validate invoice
  120. */
  121. public function validateInvoice(Facture $invoice, $sendId): Facture
  122. {
  123. ApiBbusLog::appLog("{$sendId} - validateInvoice_________START - " . microtime(true));
  124. return $this->apiInvoice->validateInvoice($invoice, 1);
  125. }
  126. /**
  127. * Validate invoice
  128. */
  129. public function validateInvoiceFromPROV(Facture $invoice, $sendId, $facture_id): Facture
  130. {
  131. $this->apiInvoice = new ApiInvoice;
  132. ApiBbusLog::eventLog("{$sendId} - validateInvoice_________START - " . microtime(true));
  133. return $this->apiInvoice->validateInvoice($invoice, 1);
  134. }
  135. /**
  136. * Set payment
  137. *
  138. * @return int Payment ID
  139. */
  140. public function setPaymentFromPROV(Facture $invoice, array $payment, string $sendId): int
  141. {
  142. $this->apiInvoice = new ApiInvoice;
  143. ApiBbusLog::eventLog("{$sendId} - setPayment_________START - " . microtime(true));
  144. return $this->apiInvoice->setPayment($invoice, $payment, $sendId);
  145. }
  146. /**
  147. * Set payment
  148. *
  149. * @return int Payment ID
  150. */
  151. public function setPayment(Facture $invoice, array $payment, string $sendId): int
  152. {
  153. ApiBbusLog::appLog("{$sendId} - setPayment_________START - " . microtime(true));
  154. return $this->apiInvoice->setPayment($invoice, $payment, $sendId);
  155. }
  156. /**
  157. * Save card payment log to invoice
  158. */
  159. public function saveCardPaymentLog(Facture $invoice, string $cardPaymentLog, $sendId): Facture
  160. {
  161. //ApiBbusLog::appLog("{$sendId} - saveCardPaymentLog_________START - " . microtime(true));
  162. $invoice->array_options['options_payment_log'] = $cardPaymentLog;
  163. $invoice->updateExtraField('payment_log');
  164. $json = json_decode($cardPaymentLog, true);
  165. if (!empty($json['authorization_number'])) {
  166. $sql = "
  167. UPDATE " . MAIN_DB_PREFIX . "paiement
  168. SET num_paiement='" . $json['authorization_number'] . "'
  169. WHERE rowid=(
  170. SELECT fk_paiement
  171. FROM " . MAIN_DB_PREFIX . "paiement_facture
  172. WHERE fk_facture={$invoice->id}
  173. )
  174. ";
  175. $this->db->query($sql);
  176. }
  177. return $invoice;
  178. }
  179. /**
  180. * Load product
  181. */
  182. public function loadProductToResult(array $line): array
  183. {
  184. $result = [];
  185. $product = new Product($this->db);
  186. if ($product->fetch($line['fk_product']) > 0) {
  187. $result = [
  188. 'id' => $product->id,
  189. 'ref' => $product->ref,
  190. 'label' => $product->label,
  191. 'description' => $product->description,
  192. 'vat' => $product->tva_tx,
  193. 'discount_period' => (empty($line['array_options']['discount_period'])) ? '' : $line['array_options']['discount_period'],
  194. 'discount_value' => (empty($line['array_options']['discount_value'])) ? '' : $line['array_options']['discount_value'],
  195. 'orig_price' => $product->price_ttc,
  196. 'price' => $product->price_ttc
  197. ];
  198. }
  199. return $result;
  200. }
  201. }
  202. /**
  203. *
  204. *
  205. */
  206. interface ApiInvoiceData
  207. {
  208. public function loadData(array $data): void;
  209. public function prepareData($currency): void;
  210. public function validate(): void;
  211. public function create(); // missing return type because of the different result objects
  212. }
  213. /**
  214. *
  215. *
  216. */
  217. class ApiInvoiceLine implements ApiInvoiceData
  218. {
  219. public $data;
  220. public $invoice;
  221. /**
  222. *
  223. */
  224. public function loadData(array $data): void
  225. {
  226. $this->data = (object) $data;
  227. }
  228. /**
  229. *
  230. */
  231. public function setInvoice(Facture $invoice): void
  232. {
  233. $this->invoice = $invoice;
  234. }
  235. /**
  236. *
  237. */
  238. public function prepareData($currency = null): void
  239. {
  240. $this->data->desc = sanitizeVal($this->data->desc, 'restricthtml');
  241. $this->data->label = sanitizeVal($this->data->label);
  242. if (($this->data->product_type != 9 && empty($this->data->fk_parent_line)) || $this->data->product_type == 9) {
  243. $this->data->fk_parent_line = 0;
  244. }
  245. }
  246. /**
  247. *
  248. */
  249. public function validate(): void
  250. {
  251. //
  252. }
  253. /**
  254. *
  255. */
  256. public function create(): Facture
  257. {
  258. $marginInfos = getMarginInfos($this->data->subprice, $this->data->remise_percent, $this->data->tva_tx, $this->data->localtax1_tx, $this->data->localtax2_tx, $this->data->fk_fournprice, $this->data->pa_ht);
  259. $pa_ht = $marginInfos[0];
  260. $updateRes = $this->invoice->addline(
  261. $this->data->desc,
  262. $this->data->subprice,
  263. $this->data->qty,
  264. $this->data->tva_tx,
  265. $this->data->localtax1_tx,
  266. $this->data->localtax2_tx,
  267. $this->data->fk_product,
  268. $this->data->remise_percent,
  269. $this->data->date_start,
  270. $this->data->date_end,
  271. $this->data->fk_code_ventilation,
  272. $this->data->info_bits,
  273. $this->data->fk_remise_except,
  274. $this->data->price_base_type ? $this->data->price_base_type : 'HT',
  275. $this->data->subprice,
  276. $this->data->product_type,
  277. $this->data->rang,
  278. $this->data->special_code,
  279. $this->data->origin,
  280. $this->data->origin_id,
  281. $this->data->fk_parent_line,
  282. empty($this->data->fk_fournprice) ? null : $this->data->fk_fournprice,
  283. $pa_ht,
  284. $this->data->label,
  285. $this->data->array_options,
  286. $this->data->situation_percent,
  287. $this->data->fk_prev_id,
  288. $this->data->fk_unit,
  289. 0,
  290. $this->data->ref_ext
  291. );
  292. if ($updateRes < 0) {
  293. throw new RestException(400, 'Unable to insert the new line. Check your inputs. ' . $this->invoice->error);
  294. }
  295. return $this->invoice;
  296. }
  297. }
  298. /**
  299. *
  300. *
  301. */
  302. class ApiInvoice implements ApiInvoiceData
  303. {
  304. //const SOCID = 1;
  305. public $data;
  306. public $invoice;
  307. /**
  308. *
  309. */
  310. public function loadData(array $data): void
  311. {
  312. $this->invoice = null;
  313. $this->data = $data;
  314. }
  315. /**
  316. *
  317. */
  318. public function prepareData($currency): void
  319. {
  320. global $user, $db;
  321. $socid = 0;
  322. $sql = "SELECT s.rowid FROM llx_societe as s
  323. INNER JOIN llx_societe_extrafields as se ON se.fk_object = s.rowid
  324. WHERE s.fk_multicurrency = {$currency} AND se.is_general_customer = 1";
  325. $result = $db->query($sql);
  326. if($db->num_rows($result) > 0){
  327. while($row = $db->fetch_object($result)){
  328. $socid = $row->rowid;
  329. }
  330. } else {
  331. throw new RestException(400, 'There is no General Customer');
  332. }
  333. $this->data['socid'] = $socid;
  334. $this->data['entity'] = $user->entity;
  335. }
  336. /**
  337. *
  338. */
  339. public function validate(): void
  340. {
  341. $fields = [
  342. 'socid',
  343. 'entity'
  344. ];
  345. foreach ($fields as $field) {
  346. if (!isset($this->data[$field])) {
  347. throw new RestException(400, "Invoice {$field} field missing");
  348. }
  349. }
  350. }
  351. /**
  352. *
  353. */
  354. public function create($company_invoice = []): Facture
  355. {
  356. global $db;
  357. $this->invoice = new Facture($db);
  358. foreach ($this->data as $field => $value) {
  359. if (preg_match('/^array_options/', $field)) {
  360. $f = str_replace('array_options_', '', $field);
  361. $this->invoice->array_options[$f] = $value;
  362. continue;
  363. }
  364. $this->invoice->$field = $value;
  365. }
  366. if (!array_key_exists('date', $this->data)) {
  367. $this->invoice->date = dol_now();
  368. }
  369. if(empty($company_invoice)){
  370. $this->invoice->type = 7;
  371. }
  372. if ($this->invoice->create(DolibarrApiAccess::$user, 0, (empty($this->data['date_lim_reglement']) ? 0 : $this->data['date_lim_reglement'])) < 0) {
  373. throw new RestException(500, 'Error creating invoice', array_merge([$this->invoice->error], $this->invoice->errors));
  374. }
  375. return $this->invoice;
  376. }
  377. /**
  378. *
  379. */
  380. public function validateInvoice(Facture $invoice, int $notrigger): Facture
  381. {
  382. $result = $invoice->validate(DolibarrApiAccess::$user, '', 0, $notrigger);
  383. if ($result == 0) {
  384. throw new RestException(304, 'Error nothing done. May be object is already validated');
  385. }
  386. if ($result < 0) {
  387. throw new RestException(500, 'Error when validating Invoice: ' . $invoice->error);
  388. }
  389. return $invoice;
  390. }
  391. /**
  392. *
  393. */
  394. public function setPayment(Facture $invoice, array $data, string $sendId): int
  395. {
  396. ApiBbusLog::appLog("ApiinvoiceHelper: setPayment function");
  397. global $db;
  398. if (isModEnabled('banque')) {
  399. if (empty($data['accountid'])) {
  400. ApiBbusLog::appLog("ApiinvoiceHelper: setPayment accountid error");
  401. throw new RestException(400, 'Account ID is mandatory');
  402. }
  403. }
  404. if (empty($data['paymentid'])) {
  405. ApiBbusLog::appLog("ApiinvoiceHelper: setPayment paymentid error");
  406. throw new RestException(400, 'Payment ID or Payment Code is mandatory');
  407. }
  408. // Calculate amount to pay
  409. $totalpaid = $invoice->getSommePaiement();
  410. $totalcreditnotes = $invoice->getSumCreditNotesUsed();
  411. $totaldeposits = $invoice->getSumDepositsUsed();
  412. $resteapayer = price2num($invoice->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
  413. $db->begin();
  414. $amounts = [];
  415. $multicurrency_amounts = [];
  416. // Clean parameters amount if payment is for a credit note
  417. if ($invoice->type == Facture::TYPE_CREDIT_NOTE) {
  418. $resteapayer = price2num($resteapayer, 'MT');
  419. $amounts[$invoice->id] = -$resteapayer;
  420. // Multicurrency
  421. $newvalue = price2num($invoice->multicurrency_total_ttc, 'MT');
  422. $multicurrency_amounts[$invoice->id] = -$newvalue;
  423. } else {
  424. $resteapayer = price2num($resteapayer, 'MT');
  425. $amounts[$invoice->id] = $resteapayer;
  426. // Multicurrency
  427. $newvalue = price2num($invoice->multicurrency_total_ttc, 'MT');
  428. $multicurrency_amounts[$invoice->id] = $newvalue;
  429. }
  430. // Creation of payment line
  431. $paymentobj = new Paiement($db);
  432. $paymentobj->datepaye = $data['datepaye'];
  433. $paymentobj->amounts = $amounts; // Array with all payments dispatching with invoice id
  434. $paymentobj->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
  435. $paymentobj->paiementid = $data['paymentid'];
  436. $paymentobj->paiementcode = dol_getIdFromCode($db, $data['paymentid'], 'c_paiement', 'id', 'code', 1);
  437. $paymentobj->num_payment = $data['num_payment'];
  438. $paymentobj->note_private = (is_array($data['comment'])) ? json_encode($data['comment']) : $data['comment'];
  439. $paymentId = $paymentobj->create(DolibarrApiAccess::$user, ($data['closepaidinvoices'] == 'yes' ? 1 : 0)); // This include closing invoices
  440. ApiBbusLog::appLog("paymentId created");
  441. if ($paymentId < 0) {
  442. $db->rollback();
  443. ApiBbusLog::appLog("{$sendId} Payment error : " . $paymentobj->error);
  444. throw new RestException(400, 'Payment error : ' . $paymentobj->error);
  445. }
  446. ApiBbusLog::appLog("paymentId created");
  447. if (isModEnabled('banque')) {
  448. $label = '(CustomerInvoicePayment)';
  449. $chqemetteur = '';
  450. $chqbank = '';
  451. if ($paymentobj->paiementcode == 'CHQ' && empty($chqemetteur)) {
  452. ApiBbusLog::appLog("{$sendId} Emetteur is mandatory when payment code is " . $paymentobj->paiementcode);
  453. throw new RestException(400, 'Emetteur is mandatory when payment code is ' . $paymentobj->paiementcode);
  454. }
  455. if ($invoice->type == Facture::TYPE_CREDIT_NOTE) {
  456. $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
  457. }
  458. $result = $paymentobj->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $data['accountid'], $chqemetteur, $chqbank);
  459. if ($result < 0) {
  460. $db->rollback();
  461. ApiBbusLog::appLog("{$sendId} Add payment to bank error : " . $paymentobj->error);
  462. throw new RestException(400, 'Add payment to bank error : ' . $paymentobj->error);
  463. }
  464. }
  465. #
  466. # set Facture -> payment_transaction_id
  467. #
  468. if (!empty($data['comment'])) {
  469. $commentJSON = json_decode($data['comment']);
  470. $invoice->array_options['options_payment_transaction_id'] = $commentJSON->card_transaction_id;
  471. $invoice->updateExtraField('payment_transaction_id');
  472. }
  473. $db->commit();
  474. ApiBbusLog::appLog("{$sendId} PAYMENT CREATED: {$paymentId}");
  475. return $paymentId;
  476. }
  477. }