PageRenderTime 67ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/magehelp/application/controllers/procurement.php

https://bitbucket.org/jit_bec/shopifine
PHP | 2916 lines | 2106 code | 420 blank | 390 comment | 350 complexity | 307cea1c9ee6777683149faca5454931 MD5 | raw file
Possible License(s): LGPL-3.0
  1. <?php
  2. require_once ("secure_area.php");
  3. class Procurement extends Secure_area
  4. {
  5. private $user;
  6. private $username;
  7. function __construct()
  8. {
  9. parent::__construct('procurement');
  10. $this->user= $this->User->get_logged_in_employee_info();
  11. $this->username = $this->user->last_name." ".$this->user->first_name;
  12. $param = array('user' => $this->user->username);
  13. $this->load->library('acl-library/Acl',$param,'Acl');
  14. }
  15. //moved to parent class
  16. // function assignEntityToUser(){
  17. // $ids = $_REQUEST['ids'];
  18. // $entity = $_REQUEST['entity'];
  19. // $role = $_REQUEST['role'];
  20. // $user_id = $_REQUEST['user_id'];
  21. // if ($entity=='rfq'){
  22. // $model = 'Request_quote_master';
  23. // }
  24. // else if ($entity=='quote'){
  25. // $model = 'Purchase_quote_master';
  26. // }
  27. // else if ($entity=='order'){
  28. // $model = 'Purchase_order_master';
  29. // }
  30. // else if ($entity=='receipt_item'){
  31. // $model = 'Receipt_item';
  32. // }
  33. // else if ($entity=='receipt'){
  34. // $model = 'Receipt_master';
  35. // }
  36. // else if ($entity=='invoice'){
  37. // $model = 'Purchase_invoice_master';
  38. // }
  39. // if (!empty($ids) && !empty($role) ){
  40. // if (empty($user_id)){
  41. // $user_id = $this->user->person_id;
  42. // }
  43. // if ($role =='approver'){
  44. // $upd_data['approved_by'] = $user_id;
  45. // }
  46. // else if ($role =='receiver'){
  47. // $upd_data['received_by'] = $user_id;
  48. // $upd_data['owner_id'] = $user_id;
  49. // }
  50. // else if ($role =='payer'){
  51. // $upd_data['payer_id'] = $user_id;
  52. // $upd_data['owner_id'] = $user_id;
  53. // }
  54. // else if ($role =='owner'){
  55. // $upd_data['owner_id'] = $user_id;
  56. // }
  57. // foreach($ids as $id){
  58. //
  59. // $this->$model->update(array('id'=>$id),$upd_data);
  60. // }
  61. // }
  62. // }
  63. // function prepareAssignDialog(){
  64. //// var_dump(($this->User->getAllEligibleOwners('rfq')));
  65. //// var_dump(($this->User->getAllEligibleApprovers('rfq')));
  66. // $entity = $_REQUEST['entity'];
  67. // if ($entity=='order'){
  68. // $owners = $this->User->getAllEligibleReceivers($_REQUEST['entity']);
  69. // }
  70. // else{
  71. // $owners = $this->User->getAllEligibleOwners($_REQUEST['entity']);
  72. // }
  73. //
  74. //
  75. // $approvers = $this->User->getAllEligibleApprovers($_REQUEST['entity']);
  76. // $adminUserOptions =null;
  77. // $userOptions = null;
  78. // foreach($owners as $owner) {
  79. //
  80. // $name=$owner["username"];
  81. // $id=$owner["person_id"];
  82. // if (!empty($name)){
  83. // $userOptions.="<OPTION VALUE=\"$id\">".$name;
  84. // }
  85. // }
  86. // foreach($approvers as $approver) {
  87. //
  88. // $name=$approver["username"];
  89. // $id=$approver["person_id"];
  90. // if (!empty($name)){
  91. // $adminUserOptions.="<OPTION VALUE=\"$id\">".$name;
  92. // }
  93. // }
  94. // $data['userOptions'] = $userOptions;
  95. // $data['adminUserOptions'] = $adminUserOptions;
  96. // echo json_encode($data);
  97. // }
  98. /* PURCHASE QUOTE GRID START */
  99. function index()
  100. {
  101. $users = $this->User->getAllUsersByRole(null,array('field_name'=>'role_name',array('Everyone','Guest')));
  102. foreach($users as $user) {
  103. $user_id=$user["person_id"];
  104. $username=$user["username"];
  105. //$value = $denom["denom_json"];
  106. if (!empty($user_id)){
  107. $userOptions.="<OPTION VALUE=\"$user_id\">".$username;
  108. }
  109. }
  110. $data['userOptions'] = $userOptions;
  111. $this->load->view("procurement/quote/purchase_quote_grid",$data);
  112. }
  113. /* common functions */
  114. function populateSuppliers(){
  115. echo populateSuppliers();
  116. }
  117. function getCostPrice(){
  118. $id = $_REQUEST['productid'];
  119. $productDetails = $this->Product_price->getByProductId($id);
  120. echo $productDetails->cost_price;
  121. }
  122. function getPriceFromPricelist(){
  123. $product_id = $_REQUEST['product_id'];
  124. $pricelist_id = $_REQUEST['pricelist_id'];
  125. $supplier_id = $_REQUEST['supplier_id'];
  126. $results = $this->Supplier_rate_items->getPriceForProduct($product_id,$pricelist_id,$supplier_id);
  127. echo $results[0]['base_price'] ;
  128. }
  129. /* end common */
  130. /*start quote */
  131. function populateRFQ(){
  132. $quotedata=array();
  133. $status = $_REQUEST['_status'];
  134. $where = array();
  135. $in_where = array();
  136. setOwnerStatusCommon($where,$in_where);
  137. $griddata= populateGridCommon('Request_quote_master',$where,null,$in_where);
  138. $dbrows = $griddata['db_data'];
  139. $data = $griddata['grid_metadata'];
  140. foreach ($dbrows as $dp){
  141. if ($status==self::WAITING_FOR_APPROVAL){
  142. /* we dont need actions column in approval grid . So not passing the blank */
  143. array_push($quotedata, array('id'=> $dp['id'],'dprow' => array($dp['reference'],$dp['supplier_name'],$dp['estimated_value'],$dp['owner_id'],$dp['status'],$dp['raised_by_name'],$dp['owner_name'],$dp['needed_by_date'],$dp['approved_by_name'],$dp['supplier_id'],$dp['warehouse_id'],$dp['approved_by'])));
  144. }
  145. //remove
  146. // else if ($status==self::REJECTED){
  147. // /* Add Extra Columns Rejected and Rejected Notes Remove Status */
  148. // array_push($quotedata, array('id'=> $dp['id'],'dprow' => array($dp['reference'],$dp['supplier_name'],$dp['estimated_value'],$dp['raised_by_name'],$dp['owner_name'],$dp['needed_by_date'],$dp['approved_by_name'],$dp['approval_notes'])));
  149. // }
  150. // //remove
  151. // else if ($status==self::OPEN){
  152. // array_push($quotedata, array('id'=> $dp['id'],'dprow' => array('',$dp['reference'],$dp['supplier_name'],$dp['estimated_value'],$dp['status'],$dp['raised_by_name'],$dp['owner_name'],$dp['needed_by_date'])));
  153. // }
  154. else if (is_array($status)){
  155. array_push($quotedata, array('id'=> $dp['id'],'dprow' => array($dp['reference'],$dp['supplier_name'],$dp['estimated_value'],$dp['owner_id'],$dp['status'],$dp['raised_by_name'],$dp['owner_name'],$dp['needed_by_date'],$dp['approved_by_name'],$dp['supplier_id'],$dp['warehouse_id'])));
  156. }
  157. else {
  158. array_push($quotedata, array('id'=> $dp['id'],'dprow' => array($dp['reference'],$dp['supplier_name'],$dp['estimated_value'],$dp['status'],$dp['raised_by_name'],$dp['owner_name'],$dp['needed_by_date'],$dp['notes'],$dp['approved_by_name'],$dp['approval_notes'])));
  159. }
  160. }
  161. $data['quotedata'] = $quotedata;
  162. echo json_encode($data);
  163. }
  164. function createRFQ(){
  165. $id = $_REQUEST['quoteId'];
  166. $purchase_quote_data['supplier_id'] = $_REQUEST['supplierId'];
  167. $purchase_quote_data['warehouse_id'] = $_REQUEST['warehouseId'];
  168. $dateObj = DateTime::createFromFormat('d/m/Y', $_REQUEST['reqdate']);
  169. log_message('debug','converted '.$dateObj->format('Y-m-d'));
  170. $purchase_quote_data['needed_by_date'] = $dateObj->format('Y-m-d');
  171. $comments = appendComments($_REQUEST['notes'], 'notes');
  172. $purchase_quote_data['owner_id'] = $this->user->person_id;
  173. if (empty($id)){
  174. $purchase_quote_data['raised_by'] = $this->user->person_id;
  175. $id = $this->Request_quote_master->createRequest($purchase_quote_data,array('notes'=>$comments));
  176. }
  177. else {
  178. $where_clause = array('id'=>$id);
  179. $this->Request_quote_master->update($where_clause, $purchase_quote_data,array('notes'=>$comments));
  180. }
  181. echo $id;
  182. }
  183. //this function validates the record after close button of dialog being pressed. If no items are aadded the record is deleted
  184. function closeValidate(){
  185. $id = $_REQUEST['id'];
  186. $entity = $_REQUEST['entity'];
  187. $items_count = $_REQUEST['items_count'];
  188. if ($entity=='quote'){
  189. $model = 'Purchase_quote_master';
  190. $itemModel= 'Purchase_quote_item';
  191. $where_clause_quote_item = array('quote_id'=>$id);
  192. }
  193. else if ($entity=='rfq'){
  194. $model = 'Request_quote_master';
  195. $itemModel= 'Request_quote_item';
  196. $where_clause_quote_item = array('rfq_id'=>$id);
  197. }
  198. if (!empty($id)){
  199. if ($items_count>0){
  200. $where_clause_quote = array('id'=>$id);
  201. $this->$model->update($where_clause_quote,array('status'=>self::OPEN));
  202. $this->$itemModel->update($where_clause_quote_item,array('status'=>self::OPEN));
  203. }
  204. }
  205. }
  206. function modifyRFQ (){
  207. $id = $_REQUEST['id'];
  208. $oper = $_REQUEST['oper'];
  209. $this->db->trans_start();
  210. if ($oper=='edit'){
  211. if (!empty($_REQUEST['needed_date'])){
  212. $dateObj = DateTime::createFromFormat('d/m/Y', $_REQUEST['needed_date']);
  213. log_message('debug','converted item date '.$dateObj->format('Y-m-d'));
  214. $purchase_quote_data['needed_by_date'] = $dateObj->format('Y-m-d');
  215. }
  216. if (!empty($_REQUEST['warehouse_id'])){
  217. $purchase_quote_data['warehouse_id'] = $_REQUEST['warehouse_id'];
  218. }
  219. $comments = appendComments($_REQUEST['notes'], 'notes');
  220. //while editing the supplier id is passed.
  221. $purchase_quote_data['supplier_id'] = $_REQUEST['supplier_name'];
  222. $where_clause_quote = array('id'=>$id);
  223. $this->Request_quote_master->update($where_clause_quote,$purchase_quote_data,array('notes'=>$comments));
  224. }
  225. else if ($oper=='del'){
  226. $idAraay = $_REQUEST['id'];
  227. foreach($idAraay as $tempId){
  228. $where_clause_quote = array('id'=>$tempId);
  229. $this->Request_quote_master->update($where_clause_quote,array('status'=>'cancelled'));
  230. $where_clause_quote_item = array('rfq_id'=>$tempId);
  231. $this->Request_quote_item->update($where_clause_quote_item,array('status'=>'cancelled'));
  232. }
  233. }
  234. $this->db->trans_complete();
  235. }
  236. function addRFQItemBulk (){
  237. //$id = $_REQUEST['quoteId'];
  238. $data= $_REQUEST['data'];
  239. $purchase_quote_data['rfq_id'] = $_REQUEST['rfq'];
  240. $this->db->trans_start();
  241. foreach($data as $itemDetails){
  242. $purchase_quote_data['product_id'] = $itemDetails['id'];
  243. $purchase_quote_data['requested_quantity'] = $itemDetails['quantity'];
  244. $this->createRFQItem($purchase_quote_data);
  245. }
  246. $this->db->trans_complete();
  247. }
  248. function addRFQItem (){
  249. //$id = $_REQUEST['quoteId'];
  250. $product_id = $_REQUEST['productid'];
  251. $purchase_quote_data['rfq_id'] = $_REQUEST['rfq'];
  252. $purchase_quote_data['product_id'] = $product_id;
  253. $needed_by = $_REQUEST['needeedByDate'];
  254. if (!empty($needed_by)){
  255. $dateObj = DateTime::createFromFormat('d/m/Y', $needed_by);
  256. log_message('debug','converted item date '.$dateObj->format('Y-m-d'));
  257. $purchase_quote_data['needed_by_date'] = $dateObj->format('Y-m-d');
  258. }
  259. $purchase_quote_data['requested_quantity'] = $_REQUEST['quantity'];
  260. $purchase_quote_data['expected_price'] = $_REQUEST['exprice'];
  261. $purchase_quote_data['estimated_value'] = $_REQUEST['quantity']*$_REQUEST['exprice'];
  262. $purchase_quote_data['comments'] = $_REQUEST['descItem'];
  263. $id = $this->createRFQItem($purchase_quote_data);
  264. }
  265. //business logic
  266. function createRFQItem($purchase_quote_data){
  267. $this->db->trans_start();
  268. /* insert into quote item */
  269. $this->Request_quote_item->insert($purchase_quote_data);
  270. log_message('debug','insert statement ='.$this->db->last_query());
  271. $id = $this->db->insert_id();
  272. /* end insert */
  273. /* update reference number in quote item */
  274. $where_clause = array('id'=>$id);
  275. $this->Request_quote_item->update($where_clause, array('reference' => 10000000 + $id));
  276. /* end update */
  277. /* update estimated value in quote master */
  278. $rfq_id = $purchase_quote_data['rfq_id'];
  279. $quote_details=$this->Request_quote_master->getById($rfq_id);
  280. $estimated_value = $quote_details->estimated_value + $purchase_quote_data['estimated_value'];
  281. $upd_data['estimated_value'] = $estimated_value;
  282. if ($quote_details->status==self::DRAFT){
  283. //if the status is draft that means previously there was no items and for the first time we are adding items.
  284. // so we set the status as open
  285. $upd_data['status'] = self::OPEN;
  286. }
  287. $this->Request_quote_master->update(array('id'=>$rfq_id),$upd_data);
  288. log_message('debug','update statement ='.$this->db->last_query());
  289. /* end update estimated value in quote master */
  290. $this->db->trans_complete();
  291. return $id;
  292. }
  293. function modifyRFQItem (){
  294. $id = $_REQUEST['line_id'];
  295. $item_details=$this->Request_quote_item->getById($id);
  296. $rfq_id = $item_details->rfq_id;
  297. $current_est_value = $item_details->estimated_value;
  298. $oper = $_REQUEST['oper'];
  299. $this->db->trans_start();
  300. if ($oper=='edit'){
  301. if (!empty($_REQUEST['needed_by_date'])){
  302. $dateObj = DateTime::createFromFormat('d/m/Y', $_REQUEST['needed_by_date']);
  303. log_message('debug','converted item date '.$dateObj->format('Y-m-d'));
  304. $purchase_quote_data['needed_by_date'] = $dateObj->format('Y-m-d');
  305. }
  306. $purchase_quote_data['requested_quantity'] = $_REQUEST['quantity'];
  307. $purchase_quote_data['expected_price'] = $_REQUEST['expected_price'];
  308. $comments = appendComments($_REQUEST['comments'], 'comments');
  309. $purchase_quote_data['estimated_value'] = $_REQUEST['requested_quantity']*$_REQUEST['expected_price'];
  310. $where_clause = array('id'=>$id);
  311. $this->Request_quote_item->update($where_clause,$purchase_quote_data,array('comments'=>$comments));
  312. $quote_details=$this->Request_quote_master->getById($rfq_id);
  313. $estimated_value = $quote_details->estimated_value - $current_est_value + $purchase_quote_data['estimated_value'];
  314. $this->Request_quote_master->update(array('id'=>$rfq_id),array('estimated_value'=>$estimated_value));
  315. }
  316. else if ($oper=='del'){
  317. $quote_details=$this->Request_quote_master->getById($rfq_id);
  318. $estimated_value = $quote_details->estimated_value - $item_details->estimated_value;
  319. $this->Request_quote_master->update(array('id'=>$rfq_id),array('estimated_value'=>$estimated_value));
  320. $where_clause = array('id'=>$id);
  321. $this->Request_quote_item->update($where_clause,array('status'=>'cancelled'));
  322. }
  323. $this->db->trans_complete();
  324. }
  325. function populateRFQItems(){
  326. $quoteid = $_REQUEST['quoteId'];
  327. if (!empty($quoteid)){
  328. $quotedata = array();
  329. $where = array('rfq_id' => $quoteid );
  330. $griddata= populateGridCommon('Request_quote_item',$where);
  331. $dbrows = $griddata['db_data'];
  332. $data = $griddata['grid_metadata'];
  333. foreach ($dbrows as $dbrow){
  334. array_push($quotedata, array('id'=> $dbrow['id'],'dprow' => array($dbrow['name'],$dbrow['requested_quantity'],$dbrow['needed_by_date'],$dbrow['expected_price'],$dbrow['estimated_value'],$dbrow['comments'])));
  335. }
  336. $data['quoteitemdata'] = $quotedata;
  337. echo json_encode($data);
  338. }
  339. }
  340. function generateQuoteFromRFQ(){
  341. $ids= $_REQUEST['ids'];
  342. foreach($ids as $id){
  343. log_message('debug',' id '.$id);
  344. $rfq_details=$this->Request_quote_master->getById($id,null,true);
  345. if ($rfq_details['status']==self::OPEN) {
  346. $this->db->trans_start();
  347. //$this->Request_quote_master->update(array('id'=>$id),array('approved_by'=>$this->user->person_id));
  348. $this->generateQuoteInternal($rfq_details);
  349. $this->db->trans_complete();
  350. }
  351. }
  352. }
  353. function getCommentsForEntity(){
  354. $entity = $_REQUEST['entity'];
  355. $id = $_REQUEST['id'];
  356. if ($entity == 'rfq'){
  357. $model = 'Request_quote_master';
  358. $col_array = array('notes','approval_notes');
  359. }
  360. else if ($entity == 'quote'){
  361. $model = 'Purchase_quote_master';
  362. $col_array = array('notes','approval_notes');
  363. }
  364. else if ($entity == 'order'){
  365. $model = 'Purchase_order_master';
  366. $col_array = array('receiving_notes');
  367. }
  368. else if ($entity == 'receipt_item'){
  369. $model = 'Receipt_item';
  370. $col_array = array('receiving_notes','pp_approval_notes');
  371. }
  372. if (!empty($id)){
  373. $details=$this->$model->getById($id,$col_array,true);
  374. echo json_encode($details);
  375. }
  376. }
  377. function addCommentsForEntity(){
  378. $entity = $_REQUEST['entity'];
  379. $id = $_REQUEST['id'];
  380. $note_type = $_REQUEST['note_type'];
  381. // if ($entity == 'rfq'){
  382. // $model = 'Request_quote_master';
  383. // $col_array = array('notes','approval_notes');
  384. // }
  385. // else if ($entity == 'quote'){
  386. // $model = 'Purchase_quote_master';
  387. // $col_array = array('notes','approval_notes');
  388. // }
  389. // else if ($entity == 'order'){
  390. // $model = 'Purchase_order_master';
  391. // $col_array = array('receiving_notes');
  392. //
  393. // }
  394. if ($entity == 'receipt_item'){
  395. $model = 'Receipt_item';
  396. if ($note_type=='pp_approval'){
  397. $comments = appendComments($_REQUEST['notes'], 'pp_approval_notes');
  398. }
  399. }
  400. if (!empty($id)){
  401. $this->$model->update($id,null,array('pp_approval_notes'=>$comments));
  402. }
  403. }
  404. function generatePOFromQuote(){
  405. $ids= $_REQUEST['ids'];
  406. foreach($ids as $id){
  407. log_message('debug',' id '.$id);
  408. $quote_details=$this->Purchase_quote_master->getById($id,null,true);
  409. if ($quote_details['status']==self::OPEN ||$quote_details['status']==self::WAITING_FOR_APPROVAL ) {
  410. $this->db->trans_start();
  411. $this->Purchase_quote_master->update(array('id'=>$id),array('approved_by'=>$this->user->person_id));
  412. $this->generatePOInternal($quote_details);
  413. $this->db->trans_complete();
  414. }
  415. }
  416. }
  417. /* PURCHASE QUOTE GRID END*/
  418. /* APPROVAL GRUD START */
  419. function approveOrReject(){
  420. $id= $_REQUEST['quoteId'];
  421. $action= $_REQUEST['action'];
  422. $entity= $_REQUEST['entity'];
  423. if ($entity=='quote'){
  424. $model = 'Purchase_quote_master';
  425. $itemModel= 'Purchase_quote_item';
  426. $parent_id = 'quote_id';
  427. }
  428. else if ($entity=='rfq'){
  429. $model = 'Request_quote_master';
  430. $itemModel= 'Request_quote_item';
  431. $parent_id = 'rfq_id';
  432. }
  433. log_message('debug',' id '.$id);
  434. log_message('debug',' action '.$action);
  435. $quote_details=$this->$model->getById($id,null,true);
  436. if ($quote_details['status']==self::WAITING_FOR_APPROVAL ) {
  437. if ($action == 'approve'){
  438. $this->db->trans_start();
  439. if ($entity=='quote'){
  440. $this->$model->update(array('id'=>$id),array('approved_by'=>$this->user->person_id,'approval_notes'=>$_REQUEST['quote_approval_notes']));
  441. $this->generatePOInternal($quote_details);
  442. }
  443. else if ($entity=='rfq'){
  444. $this->$model->update(array('id'=>$id),array('approved_by'=>$this->user->person_id,'approval_notes'=>$_REQUEST['quote_approval_notes'],'status'=>self::SUBMITTEDTOQUOTE));
  445. $this->generateQuoteInternal($quote_details);
  446. }
  447. $this->db->trans_complete();
  448. }
  449. else if ($action == 'reject'){
  450. $this->db->trans_start();
  451. $this->$model->update(array('id'=>$id),array('status'=>self::REJECTED,'approved_by'=>$this->user->person_id,'approval_notes'=>$_REQUEST['quote_approval_notes']));
  452. $item_details=$this->$itemModel->getByQuoteId($id);
  453. foreach ($item_details as $item_data){
  454. $this->$itemModel->update(array('id'=>$item_data['id']),array('status'=>self::REJECTED));
  455. }
  456. $this->db->trans_complete();
  457. }
  458. }
  459. }
  460. function approveQuotesInBulk(){
  461. $ids= $_REQUEST['ids'];
  462. // $this->db->trans_start();
  463. foreach($ids as $id){
  464. $quote_details=$this->Request_quote_master->getById($id,null,true);
  465. if ($quote_details['status']==self::OPEN ||$quote_details['status']==self::WAITING_FOR_APPROVAL ) {
  466. $this->db->trans_start();
  467. $this->Request_quote_master->update(array('id'=>$id),array('approved_by'=>$this->user->person_id,'status'=>self::SUBMITTEDTOQUOTE));
  468. $this->generateQuoteInternal($quote_details);
  469. $this->db->trans_complete();
  470. }
  471. }
  472. //$this->db->trans_complete();
  473. }
  474. /* APPROVAL GRID END */
  475. /* REJECTED GRID START*/
  476. function reopen (){
  477. $ids= $_REQUEST['ids'];
  478. $entity= $_REQUEST['entity'];
  479. if ($entity=='quote'){
  480. $model = 'Purchase_quote_master';
  481. $itemModel= 'Purchase_quote_item';
  482. $parent_id = 'quote_id';
  483. }
  484. else if ($entity=='rfq'){
  485. $model = 'Request_quote_master';
  486. $itemModel= 'Request_quote_item';
  487. $parent_id = 'rfq_id';
  488. }
  489. foreach($ids as $id){
  490. log_message('debug',' id '.$id);
  491. $quote_details=$this->$model->getById($id,null,true);
  492. if ($quote_details['status']==self::REJECTED ) {
  493. $this->db->trans_start();
  494. $this->$model->update(array('id'=>$id),array('status'=>self::OPEN,'last_updated_by'=>$this->user->person_id));
  495. $item_details=$this->$itemModel->getByQuoteId($id);
  496. foreach ($item_details as $item_data){
  497. $this->$itemModel->update(array('id'=>$item_data['id']),array('status'=>self::OPEN));
  498. }
  499. $this->db->trans_complete();
  500. }
  501. }
  502. }
  503. /* REJECTED GRID END*/
  504. /* COMMON FUNCTIONS FOR RFQ GRIDS */
  505. private function generatePOInternal($quote_details){
  506. $id=$quote_details['id'];
  507. $order_data['owner_id'] = $quote_details['owner_id'];
  508. $order_data['needed_by_date'] = $quote_details['needed_by_date'];
  509. $order_data['generated_by'] = $this->user->person_id;
  510. $order_data['quote_id'] = $quote_details['id'];
  511. log_message('debug',json_encode($order_data));
  512. $order_id = $this->createOrder($order_data);
  513. log_message('debug',$this->db->last_query());
  514. $this->Purchase_quote_master->update(array('id'=>$id),array('status'=>self::ORDERED,'order_id'=>$order_id));
  515. log_message('debug',$this->db->last_query());
  516. //now update line item status
  517. $item_details=$this->Purchase_quote_item->getByQuoteId($id);
  518. foreach ($item_details as $item_data){
  519. if ($item_data['status'] == self::OPEN || $item_data['status'] == self::WAITING_FOR_APPROVAL){
  520. $order_item_data['name'] = $item_data['name'];
  521. $order_item_data['sku'] = $item_data['sku'];
  522. $order_item_data['product_id'] = $item_data['product_id'];
  523. $order_item_data['estimated_value'] = $item_data['estimated_value'];
  524. $order_item_data['needed_by_date'] = $item_data['needed_by_date'];
  525. $order_item_data['quoted_quantity'] = $item_data['quoted_quantity'];
  526. //repeatative ..as of now as no difference between quoted and ordered quantity
  527. $order_item_data['ordered_quantity'] = $item_data['quoted_quantity'];
  528. $order_item_data['expected_price'] = $item_data['expected_price'];
  529. $order_item_data['order_id'] =$order_id;
  530. $order_item_data['quote_line_id'] = $item_data['id'];
  531. $order_line_id = $this->createOrderItem($order_item_data);
  532. $this->Purchase_quote_item->update(array('id'=>$item_data['id']),array('status'=>self::ORDERED,'order_line_id'=>$order_line_id));
  533. }
  534. }
  535. }
  536. public function createOrder($purchase_quote_data){
  537. $this->db->trans_start();
  538. $this->Purchase_order_master->insert($purchase_quote_data);
  539. $id = $this->db->insert_id();
  540. $where_clause = array('id'=>$id);
  541. $this->Purchase_order_master->update($where_clause, array('reference' => 10000000 + $id));
  542. $this->db->trans_complete();
  543. return $id;
  544. }
  545. /*end quote */
  546. /* RECEIVING GRID START */
  547. function populatePOToReceive(){
  548. // $person_id = $this->user->person_id;
  549. //$in_where=array('field_name'=>'status','value_array'=>array(self::OPEN,self::RECEIVING,self::RECEIVED)) ;
  550. $this->populatePOInternal();
  551. }
  552. /* RECEIVING GRID END */
  553. function populatePayments(){
  554. $invoiceId = $_REQUEST['invoiceId'];
  555. $orderId = $_REQUEST['orderId'];
  556. $type = $_REQUEST['type'];
  557. if (!empty($invoiceId) || !empty($orderId)){
  558. $paymentdata = array();
  559. if (!empty($invoiceId)){
  560. $where['invoice_id'] = $invoiceId;
  561. }
  562. if (!empty($orderId)){
  563. $where['order_id'] = $orderId;
  564. }
  565. if (!empty($type)){
  566. $where['payment_type'] = $type;
  567. }
  568. $griddata= populateGridCommon('Outgoing_payment',$where);
  569. $dbrows = $griddata['db_data'];
  570. $data = $griddata['grid_metadata'];
  571. foreach ($dbrows as $dbrow){
  572. $isAdvance = 'No';
  573. if ($dbrow['parent_id'] != 0){
  574. // we have advance payment
  575. $isAdvance = 'Yes';
  576. }
  577. array_push($paymentdata, array('id'=> $dbrow['id'],'dprow' => array($dbrow['payment_reference'],$dbrow['payment_mode'],$dbrow['payment_type'],$dbrow['amount'],$dbrow['comments'],$isAdvance,$dbrow['parent_id'])));
  578. }
  579. $data['paymentdata'] = $paymentdata;
  580. echo json_encode($data);
  581. }
  582. }
  583. function populateReceipts(){
  584. $where = array();
  585. $in_where = array();
  586. $status = $_REQUEST['_status'];
  587. //default status
  588. if (empty($status)){
  589. //$where['invoice_id'] = $invoice_id;
  590. $in_where=array('field_name'=>'status','value_array'=>array(self::READYTOINVOICEMEMO)) ;
  591. }
  592. setOwnerStatusCommon($where,$in_where);
  593. $page = $_REQUEST['page'];
  594. $limit = $_REQUEST['rows'];
  595. $sidx = $_REQUEST['sidx'];
  596. $sord = $_REQUEST['sord'];
  597. $searchOn = $_REQUEST['_search'];
  598. if (!empty($person_id)){
  599. $where['owner_id'] = $person_id;
  600. }
  601. //standard response parameters
  602. $quotedata = array();
  603. $count = $this->Receipt_master->totalNoOfRows($where,null,null,$in_where);
  604. if( $count > 0 && $limit > 0) {
  605. $total_pages = ceil($count/$limit);
  606. } else {
  607. $total_pages = 0;
  608. }
  609. if ($page > $total_pages) $page=$total_pages;
  610. $start = $limit*$page - $limit;
  611. // if for some reasons start position is negative set it to 0
  612. // typical case is that the user type 0 for the requested page
  613. if($start <0) $start = 0;
  614. $clauses = array('orderBy'=>$sidx,'orderDir'=>$sord,'startLimit'=>$start,'limit'=>$limit);
  615. $data['total'] = $total_pages;
  616. $data['page'] = $page;
  617. $data['records'] = $count;
  618. if($searchOn=='true') {
  619. $filters = json_decode($_REQUEST['filters'],true);
  620. $groupOp = $filters['groupOp'];
  621. $rules = $filters['rules'];
  622. $like_condition = array();
  623. foreach ($rules as $rule){
  624. $field = $rule['field'];
  625. $op= $rule['op'];
  626. $input = $rule['data'];
  627. if ($field == 'order_reference' ){
  628. $orderDetails = $this->Purchase_order_master->getGridByReference($input);
  629. $like_condition['order_id'] = $orderDetails['id'];
  630. }
  631. else if ($field == 'quote_reference'){
  632. $orderDetails = $this->Purchase_order_master->getGridByQuoteReference($input);
  633. $like_condition['order_id'] = $orderDetails['id'];
  634. }
  635. else if ($field == 'supplier_name'){
  636. $supplierDetails = $this->Supplier->getByName($input);
  637. $like_condition['supplier_id'] = $supplierDetails['id'];
  638. }
  639. else {
  640. $like_condition[$field] = trim($input);
  641. }
  642. }
  643. $quotes = $this->Receipt_master->getAll(false,$where,null,$clauses,$like_condition,$in_where);
  644. }
  645. else {
  646. $quotes = $this->Receipt_master->getAll(false,$where,null,null,null,$in_where);
  647. }
  648. foreach ($quotes as $dp){
  649. $orderDetails = $this->Purchase_order_master->getGridById($dp['order_id']);
  650. array_push($quotedata, array('id'=> $dp['id'],'dprow' => array($dp['reference'],$dp['supplier_receipt_number'],$orderDetails['supplier_name'],$dp['status'],$dp['order_id'],$orderDetails['reference'],$orderDetails['quote_reference'],$dp['owner_name'],$dp['owner_id'],$dp['approved_by_name'],$dp['approved_by'])));
  651. }
  652. $data['quotedata'] = $quotedata;
  653. echo json_encode($data);
  654. }
  655. function populatePOInternal(){
  656. $where = array();
  657. $in_where = array();
  658. setOwnerStatusCommon($where,$in_where);
  659. //standard response parameters
  660. $orderdata = array();
  661. $griddata= populateGridCommon('Purchase_order_master',$where,null,$in_where);
  662. $dbrows = $griddata['db_data'];
  663. $data = $griddata['grid_metadata'];
  664. foreach ($dbrows as $dbrow){
  665. array_push($orderdata, array('id'=> $dbrow['id'],'dprow' => array($dbrow['reference'],$dbrow['quote_reference'],$dbrow['supplier_name'],$dbrow['estimated_value'],$dbrow['owner_id'],$dbrow['status'],$dbrow['raised_by_name'],$dbrow['order_generated_by_name'],$dbrow['owner_name'],$dbrow['needed_by_date'],$dbrow['received_by_name'],$dbrow['approved_by_name'],$dbrow['supplier_id'],$dbrow['warehouse_id'],$dbrow['received_by'])));
  666. }
  667. $data['orderdata'] = $orderdata;
  668. echo json_encode($data);
  669. }
  670. function validateReceiving(){
  671. $order_id = $_REQUEST['order_id'];
  672. // this note is for order
  673. $receiving_notes = $_REQUEST['receiving_notes'];
  674. //check the no of order line items with status receiving.
  675. $totalNoOfRowsByOrderIdReceived = $this->Purchase_order_item->totalNoOfRows(array('order_id'=>$order_id,'status'=>self::RECEIVED));
  676. $totalNoOfRowsByOrderIdTotal = $this->Purchase_order_item->totalNoOfRows(array('order_id'=>$order_id));
  677. if ($totalNoOfRowsByOrderIdReceived == $totalNoOfRowsByOrderIdTotal){
  678. // all the order lines are received
  679. $this->Purchase_order_master->update(array('id'=>$order_id,'status'=>self::RECEIVING),array('status'=>self::RECEIVED,'receiving_notes'=>$receiving_notes));
  680. $this->Receipt_master->update(array('order_id'=>$order_id,'status'=>self::RECEIVING),array('status'=>self::RECEIVED));
  681. }
  682. else {
  683. $this->Purchase_order_master->update(array('id'=>$order_id,'status'=>self::RECEIVING),array('receiving_notes'=>$receiving_notes));
  684. }
  685. }
  686. function modifyOrder (){
  687. $id = $_REQUEST['id'];
  688. $oper = $_REQUEST['oper'];
  689. $this->db->trans_start();
  690. if ($oper=='edit'){
  691. //$dateObj = DateTime::createFromFormat('d/m/Y', $_REQUEST['needed_by_date']);
  692. //log_message('debug','converted item date '.$dateObj->format('Y-m-d'));
  693. $purchase_quote_data['needed_by_date'] = $_REQUEST['needed_by_date'];
  694. $purchase_quote_data['supplier_name'] = $_REQUEST['supplier_name'];
  695. $where_clause_quote = array('id'=>$id);
  696. $this->Purchase_quote_master->update($where_clause_quote,$purchase_quote_data);
  697. }
  698. else if ($oper=='del'){
  699. $idAraay = explode(",", $id);
  700. foreach($idAraay as $tempId){
  701. $where_clause_quote = array('id'=>$tempId);
  702. $this->Purchase_quote_master->update($where_clause_quote,array('status'=>'cancelled'));
  703. $where_clause_quote_item = array('quote_id'=>$tempId);
  704. $this->Purchase_quote_item->update($where_clause_quote_item,array('status'=>'cancelled'));
  705. }
  706. }
  707. $this->db->trans_complete();
  708. }
  709. function addOrderItem (){
  710. //$id = $_REQUEST['quoteId'];
  711. $product_id = $_REQUEST['productid'];
  712. $purchase_quote_data['quote_id'] = $_REQUEST['orderId'];
  713. $purchase_quote_data['product_id'] = $product_id;
  714. $dateObj = DateTime::createFromFormat('d/m/Y', $_REQUEST['needeedByDate']);
  715. log_message('debug','converted item date '.$dateObj->format('Y-m-d'));
  716. $purchase_quote_data['needed_by_date'] = $dateObj->format('Y-m-d');
  717. $purchase_quote_data['quoted_quantity'] = $_REQUEST['quantity'];
  718. $purchase_quote_data['expected_price'] = $_REQUEST['exprice'];
  719. $purchase_quote_data['estimated_value'] = $_REQUEST['quantity']*$_REQUEST['exprice'];
  720. $purchase_quote_data['comments'] = $_REQUEST['descItem'];
  721. $productDetails = $this->Product->getByProductId($product_id);
  722. $purchase_quote_data['sku'] = $productDetails->barcode;
  723. $purchase_quote_data['name'] = $productDetails->product_name;
  724. $id = $this->createQuoteItem($purchase_quote_data);
  725. }
  726. //business logic
  727. function createOrderItem($purchase_quote_data){
  728. $this->db->trans_start();
  729. /* insert into quote item */
  730. $this->Purchase_order_item->insert($purchase_quote_data);
  731. log_message('debug','insert statement ='.$this->db->last_query());
  732. $id = $this->db->insert_id();
  733. /* end insert */
  734. /* update reference number in quote item */
  735. $where_clause = array('id'=>$id);
  736. $this->Purchase_order_item->update($where_clause, array('reference' => 10000000 + $id));
  737. /* end update */
  738. $this->db->trans_complete();
  739. return $id;
  740. }
  741. function modifyOrderItem (){
  742. $id = $_REQUEST['id'];
  743. $item_details=$this->Purchase_quote_item->getById($id);
  744. $quote_id = $item_details->quote_id;
  745. $current_est_value = $item_details->estimated_value;
  746. $oper = $_REQUEST['oper'];
  747. $this->db->trans_start();
  748. if ($oper=='edit'){
  749. //$dateObj = DateTime::createFromFormat('d/m/Y', $_REQUEST['needed_by_date']);
  750. //log_message('debug','converted item date '.$dateObj->format('Y-m-d'));
  751. $purchase_quote_data['needed_by_date'] = $_REQUEST['needed_by_date'];
  752. $purchase_quote_data['quoted_quantity'] = $_REQUEST['quoted_quantity'];
  753. $purchase_quote_data['expected_price'] = $_REQUEST['expected_price'];
  754. $purchase_quote_data['comments'] = $_REQUEST['comments'];
  755. $purchase_quote_data['estimated_value'] = $_REQUEST['quoted_quantity']*$_REQUEST['expected_price'];
  756. $where_clause = array('id'=>$id);
  757. $this->Purchase_quote_item->update($where_clause,$purchase_quote_data);
  758. $quote_details=$this->Purchase_quote_master->getById($quote_id);
  759. $estimated_value = $quote_details->estimated_value - $current_est_value + $purchase_quote_data['estimated_value'];
  760. $this->Purchase_quote_master->update(array('id'=>$quote_id),array('estimated_value'=>$estimated_value));
  761. }
  762. else if ($oper=='del'){
  763. $quote_details=$this->Purchase_quote_master->getById($quote_id);
  764. $estimated_value = $quote_details->estimated_value - $item_details->estimated_value;
  765. $this->Purchase_quote_master->update(array('id'=>$quote_id),array('estimated_value'=>$estimated_value));
  766. $where_clause = array('id'=>$id);
  767. $this->Purchase_quote_item->update($where_clause,array('status'=>'cancelled'));
  768. }
  769. $this->db->trans_complete();
  770. }
  771. function populateOrderItems(){
  772. $orderid = $_REQUEST['orderId'];
  773. if (!empty($orderid)){
  774. $orderitemdata = array();
  775. $where = array('order_id' => $orderid );
  776. $griddata= populateGridCommon('Purchase_order_item',$where);
  777. $dbrows = $griddata['db_data'];
  778. $data = $griddata['grid_metadata'];
  779. foreach ($dbrows as $dbrow){
  780. array_push($orderitemdata, array('id'=> $dbrow['id'],'dprow' => array($dbrow['product_id'],$dbrow['name'],$dbrow['quoted_quantity'],$dbrow['received_quantity'],$dbrow['returned_quantity'],$dbrow['cnbd_quantity'],$dbrow['pp_quantity'],$dbrow['needed_by_date'],$dbrow['expected_price'],$dbrow['estimated_value'],$dbrow['received_value'],$dbrow['returned_value'],$dbrow['pp_value'],$dbrow['comments'])));
  781. }
  782. $data['orderitemdata'] = $orderitemdata;
  783. echo json_encode($data);
  784. }
  785. }
  786. function populateReceiptItems(){
  787. $receiptId = $_REQUEST['receiptId'];
  788. $orderLineId = $_REQUEST['orderLineId'];
  789. $receipt_line_value_in =array();
  790. $populateGrid= true;
  791. // as of now keep default oper as "receipt"
  792. $oper = "receipt";
  793. if (!empty($_REQUEST['oper'])){
  794. $oper = $_REQUEST['oper'];
  795. }
  796. $where = array();
  797. $in_where = array();
  798. setOwnerStatusCommon($where,$in_where);
  799. //standard response parameters
  800. $quotedata = array();
  801. if ($oper=="receipt"){
  802. $where['receipt_id'] = $receiptId ;
  803. }
  804. else if ($oper=="orderline"){
  805. $where['order_line_id'] = $orderLineId ;
  806. }
  807. // else if ($oper=="pp"){
  808. // $where= array(/*'pp_quantity >' => 0 ,*/'owner_id'=>$this->user->person_id,'status !='=>self::COMPLETE);
  809. // }
  810. else if ($oper=="pp_approve"){
  811. $where['pp_quantity >']= 0;
  812. $receipt_line_value_array = array_unique($this->Receipt_partpayment->getAll(false,array('status'=>self::WAITING_FOR_APPROVAL),array('receipt_line_id')));
  813. //dont fir the query if there is no pp item with wfa mode
  814. if (count($receipt_line_value_array)==0){
  815. $populateGrid = false;
  816. }
  817. foreach ($receipt_line_value_array as $value){
  818. array_push($receipt_line_value_in,$value['receipt_line_id']);
  819. }
  820. }
  821. if ($populateGrid===true){
  822. $griddata= populateGridCommon('Receipt_item',$where,null,array('field_name'=>'id','value_array'=>$receipt_line_value_in));
  823. $quotes = $griddata['db_data'];
  824. $data = $griddata['grid_metadata'];
  825. foreach ($quotes as $dp){
  826. $receipt_data = $this->Receipt_master->getById($dp['receipt_id'],array('supplier_receipt_number','reference','owner_id','owner_name'),true);
  827. $po_item_data = $this->Purchase_order_item->getById($dp['order_line_id'],array('reference','order_id'),true);
  828. //$test = $po_item_data['reference'];
  829. array_push($quotedata, array('id'=> $dp['id'],'dprow' => array($dp['reference'],$dp['batch_number']/*receipt line reference*/,$receipt_data['supplier_receipt_number'],$receipt_data['reference'],/*receipt reference*/
  830. $dp['receipt_id'],$po_item_data['order_id'], $dp['order_line_id'],$po_item_data['reference'],$dp['product_id'],$dp['name'],$dp['expiry_date'],$dp['vat'],$dp['ordered_quantity'],$dp['received_quantity'],$dp['received_value'],$dp['pp_quantity'],$dp['pp_value'],$dp['returned_quantity'],$dp['returned_value'],$dp['pp_status'],/*$dp['receiving_notes'],$dp['returned_notes'],*/$receipt_data['owner_name'],$receipt_data['owner_id'],$dp['approved_by_name'],$dp['approved_by'])));
  831. }
  832. }
  833. $data['receiptitemdata'] = $quotedata;
  834. echo json_encode($data);
  835. }
  836. function populatePartpaymentItems(){
  837. $ppdata = array();
  838. $receipt_line_id= $_REQUEST['receipt_line_id'];
  839. $where = array('receipt_line_id' => $receipt_line_id );
  840. $in_where['field_name'] = 'status' ;
  841. $in_where['value_array'] = $_REQUEST['_status'] ;
  842. $griddata= populateGridCommon('Receipt_partpayment',$where,array('id','receipt_id','receipt_line_id',
  843. 'pp_quantity','pp_value','pp_notes','status'),$in_where);
  844. $dbrows = $griddata['db_data'];
  845. $data = $griddata['grid_metadata'];
  846. foreach ($dbrows as $row){
  847. array_push($ppdata, array('id'=> $row['id'],'dprow' => array($row['receipt_id'],$row['receipt_line_id'],
  848. $row['pp_quantity'], $row['pp_value'],$row['pp_notes'],$row['status'])));
  849. }
  850. $data['ppdata'] = $ppdata;
  851. echo json_encode($data);
  852. }
  853. function getOrderDetails(){
  854. $orderId=$_REQUEST['orderId'];
  855. if (!empty($orderId)){
  856. $order = $this->Purchase_order_master->getGridById($orderId);
  857. echo json_encode($order);
  858. }
  859. }
  860. function getQuoteDetails(){
  861. $quoteId=$_REQUEST['quoteId'];
  862. if (!empty($quoteId)){
  863. $quote = $this->Purchase_quote_master->getGridById($quoteId);
  864. echo json_encode($quote);
  865. }
  866. }
  867. function getRFQDetails(){
  868. $quoteId=$_REQUEST['quoteId'];
  869. if (!empty($quoteId)){
  870. $quote = $this->Request_quote_master->getGridById($quoteId);
  871. echo json_encode($quote);
  872. }
  873. }
  874. function loadPOGrid()
  875. {
  876. $this->load->view("procurement/purchaseorder/purchase_order_grid",$data);
  877. }
  878. function loadOpenInvoicesGrid()
  879. {
  880. $this->load->view("procurement/invoice/purchase_invoice_grid",$data);
  881. }
  882. function loadFormFragment(){
  883. $this->load->view("procurement/purchaseorder/po_details",$data);
  884. }
  885. function loadNotesFragment(){
  886. $this->load->view("procurement/purchaseorder/po_notes",$data);
  887. }
  888. function loadWaitingForApprovalQuotesGrid (){
  889. $this->load->view("procurement/quote/approval/quote_approval_grid",$data);
  890. }
  891. function loadRejectedQuotesGrid (){
  892. $this->load->view("procurement/quote/rejected/quote_rejected_grid",$data);
  893. }
  894. function loadRejectedRFQGrid (){
  895. $this->load->view("procurement/quote/rejected/request_rejected_grid",$data);
  896. }
  897. function loadQuoteFormFragment(){
  898. $this->load->view("procurement/quote/approval/quote_details",$data);
  899. }
  900. function loadQuoteNotesFragment(){
  901. $this->load->view("procurement/quote/approval/quote_notes",$data);
  902. }
  903. function loadWaitingForApprovalRFQGrid (){
  904. $this->load->view("procurement/quote/approval/request_approval_grid",$data);
  905. }
  906. function loadWaitingForApprovalRFQFormFragment(){
  907. $this->load->view("procurement/quote/approval/request_details",$data);
  908. }
  909. function loadWaitingForApprovalRFQNotesFragment(){
  910. $this->load->view("procurement/quote/approval/request_notes",$data);
  911. }
  912. function getProductsDropDown(){
  913. return populateProducts();
  914. }
  915. function loadReceivedGrid (){
  916. $this->load->view("procurement/purchaseorder/received/received_order_grid",$data);
  917. }
  918. function loadPPGrid (){
  919. $this->load->view("procurement/purchaseorder/received/partpayment_grid",$data);
  920. }
  921. function loadCreateQuotesGrid (){
  922. $data['productOptions'] = $this->getProductsDropDown();
  923. $this->load->view("procurement/quote/create/quote_create_grid",$data);
  924. }
  925. function loadCreateQuoteFormFragment(){
  926. $data['warehouseOptions']= populateWarehouses();
  927. $data['supplierOptions']= populateSuppliers();
  928. $this->load->view("procurement/quote/create/quote_details",$data);
  929. }
  930. function loadCreateQuoteNotesFragment(){
  931. $this->load->view("procurement/quote/create/quote_notes",$data);
  932. }
  933. function submitForApproval(){
  934. $idArray = $_REQUEST['ids'];
  935. $entity = $_REQUEST['entity'];
  936. if (!empty($idArray) && !empty($entity)){
  937. if ($entity=='quote'){
  938. $model = 'Purchase_quote_master';
  939. $itemModel= 'Purchase_quote_item';
  940. $parent_id = 'quote_id';
  941. }
  942. else if ($entity=='rfq'){
  943. $model = 'Request_quote_master';
  944. $itemModel= 'Request_quote_item';
  945. $parent_id = 'rfq_id';
  946. }
  947. foreach($idArray as $tempId){
  948. $this->db->trans_start();
  949. $where_clause_quote = array('id'=>$tempId);
  950. $this->$model->update($where_clause_quote,array('status'=> self::WAITING_FOR_APPROVAL));
  951. log_message('debug',$this->db->last_query());
  952. $where_clause_quote_item = array($parent_id=>$tempId);
  953. $this->$itemModel->update($where_clause_quote_item,array('status'=>self::WAITING_FOR_APPROVAL));
  954. log_message('debug',$this->db->last_query());
  955. $this->db->trans_complete();
  956. }
  957. }
  958. }
  959. function assign(){
  960. $inv_value_array = json_decode($_REQUEST['sel_quote']);
  961. foreach($inv_value_array as $id){
  962. $quote_details = $this->Purchase_quote_master->getById($id);
  963. $notes= $quote_details->notes;
  964. $notes .= '<br/>Assigned By:' .$this->username.' Assignment Notes:'.$_REQUEST['assignment_notes'];
  965. $where_clause_array= array('id'=>$id);
  966. $inv_data = array
  967. (
  968. 'owner_id'=>$_REQUEST['userId'],
  969. 'notes'=>$notes
  970. );
  971. $this->Purchase_quote_master->update($where_clause_array,$inv_data);
  972. }
  973. }
  974. function processPartpayment(){
  975. $action = $_REQUEST['action'];
  976. $qty = $_REQUEST['pp_quantity'];
  977. $value = $_REQUEST['pp_value'];
  978. $line_id = $_REQUEST['receipt_line_id'];
  979. $order_line_id=$_REQUEST['order_line_id'];
  980. $pp_id = $_REQUEST['pp_id'];
  981. $pp_data['order_line_id'] = $order_line_id;
  982. $pp_data['receipt_line_id'] = $line_id;
  983. $pp_data['pp_quantity'] = $qty;
  984. $pp_data['pp_value'] = $value;
  985. $old_qty = $_REQUEST['pp_old_qty'];
  986. $old_val = $_REQUEST['pp_old_val'];
  987. $pp_data['pp_notes'] = $_REQUEST['pp_notes'];
  988. $pp_data['product_id'] = $_REQUEST['product_id'];
  989. $this->db->trans_start();
  990. if ($action == self::ADD){
  991. $this->Receipt_partpayment->insert($pp_data);
  992. }
  993. else if ($action == self::EDIT){
  994. $this->Receipt_partpayment->update(array('id'=>$pp_id),$pp_data);
  995. $qty -= $old_qty;
  996. $value -= $old_val;
  997. }
  998. $this->Receipt_item->update(array('id'=>$line_id),null,array('pp_quantity'=>'pp_quantity + '.$qty,'pp_value'=>'pp_value + '.$value));
  999. $this->Purchase_order_item->update(array('id'=>$order_line_id),null,array('pp_quantity'=>'pp_quantity + '.$qty,'pp_value'=>'pp_value + '.$value));
  1000. $this->db->trans_complete();
  1001. //$this->Receipt_partpayment
  1002. }
  1003. function cancelPartPayment (){
  1004. $ppIds = $_REQUEST['pp_ids'];
  1005. $order_line_id = $_REQUEST['order_line_id'];
  1006. $receipt_line_id = $_REQUEST['receipt_line_id'];
  1007. $batch_array =array();
  1008. foreach ($ppIds as $ppId){
  1009. array_push($batch_array,array('id'=>$ppId,'status'=>self::CANCELLED));
  1010. }
  1011. $this->db->trans_start();
  1012. //cancel in batch
  1013. $this->Receipt_partpayment->update_batch($batch_array,'id');
  1014. //reduce the part payment items from reciot and po line item
  1015. $canceledQty = $this->Receipt_partpayment->getSumTotal('pp_quantity',null,array('field_name'=>'id','value_array'=>$ppIds));
  1016. $canceledVal = $this->Receipt_partpayment->getSumTotal('pp_value',null,array('field_name'=>'id','value_array'=>$ppIds));
  1017. $this->Receipt_item->update(array('id'=>$receipt_line_id),null,array('pp_quantity'=>'pp_quantity - '.$canceledQty,'pp_value'=>'pp_value - '.$canceledVal));
  1018. $this->Purchase_order_item->update(array('id'=>$order_line_id),null,array('pp_quantity'=>'pp_quantity - '.$canceledQty,'pp_value'=>'pp_value - '.$canceledVal));
  1019. $this->db->trans_complete();
  1020. }
  1021. function submitForApprovalPartPayment (){
  1022. $ppIds = $_REQUEST['pp_ids'];
  1023. $receipt_line_id = $_REQUEST['receipt_line_id'];
  1024. $batch_array =array();
  1025. foreach ($ppIds as $ppId){
  1026. array_push($batch_array,array('id'=>$ppId,'status'=>self::WAITING_FOR_APPROVAL));
  1027. }
  1028. $this->Receipt_partpayment->update_batch($batch_array,'id');
  1029. $this->Receipt_item->update(array('id'=>$receipt_line_id),array('pp_status'=>self::WAITING_FOR_APPROVAL));
  1030. // foreach ($ppIds as $ppId){
  1031. //
  1032. // $this->Receipt_partpayment->update(array('id'=>$ppId),array('status'=>self::WAITING_FOR_APPROVAL));
  1033. // // as of now this is complete separate flow. Only thing is that less than
  1034. // // # of items registers for part payment can npt be modified for received/returned unless those are cancelled.
  1035. // }
  1036. }
  1037. // createInvoicePartPaymentUpdateOrderReceipt
  1038. function testTotal(){
  1039. $ppIds[]=6;
  1040. $ppIds[]=7;
  1041. $len = count($ppIds);
  1042. $final = array_combine($ppIds, array_fill(0,$len,'test'));
  1043. // $total_invoice_value = 0;
  1044. // $total_invoice_value +=$this->Receipt_partpayment->getSumTotal('pp_value',null,array('field_name'=>'id','value_array'=>$ppIds));
  1045. // $total_invoice_value = $this->Receipt_item->getSumTotal('`received_quantity`-`pp_quantity`');
  1046. // echo $total_invoice_value;
  1047. }
  1048. //
  1049. function createInvoicePPUpdateOrderReceipt (){
  1050. $ppIds = $_REQUEST['pp_ids'];
  1051. $order_id = $_REQUEST['order_id'];
  1052. $receipt_line_Id = $_REQUEST['receipt_line_id'];
  1053. // echo $ppIds;
  1054. // echo $order_id;
  1055. // echo $receipt_line_Id;
  1056. //
  1057. $total_invoice_qty = 0;
  1058. $total_invoice_value = 0;
  1059. $this->db->trans_start();
  1060. $inv_ins_data=array('status'=>self::PENDING,'order_id'=>$order_id,
  1061. 'payment_process_type'=>self::PARTPAYMENT);
  1062. $newInvId = $this->createInvoice($inv_ins_data);
  1063. $newInvRef = 10000000 + $newInvId;
  1064. $total_invoice_value +=$this->Receipt_partpayment->getSumTotal('pp_value',null,array('field_name'=>'id','value_array'=>$ppIds));
  1065. $total_invoice_qty +=$this->Receipt_partpayment->getSumTotal('pp_quantity',null,array('field_name'=>'id','value_array'=>$ppIds));
  1066. // //foreach ($ppIds as $receiptId){
  1067. // // create Invoice items
  1068. $receipt_item = $this->Receipt_item->getById($receipt_line_Id,
  1069. array('sku','name','product_id','price','order_line_id','receipt_id','received_value','received_quantity'),true);
  1070. //foreach ($receipt_items as $receipt_item){
  1071. $invoice_item_data = array();
  1072. //common item data
  1073. $invoice_item_data['sku'] = $receipt_item['sku'];
  1074. $invoice_item_data['name'] = $receipt_item['name'];
  1075. $invoice_item_data['product_id'] = $receipt_item['product_id'];
  1076. $invoice_item_data['price'] = $receipt_item['price'];
  1077. $invoice_item_data['order_line_id'] = $receipt_item['order_line_id'];
  1078. $invoice_item_data['invoiced_quantity'] = $total_invoice_qty;
  1079. $invoice_item_data['total_invoiced_value'] = $total_invoice_value;
  1080. $invoice_item_data['invoice_id'] = $newInvId;
  1081. $this->Purchase_invoice_item->insert($invoice_item_data);
  1082. log_message('debug','insert statement ='.$this->db->last_query());
  1083. $invoice_item_id = $this->db->insert_id();
  1084. /* end insert */
  1085. /* update reference number in line item */
  1086. $where_clause = array('id'=>$invoice_item_id);
  1087. $this->Purchase_invoice_item->update($where_clause, array('reference' => 10000000 + $invoice_item_id));
  1088. $this->Purchase_order_item->update(array('id'=>$receipt_item['order_line_id']),null,array('invoiced_quantity'=>'invoiced_quantity + '.$total_invoice_qty));
  1089. $this->Purchase_invoice_master->update(array('id'=>$newInvId),null,array('total_value'=>'total_value + '.$total_invoice_value));
  1090. $batch_array =array();
  1091. foreach ($ppIds as $ppId){
  1092. array_push($batch_array,array('id'=>$ppId,'status'=>self::PROCESSED_FOR_PAYMENT,'invoice_id'=>$newInvId,'invoice_line_id'=>$invoice_item_id));
  1093. }
  1094. $this->Receipt_partpayment->update_batch($batch_array,'id');
  1095. $where = array('status'=>self::PROCESSED_FOR_PAYMENT,'receipt_line_id'=>$receipt_line_Id);
  1096. $in_where['field_name'] = 'pp_status';
  1097. $in_where['value_array'] = array(self::OPEN,self::WAITING_FOR_APPROVAL);
  1098. // $where['pp_quantity >']= 0;
  1099. $count = $this->Receipt_partpayment->totalNoOfRows($where);
  1100. $countOpen = $this->Receipt_partpayment->totalNoOfRows(array('receipt_line_id'=>$receipt_line_Id),null,null,$in_where);
  1101. $countAll = $this->Receipt_partpayment->totalNoOfRows(array('receipt_line_id'=>$receipt_line_Id));
  1102. if ($countAll == $count){
  1103. $this->Receipt_item->update(array('id'=>$receipt_line_Id),array('pp_status'=>self::PROCESSED_FOR_PAYMENT));
  1104. }
  1105. else if ($countOpen == 0){
  1106. $this->Receipt_item->update(array('id'=>$receipt_line_Id),array('pp_status'=>self::NONE));
  1107. }
  1108. //if right now no item is in WFA state for this receiptline id mark the pp_staatus as processforpayment
  1109. $this->db->trans_complete();
  1110. if (!empty($newInvId)){
  1111. $response['invoice_id'] = $newInvRef;
  1112. }
  1113. echo json_encode($response);
  1114. }
  1115. //receivings
  1116. function receiveItems(){
  1117. $oper = $_REQUEST["oper"];
  1118. $action = $_REQUEST["action"];
  1119. $order_line_id = $_REQUEST["order_line_id"];
  1120. $receipt_line_id = $_REQUEST["receipt_line_id"];
  1121. $order_id = $_REQUEST["order_id"];
  1122. $receiptOp = $_REQUEST["receipt"];
  1123. $receiptIp = $_REQUEST["receipt_ip"];
  1124. $received_quantity = $_REQUEST["received_quantity"];
  1125. $received_value = $_REQUEST["received_value"];
  1126. $returned_quantity = $_REQUEST["returned_quantity"];
  1127. $returned_value = $_REQUEST["returned_value"];
  1128. $cnbd_quantity = $_REQUEST["cnbd_quantity"];
  1129. $batch_number = $_REQUEST["batch_number"];
  1130. $expiry_date = $_REQUEST["expiry_date"];
  1131. $vat = $_REQUEST["vat"];
  1132. // $discount = $_REQUEST["discount"];
  1133. // $free_items = $_REQUEST["free_items"];
  1134. if (!empty($cnbd_quantity)){
  1135. $cnbd_quantity = 0;
  1136. }
  1137. if ($oper == "return"){
  1138. if (!empty($_REQUEST["returned_notes"])){
  1139. $receipt_item_data['returned_notes']=$_REQUEST["returned_notes"];
  1140. }
  1141. }
  1142. else if ($oper == "receive"){
  1143. if (!empty($_REQUEST["receiving_notes"])){
  1144. $receipt_item_data['receiving_notes']=$_REQUEST["receiving_notes"];
  1145. }
  1146. }
  1147. //if (!empty($rcvd_note)){
  1148. $fmatted_rcvd_note = "&#013;&#010; **** ".date("Y-m-d H:i:s", time()). " ****&#013;&#010;".$_REQUEST["receiving_notes"];
  1149. $rcvd_note="CONCAT(`receiving_notes`, '$fmatted_rcvd_note')";
  1150. $notes_array['receiving_notes'] = $rcvd_note;
  1151. //}
  1152. //if (!empty($rtrnd_note)){
  1153. $fmatted_rtrnd_note = "&#013;&#010; **** ".date("Y-m-d H:i:s", time()). " ****&#013;&#010;".$_REQUEST["returned_notes"];
  1154. $rtrnd_note = "CONCAT(`returned_notes`, '$fmatted_rtrnd_note')";
  1155. // $receipt_item_data['returned_notes']="CONCAT(`returned_notes`, $fmatted_rtrnd_note);";
  1156. $notes_array['returned_notes'] = $rtrnd_note;
  1157. //}
  1158. $product_id = $_REQUEST["product_id"];
  1159. $supplierId=$_REQUEST["supplier_id"];
  1160. // $productdetails = $this->Product->getByProductId($product_id,true);
  1161. $receipt_item_data['product_id'] = $product_id;
  1162. // $receipt_item_data['name'] = $productdetails['product_name'];
  1163. // $receipt_item_data['sku'] = $productdetails['barcode'];
  1164. $receipt_item_data['order_line_id'] = $order_line_id;
  1165. $receipt_item_data['received_quantity']=$received_quantity;
  1166. $receipt_item_data['batch_number']=$batch_number;
  1167. $receipt_item_data['expiry_date'] = $expiry_date;
  1168. $receipt_item_data['vat']=$vat;
  1169. // $receipt_item_data['free_items']=$free_items;
  1170. // $receipt_item_data['discount']=$discount;
  1171. // total received and value for order line items
  1172. $total_received_for_order = $_REQUEST['total_received_quantity'];
  1173. $total_received_value_for_order = $_REQUEST['total_received_value'];
  1174. $total_returned_for_order = $_REQUEST['total_returned_quantity'];
  1175. $total_returned_value_for_order = $_REQUEST['total_returned_value'];
  1176. $ordered_quantity = $_REQUEST['quantity'];
  1177. $order_line_item_matched = 0;
  1178. $line_status= self::RECEIVING;
  1179. if ($ordered_quantity == $total_received_for_order + $total_returned_for_order + $cnbd_quantity){
  1180. $line_status= self::RECEIVED;
  1181. $order_line_item_matched = 1;
  1182. }
  1183. $this->db->trans_start();
  1184. //if new receipt number for this particular suppler create obe entry in recepipt table
  1185. if (empty($receiptOp) && !empty($receiptIp)){
  1186. $receiptData = array ('supplier_receipt_number'=>trim($receiptIp),'supplier_id'=>$supplierId
  1187. ,'order_id'=>$order_id,'status'=>self::RECEIVING,'owner_id'=>$this->user->person_id);
  1188. $this->Receipt_master->insert($receiptData);
  1189. // log_message('debug','insert statement ='.$this->db->last_query());
  1190. $id = $this->db->insert_id();
  1191. $where_clause = array('id'=>$id);
  1192. $this->Receipt_master->update($where_clause, array('reference' => 10000000 + $id));
  1193. // log_message('debug','update statement ='.$this->db->last_query());
  1194. $receiptOp = $id;
  1195. }
  1196. $receipt_item_data['receipt_id'] = $receiptOp;
  1197. ///****first cmmnt ****receipt line items are unique by order line id and receiot id.
  1198. //a single order line can have multiple recepit
  1199. // a single supplier receipt can also have multiple order line and multiple order
  1200. // but system receipt can only have single order and lultiple order line
  1201. //*** second comment** receipt line should be unique by batch number. During insert if no batch # the system reference is added as batch number
  1202. //**** comment **** reverting to first because different receipts can have products with same batchnumber so during add we are going to use that
  1203. //but in edit we can use receipt_line_id
  1204. if ($action == 'add'){
  1205. $itemDetails = $this->Receipt_item->getByOrderLineReceiptBatch($order_line_id,$receiptOp,$batch_number);
  1206. }
  1207. else if ($action == 'edit'){
  1208. $itemDetails = $this->Receipt_item->getById($receipt_line_id);
  1209. }
  1210. //adding up with already received
  1211. if (!empty($itemDetails) ){
  1212. if ($action == 'add'){
  1213. // for received goods
  1214. $savedValue = $itemDetails['received_value']; //this is the receipt line items total value
  1215. $savedQuantity= $itemDetails['received_quantity'];
  1216. //update new total
  1217. $received_value += $savedValue;
  1218. $received_quantity += $savedQuantity;
  1219. //for returned goods
  1220. $savedReturnedValue = $itemDetails['returned_value']; //this is the receipt line items total value
  1221. $savedReturnedQuantity= $itemDetails['returned_quantity'];
  1222. //update new total
  1223. $returned_value += $savedReturnedValue;
  1224. $returned_quantity += $savedReturnedQuantity;
  1225. }
  1226. }
  1227. $receipt_item_data['received_value'] = $received_value;
  1228. $receipt_item_data['received_quantity'] = $received_quantity;
  1229. $receipt_item_data['returned_value'] = $returned_value;
  1230. $receipt_item_data['returned_quantity'] = $returned_quantity;
  1231. $receipt_item_data['status'] = $line_status;
  1232. $receipt_item_data['ordered_quantity'] = $ordered_quantity;
  1233. //save receipt line item
  1234. if (empty($itemDetails)){
  1235. $this->Receipt_item->insert($receipt_item_data);
  1236. $id = $this->db->insert_id();
  1237. /* end insert */
  1238. /* update reference number in quote item */
  1239. $ref = 10000000 + $id;
  1240. $upd_data['reference']= $ref;
  1241. //if no batch number then reference is the batch number
  1242. if (empty($batch_number)){
  1243. $batch_number= $ref;
  1244. $upd_data['batch_number']=$batch_number;
  1245. }
  1246. $where_clause = array('id'=>$id);
  1247. $this->Receipt_item->update($where_clause, $upd_data );
  1248. }
  1249. else {
  1250. $this->Receipt_item->updateWithNotes(array('id'=>$itemDetails['id']),array('received_quantity'=>$received_quantity,'received_value'=>$received_value,'returned_quantity'=>$returned_quantity,
  1251. 'returned_value'=>$returned_value,'status'=>$line_status),$notes_array);
  1252. // $this->Receipt_item->updateWithoutEscape(array('id'=>$itemDetails['id']),'receiving_notes',$rcvd_note);
  1253. // $this->Receipt_item->updateWithoutEscape(array('id'=>$itemDetails['id']),'returned_notes',$rtrnd_note);
  1254. }
  1255. //if completed then update all the receipt line items with same order line id to "RECEIVED"
  1256. // as the parent order line id status is soon going to be set as "RECEIVED"
  1257. if ($line_status==self::RECEIVED){
  1258. $this->Receipt_item->update(array('order_line_id'=>$order_line_id),array('status'=>$line_status));
  1259. }
  1260. // update PO line with total value. Note This could be different from the received quantity
  1261. // as there could be multiple receipt line for a single order line
  1262. $this->Purchase_order_item->update(array('id'=>$order_line_id),array('received_quantity'=>$total_received_for_order,'received_value'=>$total_received_value_for_order,
  1263. 'returned_quantity'=>$total_returned_for_order,'returned_value'=>$total_returned_value_for_order,'status'=>$line_status,'matched'=>$order_line_item_matched));
  1264. //update Purchase Order So That It Can be Ready For Invoicing
  1265. $this->Purchase_order_master->update(array('id'=>$order_id),array('status'=>self::RECEIVING));
  1266. $this->db->trans_complete();
  1267. }
  1268. function registerUndelivered(){
  1269. $received_quantity = $_REQUEST["received_quantity"];
  1270. $cnbd_quantity = $_REQUEST['cnbd_quantity'];
  1271. $returned_quantity = $_REQUEST["returned_quantity"];
  1272. $ordered_quantity = $_REQUEST['ordered_quantity'];
  1273. if ($ordered_quantity == $received_quantity + $returned_quantity + $cnbd_quantity){
  1274. $order_line_item_matched = 1;
  1275. }
  1276. else {
  1277. $order_line_item_matched = 0;
  1278. }
  1279. $this->Purchase_order_item->update(array('id'=>$_REQUEST['order_line_id']),array('cnbd_quantity'=>$_REQUEST['cnbd_quantity'],'matched'=>$order_line_item_matched),array('cnbd_reason'=> appendComments($_REQUEST['cnbd_notes'], 'cnbd_reason')));
  1280. }
  1281. function populateReceiptOptions (){
  1282. $order_id= $_REQUEST['order_id'];
  1283. echo populateReceiptOptions($order_id);
  1284. }
  1285. function submitForApprovalBeforeInvoice (){
  1286. $receiptIds = $_REQUEST['receipt_ids'];
  1287. $this->db->trans_start();
  1288. foreach ($receiptIds as $receiptId){
  1289. $this->Receipt_master->update(array('id'=>$receiptId,'status'=>self::READYTOINVOICEMEMO),array('status'=>self::WAITING_FOR_APPROVAL));
  1290. $this->Receipt_item->update(array('receipt_id'=>$receiptId),array('status'=>self::WAITING_FOR_APPROVAL));
  1291. //we are not bothered about order status anymore. Goods are either received ok or returned and receipts are now processed for payments.
  1292. //So the final status of Purchase Order is REceiptssubmitted. After this only returned and received wuantities can change but the total received + returned
  1293. //is always going to be same as ordered quantity
  1294. ///$this->Purchase_order_master->update(array('id'=>$order_id),array('status'=>self::WAITING_FOR_APPROVAL));
  1295. //$this->Purchase_order_item->update(array('order_id'=>$order_id),array('status'=>self::WAITING_FOR_APPROVAL));
  1296. }
  1297. $this->db->trans_complete();
  1298. }
  1299. function markForInvoicing(){
  1300. $orderIds = $_REQUEST['orderIds'];
  1301. //very very important: Remember this means the end for order line level editing. Recap One Orderline
  1302. // can have multiple receipts and multiple receipt lines. So Theoratically Before This point
  1303. // it was possible to vary received /rejected at the receipt line items provided it does not exceed total
  1304. //order line quantity. For example a single order line with 10 Ordrd Qty can have 2 receipt lines
  1305. // Before this Point for two receipt lines it was possible to have different total of received rejected
  1306. //at receipt line level provided it does not exceed 10. But After This only Receipt Line Editing Is Possible
  1307. // That means if Total No Of recived and rejected for a receit line is 6.. total nmber of received and rejected
  1308. //can be varied but total # can not be changed from 6
  1309. foreach ($orderIds as $orderId){
  1310. $this->db->trans_start();
  1311. $this->Purchase_order_master->update(array('id'=>$orderId),array('status'=>self::RECEIPTSSUBMITTED));
  1312. $this->Purchase_order_item->update(array('order_id'=>$orderId),array('status'=>self::RECEIPTSSUBMITTED));
  1313. $this->Receipt_master->update(array('order_id'=>$orderId),array('status'=>self::READYTOINVOICEMEMO));
  1314. // update receipt line as invalid for partpayment where pp_quantity is still 0 while ready to invoice memo .
  1315. $this->Receipt_item->update(array('order_id'=>$orderId,'pp_quantity'=>0),array('status'=>self::NOTAPPLICABLE));
  1316. //$this->Receipt_master->update(array('order_id'=>$orderId,'status'=>self::RECEIVED),array('status'=>self::READYTOINVOICE));
  1317. //dont need to update recipt items here as these as the receipt is going to go tyhrough approval. Individual receipt items are not
  1318. // later all recipt items are either will be moved for invice or individual receipt items will be rejected and later corrected
  1319. // if rejected set the receipt aster status as rejected and individualreceipt item as rejected. Let only rejected receipt
  1320. //items to be modified
  1321. $this->db->trans_complete();
  1322. }
  1323. }
  1324. /*TODO: Manual Transaction */
  1325. function createInvoiceMemoUpdateOrderReceipt (){
  1326. $receiptIds = $_REQUEST['receipt_ids'];
  1327. $do_invoice = false;
  1328. $do_memo = false;
  1329. $order_id = $_REQUEST['order_id'];
  1330. $total_invoice_value = 0;
  1331. $total_memo_value = 0;
  1332. // lets see if we have inoice or memo to create. This is to take care of the border condition
  1333. // where either all are received or all are returned
  1334. if ($this->Receipt_item->getSumTotal('`received_quantity`-`pp_quantity`',null,array('field_name'=>'receipt_id','value_array'=>$receiptIds))>0){
  1335. $do_invoice = true;
  1336. }
  1337. if ($this->Receipt_item->getSumTotal('returned_quantity',null,array('field_name'=>'receipt_id','value_array'=>$receiptIds))>0){
  1338. $do_memo = true;
  1339. }
  1340. //if both are false there is a problem' Let the user know. There must be either rteturned or received
  1341. // normally user should never come across this error. The validations shpuld already take care pf that
  1342. if (!$do_invoice && !$do_memo){
  1343. echo 'error_both_zero';
  1344. return; //dont progress
  1345. }
  1346. // manual transaction for this
  1347. $this->db->trans_start();
  1348. $common_data=array('status'=>self::PENDING,'order_id'=>$order_id);
  1349. //,'owner_id'=>$this->user->person_id);
  1350. // we have received wuantities so lets create Invoice
  1351. if ($do_invoice){
  1352. $inv_ins_data = $common_data;
  1353. //$inv_ins_data['invoiced_by']=$this->user->person_id;
  1354. $newInvId = $this->createInvoice($inv_ins_data);
  1355. $newInvRef = 10000000 + $newInvId;
  1356. }
  1357. // we have returns wuantities so lets create Memo
  1358. if ($do_memo){
  1359. $inv_mem_data = $common_data;
  1360. $inv_mem_data['memo_by']=$this->user->person_id;
  1361. $newCreditMemoId = $this->createCreditmemo($inv_mem_data);
  1362. $newmemoRef = 10000000 + $newCreditMemoId;
  1363. }
  1364. $order_line_array_invoiced = array();
  1365. $order_line_array_memo = array();
  1366. foreach ($receiptIds as $receiptId){
  1367. // create Invoice items
  1368. $receipt_items = $this->Receipt_item->getAll(false,array('receipt_id'=>$receiptId),
  1369. array('sku','name','product_id','price','order_line_id','received_value','received_quantity','returned_value','returned_quantity'));
  1370. foreach ($receipt_items as $receipt_item){
  1371. $invoice_item_data = array();
  1372. $memo_item_data = array();
  1373. //common item data
  1374. // $item_data['sku'] = $receipt_item['sku'];
  1375. // $item_data['name'] = $receipt_item['name'];
  1376. $item_data['product_id'] = $receipt_item['product_id'];
  1377. $item_data['price'] = $receipt_item['price'];
  1378. $item_data['order_line_id'] = $receipt_item['order_line_id'];
  1379. $received_qty = $receipt_item['received_quantity'];
  1380. $returned_qty = $receipt_item['returned_quantity'];
  1381. $pp_quantity = $receipt_item['pp_quantity'];
  1382. $pp_value = $receipt_item['pp_value'];
  1383. //subtract part paid
  1384. $invoice_quantity = $received_qty-$pp_quantity;
  1385. // we are not checking "do" flags any more as anyway at this point we know receipt items
  1386. // must be having recvd or rtrnd other wise do flags would have failed
  1387. if ($invoice_quantity>0){
  1388. $invoice_item_data = $item_data;
  1389. $invoice_item_data['invoiced_quantity'] = $invoice_quantity;
  1390. $invoice_item_data['total_invoiced_value'] = $receipt_item['received_value']-$pp_value;
  1391. $invoice_item_data['invoice_id'] = $newInvId;
  1392. $this->Purchase_invoice_item->insert($invoice_item_data);
  1393. log_message('debug','insert statement ='.$this->db->last_query());
  1394. $id = $this->db->insert_id();
  1395. /* end insert */
  1396. /* update reference number in line item */
  1397. $where_clause = array('id'=>$id);
  1398. $this->Purchase_invoice_item->update($where_clause, array('reference' => 10000000 + $id));
  1399. // now prepare array to update order line items
  1400. if (array_key_exists($receipt_item['order_line_id'], $order_line_array_invoiced)){
  1401. // already exists .. that means in separate invoice item some of the quantity
  1402. //already invoiced.. get the old value add with the this invoice line items
  1403. // invoiced_quantity. push iit back to array
  1404. $oldvalue = $order_line_array_invoiced[$item_data['order_line_id']];
  1405. $order_line_array_invoiced[$item_data['order_line_id']] = $oldvalue + $received_qty;
  1406. }
  1407. else {
  1408. // first invoice item for this order line item
  1409. $order_line_array_invoiced[$item_data['order_line_id']] = $received_qty;
  1410. }
  1411. }
  1412. if ($returned_qty>0){
  1413. $memo_item_data = $item_data;
  1414. $memo_item_data['memo_quantity'] = $returned_qty;
  1415. $memo_item_data['total_memo_value'] = $receipt_item['returned_value'];
  1416. $memo_item_data['memo_id'] = $newCreditMemoId;
  1417. $this->Purchase_creditmemo_item->insert($memo_item_data);
  1418. log_message('debug','insert statement ='.$this->db->last_query());
  1419. $id = $this->db->insert_id();
  1420. /* end insert */
  1421. /* update reference number in line item */
  1422. $where_clause = array('id'=>$id);
  1423. $this->Purchase_creditmemo_item->update($where_clause, array('reference' => 10000000 + $id));
  1424. // now prepare array to update order line items
  1425. if (array_key_exists($receipt_item['order_line_id'], $order_line_array_memo)){
  1426. // already exists .. that means in separate invoice item some of the quantity
  1427. //already invoiced.. get the old value add with the this invoice line items
  1428. // invoiced_quantity. push iit back to array
  1429. $oldvaluememo = $order_line_array_memo[$item_data['order_line_id']];
  1430. $order_line_array_memo[$item_data['order_line_id']] = $oldvaluememo + $returned_qty;
  1431. }
  1432. else {
  1433. // first invoice item for this order line item
  1434. $order_line_array_memo[$item_data['order_line_id']] = $returned_qty;
  1435. }
  1436. }
  1437. }
  1438. //grab order line array .. update order line items
  1439. foreach ($order_line_array_invoiced as $key => $value){
  1440. $this->Purchase_order_item->update(array('id'=>$key),array('invoiced_quantity'=>$value));
  1441. }
  1442. foreach ($order_line_array_memo as $key => $value){
  1443. $this->Purchase_order_item->update(array('id'=>$key),array('memo_quantity'=>$value));
  1444. }
  1445. //calcultae total invoice value by receipt id
  1446. $total_invoice_value +=$this->Receipt_item->totalAmount($receiptId);
  1447. $total_memo_value +=$this->Receipt_item->getSumTotal('returned_value',array('receipt_id'=>$receiptId));
  1448. // as of now this is all or none.
  1449. //later add invoiced quantity
  1450. $this->Receipt_master->update(array('id'=>$receiptId),array('invoice_id'=>$newInvId,'memo_id'=>$newCreditMemoId,'status'=>self::PROCESSED_FOR_PAYMENT));
  1451. $this->Receipt_item->update(array('receipt_id'=>$receiptId),array('status'=>self::PROCESSED_FOR_PAYMENT));
  1452. }
  1453. if ($do_invoice){
  1454. $this->Purchase_invoice_master->update(array('id'=>$newInvId),array('total_value'=>$total_invoice_value));
  1455. }
  1456. if ($do_memo){
  1457. $this->Purchase_creditmemo_master->update(array('id'=>$newCreditMemoId),array('total_value'=>$total_memo_value));
  1458. }
  1459. //validate by order if invoicing complete
  1460. //first find order lines are received. If all order lines are received then there are entries in
  1461. //receipt line item table with all order line items. Next Se if all receipt Items with receipt ids
  1462. //with the order id are invoiced. If Invoiced then mark all order lines and the order as invoiced
  1463. //(Revisit This Later)
  1464. // $noOfRows = $this->Receipt_master()->totalNoOfRows(array('order_id'=>$order_id,'status'=>self::RECEIVED));
  1465. $this->db->trans_complete();
  1466. if (!empty($newInvId)){
  1467. $response['invoice_id'] = $newInvRef;
  1468. }
  1469. if (!empty($newCreditMemoId)){
  1470. $response['memo_id'] = $newmemoRef;
  1471. }
  1472. echo $response;
  1473. }
  1474. function createInvoice($invoiceData){
  1475. $this->Purchase_invoice_master->insert($invoiceData);
  1476. log_message('debug','insert statement ='.$this->db->last_query());
  1477. $id = $this->db->insert_id();
  1478. $where_clause = array('id'=>$id);
  1479. $this->Purchase_invoice_master->update($where_clause, array('reference' => 10000000 + $id));
  1480. log_message('debug','update statement ='.$this->db->last_query());
  1481. return $id;
  1482. }
  1483. function createCreditmemo($memoData){
  1484. $this->Purchase_creditmemo_master->insert($memoData);
  1485. log_message('debug','insert statement ='.$this->db->last_query());
  1486. $id = $this->db->insert_id();
  1487. $where_clause = array('id'=>$id);
  1488. $this->Purchase_creditmemo_master->update($where_clause, array('reference' => 10000000 + $id));
  1489. log_message('debug','update statement ='.$this->db->last_query());
  1490. return $id;
  1491. }
  1492. function registerPayment(){
  1493. $form_data = $_REQUEST['form_data'] ;
  1494. $total = $_REQUEST['total_value'] ;
  1495. $amount = $form_data['amount'] ;
  1496. $prevAmount = $form_data['prev_amount'] ;
  1497. $parentId = $form_data['parent_id'] ;
  1498. $invoice_id = $_REQUEST['invoice_id'];
  1499. $order_id = $_REQUEST['order_id'];
  1500. if (empty($invoice_id) && empty($order_id)){
  1501. echo 'error';
  1502. return;
  1503. }
  1504. if (!empty($invoice_id)){
  1505. $data['invoice_id'] = $invoice_id ;
  1506. }
  1507. if (!empty($order_id)){
  1508. $data['order_id'] = $order_id ;
  1509. }
  1510. $comment = appendComments( $form_data['comments'],'comments');
  1511. $oper = $form_data['oper_payment'] ;
  1512. $payment_id = $form_data['payment_id'] ;
  1513. $data['payment_reference'] = $form_data['payment_ref'] ;
  1514. $data['payment_mode'] = $form_data['payment_mode'] ;
  1515. $data['amount'] = $amount;
  1516. $type = $form_data['type_payment'] ;
  1517. // if (empty($type) && $oper != 'edit'){
  1518. // $type = 'general';
  1519. // }
  1520. if (!empty($type)){
  1521. $data['payment_type'] = $type ;
  1522. }
  1523. $total_invoiced = $_REQUEST['total_invoiced'];
  1524. if ($type==self::GENERAL){
  1525. $data['invoiced_amount'] = $form_data['amount'];
  1526. }
  1527. $this->db->trans_start();
  1528. if ($oper == 'add' || $oper == 'assign'){
  1529. $this->Outgoing_payment->insert($data,array('comments'=>$comment));
  1530. $id = $this->db->insert_id();
  1531. $where_clause = array('id'=>$id);
  1532. $update_data['reference'] = 10000000 + $id;
  1533. if ($oper == 'assign'){
  1534. //in case of advance payment record the parent child relationship. add the total invoiced
  1535. $update_data['parent_id'] = $payment_id;
  1536. $update_data['payment_type'] = self::GENERAL;
  1537. // $mapping_data['payment_id'] = $id;
  1538. // $update_data['has_advance'] = 1;
  1539. //$this->Outgoing_payment->createMapping($mapping_data);
  1540. $this->Outgoing_payment->update($where_clause, $update_data);
  1541. $this->Outgoing_payment->update(array('id'=>$payment_id), null,array('invoiced_amount'=>'invoiced_amount + '.$amount));
  1542. }
  1543. else {
  1544. $this->Outgoing_payment->update($where_clause, $update_data);
  1545. }
  1546. }
  1547. else if ($oper == 'edit'){
  1548. $this->Outgoing_payment->update(array('id'=>$payment_id),$data,array('comments'=>$comment));
  1549. if (!empty($parentId)){
  1550. // this was adjusted with advance: SO we need to adjust the advance row as well
  1551. $adj_amt = $amount - $prevAmount;
  1552. $this->Outgoing_payment->update(array('id'=>$parentId), null,array('invoiced_amount'=>'invoiced_amount + '.$adj_amt));
  1553. }
  1554. }
  1555. if ($type!='advance'){
  1556. if ($total_invoiced == $total){
  1557. $this->Purchase_invoice_master->update(array('id'=>$_REQUEST['invoice_id'] ),array('amount_paid'=>$total,'status'=>self::COMPLETE));
  1558. }
  1559. else {
  1560. $this->Purchase_invoice_master->update(array('id'=>$_REQUEST['invoice_id'] ),array('amount_paid'=>$total,'status'=>self::PARTIAL));
  1561. }
  1562. }
  1563. $this->db->trans_complete();
  1564. if ($this->db->trans_status()=== TRUE){
  1565. echo $total;
  1566. }
  1567. }
  1568. function getPaymentDetails(){
  1569. $pay_id = $_REQUEST['pay_id'];
  1570. $details = $this->Outgoing_payment->getByPaymentId($pay_id);
  1571. echo json_encode($details);
  1572. }
  1573. function populateAdvancePayments(){
  1574. echo json_encode(populateAdvancePayments($_REQUEST['order_id']));
  1575. }
  1576. function printInvoice(){
  1577. define('FPDF_FONTPATH',$this->config->item('fonts_path'));
  1578. //$this->load->library('fpdf','','fpdf');
  1579. //$this->load->library('table_pdf','','pdf');
  1580. // $this->load->library('rotation');
  1581. // $this->load->library('pdf','','pdf');
  1582. // $this->pdf->AddPage();
  1583. // $this->pdf->SetFont('Arial','B',16);
  1584. // $this->pdf->Cell(40,10,'Hello World!');
  1585. $header = array('Type', 'Payment Ref', 'Amount');
  1586. $data = $this->Outgoing_payment->getColumnValues(false,null,array('payment_type','payment_reference','amount'));
  1587. $this->pdf->SetFont('Arial','',14);
  1588. // $this->pdf->AddPage();
  1589. // $this->pdf->BasicTable($header,$data);
  1590. // $this->pdf->AddPage();
  1591. // $this->pdf->ImprovedTable($header,$data);
  1592. $this->pdf->AddPage();
  1593. $this->pdf->FancyTable($header,$data);
  1594. //$this->pdf->Output('/tmp/test'.time().'.pdf', 'F');
  1595. $this->pdf->Output('/tmp/test.pdf', 'F');
  1596. }
  1597. /* Invoice Grid Start */
  1598. function populateInvoicesToPay(){
  1599. $quotedata=array();
  1600. $where = array();
  1601. $in_where = array();
  1602. setOwnerStatusCommon($where,$in_where);
  1603. $griddata= populateGridCommon('Purchase_invoice_master',$where,null,$in_where);
  1604. $dbrows = $griddata['db_data'];
  1605. $data = $griddata['grid_metadata'];
  1606. foreach ($dbrows as $dp){
  1607. // $orderDetails = $this->Purchase_order_master->getGridById($dp['order_id']);
  1608. // $userDetails = $this->User->getUserInfo($dp['invoiced_by'],true);
  1609. array_push($quotedata, array('id'=> $dp['id'],'dprow' => array($dp['reference'],$dp['payment_process_type'],$dp['total_value'],$dp['amount_paid'],$dp['status'],$dp['payer_id'],$dp['payer_name'],$dp['owner_id'],$dp['owner_name'],$dp['order_id'],$dp['order_reference'])));
  1610. }
  1611. $data['quotedata'] = $quotedata;
  1612. echo json_encode($data);
  1613. }
  1614. function populateInvoiceItems(){
  1615. $invoiceId = $_REQUEST['invoiceId'];
  1616. if (!empty($invoiceId)){
  1617. $page = $_REQUEST['page'];
  1618. $limit = $_REQUEST['rows'];
  1619. $sidx = $_REQUEST['sidx'];
  1620. $sord = $_REQUEST['sord'];
  1621. //standard response parameters
  1622. $quotedata = array();
  1623. $where = array('invoice_id' => $invoiceId );
  1624. $count = $this->Purchase_invoice_item->totalNoOfRows($where);
  1625. if( $count > 0 && $limit > 0) {
  1626. $total_pages = ceil($count/$limit);
  1627. } else {
  1628. $total_pages = 0;
  1629. }
  1630. if ($page > $total_pages) $page=$total_pages;
  1631. $start = $limit*$page - $limit;
  1632. // if for some reasons start position is negative set it to 0
  1633. // typical case is that the user type 0 for the requested page
  1634. if($start <0) $start = 0;
  1635. $clauses = array('orderBy'=>$sidx,'orderDir'=>$sord,'startLimit'=>$start,'limit'=>$limit);
  1636. $data['total'] = $total_pages;
  1637. $data['page'] = $page;
  1638. $data['records'] = $count;
  1639. $quotes = $this->Purchase_invoice_item->getAll(false,$where);
  1640. foreach ($quotes as $dp){
  1641. //$order_line = $this->Purchase_order_item->getById($dp['order_line_id']);
  1642. array_push($quotedata, array('id'=> $dp['id'],'dprow' => array($dp['product_id'],$dp['name'],$dp['invoiced_quantity'],$dp['total_invoiced_value'])));
  1643. }
  1644. $data['invoiceitemdata'] = $quotedata;
  1645. echo json_encode($data);
  1646. }
  1647. }
  1648. //receipt approval
  1649. function loadReceiptsToApprove(){
  1650. $this->load->view("procurement/purchaseorder/approval/receipt_approval_grid",$data);
  1651. }
  1652. function rejectReceipt (){
  1653. $receiptId = $_REQUEST['receiptId'];
  1654. if (!empty($receiptId)){
  1655. $comment = appendComments( $_REQUEST['rejection_notes'],'rejection_notes');
  1656. $this->Receipt_master->update(array('id'=>$receiptId),array('status'=>self::REJECTED),array('rejection_notes'=>$comment));
  1657. }
  1658. }
  1659. function rejectReceiptLineItem (){
  1660. $receiptId = $_REQUEST['receiptId'];
  1661. if ($_REQUEST['multiple']){
  1662. // if multiple line items are rejected we are not updating rejection comments at line level
  1663. // we are adding at the receipt level
  1664. $receiptLineIds = $_REQUEST['receiptLineIds'];
  1665. $this->db->trans_start();
  1666. foreach ($receiptLineIds as $lineId){
  1667. $this->Receipt_item->update(array('id'=>$lineId),array('status'=>self::REJECTED));
  1668. }
  1669. $comment = appendComments( $_REQUEST['rejection_notes'],'rejection_notes');
  1670. $this->Receipt_master->update(array('id'=>$receiptId),array('status'=>self::REJECTED),array('rejection_notes'=>$comment));
  1671. $this->db->trans_complete();
  1672. }
  1673. else {
  1674. $receiptLineId = $_REQUEST['receiptLineId'];
  1675. $item_comment = appendComments( $_REQUEST['rejection_notes'],'rejection_notes');
  1676. $this->db->trans_start();
  1677. $this->Receipt_item->update(array('id'=>$receiptLineId),array('status'=>self::REJECTED),array('rejection_notes'=>$item_comment));
  1678. // update omment about single line item rejection
  1679. $comment = appendComments( 'Single Receipt Item Rejected.Check Notes At Line Item Level','rejection_notes');
  1680. $this->Receipt_master->update(array('id'=>$receiptId),array('status'=>self::REJECTED),array('rejection_notes'=>$comment));
  1681. $this->db->trans_complete();
  1682. }
  1683. }
  1684. //end approval grid
  1685. //start rejected grid
  1686. //receipt approval
  1687. function loadRejectedReceipts(){
  1688. $this->load->view("procurement/purchaseorder/rejected/receipt_rejected_grid",$data);
  1689. }
  1690. function resubmitReceiptLineItem(){
  1691. $receiptLineId =$_REQUEST["receiptLineId"];
  1692. $receiptId =$_REQUEST["receiptId"];
  1693. $item_data['received_quantity'] = $_REQUEST["received_quantity"];
  1694. $item_data['received_value'] = $_REQUEST["received_value"];
  1695. $item_data['returned_quantity'] = $_REQUEST["returned_quantity"];
  1696. $item_data['returned_value'] = $_REQUEST["returned_value"];
  1697. $item_data['status'] = self::WAITING_FOR_APPROVAL;
  1698. $returned_notes =$_REQUEST["returned_notes"];
  1699. $receiving_notes =$_REQUEST["receiving_notes"];
  1700. if (empty($receiving_notes)){
  1701. $receiving_notes = 'Resubmitting For Approval';
  1702. }
  1703. if (empty($returned_notes)){
  1704. $returned_notes = 'Resubmitting For Approval';
  1705. }
  1706. $notes['receiving_notes'] = appendComments($receiving_notes,'receiving_notes');
  1707. $notes['returned_notes'] = appendComments( $returned_notes,'returned_notes');
  1708. //$this->db->trans_start();
  1709. $this->Receipt_item->update(array('id'=>$receiptLineId,'status'=>self::REJECTED),$item_data,$notes);
  1710. //$this->db->trans_complete();
  1711. }
  1712. function resubmitReceipts(){
  1713. $receiptIds =$_REQUEST["receipt_ids"];
  1714. $still_rejected_receipts = array();
  1715. $success_receipts = array();
  1716. foreach($receiptIds as $receiptId){
  1717. // get the # of receipt line items for this receipt which are at rejected state
  1718. $still_rejected_state =$this->Receipt_item->totalNoOfRows(array('receipt_id'=>$receiptId,'status'=>self::REJECTED));
  1719. // if still there are line items in rejected state dont set the stuus to waitingforaprroval i.e. for reapproval
  1720. if ($still_rejected_state>0){
  1721. array_push($still_rejected_receipts, $this->Receipt_master->getById($receiptId,array('reference'))->reference);
  1722. }
  1723. else {
  1724. $this->Receipt_master->update(array('id'=>$receiptId),array('status'=>self::WAITING_FOR_APPROVAL));
  1725. array_push($success_receipts, $this->Receipt_item->getById($receiptId,array('reference'))->reference);
  1726. }
  1727. }
  1728. if (!empty($success_receipts)){
  1729. $response['success'] = $success_receipts;
  1730. }
  1731. if (!empty($still_rejected_receipts)){
  1732. $response['failed'] = $still_rejected_receipts;
  1733. }
  1734. echo json_encode($response);
  1735. }
  1736. function loadPricelist(){
  1737. $data['supplierOptions']= populateSuppliers();
  1738. $data['productOptions'] = $this->getProductsDropDown();
  1739. $data['supplierPriceListOptions'] = populateBaseContracts();
  1740. $this->load->view('pricelist/define_pricelist',$data);
  1741. }
  1742. function createPricelist(){
  1743. $id = $_REQUEST['pricelistId'];
  1744. $ischanged = $_REQUEST['ischanged'];
  1745. $pricelist_data['name'] = $_REQUEST['name'];
  1746. $pricelist_data['type'] = $_REQUEST['typeOp'];
  1747. $type =$_REQUEST['typeOp'];
  1748. $supplierPriceListOp = $_REQUEST['supplierPriceListOp'];
  1749. $rootPriceListOp = $_REQUEST['rootPriceListOp'];
  1750. if ($type==parent::SUPPLIERPRICELIST){
  1751. //$pricelist_data['parent'] = $rootPriceListOp;
  1752. $pricelist_data['supplier_id'] = $_REQUEST['supplierOp'];
  1753. $pricelist_data['name'] = trim($_REQUEST['supplierName']).'- Base Rate Contract';
  1754. }
  1755. else if ($type==parent::VERSION){
  1756. $pricelist_data['parent'] = $supplierPriceListOp;
  1757. $parentDetails = $this->Pricelist_master->getById($supplierPriceListOp,array('supplier_id','name'),true);
  1758. $pricelist_data['supplier_id'] = $parentDetails['supplier_id'];
  1759. $pricelist_data['version'] = $this->Pricelist_master->getByHighestVersion($supplierPriceListOp)+1;
  1760. $validfromdateObj = DateTime::createFromFormat('d/m/Y', $_REQUEST['validfrom']);
  1761. log_message('debug','converted '.$validfromdateObj->format('Y-m-d'));
  1762. $pricelist_data['valid_from'] = $validfromdateObj->format('Y-m-d');
  1763. $validtodateObj = DateTime::createFromFormat('d/m/Y', $_REQUEST['validto']);
  1764. log_message('debug','converted '.$validtodateObj->format('Y-m-d'));
  1765. $pricelist_data['valid_to'] = $validtodateObj->format('Y-m-d');
  1766. $pricelist_data['name'] = " V ".$pricelist_data['version']." ".$parentDetails['name'];
  1767. }
  1768. if (empty($id)){
  1769. $this->Pricelist_master->insert($pricelist_data);
  1770. $id = $this->db->insert_id();
  1771. }
  1772. else {
  1773. if ($ischanged){
  1774. $where_clause = array('id'=>$id);
  1775. if ($type == parent::VERSION){
  1776. $edit_data['valid_from'] = $pricelist_data['valid_from'];
  1777. $edit_data['valid_to'] = $pricelist_data['valid_to'];
  1778. }
  1779. $edit_data['active'] = $_REQUEST['isactive'];
  1780. $this->Pricelist_master->update($where_clause, $edit_data);
  1781. }
  1782. }
  1783. echo $id;
  1784. }
  1785. function addSupplierRate(){
  1786. $supplier_rate_list['base_price']= $_REQUEST['product_price'];
  1787. $supplier_rate_list['pricelist_id']= $_REQUEST['pricelist_id'];
  1788. $products = $_REQUEST['productOptions'];
  1789. $this->db->trans_start();
  1790. foreach($products as $product) {
  1791. $supplier_rate_list['product_id']=$product;
  1792. $this->Supplier_rate_items->insert($supplier_rate_list);
  1793. }
  1794. $discount= $_REQUEST['discount_value'];
  1795. // non empty discount means rule exists
  1796. //so call add Supllier Rule
  1797. if (!empty($discount)){
  1798. $ruleMessage = $this->addSupplierRule(true);
  1799. }
  1800. $this->db->trans_complete();
  1801. if ($this->db->trans_status()===FALSE){
  1802. $response = " The Operation Could Not Be Completed Due To Internal Error";
  1803. }
  1804. else {
  1805. $response = " Rates Are Succesfully Added For Selected Products";
  1806. if(!empty($ruleMessage)){
  1807. $response = $response .'/n/'.$ruleMessage;
  1808. }
  1809. }
  1810. echo $response;
  1811. }
  1812. function addSupplierRule($isInternal=false){
  1813. $app= $_REQUEST['apply_to_all'];
  1814. $supplier_rule_list['discount_type']= $_REQUEST['discount_type'];
  1815. $supplier_rule_list['discount_value']= $_REQUEST['discount_value'];
  1816. $supplier_rule_list['operator']= $_REQUEST['operator'];
  1817. $supplier_rule_list['qualifier_value_point']= $_REQUEST['qualifier_value'];
  1818. $supplier_rule_list['qualifier_value_from']= $_REQUEST['qualifier_value_from'];
  1819. $supplier_rule_list['qualifier_value_to']= $_REQUEST['qualifier_value_to'];
  1820. //$supplier_rate_list['base_price']= $_REQUEST['product_price'];
  1821. $supplier_rule_list['discount_type']= $_REQUEST['discount_type'];
  1822. $supplier_rule_list['qualifier']= $_REQUEST['qualifier'];
  1823. $supplier_rule_list['pricelist_id']= $_REQUEST['pricelist_id'];
  1824. $action = $_REQUEST['action'];
  1825. $precedencechanged= $_REQUEST['precedencechanged'];
  1826. $oldprecedence= $_REQUEST['oldprecedence'];
  1827. $shiftneeded = false;
  1828. if ($action=='edit_rule'){
  1829. $products = array($_REQUEST['product_id']);
  1830. }
  1831. else {
  1832. $products = $_REQUEST['productOptions'];
  1833. }
  1834. $precedence = $_REQUEST['precedence'];
  1835. $rule_id = $_REQUEST['rule_id'];
  1836. if (!$isInternal){
  1837. $this->db->trans_start();
  1838. }
  1839. foreach($products as $product) {
  1840. $supplier_rule_list['product_id']=$product;
  1841. // if called from rate API we are already inside an transaction. So dont start a txn
  1842. ///if precedence not specified find the highest. add one
  1843. if (empty($precedence)){
  1844. // if edit and precedence is blank that means an existing precedence is going to be set as lowest precendence. So
  1845. //we have to reaarange
  1846. if ($action=='edit_rule'){
  1847. $shiftneeded = true;
  1848. }
  1849. $supplier_rule_list['precedence'] = $this->Pricelist_rules->getHighestPrecedence($_REQUEST['pricelist_id'],$product)+1;
  1850. }
  1851. //else validate rearramge if required
  1852. else{
  1853. if ($precedencechanged!=0){
  1854. if ($this->validatePrecedence($_REQUEST['pricelist_id'],$product,$precedence,$action,$oldprecedence)){
  1855. $newPrecedence = $_REQUEST['precedence']+1;
  1856. $supplier_rule_list['precedence']= $newPrecedence;
  1857. $response ="The Precedence # Already Existed.So Next Lower Precedent ".$newPrecedence." Is Attached To The Rule. Rules With Lower Precedences Have Been Lowered By One ";
  1858. }
  1859. else {
  1860. $supplier_rule_list['precedence']= $precedence;
  1861. $response ="The Precedence # $precedence Will Be Assigned.";
  1862. }
  1863. }
  1864. }
  1865. if ($action=='edit_rule'){
  1866. $this->Pricelist_rules->update(array('id'=>$rule_id),$supplier_rule_list);
  1867. //if shift needed shift one back
  1868. if ($shiftneeded){
  1869. $this->Pricelist_rules->update(array('precedence > '=>$oldprecedence),null,array('precedence'=>'precedence - 1'));
  1870. }
  1871. }
  1872. else{
  1873. $this->Pricelist_rules->insert($supplier_rule_list);
  1874. }
  1875. }
  1876. if (!$isInternal){
  1877. $this->db->trans_complete();
  1878. }
  1879. if (!$isInternal){
  1880. if ($this->db->trans_status()===FALSE){
  1881. $response = " The Operation Could Not Be Completed Due To Internal Error";
  1882. }
  1883. }
  1884. if (!$isInternal){
  1885. echo $response;
  1886. }
  1887. else return $response;
  1888. }
  1889. function validatePrecedence($pricelist_id,$product_id,$precedence,$action,$oldprecedence){
  1890. $incrementprecedence = false;
  1891. if (!empty($precedence)){
  1892. $where_clause = array('pricelist_id'=>$pricelist_id,'product_id'=>$product_id,'precedence'=>$precedence);
  1893. $precedencelist= $this->Pricelist_rules->getAll(false,$where_clause,array('id'));
  1894. //this Precedence Already Exists. So We have To Re Arrange The Precedence
  1895. if (!empty($precedencelist)){
  1896. if ($action =='add_rule'){
  1897. $this->Pricelist_rules->update(array('precedence > '=>$precedence),null,array('precedence'=>'precedence + 1'));
  1898. $incrementprecedence = true;
  1899. }
  1900. else if ($action =='edit_rule'){
  1901. if ($precedence<$oldprecedence){
  1902. $this->Pricelist_rules->update(array('precedence >= '=>$precedence,'precedence < '=>$oldprecedence),null,array('precedence'=>'precedence + 1'));
  1903. }
  1904. else if ($precedence>$oldprecedence){
  1905. $this->Pricelist_rules->update(array('precedence <= '=>$precedence,'precedence > '=>$oldprecedence),null,array('precedence'=>'precedence - 1'));
  1906. }
  1907. }
  1908. }
  1909. }
  1910. return $incrementprecedence;
  1911. }
  1912. function populatePriceLists(){
  1913. $gridrowdata=array();
  1914. $griddata= populateGridCommon('Pricelist_master');
  1915. $dbrows = $griddata['db_data'];
  1916. $data = $griddata['grid_metadata'];
  1917. foreach ($dbrows as $dbrow){
  1918. //$order_line = $this->Purchase_order_item->getById($dp['order_line_id']);
  1919. array_push($gridrowdata, array('id'=> $dbrow['id'],'dprow' => array($dbrow['name'],$dbrow['parent_name'],$dbrow['supplier_id'],$dbrow['supplier_name'],$dbrow['valid_from'],$dbrow['valid_to'],$dbrow['active'],$dbrow['type'],$dbrow['version'])));
  1920. }
  1921. $data['pricelistdata'] = $gridrowdata;
  1922. echo json_encode($data);
  1923. }
  1924. function populatePriceData(){
  1925. $page = $_REQUEST['page'];
  1926. $limit = $_REQUEST['rows'];
  1927. $sidx = $_REQUEST['sidx'];
  1928. $sord = $_REQUEST['sord'];
  1929. $searchOn = $_REQUEST['_search'];
  1930. //$where['active'] = 1;
  1931. $pricelist_id = $_REQUEST['pricelist_id'];
  1932. $supplier_id = $_REQUEST['supplier_id'];
  1933. //standard response parameters
  1934. $pricelistdata = array();
  1935. //$where = array();
  1936. $count = $this->Supplier_rate_items->getAllUnion(null,$pricelist_id,$supplier_id,null,null,null,true);
  1937. if( $count > 0 && $limit > 0) {
  1938. $total_pages = ceil($count/$limit);
  1939. } else {
  1940. $total_pages = 0;
  1941. }
  1942. if ($page > $total_pages) $page=$total_pages;
  1943. $start = $limit*$page - $limit;
  1944. // if for some reasons start position is negative set it to 0
  1945. // typical case is that the user type 0 for the requested page
  1946. if($start <0) $start = 0;
  1947. $clauses = array('orderBy'=>$sidx,'orderDir'=>$sord,'startLimit'=>$start,'limit'=>$limit);
  1948. $data['total'] = $total_pages;
  1949. $data['page'] = $page;
  1950. $data['records'] = $count;
  1951. if($searchOn=='true') {
  1952. $filters = json_decode($_REQUEST['filters'],true);
  1953. $groupOp = $filters['groupOp'];
  1954. $rules = $filters['rules'];
  1955. $like_condition = array();
  1956. foreach ($rules as $rule){
  1957. $field = $rule['field'];
  1958. $op= $rule['op'];
  1959. $input = $rule['data'];
  1960. $like_condition[$field] = trim($input);
  1961. }
  1962. $pricelists = $this->Supplier_rate_items->getAllUnion(array('id','lineitem_id','barcode','product_name','product_id','manufacturer','model','base_price','pricelist_id'),$pricelist_id,$supplier_id,null,$clauses,$like_condition,false);
  1963. }
  1964. else {
  1965. $pricelists = $this->Supplier_rate_items->getAllUnion(array('id','lineitem_id','barcode','product_name','product_id','manufacturer','model','base_price','pricelist_id'),$pricelist_id,$supplier_id,null,$clauses);
  1966. }
  1967. foreach ($pricelists as $dp){
  1968. //$order_line = $this->Purchase_order_item->getById($dp['order_line_id']);
  1969. $base_price= "Not Defined";
  1970. if (!empty($dp['base_price'])){
  1971. $base_price = $dp['base_price'];
  1972. }
  1973. if ($dp['pricelist_id']!=0 ){
  1974. if ($dp['pricelist_id']!=$pricelist_id){
  1975. $inherited= "Yes";
  1976. }
  1977. else {
  1978. $inherited= "No";
  1979. }
  1980. }
  1981. else {
  1982. $inherited = "NA";
  1983. }
  1984. array_push($pricelistdata, array('id'=> $dp['id'],'dprow' => array($dp['lineitem_id'],$dp['barcode'],$dp['product_name'],$dp['product_id'],$dp['manufacturer'],$dp['model'],$base_price,$inherited)));
  1985. }
  1986. $data['ratecontractdata'] = $pricelistdata;
  1987. echo json_encode($data);
  1988. }
  1989. function editPrice(){
  1990. $lineitem_id = $_REQUEST['lineitem_id'];
  1991. $price = $_REQUEST['price'];
  1992. if (!empty($lineitem_id) && !empty($price)){
  1993. $this->Supplier_rate_items->update(array('id'=>$lineitem_id),array('base_price'=>$price));
  1994. echo "success";
  1995. }
  1996. else {
  1997. echo "notupdated";
  1998. }
  1999. }
  2000. function deletePrice(){
  2001. $lineitem_id = $_REQUEST['id'];
  2002. if (!empty($lineitem_id) ){
  2003. $this->Supplier_rate_items->delete($lineitem_id);
  2004. echo "success";
  2005. }
  2006. else {
  2007. echo "notupdated";
  2008. }
  2009. }
  2010. function ruleUnionTest(){
  2011. var_dump($this->Pricelist_rules->getAllUnion());
  2012. }
  2013. function applyPriceRules(){
  2014. $where['active'] = 1;
  2015. $where['pricelist_id'] = $_REQUEST['pricelist_id'];
  2016. $where['product_id'] = $_REQUEST['product_id'];
  2017. $inherit_rules = $_REQUEST['inherit_rules'];
  2018. $inherit_rules_dir = $_REQUEST['inherit_rules_dir'];
  2019. $unit_price = $_REQUEST['unit_price'];
  2020. $quantity = $_REQUEST['quantity'];
  2021. // $where['pricelist_id'] = 19;
  2022. // $where['product_id'] =17;
  2023. // $unit_price = 20;
  2024. // $quantity = 10;
  2025. $clauses = array('orderDir'=>$inherit_rules_dir);
  2026. $discounted_price = $unit_price;
  2027. $free_quantity = 0;
  2028. if ($inherit_rules== parent::NONE){
  2029. $rules= $this->Pricelist_rules->getAll(false,$where,null,array('orderBy'=>'precedence','orderDir'=>'asc'));
  2030. }
  2031. else if ($inherit_rules== parent::ALL){
  2032. $rules = $this->Pricelist_rules->getAllUnion($where,false,$clauses);
  2033. }
  2034. else if ($inherit_rules== parent::SOME){
  2035. $rules = $this->Pricelist_rules->getSomeUnion($where,false,$clauses);
  2036. }
  2037. //
  2038. if ($discounted_price!=0){
  2039. foreach ($rules as $rule){
  2040. $qual = $rule['qualifier'];
  2041. $op = $rule['operator'];
  2042. $discount_type= $rule['discount_type'];
  2043. $discount_value= $rule['discount_value'];
  2044. if ($qual=='product'){
  2045. $this->calculateDiscount($discount_type,$discount_value,$discounted_price,$free_quantity);
  2046. }
  2047. else if ($qual=='quantity'){
  2048. $valuepoint = $rule['qualifier_value_point'];
  2049. if ($op=='between'){
  2050. $valuefrom = $rule['qualifier_value_from'];
  2051. $valueto = $rule['qualifier_value_to'];
  2052. if ($quantity >= $valuefrom&& $quantity<=$valueto){
  2053. $this->calculateDiscount($discount_type,$discount_value,$discounted_price,$free_quantity);
  2054. }
  2055. }
  2056. else if ($op=='equal'){
  2057. if ($quantity == $valuepoint){
  2058. $this->calculateDiscount($discount_type,$discount_value,$discounted_price,$free_quantity);
  2059. }
  2060. }
  2061. else if ($op=='more'){
  2062. if ($quantity >= $valuepoint){
  2063. $this->calculateDiscount($discount_type,$discount_value,$discounted_price,$free_quantity);
  2064. }
  2065. }
  2066. else if ($op=='less'){
  2067. if ($quantity <= $valuepoint){
  2068. $this->calculateDiscount($discount_type,$discount_value,$discounted_price,$free_quantity);
  2069. }
  2070. }
  2071. }
  2072. }
  2073. }
  2074. $data['final_unit_price'] = $discounted_price;
  2075. $data['free_items'] = $free_quantity;
  2076. echo json_encode($data);
  2077. }
  2078. function calculateDiscount($discount_type,$discount_value,&$discounted_price,&$free_quantity){
  2079. if ($discount_type=='flat'){
  2080. $discount = $discount_value;
  2081. $discounted_price -=$discount;
  2082. if ($discounted_price<0){
  2083. $discounted_price = 0;
  2084. }
  2085. }
  2086. else if ($discount_type=='percentage'){
  2087. // aappy on base price or discounted price
  2088. $discount = $discount_value*$discounted_price/100;
  2089. $discounted_price -=$discount;
  2090. if ($discounted_price<0){
  2091. $discounted_price = 0;
  2092. }
  2093. }
  2094. else if ($discount_type=='free'){
  2095. // aappy on base price or discounted price
  2096. $free_quantity += $discount_value;
  2097. }
  2098. }
  2099. function populatePriceRules(){
  2100. $pricerulesdata=array();
  2101. //default
  2102. $pricelist_id = $_REQUEST['pricelist_id'];
  2103. $product_id = $_REQUEST['product_id'];
  2104. $inherit_rules = $_REQUEST['inherit_rules'];
  2105. $inherit_rules_dir = $_REQUEST['inherit_rules_dir'];
  2106. $where['active'] = 1;
  2107. $where['pricelist_id'] = $pricelist_id;
  2108. $where['product_id'] = $product_id;
  2109. $page = $_REQUEST['page'];
  2110. $limit = $_REQUEST['rows'];
  2111. $sidx = $_REQUEST['sidx'];
  2112. $sord = $_REQUEST['sord'];
  2113. if (empty($inherit_rules)){$inherit_rules = parent::NONE;}
  2114. //$count;
  2115. if ($inherit_rules== parent::NONE){
  2116. $count= $this->Pricelist_rules->totalNoOfRows($where);
  2117. }
  2118. else if ($inherit_rules== parent::ALL){
  2119. $sord = $inherit_rules_dir;
  2120. $count = $this->Pricelist_rules->getAllUnion($where,true);
  2121. }
  2122. else if ($inherit_rules== parent::SOME){
  2123. $sord = $inherit_rules_dir;
  2124. $count = $this->Pricelist_rules->getSomeUnion($where,true);
  2125. }
  2126. //standard response parameters
  2127. if( $count > 0 && $limit > 0) {
  2128. $total_pages = ceil($count/$limit);
  2129. } else {
  2130. $total_pages = 0;
  2131. }
  2132. if ($page > $total_pages) $page=$total_pages;
  2133. $start = $limit*$page - $limit;
  2134. // if for some reasons start position is negative set it to 0
  2135. // typical case is that the user type 0 for the requested page
  2136. if($start <0) $start = 0;
  2137. $clauses = array('orderBy'=>$sidx,'orderDir'=>$sord,'startLimit'=>$start,'limit'=>$limit);
  2138. $data['total'] = $total_pages;
  2139. $data['page'] = $page;
  2140. $data['records'] = $count;
  2141. //$dbrows;
  2142. if ($inherit_rules== parent::NONE){
  2143. //constant
  2144. $clauses['orderBy'] ='precedence';
  2145. $clauses['orderDir'] ='asc';
  2146. $dbrows= $this->Pricelist_rules->getAll(false,$where,null,$clauses);
  2147. }
  2148. else if ($inherit_rules== parent::ALL){
  2149. $dbrows = $this->Pricelist_rules->getAllUnion($where,false,$clauses);
  2150. }
  2151. else if ($inherit_rules== parent::SOME){
  2152. $dbrows = $this->Pricelist_rules->getSomeUnion($where,false,$clauses);
  2153. }
  2154. foreach ($dbrows as $dbrow){
  2155. //$order_line = $this->Purchase_order_item->getById($dp['order_line_id']);
  2156. if ($dbrow['operator']==self::BETWEEN){
  2157. $condition = $dbrow['qualifier'].' Ranges '.$dbrow['qualifier_value_from'].'-'.$dbrow['qualifier_value_to'];
  2158. }
  2159. else if ($dbrow['operator']==self::MORETHAN){
  2160. $condition = $dbrow['qualifier'].' Is More Than '.$dbrow['qualifier_value_point'];
  2161. }
  2162. else if ($dbrow['operator']==self::LESSTHAN){
  2163. $condition = $dbrow['qualifier'].' Is Less Than '.$dbrow['qualifier_value_point'];
  2164. }
  2165. else if ($dbrow['operator']==self::EQUAL){
  2166. $condition = $dbrow['qualifier'].' Is Equal To '.$dbrow['qualifier_value_point'];
  2167. }
  2168. if ($dbrow['qualifier'] ==self::PRODUCT){
  2169. $condition = 'The Product Is '.$dbrow['product_name'];
  2170. }
  2171. if ($dbrow['pricelist_id']!=0 ){
  2172. if ($dbrow['pricelist_id']!=$pricelist_id){
  2173. $inherited= "Yes";
  2174. }
  2175. else {
  2176. $inherited= "No";
  2177. }
  2178. }
  2179. array_push($pricerulesdata, array('id'=> $dbrow['id'],'dprow' => array(/*$dp['product_name'],*/$dbrow['rule_type'],$inherited,$dbrow['precedence'],$dbrow['qualifier'],$condition,$dbrow['discount_type'],$dbrow['discount_value'],$dbrow['operator'],$dbrow['qualifier_value_from'],$dbrow['qualifier_value_to'],$dbrow['qualifier_value_point'])));
  2180. }
  2181. $data['rulesdata'] = $pricerulesdata;
  2182. echo json_encode($data);
  2183. }
  2184. function getAllProductsDropDownForSupplier(){
  2185. echo populateProductsBySupplier($_REQUEST['supplier_id']);
  2186. }
  2187. function getProductsToAddRateDropDown(){
  2188. $where['pricelist_id'] = $_REQUEST['pricelist_id'];
  2189. $listed_products = $this->Supplier_rate_items->getAll(false,$where,array('product_id'));
  2190. $listed_array = array();
  2191. foreach ($listed_products as $product){
  2192. array_push($listed_array, $product['product_id']);
  2193. }
  2194. $not_in_where_clause = array('field_name'=>'product_id','value_array'=>$listed_array);
  2195. $not_listed_products = $this->Supplier->getAllProductsSupplierMapping(false, null, array('product_id','product_name','manufacturer','model','measurement_denomination','uom','barcode'), array('orderBy'=>'product_id'), null, null, null,$not_in_where_clause);
  2196. foreach ($not_listed_products as $product){
  2197. $id = $product['product_id'];
  2198. $name = $product['product_name'].', '.$product['barcode'].', '.$product['manufacturer'].' '.$product['model']
  2199. .' '.$product['measurement_denomination'].' '.$product['uom'];
  2200. $productOptions.="<OPTION VALUE=\"$id\">".$name;
  2201. }
  2202. echo $productOptions;
  2203. }
  2204. function loadRFQGrid (){
  2205. $data['productOptions'] = $this->getProductsDropDown();
  2206. $deliveryPoints = $this->Delivery_point->getAll();
  2207. foreach($deliveryPoints as $deliveryPoint) {
  2208. $id=$deliveryPoint["id"];
  2209. $thing=$deliveryPoint["name"];
  2210. $options.="<OPTION VALUE=\"$id\">".$thing;
  2211. }
  2212. $data['warehouseOptions']=$options;
  2213. $data['supplierOptions']= populateSuppliers();
  2214. $this->load->view("procurement/quote/request/quote_request_grid",$data);
  2215. }
  2216. function loadRFQFormFragment(){
  2217. $deliveryPoints = $this->Delivery_point->getAll();
  2218. foreach($deliveryPoints as $deliveryPoint) {
  2219. $id=$deliveryPoint["id"];
  2220. $thing=$deliveryPoint["name"];
  2221. $options.="<OPTION VALUE=\"$id\">".$thing;
  2222. }
  2223. $data['warehouseOptions']=$options;
  2224. $data['supplierOptions']= populateSuppliers();
  2225. $this->load->view("procurement/quote/request/request_details",$data);
  2226. }
  2227. function loadRFQNotesFragment(){
  2228. $this->load->view("procurement/quote/request/request_notes",$data);
  2229. }
  2230. function populateQuotes(){
  2231. $quotedata=array();
  2232. $status = $_REQUEST['_status'];
  2233. $where = array();
  2234. $in_where = array();
  2235. setOwnerStatusCommon($where,$in_where);
  2236. $griddata= populateGridCommon('Purchase_quote_master',$where,null,$in_where);
  2237. $dbrows = $griddata['db_data'];
  2238. $data = $griddata['grid_metadata'];
  2239. foreach ($dbrows as $dp){
  2240. // if ($status==self::WAITING_FOR_APPROVAL){
  2241. // /* we dont need actions column in approval grid . So not passing the blank */
  2242. // array_push($quotedata, array('id'=> $dp['id'],'dprow' => array($dp['reference'],$dp['supplier_name'],$dp['estimated_value'],$dp['status'],$dp['raised_by_name'],$dp['owner_name'],$dp['needed_by_date'])));
  2243. // }
  2244. // else if ($status==self::REJECTED){
  2245. // /* Add Extra Columns Rejected and Rejected Notes Remove Status */
  2246. // array_push($quotedata, array('id'=> $dp['id'],'dprow' => array($dp['reference'],$dp['supplier_name'],$dp['estimated_value'],$dp['raised_by_name'],$dp['owner_name'],$dp['needed_by_date'],$dp['approved_by_name'],$dp['approval_notes'])));
  2247. // }
  2248. if ($status==self::OPEN){
  2249. array_push($quotedata, array('id'=> $dp['id'],'dprow' => array($dp['reference'],$dp['rfq_reference'],$dp['supplier_name'],$dp['estimated_value'],$dp['discount_type'],$dp['discount_value'],$dp['pricelist_id'],$dp['discount_amount'],$dp['final_total'],$dp['status'],$dp['raised_by_name'],$dp['owner_name'],$dp['needed_by_date'],$dp['supplier_id'],$dp['warehouse_id'])));
  2250. }
  2251. else if (is_array($status) || $status==self::WAITING_FOR_APPROVAL){
  2252. array_push($quotedata, array('id'=> $dp['id'],'dprow' => array($dp['reference'],$dp['rfq_reference'],$dp['supplier_name'],$dp['estimated_value'],$dp['discount_type'],$dp['discount_value'],$dp['pricelist_id'],$dp['discount_amount'],$dp['final_total'],$dp['owner_id'],$dp['status'],$dp['raised_by_name'],$dp['owner_name'],$dp['needed_by_date'],$dp['approved_by_name'],$dp['supplier_id'],$dp['warehouse_id'],$dp['approved_by'])));
  2253. }
  2254. else {
  2255. array_push($quotedata, array('id'=> $dp['id'],'dprow' => array($dp['reference'],$dp['supplier_name'],$dp['estimated_value'],$dp['status'],$dp['raised_by_name'],$dp['owner_name'],$dp['needed_by_date'],$dp['notes'],$dp['approved_by_name'],$dp['approval_notes'])));
  2256. }
  2257. }
  2258. $data['quotedata'] = $quotedata;
  2259. echo json_encode($data);
  2260. }
  2261. private function generateQuoteInternal($rfq_details){
  2262. $id=$rfq_details['id'];
  2263. $quote_data['owner_id'] = $rfq_details['owner_id'];
  2264. $quote_data['supplier_id'] = $rfq_details['supplier_id'];
  2265. $quote_data['warehouse_id'] = $rfq_details['warehouse_id'];
  2266. $quote_data['needed_by_date'] = $rfq_details['needed_by_date'];
  2267. $quote_data['raised_by'] = $this->user->person_id;
  2268. $quote_data['rfq_id'] = $rfq_details['id'];
  2269. log_message('debug',json_encode($quote_data));
  2270. $quote_id = $this->Purchase_quote_master->createQuote($quote_data);
  2271. log_message('debug',$this->db->last_query());
  2272. $this->Request_quote_master->update(array('id'=>$id),array('status'=>self::SUBMITTEDTOQUOTE,'quote_id'=>$quote_id));
  2273. log_message('debug',$this->db->last_query());
  2274. //now update line item status
  2275. $item_details=$this->Request_quote_item->getByQuoteId($id);
  2276. foreach ($item_details as $item_data){
  2277. if ($item_data['status'] == self::OPEN || $item_data['status'] == self::WAITING_FOR_APPROVAL){
  2278. $quote_item_data['name'] = $item_data['name'];
  2279. $quote_item_data['sku'] = $item_data['sku'];
  2280. $quote_item_data['product_id'] = $item_data['product_id'];
  2281. $quote_item_data['estimated_value'] = $item_data['estimated_value'];
  2282. $quote_item_data['needed_by_date'] = $item_data['needed_by_date'];
  2283. $quote_item_data['quoted_quantity'] = $item_data['requested_quantity'];
  2284. $quote_item_data['expected_price'] = $item_data['expected_price'];
  2285. $quote_item_data['quote_id'] =$quote_id;
  2286. $quote_item_data['rfq_line_id'] = $item_data['id'];
  2287. $quote_line_id = $this->createQuoteItem($quote_item_data);
  2288. $this->Request_quote_item->update(array('id'=>$item_data['id']),array('status'=>self::SUBMITTEDTOQUOTE,'quote_line_id'=>$quote_line_id));
  2289. }
  2290. }
  2291. }
  2292. function createQuotes(){
  2293. $id = $_REQUEST['quoteId'];
  2294. $form_data=$_REQUEST['form_data'];
  2295. $purchase_quote_data['supplier_id'] = $form_data['supplierOp'];
  2296. $purchase_quote_data['warehouse_id'] = $form_data['warehouseOp'];
  2297. $pricerule = $form_data['pricerule_quote'];
  2298. $purchase_quote_data['discount_type'] = $pricerule;
  2299. $discount = 0;
  2300. if ($pricerule==self::EXISTING){
  2301. $purchase_quote_data['pricelist_id'] = $form_data['pricelist_id'];
  2302. }
  2303. else if ($pricerule==self::DIRECTAMOUNTTOTAL){
  2304. $purchase_quote_data['discount_value'] = $form_data['dir_disc_total_quote'];
  2305. }
  2306. else if ($pricerule==self::DIRECTPERCENTAGE){
  2307. $purchase_quote_data['discount_value'] = $form_data['dir_disc_perc_quote'];
  2308. }
  2309. if (!empty($_REQUEST['total_before_discount'])){
  2310. if (!empty($_REQUEST['total_discount'])){
  2311. $discount = $_REQUEST['total_discount'];
  2312. }
  2313. $purchase_quote_data['discount_amount'] = $discount;
  2314. }
  2315. $purchase_quote_data['final_total'] = $_REQUEST['total_before_discount'] - $discount;
  2316. if (!empty($form_data['reqdate'])){
  2317. $dateObj = DateTime::createFromFormat('d/m/Y', $form_data['reqdate']);
  2318. log_message('debug','converted '.$dateObj->format('Y-m-d'));
  2319. $purchase_quote_data['needed_by_date'] = $dateObj->format('Y-m-d');
  2320. }
  2321. $comments = appendComments($form_data['notes'], 'notes');
  2322. $purchase_quote_data['owner_id'] = $this->user->person_id;
  2323. if (empty($id)){
  2324. $purchase_quote_data['raised_by'] = $this->user->person_id;
  2325. $id = $this->Purchase_quote_master->createQuote($purchase_quote_data,array('notes'=>$comments));
  2326. }
  2327. else {
  2328. $where_clause = array('id'=>$id);
  2329. $this->Purchase_quote_master->update($where_clause, $purchase_quote_data,array('notes'=>$comments));
  2330. }
  2331. echo $id;
  2332. }
  2333. function modifyQuote (){
  2334. $id = $_REQUEST['id'];
  2335. $oper = $_REQUEST['oper'];
  2336. $this->db->trans_start();
  2337. if ($oper=='edit'){
  2338. //$dateObj = DateTime::createFromFormat('d/m/Y', $_REQUEST['needed_by_date']);
  2339. //log_message('debug','converted item date '.$dateObj->format('Y-m-d'));
  2340. $purchase_quote_data['needed_by_date'] = $_REQUEST['needed_by_date'];
  2341. //while editing the supplier id is passed.
  2342. $purchase_quote_data['supplier_id'] = $_REQUEST['supplier_name'];
  2343. $where_clause_quote = array('id'=>$id);
  2344. $this->Purchase_quote_master->update($where_clause_quote,$purchase_quote_data);
  2345. }
  2346. else if ($oper=='del'){
  2347. $idAraay = $_REQUEST['id'];
  2348. foreach($idAraay as $tempId){
  2349. $where_clause_quote = array('id'=>$tempId);
  2350. $this->Purchase_quote_master->update($where_clause_quote,array('status'=>'cancelled'));
  2351. $where_clause_quote_item = array('quote_id'=>$tempId);
  2352. $this->Purchase_quote_item->update($where_clause_quote_item,array('status'=>'cancelled'));
  2353. }
  2354. //
  2355. }
  2356. $this->db->trans_complete();
  2357. }
  2358. function addQuoteItem (){
  2359. $form_data=$_REQUEST['form_data'];
  2360. $pricerule= $form_data['pricerule'];
  2361. $purchase_quote_data['pricerule_type'] = $pricerule;
  2362. $qty=$form_data['quantity'];
  2363. if ($pricerule==self::EXISTING){
  2364. $purchase_quote_data['pricelist_id'] = $form_data['pricelist_id'];
  2365. }
  2366. else if ($pricerule==self::DIRECTAMOUNTUNIT){
  2367. $purchase_quote_data['discount_value'] = $form_data['dir_disc_unit'];
  2368. }
  2369. else if ($pricerule==self::DIRECTAMOUNTTOTAL){
  2370. $purchase_quote_data['discount_value'] = $form_data['dir_disc_total'];
  2371. }
  2372. else if ($pricerule==self::DIRECTPERCENTAGE){
  2373. $purchase_quote_data['discount_value'] = $form_data['dir_disc_perc'];
  2374. }
  2375. $purchase_quote_data['product_id'] =$form_data['productOp'];
  2376. $purchase_quote_data['quote_id'] = $_REQUEST['quoteid'];
  2377. if (!empty($_REQUEST['unit_discount'])){
  2378. $unit_discount = $_REQUEST['unit_discount'];
  2379. }
  2380. else {
  2381. $unit_discount = 0;
  2382. }
  2383. if (!empty($_REQUEST['dir_disc_fg'])){
  2384. $free_items = $_REQUEST['dir_disc_fg'];
  2385. }
  2386. else {
  2387. $free_items = 0;
  2388. }
  2389. if (!empty($form_data['neededByDate'])){
  2390. $dateObj = DateTime::createFromFormat('d/m/Y', $_REQUEST['neededByDate']);
  2391. log_message('debug','converted item date '.$dateObj->format('Y-m-d'));
  2392. $purchase_quote_data['needed_by_date'] = $dateObj->format('Y-m-d');
  2393. }
  2394. $unit_price = $form_data['exPrice'];
  2395. $purchase_quote_data['quoted_quantity'] = $qty;
  2396. $purchase_quote_data['expected_price'] = $unit_price;
  2397. $final_unit_price = $unit_price-$unit_discount;
  2398. $purchase_quote_data['final_unit_price'] = $final_unit_price;
  2399. $purchase_quote_data['estimated_value'] = $qty*$final_unit_price;
  2400. $purchase_quote_data['free_items'] = $free_items;
  2401. $purchase_quote_data['comments'] = $form_data['notes_item'];
  2402. $id = $this->createQuoteItem($purchase_quote_data);
  2403. }
  2404. //business logic
  2405. function createQuoteItem($purchase_quote_data){
  2406. $this->db->trans_start();
  2407. /* insert into quote item */
  2408. $this->Purchase_quote_item->insert($purchase_quote_data);
  2409. log_message('debug','insert statement ='.$this->db->last_query());
  2410. $id = $this->db->insert_id();
  2411. /* end insert */
  2412. /* update reference number in quote item */
  2413. $where_clause = array('id'=>$id);
  2414. $this->Purchase_quote_item->update($where_clause, array('reference' => 10000000 + $id));
  2415. /* end update */
  2416. /* update estimated value in quote master */
  2417. $quote_id = $purchase_quote_data['quote_id'];
  2418. $quote_details=$this->Purchase_quote_master->getById($quote_id);
  2419. $estimated_value = $quote_details->estimated_value + $purchase_quote_data['estimated_value'];
  2420. $existing_discount = $quote_details->discount_amount;
  2421. $final_total = $estimated_value-$existing_discount;
  2422. $this->Purchase_quote_master->update(array('id'=>$quote_id),array('estimated_value'=>$estimated_value,'final_total'=>$final_total));
  2423. log_message('debug','update statement ='.$this->db->last_query());
  2424. /* end update estimated value in quote master */
  2425. $this->db->trans_complete();
  2426. return $id;
  2427. }
  2428. function modifyQuoteItem (){
  2429. $id = $_REQUEST['id'];
  2430. $item_details=$this->Purchase_quote_item->getById($id);
  2431. $quote_id = $item_details->quote_id;
  2432. $current_est_value = $item_details->estimated_value;
  2433. $oper = $_REQUEST['oper'];
  2434. $this->db->trans_start();
  2435. if ($oper=='edit'){
  2436. //$dateObj = DateTime::createFromFormat('d/m/Y', $_REQUEST['needed_by_date']);
  2437. //log_message('debug','converted item date '.$dateObj->format('Y-m-d'));
  2438. $purchase_quote_data['needed_by_date'] = $_REQUEST['needed_by_date'];
  2439. $purchase_quote_data['quoted_quantity'] = $_REQUEST['quoted_quantity'];
  2440. $purchase_quote_data['expected_price'] = $_REQUEST['expected_price'];
  2441. $purchase_quote_data['comments'] = $_REQUEST['comments'];
  2442. $purchase_quote_data['estimated_value'] = $_REQUEST['quoted_quantity']*$_REQUEST['expected_price'];
  2443. $where_clause = array('id'=>$id);
  2444. $this->Purchase_quote_item->update($where_clause,$purchase_quote_data);
  2445. $quote_details=$this->Purchase_quote_master->getById($quote_id);
  2446. $estimated_value = $quote_details->estimated_value - $current_est_value + $purchase_quote_data['estimated_value'];
  2447. $existing_discount = $quote_details->discount_amount;
  2448. $final_total = $estimated_value-$existing_discount;
  2449. $this->Purchase_quote_master->update(array('id'=>$quote_id),array('estimated_value'=>$estimated_value,'final_total'=>$final_total));
  2450. }
  2451. else if ($oper=='del'){
  2452. $quote_details=$this->Purchase_quote_master->getById($quote_id);
  2453. $estimated_value = $quote_details->estimated_value - $item_details->estimated_value;
  2454. $existing_discount = $quote_details->discount_amount;
  2455. $final_total = $estimated_value-$existing_discount;
  2456. $this->Purchase_quote_master->update(array('id'=>$quote_id),array('estimated_value'=>$estimated_value,'final_total'=>$final_total));
  2457. $where_clause = array('id'=>$id);
  2458. $this->Purchase_quote_item->update($where_clause,array('status'=>'cancelled'));
  2459. }
  2460. $this->db->trans_complete();
  2461. }
  2462. function populateQuoteItems(){
  2463. $quoteid = $_REQUEST['quoteId'];
  2464. if (!empty($quoteid)){
  2465. $quotedata = array();
  2466. $where = array('quote_id' => $quoteid );
  2467. $griddata= populateGridCommon('Purchase_quote_item',$where);
  2468. $dbrows = $griddata['db_data'];
  2469. $data = $griddata['grid_metadata'];
  2470. //$data['userdata']['quoted_quantity']=0;
  2471. //['userdata']['free_items']=0;
  2472. foreach ($dbrows as $dbrow){
  2473. array_push($quotedata, array('id'=> $dbrow['id'],'dprow' => array($dbrow['name'].",".$dbrow['sku'],$dbrow['quoted_quantity'],$dbrow['free_items'],$dbrow['expected_price'],$dbrow['unit_price_discount'],$dbrow['final_unit_price'],$dbrow['total_before_discount'],$dbrow['total_discount'],$dbrow['final_total'],$dbrow['needed_by_date'],$dbrow['comments'],$dbrow['product_id'],$dbrow['pricerule_type'],$dbrow['pricelist_id'],$dbrow['discount_value'])));
  2474. $data['userdata']['quoted_quantity']+=$dbrow['quoted_quantity'];
  2475. $data['userdata']['free_items']+=$dbrow['free_items'];
  2476. $data['userdata']['total_before_discount']+=$dbrow['total_before_discount'];
  2477. $data['userdata']['total_discount']+=$dbrow['total_discount'];
  2478. $data['userdata']['final_total']+=$dbrow['final_total'];
  2479. }
  2480. $data['quoteitemdata'] = $quotedata;
  2481. $data['userdata']['name'] = 'Total';
  2482. echo json_encode($data);
  2483. }
  2484. }
  2485. function getRelevantPriceListId(){
  2486. $supplier_id= $_REQUEST['supplier_id'];
  2487. // $today = date("Y-m-d");
  2488. $version = $this->Pricelist_master->applicableVersionList(date("Y-m-d"),$supplier_id);
  2489. $ret['id']=$version->id;
  2490. $ret['name']=$version->name;
  2491. $ret['inherit_rules']=$version->inherit_rules;
  2492. $ret['inherit_rules_dir']=$version->inherit_rules_dir;
  2493. echo json_encode($ret) ;
  2494. }
  2495. }
  2496. ?>