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