c63e0f2fc745ddad56426ce053f6ab812c67b0de
[fa-stable.git] / sales / sales_order_entry.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 //-----------------------------------------------------------------------------
13 //
14 //      Entry/Modify Sales Order
15 //      Entry Direct Delivery
16 //      Entry Direct Invoice
17 //
18
19 $page_security = 1;
20 $path_to_root="..";
21
22 include_once($path_to_root . "/sales/includes/cart_class.inc");
23 include_once($path_to_root . "/includes/session.inc");
24 include_once($path_to_root . "/sales/includes/sales_ui.inc");
25 include_once($path_to_root . "/sales/includes/ui/sales_order_ui.inc");
26 include_once($path_to_root . "/sales/includes/sales_db.inc");
27 include_once($path_to_root . "/sales/includes/db/sales_types_db.inc");
28 include_once($path_to_root . "/reporting/includes/reporting.inc");
29 $js = '';
30
31 editor_redirect( array(
32         'customer_id' => $path_to_root.'/sales/manage/customers.php?debtor_no='.get_post('customer_id'),
33         'branch_id' => $path_to_root.'/sales/manage/customer_branches.php?branch_id='.get_post('branch_id'),
34         ));
35
36 editor_return( array(
37         'customer_id'=>'customer_id',
38         'branch_id'=>'branch_id'));
39
40 if ($use_popup_windows) {
41         $js .= get_js_open_window(900, 500);
42 }
43
44 if ($use_date_picker) {
45         $js .= get_js_date_picker();
46 }
47
48 if (isset($_GET['NewDelivery']) && is_numeric($_GET['NewDelivery'])) {
49
50         $_SESSION['page_title'] = _("Direct Sales Delivery");
51         create_cart(13, $_GET['NewDelivery']);
52
53 } elseif (isset($_GET['NewInvoice']) && is_numeric($_GET['NewInvoice'])) {
54
55         $_SESSION['page_title'] = _("Direct Sales Invoice");
56         create_cart(10, $_GET['NewInvoice']);
57
58 } elseif (isset($_GET['ModifyOrderNumber']) && is_numeric($_GET['ModifyOrderNumber'])) {
59
60         $help_page_title = _('Modifying Sales Order');
61         $_SESSION['page_title'] = sprintf( _("Modifying Sales Order # %d"), $_GET['ModifyOrderNumber']);
62         create_cart(30, $_GET['ModifyOrderNumber']);
63
64 } elseif (isset($_GET['NewOrder'])) {
65
66         $_SESSION['page_title'] = _("New Sales Order Entry");
67         create_cart(30, 0);
68 }
69
70 page($_SESSION['page_title'], false, false, "", $js);
71 //-----------------------------------------------------------------------------
72
73 if (isset($_GET['AddedID'])) {
74         $order_no = $_GET['AddedID'];
75         display_notification_centered(sprintf( _("Order # %d has been entered."),$order_no));
76
77         submenu_view(_("&View This Order"), 30, $order_no);
78
79         submenu_print(_("&Print This Order"), 30, $order_no, 'prtopt');
80         set_focus('prtopt');
81         
82         submenu_option(_("Make &Delivery Against This Order"),
83                 "/sales/customer_delivery.php?OrderNumber=$order_no");
84
85         submenu_option(_("Enter a &New Order"), $_SERVER['PHP_SELF']."?NewOrder=0");
86
87         display_footer_exit();
88
89 } elseif (isset($_GET['UpdatedID'])) {
90         $order_no = $_GET['UpdatedID'];
91
92         display_notification_centered(sprintf( _("Order # %d has been updated."),$order_no));
93
94         submenu_view(_("&View This Order"), 30, $order_no);
95
96         submenu_print(_("&Print This Order"), 30, $order_no, 'prtopt');
97         set_focus('prtopt');
98
99         submenu_option(_("Confirm Order Quantities and Make &Delivery"),
100                 "/sales/customer_delivery.php?OrderNumber=$order_no");
101
102         submenu_option(_("Select A Different &Order"),
103                 "/sales/inquiry/sales_orders_view.php?OutstandingOnly=1");
104
105         display_footer_exit();
106
107 } elseif (isset($_GET['AddedDN'])) {
108         $delivery = $_GET['AddedDN'];
109
110         display_notification_centered(sprintf(_("Delivery # %d has been entered."),$delivery));
111
112         submenu_view(_("&View This Delivery"), 13, $delivery);
113
114         submenu_print(_("&Print Delivery Note"), 13, $delivery, 'prtopt');
115         set_focus('prtopt');
116
117         submenu_option(_("Make &Invoice Against This Delivery"),
118                 "/sales/customer_invoice.php?DeliveryNumber=$delivery");
119
120         if ((isset($_GET['Type']) && $_GET['Type'] == 1))
121                 submenu_option(_("Enter a New Template &Delivery"),
122                         "inquiry/sales_orders_view.php?DeliveryTemplates=Yes");
123         else
124                 submenu_option(_("Enter a &New Delivery"), 
125                         $_SERVER['PHP_SELF']."?NewDelivery=0");
126
127         display_footer_exit();
128
129 } elseif (isset($_GET['AddedDI'])) {
130         $invoice = $_GET['AddedDI'];
131
132         display_notification_centered(sprintf(_("Invoice # %d has been entered."), $invoice));
133
134         submenu_view(_("&View This Invoice"), 10, $invoice);
135
136         submenu_print(_("&Print Sales Invoice"), 10, $invoice, 'prtopt');
137         set_focus('prtopt');
138
139         if ((isset($_GET['Type']) && $_GET['Type'] == 1))
140                 submenu_option(_("Enter a &New Template Invoice"), 
141                         "inquiry/sales_orders_view.php?InvoiceTemplates=Yes");
142         else
143                 submenu_option(_("Enter a &New Direct Invoice"),
144                         $_SERVER['PHP_SELF']."?NewInvoice=0");
145
146         display_footer_exit();
147 } else
148         check_edit_conflicts();
149
150 //-----------------------------------------------------------------------------
151
152 function copy_to_cart()
153 {
154         $cart = &$_SESSION['Items'];
155
156         if ($cart->trans_type!=30) {
157                 $cart->reference = $_POST['ref'];
158         } 
159         $cart->Comments =  $_POST['Comments'];
160
161         $cart->document_date = $_POST['OrderDate'];
162         if ($cart->trans_type == 10)
163                 $cart->cash = $_POST['cash']; 
164         if ($cart->cash) {
165                 $cart->due_date = $cart->document_date;
166                 $cart->phone = $cart->cust_ref = $cart->delivery_address = '';
167                 $cart->freight_cost = 0;
168                 $cart->ship_via = 1;
169                 $cart->deliver_to = '';//$_POST['deliver_to'];
170         } else {
171                 $cart->due_date = $_POST['delivery_date'];
172                 $cart->cust_ref = $_POST['cust_ref'];
173                 $cart->freight_cost = input_num('freight_cost');
174                 $cart->deliver_to = $_POST['deliver_to'];
175                 $cart->delivery_address = $_POST['delivery_address'];
176                 $cart->phone = $_POST['phone'];
177                 $cart->Location = $_POST['Location'];
178                 $cart->ship_via = $_POST['ship_via'];
179         }
180         if (isset($_POST['email']))
181                 $cart->email =$_POST['email'];
182         else
183                 $cart->email = '';
184         $cart->customer_id      = $_POST['customer_id'];
185         $cart->Branch = $_POST['branch_id'];
186         $cart->sales_type = $_POST['sales_type'];
187         // POS
188         if ($cart->trans_type!=30) { // 2008-11-12 Joe Hunt
189                 $cart->dimension_id = $_POST['dimension_id'];
190                 $cart->dimension2_id = $_POST['dimension2_id'];
191         }       
192 }
193
194 //-----------------------------------------------------------------------------
195
196 function copy_from_cart()
197 {
198         $cart = &$_SESSION['Items'];
199         if ($cart->trans_type!=30) {
200                 $_POST['ref'] = $cart->reference;
201         }
202         $_POST['Comments'] = $cart->Comments;
203
204         $_POST['OrderDate'] = $cart->document_date;
205         $_POST['delivery_date'] = $cart->due_date;
206         $_POST['cust_ref'] = $cart->cust_ref;
207         $_POST['freight_cost'] = price_format($cart->freight_cost);
208
209         $_POST['deliver_to'] = $cart->deliver_to;
210         $_POST['delivery_address'] = $cart->delivery_address;
211         $_POST['phone'] = $cart->phone;
212         $_POST['Location'] = $cart->Location;
213         $_POST['ship_via'] = $cart->ship_via;
214
215         $_POST['customer_id'] = $cart->customer_id;
216
217         $_POST['branch_id'] = $cart->Branch;
218         $_POST['sales_type'] = $cart->sales_type;
219         // POS 
220         if ($cart->trans_type == 10)
221                 $_POST['cash'] = $cart->cash;
222         if ($cart->trans_type!=30) { // 2008-11-12 Joe Hunt
223                 $_POST['dimension_id'] = $cart->dimension_id;
224                 $_POST['dimension2_id'] = $cart->dimension2_id;
225         }       
226         $_POST['cart_id'] = $cart->cart_id;
227                 
228 }
229 //--------------------------------------------------------------------------------
230
231 function line_start_focus() {
232   global        $Ajax;
233
234   $Ajax->activate('items_table');
235   set_focus('_stock_id_edit');
236 }
237 //--------------------------------------------------------------------------------
238
239 function can_process() {
240         if (!is_date($_POST['OrderDate'])) {
241                 display_error(_("The entered date is invalid."));
242                 set_focus('OrderDate');
243                 return false;
244         }
245         if ($_SESSION['Items']->trans_type!=30 && !is_date_in_fiscalyear($_POST['OrderDate'])) {
246                 display_error(_("The entered date is not in fiscal year"));
247                 set_focus('OrderDate');
248                 return false;
249         }
250         if (count($_SESSION['Items']->line_items) == 0) {
251                 display_error(_("You must enter at least one non empty item line."));
252                 set_focus('AddItem');
253                 return false;
254         }
255         if ($_SESSION['Items']->cash == 0) {
256         if (strlen($_POST['deliver_to']) <= 1) {
257                 display_error(_("You must enter the person or company to whom delivery should be made to."));
258                 set_focus('deliver_to');
259                 return false;
260         }
261
262                 if (strlen($_POST['delivery_address']) <= 1) {
263                         display_error( _("You should enter the street address in the box provided. Orders cannot be accepted without a valid street address."));
264                         set_focus('delivery_address');
265                         return false;
266                 }
267
268                 if ($_POST['freight_cost'] == "")
269                         $_POST['freight_cost'] = price_format(0);
270
271                 if (!check_num('freight_cost',0)) {
272                         display_error(_("The shipping cost entered is expected to be numeric."));
273                         set_focus('freight_cost');
274                         return false;
275                 }
276                 if (!is_date($_POST['delivery_date'])) {
277                         display_error(_("The delivery date is invalid."));
278                         set_focus('delivery_date');
279                         return false;
280                 }
281                 //if (date1_greater_date2($_SESSION['Items']->document_date, $_POST['delivery_date'])) {
282                 if (date1_greater_date2($_POST['OrderDate'], $_POST['delivery_date'])) {
283                         display_error(_("The requested delivery date is before the date of the order."));
284                         set_focus('delivery_date');
285                         return false;
286                 }
287         }
288         if ($_SESSION['Items']->trans_type != 30 && !references::is_valid($_POST['ref'])) {
289                 display_error(_("You must enter a reference."));
290                 set_focus('ref');
291                 return false;
292         }
293         return true;
294 }
295
296 //-----------------------------------------------------------------------------
297
298 if (isset($_POST['ProcessOrder']) && can_process()) {
299         copy_to_cart();
300
301         $modified = ($_SESSION['Items']->trans_no != 0);
302         $so_type = $_SESSION['Items']->so_type;
303         $_SESSION['Items']->write(1);
304         if (count($messages)) { // abort on failure or error messages are lost
305                 $Ajax->activate('_page_body');
306                 display_footer_exit();
307         }
308         $trans_no = key($_SESSION['Items']->trans_no);
309         $trans_type = $_SESSION['Items']->trans_type;
310         new_doc_date($_SESSION['Items']->document_date);
311         processing_end();
312         if ($modified) {
313                 meta_forward($_SERVER['PHP_SELF'], "UpdatedID=$trans_no");
314         } elseif ($trans_type == 30) {
315                 meta_forward($_SERVER['PHP_SELF'], "AddedID=$trans_no");
316         } elseif ($trans_type == 10) {
317                 meta_forward($_SERVER['PHP_SELF'], "AddedDI=$trans_no&Type=$so_type");
318         } else {
319                 meta_forward($_SERVER['PHP_SELF'], "AddedDN=$trans_no&Type=$so_type");
320         }
321 }
322
323 //--------------------------------------------------------------------------------
324
325 function check_item_data()
326 {
327         if (!check_num('qty', 0) || !check_num('Disc', 0, 100)) {
328                 display_error( _("The item could not be updated because you are attempting to set the quantity ordered to less than 0, or the discount percent to more than 100."));
329                 set_focus('qty');
330                 return false;
331         } elseif (!check_num('price', 0)) {
332                 display_error( _("Price for item must be entered and can not be less than 0"));
333                 set_focus('price');
334                 return false;
335         } elseif (isset($_POST['LineNo']) && isset($_SESSION['Items']->line_items[$_POST['LineNo']])
336             && !check_num('qty', $_SESSION['Items']->line_items[$_POST['LineNo']]->qty_done)) {
337
338                 set_focus('qty');
339                 display_error(_("You attempting to make the quantity ordered a quantity less than has already been delivered. The quantity delivered cannot be modified retrospectively."));
340                 return false;
341         } // Joe Hunt added 2008-09-22 -------------------------
342         elseif ($_SESSION['Items']->trans_type!=30 && !sys_prefs::allow_negative_stock() &&
343                 is_inventory_item($_POST['stock_id']))
344         {
345                 $qoh = get_qoh_on_date($_POST['stock_id'], $_POST['Location'], $_POST['OrderDate']);
346                 if (input_num('qty') > $qoh)
347                 {
348                         $stock = get_item($_POST['stock_id']);
349                         display_error(_("The delivery cannot be processed because there is an insufficient quantity for item:") .
350                                 " " . $stock['stock_id'] . " - " . $stock['description'] . " - " .
351                                 _("Quantity On Hand") . " = " . number_format2($qoh, get_qty_dec($_POST['stock_id'])));
352                         return false;
353                 }
354                 return true;
355         }
356         return true;
357 }
358
359 //--------------------------------------------------------------------------------
360
361 function handle_update_item()
362 {
363         if ($_POST['UpdateItem'] != '' && check_item_data()) {
364                 //alert("description=".$_POST['item_description']);
365                 //$_SESSION['items']->line_items[$_POST['LineNo']]->item_description = $_POST['item_description'];
366                 $_SESSION['Items']->update_cart_item($_POST['LineNo'],
367                  input_num('qty'), input_num('price'),
368                  input_num('Disc') / 100, $_POST['item_description'] );
369         }
370   line_start_focus();
371 }
372
373 //--------------------------------------------------------------------------------
374
375 function handle_delete_item($line_no)
376 {
377     if ($_SESSION['Items']->some_already_delivered($line_no) == 0) {
378             $_SESSION['Items']->remove_from_cart($line_no);
379     } else {
380         display_error(_("This item cannot be deleted because some of it has already been delivered."));
381     }
382     line_start_focus();
383 }
384
385 //--------------------------------------------------------------------------------
386
387 function handle_new_item()
388 {
389
390         if (!check_item_data()) {
391                         return;
392         }
393         add_to_order($_SESSION['Items'], $_POST['stock_id'], input_num('qty'),
394                 input_num('price'), input_num('Disc') / 100);
395         $_POST['_stock_id_edit'] = $_POST['stock_id']   = "";
396         line_start_focus();
397 }
398
399 //--------------------------------------------------------------------------------
400
401 function  handle_cancel_order()
402 {
403         global $path_to_root, $Ajax;
404
405
406         if ($_SESSION['Items']->trans_type == 13) {
407                 display_note(_("Direct delivery entry has been cancelled as requested."), 1);
408                 submenu_option(_("Enter a New Sales Delivery"), $_SERVER['PHP_SELF']."?NewDelivery=0");
409
410         } elseif ($_SESSION['Items']->trans_type == 10) {
411                 display_note(_("Direct invoice entry has been cancelled as requested."), 1);
412                 submenu_option(_("Enter a New Sales Invoice"),  $_SERVER['PHP_SELF']."?NewInvoice=0");
413         } else {
414                 if ($_SESSION['Items']->trans_no != 0) {
415                         if (sales_order_has_deliveries(key($_SESSION['Items']->trans_no)))
416                                 display_error(_("This order cannot be cancelled because some of it has already been invoiced or dispatched. However, the line item quantities may be modified."));
417                         else {
418                                 delete_sales_order(key($_SESSION['Items']->trans_no));
419
420                         display_note(_("This sales order has been cancelled as requested."), 1);
421                         submenu_option(_("Enter a New Sales Order"), $_SERVER['PHP_SELF']."?NewOrder=Yes");
422                         }
423                 } else {
424                         processing_end();
425                         meta_forward($path_to_root.'/index.php?application=orders');
426                 }
427         }
428         $Ajax->activate('_page_body');
429         processing_end();
430         br(1);
431         end_page();
432         exit;
433 }
434
435 //--------------------------------------------------------------------------------
436
437 function create_cart($type, $trans_no)
438 {
439         processing_start();
440         $doc_type = $type;
441
442         if($type != 30 && $trans_no != 0) { // this is template
443                 $doc_type = 30;
444
445                 $doc = new Cart(30, array($trans_no));
446                 $doc->trans_type = $type;
447                 $doc->trans_no = 0;
448                 $doc->document_date = new_doc_date();
449                 if ($type == 10) {
450                         $doc->due_date = get_invoice_duedate($doc->customer_id, $doc->document_date);
451                         $doc->pos = user_pos();
452                         $pos = get_sales_point($doc->pos);
453                         $doc->cash = $pos['cash_sale'];
454                         if (!$pos['cash_sale'] || !$pos['credit_sale']) 
455                                 $doc->pos = -1; // mark not editable payment type
456                         else
457                                 $doc->cash = date_diff($doc->due_date, Today(), 'd')<2;
458                 } else
459                         $doc->due_date = $doc->document_date;
460                 $doc->reference = references::get_next($doc->trans_type);
461                 $doc->Comments='';
462                 foreach($doc->line_items as $line_no => $line) {
463                         $doc->line_items[$line_no]->qty_done = 0;
464                 }
465                 $_SESSION['Items'] = $doc;
466         } else
467                 $_SESSION['Items'] = new Cart($type,array($trans_no));
468         copy_from_cart();
469 }
470
471 //--------------------------------------------------------------------------------
472
473 if (isset($_POST['CancelOrder']))
474         handle_cancel_order();
475
476 $id = find_submit('Delete');
477 if ($id!=-1)
478         handle_delete_item($id);
479
480 if (isset($_POST['UpdateItem']))
481         handle_update_item();
482
483 if (isset($_POST['AddItem']))
484         handle_new_item();
485
486 if (isset($_POST['CancelItemChanges'])) {
487         line_start_focus();
488 }
489
490 //--------------------------------------------------------------------------------
491 check_db_has_stock_items(_("There are no inventory items defined in the system."));
492
493 check_db_has_customer_branches(_("There are no customers, or there are no customers with branches. Please define customers and customer branches."));
494
495 if ($_SESSION['Items']->trans_type == 10) {
496         $idate = _("Invoice Date:");
497         $orderitems = _("Sales Invoice Items");
498         $deliverydetails = _("Enter Delivery Details and Confirm Invoice");
499         $cancelorder = _("Cancel Invoice");
500         $porder = _("Place Invoice");
501 } elseif ($_SESSION['Items']->trans_type == 13) {
502         $idate = _("Delivery Date:");
503         $orderitems = _("Delivery Note Items");
504         $deliverydetails = _("Enter Delivery Details and Confirm Dispatch");
505         $cancelorder = _("Cancel Delivery");
506         $porder = _("Place Delivery");
507 } else {
508         $idate = _("Order Date:");
509         $orderitems = _("Sales Order Items");
510         $deliverydetails = _("Enter Delivery Details and Confirm Order");
511         $cancelorder = _("Cancel Order");
512         $porder = _("Place Order");
513         $corder = _("Commit Order Changes");
514 }
515 start_form();
516 hidden('cart_id');
517
518 $customer_error = display_order_header($_SESSION['Items'],
519         ($_SESSION['Items']->any_already_delivered() == 0), $idate);
520
521 if ($customer_error == "") {
522         start_table("$table_style width=80%", 10);
523         echo "<tr><td>";
524         display_order_summary($orderitems, $_SESSION['Items'], true);
525         echo "</td></tr>";
526         echo "<tr><td>";
527         display_delivery_details($_SESSION['Items']);
528         echo "</td></tr>";
529         end_table(1);
530
531         if ($_SESSION['Items']->trans_no == 0) {
532
533                 submit_center_first('ProcessOrder', $porder,
534                     _('Check entered data and save document'), 'default');
535         } else {
536                 submit_center_first('ProcessOrder', $corder,
537                     _('Validate changes and update document'), 'default');
538         }
539
540         submit_center_last('CancelOrder', $cancelorder,
541            _('Cancels document entry or removes sales order when editing an old document'));
542 } else {
543         display_error($customer_error);
544 }
545 end_form();
546 end_page();
547
548 ?>