apiinvoicehelper.class.php 13 KB

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