756add4d4259c6e27d993ed938fba77463da005b
[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 . "/reporting/includes/reporting.inc");
18
19 set_page_security( @$_SESSION['PO']->trans_type,
20         array(  ST_PURCHORDER => 'SA_PURCHASEORDER',
21                         ST_SUPPRECEIVE => 'SA_GRN',
22                         ST_SUPPINVOICE => 'SA_SUPPLIERINVOICE'),
23         array(  'NewOrder' => 'SA_PURCHASEORDER',
24                         'ModifyOrderNumber' => 'SA_PURCHASEORDER',
25                         'NewGRN' => 'SA_GRN',
26                         'NewInvoice' => 'SA_SUPPLIERINVOICE')
27 );
28
29 $js = '';
30 if ($use_popup_windows)
31         $js .= get_js_open_window(900, 500);
32 if ($use_date_picker)
33         $js .= get_js_date_picker();
34
35 if (isset($_GET['ModifyOrderNumber']) && is_numeric($_GET['ModifyOrderNumber'])) {
36
37         $_SESSION['page_title'] = _($help_context = "Modify Purchase Order #") . $_GET['ModifyOrderNumber'];
38         create_new_po(ST_PURCHORDER, $_GET['ModifyOrderNumber']);
39         copy_from_cart();
40 } elseif (isset($_GET['NewOrder'])) {
41
42         $_SESSION['page_title'] = _($help_context = "Purchase Order Entry");
43         create_new_po(ST_PURCHORDER, 0);
44         copy_from_cart();
45 } elseif (isset($_GET['NewGRN'])) {
46
47         $_SESSION['page_title'] = _($help_context = "Direct GRN Entry");
48         create_new_po(ST_SUPPRECEIVE, 0);
49         copy_from_cart();
50 } elseif (isset($_GET['NewInvoice'])) {
51
52         $_SESSION['page_title'] = _($help_context = "Direct Purchase Invoice Entry");
53         create_new_po(ST_SUPPINVOICE, 0);
54         copy_from_cart();
55 }
56
57 page($_SESSION['page_title'], false, false, "", $js);
58
59 //---------------------------------------------------------------------------------------------------
60
61 check_db_has_suppliers(_("There are no suppliers defined in the system."));
62
63 check_db_has_purchasable_items(_("There are no purchasable inventory items defined in the system."));
64
65 //---------------------------------------------------------------------------------------------------------------
66
67 if (isset($_GET['AddedID'])) 
68 {
69         $order_no = $_GET['AddedID'];
70         $trans_type = ST_PURCHORDER;    
71
72         if (!isset($_GET['Updated']))
73                 display_notification_centered(_("Purchase Order has been entered"));
74         else
75                 display_notification_centered(_("Purchase Order has been updated") . " #$order_no");
76         display_note(get_trans_view_str($trans_type, $order_no, _("&View this order")), 0, 1);
77
78         display_note(print_document_link($order_no, _("&Print This Order"), true, $trans_type), 0, 1);
79
80         display_note(print_document_link($order_no, _("&Email This Order"), true, $trans_type, false, "printlink", "", 1));
81
82         hyperlink_params($path_to_root . "/purchasing/po_receive_items.php", _("&Receive Items on this Purchase Order"), "PONumber=$order_no");
83
84         hyperlink_params($_SERVER['PHP_SELF'], _("Enter &Another Purchase Order"), "NewOrder=yes");
85         
86         hyperlink_no_params($path_to_root."/purchasing/inquiry/po_search.php", _("Select An &Outstanding Purchase Order"));
87         
88         display_footer_exit();  
89
90 } elseif (isset($_GET['AddedGRN'])) {
91
92         $trans_no = $_GET['AddedGRN'];
93         $trans_type = ST_SUPPRECEIVE;
94
95         display_notification_centered(_("Direct GRN has been entered"));
96
97         display_note(get_trans_view_str($trans_type, $trans_no, _("&View this GRN")), 0);
98
99 // not yet
100 //      display_note(print_document_link($trans_no, _("&Print This GRN"), true, $trans_type), 0, 1);
101
102         hyperlink_params("$path_to_root/purchasing/supplier_invoice.php",
103                 _("Entry purchase &invoice for this receival"), "New=1");
104
105         hyperlink_params("$path_to_root/admin/attachments.php", _("Add an Attachment"), 
106                 "filterType=$trans_type&trans_no=$trans_no");
107
108         hyperlink_params($_SERVER['PHP_SELF'], _("Enter &Another GRN"), "NewGRN=Yes");
109         
110         display_footer_exit();  
111
112 } elseif (isset($_GET['AddedPI'])) {
113
114         $trans_no = $_GET['AddedPI'];
115         $trans_type = ST_SUPPINVOICE;
116
117         display_notification_centered(_("Direct Purchase Invoice has been entered"));
118
119         display_note(get_trans_view_str($trans_type, $trans_no, _("&View this Invoice")), 0);
120
121 // not yet
122 //      display_note(print_document_link($trans_no, _("&Print This Invoice"), true, $trans_type), 0, 1);
123
124         display_note(get_gl_view_str($trans_type, $trans_no, _("View the GL Journal Entries for this Invoice")), 1);
125
126         hyperlink_params("$path_to_root/purchasing/supplier_payment.php", _("Entry supplier &payment for this invoice"),
127                 "PInvoice=".$trans_no);
128
129         hyperlink_params("$path_to_root/admin/attachments.php", _("Add an Attachment"), 
130                 "filterType=$trans_type&trans_no=$trans_no");
131
132         hyperlink_params($_SERVER['PHP_SELF'], _("Enter &Another Direct Invoice"), "NewInvoice=Yes");
133         
134         display_footer_exit();  
135 }
136 //--------------------------------------------------------------------------------------------------
137
138 function line_start_focus() {
139   global        $Ajax;
140
141   $Ajax->activate('items_table');
142   set_focus('_stock_id_edit');
143 }
144 //--------------------------------------------------------------------------------------------------
145
146 function unset_form_variables() {
147         unset($_POST['stock_id']);
148     unset($_POST['qty']);
149     unset($_POST['price']);
150     unset($_POST['req_del_date']);
151 }
152
153 //---------------------------------------------------------------------------------------------------
154
155 function handle_delete_item($line_no)
156 {
157         if($_SESSION['PO']->some_already_received($line_no) == 0)
158         {
159                 $_SESSION['PO']->remove_from_order($line_no);
160                 unset_form_variables();
161         } 
162         else 
163         {
164                 display_error(_("This item cannot be deleted because some of it has already been received."));
165         }       
166     line_start_focus();
167 }
168
169 //---------------------------------------------------------------------------------------------------
170
171 function handle_cancel_po()
172 {
173         global $path_to_root;
174         
175         //need to check that not already dispatched or invoiced by the supplier
176         if(($_SESSION['PO']->order_no != 0) && 
177                 $_SESSION['PO']->any_already_received() == 1)
178         {
179                 display_error(_("This order cannot be cancelled because some of it has already been received.") 
180                         . "<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."));
181                 return;
182         }
183         
184         if($_SESSION['PO']->order_no != 0)
185         {
186                 delete_po($_SESSION['PO']->order_no);
187         } else {
188                 unset($_SESSION['PO']);
189                 meta_forward($path_to_root.'/index.php','application=AP');
190         }
191
192         $_SESSION['PO']->clear_items();
193         $_SESSION['PO'] = new purch_order;
194
195         display_notification(_("This purchase order has been cancelled."));
196
197         hyperlink_params($path_to_root . "/purchasing/po_entry_items.php", _("Enter a new purchase order"), "NewOrder=Yes");
198         echo "<br>";
199
200         end_page();
201         exit;
202 }
203
204 //---------------------------------------------------------------------------------------------------
205
206 function check_data()
207 {
208         if(!get_post('stock_id_text', true)) {
209                 display_error( _("Item description cannot be empty."));
210                 set_focus('stock_id_edit');
211                 return false;
212         }
213
214         $dec = get_qty_dec($_POST['stock_id']);
215         $min = 1 / pow(10, $dec);
216     if (!check_num('qty',$min))
217     {
218         $min = number_format2($min, $dec);
219                 display_error(_("The quantity of the order item must be numeric and not less than ").$min);
220                 set_focus('qty');
221                 return false;
222     }
223
224     if (!check_num('price', 0))
225     {
226                 display_error(_("The price entered must be numeric and not less than zero."));
227                 set_focus('price');
228                 return false;      
229     }
230     if ($_SESSION['PO']->trans_type == ST_PURCHORDER && !is_date($_POST['req_del_date'])){
231                 display_error(_("The date entered is in an invalid format."));
232                 set_focus('req_del_date');
233                 return false;            
234     }
235      
236     return true;        
237 }
238
239 //---------------------------------------------------------------------------------------------------
240
241 function handle_update_item()
242 {
243         $allow_update = check_data(); 
244
245         if ($allow_update)
246         {
247                 if ($_SESSION['PO']->line_items[$_POST['line_no']]->qty_inv > input_num('qty') ||
248                         $_SESSION['PO']->line_items[$_POST['line_no']]->qty_received > input_num('qty'))
249                 {
250                         display_error(_("You are attempting to make the quantity ordered a quantity less than has already been invoiced or received.  This is prohibited.") .
251                                 "<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."));
252                         set_focus('qty');
253                         return;
254                 }
255         
256                 $_SESSION['PO']->update_order_item($_POST['line_no'], input_num('qty'), input_num('price'),
257                         @$_POST['req_del_date'], $_POST['item_description'] );
258                 unset_form_variables();
259         }       
260     line_start_focus();
261 }
262
263 //---------------------------------------------------------------------------------------------------
264
265 function handle_add_new_item()
266 {
267         $allow_update = check_data();
268         
269         if ($allow_update == true)
270         { 
271                 if (count($_SESSION['PO']->line_items) > 0)
272                 {
273                     foreach ($_SESSION['PO']->line_items as $order_item) 
274                     {
275                         /* do a loop round the items on the order to see that the item
276                         is not already on this order */
277                             if (($order_item->stock_id == $_POST['stock_id'])) 
278                             {
279                                         display_warning(_("The selected item is already on this order."));
280                             }
281                     } /* end of the foreach loop to look for pre-existing items of the same code */
282                 }
283
284                 if ($allow_update == true)
285                 {
286                         $result = get_short_info($_POST['stock_id']);
287
288                         if (db_num_rows($result) == 0)
289                         {
290                                 $allow_update = false;
291                         }
292
293                         if ($allow_update)
294                         {
295                                 $myrow = db_fetch($result);
296                                 $_SESSION['PO']->add_to_order (count($_SESSION['PO']->line_items), $_POST['stock_id'], input_num('qty'), 
297                                         get_post('stock_id_text'), //$myrow["description"], 
298                                         input_num('price'), '', // $myrow["units"], (retrived in cart)
299                                         $_SESSION['PO']->trans_type == ST_PURCHORDER ? $_POST['req_del_date'] : '', 0, 0);
300
301                                 unset_form_variables();
302                                 $_POST['stock_id']      = "";
303                         } 
304                         else 
305                         {
306                              display_error(_("The selected item does not exist or it is a kit part and therefore cannot be purchased."));
307                         }
308
309                 } /* end of if not already on the order and allow input was true*/
310     }
311         line_start_focus();
312 }
313
314 //---------------------------------------------------------------------------------------------------
315
316 function can_commit()
317 {
318         global $Refs;
319
320         if (!get_post('supplier_id')) 
321         {
322                 display_error(_("There is no supplier selected."));
323                 set_focus('supplier_id');
324                 return false;
325         } 
326         
327         if (!is_date($_POST['OrderDate'])) 
328         {
329                 display_error(_("The entered order date is invalid."));
330                 set_focus('OrderDate');
331                 return false;
332         } 
333         
334         if (!$_SESSION['PO']->order_no) 
335         {
336         if (!$Refs->is_valid(get_post('ref'))) 
337         {
338                 display_error(_("There is no reference entered for this purchase order."));
339                         set_focus('ref');
340                 return false;
341         } 
342         
343         if (!is_new_reference(get_post('ref'), $_SESSION['PO']->trans_type)) 
344         {
345                 display_error(_("The entered reference is already in use."));
346                         set_focus('ref');
347                 return false;
348         }
349         }
350         
351         if ($_SESSION['PO']->trans_type == ST_PURCHORDER && get_post('delivery_address') == '')
352         {
353                 display_error(_("There is no delivery address specified."));
354                 set_focus('delivery_address');
355                 return false;
356         } 
357         
358         if (get_post('StkLocation') == '')
359         {
360                 display_error(_("There is no location specified to move any items into."));
361                 set_focus('StkLocation');
362                 return false;
363         } 
364         
365         if ($_SESSION['PO']->order_has_items() == false)
366         {
367         display_error (_("The order cannot be placed because there are no lines entered on this order."));
368         return false;
369         }
370                 
371         return true;
372 }
373
374 //---------------------------------------------------------------------------------------------------
375
376 function handle_commit_order()
377 {
378         $cart = &$_SESSION['PO'];
379
380         if (can_commit()) {
381
382                 copy_to_cart();
383                 if ($cart->trans_type != ST_PURCHORDER) {
384                         // for direct grn/invoice set same dates for lines as for whole document
385                         foreach ($cart->line_items as $line_no =>$line)
386                                 $cart->line_items[$line_no]->req_del_date = $cart->orig_order_date;
387                 }
388                 if ($cart->order_no == 0) { // new po/grn/invoice
389                         /*its a new order to be inserted */
390                         $ref = $cart->reference;
391                         if ($cart->trans_type != ST_PURCHORDER) {
392                                 $cart->reference = 'auto';
393                                 begin_transaction();    // all db changes as single transaction for direct document
394                         }
395                         $order_no = add_po($cart);
396                         new_doc_date($cart->orig_order_date); 
397                 $cart->order_no = $order_no;
398
399                         if ($cart->trans_type == ST_PURCHORDER) {
400                                 unset($_SESSION['PO']);
401                         meta_forward($_SERVER['PHP_SELF'], "AddedID=$order_no");
402                 }
403                         //Direct GRN
404                         if ($cart->trans_type == ST_SUPPRECEIVE)
405                                 $cart->reference = $ref;
406                         $cart->Comments = $cart->reference; //grn does not hold supp_ref
407                         foreach($cart->line_items as $key => $line)
408                                 $cart->line_items[$key]->receive_qty = $line->quantity;
409                         $grn_no = add_grn($cart);
410                         if ($cart->trans_type == ST_SUPPRECEIVE) {
411                                 commit_transaction(); // save PO+GRN
412                                 unset($_SESSION['PO']);
413                         meta_forward($_SERVER['PHP_SELF'], "AddedGRN=$grn_no");
414                         }
415 //                      Direct Purchase Invoice
416                         $inv = new supp_trans(ST_SUPPINVOICE);
417                         $inv->Comments = $cart->Comments;
418                         $inv->supplier_id = $cart->supplier_id;
419                         $inv->tran_date = $cart->orig_order_date;
420                         $inv->reference = $ref;
421                         $inv->supp_reference = $cart->supp_ref;
422                         $supp = get_supplier($cart->supplier_id);
423                         $inv->tax_group_id = $supp['tax_group_id'];
424 //                      $inv->ov_discount 'this isn't used at all'
425 //                      $inv->terms = not used, TODO
426                         $terms =  $supp['payment_terms'];
427                         $inv->ov_amount = $inv->ov_gst = 0;
428                         $inv->due_date = get_invoice_duedate($terms, $inv->tran_date);
429                         foreach($cart->line_items as $key => $line) {
430                                 $inv->add_grn_to_trans($line->grn_item_id, $line->po_detail_rec, $line->stock_id,
431                                         $line->item_description, $line->receive_qty, 0, $line->receive_qty,
432                                         $line->price, $line->price, true, get_standard_cost($line->stock_id), '');
433                                 $inv->ov_amount += round2(($line->receive_qty * $line->price), user_price_dec());
434                         }
435                         $taxes = $inv->get_taxes($inv->tax_group_id, 0, false);
436                         foreach( $taxes as $taxitem) {
437                                 $inv->ov_gst += round2($taxitem['Value'], user_price_dec());
438                         }
439                         $inv_no = add_supp_invoice($inv);
440                         commit_transaction(); // save PO+GRN+PI
441                         // payment for cash terms...
442                         unset($_SESSION['PO']);
443                 meta_forward($_SERVER['PHP_SELF'], "AddedPI=$inv_no");
444                 }
445                 else { // order modification
446                 
447                         $order_no = update_po($cart);
448                         unset($_SESSION['PO']);
449                 meta_forward($_SERVER['PHP_SELF'], "AddedID=$order_no&Updated=1");      
450                 }
451         }
452 }
453 //---------------------------------------------------------------------------------------------------
454 $id = find_submit('Delete');
455 if ($id != -1)
456         handle_delete_item($id);
457
458 if (isset($_POST['Commit']))
459 {
460         handle_commit_order();
461 }
462 if (isset($_POST['UpdateLine']))
463         handle_update_item();
464
465 if (isset($_POST['EnterLine']))
466         handle_add_new_item();
467
468 if (isset($_POST['CancelOrder'])) 
469         handle_cancel_po();
470
471 if (isset($_POST['CancelUpdate']))
472         unset_form_variables();
473
474 if (isset($_POST['CancelUpdate']) || isset($_POST['UpdateLine'])) {
475         line_start_focus();
476 }
477
478 //---------------------------------------------------------------------------------------------------
479
480 start_form();
481
482 display_po_header($_SESSION['PO']);
483 echo "<br>";
484
485 display_po_items($_SESSION['PO']);
486
487 start_table(TABLESTYLE2);
488 textarea_row(_("Memo:"), 'Comments', null, 70, 4);
489
490 end_table(1);
491
492 div_start('controls', 'items_table');
493 if ($_SESSION['PO']->order_has_items()) 
494 {
495         if ($_SESSION['PO']->order_no)
496                 submit_center_first('Commit', _("Update Order"), '', 'default');
497         else
498                 submit_center_first('Commit', _("Place Order"), '', 'default');
499         submit_center_last('CancelOrder', _("Cancel Order"));   
500 }
501 else
502         submit_center('CancelOrder', _("Cancel Order"), true, false, 'cancel');
503 div_end();
504 //---------------------------------------------------------------------------------------------------
505
506 end_form();
507 end_page();
508 ?>