actions_addupdatedelete.inc.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  1. <?php
  2. /* Copyright (C) 2017-2019 Laurent Destailleur <eldy@users.sourceforge.net>
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. * or see https://www.gnu.org/
  17. */
  18. /**
  19. * \file htdocs/core/actions_addupdatedelete.inc.php
  20. * \brief Code for common actions cancel / add / update / update_extras / delete / deleteline / validate / cancel / reopen / clone
  21. */
  22. // $action or $cancel must be defined
  23. // $object must be defined
  24. // $permissiontoadd must be defined
  25. // $permissiontodelete must be defined
  26. // $backurlforlist must be defined
  27. // $backtopage may be defined
  28. // $noback may be defined
  29. // $triggermodname may be defined
  30. $hidedetails = isset ($hidedetails) ? $hidedetails : '';
  31. $hidedesc = isset ($hidedesc) ? $hidedesc : '';
  32. $hideref = isset ($hideref) ? $hideref : '';
  33. if (!empty ($permissionedit) && empty ($permissiontoadd)) {
  34. $permissiontoadd = $permissionedit; // For backward compatibility
  35. }
  36. if ($cancel) {
  37. /*var_dump($cancel);var_dump($backtopage);var_dump($backtopageforcancel);exit;*/
  38. if (!empty ($backtopageforcancel)) {
  39. header("Location: " . $backtopageforcancel);
  40. exit;
  41. } elseif (!empty ($backtopage)) {
  42. header("Location: " . $backtopage);
  43. exit;
  44. }
  45. $action = '';
  46. }
  47. if ($action == 'confirm_checkoutclosure_settlement') {
  48. $checkoutClosure = new Checkoutclosure($db);
  49. $data = explode('_', $datastring);
  50. $idmenu = $data[0];
  51. $entity = $data[1];
  52. $from = $data[2];
  53. $sumHUFCash = 0;
  54. $sumEURCash = 0;
  55. $to = date("Y-m-d H:i:s", dol_now());
  56. $HUFCash = $factureStat->sumSaleInHufCash($from, $to, $entity);
  57. $EURCash = $factureStat->sumSaleInEurCash($from, $to, $entity);
  58. foreach ($HUFCash as $huf) {
  59. $sumHUFCash += $huf['multicurrency_total_ttc'];
  60. }
  61. foreach ($EURCash as $eur) {
  62. $sumEURCash += $eur['multicurrency_total_ttc'];
  63. }
  64. $sumByVAT = $helper->getSumByVAT($from, $entity);
  65. $JSONDataArray = [
  66. 'sumHUFCash' => $sumHUFCash,
  67. 'sumEURCash' => $sumEURCash,
  68. 'sumByVAT' => $sumByVAT,
  69. 'entity' => $entity,
  70. 'from' => $from,
  71. 'to' => $to
  72. ];
  73. $html = $helper->createHTMLForDailyClosingCheckoutClosure($entity, 'Mr NILSZ Kft.', $from, $sumHUFCash, $sumEURCash);
  74. $pdf = new SettlementsPDFPrint($html);
  75. $checkoutclosurePDF = $pdf->generateDailyClosuingCheckoutClosurePDF();
  76. //exit;
  77. $checkoutClosure->entity = $entity;
  78. $checkoutClosure->label = 'Checkout closure';
  79. $checkoutClosure->status = 1;
  80. $checkoutClosure->model_pdf = $checkoutclosurePDF;
  81. $checkoutClosure->checkout_json = json_encode($JSONDataArray);
  82. $checkoutClosure->date_closing = $to;
  83. $checkoutClosure->create($user);
  84. $urltogo = '/custom/financialreport/checkoutclosureindex.php?idmenu=' . $idmenu . '&mainmenu=financialreport&leftmenu=';
  85. header("Location: " . $urltogo);
  86. exit;
  87. }
  88. if ($action == 'confirm_payment') {
  89. $userinvoice = new UserInvoice($db);
  90. $result = $userinvoice->fetch($id);
  91. $now = date("Y-m-d H:i:s", dol_now());
  92. if ($result > 0) {
  93. $userinvoice->payed = 1;
  94. $userinvoice->paymentdate = $now;
  95. $userinvoice->receipt_pdf = $fullpath;
  96. $updated = $userinvoice->update($user);
  97. if ($updated > 0) {
  98. $urltogo = '/custom/financialreport/userinvoice_card.php?id=' . $id . '&user_id=' . $user_id . '&payment_type=' . $payment_type . '&idmenu=&save_lastsearch_values=1';
  99. setEventMessage($langs->trans("CommissionUpdateSucces"), 'mesgs');
  100. header("Location: " . $urltogo);
  101. exit;
  102. } else {
  103. $urltogo = '/custom/financialreport/userinvoice_card.php?id=' . $id . '&user_id=' . $user_id . '&payment_type=' . $payment_type . '&idmenu=&save_lastsearch_values=1';
  104. setEventMessage($langs->trans("CommissionUpdateFailed"), 'error');
  105. header("Location: " . $urltogo);
  106. exit;
  107. }
  108. } else {
  109. $urltogo = '/custom/financialreport/userinvoice_card.php?id=' . $id . '&user_id=' . $user_id . '&payment_type=' . $payment_type . '&idmenu=&save_lastsearch_values=1';
  110. setEventMessage($langs->trans("CommisonFaultyRecord"), 'error');
  111. header("Location: " . $urltogo);
  112. exit;
  113. }
  114. }
  115. if ($action == 'confirm_settlement') {
  116. $isMinCommissionActice = false;
  117. $commissionhandler = new CommissionHandler();
  118. $selectedDataByOptionsArray = [];
  119. $data = explode('@', $commissions);
  120. $selectedOptions = explode("@", $optionsString);
  121. foreach ($selectedOptions as $itemtmp) {
  122. $array = explode('|', $itemtmp);
  123. $arrayTMP[$array[0]] = $array[1];
  124. }
  125. $summaHUF = 0;
  126. foreach ($data as $dataKey => $dataValue) {
  127. $tmpDataArray = explode("_", $dataValue);
  128. $logoutDate = $helper->checklogoutRecordInUserNaplo($tmpDataArray[0], $tmpDataArray[1], $id);
  129. $to = $logoutDate != '' ? $logoutDate : date('Y-m-d H:i:s', dol_now());
  130. $totalCommission = $commmissionhandler->getTotalCommission($tmpDataArray[0], $tmpDataArray[1], $to);
  131. $tmpDataArray[1] = $tmpDataArray[1] . '||' . $to;
  132. $tmpDataArray[2] = $totalCommission;
  133. $dataValue = implode("_", $tmpDataArray);
  134. if (in_array($dataKey, $selectedOptions)) {
  135. $selectedDataByOptionsArray[] = $dataValue;
  136. }
  137. }
  138. foreach ($selectedDataByOptionsArray as $item) {
  139. $itemData = explode('_', $item);
  140. $interval = explode('||', $itemData[1]);
  141. $usersDataDateArrayFrom[][$itemData[0]] = $interval[0];
  142. $usersDataDateArrayTo[][$itemData[0]] = $interval[1];
  143. $usersDateArray[][$itemData[0]] = $itemData[1];
  144. }
  145. foreach ($usersDateArray as $record) {
  146. foreach ($record as $recordKey => $recordValue) {
  147. $usersDateArrayTMP[][$recordKey] = explode('||', $recordValue);
  148. }
  149. }
  150. $usersArray = $helper->getUsersArray($selectedDataByOptionsArray);
  151. $usersArrayTMP = $usersArray;
  152. $allUsersString = implode(',', $usersArray);
  153. $settledInvoicesArray = [];
  154. $usersAmountArray = [];
  155. $validatorArray = [];
  156. $usersInvoicesArray = [];
  157. $usersString = '';
  158. $invocesRowidString = '';
  159. $queryArray = $helper->getQueryArray($usersDataDateArrayFrom, $usersDataDateArrayTo);
  160. foreach ($usersArray as $userRecord) {
  161. $usersAmountArray[$userRecord]['amount'] = 0;
  162. $usersAmountArray[$userRecord]['invoices'] = '';
  163. }
  164. foreach ($queryArray as $value) {
  165. $from = $value['from'];
  166. $to = $value['to'];
  167. $exception = $helper->getAllComissionInvoicesOfUserInTheGroupFromUserInvoiceCreated($allUsersString, $queryArray[0]['from'], $queryArray[count($queryArray) - 1]['to']);
  168. $invocesRowidString = $helper->getInvoicesRowidFromFactureInAnIntervalByEveryUser($allUsersString, $from, $to, $exception);
  169. $usrCount = 0;
  170. $index = 0;
  171. $usersArrayFilteredUsers = [];
  172. $usersArrayFilteredUsersFrom = [];
  173. foreach ($usersDateArrayTMP as $usrDate) {
  174. foreach ($usrDate as $key => $value1) {
  175. if ($value1[0] == $from && $value1[1] > $to) {
  176. $usrCount++;
  177. $validatorArray[$key]['valid'] = true;
  178. } elseif ($value1[0] < $from && $value1[1] > $to) {
  179. $usrCount++;
  180. $validatorArray[$key]['valid'] = true;
  181. } elseif ($value1[0] < $from && $value1[1] == $to) {
  182. $usrCount++;
  183. $validatorArray[$key]['valid'] = true;
  184. } elseif ($value1[0] == $from && $value1[1] == $to) {
  185. $usrCount++;
  186. $validatorArray[$key]['valid'] = true;
  187. } else {
  188. $validatorArray[$key]['valid'] = false;
  189. }
  190. if ($validatorArray[$key]['valid']) {
  191. $usersArrayFilteredUsers[] = $key;
  192. }
  193. $usersArrayFilteredUsersFrom[$key] = $value1[0];
  194. }
  195. }
  196. $usersString = implode(',', $usersArrayFilteredUsers);
  197. if ($usersString != '') {
  198. $invocesRowidString = $helper->getInvoicesRowidFromFactureInAnIntervalByEveryUser($usersString, $from, $to, $exception);
  199. $allComissionInvoicesOfUserInTheGroupFromUserInvoice = '';
  200. $commissionHUF = $commmissionhandler->getAllCommission($usersString, 'HUF', $from, $to, $exception);
  201. $commissionEUR = $commmissionhandler->getAllCommission($usersString, 'EUR', $from, $to, $exception);
  202. $osszeg = $commissionHUF + $commissionEUR;
  203. if ($usrCount > 0) {
  204. $amount = $osszeg / $usrCount;
  205. }
  206. }
  207. foreach ($usersArrayFilteredUsers as $filteredUser) {
  208. $usersAmountArray[$filteredUser]['amount'] += $amount;
  209. if ($invocesRowidString != '') {
  210. if ($usersAmountArray[$filteredUser]['invoices'] != '') {
  211. $usersAmountArray[$filteredUser]['invoices'] .= ',';
  212. }
  213. $usersAmountArray[$filteredUser]['invoices'] .= $invocesRowidString;
  214. $usersAmountArray[$filteredUser]['namedata'] .= $helper->getNamedataFoTheUser($filteredUser);
  215. }
  216. }
  217. }
  218. $summaHUF = saveUserInvoiceRecordAndSetSummaHUF($commissionhandler, $usersAmountArray, $helper, $usersArrayFilteredUsersFrom, $isMinCommissionActice);
  219. $dataArray = array(
  220. 'GroupName' => $helper->getGroupLabelById($id),
  221. 'UsersData' => $usersAmountArray,
  222. 'FullAmount' => $summaHUF,
  223. 'Interval' => $helper->getFirstDateFromUserNaplo($id) . ' - ' . date('Y-m-d H:i:s'),
  224. );
  225. insertCommissionSettlementObj($dataArray, $groupEntity, $summaHUF, $helper);
  226. $urltogo = getUrltogo($hotelgroup, $id);
  227. header("Location: " . $urltogo);
  228. exit;
  229. }
  230. function saveUserInvoiceRecordAndSetSummaHUF($commissionhandler, $usersAmountArray, $helper, $usersArrayFilteredUsersFrom, $isMinCommissionActice = false)
  231. {
  232. $generalDailyCommission = $commissionhandler->getDailyMinimumCommission();
  233. foreach ($usersAmountArray as $useKey => $userInvoiceRecord) {
  234. $uniformHUF = (int) $userInvoiceRecord['amount'];
  235. if ($uniformHUF != 0) {
  236. if ($isMinCommissionActice) {
  237. if ($generalDailyCommission > $uniformHUF) {
  238. $uniformHUF = $generalDailyCommission;
  239. }
  240. }
  241. $uniformInvoices = $userInvoiceRecord['invoices'];
  242. $helper->saveUserInvoiceRecord($usersArrayFilteredUsersFrom, $useKey, $uniformHUF, $uniformInvoices);
  243. $summaHUF += $uniformHUF;
  244. }
  245. }
  246. return $summaHUF;
  247. }
  248. function getUrltogo($hotelgroup, $id)
  249. {
  250. if ($hotelgroup) {
  251. return '/custom/financialreport/settlementsstatementshotelsindex.php?id=' . $id;
  252. //} elseif (date("Y-m-d", dol_now()) != $exceptionFrom) {
  253. // $urltogo = '/custom/financialreport/settlementsdaterangeindex.php?id=' . $id . '&datepicker=' . $exceptionFrom . ' - ' . $exceptionTo;
  254. } else {
  255. return '/custom/financialreport/settlementsstatementsindex.php?id=' . $id;
  256. }
  257. }
  258. function insertCommissionSettlementObj($dataArray, $groupEntity, $summaHUF, $helper)
  259. {
  260. global $db, $user;
  261. $html = $helper->createHTMLForSettlement($dataArray);
  262. $pdf = new SettlementsPDFPrint($html);
  263. $CommissionPDF = $pdf->generateCommissionSettlementsPDF();
  264. $commissionSettlementsObj = new Commissionsettlements($db);
  265. $jsonData = json_encode($dataArray, JSON_PRETTY_PRINT);
  266. //exit;
  267. $sql = "INSERT INTO " . MAIN_DB_PREFIX . $commissionSettlementsObj->table_element . " (entity, ref, label, amount, description, model_pdf, fk_user_creat) VALUES ({$groupEntity}, '" . $helper->generateRef('2') . "', '', '{$summaHUF}', '{$jsonData}', '{$CommissionPDF}', $user->id)";
  268. $result = $db->query($sql);
  269. }
  270. function datumOsszehasonlitas($a, $b)
  271. {
  272. $idopontA = strtotime($a);
  273. $idopontB = strtotime($b);
  274. if ($idopontA == $idopontB) {
  275. return 0;
  276. }
  277. return ($idopontA < $idopontB) ? -1 : 1;
  278. }
  279. if ($action == 'confirm_makeupto') {
  280. $tempDataArray = explode('|', $datastring);
  281. $makeUpToDataArray = ['user_id' => $tempDataArray[0], 'amount' => intval($tempDataArray[1]), 'year' => $tempDataArray[2], 'month' => $tempDataArray[3]];
  282. $date = $makeUpToDataArray['year'] . '-' . $makeUpToDataArray['month'] . '-' . date("t", strtotime("$year-$month-01"));
  283. $userinvoice = new UserInvoice($db);
  284. $userinvoice->ref = $helper->generateRef(2);
  285. $userinvoice->label = 'Jutalék/Commission ' . $date;
  286. $userinvoice->date_creation = $date;
  287. $userinvoice->description = 'Összeg / Amount: ' . $helper->correctNumber($makeUpToDataArray['amount']) . ' HUF. Make up to on: ' . $date;
  288. $userinvoice->user_id = $makeUpToDataArray['user_id'];
  289. $userinvoice->payment_type = 2;
  290. $userinvoice->amount = $makeUpToDataArray['amount'];
  291. $userinvoice->currency = 'HUF';
  292. $userinvoice->individual = 1;
  293. $userinvoice->create($user);
  294. setEventMessage($langs->trans('CommissionSaved'));
  295. $urltogo = '/custom/financialreport/commissionsummaryindex.php?idmenu=1628&year=' . $makeUpToDataArray['year'] . '&month=' . $makeUpToDataArray['month'] . '&mainmenu=financialreport&leftmenu=';
  296. header("Location: " . $urltogo);
  297. exit;
  298. }
  299. if ($action == 'confirm_personal_settlement') {
  300. $isMinCommissionActice = false;
  301. $commissionhandler = new CommissionHandler();
  302. $commissionArray = [];
  303. $result = explode('_', $commissions);
  304. $user_id = $result[0];
  305. $from = $result[1];
  306. $logoutDate = $helper->checklogoutRecordInUserNaplo($user_id, $from, $id);
  307. $to = $logoutDate != '' ? $logoutDate : date('Y-m-d H:i:s', dol_now());
  308. $totalCommission = $commmissionhandler->getTotalCommission($user_id, $from, $to);
  309. $result[2] = $totalCommission;
  310. $commissionArray['HUF'] = $result[2];
  311. if ($commissionArray['HUF'] > 0) {
  312. $invocesRowidString = $helper->getInvoicesRowidFromFacture($user_id, $from, $to);
  313. }
  314. $exceptionFrom = $exceptionTo = date("Y-m-d", strtotime($from));
  315. foreach ($commissionArray as $key => $amount) {
  316. if ($amount > 0) {
  317. if ($isMinCommissionActice) {
  318. $generalDailyCommission = $commissionhandler->getDailyMinimumCommission();
  319. if ($generalDailyCommission > $amount) {
  320. $amount = $generalDailyCommission;
  321. }
  322. }
  323. $userinvoice = new UserInvoice($db);
  324. $currency = $key == 'HUF' ? 0 : 1;
  325. $userinvoice->ref = $helper->generateRef(2);
  326. $userinvoice->label = 'Jutalék/Commission ' . date("Y-m-d", strtotime($from));
  327. $userinvoice->description = 'Összeg / Amount: ' . $amount . ' ' . $key;
  328. $userinvoice->user_id = $user_id;
  329. $userinvoice->payment_type = 2;
  330. $userinvoice->amount = $amount;
  331. $userinvoice->currency = $currency;
  332. $userinvoice->individual = 1;
  333. $userinvoice->invoices = $invocesRowidString;
  334. $userinvoice->date_creation = strtotime($from);
  335. $userinvoice->create($user);
  336. }
  337. }
  338. //if (date("Y-m-d", dol_now()) != $exceptionFrom) {
  339. // $urltogo = '/custom/financialreport/settlementsdaterangeindex.php?id=' . $id . '&datepicker=' . $exceptionFrom . ' - ' . $exceptionTo;
  340. //} else {
  341. $urltogo = '/custom/financialreport/settlementsstatementsindex.php?id=' . $id;
  342. //}
  343. header("Location: " . $urltogo);
  344. exit;
  345. }
  346. // Action to add record
  347. if ($action == 'add' && !empty ($permissiontoadd)) {
  348. foreach ($object->fields as $key => $val) {
  349. if ($object->fields[$key]['type'] == 'duration') {
  350. if (GETPOST($key . 'hour') == '' && GETPOST($key . 'min') == '') {
  351. continue; // The field was not submited to be saved
  352. }
  353. } else {
  354. if (!GETPOSTISSET($key)) {
  355. continue; // The field was not submited to be saved
  356. }
  357. }
  358. // Ignore special fields
  359. if (in_array($key, array('rowid', 'entity', 'import_key'))) {
  360. continue;
  361. }
  362. if (in_array($key, array('date_creation', 'tms', 'fk_user_creat', 'fk_user_modif'))) {
  363. if (!in_array(abs($val['visible']), array(1, 3))) {
  364. continue; // Only 1 and 3 that are case to create
  365. }
  366. }
  367. // Set value to insert
  368. if (in_array($object->fields[$key]['type'], array('text', 'html'))) {
  369. $value = GETPOST($key, 'restricthtml');
  370. } elseif ($object->fields[$key]['type'] == 'date') {
  371. $value = dol_mktime(12, 0, 0, GETPOST($key . 'month', 'int'), GETPOST($key . 'day', 'int'), GETPOST($key . 'year', 'int')); // for date without hour, we use gmt
  372. } elseif ($object->fields[$key]['type'] == 'datetime') {
  373. $value = dol_mktime(GETPOST($key . 'hour', 'int'), GETPOST($key . 'min', 'int'), GETPOST($key . 'sec', 'int'), GETPOST($key . 'month', 'int'), GETPOST($key . 'day', 'int'), GETPOST($key . 'year', 'int'), 'tzuserrel');
  374. } elseif ($object->fields[$key]['type'] == 'duration') {
  375. $value = 60 * 60 * GETPOST($key . 'hour', 'int') + 60 * GETPOST($key . 'min', 'int');
  376. } elseif (preg_match('/^(integer|price|real|double)/', $object->fields[$key]['type'])) {
  377. $value = price2num(GETPOST($key, 'alphanohtml')); // To fix decimal separator according to lang setup
  378. } elseif ($object->fields[$key]['type'] == 'boolean') {
  379. $value = ((GETPOST($key) == '1' || GETPOST($key) == 'on') ? 1 : 0);
  380. } elseif ($object->fields[$key]['type'] == 'reference') {
  381. $tmparraykey = array_keys($object->param_list);
  382. $value = $tmparraykey[GETPOST($key)] . ',' . GETPOST($key . '2');
  383. } else {
  384. if ($key == 'lang') {
  385. $value = GETPOST($key, 'aZ09') ? GETPOST($key, 'aZ09') : "";
  386. } else {
  387. $value = GETPOST($key, 'alphanohtml');
  388. }
  389. }
  390. if (preg_match('/^integer:/i', $object->fields[$key]['type']) && $value == '-1') {
  391. $value = ''; // This is an implicit foreign key field
  392. }
  393. if (!empty ($object->fields[$key]['foreignkey']) && $value == '-1') {
  394. $value = ''; // This is an explicit foreign key field
  395. }
  396. //var_dump($key.' '.$value.' '.$object->fields[$key]['type']);
  397. $object->$key = $value;
  398. if (!empty ($val['notnull']) && $val['notnull'] > 0 && $object->$key == '' && isset ($val['default']) && $val['default'] == '(PROV)') {
  399. $object->$key = '(PROV)';
  400. }
  401. if (!empty ($val['notnull']) && $val['notnull'] > 0 && $object->$key == '' && !isset ($val['default'])) {
  402. $error++;
  403. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv($val['label'])), null, 'errors');
  404. }
  405. // Validation of fields values
  406. if (getDolGlobalInt('MAIN_FEATURES_LEVEL') >= 2 || !empty ($conf->global->MAIN_ACTIVATE_VALIDATION_RESULT)) {
  407. if (!$error && !empty ($val['validate']) && is_callable(array($object, 'validateField'))) {
  408. if (!$object->validateField($object->fields, $key, $value)) {
  409. $error++;
  410. }
  411. }
  412. }
  413. }
  414. // Fill array 'array_options' with data from add form
  415. if (!$error) {
  416. $ret = $extrafields->setOptionalsFromPost(null, $object, '', 1);
  417. if ($ret < 0) {
  418. $error++;
  419. }
  420. }
  421. if (!$error) {
  422. $result = $object->create($user);
  423. if ($result > 0) {
  424. // Creation OK
  425. if (isModEnabled('categorie') && method_exists($object, 'setCategories')) {
  426. $categories = GETPOST('categories', 'array:int');
  427. $object->setCategories($categories);
  428. }
  429. $backtopage .= '?id=' . $object->id . '&user_id=' . $user_id . '&payment_type=' . $payment_type . '&idmenu=' . $idmenu . '&save_lastsearch_values=1';
  430. $urltogo = $backtopage ? str_replace('__ID__', $result, $backtopage) : $backurlforlist;
  431. $urltogo = preg_replace('/--IDFORBACKTOPAGE--/', $object->id, $urltogo); // New method to autoselect project after a New on another form object creation
  432. if (empty ($noback)) {
  433. header("Location: " . $urltogo);
  434. exit;
  435. }
  436. } else {
  437. $error++;
  438. // Creation KO
  439. if (!empty ($object->errors)) {
  440. setEventMessages(null, $object->errors, 'errors');
  441. } else {
  442. setEventMessages($object->error, null, 'errors');
  443. }
  444. $action = 'create';
  445. }
  446. } else {
  447. $action = 'create';
  448. }
  449. }
  450. // Action to update record
  451. if ($action == 'update' && !empty ($permissiontoadd)) {
  452. $backtopage .= '?id=' . $id . '&user_id=' . $user_id . '&payment_type=' . $payment_type . '&idmenu=' . $idmenu . '&save_lastsearch_values=1';
  453. foreach ($object->fields as $key => $val) {
  454. // Check if field was submited to be edited
  455. if ($object->fields[$key]['type'] == 'duration') {
  456. if (!GETPOSTISSET($key . 'hour') || !GETPOSTISSET($key . 'min')) {
  457. continue; // The field was not submited to be saved
  458. }
  459. } elseif ($object->fields[$key]['type'] == 'boolean') {
  460. if (!GETPOSTISSET($key)) {
  461. $object->$key = 0; // use 0 instead null if the field is defined as not null
  462. continue;
  463. }
  464. } else {
  465. if (!GETPOSTISSET($key)) {
  466. continue; // The field was not submited to be saved
  467. }
  468. }
  469. // Ignore special fields
  470. if (in_array($key, array('rowid', 'entity', 'import_key'))) {
  471. continue;
  472. }
  473. if (in_array($key, array('date_creation', 'tms', 'fk_user_creat', 'fk_user_modif'))) {
  474. if (!in_array(abs($val['visible']), array(1, 3, 4))) {
  475. continue; // Only 1 and 3 and 4, that are cases to update
  476. }
  477. }
  478. // Set value to update
  479. if (preg_match('/^(text|html)/', $object->fields[$key]['type'])) {
  480. $tmparray = explode(':', $object->fields[$key]['type']);
  481. if (!empty ($tmparray[1])) {
  482. $value = GETPOST($key, $tmparray[1]);
  483. } else {
  484. $value = GETPOST($key, 'restricthtml');
  485. }
  486. } elseif ($object->fields[$key]['type'] == 'date') {
  487. $value = dol_mktime(12, 0, 0, GETPOST($key . 'month', 'int'), GETPOST($key . 'day', 'int'), GETPOST($key . 'year', 'int')); // for date without hour, we use gmt
  488. } elseif ($object->fields[$key]['type'] == 'datetime') {
  489. $value = dol_mktime(GETPOST($key . 'hour', 'int'), GETPOST($key . 'min', 'int'), GETPOST($key . 'sec', 'int'), GETPOST($key . 'month', 'int'), GETPOST($key . 'day', 'int'), GETPOST($key . 'year', 'int'), 'tzuserrel');
  490. } elseif ($object->fields[$key]['type'] == 'duration') {
  491. if (GETPOST($key . 'hour', 'int') != '' || GETPOST($key . 'min', 'int') != '') {
  492. $value = 60 * 60 * GETPOST($key . 'hour', 'int') + 60 * GETPOST($key . 'min', 'int');
  493. } else {
  494. $value = '';
  495. }
  496. } elseif (preg_match('/^(integer|price|real|double)/', $object->fields[$key]['type'])) {
  497. $value = price2num(GETPOST($key, 'alphanohtml')); // To fix decimal separator according to lang setup
  498. } elseif ($object->fields[$key]['type'] == 'boolean') {
  499. $value = ((GETPOST($key, 'aZ09') == 'on' || GETPOST($key, 'aZ09') == '1') ? 1 : 0);
  500. } elseif ($object->fields[$key]['type'] == 'reference') {
  501. $value = array_keys($object->param_list)[GETPOST($key)] . ',' . GETPOST($key . '2');
  502. } else {
  503. if ($key == 'lang') {
  504. $value = GETPOST($key, 'aZ09');
  505. } else {
  506. $value = GETPOST($key, 'alphanohtml');
  507. }
  508. }
  509. if (preg_match('/^integer:/i', $object->fields[$key]['type']) && $value == '-1') {
  510. $value = ''; // This is an implicit foreign key field
  511. }
  512. if (!empty ($object->fields[$key]['foreignkey']) && $value == '-1') {
  513. $value = ''; // This is an explicit foreign key field
  514. }
  515. $object->$key = $value;
  516. if ($val['notnull'] > 0 && $object->$key == '' && is_null($val['default'])) {
  517. $error++;
  518. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv($val['label'])), null, 'errors');
  519. }
  520. // Validation of fields values
  521. if (getDolGlobalInt('MAIN_FEATURES_LEVEL') >= 2 || !empty ($conf->global->MAIN_ACTIVATE_VALIDATION_RESULT)) {
  522. if (!$error && !empty ($val['validate']) && is_callable(array($object, 'validateField'))) {
  523. if (!$object->validateField($object->fields, $key, $value)) {
  524. $error++;
  525. }
  526. }
  527. }
  528. if (isModEnabled('categorie')) {
  529. $categories = GETPOST('categories', 'array');
  530. if (method_exists($object, 'setCategories')) {
  531. $object->setCategories($categories);
  532. }
  533. }
  534. }
  535. // Fill array 'array_options' with data from add form
  536. if (!$error) {
  537. $ret = $extrafields->setOptionalsFromPost(null, $object, '@GETPOSTISSET');
  538. if ($ret < 0) {
  539. $error++;
  540. }
  541. }
  542. if (!$error) {
  543. $result = $object->update($user);
  544. if ($result > 0) {
  545. $action = 'view';
  546. $urltogo = $backtopage ? str_replace('__ID__', $result, $backtopage) : $backurlforlist;
  547. $urltogo = preg_replace('/--IDFORBACKTOPAGE--/', $object->id, $urltogo); // New method to autoselect project after a New on another form object creation
  548. if ($urltogo && !$noback) {
  549. header("Location: " . $urltogo);
  550. exit;
  551. }
  552. } else {
  553. $error++;
  554. // Creation KO
  555. setEventMessages($object->error, $object->errors, 'errors');
  556. $action = 'edit';
  557. }
  558. } else {
  559. $action = 'edit';
  560. }
  561. }
  562. // Action to update one extrafield
  563. if ($action == "update_extras" && !empty ($permissiontoadd)) {
  564. $object->fetch(GETPOST('id', 'int'));
  565. $attributekey = GETPOST('attribute', 'alpha');
  566. $attributekeylong = 'options_' . $attributekey;
  567. if (GETPOSTISSET($attributekeylong . 'day') && GETPOSTISSET($attributekeylong . 'month') && GETPOSTISSET($attributekeylong . 'year')) {
  568. // This is properties of a date
  569. $object->array_options['options_' . $attributekey] = dol_mktime(GETPOST($attributekeylong . 'hour', 'int'), GETPOST($attributekeylong . 'min', 'int'), GETPOST($attributekeylong . 'sec', 'int'), GETPOST($attributekeylong . 'month', 'int'), GETPOST($attributekeylong . 'day', 'int'), GETPOST($attributekeylong . 'year', 'int'));
  570. //var_dump(dol_print_date($object->array_options['options_'.$attributekey]));exit;
  571. } else {
  572. $object->array_options['options_' . $attributekey] = GETPOST($attributekeylong, 'alpha');
  573. }
  574. $result = $object->insertExtraFields(empty ($triggermodname) ? '' : $triggermodname, $user);
  575. if ($result > 0) {
  576. setEventMessages($langs->trans('RecordSaved'), null, 'mesgs');
  577. $action = 'view';
  578. } else {
  579. $error++;
  580. setEventMessages($object->error, $object->errors, 'errors');
  581. $action = 'edit_extras';
  582. }
  583. }
  584. // Action to delete
  585. if ($action == 'confirm_delete' && !empty ($permissiontodelete)) {
  586. if (!($object->id > 0)) {
  587. dol_print_error('', 'Error, object must be fetched before being deleted');
  588. exit;
  589. }
  590. $result = $object->delete($user);
  591. if ($result > 0) {
  592. // Delete OK
  593. setEventMessages("RecordDeleted", null, 'mesgs');
  594. if (empty ($noback)) {
  595. header("Location: " . $backurlforlist);
  596. exit;
  597. }
  598. } else {
  599. $error++;
  600. if (!empty ($object->errors)) {
  601. setEventMessages(null, $object->errors, 'errors');
  602. } else {
  603. setEventMessages($object->error, null, 'errors');
  604. }
  605. }
  606. $action = '';
  607. }
  608. // Remove a line
  609. if ($action == 'confirm_deleteline' && $confirm == 'yes' && !empty ($permissiontoadd)) {
  610. if (method_exists($object, 'deleteline')) {
  611. $result = $object->deleteline($user, $lineid); // For backward compatibility
  612. } else {
  613. $result = $object->deleteLine($user, $lineid);
  614. }
  615. if ($result > 0) {
  616. // Define output language
  617. $outputlangs = $langs;
  618. $newlang = '';
  619. if ($conf->global->MAIN_MULTILANGS && empty ($newlang) && GETPOST('lang_id', 'aZ09')) {
  620. $newlang = GETPOST('lang_id', 'aZ09');
  621. }
  622. if ($conf->global->MAIN_MULTILANGS && empty ($newlang) && is_object($object->thirdparty)) {
  623. $newlang = $object->thirdparty->default_lang;
  624. }
  625. if (!empty ($newlang)) {
  626. $outputlangs = new Translate("", $conf);
  627. $outputlangs->setDefaultLang($newlang);
  628. }
  629. if (empty ($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  630. if (method_exists($object, 'generateDocument')) {
  631. $ret = $object->fetch($object->id); // Reload to get new records
  632. $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  633. }
  634. }
  635. setEventMessages($langs->trans('RecordDeleted'), null, 'mesgs');
  636. if (empty ($noback)) {
  637. header('Location: ' . $_SERVER["PHP_SELF"] . '?id=' . $object->id);
  638. exit;
  639. }
  640. } else {
  641. $error++;
  642. setEventMessages($object->error, $object->errors, 'errors');
  643. }
  644. $action = '';
  645. }
  646. // Action validate object
  647. if ($action == 'confirm_validate' && $confirm == 'yes' && $permissiontoadd) {
  648. $result = $object->validate($user);
  649. if ($result >= 0) {
  650. // Define output language
  651. if (empty ($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  652. if (method_exists($object, 'generateDocument')) {
  653. $outputlangs = $langs;
  654. $newlang = '';
  655. if (!empty ($conf->global->MAIN_MULTILANGS) && empty ($newlang) && GETPOST('lang_id', 'aZ09')) {
  656. $newlang = GETPOST('lang_id', 'aZ09');
  657. }
  658. if (!empty ($conf->global->MAIN_MULTILANGS) && empty ($newlang)) {
  659. $newlang = $object->thirdparty->default_lang;
  660. }
  661. if (!empty ($newlang)) {
  662. $outputlangs = new Translate("", $conf);
  663. $outputlangs->setDefaultLang($newlang);
  664. }
  665. $ret = $object->fetch($id); // Reload to get new records
  666. $model = $object->model_pdf;
  667. $retgen = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  668. if ($retgen < 0) {
  669. setEventMessages($object->error, $object->errors, 'warnings');
  670. }
  671. }
  672. }
  673. } else {
  674. $error++;
  675. setEventMessages($object->error, $object->errors, 'errors');
  676. }
  677. $action = '';
  678. }
  679. // Action close object
  680. if ($action == 'confirm_close' && $confirm == 'yes' && $permissiontoadd) {
  681. $result = $object->cancel($user);
  682. if ($result >= 0) {
  683. // Define output language
  684. if (empty ($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  685. if (method_exists($object, 'generateDocument')) {
  686. $outputlangs = $langs;
  687. $newlang = '';
  688. if ($conf->global->MAIN_MULTILANGS && empty ($newlang) && GETPOST('lang_id', 'aZ09')) {
  689. $newlang = GETPOST('lang_id', 'aZ09');
  690. }
  691. if ($conf->global->MAIN_MULTILANGS && empty ($newlang)) {
  692. $newlang = $object->thirdparty->default_lang;
  693. }
  694. if (!empty ($newlang)) {
  695. $outputlangs = new Translate("", $conf);
  696. $outputlangs->setDefaultLang($newlang);
  697. }
  698. $model = $object->model_pdf;
  699. $ret = $object->fetch($id); // Reload to get new records
  700. $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  701. }
  702. }
  703. } else {
  704. $error++;
  705. setEventMessages($object->error, $object->errors, 'errors');
  706. }
  707. $action = '';
  708. }
  709. // Action setdraft object
  710. if ($action == 'confirm_setdraft' && $confirm == 'yes' && $permissiontoadd) {
  711. $result = $object->setDraft($user);
  712. if ($result >= 0) {
  713. // Nothing else done
  714. } else {
  715. $error++;
  716. setEventMessages($object->error, $object->errors, 'errors');
  717. }
  718. $action = '';
  719. }
  720. // Action reopen object
  721. if ($action == 'confirm_reopen' && $confirm == 'yes' && $permissiontoadd) {
  722. $result = $object->reopen($user);
  723. if ($result >= 0) {
  724. // Define output language
  725. if (empty ($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  726. if (method_exists($object, 'generateDocument')) {
  727. $outputlangs = $langs;
  728. $newlang = '';
  729. if ($conf->global->MAIN_MULTILANGS && empty ($newlang) && GETPOST('lang_id', 'aZ09')) {
  730. $newlang = GETPOST('lang_id', 'aZ09');
  731. }
  732. if ($conf->global->MAIN_MULTILANGS && empty ($newlang)) {
  733. $newlang = $object->thirdparty->default_lang;
  734. }
  735. if (!empty ($newlang)) {
  736. $outputlangs = new Translate("", $conf);
  737. $outputlangs->setDefaultLang($newlang);
  738. }
  739. $model = $object->model_pdf;
  740. $ret = $object->fetch($id); // Reload to get new records
  741. $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  742. }
  743. }
  744. } else {
  745. $error++;
  746. setEventMessages($object->error, $object->errors, 'errors');
  747. }
  748. $action = '';
  749. }
  750. // Action clone object
  751. if ($action == 'confirm_clone' && $confirm == 'yes' && !empty ($permissiontoadd)) {
  752. if (1 == 0 && !GETPOST('clone_content') && !GETPOST('clone_receivers')) {
  753. setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors');
  754. } else {
  755. $objectutil = dol_clone($object, 1); // To avoid to denaturate loaded object when setting some properties for clone or if createFromClone modifies the object. We use native clone to keep this->db valid.
  756. //$objectutil->date = dol_mktime(12, 0, 0, GETPOST('newdatemonth', 'int'), GETPOST('newdateday', 'int'), GETPOST('newdateyear', 'int'));
  757. // ...
  758. $result = $objectutil->createFromClone($user, (($object->id > 0) ? $object->id : $id));
  759. if (is_object($result) || $result > 0) {
  760. $newid = 0;
  761. if (is_object($result)) {
  762. $newid = $result->id;
  763. } else {
  764. $newid = $result;
  765. }
  766. if (empty ($noback)) {
  767. header("Location: " . $_SERVER['PHP_SELF'] . '?id=' . $newid); // Open record of new object
  768. exit;
  769. }
  770. } else {
  771. $error++;
  772. setEventMessages($objectutil->error, $objectutil->errors, 'errors');
  773. $action = '';
  774. }
  775. }
  776. }