apiinvoicehelper.class.php.bak 14 KB

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