apiinvoicehelper.class.php 14 KB

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