Merged changes from stable branch up to 2.3.12
[fa-stable.git] / purchasing / po_entry_items.php
1 <?php
2 /**********************************************************************
3     Copyright (C) FrontAccounting, LLC.
4         Released under the terms of the GNU General Public License, GPL, 
5         as published by the Free Software Foundation, either version 3 
6         of the License, or (at your option) any later version.
7     This program is distributed in the hope that it will be useful,
8     but WITHOUT ANY WARRANTY; without even the implied warranty of
9     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
10     See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
11 ***********************************************************************/
12 $path_to_root = "..";
13 $page_security = 'SA_PURCHASEORDER';
14 include_once($path_to_root . "/purchasing/includes/po_class.inc");
15 include_once($path_to_root . "/includes/session.inc");
16 include_once($path_to_root . "/purchasing/includes/purchasing_ui.inc");
17 include_once($path_to_root . "/purchasing/includes/db/suppliers_db.inc");
18 include_once($path_to_root . "/reporting/includes/reporting.inc");
19
20 set_page_security( @$_SESSION['PO']->trans_type,
21         array(  ST_PURCHORDER => 'SA_PURCHASEORDER',
22                         ST_SUPPRECEIVE => 'SA_GRN',
23                         ST_SUPPINVOICE => 'SA_SUPPLIERINVOICE'),
24         array(  'NewOrder' => 'SA_PURCHASEORDER',
25                         'ModifyOrderNumber' => 'SA_PURCHASEORDER',
26                         'AddedID' => 'SA_PURCHASEORDER',
27                         'NewGRN' => 'SA_GRN',
28                         'AddedGRN' => 'SA_GRN',
29                         'NewInvoice' => 'SA_SUPPLIERINVOICE',
30                         'AddedPI' => 'SA_SUPPLIERINVOICE')
31 );
32
33 $js = '';
34 if ($use_popup_windows)
35         $js .= get_js_open_window(900, 500);
36 if ($use_date_picker)
37         $js .= get_js_date_picker();
38
39 if (isset($_GET['ModifyOrderNumber']) && is_numeric($_GET['ModifyOrderNumber'])) {
40
41         $_SESSION['page_title'] = _($help_context = "Modify Purchase Order #") . $_GET['ModifyOrderNumber'];
42         create_new_po(ST_PURCHORDER, $_GET['ModifyOrderNumber']);
43         copy_from_cart();
44 } elseif (isset($_GET['NewOrder'])) {
45
46         $_SESSION['page_title'] = _($help_context = "Purchase Order Entry");
47         create_new_po(ST_PURCHORDER, 0);
48         copy_from_cart();
49 } elseif (isset($_GET['NewGRN'])) {
50
51         $_SESSION['page_title'] = _($help_context = "Direct GRN Entry");
52         create_new_po(ST_SUPPRECEIVE, 0);
53         copy_from_cart();
54 } elseif (isset($_GET['NewInvoice'])) {
55
56         $_SESSION['page_title'] = _($help_context = "Direct Purchase Invoice Entry");
57         create_new_po(ST_SUPPINVOICE, 0);
58         copy_from_cart();
59 }
60
61 page($_SESSION['page_title'], false, false, "", $js);
62
63 if (isset($_GET['ModifyOrderNumber']))
64         check_is_editable(ST_PURCHORDER, $_GET['ModifyOrderNumber']);
65
66 //---------------------------------------------------------------------------------------------------
67
68 check_db_has_suppliers(_("There are no suppliers defined in the system."));
69
70 check_db_has_purchasable_items(_("There are no purchasable inventory items defined in the system."));
71
72 //---------------------------------------------------------------------------------------------------------------
73
74 if (isset($_GET['AddedID'])) 
75 {
76         $order_no = $_GET['AddedID'];
77         $trans_type = ST_PURCHORDER;    
78
79         if (!isset($_GET['Updated']))
80                 display_notification_centered(_("Purchase Order has been entered"));
81         else
82                 display_notification_centered(_("Purchase Order has been updated") . " #$order_no");
83         display_note(get_trans_view_str($trans_type, $order_no, _("&View this order")), 0, 1);
84
85         display_note(print_document_link($order_no, _("&Print This Order"), true, $trans_type), 0, 1);
86
87         display_note(print_document_link($order_no, _("&Email This Order"), true, $trans_type, false, "printlink", "", 1));
88
89         hyperlink_params($path_to_root . "/purchasing/po_receive_items.php", _("&Receive Items on this Purchase Order"), "PONumber=$order_no");
90
91         hyperlink_params($_SERVER['PHP_SELF'], _("Enter &Another Purchase Order"), "NewOrder=yes");
92         
93         hyperlink_no_params($path_to_root."/purchasing/inquiry/po_search.php", _("Select An &Outstanding Purchase Order"));
94         
95         display_footer_exit();  
96
97 } elseif (isset($_GET['AddedGRN'])) {
98
99         $trans_no = $_GET['AddedGRN'];
100         $trans_type = ST_SUPPRECEIVE;
101
102         display_notification_centered(_("Direct GRN has been entered"));
103
104         display_note(get_trans_view_str($trans_type, $trans_no, _("&View this GRN")), 0);
105
106     $clearing_act = get_company_pref('grn_clearing_act');
107         if ($clearing_act)      
108                 display_note(get_gl_view_str($trans_type, $trans_no, _("View the GL Journal Entries for this Delivery")), 1);
109 // not yet
110 //      display_note(print_document_link($trans_no, _("&Print This GRN"), true, $trans_type), 0, 1);
111
112         hyperlink_params("$path_to_root/purchasing/supplier_invoice.php",
113                 _("Entry purchase &invoice for this receival"), "New=1");
114
115         hyperlink_params("$path_to_root/admin/attachments.php", _("Add an Attachment"), 
116                 "filterType=$trans_type&trans_no=$trans_no");
117
118         hyperlink_params($_SERVER['PHP_SELF'], _("Enter &Another GRN"), "NewGRN=Yes");
119         
120         display_footer_exit();  
121
122 } elseif (isset($_GET['AddedPI'])) {
123
124         $trans_no = $_GET['AddedPI'];
125         $trans_type = ST_SUPPINVOICE;
126
127         display_notification_centered(_("Direct Purchase Invoice has been entered"));
128
129         display_note(get_trans_view_str($trans_type, $trans_no, _("&View this Invoice")), 0);
130
131 // not yet
132 //      display_note(print_document_link($trans_no, _("&Print This Invoice"), true, $trans_type), 0, 1);
133
134         display_note(get_gl_view_str($trans_type, $trans_no, _("View the GL Journal Entries for this Invoice")), 1);
135
136         hyperlink_params("$path_to_root/purchasing/supplier_payment.php", _("Entry supplier &payment for this invoice"),
137                 "PInvoice=".$trans_no);
138
139         hyperlink_params("$path_to_root/admin/attachments.php", _("Add an Attachment"), 
140                 "filterType=$trans_type&trans_no=$trans_no");
141
142         hyperlink_params($_SERVER['PHP_SELF'], _("Enter &Another Direct Invoice"), "NewInvoice=Yes");
143         
144         display_footer_exit();  
145 }
146 //--------------------------------------------------------------------------------------------------
147
148 function line_start_focus() {
149   global        $Ajax;
150
151   $Ajax->activate('items_table');
152   set_focus('_stock_id_edit');
153 }
154 //--------------------------------------------------------------------------------------------------
155
156 function unset_form_variables() {
157         unset($_POST['stock_id']);
158     unset($_POST['qty']);
159     unset($_POST['price']);
160     unset($_POST['req_del_date']);
161 }
162
163 //---------------------------------------------------------------------------------------------------
164
165 function handle_delete_item($line_no)
166 {
167         if($_SESSION['PO']->some_already_received($line_no) == 0)
168         {
169                 $_SESSION['PO']->remove_from_order($line_no);
170                 unset_form_variables();
171         } 
172         else 
173         {
174                 display_error(_("This item cannot be deleted because some of it has already been received."));
175         }       
176     line_start_focus();
177 }
178
179 //---------------------------------------------------------------------------------------------------
180
181 function handle_cancel_po()
182 {
183         global $path_to_root;
184         
185         //need to check that not already dispatched or invoiced by the supplier
186         if(($_SESSION['PO']->order_no != 0) && 
187                 $_SESSION['PO']->any_already_received() == 1)
188         {
189                 display_error(_("This order cannot be cancelled because some of it has already been received.") 
190                         . "<br>" . _("The line item quantities may be modified to quantities more than already received. prices cannot be altered for lines that have already been received and quantities cannot be reduced below the quantity already received."));
191                 return;
192         }
193         
194         if($_SESSION['PO']->order_no != 0)
195         {
196                 delete_po($_SESSION['PO']->order_no);
197         } else {
198                 unset($_SESSION['PO']);
199                 meta_forward($path_to_root.'/index.php','application=AP');
200         }
201
202         $_SESSION['PO']->clear_items();
203         $_SESSION['PO'] = new purch_order;
204
205         display_notification(_("This purchase order has been cancelled."));
206
207         hyperlink_params($path_to_root . "/purchasing/po_entry_items.php", _("Enter a new purchase order"), "NewOrder=Yes");
208         echo "<br>";
209
210         end_page();
211         exit;
212 }
213
214 //---------------------------------------------------------------------------------------------------
215
216 function check_data()
217 {
218         if(!get_post('stock_id_text', true)) {
219                 display_error( _("Item description cannot be empty."));
220                 set_focus('stock_id_edit');
221                 return false;
222         }
223
224         $dec = get_qty_dec($_POST['stock_id']);
225         $min = 1 / pow(10, $dec);
226     if (!check_num('qty',$min))
227     {
228         $min = number_format2($min, $dec);
229                 display_error(_("The quantity of the order item must be numeric and not less than ").$min);
230                 set_focus('qty');
231                 return false;
232     }
233
234     if (!check_num('price', 0))
235     {
236                 display_error(_("The price entered must be numeric and not less than zero."));
237                 set_focus('price');
238                 return false;      
239     }
240     if ($_SESSION['PO']->trans_type == ST_PURCHORDER && !is_date($_POST['req_del_date'])){
241                 display_error(_("The date entered is in an invalid format."));
242                 set_focus('req_del_date');
243                 return false;            
244     }
245      
246     return true;        
247 }
248
249 //---------------------------------------------------------------------------------------------------
250
251 function handle_update_item()
252 {
253         $allow_update = check_data(); 
254
255         if ($allow_update)
256         {
257                 if ($_SESSION['PO']->line_items[$_POST['line_no']]->qty_inv > input_num('qty') ||
258                         $_SESSION['PO']->line_items[$_POST['line_no']]->qty_received > input_num('qty'))
259                 {
260                         display_error(_("You are attempting to make the quantity ordered a quantity less than has already been invoiced or received.  This is prohibited.") .
261                                 "<br>" . _("The quantity received can only be modified by entering a negative receipt and the quantity invoiced can only be reduced by entering a credit note against this item."));
262                         set_focus('qty');
263                         return;
264                 }
265         
266                 $_SESSION['PO']->update_order_item($_POST['line_no'], input_num('qty'), input_num('price'),
267                         @$_POST['req_del_date'], $_POST['item_description'] );
268                 unset_form_variables();
269         }       
270     line_start_focus();
271 }
272
273 //---------------------------------------------------------------------------------------------------
274
275 function handle_add_new_item()
276 {
277         $allow_update = check_data();
278         
279         if ($allow_update == true)
280         { 
281                 if (count($_SESSION['PO']->line_items) > 0)
282                 {
283                     foreach ($_SESSION['PO']->line_items as $order_item) 
284                     {
285                         /* do a loop round the items on the order to see that the item
286                         is not already on this order */
287                             if (($order_item->stock_id == $_POST['stock_id'])) 
288                             {
289                                         display_warning(_("The selected item is already on this order."));
290                             }
291                     } /* end of the foreach loop to look for pre-existing items of the same code */
292                 }
293
294                 if ($allow_update == true)
295                 {
296                         $result = get_short_info($_POST['stock_id']);
297
298                         if (db_num_rows($result) == 0)
299                         {
300                                 $allow_update = false;
301                         }
302
303                         if ($allow_update)
304                         {
305                                 $myrow = db_fetch($result);
306                                 $_SESSION['PO']->add_to_order (count($_SESSION['PO']->line_items), $_POST['stock_id'], input_num('qty'), 
307                                         get_post('stock_id_text'), //$myrow["description"], 
308                                         input_num('price'), '', // $myrow["units"], (retrived in cart)
309                                         $_SESSION['PO']->trans_type == ST_PURCHORDER ? $_POST['req_del_date'] : '', 0, 0);
310
311                                 unset_form_variables();
312                                 $_POST['stock_id']      = "";
313                         } 
314                         else 
315                         {
316                              display_error(_("The selected item does not exist or it is a kit part and therefore cannot be purchased."));
317                         }
318
319                 } /* end of if not already on the order and allow input was true*/
320     }
321         line_start_focus();
322 }
323
324 //---------------------------------------------------------------------------------------------------
325
326 function can_commit()
327 {
328         global $Refs;
329
330         if (!get_post('supplier_id')) 
331         {
332                 display_error(_("There is no supplier selected."));
333                 set_focus('supplier_id');
334                 return false;
335         } 
336
337         if (!is_date($_POST['OrderDate'])) 
338         {
339                 display_error(_("The entered order date is invalid."));
340                 set_focus('OrderDate');
341                 return false;
342         } 
343         if (($_SESSION['PO']->trans_type == ST_SUPPRECEIVE || $_SESSION['PO']->trans_type == ST_SUPPINVOICE) 
344                 && !is_date_in_fiscalyear($_POST['OrderDate'])) {
345                 display_error(_("The entered date is out of fiscal year or is closed for further data entry."));
346                 set_focus('OrderDate');
347                 return false;
348         }
349
350         if (($_SESSION['PO']->trans_type==ST_SUPPINVOICE) && !is_date($_POST['due_date'])) 
351         {
352                 display_error(_("The entered due date is invalid."));
353                 set_focus('due_date');
354                 return false;
355         } 
356
357         if (!$_SESSION['PO']->order_no) 
358         {
359         if (!$Refs->is_valid(get_post('ref'))) 
360         {
361                 display_error(_("There is no reference entered for this purchase order."));
362                         set_focus('ref');
363                 return false;
364         } 
365
366         if (!is_new_reference(get_post('ref'), $_SESSION['PO']->trans_type)) 
367         {
368                 display_error(_("The entered reference is already in use."));
369                         set_focus('ref');
370                 return false;
371         }
372         }
373
374         if ($_SESSION['PO']->trans_type == ST_SUPPINVOICE && !$Refs->is_valid(get_post('supp_ref'))) 
375         {
376                 display_error(_("You must enter a supplier's invoice reference."));
377                 set_focus('supp_ref');
378                 return false;
379         }
380         if ($_SESSION['PO']->trans_type==ST_SUPPINVOICE 
381                 && is_reference_already_there($_SESSION['PO']->supplier_id, get_post('supp_ref'), $_SESSION['PO']->order_no))
382         {
383                 display_error(_("This invoice number has already been entered. It cannot be entered again.") . " (" . get_post('supp_ref') . ")");
384                 set_focus('supp_ref');
385                 return false;
386         }
387         if ($_SESSION['PO']->trans_type == ST_PURCHORDER && get_post('delivery_address') == '')
388         {
389                 display_error(_("There is no delivery address specified."));
390                 set_focus('delivery_address');
391                 return false;
392         } 
393         if (get_post('StkLocation') == '')
394         {
395                 display_error(_("There is no location specified to move any items into."));
396                 set_focus('StkLocation');
397                 return false;
398         } 
399         if (!db_has_currency_rates($_SESSION['PO']->curr_code, $_POST['OrderDate']))
400                 return false;
401         if ($_SESSION['PO']->order_has_items() == false)
402         {
403         display_error (_("The order cannot be placed because there are no lines entered on this order."));
404         return false;
405         }
406         if (floatcmp(input_num('prep_amount'), $_SESSION['PO']->get_trans_total()) > 0)
407         {
408                 display_error(_("Required prepayment is greater than total invoice value."));
409                 set_focus('prep_amount');
410                 return false;
411         }
412
413         return true;
414 }
415
416 //---------------------------------------------------------------------------------------------------
417
418 function handle_commit_order()
419 {
420         global $Refs, $type_shortcuts;
421
422         $cart = &$_SESSION['PO'];
423
424         if (can_commit()) {
425
426                 copy_to_cart();
427                 if ($cart->trans_type != ST_PURCHORDER) {
428                         // for direct grn/invoice set same dates for lines as for whole document
429                         foreach ($cart->line_items as $line_no =>$line)
430                                 $cart->line_items[$line_no]->req_del_date = $cart->orig_order_date;
431                 }
432                 if ($cart->order_no == 0) { // new po/grn/invoice
433                         /*its a new order to be inserted */
434                         $ref = $cart->reference;
435                         if ($cart->trans_type != ST_PURCHORDER) {
436                                 $cart->reference = 'auto';
437                                 begin_transaction();    // all db changes as single transaction for direct document
438                         }
439                         $order_no = add_po($cart);
440                         new_doc_date($cart->orig_order_date); 
441                 $cart->order_no = $order_no;
442
443                         if ($cart->trans_type == ST_PURCHORDER) {
444                                 unset($_SESSION['PO']);
445                         meta_forward($_SERVER['PHP_SELF'], "AddedID=$order_no");
446                 }
447                         //Direct GRN
448                         if ($cart->trans_type == ST_SUPPRECEIVE)
449                                 $cart->reference = $ref;
450                         $cart->Comments = $cart->reference; //grn does not hold supp_ref
451                         foreach($cart->line_items as $key => $line)
452                                 $cart->line_items[$key]->receive_qty = $line->quantity;
453                         $grn_no = add_grn($cart);
454                         if ($cart->trans_type == ST_SUPPRECEIVE) {
455                                 commit_transaction(); // save PO+GRN
456                                 unset($_SESSION['PO']);
457                         meta_forward($_SERVER['PHP_SELF'], "AddedGRN=$grn_no");
458                         }
459 //                      Direct Purchase Invoice
460                         $inv = new supp_trans(ST_SUPPINVOICE);
461                         $inv->Comments = $cart->Comments;
462                         $inv->supplier_id = $cart->supplier_id;
463                         $inv->tran_date = $cart->orig_order_date;
464                         $inv->due_date = $cart->due_date;
465                         $inv->reference = $ref;
466                         $inv->supp_reference = $cart->supp_ref;
467                         $inv->tax_included = $cart->tax_included;
468                         $inv->tax_algorithm = $cart->tax_algorithm;
469                         $inv->stored_algorithm = $cart->stored_algorithm;
470                         $supp = get_supplier($cart->supplier_id);
471                         $inv->tax_group_id = $supp['tax_group_id'];
472                         $total = 0;
473
474                         foreach($cart->line_items as $key => $line) {
475                                 $inv->add_grn_to_trans($line->grn_item_id, $line->po_detail_rec, $line->stock_id,
476                                         $line->item_description, $line->receive_qty, 0, $line->receive_qty,
477                                         $line->price, $line->price, true, get_standard_cost($line->stock_id), '');
478                                 $total += round2(($line->receive_qty * $line->price), user_price_dec());
479                         }
480                         if (!$inv->tax_included) {
481                                 $taxes = $inv->get_taxes($inv->tax_group_id, 0, false, $inv->tax_algorithm);
482                                 foreach( $taxes as $taxitem) {
483                                         $total += $taxitem['Value'];
484                                 }
485                         }
486
487                         $inv_no = add_supp_invoice($inv);
488                         // presume supplier data need correction
489                         if ($inv->stored_algorithm != $inv->tax_algorithm)
490                                 update_supp_tax_algorithm($inv->supplier_id, $inv->tax_algorithm);
491
492                         if (get_post('cash_account')) {
493
494                                 $pmt_no = add_supp_payment($inv->supplier_id, $inv->tran_date, get_post('cash_account'),
495                                         $total, 0,      $Refs->get_next(ST_SUPPAYMENT), 
496                                         _('Payment for:').$inv->supp_reference .' ('.$type_shortcuts[ST_SUPPINVOICE].$inv_no.')');
497                                 add_supp_allocation($total, ST_SUPPAYMENT, $pmt_no, ST_SUPPINVOICE, $inv_no, $inv->tran_date);
498                                 update_supp_trans_allocation(ST_SUPPINVOICE, $inv_no, $total);
499                                 update_supp_trans_allocation(ST_SUPPAYMENT, $pmt_no, $total);
500
501                         }
502
503                         commit_transaction(); // save PO+GRN+PI(+SP)
504
505                         unset($_SESSION['PO']);
506                 meta_forward($_SERVER['PHP_SELF'], "AddedPI=$inv_no");
507                 }
508                 else { // order modification
509                 
510                         $order_no = update_po($cart);
511                         unset($_SESSION['PO']);
512                 meta_forward($_SERVER['PHP_SELF'], "AddedID=$order_no&Updated=1");      
513                 }
514         }
515 }
516 //---------------------------------------------------------------------------------------------------
517 $id = find_submit('Delete');
518 if ($id != -1)
519         handle_delete_item($id);
520
521 if (isset($_POST['Commit']))
522 {
523         handle_commit_order();
524 }
525 if (isset($_POST['UpdateLine']))
526         handle_update_item();
527
528 if (isset($_POST['EnterLine']))
529         handle_add_new_item();
530
531 if (isset($_POST['CancelOrder'])) 
532         handle_cancel_po();
533
534 if (isset($_POST['CancelUpdate']))
535         unset_form_variables();
536
537 if (isset($_POST['CancelUpdate']) || isset($_POST['UpdateLine'])) {
538         line_start_focus();
539 }
540
541 //---------------------------------------------------------------------------------------------------
542
543 start_form();
544
545 display_po_header($_SESSION['PO']);
546 echo "<br>";
547
548 display_po_items($_SESSION['PO']);
549
550 start_table(TABLESTYLE2);
551
552 if (list_updated('tax_algorithm')) {
553         $_SESSION['PO']->tax_algorithm = $_POST['tax_algorithm'];
554     $Ajax->activate('items_table');
555 }
556
557 if ($_SESSION['PO']->trans_type == ST_SUPPINVOICE) {
558         tax_algorithm_list_row(_("Tax algorithm:"), 'tax_algorithm', null, true);
559         cash_accounts_list_row(_("Payment:"), 'cash_account', null, false, _('Delayed'));
560 }
561
562 textarea_row(_("Memo:"), 'Comments', null, 70, 4);
563
564 end_table(1);
565
566 div_start('controls', 'items_table');
567 $process_txt = _("Place Order");
568 $update_txt = _("Update Order");
569 $cancel_txt = _("Cancel Order");
570 if ($_SESSION['PO']->trans_type == ST_SUPPRECEIVE) {
571         $process_txt = _("Process GRN");
572         $update_txt = _("Update GRN");
573         $cancel_txt = _("Cancel GRN");
574 }       
575 elseif ($_SESSION['PO']->trans_type == ST_SUPPINVOICE) {
576         $process_txt = _("Process Invoice");
577         $update_txt = _("Update Invoice");
578         $cancel_txt = _("Cancel Invoice");
579 }       
580 if ($_SESSION['PO']->order_has_items()) 
581 {
582         if ($_SESSION['PO']->order_no)
583                 submit_center_first('Commit', $update_txt, '', 'default');
584         else
585                 submit_center_first('Commit', $process_txt, '', 'default');
586         submit_center_last('CancelOrder', $cancel_txt);         
587 }
588 else
589         submit_center('CancelOrder', $cancel_txt, true, false, 'cancel');
590 div_end();
591 //---------------------------------------------------------------------------------------------------
592
593 end_form();
594 end_page();
595 ?>