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