actions_addupdatedelete.inc.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882
  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. $invocesRowidString = '';
  166. $from = $value['from'];
  167. $to = $value['to'];
  168. $exception = $helper->getAllComissionInvoicesOfUserInTheGroupFromUserInvoiceCreated($allUsersString, $queryArray[0]['from'], $queryArray[count($queryArray) - 1]['to']);
  169. $invocesRowidString = $helper->getInvoicesRowidFromFactureInAnIntervalByEveryUser($allUsersString, $from, $to, $exception);
  170. if($invocesRowidString != ''){
  171. $invocesRowidString .= ",";
  172. }
  173. $allFactures = $helper->getInvoicesRowidFromFactureInAnIntervalByEveryUserWithoutInvoicePrinting($allUsersString, $from, $to, $exception);
  174. $invocesRowidString .= $helper->getCrossShoppingInvoicesRowidFromFacture($allFactures, $from, $to);
  175. $usrCount = 0;
  176. $index = 0;
  177. $usersArrayFilteredUsers = [];
  178. $usersArrayFilteredUsersFrom = [];
  179. foreach ($usersDateArrayTMP as $usrDate) {
  180. foreach ($usrDate as $key => $value1) {
  181. if ($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. } elseif ($value1[0] < $from && $value1[1] == $to) {
  188. $usrCount++;
  189. $validatorArray[$key]['valid'] = true;
  190. } elseif ($value1[0] == $from && $value1[1] == $to) {
  191. $usrCount++;
  192. $validatorArray[$key]['valid'] = true;
  193. } else {
  194. $validatorArray[$key]['valid'] = false;
  195. }
  196. if ($validatorArray[$key]['valid']) {
  197. $usersArrayFilteredUsers[] = $key;
  198. }
  199. $usersArrayFilteredUsersFrom[$key] = $value1[0];
  200. }
  201. }
  202. $usersString = implode(',', $usersArrayFilteredUsers);
  203. if ($usersString != '') {
  204. $invocesRowidString = $helper->getInvoicesRowidFromFactureInAnIntervalByEveryUser($usersString, $from, $to, $exception);
  205. $allFactures = $helper->getInvoicesRowidFromFactureInAnIntervalByEveryUserWithoutInvoicePrinting($allUsersString, $from, $to, $exception);
  206. $crossShoppingString = $helper->getCrossShoppingInvoicesRowidFromFacture($allFactures, $from, $to);
  207. if($invocesRowidString != '' && $crossShoppingString != ''){
  208. $invocesRowidString .= ",";
  209. }
  210. $invocesRowidString .= $crossShoppingString;
  211. $allComissionInvoicesOfUserInTheGroupFromUserInvoice = '';
  212. $commissionHUF = $commmissionhandler->getAllCommission($usersString, 'HUF', $from, $to, $exception);
  213. $commissionEUR = $commmissionhandler->getAllCommission($usersString, 'EUR', $from, $to, $exception);
  214. $osszeg = $commissionHUF + $commissionEUR;
  215. if ($usrCount > 0) {
  216. $amount = $osszeg / $usrCount;
  217. }
  218. }
  219. foreach ($usersArrayFilteredUsers as $filteredUser) {
  220. $usersAmountArray[$filteredUser]['amount'] += $amount;
  221. if ($invocesRowidString != '') {
  222. if ($usersAmountArray[$filteredUser]['invoices'] != '') {
  223. $usersAmountArray[$filteredUser]['invoices'] .= ',';
  224. }
  225. $usersAmountArray[$filteredUser]['invoices'] .= $invocesRowidString;
  226. $usersAmountArray[$filteredUser]['namedata'] .= $helper->getNamedataFoTheUser($filteredUser);
  227. }
  228. }
  229. }
  230. $summaHUF = saveUserInvoiceRecordAndSetSummaHUF($commissionhandler, $usersAmountArray, $helper, $usersArrayFilteredUsersFrom, $isMinCommissionActice);
  231. $dataArray = array(
  232. 'GroupName' => $helper->getGroupLabelById($id),
  233. 'UsersData' => $usersAmountArray,
  234. 'FullAmount' => $summaHUF,
  235. 'Interval' => $helper->getFirstDateFromUserNaplo($id) . ' - ' . date('Y-m-d H:i:s'),
  236. );
  237. insertCommissionSettlementObj($dataArray, $groupEntity, $summaHUF, $helper);
  238. $urltogo = getUrltogo($hotelgroup, $id);
  239. header("Location: " . $urltogo);
  240. exit;
  241. }
  242. function saveUserInvoiceRecordAndSetSummaHUF($commissionhandler, $usersAmountArray, $helper, $usersArrayFilteredUsersFrom, $isMinCommissionActice = false)
  243. {
  244. $generalDailyCommission = $commissionhandler->getDailyMinimumCommission();
  245. foreach ($usersAmountArray as $useKey => $userInvoiceRecord) {
  246. $uniformHUF = (int) $userInvoiceRecord['amount'];
  247. if ($uniformHUF != 0) {
  248. if ($isMinCommissionActice) {
  249. if ($generalDailyCommission > $uniformHUF) {
  250. $uniformHUF = $generalDailyCommission;
  251. }
  252. }
  253. $uniformInvoices = $userInvoiceRecord['invoices'];
  254. $helper->saveUserInvoiceRecord($usersArrayFilteredUsersFrom, $useKey, $uniformHUF, $uniformInvoices);
  255. $summaHUF += $uniformHUF;
  256. }
  257. }
  258. return $summaHUF;
  259. }
  260. function getUrltogo($hotelgroup, $id)
  261. {
  262. if ($hotelgroup) {
  263. return '/custom/financialreport/settlementsstatementshotelsindex.php?id=' . $id;
  264. //} elseif (date("Y-m-d", dol_now()) != $exceptionFrom) {
  265. // $urltogo = '/custom/financialreport/settlementsdaterangeindex.php?id=' . $id . '&datepicker=' . $exceptionFrom . ' - ' . $exceptionTo;
  266. } else {
  267. return '/custom/financialreport/settlementsstatementsindex.php?id=' . $id;
  268. }
  269. }
  270. function insertCommissionSettlementObj($dataArray, $groupEntity, $summaHUF, $helper)
  271. {
  272. global $db, $user;
  273. $html = $helper->createHTMLForSettlement($dataArray);
  274. $pdf = new SettlementsPDFPrint($html);
  275. $CommissionPDF = $pdf->generateCommissionSettlementsPDF();
  276. $commissionSettlementsObj = new Commissionsettlements($db);
  277. $jsonData = json_encode($dataArray, JSON_PRETTY_PRINT);
  278. //exit;
  279. $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)";
  280. $result = $db->query($sql);
  281. }
  282. function datumOsszehasonlitas($a, $b)
  283. {
  284. $idopontA = strtotime($a);
  285. $idopontB = strtotime($b);
  286. if ($idopontA == $idopontB) {
  287. return 0;
  288. }
  289. return ($idopontA < $idopontB) ? -1 : 1;
  290. }
  291. if ($action == 'confirm_makeupto') {
  292. $tempDataArray = explode('|', $datastring);
  293. $makeUpToDataArray = ['user_id' => $tempDataArray[0], 'amount' => intval($tempDataArray[1]), 'year' => $tempDataArray[2], 'month' => $tempDataArray[3]];
  294. $date = $makeUpToDataArray['year'] . '-' . $makeUpToDataArray['month'] . '-' . date("t", strtotime("$year-$month-01"));
  295. $userinvoice = new UserInvoice($db);
  296. $userinvoice->ref = $helper->generateRef(2);
  297. $userinvoice->label = 'Jutalék/Commission ' . $date;
  298. $userinvoice->date_creation = $date;
  299. $userinvoice->description = 'Összeg / Amount: ' . $helper->correctNumber($makeUpToDataArray['amount']) . ' HUF. Make up to on: ' . $date;
  300. $userinvoice->user_id = $makeUpToDataArray['user_id'];
  301. $userinvoice->payment_type = 2;
  302. $userinvoice->amount = $makeUpToDataArray['amount'];
  303. $userinvoice->currency = 'HUF';
  304. $userinvoice->individual = 1;
  305. $userinvoice->create($user);
  306. setEventMessage($langs->trans('CommissionSaved'));
  307. $urltogo = '/custom/financialreport/commissionsummaryindex.php?idmenu=1628&year=' . $makeUpToDataArray['year'] . '&month=' . $makeUpToDataArray['month'] . '&mainmenu=financialreport&leftmenu=';
  308. header("Location: " . $urltogo);
  309. exit;
  310. }
  311. if ($action == 'confirm_personal_settlement') {
  312. $isMinCommissionActice = false;
  313. $commissionhandler = new CommissionHandler();
  314. $commissionArray = [];
  315. $result = explode('_', $commissions);
  316. $user_id = $result[0];
  317. $from = $result[1];
  318. $logoutDate = $helper->checklogoutRecordInUserNaplo($user_id, $from, $id);
  319. $to = $logoutDate != '' ? $logoutDate : date('Y-m-d H:i:s', dol_now());
  320. $totalCommission = $commmissionhandler->getTotalCommission($user_id, $from, $to);
  321. $result[2] = $totalCommission;
  322. $commissionArray['HUF'] = $result[2];
  323. if ($commissionArray['HUF'] > 0) {
  324. $invocesRowidString = '';
  325. $allFactures = $helper->getAllFacturesOfThisUser($user_id, $from, $to);
  326. $invocesRowidString = $helper->getInvoicesRowidFromFacture($user_id, $from, $to);
  327. $crossShoppingString = $helper->getCrossShoppingInvoicesRowidFromFacture($allFactures, $from, $to);
  328. if($invocesRowidString != '' && $crossShoppingString != ''){
  329. $invocesRowidString .= ",";
  330. }
  331. $invocesRowidString .= $crossShoppingString;
  332. }
  333. $exceptionFrom = $exceptionTo = date("Y-m-d", strtotime($from));
  334. foreach ($commissionArray as $key => $amount) {
  335. if ($amount > 0) {
  336. if ($isMinCommissionActice) {
  337. $generalDailyCommission = $commissionhandler->getDailyMinimumCommission();
  338. if ($generalDailyCommission > $amount) {
  339. $amount = $generalDailyCommission;
  340. }
  341. }
  342. $userinvoice = new UserInvoice($db);
  343. $currency = $key == 'HUF' ? 0 : 1;
  344. $userinvoice->ref = $helper->generateRef(2);
  345. $userinvoice->label = 'Jutalék/Commission ' . date("Y-m-d", strtotime($from));
  346. $userinvoice->description = 'Összeg / Amount: ' . $amount . ' ' . $key;
  347. $userinvoice->user_id = $user_id;
  348. $userinvoice->payment_type = 2;
  349. $userinvoice->amount = $amount;
  350. $userinvoice->currency = $currency;
  351. $userinvoice->individual = 1;
  352. $userinvoice->invoices = $invocesRowidString;
  353. $userinvoice->date_creation = strtotime($from);
  354. $userinvoice->create($user);
  355. }
  356. }
  357. //if (date("Y-m-d", dol_now()) != $exceptionFrom) {
  358. // $urltogo = '/custom/financialreport/settlementsdaterangeindex.php?id=' . $id . '&datepicker=' . $exceptionFrom . ' - ' . $exceptionTo;
  359. //} else {
  360. $urltogo = '/custom/financialreport/settlementsstatementsindex.php?id=' . $id;
  361. //}
  362. header("Location: " . $urltogo);
  363. exit;
  364. }
  365. // Action to add record
  366. if ($action == 'add' && !empty ($permissiontoadd)) {
  367. foreach ($object->fields as $key => $val) {
  368. if ($object->fields[$key]['type'] == 'duration') {
  369. if (GETPOST($key . 'hour') == '' && GETPOST($key . 'min') == '') {
  370. continue; // The field was not submited to be saved
  371. }
  372. } else {
  373. if (!GETPOSTISSET($key)) {
  374. continue; // The field was not submited to be saved
  375. }
  376. }
  377. // Ignore special fields
  378. if (in_array($key, array('rowid', 'entity', 'import_key'))) {
  379. continue;
  380. }
  381. if (in_array($key, array('date_creation', 'tms', 'fk_user_creat', 'fk_user_modif'))) {
  382. if (!in_array(abs($val['visible']), array(1, 3))) {
  383. continue; // Only 1 and 3 that are case to create
  384. }
  385. }
  386. // Set value to insert
  387. if (in_array($object->fields[$key]['type'], array('text', 'html'))) {
  388. $value = GETPOST($key, 'restricthtml');
  389. } elseif ($object->fields[$key]['type'] == 'date') {
  390. $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
  391. } elseif ($object->fields[$key]['type'] == 'datetime') {
  392. $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');
  393. } elseif ($object->fields[$key]['type'] == 'duration') {
  394. $value = 60 * 60 * GETPOST($key . 'hour', 'int') + 60 * GETPOST($key . 'min', 'int');
  395. } elseif (preg_match('/^(integer|price|real|double)/', $object->fields[$key]['type'])) {
  396. $value = price2num(GETPOST($key, 'alphanohtml')); // To fix decimal separator according to lang setup
  397. } elseif ($object->fields[$key]['type'] == 'boolean') {
  398. $value = ((GETPOST($key) == '1' || GETPOST($key) == 'on') ? 1 : 0);
  399. } elseif ($object->fields[$key]['type'] == 'reference') {
  400. $tmparraykey = array_keys($object->param_list);
  401. $value = $tmparraykey[GETPOST($key)] . ',' . GETPOST($key . '2');
  402. } else {
  403. if ($key == 'lang') {
  404. $value = GETPOST($key, 'aZ09') ? GETPOST($key, 'aZ09') : "";
  405. } else {
  406. $value = GETPOST($key, 'alphanohtml');
  407. }
  408. }
  409. if (preg_match('/^integer:/i', $object->fields[$key]['type']) && $value == '-1') {
  410. $value = ''; // This is an implicit foreign key field
  411. }
  412. if (!empty ($object->fields[$key]['foreignkey']) && $value == '-1') {
  413. $value = ''; // This is an explicit foreign key field
  414. }
  415. //var_dump($key.' '.$value.' '.$object->fields[$key]['type']);
  416. $object->$key = $value;
  417. if (!empty ($val['notnull']) && $val['notnull'] > 0 && $object->$key == '' && isset ($val['default']) && $val['default'] == '(PROV)') {
  418. $object->$key = '(PROV)';
  419. }
  420. if (!empty ($val['notnull']) && $val['notnull'] > 0 && $object->$key == '' && !isset ($val['default'])) {
  421. $error++;
  422. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv($val['label'])), null, 'errors');
  423. }
  424. // Validation of fields values
  425. if (getDolGlobalInt('MAIN_FEATURES_LEVEL') >= 2 || !empty ($conf->global->MAIN_ACTIVATE_VALIDATION_RESULT)) {
  426. if (!$error && !empty ($val['validate']) && is_callable(array($object, 'validateField'))) {
  427. if (!$object->validateField($object->fields, $key, $value)) {
  428. $error++;
  429. }
  430. }
  431. }
  432. }
  433. // Fill array 'array_options' with data from add form
  434. if (!$error) {
  435. $ret = $extrafields->setOptionalsFromPost(null, $object, '', 1);
  436. if ($ret < 0) {
  437. $error++;
  438. }
  439. }
  440. if (!$error) {
  441. $result = $object->create($user);
  442. if ($result > 0) {
  443. // Creation OK
  444. if (isModEnabled('categorie') && method_exists($object, 'setCategories')) {
  445. $categories = GETPOST('categories', 'array:int');
  446. $object->setCategories($categories);
  447. }
  448. $backtopage .= '?id=' . $object->id . '&user_id=' . $user_id . '&payment_type=' . $payment_type . '&idmenu=' . $idmenu . '&save_lastsearch_values=1';
  449. $urltogo = $backtopage ? str_replace('__ID__', $result, $backtopage) : $backurlforlist;
  450. $urltogo = preg_replace('/--IDFORBACKTOPAGE--/', $object->id, $urltogo); // New method to autoselect project after a New on another form object creation
  451. if (empty ($noback)) {
  452. header("Location: " . $urltogo);
  453. exit;
  454. }
  455. } else {
  456. $error++;
  457. // Creation KO
  458. if (!empty ($object->errors)) {
  459. setEventMessages(null, $object->errors, 'errors');
  460. } else {
  461. setEventMessages($object->error, null, 'errors');
  462. }
  463. $action = 'create';
  464. }
  465. } else {
  466. $action = 'create';
  467. }
  468. }
  469. // Action to update record
  470. if ($action == 'update' && !empty ($permissiontoadd)) {
  471. $backtopage .= '?id=' . $id . '&user_id=' . $user_id . '&payment_type=' . $payment_type . '&idmenu=' . $idmenu . '&save_lastsearch_values=1';
  472. foreach ($object->fields as $key => $val) {
  473. // Check if field was submited to be edited
  474. if ($object->fields[$key]['type'] == 'duration') {
  475. if (!GETPOSTISSET($key . 'hour') || !GETPOSTISSET($key . 'min')) {
  476. continue; // The field was not submited to be saved
  477. }
  478. } elseif ($object->fields[$key]['type'] == 'boolean') {
  479. if (!GETPOSTISSET($key)) {
  480. $object->$key = 0; // use 0 instead null if the field is defined as not null
  481. continue;
  482. }
  483. } else {
  484. if (!GETPOSTISSET($key)) {
  485. continue; // The field was not submited to be saved
  486. }
  487. }
  488. // Ignore special fields
  489. if (in_array($key, array('rowid', 'entity', 'import_key'))) {
  490. continue;
  491. }
  492. if (in_array($key, array('date_creation', 'tms', 'fk_user_creat', 'fk_user_modif'))) {
  493. if (!in_array(abs($val['visible']), array(1, 3, 4))) {
  494. continue; // Only 1 and 3 and 4, that are cases to update
  495. }
  496. }
  497. // Set value to update
  498. if (preg_match('/^(text|html)/', $object->fields[$key]['type'])) {
  499. $tmparray = explode(':', $object->fields[$key]['type']);
  500. if (!empty ($tmparray[1])) {
  501. $value = GETPOST($key, $tmparray[1]);
  502. } else {
  503. $value = GETPOST($key, 'restricthtml');
  504. }
  505. } elseif ($object->fields[$key]['type'] == 'date') {
  506. $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
  507. } elseif ($object->fields[$key]['type'] == 'datetime') {
  508. $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');
  509. } elseif ($object->fields[$key]['type'] == 'duration') {
  510. if (GETPOST($key . 'hour', 'int') != '' || GETPOST($key . 'min', 'int') != '') {
  511. $value = 60 * 60 * GETPOST($key . 'hour', 'int') + 60 * GETPOST($key . 'min', 'int');
  512. } else {
  513. $value = '';
  514. }
  515. } elseif (preg_match('/^(integer|price|real|double)/', $object->fields[$key]['type'])) {
  516. $value = price2num(GETPOST($key, 'alphanohtml')); // To fix decimal separator according to lang setup
  517. } elseif ($object->fields[$key]['type'] == 'boolean') {
  518. $value = ((GETPOST($key, 'aZ09') == 'on' || GETPOST($key, 'aZ09') == '1') ? 1 : 0);
  519. } elseif ($object->fields[$key]['type'] == 'reference') {
  520. $value = array_keys($object->param_list)[GETPOST($key)] . ',' . GETPOST($key . '2');
  521. } else {
  522. if ($key == 'lang') {
  523. $value = GETPOST($key, 'aZ09');
  524. } else {
  525. $value = GETPOST($key, 'alphanohtml');
  526. }
  527. }
  528. if (preg_match('/^integer:/i', $object->fields[$key]['type']) && $value == '-1') {
  529. $value = ''; // This is an implicit foreign key field
  530. }
  531. if (!empty ($object->fields[$key]['foreignkey']) && $value == '-1') {
  532. $value = ''; // This is an explicit foreign key field
  533. }
  534. $object->$key = $value;
  535. if ($val['notnull'] > 0 && $object->$key == '' && is_null($val['default'])) {
  536. $error++;
  537. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv($val['label'])), null, 'errors');
  538. }
  539. // Validation of fields values
  540. if (getDolGlobalInt('MAIN_FEATURES_LEVEL') >= 2 || !empty ($conf->global->MAIN_ACTIVATE_VALIDATION_RESULT)) {
  541. if (!$error && !empty ($val['validate']) && is_callable(array($object, 'validateField'))) {
  542. if (!$object->validateField($object->fields, $key, $value)) {
  543. $error++;
  544. }
  545. }
  546. }
  547. if (isModEnabled('categorie')) {
  548. $categories = GETPOST('categories', 'array');
  549. if (method_exists($object, 'setCategories')) {
  550. $object->setCategories($categories);
  551. }
  552. }
  553. }
  554. // Fill array 'array_options' with data from add form
  555. if (!$error) {
  556. $ret = $extrafields->setOptionalsFromPost(null, $object, '@GETPOSTISSET');
  557. if ($ret < 0) {
  558. $error++;
  559. }
  560. }
  561. if (!$error) {
  562. $result = $object->update($user);
  563. if ($result > 0) {
  564. $action = 'view';
  565. $urltogo = $backtopage ? str_replace('__ID__', $result, $backtopage) : $backurlforlist;
  566. $urltogo = preg_replace('/--IDFORBACKTOPAGE--/', $object->id, $urltogo); // New method to autoselect project after a New on another form object creation
  567. if ($urltogo && !$noback) {
  568. header("Location: " . $urltogo);
  569. exit;
  570. }
  571. } else {
  572. $error++;
  573. // Creation KO
  574. setEventMessages($object->error, $object->errors, 'errors');
  575. $action = 'edit';
  576. }
  577. } else {
  578. $action = 'edit';
  579. }
  580. }
  581. // Action to update one extrafield
  582. if ($action == "update_extras" && !empty ($permissiontoadd)) {
  583. $object->fetch(GETPOST('id', 'int'));
  584. $attributekey = GETPOST('attribute', 'alpha');
  585. $attributekeylong = 'options_' . $attributekey;
  586. if (GETPOSTISSET($attributekeylong . 'day') && GETPOSTISSET($attributekeylong . 'month') && GETPOSTISSET($attributekeylong . 'year')) {
  587. // This is properties of a date
  588. $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'));
  589. //var_dump(dol_print_date($object->array_options['options_'.$attributekey]));exit;
  590. } else {
  591. $object->array_options['options_' . $attributekey] = GETPOST($attributekeylong, 'alpha');
  592. }
  593. $result = $object->insertExtraFields(empty ($triggermodname) ? '' : $triggermodname, $user);
  594. if ($result > 0) {
  595. setEventMessages($langs->trans('RecordSaved'), null, 'mesgs');
  596. $action = 'view';
  597. } else {
  598. $error++;
  599. setEventMessages($object->error, $object->errors, 'errors');
  600. $action = 'edit_extras';
  601. }
  602. }
  603. // Action to delete
  604. if ($action == 'confirm_delete' && !empty ($permissiontodelete)) {
  605. if (!($object->id > 0)) {
  606. dol_print_error('', 'Error, object must be fetched before being deleted');
  607. exit;
  608. }
  609. $result = $object->delete($user);
  610. if ($result > 0) {
  611. // Delete OK
  612. setEventMessages("RecordDeleted", null, 'mesgs');
  613. if (empty ($noback)) {
  614. header("Location: " . $backurlforlist);
  615. exit;
  616. }
  617. } else {
  618. $error++;
  619. if (!empty ($object->errors)) {
  620. setEventMessages(null, $object->errors, 'errors');
  621. } else {
  622. setEventMessages($object->error, null, 'errors');
  623. }
  624. }
  625. $action = '';
  626. }
  627. // Remove a line
  628. if ($action == 'confirm_deleteline' && $confirm == 'yes' && !empty ($permissiontoadd)) {
  629. if (method_exists($object, 'deleteline')) {
  630. $result = $object->deleteline($user, $lineid); // For backward compatibility
  631. } else {
  632. $result = $object->deleteLine($user, $lineid);
  633. }
  634. if ($result > 0) {
  635. // Define output language
  636. $outputlangs = $langs;
  637. $newlang = '';
  638. if ($conf->global->MAIN_MULTILANGS && empty ($newlang) && GETPOST('lang_id', 'aZ09')) {
  639. $newlang = GETPOST('lang_id', 'aZ09');
  640. }
  641. if ($conf->global->MAIN_MULTILANGS && empty ($newlang) && is_object($object->thirdparty)) {
  642. $newlang = $object->thirdparty->default_lang;
  643. }
  644. if (!empty ($newlang)) {
  645. $outputlangs = new Translate("", $conf);
  646. $outputlangs->setDefaultLang($newlang);
  647. }
  648. if (empty ($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  649. if (method_exists($object, 'generateDocument')) {
  650. $ret = $object->fetch($object->id); // Reload to get new records
  651. $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  652. }
  653. }
  654. setEventMessages($langs->trans('RecordDeleted'), null, 'mesgs');
  655. if (empty ($noback)) {
  656. header('Location: ' . $_SERVER["PHP_SELF"] . '?id=' . $object->id);
  657. exit;
  658. }
  659. } else {
  660. $error++;
  661. setEventMessages($object->error, $object->errors, 'errors');
  662. }
  663. $action = '';
  664. }
  665. // Action validate object
  666. if ($action == 'confirm_validate' && $confirm == 'yes' && $permissiontoadd) {
  667. $result = $object->validate($user);
  668. if ($result >= 0) {
  669. // Define output language
  670. if (empty ($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  671. if (method_exists($object, 'generateDocument')) {
  672. $outputlangs = $langs;
  673. $newlang = '';
  674. if (!empty ($conf->global->MAIN_MULTILANGS) && empty ($newlang) && GETPOST('lang_id', 'aZ09')) {
  675. $newlang = GETPOST('lang_id', 'aZ09');
  676. }
  677. if (!empty ($conf->global->MAIN_MULTILANGS) && empty ($newlang)) {
  678. $newlang = $object->thirdparty->default_lang;
  679. }
  680. if (!empty ($newlang)) {
  681. $outputlangs = new Translate("", $conf);
  682. $outputlangs->setDefaultLang($newlang);
  683. }
  684. $ret = $object->fetch($id); // Reload to get new records
  685. $model = $object->model_pdf;
  686. $retgen = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  687. if ($retgen < 0) {
  688. setEventMessages($object->error, $object->errors, 'warnings');
  689. }
  690. }
  691. }
  692. } else {
  693. $error++;
  694. setEventMessages($object->error, $object->errors, 'errors');
  695. }
  696. $action = '';
  697. }
  698. // Action close object
  699. if ($action == 'confirm_close' && $confirm == 'yes' && $permissiontoadd) {
  700. $result = $object->cancel($user);
  701. if ($result >= 0) {
  702. // Define output language
  703. if (empty ($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  704. if (method_exists($object, 'generateDocument')) {
  705. $outputlangs = $langs;
  706. $newlang = '';
  707. if ($conf->global->MAIN_MULTILANGS && empty ($newlang) && GETPOST('lang_id', 'aZ09')) {
  708. $newlang = GETPOST('lang_id', 'aZ09');
  709. }
  710. if ($conf->global->MAIN_MULTILANGS && empty ($newlang)) {
  711. $newlang = $object->thirdparty->default_lang;
  712. }
  713. if (!empty ($newlang)) {
  714. $outputlangs = new Translate("", $conf);
  715. $outputlangs->setDefaultLang($newlang);
  716. }
  717. $model = $object->model_pdf;
  718. $ret = $object->fetch($id); // Reload to get new records
  719. $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  720. }
  721. }
  722. } else {
  723. $error++;
  724. setEventMessages($object->error, $object->errors, 'errors');
  725. }
  726. $action = '';
  727. }
  728. // Action setdraft object
  729. if ($action == 'confirm_setdraft' && $confirm == 'yes' && $permissiontoadd) {
  730. $result = $object->setDraft($user);
  731. if ($result >= 0) {
  732. // Nothing else done
  733. } else {
  734. $error++;
  735. setEventMessages($object->error, $object->errors, 'errors');
  736. }
  737. $action = '';
  738. }
  739. // Action reopen object
  740. if ($action == 'confirm_reopen' && $confirm == 'yes' && $permissiontoadd) {
  741. $result = $object->reopen($user);
  742. if ($result >= 0) {
  743. // Define output language
  744. if (empty ($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  745. if (method_exists($object, 'generateDocument')) {
  746. $outputlangs = $langs;
  747. $newlang = '';
  748. if ($conf->global->MAIN_MULTILANGS && empty ($newlang) && GETPOST('lang_id', 'aZ09')) {
  749. $newlang = GETPOST('lang_id', 'aZ09');
  750. }
  751. if ($conf->global->MAIN_MULTILANGS && empty ($newlang)) {
  752. $newlang = $object->thirdparty->default_lang;
  753. }
  754. if (!empty ($newlang)) {
  755. $outputlangs = new Translate("", $conf);
  756. $outputlangs->setDefaultLang($newlang);
  757. }
  758. $model = $object->model_pdf;
  759. $ret = $object->fetch($id); // Reload to get new records
  760. $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  761. }
  762. }
  763. } else {
  764. $error++;
  765. setEventMessages($object->error, $object->errors, 'errors');
  766. }
  767. $action = '';
  768. }
  769. // Action clone object
  770. if ($action == 'confirm_clone' && $confirm == 'yes' && !empty ($permissiontoadd)) {
  771. if (1 == 0 && !GETPOST('clone_content') && !GETPOST('clone_receivers')) {
  772. setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors');
  773. } else {
  774. $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.
  775. //$objectutil->date = dol_mktime(12, 0, 0, GETPOST('newdatemonth', 'int'), GETPOST('newdateday', 'int'), GETPOST('newdateyear', 'int'));
  776. // ...
  777. $result = $objectutil->createFromClone($user, (($object->id > 0) ? $object->id : $id));
  778. if (is_object($result) || $result > 0) {
  779. $newid = 0;
  780. if (is_object($result)) {
  781. $newid = $result->id;
  782. } else {
  783. $newid = $result;
  784. }
  785. if (empty ($noback)) {
  786. header("Location: " . $_SERVER['PHP_SELF'] . '?id=' . $newid); // Open record of new object
  787. exit;
  788. }
  789. } else {
  790. $error++;
  791. setEventMessages($objectutil->error, $objectutil->errors, 'errors');
  792. $action = '';
  793. }
  794. }
  795. }