apiinvoicehelper.class.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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();
  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();
  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. $productObj->subprice = $productObj->price_ttc;
  108. $productObj->qty = 1;
  109. $productObj->array_options['options_discount_hours'] = null;
  110. $productObj->array_options['options_discount_percent'] = null;
  111. $lines[] = (array) $productObj;
  112. return $lines;
  113. }
  114. /**
  115. * Validate invoice
  116. */
  117. public function validateInvoice(Facture $invoice, $sendId): Facture
  118. {
  119. ApiBbusLog::appLog("{$sendId} - validateInvoice_________START - " . microtime(true));
  120. return $this->apiInvoice->validateInvoice($invoice, 1);
  121. }
  122. /**
  123. * Validate invoice
  124. */
  125. public function validateInvoiceFromPROV(Facture $invoice, $sendId, $facture_id): Facture
  126. {
  127. $this->apiInvoice = new ApiInvoice;
  128. ApiBbusLog::eventLog("{$sendId} - validateInvoice_________START - " . microtime(true));
  129. return $this->apiInvoice->validateInvoice($invoice, 1);
  130. }
  131. /**
  132. * Set payment
  133. *
  134. * @return int Payment ID
  135. */
  136. public function setPaymentFromPROV(Facture $invoice, array $payment, string $sendId): int
  137. {
  138. $this->apiInvoice = new ApiInvoice;
  139. ApiBbusLog::eventLog("{$sendId} - setPayment_________START - " . microtime(true));
  140. return $this->apiInvoice->setPayment($invoice, $payment, $sendId);
  141. }
  142. /**
  143. * Set payment
  144. *
  145. * @return int Payment ID
  146. */
  147. public function setPayment(Facture $invoice, array $payment, string $sendId): int
  148. {
  149. ApiBbusLog::appLog("{$sendId} - setPayment_________START - " . microtime(true));
  150. return $this->apiInvoice->setPayment($invoice, $payment, $sendId);
  151. }
  152. /**
  153. * Save card payment log to invoice
  154. */
  155. public function saveCardPaymentLog(Facture $invoice, string $cardPaymentLog, $sendId): Facture
  156. {
  157. //ApiBbusLog::appLog("{$sendId} - saveCardPaymentLog_________START - " . microtime(true));
  158. $invoice->array_options['options_payment_log'] = $cardPaymentLog;
  159. $invoice->updateExtraField('payment_log');
  160. $json = json_decode($cardPaymentLog, true);
  161. if (!empty($json['authorization_number'])) {
  162. $sql = "
  163. UPDATE " . MAIN_DB_PREFIX . "paiement
  164. SET num_paiement='" . $json['authorization_number'] . "'
  165. WHERE rowid=(
  166. SELECT fk_paiement
  167. FROM " . MAIN_DB_PREFIX . "paiement_facture
  168. WHERE fk_facture={$invoice->id}
  169. )
  170. ";
  171. $this->db->query($sql);
  172. }
  173. return $invoice;
  174. }
  175. /**
  176. * Load product
  177. */
  178. public function loadProductToResult(array $line): array
  179. {
  180. $result = [];
  181. $product = new Product($this->db);
  182. if ($product->fetch($line['fk_product']) > 0) {
  183. $result = [
  184. 'id' => $product->id,
  185. 'ref' => $product->ref,
  186. 'label' => $product->label,
  187. 'description' => $product->description,
  188. 'vat' => $product->tva_tx,
  189. 'discount_period' => (empty($line['array_options']['discount_period'])) ? '' : $line['array_options']['discount_period'],
  190. 'discount_value' => (empty($line['array_options']['discount_value'])) ? '' : $line['array_options']['discount_value'],
  191. 'orig_price' => $product->price_ttc,
  192. 'price' => $product->price_ttc
  193. ];
  194. }
  195. return $result;
  196. }
  197. }
  198. /**
  199. *
  200. *
  201. */
  202. interface ApiInvoiceData
  203. {
  204. public function loadData(array $data): void;
  205. public function prepareData(): void;
  206. public function validate(): void;
  207. public function create(); // missing return type because of the different result objects
  208. }
  209. /**
  210. *
  211. *
  212. */
  213. class ApiInvoiceLine implements ApiInvoiceData
  214. {
  215. public $data;
  216. public $invoice;
  217. /**
  218. *
  219. */
  220. public function loadData(array $data): void
  221. {
  222. $this->data = (object) $data;
  223. }
  224. /**
  225. *
  226. */
  227. public function setInvoice(Facture $invoice): void
  228. {
  229. $this->invoice = $invoice;
  230. }
  231. /**
  232. *
  233. */
  234. public function prepareData(): void
  235. {
  236. $this->data->desc = sanitizeVal($this->data->desc, 'restricthtml');
  237. $this->data->label = sanitizeVal($this->data->label);
  238. if (($this->data->product_type != 9 && empty($this->data->fk_parent_line)) || $this->data->product_type == 9) {
  239. $this->data->fk_parent_line = 0;
  240. }
  241. }
  242. /**
  243. *
  244. */
  245. public function validate(): void
  246. {
  247. //
  248. }
  249. /**
  250. *
  251. */
  252. public function create(): Facture
  253. {
  254. $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);
  255. $pa_ht = $marginInfos[0];
  256. $updateRes = $this->invoice->addline(
  257. $this->data->desc,
  258. $this->data->subprice,
  259. $this->data->qty,
  260. $this->data->tva_tx,
  261. $this->data->localtax1_tx,
  262. $this->data->localtax2_tx,
  263. $this->data->fk_product,
  264. $this->data->remise_percent,
  265. $this->data->date_start,
  266. $this->data->date_end,
  267. $this->data->fk_code_ventilation,
  268. $this->data->info_bits,
  269. $this->data->fk_remise_except,
  270. $this->data->price_base_type ? $this->data->price_base_type : 'HT',
  271. $this->data->subprice,
  272. $this->data->product_type,
  273. $this->data->rang,
  274. $this->data->special_code,
  275. $this->data->origin,
  276. $this->data->origin_id,
  277. $this->data->fk_parent_line,
  278. empty($this->data->fk_fournprice) ? null : $this->data->fk_fournprice,
  279. $pa_ht,
  280. $this->data->label,
  281. $this->data->array_options,
  282. $this->data->situation_percent,
  283. $this->data->fk_prev_id,
  284. $this->data->fk_unit,
  285. 0,
  286. $this->data->ref_ext
  287. );
  288. if ($updateRes < 0) {
  289. throw new RestException(400, 'Unable to insert the new line. Check your inputs. ' . $this->invoice->error);
  290. }
  291. return $this->invoice;
  292. }
  293. }
  294. /**
  295. *
  296. *
  297. */
  298. class ApiInvoice implements ApiInvoiceData
  299. {
  300. const SOCID = 1;
  301. public $data;
  302. public $invoice;
  303. /**
  304. *
  305. */
  306. public function loadData(array $data): void
  307. {
  308. $this->invoice = null;
  309. $this->data = $data;
  310. }
  311. /**
  312. *
  313. */
  314. public function prepareData(): void
  315. {
  316. global $user;
  317. $this->data['socid'] = self::SOCID;
  318. $this->data['entity'] = $user->entity;
  319. }
  320. /**
  321. *
  322. */
  323. public function validate(): void
  324. {
  325. $fields = [
  326. 'socid',
  327. 'entity'
  328. ];
  329. foreach ($fields as $field) {
  330. if (!isset($this->data[$field])) {
  331. throw new RestException(400, "Invoice {$field} field missing");
  332. }
  333. }
  334. }
  335. /**
  336. *
  337. */
  338. public function create($company_invoice = []): Facture
  339. {
  340. global $db;
  341. $this->invoice = new Facture($db);
  342. foreach ($this->data as $field => $value) {
  343. if (preg_match('/^array_options/', $field)) {
  344. $f = str_replace('array_options_', '', $field);
  345. $this->invoice->array_options[$f] = $value;
  346. continue;
  347. }
  348. $this->invoice->$field = $value;
  349. }
  350. if (!array_key_exists('date', $this->data)) {
  351. $this->invoice->date = dol_now();
  352. }
  353. if(empty($company_invoice)){
  354. $this->invoice->type = 7;
  355. }
  356. if ($this->invoice->create(DolibarrApiAccess::$user, 0, (empty($this->data['date_lim_reglement']) ? 0 : $this->data['date_lim_reglement'])) < 0) {
  357. throw new RestException(500, 'Error creating invoice', array_merge([$this->invoice->error], $this->invoice->errors));
  358. }
  359. return $this->invoice;
  360. }
  361. /**
  362. *
  363. */
  364. public function validateInvoice(Facture $invoice, int $notrigger): Facture
  365. {
  366. $result = $invoice->validate(DolibarrApiAccess::$user, '', 0, $notrigger);
  367. if ($result == 0) {
  368. throw new RestException(304, 'Error nothing done. May be object is already validated');
  369. }
  370. if ($result < 0) {
  371. throw new RestException(500, 'Error when validating Invoice: ' . $invoice->error);
  372. }
  373. return $invoice;
  374. }
  375. /**
  376. *
  377. */
  378. public function setPayment(Facture $invoice, array $data, string $sendId): int
  379. {
  380. ApiBbusLog::appLog("ApiinvoiceHelper: setPayment function");
  381. global $db;
  382. if (isModEnabled('banque')) {
  383. if (empty($data['accountid'])) {
  384. ApiBbusLog::appLog("ApiinvoiceHelper: setPayment accountid error");
  385. throw new RestException(400, 'Account ID is mandatory');
  386. }
  387. }
  388. if (empty($data['paymentid'])) {
  389. ApiBbusLog::appLog("ApiinvoiceHelper: setPayment paymentid error");
  390. throw new RestException(400, 'Payment ID or Payment Code is mandatory');
  391. }
  392. // Calculate amount to pay
  393. $totalpaid = $invoice->getSommePaiement();
  394. $totalcreditnotes = $invoice->getSumCreditNotesUsed();
  395. $totaldeposits = $invoice->getSumDepositsUsed();
  396. $resteapayer = price2num($invoice->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
  397. $db->begin();
  398. $amounts = [];
  399. $multicurrency_amounts = [];
  400. // Clean parameters amount if payment is for a credit note
  401. if ($invoice->type == Facture::TYPE_CREDIT_NOTE) {
  402. $resteapayer = price2num($resteapayer, 'MT');
  403. $amounts[$invoice->id] = -$resteapayer;
  404. // Multicurrency
  405. $newvalue = price2num($invoice->multicurrency_total_ttc, 'MT');
  406. $multicurrency_amounts[$invoice->id] = -$newvalue;
  407. } else {
  408. $resteapayer = price2num($resteapayer, 'MT');
  409. $amounts[$invoice->id] = $resteapayer;
  410. // Multicurrency
  411. $newvalue = price2num($invoice->multicurrency_total_ttc, 'MT');
  412. $multicurrency_amounts[$invoice->id] = $newvalue;
  413. }
  414. // Creation of payment line
  415. $paymentobj = new Paiement($db);
  416. $paymentobj->datepaye = $data['datepaye'];
  417. $paymentobj->amounts = $amounts; // Array with all payments dispatching with invoice id
  418. $paymentobj->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
  419. $paymentobj->paiementid = $data['paymentid'];
  420. $paymentobj->paiementcode = dol_getIdFromCode($db, $data['paymentid'], 'c_paiement', 'id', 'code', 1);
  421. $paymentobj->num_payment = $data['num_payment'];
  422. $paymentobj->note_private = (is_array($data['comment'])) ? json_encode($data['comment']) : $data['comment'];
  423. $paymentId = $paymentobj->create(DolibarrApiAccess::$user, ($data['closepaidinvoices'] == 'yes' ? 1 : 0)); // This include closing invoices
  424. if ($paymentId < 0) {
  425. $db->rollback();
  426. ApiBbusLog::appLog("{$sendId} Payment error : " . $paymentobj->error);
  427. throw new RestException(400, 'Payment error : ' . $paymentobj->error);
  428. }
  429. ApiBbusLog::appLog("paymentId created");
  430. if (isModEnabled('banque')) {
  431. $label = '(CustomerInvoicePayment)';
  432. $chqemetteur = '';
  433. $chqbank = '';
  434. if ($paymentobj->paiementcode == 'CHQ' && empty($chqemetteur)) {
  435. ApiBbusLog::appLog("{$sendId} Emetteur is mandatory when payment code is " . $paymentobj->paiementcode);
  436. throw new RestException(400, 'Emetteur is mandatory when payment code is ' . $paymentobj->paiementcode);
  437. }
  438. if ($invoice->type == Facture::TYPE_CREDIT_NOTE) {
  439. $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
  440. }
  441. $result = $paymentobj->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $data['accountid'], $chqemetteur, $chqbank);
  442. if ($result < 0) {
  443. $db->rollback();
  444. ApiBbusLog::appLog("{$sendId} Add payment to bank error : " . $paymentobj->error);
  445. throw new RestException(400, 'Add payment to bank error : ' . $paymentobj->error);
  446. }
  447. }
  448. #
  449. # set Facture -> payment_transaction_id
  450. #
  451. if (!empty($data['comment'])) {
  452. $commentJSON = json_decode($data['comment']);
  453. $invoice->array_options['options_payment_transaction_id'] = $commentJSON->card_transaction_id;
  454. $invoice->updateExtraField('payment_transaction_id');
  455. }
  456. $db->commit();
  457. ApiBbusLog::appLog("{$sendId} PAYMENT CREATED: {$paymentId}");
  458. return $paymentId;
  459. }
  460. }