Final rewriting of sales module
authorJanusz Dobrowolski <janusz@frontaccounting.eu>
Fri, 7 Mar 2008 21:07:13 +0000 (21:07 +0000)
committerJanusz Dobrowolski <janusz@frontaccounting.eu>
Fri, 7 Mar 2008 21:07:13 +0000 (21:07 +0000)
40 files changed:
applications/customers.php
includes/ui/ui_input.inc
reporting/rep107.php
reporting/rep109.php
reporting/rep110.php
sales/allocations/customer_allocate.php
sales/allocations/customer_allocation_main.php
sales/credit_note_entry.php
sales/customer_credit_invoice.php
sales/customer_delivery.php
sales/customer_invoice.php
sales/customer_payments.php
sales/includes/cart_class.inc
sales/includes/db/cust_trans_db.inc
sales/includes/db/cust_trans_details_db.inc
sales/includes/db/custalloc_db.inc
sales/includes/db/customers_db.inc
sales/includes/db/payment_db.inc
sales/includes/db/sales_credit_db.inc
sales/includes/db/sales_delivery_db.inc
sales/includes/db/sales_invoice_db.inc
sales/includes/db/sales_order_db.inc
sales/includes/db/sales_types_db.inc
sales/includes/sales_db.inc
sales/includes/sales_ui.inc
sales/includes/ui/print_invoice.inc
sales/includes/ui/sales_credit_ui.inc
sales/includes/ui/sales_order_ui.inc
sales/inquiry/customer_allocation_inquiry.php
sales/inquiry/customer_inquiry.php
sales/inquiry/sales_deliveries_view.php
sales/inquiry/sales_orders_view.php
sales/manage/credit_status.php
sales/manage/sales_types.php
sales/sales_order_entry.php
sales/view/view_credit.php
sales/view/view_dispatch.php
sales/view/view_invoice.php
sales/view/view_receipt.php
sales/view/view_sales_order.php

index c390b6e0a1480b50e543a6dbf885d916eb4a6d53..c6d5519c85cd5392480c07bc910f7a51e868dcb1 100644 (file)
                
                        $this->add_module(_("Transactions"));
                        $this->add_lapp_function(0, _("Sales Order Entry"),"sales/sales_order_entry.php?NewOrder=Yes");
+                       $this->add_lapp_function(0, _("Direct Delivery"),"sales/sales_order_entry.php?NewDelivery=0");                  
+                       $this->add_lapp_function(0, _("Direct Invoice"),"sales/sales_order_entry.php?NewInvoice=0");
+                       $this->add_lapp_function(0, "","");
                        $this->add_lapp_function(0, _("Delivery Against Sales Orders"),"sales/inquiry/sales_orders_view.php?OutstandingOnly=1");
-                       $this->add_lapp_function(0, _("Direct Delivery"),"sales/sales_order_entry.php?NewDelivery=Yes");                        
+                       $this->add_lapp_function(0, _("Invoice Against Sales Delivery"),"sales/inquiry/sales_deliveries_view.php?OutstandingOnly=1");
 
+                       $this->add_rapp_function(0, _("Template Delivery"),"sales/inquiry/sales_orders_view.php?DeliveryTemplates=Yes");
+                       $this->add_rapp_function(0, _("Template Invoice"),"sales/inquiry/sales_orders_view.php?InvoiceTemplates=Yes");
+                       $this->add_rapp_function(0, "","");
                        $this->add_rapp_function(0, _("Customer Payments"),"sales/customer_payments.php?");
-                       $this->add_rapp_function(0, _("Sales Invoices"),"sales/inquiry/sales_deliveries_view.php?OutstandingOnly=1");
                        $this->add_rapp_function(0, _("Customer Credit Notes"),"sales/credit_note_entry.php?NewCredit=Yes");
                        $this->add_rapp_function(0, _("Allocate Customer Payments or Credit Notes"),"sales/allocations/customer_allocation_main.php?");
 
index 7e122c3bb2abaad27e697e84ca33fb3e5781bf2b..ab33f649a81ce3cb4418b2ad9f4f4a5e191e03d7 100644 (file)
@@ -185,10 +185,12 @@ function label_cells($label, $value, $params="", $params2="")
        echo "<td $params2>$value</td>\n";
 }
 
-function label_row($label, $value, $params="", $params2="")
+function label_row($label, $value, $params="", $params2="", $leftfill=0)
 {
        echo "<tr>";
        label_cells($label, $value, $params, $params2);
+       if($leftfill!=0)
+         echo "<td colspan=$leftfill></td>";
        echo "</tr>\n";
 }
 
@@ -319,8 +321,7 @@ function percent_row($label, $name, $init=null)
 
        if (!isset($_POST[$name]) || $_POST[$name]=="")
        {
-               if ($init)
-                       $_POST[$name] = $init;
+                       $_POST[$name] = $init== null ? '' : $init;
        }
 
        text_row($label, $name, $_POST[$name], 6, 6, "", "%");
index 5e56cfc23921d0d6e96f01268595accb512f6e8e..7baef1a4daadcb783c316f9f3a6aca3f6684494c 100644 (file)
@@ -71,11 +71,12 @@ function print_invoices()
                                continue;
                        if (!exists_customer_trans($j, $i))
                                continue;
+                       $sign = $j==10 ? 1 : -1;
                        $myrow = get_customer_trans($i, $j);
                        $branch = get_branch($myrow["branch_code"]);
                        $branch['disable_branch'] = $paylink; // helper
                        if ($j == 10)
-                               $sales_order = get_sales_order($myrow["order_"]);
+                               $sales_order = get_sales_order_header($myrow["order_"]);
                        else
                                $sales_order = null;
                        if ($email == 1)
@@ -103,10 +104,10 @@ function print_invoices()
                        $SubTotal = 0;
                        while ($myrow2=db_fetch($result))
                        {
-                               $Net = ((1 - $myrow2["discount_percent"]) * $myrow2["FullUnitPrice"] * -$myrow2["quantity"]);
-                               $SubTotal += $Net;
-                       $DisplayPrice = number_format2($myrow2["FullUnitPrice"],$dec);
-                       $DisplayQty = number_format2(-$myrow2["quantity"],user_qty_dec());
+                       $Net = $sign * ((1 - $myrow2["discount_percent"]) * $myrow2["unit_price"] * $myrow2["quantity"]);
+                       $SubTotal += $Net;
+                       $DisplayPrice = number_format2($myrow2["unit_price"],$dec);
+                       $DisplayQty = number_format2($sign*$myrow2["quantity"],user_qty_dec());
                        $DisplayNet = number_format2($Net,$dec);
                        if ($myrow2["discount_percent"]==0)
                                        $DisplayDiscount ="";
@@ -133,9 +134,9 @@ function print_invoices()
                        }
 
                        $DisplaySubTot = number_format2($SubTotal,$dec);
-                       $DisplayFreight = number_format2($myrow["ov_freight"],$dec);
+                       $DisplayFreight = number_format2($sign*$myrow["ov_freight"],$dec);
 
-               $rep->row = $rep->bottomMargin + (15 * $rep->lineHeight);
+                       $rep->row = $rep->bottomMargin + (15 * $rep->lineHeight);
                        $linetype = true;
                        $doctype = $j;
                        if ($rep->currency != $myrow['curr_code'])
@@ -156,7 +157,8 @@ function print_invoices()
                        $tax_items = get_customer_trans_tax_details($j, $i);
                while ($tax_item = db_fetch($tax_items))
                {
-                       $DisplayTax = number_format2($tax_item['amount'], $dec);
+                       $DisplayTax = number_format2($sign*$tax_item['amount'], $dec);
+                       
                        if ($tax_item['included_in_price'])
                        {
                                        $rep->TextCol(3, 7, $doc_Included . " " . $tax_item['tax_type_name'] .
@@ -171,11 +173,11 @@ function print_invoices()
                                $rep->NewLine();
                }
                $rep->NewLine();
-                       $DisplayTotal = number_format2($myrow["ov_freight"] + $myrow["ov_gst"] +
-                               $myrow["ov_amount"],$dec);
+                       $DisplayTotal = number_format2($sign*($myrow["ov_freight"] + $myrow["ov_gst"] +
+                               $myrow["ov_amount"]+$myrow["ov_freight_tax"]),$dec);
                        $rep->Font('bold');
                        $rep->TextCol(3, 6, $doc_TOTAL_INVOICE, - 2);
-                       $rep->TextCol(6, 7,     $DisplayTotal, -2);
+                       $rep->TextCol(6, 7, $DisplayTotal, -2);
                        $rep->Font();
                        if ($email == 1)
                        {
index db251ae50ca4e46a7eff0c4abdd785ff09c194a6..dac0e0563f873d459e78f08d4d17e2c57dbb8825 100644 (file)
@@ -19,20 +19,6 @@ include_once($path_to_root . "sales/includes/sales_db.inc");
 // trial_inquiry_controls();
 print_sales_orders();
 
-//----------------------------------------------------------------------------------------------------
-
-function get_sales_order_details($order_no)
-{
-       $sql = "SELECT stk_code, unit_price, ".TB_PREF."sales_order_details.description,
-               ".TB_PREF."sales_order_details.quantity, discount_percent, 
-               qty_sent, units,
-               ".TB_PREF."stock_master.material_cost + ".TB_PREF."stock_master.labour_cost + ".TB_PREF."stock_master.overhead_cost AS standard_cost
-               FROM ".TB_PREF."sales_order_details, ".TB_PREF."stock_master 
-                       WHERE ".TB_PREF."sales_order_details.stk_code = ".TB_PREF."stock_master.stock_id 
-                               AND order_no =" . $order_no;
-       return db_query($sql, "Retreive order Line Items");
-}
-
 $print_as_quote = 0;
 
 function print_sales_orders()
@@ -79,7 +65,7 @@ function print_sales_orders()
 
        for ($i = $from; $i <= $to; $i++)
        {
-               $myrow = get_sales_order($i);
+               $myrow = get_sales_order_header($i);
                $branch = get_branch($myrow["branch_code"]);
                if ($email == 1)
                {
index 7142c38666a557b06a5acd1b1c6ef6faae422ba6..de81925bcc5e600d6bc5e5740fad9127af50fc81 100644 (file)
@@ -65,7 +65,7 @@ function print_deliveries()
                                continue;
                        $myrow = get_customer_trans($i, 13);
                        $branch = get_branch($myrow["branch_code"]);
-                       $sales_order = get_sales_order($myrow["order_"]); // ?
+                       $sales_order = get_sales_order_header($myrow["order_"]); // ?
                        if ($email == 1)
                        {
                                $rep = new FrontReport("", "", user_pagesize());
@@ -83,10 +83,10 @@ function print_deliveries()
                        $SubTotal = 0;
                        while ($myrow2=db_fetch($result))
                        {
-                               $Net = ((1 - $myrow2["discount_percent"]) * $myrow2["FullUnitPrice"] * -$myrow2["quantity"]);
+                               $Net = ((1 - $myrow2["discount_percent"]) * $myrow2["unit_price"] * $myrow2["quantity"]);
                                $SubTotal += $Net;
-                       $DisplayPrice = number_format2($myrow2["FullUnitPrice"],$dec);
-                       $DisplayQty = number_format2(-$myrow2["quantity"],user_qty_dec());
+                       $DisplayPrice = number_format2($myrow2["unit_price"],$dec);
+                       $DisplayQty = number_format2($myrow2["quantity"],user_qty_dec());
                        $DisplayNet = number_format2($Net,$dec);
                        if ($myrow2["discount_percent"]==0)
                                        $DisplayDiscount ="";
@@ -151,7 +151,7 @@ function print_deliveries()
                                $rep->NewLine();
                }
                $rep->NewLine();
-                       $DisplayTotal = number_format2($myrow["ov_freight"] + $myrow["ov_gst"] +
+                       $DisplayTotal = number_format2($myrow["ov_freight"] +$myrow["ov_freight_tax"] + $myrow["ov_gst"] +
                                $myrow["ov_amount"],$dec);
                        $rep->Font('bold');     
                        $rep->TextCol(3, 6, $doc_TOTAL_DELIVERY, - 2); 
index 15eba74cdd4c27436b0afba00284906196e42c22..46daa72dde799c47617f19c419c9c139fb357e48 100644 (file)
@@ -2,16 +2,19 @@
 
 $path_to_root="../..";
 $page_security = 3;
+
 include($path_to_root . "/includes/ui/allocation_cart.inc");
 include_once($path_to_root . "/includes/session.inc");
-
 include_once($path_to_root . "/sales/includes/sales_ui.inc");
 include_once($path_to_root . "/sales/includes/sales_db.inc");
+
 $js = "";
 if ($use_popup_windows)
        $js .= get_js_open_window(900, 500);
-page(_("Allocate Customer Payment or Credit Note"), false, false, "", $js);
 
+$js .= get_js_allocate();
+
+page(_("Allocate Customer Payment or Credit Note"), false, false, "", $js);
 
 //--------------------------------------------------------------------------------
 
@@ -22,7 +25,7 @@ function clear_allocations()
                unset($_SESSION['alloc']->allocs);
                unset($_SESSION['alloc']);
        }
-       session_register("alloc");
+       session_register('alloc');
 }
 
 //--------------------------------------------------------------------------------
@@ -58,7 +61,7 @@ function check_data()
                $total_allocated += $_POST['amount' . $counter];
        }
 
-       if ($total_allocated + $_SESSION['alloc']->amount > sys_prefs::allocation_settled_allowance())
+       if ($total_allocated - $_SESSION['alloc']->amount > sys_prefs::allocation_settled_allowance())
        {
                display_error(_("These allocations cannot be processed because the amount allocated is more than the total amount left to allocate."));
                //echo  _("Total allocated:") . " " . $total_allocated ;
@@ -107,7 +110,7 @@ function handle_process()
 
 if (isset($_POST['Process']))
 {
-       if (check_data()) 
+       if (check_data())
        {
                handle_process();
                $_POST['Cancel'] = 1;
@@ -131,7 +134,7 @@ function get_allocations_for_transaction($type, $trans_no)
 
        $debtor = get_customer_trans($trans_no, $type);
 
-       $_SESSION['alloc'] = new allocation($trans_no, $type, $debtor["debtor_no"], 
+       $_SESSION['alloc'] = new allocation($trans_no, $type, $debtor["debtor_no"],
                $debtor["DebtorName"], $debtor["Total"], sql2date($debtor["tran_date"]));
 
        /* Now populate the array of possible (and previous actual) allocations for this customer */
@@ -171,22 +174,22 @@ function edit_allocations_for_transaction($type, $trans_no)
 
        start_form(false, true);
 
-    display_heading(_("Allocation of") . " " . systypes::name($_SESSION['alloc']->type) . " # " . $_SESSION['alloc']->trans_no);
+    display_heading(sprintf(_("Allocation of %s # %d"), systypes::name($_SESSION['alloc']->type),$_SESSION['alloc']->trans_no));
 
-       display_heading($_SESSION['alloc']->person_name);
+    display_heading($_SESSION['alloc']->person_name);
 
     display_heading2(_("Date:") . " <b>" . $_SESSION['alloc']->date_ . "</b>");
-    display_heading2(_("Total:") . " <b>" . number_format2(-$_SESSION['alloc']->amount,user_price_dec()) . "</b>");
+    display_heading2(_("Total:") . " <b>" . number_format2($_SESSION['alloc']->amount,user_price_dec()) . "</b>");
 
     echo "<br>";
 
     if (count($_SESSION['alloc']->allocs) > 0)
     {
                start_table($table_style);
-               
+
                $th = array(_("Transaction Type"), _("#"), _("Date"), _("Due Date"), _("Amount"),
                        _("Other Allocations"), _("This Allocation"), _("Left to Allocate"), "", "");
-                       
+
                table_header($th);
 
         $k = $counter = $total_allocated = 0;
@@ -210,33 +213,37 @@ function edit_allocations_for_transaction($type, $trans_no)
                hidden("un_allocated" . $counter, $un_allocated);
                amount_cell($un_allocated);
 
-                       label_cell("<a href='#' onclick='forms[0].amount$counter.value=forms[0].un_allocated$counter.value; return true;'>" . _("All") . "</a>");
-                       label_cell("<a href='#' onclick='forms[0].amount$counter.value=0; return true;'>" . _("None") . "</a>");
+                       label_cell("<a href='#' name=Alloc$counter onclick='allocate_all(this.name.substr(5));return true;'>"
+                                        . _("All") . "</a>");
+                       label_cell("<a href='#' name=DeAll$counter onclick='allocate_none(this.name.substr(5));return true;'>"
+                                        . _("None") . "</a>");
                        end_row();
 
            $total_allocated += $_POST['amount' . $counter];
            $counter++;
                }
 
-               label_row(_("Total Allocated"), number_format2($total_allocated,user_price_dec()), 
+               label_row(_("Total Allocated"), number_format2($total_allocated,user_price_dec()),
                        "colspan=6 align=right", "nowrap align=right");
-        if (-$_SESSION['alloc']->amount - $total_allocated < 0)
+        if ($_SESSION['alloc']->amount - $total_allocated < 0)
         {
                $font1 = "<font color=red>";
                $font2 = "</font>";
         }
         else
                $font1 = $font2 = "";
-        label_row(_("Left to Allocate"), $font1 . number_format2(-$_SESSION['alloc']->amount - 
-               $total_allocated,user_price_dec()) . $font2, "colspan=6 align=right", 
-               "nowrap align=right");
+               $left_to_allocate = $_SESSION['alloc']->amount - $total_allocated;
+               $left_to_allocate = number_format2($left_to_allocate, user_price_dec());
+        label_row(_("Left to Allocate"), $font1 . $left_to_allocate . $font2,
+               "colspan=6 align=right", "nowrap align=right");
         end_table(1);
 
                hidden('TotalNumberOfAllocs', $counter);
+               hidden('left_to_allocate', $left_to_allocate);
                submit_center_first('UpdateDisplay', _("Update"));
                submit('Process', _("Process"));
-       } 
-       else 
+       }
+       else
        {
        display_note(_("There are no unsettled transactions to allocate."), 0, 1);
     }
index 20baf5cace8b7002ffda2d6527091886b8308ef3..8d85e42317e8713d9aef77f8c3e93012d9de1548 100644 (file)
@@ -24,7 +24,7 @@ function display_allocatable_transactions()
        {
                unset($_SESSION['alloc']->allocs);
                unset($_SESSION['alloc']);
-       }       
+       }
     if (!isset($_POST['customer_id']))
        $_POST['customer_id'] = get_global_customer();
 
@@ -36,7 +36,7 @@ function display_allocatable_transactions()
 
        set_global_customer($_POST['customer_id']);
 
-       if (isset($_POST['customer_id']) && ($_POST['customer_id'] == reserved_words::get_all())) 
+       if (isset($_POST['customer_id']) && ($_POST['customer_id'] == reserved_words::get_all()))
        {
                unset($_POST['customer_id']);
        }
@@ -61,7 +61,7 @@ function display_allocatable_transactions()
        if (!isset($_POST['customer_id']))
                $th = array(_("Transaction Type"), _("#"), _("Reference"), _("Date"), _("Customer"),
                        _("Currency"), _("Total"), _("Left To Allocate"), "");
-       else    
+       else
                $th = array(_("Transaction Type"), _("#"), _("Reference"), _("Date"),
                        _("Total"), _("Left To Allocate"), "");
        table_header($th);
@@ -70,12 +70,12 @@ function display_allocatable_transactions()
 
        while ($myrow = db_fetch($trans_items))
        {
-       if ($myrow["settled"] == 1) 
+       if ($myrow["settled"] == 1)
        {
                start_row("class='settledbg'");
                $has_settled_items = true;
-       } 
-       else 
+       }
+       else
        {
                alt_table_row_color($k);
        }
@@ -90,10 +90,11 @@ function display_allocatable_transactions()
                label_cell($myrow["DebtorName"]);
                label_cell($myrow["curr_code"]);
                }
-               amount_cell(-$myrow["Total"]);
-       amount_cell(-$myrow["Total"] - $myrow["alloc"]);
-       if (-$myrow["Total"] - $myrow["alloc"] != 0.0)
-               label_cell("<a href='$path_to_root/sales/allocations/customer_allocate.php?trans_no=" . $myrow["trans_no"] . "&trans_type=" . $myrow["type"]  . "'>" . _("Allocate") . "</a>");
+               amount_cell($myrow["Total"]);
+       amount_cell($myrow["Total"] - $myrow["alloc"]);
+       if ($myrow["Total"] - $myrow["alloc"] != 0.0)
+               label_cell("<a href='$path_to_root/sales/allocations/customer_allocate.php?trans_no="
+                                       .$myrow["trans_no"] . "&trans_type=" . $myrow["type"]  . "'>" . _("Allocate") . "</a>");
        else
                label_cell("");
        end_row();
index c53cc062b6eeeae4d46c90c671605b8262368140..5b43a17352f7b6d443c08d2d296064fb001b7093 100644 (file)
 <?php
-
-/*The credit selection screen uses the Cart class used for the making up orders
-some of the variable names refer to order - please think credit when you read order */
-
+//---------------------------------------------------------------------------
+//
+//     Entry/Modify free hand Credit Note
+//
 $page_security = 3;
 $path_to_root="..";
 include_once($path_to_root . "/sales/includes/cart_class.inc");
-
 include_once($path_to_root . "/includes/session.inc");
-
 include_once($path_to_root . "/includes/data_checks.inc");
-
 include_once($path_to_root . "/sales/includes/sales_db.inc");
-
 include_once($path_to_root . "/sales/includes/sales_ui.inc");
-
 include_once($path_to_root . "/sales/includes/ui/sales_credit_ui.inc");
 include_once($path_to_root . "/sales/includes/ui/sales_order_ui.inc");
 
 $js = "";
-if ($use_popup_windows)
+if ($use_popup_windows) {
        $js .= get_js_open_window(900, 500);
-if ($use_date_picker)
+}
+if ($use_date_picker) {
        $js .= get_js_date_picker();
-page(_("Customer Credit Note"), false, false, "", $js);
+}
+
+if(isset($_GET['NewCredit'])) {
+       $_SESSION['page_title'] = _("Customer Credit Note");
+       handle_new_credit(0);
+} elseif (isset($_GET['ModifyCredit'])) {
+       $_SESSION['page_title'] = sprintf(_("Modifying Customer Credit Note #%d"), $_GET['ModifyCredit']);
+       handle_new_credit($_GET['ModifyCredit']);
+       $help_page_title = _("Modifying Customer Credit Note");
+}
+
+page($_SESSION['page_title'],false, false, "", $js);
 
-//-----------------------------------------------------------------------------------------------
+//-----------------------------------------------------------------------------
 
 check_db_has_stock_items(_("There are no items defined in the system."));
 
 check_db_has_customer_branches(_("There are no customers, or there are no customers with branches. Please define customers and customer branches."));
 
-//---------------------------------------------------------------------------------------------------------------
+//-----------------------------------------------------------------------------
 
-if (isset($_GET['AddedID']))
-{
+if (isset($_GET['AddedID'])) {
        $credit_no = $_GET['AddedID'];
        $trans_type = 11;
 
-       display_notification_centered(_("Credit Note has been processed"));
+       display_notification_centered(sprintf(_("Credit Note # %d has been processed"),$credit_no));
+
        display_note(get_customer_trans_view_str($trans_type, $credit_no, _("View this credit note")), 0, 1);
 
-       display_note(get_gl_view_str($trans_type, $credit_no, _("View the GL Journal Entries for this Credit Note")));
+       display_note(get_gl_view_str($trans_type, $credit_no, _("View the GL Journal Entries for this Credit Note")));
 
        hyperlink_params($_SERVER['PHP_SELF'], _("Enter Another Credit Note"), "NewCredit=yes");
 
        display_footer_exit();
 }
 
-//--------------------------------------------------------------------------------------------------
+//-----------------------------------------------------------------------------
 
 function copy_to_cn()
 {
-       $_SESSION['credit_items']->memo_ = $_POST['CreditText'];
-
-       $_SESSION['credit_items']->orig_order_date = $_POST['OrderDate'];
-       $_SESSION['credit_items']->freight_cost = $_POST['ChargeFreightCost'];
-
-       $_SESSION['credit_items']->Location = $_POST["Location"];
-
-       $_SESSION['credit_items']->default_sales_type = $_POST['sales_type_id'];
-       $_SESSION['credit_items']->tax_group_id = $_POST["tax_group_id"];
+       $_SESSION['Items']->Comments = $_POST['CreditText'];
+       $_SESSION['Items']->document_date = $_POST['OrderDate'];
+       $_SESSION['Items']->freight_cost = $_POST['ChargeFreightCost'];
+       $_SESSION['Items']->Location = $_POST["Location"];
+       $_SESSION['Items']->default_sales_type = $_POST['sales_type_id'];
+       $_SESSION['Items']->reference = $_POST['ref'];
+       $_SESSION['Items']->ship_via = $_POST['ShipperID'];
 }
 
-//--------------------------------------------------------------------------------------------------
+//-----------------------------------------------------------------------------
 
 function copy_from_cn()
 {
-       $_POST['CreditText'] = $_SESSION['credit_items']->memo_;
-
-       $_POST['OrderDate'] = $_SESSION['credit_items']->orig_order_date;
-       $_POST['ChargeFreightCost'] = $_SESSION['credit_items']->freight_cost;
-
-       $_POST["Location"] = $_SESSION['credit_items']->Location;
-
-       $_POST['sales_type_id'] = $_SESSION['credit_items']->default_sales_type;
-       $_POST["tax_group_id"] = $_SESSION['credit_items']->tax_group_id;
+       $_POST['CreditText'] = $_SESSION['Items']->Comments;
+       $_POST['OrderDate'] = $_SESSION['Items']->document_date;
+       $_POST['ChargeFreightCost'] = $_SESSION['Items']->freight_cost;
+       $_POST['Location'] = $_SESSION['Items']->Location;
+       $_POST['sales_type_id'] = $_SESSION['Items']->default_sales_type;
+       $_POST['ref'] = $_SESSION['Items']->reference;
+       $_POST['ShipperID'] = $_SESSION['Items']->ship_via;
 }
 
-//-----------------------------------------------------------------------------------------------
+//-----------------------------------------------------------------------------
 
-function handle_new_order()
+function handle_new_credit($trans_no)
 {
-       if (isset($_SESSION['credit_items']))
-       {
-               unset ($_SESSION['credit_items']->line_items);
-               unset ($_SESSION['credit_items']);
-       }
-
-    session_register("credit_items");
-
-    $_SESSION['credit_items'] = new cart;
-       $_POST['OrderDate'] = Today();
-       if (!is_date_in_fiscalyear($_POST['OrderDate']))
-               $_POST['OrderDate'] = end_fiscalyear();
-       $_SESSION['credit_items']->orig_order_date = $_POST['OrderDate'];
-
+       processing_start();
+       $_SESSION['Items'] = new Cart(11,$trans_no);
+       copy_from_cn();
 }
 
-//-----------------------------------------------------------------------------------------------
+//-----------------------------------------------------------------------------
 
-if (isset($_POST['ProcessCredit']))
+function can_process()
 {
 
        $input_error = 0;
 
-       if (!references::is_valid($_POST['ref']))
-       {
+       if ($_SESSION['Items']->count_items() == 0
+               && (!isset($_POST['ChargeFreightCost']) || $_POST['ChargeFreightCost'] <= 0))
+               return false;
+
+       if (!references::is_valid($_POST['ref'])) {
                display_error( _("You must enter a reference."));
                $input_error = 1;
-       }
-       elseif (!is_new_reference($_POST['ref'], 11))
-       {
+       } elseif (!is_new_reference($_POST['ref'], 11)) {
                display_error( _("The entered reference is already in use."));
                $input_error = 1;
-       }
-       elseif (!is_date($_POST['OrderDate']))
-       {
+       } elseif (!is_date($_POST['OrderDate'])) {
                display_error(_("The entered date for the credit note is invalid."));
                $input_error = 1;
-       }
-       elseif (!is_date_in_fiscalyear($_POST['OrderDate']))
-       {
+       } elseif (!is_date_in_fiscalyear($_POST['OrderDate'])) {
                display_error(_("The entered date is not in fiscal year."));
                $input_error = 1;
        }
-       if ($input_error == 1)
-               unset($_POST['ProcessCredit']);
+       return ($input_error == 0);
 }
 
-//------------------------------------------------------------------------------------
+//-----------------------------------------------------------------------------
 
-if (isset($_POST['ProcessCredit']))
-{
-       //alert("WriteOffGLCode = ".$_POST['WriteOffGLCode'].", CreditType = ".$_POST['CreditType']);
+if (isset($_POST['ProcessCredit']) && can_process()) {
        if ($_POST['CreditType'] == "WriteOff" && (!isset($_POST['WriteOffGLCode']) ||
-               $_POST['WriteOffGLCode'] == ''))
-       {
+               $_POST['WriteOffGLCode'] == '')) {
                display_note(_("For credit notes created to write off the stock, a general ledger account is required to be selected."), 1, 0);
-               display_note(_("Please select an account to write the cost of the stock off to, then click on Process again."), 1, 0);
+               display_note(_("Please select an account to write the cost of the stock off to, then click on Process again."), 1, 0);
                exit;
        }
-       if (!isset($_POST['WriteOffGLCode']))
-               $_POST['WriteOffGLCode'] = "";
-       if (!isset($_POST['ShipperID']))
-               $_POST['ShipperID'] = 0;
-       $credit_no = add_credit_note($_SESSION['credit_items'], $_POST['OrderDate'],
-               $_POST['CreditType'], $_POST['tax_group_id'],
-               $_POST['ChargeFreightCost'], $_POST['sales_type_id'], $_POST['ShipperID'],
-               $_POST['ref'], $_POST['CreditText'], $_POST['WriteOffGLCode']);
-
-       unset($_SESSION['credit_items']->line_items);
-       unset($_SESSION['credit_items']);
-
+       if (!isset($_POST['WriteOffGLCode'])) {
+               $_POST['WriteOffGLCode'] = 0;
+       }
+       $credit_no = $_SESSION['Items']->write($_POST['WriteOffGLCode']);
+       processing_end();
        meta_forward($_SERVER['PHP_SELF'], "AddedID=$credit_no");
 
 } /*end of process credit note */
 
-//---------------------------------------------------------------------------------------------------
-
-function get_details_from_customer()
-{
-       return get_customer_details_to_order($_SESSION['credit_items'], $_POST['customer_id'], $_POST['branch_id']);
-}
-
-//-----------------------------------------------------------------------------------------------
+  //-----------------------------------------------------------------------------
 
 function check_item_data()
 {
-       if ($_POST['qty'] <= 0)
-       {
+       if ($_POST['qty'] <= 0) {
                display_error(_("The quantity must be greater than zero."));
                return false;
        }
-       if (!is_numeric($_POST['price']) || $_POST['price'] < 0)
-       {
+       if (!is_numeric($_POST['price']) || $_POST['price'] < 0) {
                display_error(_("The entered price is negative or invalid."));
                return false;
        }
-       if (!is_numeric($_POST['Disc']) || $_POST['Disc'] > 100 || $_POST['Disc'] < 0)
-       {
+       if (!is_numeric($_POST['Disc']) || $_POST['Disc'] > 100 || $_POST['Disc'] < 0) {
                display_error(_("The entered discount percent is negative, greater than 100 or invalid."));
                return false;
        }
-       return true;
+       return true;
 }
 
-//-----------------------------------------------------------------------------------------------
+//-----------------------------------------------------------------------------
 
 function handle_update_item()
 {
-    if($_POST['UpdateItem'] != "" && check_item_data())
-    {
-       $_SESSION['credit_items']->update_cart_item($_POST['line_no'], $_POST['qty'],
-               $_POST['price'], ($_POST['Disc'] / 100));
-    }
+       if ($_POST['UpdateItem'] != "" && check_item_data()) {
+               $_SESSION['Items']->update_cart_item($_POST['line_no'], $_POST['qty'],
+                       $_POST['price'], ($_POST['Disc'] / 100));
+       }
 }
 
-//-----------------------------------------------------------------------------------------------
+//-----------------------------------------------------------------------------
 
 function handle_delete_item()
 {
-       $_SESSION['credit_items']->remove_from_cart($_GET['Delete']);
+       $_SESSION['Items']->remove_from_cart($_GET['Delete']);
 }
 
-//-----------------------------------------------------------------------------------------------
+//-----------------------------------------------------------------------------
 
 function handle_new_item()
 {
+
        if (!check_item_data())
                return;
 
-       add_to_order($_SESSION['credit_items'], $_POST['line_no'], $_POST['stock_id'], $_POST['qty'],
+       add_to_order($_SESSION['Items'], $_POST['stock_id'], $_POST['qty'],
                $_POST['price'], $_POST['Disc'] / 100);
 }
-
-//-----------------------------------------------------------------------------------------------
+//-----------------------------------------------------------------------------
 if (isset($_GET['Delete']) || isset($_GET['Edit']))
        copy_from_cn();
 
@@ -231,51 +198,38 @@ if (isset($_POST['AddItem']))
 if (isset($_POST['UpdateItem']))
        handle_update_item();
 
-//-----------------------------------------------------------------------------------------------
+//-----------------------------------------------------------------------------
 
-if (isset($_GET['NewCredit']) || !isset($_SESSION['credit_items']))
-{
-       handle_new_order();
-}
-else
-{
+if (!processing_active()) {
+       handle_new_credit();
+} else {
        if (!isset($_POST['customer_id']))
-               $_POST['customer_id'] = $_SESSION['credit_items']->customer_id;
+               $_POST['customer_id'] = $_SESSION['Items']->customer_id;
        if (!isset($_POST['branch_id']))
-               $_POST['branch_id'] = $_SESSION['credit_items']->Branch;
+               $_POST['branch_id'] = $_SESSION['Items']->Branch;
 }
 
-//-----------------------------------------------------------------------------------------------
+//-----------------------------------------------------------------------------
 
 start_form(false, true);
 
-$customer_error = display_credit_header($_SESSION['credit_items']);
+$customer_error = display_credit_header($_SESSION['Items']);
 
-if ($customer_error == "")
-{
+if ($customer_error == "") {
        start_table("$table_style width=80%", 10);
        echo "<tr><td>";
-    display_credit_items(_("Credit Note Items"), $_SESSION['credit_items']);
-    credit_options_controls();
-    echo "</td></tr>";
-    end_table();
-}
-else
-{
+       display_credit_items(_("Credit Note Items"), $_SESSION['Items']);
+       credit_options_controls();
+       echo "</td></tr>";
+       end_table();
+} else {
        display_error($customer_error);
 }
 
-if (!isset($_POST['ProcessCredit']))
-{
-    echo "<br><center><table><tr>";
-    submit_cells('Update', _("Update"));
-       if ($_SESSION['credit_items']->count_items() >= 1
-                       /*OR $_POST['ChargeTax'] > 0*/ || (isset($_POST['ChargeFreightCost']) && $_POST['ChargeFreightCost'] > 0))
-       {
-           submit_cells('ProcessCredit', _("Process Credit Note"));
-       }
-       echo "</tr></table>";
-}
+echo "<br><center><table><tr>";
+submit_cells('Update', _("Update"));
+submit_cells('ProcessCredit', _("Process Credit Note"));
+echo "</tr></table>";
 
 end_form();
 end_page();
index c97930ee7cfd032462329e03caa0f5407704f8f5..31306707c7597736e1fa05bb833bcdc009b81468 100644 (file)
@@ -1,76 +1,96 @@
 <?php
+//---------------------------------------------------------------------------
+//
+//     Entry/Modify Credit Note for selected Sales Invoice
+//
 
-$page_security =3;
-$path_to_root="..";
+$page_security = 3;
+$path_to_root = "..";
 
 include_once($path_to_root . "/sales/includes/cart_class.inc");
 include_once($path_to_root . "/includes/session.inc");
-
 include_once($path_to_root . "/includes/data_checks.inc");
-
 include_once($path_to_root . "/includes/manufacturing.inc");
 include_once($path_to_root . "/sales/includes/sales_db.inc");
 include_once($path_to_root . "/sales/includes/sales_ui.inc");
+include_once($path_to_root . "/reporting/includes/reporting.inc");
+
 $js = "";
-if ($use_popup_windows)
+if ($use_popup_windows) {
        $js .= get_js_open_window(900, 500);
-if ($use_date_picker)
+}
+
+if ($use_date_picker) {
        $js .= get_js_date_picker();
-page(_("Credit all or part of an Invoice"), false, false, "", $js);
+}
 
-//---------------------------------------------------------------------------------------------------------------
+if (isset($_GET['ModifyCredit'])) {
+       $_SESSION['page_title'] = sprintf(_("Modifying Credit Invoice # %d."), $_GET['ModifyCredit']);
+       $help_page_title =_("Modifying Credit Invoice");
+       processing_start();
+} elseif (isset($_GET['InvoiceNumber'])) {
+       $_SESSION['page_title'] = _("Credit all or part of an Invoice");
+       processing_start();
+}
+page($_SESSION['page_title'], false, false, "", $js);
 
-if (isset($_GET['AddedID']))
-{
+//-----------------------------------------------------------------------------
+
+if (isset($_GET['AddedID'])) {
        $credit_no = $_GET['AddedID'];
        $trans_type = 11;
+       print_hidden_script(11);
 
-       echo "<center>";
        display_notification_centered(_("Credit Note has been processed"));
-       display_note(get_customer_trans_view_str($trans_type, $credit_no, _("View this credit note")), 0, 0);
 
-       display_note(get_gl_view_str($trans_type, $credit_no, _("View the GL Journal Entries for this Credit Note")));
+       display_note(get_customer_trans_view_str($trans_type, $credit_no, _("View This Credit Note")), 0, 0);
+
+       display_note(print_document_link($credit_no, _("Print This Credit Note"), true, 11),1);
+
+       display_note(get_gl_view_str($trans_type, $credit_no, _("View the GL Journal Entries for this Credit Note")),1);
 
        display_footer_exit();
-}
 
-//--------------------------------------------------------------------------------------
+} elseif (isset($_GET['UpdatedID'])) {
+       $credit_no = $_GET['UpdatedID'];
+       $trans_type = 11;
+       print_hidden_script(11);
 
-if (!isset($_GET['InvoiceNumber']) && !$_SESSION['InvoiceToCredit'])
-{
-       /* This page can only be called with an invoice number for crediting*/
-       die (_("This page can only be opened if an invoice has been selected for crediting."));
+       display_notification_centered(_("Credit Note has been updated"));
+
+       display_note(get_customer_trans_view_str($trans_type, $credit_no, _("View This Credit Note")), 0, 0);
+
+       display_note(print_document_link($credit_no, _("Print This Credit Note"), true, 11),1);
+
+       display_note(get_gl_view_str($trans_type, $credit_no, _("View the GL Journal Entries for this Credit Note")),1);
+
+       display_footer_exit();
 }
 
-//--------------------------------------------------------------------------------------
+//-----------------------------------------------------------------------------
 
 function can_process()
 {
-       if (!is_date($_POST['CreditDate']))
-       {
+       if (!is_date($_POST['CreditDate'])) {
                display_error(_("The entered date is invalid."));;
                return false;
-       }
-       elseif (!is_date_in_fiscalyear($_POST['CreditDate']))
-       {
+       } elseif (!is_date_in_fiscalyear($_POST['CreditDate'])) {
                display_error(_("The entered date is not in fiscal year."));
                return false;
        }
 
-       if (!references::is_valid($_POST['ref']))
-       {
-               display_error(_("You must enter a reference."));;
-               return false;
-       }
-
-       if (!is_new_reference($_POST['ref'], 11))
-       {
-               display_error(_("The entered reference is already in use."));;
-               return false;
-       }
+    if ($_SESSION['Items']->trans_no==0) {
+               if (!references::is_valid($_POST['ref'])) {
+                       display_error(_("You must enter a reference."));;
+                       return false;
+               }
 
-       if (!is_numeric($_POST['ChargeFreightCost']) || $_POST['ChargeFreightCost'] < 0)
-       {
+               if (!is_new_reference($_POST['ref'], 11)) {
+                       display_error(_("The entered reference is already in use."));;
+                       return false;
+               }
+    }
+       if (!is_numeric($_POST['ChargeFreightCost']) || $_POST['ChargeFreightCost'] < 0) {
                display_error(_("The entered shipping cost is invalid or less than zero."));;
                return false;
        }
@@ -78,159 +98,109 @@ function can_process()
        return true;
 }
 
-//--------------------------------------------------------------------------------------
-
-function clear_globals()
-{
-       if (isset($_SESSION['Items']))
-       {
-               unset($_SESSION['Items']->line_items);
-               unset($_SESSION['Items']);
-       }
-       unset($_SESSION['InvoiceToCredit']);
-}
-
-//--------------------------------------------------------------------------------------
-
-function process_credit()
-{
-       global $path_to_root;
-       if (can_process())
-       {
-               $credit_no = credit_invoice($_SESSION['Items'], $_SESSION['InvoiceToCredit'],
-                       $_SESSION['Order'],     $_POST['CreditDate'], $_POST['CreditType'],
-                       $_POST['tax_group_id'], $_POST['ChargeFreightCost'], $_POST['ref'],
-                       $_POST['CreditText'], $_POST['WriteOffGLCode']);
-
-               clear_globals();
-
-               meta_forward($_SERVER['PHP_SELF'], "AddedID=$credit_no");
-       }
-}
-
-//--------------------------------------------------------------------------------------
-
-if (isset($_GET['InvoiceNumber']) && $_GET['InvoiceNumber'] > 0)
-{
-
-       clear_globals();
-
-       $_SESSION['InvoiceToCredit'] = $_GET['InvoiceNumber'];
-       $_SESSION['Items'] = new cart;
-
-       /*read in all the guff from the selected invoice into the Items cart    */
-
-       // we need a distinct here so that it only returns 1 line - because there can be multiple moves
-       // per item (for assemblies, etc)
-       $sql = "SELECT DISTINCT ".TB_PREF."debtor_trans.*,
-               ".TB_PREF."cust_branch.default_location, ".TB_PREF."cust_branch.default_ship_via,
-               ".TB_PREF."debtors_master.name, ".TB_PREF."debtors_master.curr_code,
-       ".TB_PREF."tax_groups.name AS tax_group_name, ".TB_PREF."tax_groups.id AS tax_group_id,
-       ".TB_PREF."sales_orders.from_stk_loc
-       FROM ".TB_PREF."debtor_trans, ".TB_PREF."debtors_master, ".TB_PREF."cust_branch, ".TB_PREF."tax_groups, ".TB_PREF."sales_orders
-       WHERE ".TB_PREF."debtor_trans.debtor_no = ".TB_PREF."debtors_master.debtor_no
-       AND ".TB_PREF."debtor_trans.branch_code = ".TB_PREF."cust_branch.branch_code
-       AND ".TB_PREF."debtor_trans.debtor_no = ".TB_PREF."cust_branch.debtor_no
-       AND ".TB_PREF."cust_branch.tax_group_id = ".TB_PREF."tax_groups.id
-       AND ".TB_PREF."debtor_trans.trans_no = " . $_GET['InvoiceNumber'] . "
-               AND ".TB_PREF."debtor_trans.type=10
-       AND ".TB_PREF."sales_orders.order_no=".TB_PREF."debtor_trans.order_";
-
-       $result = db_query($sql,"The invoice details cannot be retrieved");
-
-       if (db_num_rows($result) == 1)
-       {
+//-----------------------------------------------------------------------------
 
-               $myrow = db_fetch($result);
+if (isset($_GET['InvoiceNumber']) && $_GET['InvoiceNumber'] > 0) {
 
-               $_SESSION['Items']->customer_id = $myrow["debtor_no"];
-               $_SESSION['Items']->customer_name = $myrow["name"];
-               $_SESSION['Items']->cust_ref = $myrow["reference"];
-               $_SESSION['Items']->Branch = $myrow["branch_code"];
-               $_SESSION['Items']->customer_currency = $myrow["curr_code"];
+    $ci = new Cart(10, $_GET['InvoiceNumber'], true);
 
-               $_SESSION['Items']->Comments = "";
-               $_SESSION['Items']->default_sales_type =$myrow["tpe"];
-               $_SESSION['Items']->Location = $myrow["from_stk_loc"];
-
-               $_SESSION['Items']->tax_group_name = $myrow["tax_group_name"];
-               $_SESSION['Items']->tax_group_id = $myrow["tax_group_id"];
-
-               $_SESSION['Items']->delivery_date = sql2date($myrow["tran_date"]);
-               $_SESSION['Items']->freight_cost = $myrow["ov_freight"];
-
-               $_SESSION['Items']->ship_via = $myrow["default_ship_via"];
-
-               $_SESSION['Order'] = $myrow["order_"];
-
-               db_free_result($result);
-
-               /*now populate the line items array with the detail records for the invoice*/
+    if ($ci==null) {
+               display_error(_("This invoice can not be credited using the automatic facility."));
+               display_error("Please report that a duplicate debtor_trans header record was found for invoice " . key($ci->src_docs));
+               echo "<br><br>";
+               processing_end();
+               exit;
+    }
+    //valid invoice record returned from the entered invoice number
 
-               $result = get_customer_trans_details(10, $_GET['InvoiceNumber']);
+    $ci->trans_type = 11;
+    $ci->src_docs = $ci->trans_no;
+    $ci->src_date = $ci->document_date;
+    $ci->trans_no = 0;
+    $ci->document_date = Today();
+    $ci->reference = references::get_next(11);
 
-               if (db_num_rows($result) > 0)
-               {
+    for ($line_no=0; $line_no<count($ci->line_items); $line_no++) {
+       $ci->line_items[$line_no]->qty_dispatched = '0';
+    }
 
-                       while ($myrow = db_fetch($result))
-                       {
+    $_SESSION['Items'] = $ci;
+       copy_from_cart();
 
-                               $_SESSION['Items']->add_to_cart($myrow["stock_id"],-$myrow["quantity"],
-                                       $myrow["FullUnitPrice"],$myrow["discount_percent"],$myrow["qty_done"],
-                                       $myrow["standard_cost"],$myrow["description"],$myrow["id"]);
+} elseif ( isset($_GET['ModifyCredit']) && $_GET['ModifyCredit']>0) {
 
+       $_SESSION['Items'] = new Cart(11,$_GET['ModifyCredit']);
+       copy_from_cart();
 
+} elseif (!processing_active()) {
+       /* This page can only be called with an invoice number for crediting*/
+       die (_("This page can only be opened if an invoice has been selected for crediting."));
+} else {
+       foreach ($_SESSION['Items']->line_items as $line_no=>$itm) {
+               if (isset($_POST['Line'.$line_no])) {
+                       $line_qty = $_POST['Line'.$line_no];
+                       if (is_numeric($line_qty) && $_POST['Line'.$line_no] <= ($itm->quantity - $itm->qty_done)) {
+                               $_SESSION['Items']->line_items[$line_no]->qty_dispatched = $line_qty;
                        }
+               }
 
-               } /*else { // there are no item records created for that invoice
-                       // it's ok there might be shipping or only taxes !!
-                       echo "<CENTER><A HREF='$path_to_root/index.php?" . SID . "'>" . _("Back to the main menu") . "</A>";
-                       echo "<P>" . _("There are no line items that were retrieved for this invoice. A credit note cannot be created from this invoice."). "<BR><BR>";
-                       end_page();
-                       exit;
-
-               }*/ //end of checks on returned data set
-               db_free_result($result);
+               if (isset($_POST['Line'.$line_no.'Desc'])) {
+                       $line_desc = $_POST['Line'.$line_no.'Desc'];
+                       if (strlen($line_desc) > 0) {
+                               $_SESSION['Items']->line_items[$line_no]->item_description = $line_desc;
+                       }
+               }
        }
-       else
-       {
-               display_error(_("This invoice can not be credited using the automatic facility."));
-               display_error("Please report that a duplicate debtor_trans header record was found for invoice " . $SESSION['InvoiceToCredit']);
-               echo "<br><br>";
-               exit;
-       } //valid invoice record returned from the entered invoice number
+}
+//-----------------------------------------------------------------------------
 
+function copy_to_cart()
+{
+  $cart = &$_SESSION['Items'];
+  $cart->ship_via = $_POST['ShipperID'];
+  $cart->freight_cost = $_POST['ChargeFreightCost'];
+  $cart->document_date =  $_POST['CreditDate'];
+  $cart->Location = $_POST['Location'];
+  $cart->Comments = $_POST['CreditText'];
 }
-else
+//-----------------------------------------------------------------------------
+
+function copy_from_cart()
 {
+  $cart = &$_SESSION['Items'];
+  $_POST['ShipperID'] = $cart->ship_via;
+  $_POST['ChargeFreightCost'] = $cart->freight_cost;
+  $_POST['CreditDate']= $cart->document_date;
+  $_POST['Location']= $cart->Location;
+  $_POST['CreditText']= $cart->Comments;
+}
+//-----------------------------------------------------------------------------
 
-/* if processing, the page has been called and ${$StkItm->stock_id} would have been set from the post */
-       foreach ($_SESSION['Items']->line_items as $itm)
-       {
-               $_SESSION['Items']->line_items[$itm->line_no]->qty_dispatched = $_POST[$itm->stock_id];
+if (isset($_POST['ProcessCredit']) && can_process()) {
 
-               if (isset($_POST[$itm->stock_id . "Desc"]) && strlen($_POST[$itm->stock_id . "Desc"]) > 0)
-               {
-                       $_SESSION['Items']->line_items[$itm->line_no]->item_description = $_POST[$itm->stock_id . "Desc"];
-               }
-       }
-}
+    $newcredit = ($_SESSION['Items']->trans_no == 0);
 
-//--------------------------------------------------------------------------------------
+    if (!isset($_POST['WriteOffGLCode']))
+               $_POST['WriteOffGLCode'] = 0;
 
-if (isset($_POST['ProcessCredit']))
-{
-       process_credit();
+       copy_to_cart();
+    $credit_no = $_SESSION['Items']->write($_POST['WriteOffGLCode']);
+
+       processing_end();
+       if ($newcredit) {
+               meta_forward($_SERVER['PHP_SELF'], "AddedID=$credit_no");
+       } else {
+               meta_forward($_SERVER['PHP_SELF'], "UpdatedID=$credit_no");
+       }
 }
 
-//--------------------------------------------------------------------------------------
+//-----------------------------------------------------------------------------
 
-if (isset($_POST['Location']))
-{
+if (isset($_POST['Location'])) {
        $_SESSION['Items']->Location = $_POST['Location'];
 }
 
-//--------------------------------------------------------------------------------------
+//-----------------------------------------------------------------------------
 
 function display_credit_items()
 {
@@ -249,17 +219,27 @@ function display_credit_items()
     end_row();
     start_row();
 
-       if (!isset($_POST['ref']))
-               $_POST['ref'] = references::get_next(11);
+//     if (!isset($_POST['ref']))
+//             $_POST['ref'] = references::get_next(11);
 
-    ref_cells(_("Reference"), 'ref', null, "class='tableheader2'");
+    if ($_SESSION['Items']->trans_no==0) {
+               ref_cells(_("Reference"), 'ref', $_SESSION['Items']->reference, "class='tableheader2'");
+       } else {
+               label_cells(_("Reference"), $_SESSION['Items']->reference, "class='tableheader2'");
+       }
+//    label_cells(_("Crediting Invoice"), get_customer_trans_view_str(10, $_SESSION['InvoiceToCredit']), "class='tableheader2'");
+    label_cells(_("Crediting Invoice"), get_customer_trans_view_str(10, array_keys($_SESSION['Items']->src_docs)), "class='tableheader2'");
 
-    label_cells(_("Crediting Invoice"), get_customer_trans_view_str(10, $_SESSION['InvoiceToCredit']), "class='tableheader2'");
+       if (!isset($_POST['ShipperID'])) {
+               $_POST['ShipperID'] = $_SESSION['Items']->ship_via;
+       }
+       label_cell(_("Shipping Company"), "class='tableheader2'");
+       shippers_list_cells(null, 'ShipperID', $_POST['ShipperID']);
+//     if (!isset($_POST['sales_type_id']))
+//       $_POST['sales_type_id'] = $_SESSION['Items']->default_sales_type;
+//     label_cell(_("Sales Type"), "class='tableheader2'");
+//     sales_types_list_cells(null, 'sales_type_id', $_POST['sales_type_id']);
 
-    if (!isset($_POST['tax_group_id']))
-       $_POST['tax_group_id'] = $_SESSION['Items']->tax_group_id;
-    label_cell(_("Tax Group"), "class='tableheader2'");
-    tax_groups_list_cells(null, 'tax_group_id', $_POST['tax_group_id'], false, null, true);
        end_row();
        end_table();
 
@@ -267,7 +247,7 @@ function display_credit_items()
 
     start_table("$table_style width=100%");
 
-    label_row(_("Invoice Date"), $_SESSION['Items']->delivery_date, "class='tableheader2'");
+    label_row(_("Invoice Date"), $_SESSION['Items']->src_date, "class='tableheader2'");
 
     date_row(_("Credit Note Date"), 'CreditDate', null, 0, 0, 0, "class='tableheader2'");
 
@@ -284,19 +264,23 @@ function display_credit_items()
 
     $k = 0; //row colour counter
 
-    foreach ($_SESSION['Items']->line_items as $ln_itm)
-    {
-
-       alt_table_row_color($k);
+    foreach ($_SESSION['Items']->line_items as $line_no=>$ln_itm) {
+               if ($ln_itm->quantity==$ln_itm->qty_done) {
+                       continue; // this line was fully credited
+               }
+               alt_table_row_color($k);
 
-       $line_total =($ln_itm->qty_dispatched * $ln_itm->price * (1 - $ln_itm->discount_percent));
 
+               //      view_stock_status_cell($ln_itm->stock_id); alternative view
        label_cell($ln_itm->stock_id);
-               text_cells(null, $ln_itm->stock_id . "Desc", $ln_itm->item_description, 30, 50);
+
+               text_cells(null, 'Line'.$line_no.'Desc', $ln_itm->item_description, 30, 50);
+
        qty_cell($ln_itm->quantity);
        label_cell($ln_itm->units);
+           text_cells(null, 'Line'.$line_no, $ln_itm->qty_dispatched, 13, 15);
 
-       text_cells(null, $ln_itm->stock_id, $ln_itm->qty_dispatched, 13, 15);
+       $line_total =($ln_itm->qty_dispatched * $ln_itm->price * (1 - $ln_itm->discount_percent));
 
        amount_cell($ln_itm->price);
        amount_cell($ln_itm->discount_percent*100);
@@ -304,10 +288,14 @@ function display_credit_items()
        end_row();
     }
 
-    if (!isset($_POST['ChargeFreightCost']) || ($_POST['ChargeFreightCost'] == ""))
-    {
+    if (!isset($_POST['ChargeFreightCost']) || ($_POST['ChargeFreightCost'] == "")) {
        $_POST['ChargeFreightCost'] = $_SESSION['Items']->freight_cost;
     }
+
+    if (!is_numeric($_POST['ChargeFreightCost']))
+    {
+       $_POST['ChargeFreightCost'] = 0;
+    }
        start_row();
        label_cell(_("Credit Shipping Cost"), "colspan=7 align=right");
     text_cells(null, "ChargeFreightCost", $_POST['ChargeFreightCost'], 6, 6);
@@ -318,9 +306,9 @@ function display_credit_items()
     $display_sub_total = number_format2($inv_items_total + $_POST['ChargeFreightCost'],user_price_dec());
     label_row(_("Sub-total"), $display_sub_total, "colspan=7 align=right", "align=right");
 
-    $taxes = $_SESSION['Items']->get_taxes($_POST['tax_group_id'], $_POST['ChargeFreightCost']);
+    $taxes = $_SESSION['Items']->get_taxes($_POST['ChargeFreightCost']);
 
-    $tax_total = display_edit_tax_items($taxes, 7);
+    $tax_total = display_edit_tax_items($taxes, 7, $_SESSION['Items']->tax_included);
 
     $display_total = number_format2(($inv_items_total + $_POST['ChargeFreightCost'] + $tax_total), user_price_dec());
 
@@ -329,7 +317,7 @@ function display_credit_items()
     end_table();
 }
 
-//--------------------------------------------------------------------------------------
+//-----------------------------------------------------------------------------
 
 function display_credit_options()
 {
@@ -340,41 +328,32 @@ function display_credit_options()
 
     echo "<tr><td>" . _("Credit Note Type") . "</td>";
     echo "<td><select name='CreditType' onchange='this.form.submit();'>";
-    if (!isset($_POST['CreditType']) || $_POST['CreditType'] == "Return")
-    {
+    if (!isset($_POST['CreditType']) || $_POST['CreditType'] == "Return") {
        echo "<option value='WriteOff'>" . _("Items Written Off") . "</option>";
        echo "<option selected value='Return'>" . _("Items Returned to Inventory Location") . "</option>";
-    }
-    else
-    {
+    } else {
        echo "<option selected value='WriteOff'>" . _("Items Written Off") . "</option>";
        echo "<option value='Return'>" . _("Items Returned to Inventory Location") . "</option>";
     }
     echo "</select>";
     echo"</td></tr>";
 
-    if (!isset($_POST['CreditType']) || $_POST['CreditType'] == "Return")
-    {
+    if (!isset($_POST['CreditType']) || $_POST['CreditType'] == "Return") {
 
        /*if the credit note is a return of goods then need to know which location to receive them into */
-       if (!isset($_POST['Location']))
-       {
+       if (!isset($_POST['Location'])) {
                $_POST['Location'] = $_SESSION['Items']->Location;
        }
 
        locations_list_row(_("Items Returned to Inventory Location"), 'Location', $_POST['Location']);
-
-    }
-    else
-    {  /* the goods are to be written off to somewhere */
-
+    } else {   /* the goods are to be written off to somewhere */
        gl_all_accounts_list_row(_("Write Off the Cost of the Items to"), 'WriteOffGLCode', $_POST['WriteOffGLCode']);
     }
     textarea_row(_("Memo"), "CreditText", null, 45, 3);
     end_table();
 }
 
-//--------------------------------------------------------------------------------------
+//-----------------------------------------------------------------------------
 
 display_credit_items();
 display_credit_options();
@@ -387,7 +366,6 @@ echo "</center>";
 
 end_form();
 
-//--------------------------------------------------------------------------------------
 
 end_page();
 
index c7ba4b6183df4eb194e91aaed9d81ede66f365f5..a1672775c74685780b4bc4ed9ed558d1e6135b2a 100644 (file)
 <?php
-
+//-----------------------------------------------------------------------------
+//
+//     Entry/Modify Delivery Note against Sales Order
+//
 $page_security = 2;
 $path_to_root="..";
+
 include_once($path_to_root . "/sales/includes/cart_class.inc");
 include_once($path_to_root . "/includes/session.inc");
-
 include_once($path_to_root . "/includes/data_checks.inc");
-
 include_once($path_to_root . "/includes/manufacturing.inc");
 include_once($path_to_root . "/sales/includes/sales_db.inc");
 include_once($path_to_root . "/sales/includes/sales_ui.inc");
-
+include_once($path_to_root . "/reporting/includes/reporting.inc");
 include_once($path_to_root . "/taxes/tax_calc.inc");
 
 $js = "";
-if ($use_popup_windows)
+if ($use_popup_windows) {
        $js .= get_js_open_window(900, 500);
-if ($use_date_picker)
+}
+if ($use_date_picker) {
        $js .= get_js_date_picker();
-
-if(isset($_GET['ModifyDelivery'])) {
-       $_SESSION['page_title'] = _("Modifying Delivery Note") . " #".$_GET['ModifyDelivery']; 
 }
-else { 
+
+if (isset($_GET['ModifyDelivery'])) {
+       $_SESSION['page_title'] = sprintf(_("Modifying Delivery Note # %d."), $_GET['ModifyDelivery']);
+       $help_page_title = _("Modifying Delivery Note");
+       processing_start();
+} elseif (isset($_GET['OrderNumber'])) {
        $_SESSION['page_title'] = _("Deliver Items for a Sales Order");
+       processing_start();
 }
 
-page($_SESSION['page_title'], false, false, "", $js); 
+page($_SESSION['page_title'], false, false, "", $js);
 
-if (isset($_GET['AddedID'])) 
-{
+if (isset($_GET['AddedID'])) {
        $dispatch_no = $_GET['AddedID'];
-       $trans_type = 13;
+       print_hidden_script(13);
 
        display_notification(_("Dispatch processed:") . ' '.$_GET['AddedID'], true);
 
-       display_note(get_customer_trans_view_str($trans_type, $dispatch_no, _("View this dispatch")), 0, 1);
+       display_note(get_customer_trans_view_str(13, $dispatch_no, _("View this dispatch")), 0, 1);
 
-       display_note(get_gl_view_str($trans_type, $dispatch_no, _("View the GL Journal Entries for this Dispatch")));
+       display_note(print_document_link($dispatch_no, _("Print this delivery"), true, 13));
+
+       display_note(get_gl_view_str(13, $dispatch_no, _("View the GL Journal Entries for this Dispatch")),1);
 
        hyperlink_params("$path_to_root/sales/customer_invoice.php", _("Invoice This Delivery"), "DeliveryNumber=$dispatch_no");
 
-       if ($_SESSION['Items']->trans_type=='invoice')
-               hyperlink_params("$path_to_root/sales/sales_order_entry.php", _("Make Another Dispatch"), "NewDispatch=Yes");
-       else
-               hyperlink_params("$path_to_root/sales/inquiry/sales_orders_view.php", _("Select Another Order For Dispatch"), "OutstandingOnly=1");
+       hyperlink_params("$path_to_root/sales/inquiry/sales_orders_view.php", _("Select Another Order For Dispatch"), "OutstandingOnly=1");
 
        display_footer_exit();
-}
 
-//---------------------------------------------------------------------------------------------------------------
+} elseif (isset($_GET['UpdatedID'])) {
 
-if (!isset($_GET['OrderNumber']) && !isset($_SESSION['ProcessingOrder']) && 
- !isset($_GET['ModifyDelivery']) && !isset($_GET['process_delivery'])) 
-{
-       /* This page can only be called with an order number for invoicing*/
-       display_error(_("This page can only be opened if an order or delivery note has been selected. Please select it first."));
+       $delivery_no = $_GET['UpdatedID'];
+       print_hidden_script(13);
 
-       hyperlink_params("$path_to_root/sales/inquiry/sales_orders_view.php", _("Select a Sales Order to Delivery"), "OutstandingOnly=1");
+       display_notification_centered(sprintf(_('Delivery Note # %d has been updated.'),$delivery_no));
 
-       end_page();
-       exit;
+       display_note(get_trans_view_str(13, $delivery_no, _("View this delivery")));
+       echo '<br>';
+       display_note(print_document_link($delivery_no, _("Print this delivery"), true, 13));
 
-} 
-elseif (isset($_GET['OrderNumber']) && $_GET['OrderNumber'] > 0) 
-{
+       hyperlink_params($path_to_root . "/sales/customer_invoice.php", _("Confirm Delivery and Invoice"), "DeliveryNumber=$delivery_no");
 
-       if (isset($_SESSION['Items']))
-       {
-               unset($_SESSION['Items']->line_items);
-               unset ($_SESSION['Items']);
-       }
-
-       $_SESSION['ProcessingOrder'] = $_GET['OrderNumber'];
-       $_SESSION['Items'] = new cart;
-       
-       /*read in all the selected order into the Items cart  */
+       hyperlink_params($path_to_root . "/sales/inquiry/sales_deliveries_view.php", _("Select A Different Delivery"), "OutstandingOnly=1");
 
-       if (read_sales_order($_SESSION['ProcessingOrder'], $_SESSION['Items'])) 
-       {
-               if ($_SESSION['Items']->count_items() == 0) 
-               {
-               hyperlink_params($path_to_root . "/sales/inquiry/sales_orders_view.php", _("Select a different sales order to delivery"), "OutstandingOnly=1");
-               die ("<br><b>" . _("This order has no items. There is nothing to delivery.") . "</b>");
-               }
-       } 
-       else 
-       {
-               hyperlink_no_params("/sales_orders_view.php", _("Select a sales order to dispatch"));
-               die ("<br><b>" . _("This order items could not be retrieved. Please select another order.") . "</b>");
-       }
-
-} 
-elseif (isset($_GET['ModifyDelivery']) && $_GET['ModifyDelivery'] > 0) {
-       if (isset($_SESSION['Items']))
-       {
-               unset($_SESSION['Items']->line_items);
-               unset ($_SESSION['Items']);
-       }
-       $_SESSION['Items'] = new cart;
-       
-       if(read_sales_delivery($_GET['ModifyDelivery'],$_SESSION['Items'] ))
-       {
-           if ($_SESSION['Items']->count_items() == 0) 
-           {
-               hyperlink_params($path_to_root . "/sales/inquiry/sales_orders_view.php", _("Select a different delivery"), "OutstandingOnly=1");
-               die ("<br><b>" . _("This delivery has all items invoiced. There is nothing to modify.") . "</b>");
-           }
-       } 
-       else 
-       {
-               hyperlink_no_params("/sales_orders_view.php", _("Select a sales order to dispatch"));
-               die ("<br><b>" . _("This sales delivery item could not be retrieved. Please select another delivery.") . "</b>");
-       }
-
-       $_SESSION['ProcessingOrder'] = $_SESSION['Items']->order_no;
-} else 
-{
- // Update cart delivery quantities/descriptions
-       foreach ($_SESSION['Items']->line_items as $line=>$itm) 
-       {
-         if(isset($_POST['Line'.$line])) {
-               $line_qty = $_POST['Line'.$line];
-               if (is_numeric($line_qty) && $_POST['Line'.$line] <= ($itm->quantity - $itm->qty_done))
-               {
-                       $_SESSION['Items']->line_items[$line]->qty_dispatched = $line_qty;
-               }
-         }
-       
-         if(isset($_POST['Line'.$line.'Desc'])) {
-               $line_desc = $_POST['Line'.$line.'Desc'];
-               if (strlen($line_desc) > 0) 
-               {
-                       $_SESSION['Items']->line_items[$line]->item_description = $line_desc;
-               }
-         }
-       }
+       display_footer_exit();
 }
+//-----------------------------------------------------------------------------
 
-//---------------------------------------------------------------------------------------------------------------
+if (isset($_GET['OrderNumber']) && $_GET['OrderNumber'] > 0) {
 
-function order_changed_error()
-{
-       global $path_to_root;
-       display_note(_("This order has been changed or invoiced since this delivery was started to be confirmed. Processing halted."), 1, 0);
-       display_note(_("To enter and confirm this dispatch the order must be re-selected and re-read again to update the changes made by the other user."), 1, 0);
+       $ord = new Cart(30,$_GET['OrderNumber'], true);
 
-       hyperlink_no_params("$path_to_root/sales/inquiry/sales_orders_view.php", _("Select a sales order for confirming deliveries"));
+       /*read in all the selected order into the Items cart  */
 
-       unset($_SESSION['ProcessingOrder']);
-       exit;
-}
+       if ($ord->count_items() == 0) {
+               hyperlink_params($path_to_root . "/sales/inquiry/sales_orders_view.php",
+                       _("Select a different sales order to delivery"), "OutstandingOnly=1");
+               die ("<br><b>" . _("This order has no items. There is nothing to delivery.") . "</b>");
+       }
 
-//---------------------------------------------------------------------------------------------------------------
+       $ord->trans_type = 13;
+       $ord->src_docs = $ord->trans_no;
+       $ord->order_no = key($ord->trans_no);
+       $ord->trans_no = 0;
+       $ord->reference = references::get_next(13);
+       $_SESSION['Items'] = $ord;
+       copy_from_cart();
 
-function check_order_changed()
-{
-       global $debug;
+} elseif (isset($_GET['ModifyDelivery']) && $_GET['ModifyDelivery'] > 0) {
 
-       /*Now need to check that the order details are the same as they were when
-                       they were read into the Items array.
-       If they've changed then someone else may have dispatch them */
+       $_SESSION['Items'] = new Cart(13,$_GET['ModifyDelivery']);
 
-       $sql = "SELECT id, stk_code, quantity, qty_sent FROM ".TB_PREF."sales_order_details WHERE
-               order_no = " . $_SESSION['ProcessingOrder']. " ORDER BY id";
+       if ($_SESSION['Items']->count_items() == 0) {
+               hyperlink_params($path_to_root . "/sales/inquiry/sales_orders_view.php",
+                       _("Select a different delivery"), "OutstandingOnly=1");
+               echo "<br><center><b>" . _("This delivery has all items invoiced. There is nothing to modify.") .
+                       "</center></b>";
+               display_footer_exit();
+       }
 
-       $result = db_query($sql,"retreive sales order details");
+       copy_from_cart();
 
-       if (db_num_rows($result) != count($_SESSION['Items']->line_items))
-       {
+} elseif ( !processing_active() ) {
+       /* This page can only be called with an order number for invoicing*/
 
-               /*there should be the same number of items returned from this query as 
-                  count of lines on the delivery notes - if  not       then someone has 
-                  already invoiced or credited some lines */
-       if ($debug == 1)
-       {
-               display_note($sql, 1, 0);
-               display_note("No rows returned by sql:" . db_num_rows($result), 1, 0);
-               display_note("Count of items in the cart " . count($_SESSION['Items']->line_items), 1, 0);
-       }
+       display_error(_("This page can only be opened if an order or delivery note has been selected. Please select it first."));
 
-               return false;
-       }
-       $line=0;
-       while ($myrow = db_fetch($result)) 
-       {
-               $stk_itm = $myrow["stk_code"];
-               if ($_SESSION['Items']->line_items[$line]->quantity != $myrow["quantity"] ||
-                       $_SESSION['Items']->line_items[$line]->qty_done != $myrow["qty_sent"])
-               {
-                       display_note(_("Original order for") . " '" . $myrow["stk_code"] . "' " .
-                               _("has a quantity of") . " " . $myrow["quantity"] . " " . 
-                               _("and an delivered quantity of") . " " . $myrow["qty_sent"] . " " .
-                               _("the cart shows quantity of") . " " . 
-                               $_SESSION['Items']->line_items[$line]->quantity . " " . 
-                               _("and delivered quantity of") . " " . 
-                               $_SESSION['Items']->line_items[$line]->qty_done, 1, 0);
+       hyperlink_params("$path_to_root/sales/inquiry/sales_orders_view.php", _("Select a Sales Order to Delivery"), "OutstandingOnly=1");
 
-                       return false;
-               }
-       $line++;
-       } /*loop through all line items of the order to ensure none have been invoiced */
-       return true;
-}
+       end_page();
+       exit;
 
-//---------------------------------------------------------------------------------------------------------------
+} elseif (!check_quantities()) {
+       display_error(_("Selected quantity cannot be less then quantity invoiced nor more then quantity
+               not dispatched on sales order."));
+}
+//-----------------------------------------------------------------------------
 
 function check_data()
 {
-       if (!isset($_POST['DispatchDate']) || !is_date($_POST['DispatchDate'])) 
-       {
+       if (!isset($_POST['DispatchDate']) || !is_date($_POST['DispatchDate'])) {
                display_error(_("The entered date of delivery is invalid."));
                return false;
        }
-       if (!is_date_in_fiscalyear($_POST['DispatchDate'])) 
-       {
+
+       if (!is_date_in_fiscalyear($_POST['DispatchDate'])) {
                display_error(_("The entered date of delivery is not in fiscal year."));
                return false;
        }
-       if (!isset($_POST['due_date']) || !is_date($_POST['due_date'])) 
-       {
+
+       if (!isset($_POST['due_date']) || !is_date($_POST['due_date'])) {
                display_error(_("The entered dead-line for invoice is invalid."));
                return false;
        }
 
-       if (!references::is_valid($_POST['ref'])) 
-       {
-               display_error(_("You must enter a reference."));
-               return false;
-       }
+       if ($_SESSION['Items']->trans_no==0) {
+               if (!references::is_valid($_POST['ref'])) {
+                       display_error(_("You must enter a reference."));
+                       return false;
+               }
 
-       if (!is_new_reference($_POST['ref'], 13)) 
-       {
-               display_error(_("The entered reference is already in use."));
-               return false;
+               if ($_SESSION['Items']->trans_no==0 && !is_new_reference($_POST['ref'], 13)) {
+                       display_error(_("The entered reference is already in use."));
+                       return false;
+               }
        }
-       if ($_POST['ChargeFreightCost'] == "")
+       if ($_POST['ChargeFreightCost'] == "") {
                $_POST['ChargeFreightCost'] = 0;
-       if (!is_numeric($_POST['ChargeFreightCost']) || $_POST['ChargeFreightCost'] < 0)        
-       {
+       }
+
+       if (!is_numeric($_POST['ChargeFreightCost']) || $_POST['ChargeFreightCost'] < 0) {
                display_error(_("The entered shipping value is not numeric."));
                return false;
        }
 
-       if ($_SESSION['Items']->has_items_dispatch() == 0 && $_POST['ChargeFreightCost'] == 0)  
-       {
+       if ($_SESSION['Items']->has_items_dispatch() == 0 && $_POST['ChargeFreightCost'] == 0) {
                display_error(_("There are no item quantities on this delivery note."));
                return false;
        }
 
+       if (!check_quantities()) {
+               display_error(_("Selected quantity cannot be less then quantity invoiced nor more then quantity
+               not dispatched on sales order."));
+               return false;
+       }
+
        return true;
 }
+//------------------------------------------------------------------------------
+function copy_to_cart()
+{
+       $cart = &$_SESSION['Items'];
+       $cart->ship_via = $_POST['ship_via'];
+       $cart->freight_cost = $_POST['ChargeFreightCost'];
+       $cart->document_date =  $_POST['DispatchDate'];
+       $cart->due_date =  $_POST['due_date'];
+       $cart->Location = $_POST['Location'];
+       $cart->Comments = $_POST['Comments'];
+       $cart->default_sales_type = $_POST['sales_type_id'];
+}
+//------------------------------------------------------------------------------
 
-//---------------------------------------------------------------------------------------------------------------
+function copy_from_cart()
+{
+       $cart = &$_SESSION['Items'];
+       $_POST['ship_via'] = $cart->ship_via;
+       $_POST['ChargeFreightCost'] = $cart->freight_cost;
+       $_POST['DispatchDate']= $cart->document_date;
+       $_POST['due_date'] = $cart->due_date;
+       $_POST['Location']= $cart->Location;
+       $_POST['Comments']= $cart->Comments;
+       $_POST['sales_type_id'] = $cart->default_sales_type;
+}
+//------------------------------------------------------------------------------
+
+function check_quantities()
+{
+       $ok =1;
+       // Update cart delivery quantities/descriptions
+       foreach ($_SESSION['Items']->line_items as $line=>$itm) {
+               if (isset($_POST['Line'.$line])) {
+               $line_qty = $_POST['Line'.$line];
+                       if (is_numeric($line_qty) && ($_POST['Line'.$line] <= $itm->quantity) &&
+                               ($_POST['Line'.$line] >= $itm->qty_done)) {
+
+                               $_SESSION['Items']->line_items[$line]->qty_dispatched = $line_qty;
+                       } else {
+                               $ok = 0;
+                       }
+
+               }
+
+               if (isset($_POST['Line'.$line.'Desc'])) {
+                       $line_desc = $_POST['Line'.$line.'Desc'];
+                       if (strlen($line_desc) > 0) {
+                               $_SESSION['Items']->line_items[$line]->item_description = $line_desc;
+                       }
+               }
+       }
+       $_SESSION['Items']->freight_cost = $_POST['ChargeFreightCost'];
+
+       return $ok;
+}
+//------------------------------------------------------------------------------
 
 function check_qoh()
 {
-       if (!sys_prefs::allow_negative_stock())
-       {
-       foreach ($_SESSION['Items']->line_items as $itm) 
-       {
+       if (!sys_prefs::allow_negative_stock()) {
+               foreach ($_SESSION['Items']->line_items as $itm) {
 
-                       if ($itm->qty_dispatched && has_stock_holding($itm->mb_flag))
-                       {
+                       if ($itm->qty_dispatched && has_stock_holding($itm->mb_flag)) {
                                $qoh = get_qoh_on_date($itm->stock_id, $_POST['Location'], $_POST['DispatchDate']);
 
-                       if ($itm->qty_dispatched > $qoh) 
-                       {
-                               display_error(_("The delivery cannot be processed because there is an insufficient quantity for item:") .
-                                       " " . $itm->stock_id . " - " .  $itm->item_description);
-                               return false;
-                       }
-               }
-       }
+                               if ($itm->qty_dispatched > $qoh) {
+                                       display_error(_("The delivery cannot be processed because there is an insufficient quantity for item:") .
+                                               " " . $itm->stock_id . " - " .  $itm->item_description);
+                                       return false;
+                               }
+                       }
+               }
        }
-
        return true;
 }
+//------------------------------------------------------------------------------
 
-//---------------------------------------------------------------------------------------------------------------
+if (isset($_POST['process_delivery']) && check_data() && check_qoh()) {
 
-function process_delivery($get_from_order=false)
-{
-       if ($get_from_order)
-       {   // entry point for direct delivery - cart contains completed order;
-           // we should have qty_dispatched and standard cost set anyway
-               unset($_SESSION['Items']->line_items);
-           read_sales_order($_SESSION['Items']->order_no, $_SESSION['Items']);
-
-               $duedate = get_invoice_duedate($_SESSION['Items']->customer_id, $_SESSION['Items']->delivery_date);
-               $delivery_no = add_sales_delivery($_SESSION['Items'],
-                       $_SESSION['Items']->delivery_date, $duedate, $_SESSION['Items']->order_no,
-                       $_SESSION['Items']->tax_group_id, $_SESSION['Items']->freight_cost,
-                       $_SESSION['Items']->Location, $_SESSION['Items']->ship_via,
-                       $_SESSION['Items']->default_sales_type, references::get_next(13),
-                       $_SESSION['Items']->memo_,0);
-       } 
-       else 
-       {
-       
-               if (!check_data())
-                       return;
-
-               if (!check_order_changed())
-                       order_changed_error();
-
-               if (!check_qoh())
-                       return;
-
-               if ($_POST['bo_policy'])
-                       $bo_policy = 0;
-               else
-                       $bo_policy = 1;
-                       
-               $delivery_no = add_sales_delivery($_SESSION['Items'],
-                       $_POST['DispatchDate'], $_POST['due_date'],     $_SESSION['ProcessingOrder'],
-                       $_SESSION['Items']->tax_group_id,$_POST['ChargeFreightCost'], $_POST['Location'],
-                       $_POST['ship_via'],     $_POST['sales_type_id'], $_POST['ref'],
-                       $_POST['InvoiceText'], $bo_policy);
-               unset($_SESSION['ProcessingOrder']);
+       $dn = &$_SESSION['Items'];
+
+       if ($_POST['bo_policy']) {
+               $bo_policy = 0;
+       } else {
+               $bo_policy = 1;
        }
-       meta_forward($_SERVER['PHP_SELF'], "AddedID=$delivery_no");
-}
+       $newdelivery = $dn->trans_no==0;
 
-//---------------------------------------------------------------------------------------------------------------
-if (isset($_GET['process_delivery']))
-       process_delivery(true);
-elseif (isset($_POST['process_delivery']))
-       process_delivery();
+       if ($newdelivery)
+                $dn->ref = $_POST['ref'];
 
-//-------------------------------------------------------------------------------------------------
+       copy_to_cart();
+       $delivery_no = $dn->write($bo_policy);
+       processing_end();
+
+       if ($newdelivery) {
+               meta_forward($_SERVER['PHP_SELF'], "AddedID=$delivery_no");
+       } else {
+               meta_forward($_SERVER['PHP_SELF'], "UpdatedID=$delivery_no");
+       }
+}
 
+//------------------------------------------------------------------------------
 start_form(false, true);
 
 start_table("$table_style2 width=80%", 5);
@@ -344,37 +287,44 @@ label_cells(_("Currency"), $_SESSION['Items']->customer_currency, "class='tableh
 end_row();
 start_row();
 
-if (!isset($_POST['ref']))
-       $_POST['ref'] = references::get_next(13);
+//if (!isset($_POST['ref']))
+//     $_POST['ref'] = references::get_next(13);
 
-ref_cells(_("Reference"), 'ref', null, "class='tableheader2'");
+if ($_SESSION['Items']->trans_no==0) {
+       ref_cells(_("Reference"), 'ref', $_SESSION['Items']->reference, "class='tableheader2'");
+} else {
+       label_cells(_("Reference"), $_SESSION['Items']->reference, "class='tableheader2'");
+}
 
-label_cells(_("For Sales Order"), get_customer_trans_view_str(systypes::sales_order(), $_SESSION['ProcessingOrder']), "class='tableheader2'");
+label_cells(_("For Sales Order"), get_customer_trans_view_str(systypes::sales_order(), $_SESSION['Items']->order_no), "class='tableheader2'");
 
-if (!isset($_POST['sales_type_id']))
+if (!isset($_POST['sales_type_id'])) {
        $_POST['sales_type_id'] = $_SESSION['Items']->default_sales_type;
-label_cell(_("Sales Type"), "class='tableheader2'");   
+}
+label_cell(_("Sales Type"), "class='tableheader2'");
 sales_types_list_cells(null, 'sales_type_id', $_POST['sales_type_id']);
 
 end_row();
 start_row();
 
-if (!isset($_POST['Location']))
+if (!isset($_POST['Location'])) {
        $_POST['Location'] = $_SESSION['Items']->Location;
-label_cell(_("Delivery From"), "class='tableheader2'");        
-locations_list_cells(null, 'Location', $_POST['Location'], false, true);
+}
+label_cell(_("Delivery From"), "class='tableheader2'");
+locations_list_cells(null, 'Location',$_POST['Location'], false, true);
 
-if (!isset($_POST['ship_via']))
+if (!isset($_POST['ship_via'])) {
        $_POST['ship_via'] = $_SESSION['Items']->ship_via;
-label_cell(_("Shipping Company"), "class='tableheader2'");     
+}
+label_cell(_("Shipping Company"), "class='tableheader2'");
 shippers_list_cells(null, 'ship_via', $_POST['ship_via']);
 
 // set this up here cuz it's used to calc qoh
-if (!isset($_POST['DispatchDate']) || !is_date($_POST['DispatchDate']))
-{
+if (!isset($_POST['DispatchDate']) || !is_date($_POST['DispatchDate'])) {
        $_POST['DispatchDate'] = Today();
-       if (!is_date_in_fiscalyear($_POST['DispatchDate']))
+       if (!is_date_in_fiscalyear($_POST['DispatchDate'])) {
                $_POST['DispatchDate'] = end_fiscalyear();
+       }
 }
 date_cells(_("Date"), 'DispatchDate', $_POST['DispatchDate'], 0, 0, 0, "class='tableheader'");
 end_row();
@@ -385,17 +335,16 @@ echo "</td><td>";// outer table
 
 start_table("$table_style width=90%");
 
-if (!isset($_POST['due_date']) || !is_date($_POST['due_date']))
-
+if (!isset($_POST['due_date']) || !is_date($_POST['due_date'])) {
        $_POST['due_date'] = get_invoice_duedate($_SESSION['Items']->customer_id, $_POST['DispatchDate']);
-
+}
 date_row(_("Invoice Dead-line"), 'due_date', $_POST['due_date'], 0, 0, 0, "class='tableheader'");
 end_table();
 
 echo "</td></tr>";
 end_table(1); // outer table
 
-display_heading(_("Invoice Items"));
+display_heading(_("Delivery Items"));
 
 start_table("$table_style width=80%");
 $th = array(_("Item Code"), _("Item Description"), _("Ordered"), _("Units"), _("Delivered"),
@@ -405,26 +354,27 @@ $k = 0;
 $has_marked = false;
 $show_qoh = true;
 
-foreach ($_SESSION['Items']->line_items as $line=>$ln_itm) 
-{      
-       if($ln_itm->quantity==$ln_itm->qty_done) continue; //this line is fully delivered
-    // if it's a non-stock item (eg. service) don't show qoh
-    if (sys_prefs::allow_negative_stock() || !has_stock_holding($ln_itm->mb_flag) ||
-               $ln_itm->qty_dispatched == 0)
-       $show_qoh = false;
+foreach ($_SESSION['Items']->line_items as $line=>$ln_itm) {
+       if ($ln_itm->quantity==$ln_itm->qty_done) {
+               continue; //this line is fully delivered
+       }
+       // if it's a non-stock item (eg. service) don't show qoh
+       if (sys_prefs::allow_negative_stock() || !has_stock_holding($ln_itm->mb_flag) ||
+               $ln_itm->qty_dispatched == 0) {
+               $show_qoh = false;
+       }
 
-       if ($show_qoh)
+       if ($show_qoh) {
                $qoh = get_qoh_on_date($ln_itm->stock_id, $_POST['Location'], $_POST['DispatchDate']);
+       }
 
-       if ($show_qoh && ($ln_itm->qty_dispatched > $qoh)) 
-       {
+       if ($show_qoh && ($ln_itm->qty_dispatched > $qoh)) {
                // oops, we don't have enough of one of the component items
                start_row("class='stockmankobg'");
                $has_marked = true;
-       } 
-       else
+       } else {
                alt_table_row_color($k);
-
+       }
        view_stock_status_cell($ln_itm->stock_id);
 
        text_cells(null, 'Line'.$line.'Desc', $ln_itm->item_description, 30, 50);
@@ -445,17 +395,16 @@ foreach ($_SESSION['Items']->line_items as $line=>$ln_itm)
 
        end_row();
 }
-  
+
 $_POST['ChargeFreightCost'] = $_SESSION['Items']->freight_cost;
 
-if (!is_numeric($_POST['ChargeFreightCost']))
-{
-       $_POST['ChargeFreightCost'] = 0;
+if (!is_numeric($_POST['ChargeFreightCost'])) {
+               $_POST['ChargeFreightCost'] = 0;
 }
 
 start_row();
 
-small_amount_cells(_("Shipping Cost"), 'ChargeFreightCost', null, "colspan=9 align=right");
+small_amount_cells(_("Shipping Cost"), 'ChargeFreightCost', $_SESSION['Items']->freight_cost, "colspan=9 align=right");
 
 $inv_items_total = $_SESSION['Items']->get_items_total_dispatch();
 
@@ -463,8 +412,8 @@ $display_sub_total = number_format2($inv_items_total + $_POST['ChargeFreightCost
 
 label_row(_("Sub-total"), $display_sub_total, "colspan=9 align=right","align=right");
 
-$taxes = $_SESSION['Items']->get_taxes($_SESSION['Items']->tax_group_id, $_POST['ChargeFreightCost']);
-$tax_total = display_edit_tax_items($taxes, 9);
+$taxes = $_SESSION['Items']->get_taxes($_POST['ChargeFreightCost']);
+$tax_total = display_edit_tax_items($taxes, 9, $_SESSION['Items']->tax_included);
 
 $display_total = number_format2(($inv_items_total + $_POST['ChargeFreightCost'] + $tax_total), user_price_dec());
 
@@ -472,14 +421,14 @@ label_row(_("Amount Total"), $display_total, "colspan=9 align=right","align=righ
 
 end_table(1);
 
-if ($has_marked)
-       display_note(_("Marked items have insufficient quantities in stock."), 0, 1, "class='red'");
-
+if ($has_marked) {
+       display_note(_("Marked items have insufficient quantities in stock as on day of delivery."), 0, 1, "class='red'");
+}
 start_table($table_style2);
 
 policy_list_row(_("Action For Balance"), "bo_policy", null);
 
-textarea_row(_("Memo"), 'InvoiceText', null, 50, 4);
+textarea_row(_("Memo"), 'Comments', null, 50, 4);
 
 end_table(1);
 
@@ -488,7 +437,6 @@ submit_center_last('process_delivery', _("Process Dispatch"));
 
 end_form();
 
-//---------------------------------------------------------------------------------------------
 
 end_page();
 
index 27d5d22066f51f125c2e43ad3b6d6f59b4dfb178..51c38d2fad729cebed7a8d8d4addececdfecc8cc 100644 (file)
 <?php
-
+//---------------------------------------------------------------------------
+//
+//     Entry/Modify Sales Invoice against single delivery
+//     Entry/Modify Batch Sales Invoice against batch of deliveries
+//
 $page_security = 2;
 $path_to_root="..";
 include_once($path_to_root . "/sales/includes/cart_class.inc");
 include_once($path_to_root . "/includes/session.inc");
-
 include_once($path_to_root . "/includes/data_checks.inc");
-
 include_once($path_to_root . "/includes/manufacturing.inc");
 include_once($path_to_root . "/sales/includes/sales_db.inc");
 include_once($path_to_root . "/sales/includes/sales_ui.inc");
-
+include_once($path_to_root . "/reporting/includes/reporting.inc");
 include_once($path_to_root . "/taxes/tax_calc.inc");
 
 $js = "";
-if ($use_popup_windows)
+if ($use_popup_windows) {
        $js .= get_js_open_window(900, 500);
-if ($use_date_picker)
+}
+if ($use_date_picker) {
        $js .= get_js_date_picker();
-page(_("Issue an Invoice for Delivery Note(s)"), false, false, "", $js);
+}
 
-//---------------------------------------------------------------------------------------------------------------
+if (isset($_GET['ModifyInvoice'])) {
+       $_SESSION['page_title'] = sprintf(_("Modifying Sales Invoice # %d.") ,$_GET['ModifyInvoice']);
+       $help_page_title = _("Modifying Sales Invoice");
+} elseif (isset($_GET['DeliveryNumber'])) {
+       $_SESSION['page_title'] = _("Issue an Invoice for Delivery Note");
+} elseif (isset($_GET['BatchInvoice'])) {
+       $_SESSION['page_title'] = _("Issue Batch Invoice for Delivery Notes");
+}
+
+page($_SESSION['page_title'], false, false, "", $js);
+
+//-----------------------------------------------------------------------------
+
+if (isset($_GET['AddedID'])) {
 
-if (isset($_GET['AddedID'])) 
-{
        $invoice_no = $_GET['AddedID'];
        $trans_type = 10;
+       print_hidden_script(10);
 
        display_notification(_("Selected deliveries has been processed"), true);
 
-       display_note(get_customer_trans_view_str($trans_type, $invoice_no, _("View this invoice")), 0, 1);
+       display_note(get_customer_trans_view_str($trans_type, $invoice_no, _("View This Invoice")), 0, 1);
+
+       display_note(print_document_link($invoice_no, _("Print This Invoice"), true, 10));
 
-       display_note(get_gl_view_str($trans_type, $invoice_no, _("View the GL Journal Entries for this Invoice")));
+       display_note(get_gl_view_str($trans_type, $invoice_no, _("View the GL Journal Entries for this Invoice")),1);
 
        hyperlink_params("$path_to_root/sales/inquiry/sales_deliveries_view.php", _("Select Another Delivery For Invoicing"), "OutstandingOnly=1");
 
        display_footer_exit();
-}
 
-//---------------------------------------------------------------------------------------------------------------
+} elseif (isset($_GET['UpdatedID']))  {
 
-if (!isset($_GET['DeliveryNumber']) && !isset($_SESSION['ProcessingDelivery']) && 
-       !isset($_GET['BatchInvoice']) && !isset($_GET['process_invoice'])) 
-{
-       /* This page can only be called with a delivery for invoicing*/
-       display_error(_("This page can only be opened after delivery selection. Please select delivery to invoicing first."));
+       $invoice_no = $_GET['UpdatedID'];
+       print_hidden_script(10);
 
-       hyperlink_no_params("$path_to_root/sales/inquiry/sales_deliveries_view.php", _("Select Delivery to Invoice"));
+       display_notification_centered(sprintf(_('Sales Invoice # %d has been updated.'),$invoice_no));
 
-       end_page();
-       exit;
-} 
-elseif (isset($_GET['DeliveryNumber'])|| isset($_GET['BatchInvoice'])) 
-{
+       display_note(get_trans_view_str(10, $invoice_no, _("View This Invoice")));
+       echo '<br>';
+       display_note(print_document_link($invoice_no, _("Print This Invoice"), true, 10));
 
+       hyperlink_no_params($path_to_root . "/sales/inquiry/customer_inquiry.php", _("Select A Different Invoice to Modify"));
 
-       if (isset($_SESSION['Items']))
-       {
-               unset($_SESSION['Items']->line_items);
-               unset ($_SESSION['Items']);
-       }
-
-    if(isset($_GET['BatchInvoice'])) {
-         $_SESSION['ProcessingDelivery'] = $_SESSION['DeliveryBatch'];
-         unset($_SESSION['DeliveryBatch']);
-    }
-    else
-         $_SESSION['ProcessingDelivery'] = array($_GET['DeliveryNumber']);
+       display_footer_exit();
 
-    $_SESSION['Items'] = new cart('delivery');
-    $_SESSION['Items']->trans_no = $_SESSION['ProcessingDelivery'];
+} elseif (isset($_GET['RemoveDN'])) {
 
-       /*read in all the selected deliveries into the Items cart  */
-       if (read_sales_delivery($_SESSION['ProcessingDelivery'], $_SESSION['Items'])) 
-       {
-         if ($_SESSION['Items']->count_items() == 0) 
-         {
-               hyperlink_params($path_to_root . "/sales/inquiry/sales_deliveries_view.php", _("Select a different delivery to invoice"), "OutstandingOnly=1");
-               die ("<br><b>" . _("There are no delivered items with a quantity left to invoice. There is nothing left to invoice.") . "</b>");
-      }
-       } 
-       else 
-       {
-               hyperlink_no_params("/sales_deliveries_view.php", _("Select a delivery note to invoice"));
-               die ("<br><b>" . _("This delivery note could not be retrieved. Please select another delivery.") . "</b>");
-       }
-} 
-else 
-{
-       foreach ($_SESSION['Items']->line_items as $line=>$itm) 
-       {
-         if(isset($_POST['Line'.$line])) {
-               $line_qty = $_POST['Line'.$line];
-               if (is_numeric($line_qty) && $_POST['Line'.$line] <= ($itm->quantity - $itm->qty_done))
-               {
-                       $_SESSION['Items']->line_items[$line]->qty_dispatched = $line_qty;
-               }
-         }
-       
-         if(isset($_POST['Line'.$line.'Desc'])) {
-               $line_desc = $_POST['Line'.$line.'Desc'];
-               if (strlen($line_desc) > 0) 
-               {
-                       $_SESSION['Items']->line_items[$line]->item_description = $line_desc;
+       for($line_no = 0; $line_no < count($_SESSION['Items']->line_items); $line_no++) {
+               $line = &$_SESSION['Items']->line_items[$line_no];
+               if ($line->src_no == $_GET['RemoveDN']) {
+                       $line->quantity = $line->qty_done;
+                       $line->qty_dispatched=0;
                }
-         }
        }
+       unset($line);
 }
 
-//---------------------------------------------------------------------------------------------------------------
+//-----------------------------------------------------------------------------
 
-function delivery_changed_error()
-{
-       global $path_to_root;
-       display_note(_("This delivery note has been changed or invoiced since this invoice was started to be confirmed. Processing halted."), 1, 0);
-       display_note(_("To enter and confirm this invoice the order must be re-selected and re-read again to update the changes made by the other user."), 1, 0);
+if ( (isset($_GET['DeliveryNumber']) && ($_GET['DeliveryNumber'] > 0) )
+       || isset($_GET['BatchInvoice'])) {
 
-       hyperlink_no_params("$path_to_root/sales/inquiry/sales_deliveries_view.php", _("Select a sales order for invoicing"));
+       processing_start();
 
-       unset($_SESSION['ProcessingDelivery']);
-       exit;
-}
+       if (isset($_GET['BatchInvoice'])) {
+               $src = $_SESSION['DeliveryBatch'];
+               unset($_SESSION['DeliveryBatch']);
+       } else {
+               $src = array($_GET['DeliveryNumber']);
+       }
+       /*read in all the selected deliveries into the Items cart  */
+       $dn = new Cart(13, $src, true);
 
-//---------------------------------------------------------------------------------------------------------------
+       if ($dn->count_items() == 0) {
+               hyperlink_params($path_to_root . "/sales/inquiry/sales_deliveries_view.php",
+                       _("Select a different delivery to invoice"), "OutstandingOnly=1");
+               die ("<br><b>" . _("There are no delivered items with a quantity left to invoice. There is nothing left to invoice.") . "</b>");
+       }
 
-function check_delivery_changed()
-{
-       global $debug;
+       $dn->trans_type = 10;
+       $dn->src_docs = $dn->trans_no;
+       $dn->trans_no = 0;
+       $dn->reference = references::get_next(10);
 
-       /*Now need to check that the delivery note details are the same 
-       as they were when they were read into the Items array.
-       If they've changed then someone else may have invoiced them */
+       $_SESSION['Items'] = $dn;
+       copy_from_cart();
 
-       $sql = "SELECT id, stock_id, quantity, qty_done FROM "
-               .TB_PREF."debtor_trans_details WHERE
-               debtor_trans_type = 13 AND (";
+} elseif (isset($_GET['ModifyInvoice']) && $_GET['ModifyInvoice'] > 0) {
 
-       foreach($_SESSION['Items']->trans_no as $key=>$num) {
-           if($key!=0) $sql .= ' OR ';
-           $sql .= 'debtor_trans_no =' . $num;
+       processing_start();
+       $_SESSION['Items'] = new Cart(10, $_GET['ModifyInvoice']);
+
+       if ($_SESSION['Items']->count_items() == 0) {
+               echo"<center><br><b>" . _("All quantities on this invoice has been credited. There is nothing to modify on this invoice") . "</b></center>";
+               display_footer_exit();
        }
-       $sql .= ') ORDER BY id';
-       $result = db_query($sql,"while checking delivery changes");
+       copy_from_cart();
+} elseif (!processing_active()) {
+       /* This page can only be called with a delivery for invoicing or invoice no for edit */
+       display_error(_("This page can only be opened after delivery selection. Please select delivery to invoicing first."));
 
-       if (db_num_rows($result) != count($_SESSION['Items']->line_items))
-       {
+       hyperlink_no_params("$path_to_root/sales/inquiry/sales_deliveries_view.php", _("Select Delivery to Invoice"));
 
-               /*there should be the same number of items returned from this query as there are lines on the invoice -
-                       if not then someone has already invoiced or credited some lines */
-       if ($debug == 1)
-       {
-               display_note($sql, 1, 0);
-               display_note("No rows returned by sql:" . db_num_rows($result), 1, 0);
-               display_note("Count of items in the session " . count($_SESSION['Items']->line_items), 1, 0);
-       }
+       end_page();
+       exit;
+} else {
+       foreach ($_SESSION['Items']->line_items as $line_no=>$itm) {
+               if (isset($_POST['Line'.$line_no])) {
+                       $line_qty = $_POST['Line'.$line_no];
+                       if (is_numeric($line_qty) && $_POST['Line'.$line_no] <= ($itm->quantity - $itm->qty_done)) {
+                               $_SESSION['Items']->line_items[$line_no]->qty_dispatched = $line_qty;
+                       }
+               }
 
-               return false;
+               if (isset($_POST['Line'.$line_no.'Desc'])) {
+                       $line_desc = $_POST['Line'.$line_no.'Desc'];
+                       if (strlen($line_desc) > 0) {
+                               $_SESSION['Items']->line_items[$line_no]->item_description = $line_desc;
+                       }
+               }
        }
-       $line=0;
-       while ($myrow = db_fetch($result)) 
-       {
-               $stk_itm = $myrow["stock_id"];
-
-               if ($_SESSION['Items']->line_items[$line]->quantity != -$myrow["quantity"] ||
-                       $_SESSION['Items']->line_items[$line]->qty_done != -$myrow["qty_done"])
-               {
-                       display_note(_("Original delivery for line #") . $line+1 . ' '.
-                               _("has a quantity of") . " " . -$myrow["quantity"] . " " . 
-                               _("and an delivered quantity of") . " " . -$myrow["qty_done"] . "." .
-                               _("Now the quantity of") . " " . 
-                               $_SESSION['Items']->line_items[$line]->quantity . " " . 
-                               _("and invoiced quantity of") . " " . 
-                               $_SESSION['Items']->line_items[$line]->qty_done, 1, 0);
+}
+//-----------------------------------------------------------------------------
 
-                       return false;
-               }
-       $line++;
-       } /*loop through all line items of the order to ensure none have been invoiced */
-       return true;
+function copy_to_cart()
+{
+       $cart = &$_SESSION['Items'];
+       $cart->ship_via = $_POST['ship_via'];
+       $cart->freight_cost = $_POST['ChargeFreightCost'];
+       $cart->document_date =  $_POST['InvoiceDate'];
+       $cart->due_date =  $_POST['due_date'];
+       $cart->Comments = $_POST['Comments'];
 }
+//-----------------------------------------------------------------------------
 
+function copy_from_cart()
+{
+       $cart = &$_SESSION['Items'];
+       $_POST['ship_via'] = $cart->ship_via;
+       $_POST['ChargeFreightCost'] = $cart->freight_cost;
+       $_POST['InvoiceDate']= $cart->document_date;
+       $_POST['due_date'] = $cart->due_date;
+       $_POST['Comments']= $cart->Comments;
+}
 
-//---------------------------------------------------------------------------------------------------------------
+//-----------------------------------------------------------------------------
 
 function check_data()
 {
-       if (!isset($_POST['InvoiceDate']) || !is_date($_POST['InvoiceDate']))   
-       {
+       if (!isset($_POST['InvoiceDate']) || !is_date($_POST['InvoiceDate'])) {
                display_error(_("The entered invoice date is invalid."));
                return false;
        }
-       if (!is_date_in_fiscalyear($_POST['InvoiceDate'])) 
-       {
+
+       if (!is_date_in_fiscalyear($_POST['InvoiceDate'])) {
                display_error(_("The entered invoice date is not in fiscal year."));
                return false;
        }
-       if (!isset($_POST['due_date']) || !is_date($_POST['due_date'])) 
-       {
+
+       if (!isset($_POST['due_date']) || !is_date($_POST['due_date'])) {
                display_error(_("The entered invoice due date is invalid."));
                return false;
        }
 
-       if (!references::is_valid($_POST['ref'])) 
-       {
-               display_error(_("You must enter a reference."));
-               return false;
-       }
+       if ($_SESSION['Items']->trans_no == 0) {
+               if (!references::is_valid($_POST['ref'])) {
+                       display_error(_("You must enter a reference."));
+                       return false;
+               }
 
-       if (!is_new_reference($_POST['ref'], 10)) 
-       {
-               display_error(_("The entered reference is already in use."));
-               return false;
+               if (!is_new_reference($_POST['ref'], 10)) {
+                       display_error(_("The entered reference is already in use."));
+                       return false;
+               }
        }
-       if ($_POST['ChargeFreightCost'] == "")
+
+       if ($_POST['ChargeFreightCost'] == "") {
                $_POST['ChargeFreightCost'] = 0;
-       if (!is_numeric($_POST['ChargeFreightCost']) || $_POST['ChargeFreightCost'] < 0)        
-       {
+       }
+
+       if (!is_numeric($_POST['ChargeFreightCost']) || $_POST['ChargeFreightCost'] < 0) {
                display_error(_("The entered shipping value is not numeric."));
                return false;
        }
 
-       if ($_SESSION['Items']->has_items_dispatch() == 0 && $_POST['ChargeFreightCost'] == 0)  
-       {
+       if ($_SESSION['Items']->has_items_dispatch() == 0 && $_POST['ChargeFreightCost'] == 0) {
                display_error(_("There are no item quantities on this invoice."));
                return false;
        }
@@ -229,56 +217,50 @@ function check_data()
        return true;
 }
 
-//---------------------------------------------------------------------------------------------------------------
+//-----------------------------------------------------------------------------
+if (isset($_POST['process_invoice']) && check_data()) {
 
-function process_invoice($invoicing=false)
-{
-       if ($invoicing) 
-       {
-               read_sales_delivery($_SESSION['Items']->trans_no, $_SESSION['Items']);
-               $duedate = get_invoice_duedate($_SESSION['Items']->customer_id, $_SESSION['Items']->delivery_date);
-               $invoice_no = add_sales_invoice($_SESSION['Items'],
-                       $_SESSION['Items']->delivery_date, $duedate,
-                       $_SESSION['Items']->tax_group_id, $_SESSION['Items']->freight_cost,
-                       $_SESSION['Items']->Location, $_SESSION['Items']->ship_via,
-                       $_SESSION['Items']->default_sales_type, references::get_next(10),
-                       $_SESSION['Items']->memo_);
-       } 
-       else 
-       {
-       
-               if (!check_data())
-                       return;
-
-               if (!check_delivery_changed())
-                       delivery_changed_error();
-
-               $invoice_no = add_sales_invoice($_SESSION['Items'],
-                       $_POST['InvoiceDate'], $_POST['due_date'],
-                       $_SESSION['Items']->tax_group_id,       
-                       $_POST['ChargeFreightCost'], 
-                       $_SESSION['Items']->Location, 
-                       $_POST['ship_via'],     $_POST['sales_type_id'], $_POST['ref'],
-                       $_POST['InvoiceText']); 
-               unset($_SESSION['ProcessingDelivery']);
+       $newinvoice=  $_SESSION['Items']->trans_no == 0;
+       copy_to_cart();
+       $invoice_no = $_SESSION['Items']->write();
+
+       processing_end();
+       if ($newinvoice) {
+               meta_forward($_SERVER['PHP_SELF'], "AddedID=$invoice_no");
+       } else {
+               meta_forward($_SERVER['PHP_SELF'], "UpdatedID=$invoice_no");
        }
-       meta_forward($_SERVER['PHP_SELF'], "AddedID=$invoice_no");
 }
 
-//---------------------------------------------------------------------------------------------------------------
-if (isset($_GET['process_invoice']))
-       process_invoice(true);
-elseif (isset($_POST['process_invoice']))
-       process_invoice();
+// find delivery spans for batch invoice display
+$dspans = array();
+$lastdn = ''; $spanlen=1;
+
+for ($line_no = 0; $line_no < count($_SESSION['Items']->line_items); $line_no++) {
+       $line = $_SESSION['Items']->line_items[$line_no];
+       if ($line->quantity == $line->qty_done) {
+               continue;
+       }
+       if ($line->src_no == $lastdn) {
+               $spanlen++;
+       } else {
+               if ($lastdn != '') {
+                       $dspans[] = $spanlen;
+                       $spanlen = 1;
+               }
+       }
+       $lastdn = $line->src_no;
+}
+$dspans[] = $spanlen;
 
-//-------------------------------------------------------------------------------------------------
+//-----------------------------------------------------------------------------
 
+$is_batch_invoice = count($_SESSION['Items']->src_docs) > 1;
+$is_edition = $_SESSION['Items']->trans_type == 10 && $_SESSION['Items']->trans_no != 0;
 start_form(false, true);
 
 start_table("$table_style2 width=80%", 5);
-//echo "<tr><td>"; // outer table
 
-//start_table("$table_style width=100%");
 start_row();
 label_cells(_("Customer"), $_SESSION['Items']->customer_name, "class='tableheader2'");
 label_cells(_("Branch"), get_branch_name($_SESSION['Items']->Branch), "class='tableheader2'");
@@ -286,82 +268,92 @@ label_cells(_("Currency"), $_SESSION['Items']->customer_currency, "class='tableh
 end_row();
 start_row();
 
-if (!isset($_POST['ref']))
-       $_POST['ref'] = references::get_next(10);
-
-ref_cells(_("Reference"), 'ref', null, "class='tableheader2'");
-
-label_cells(_("Delivery Notes:"), get_customer_trans_view_str(systypes::cust_dispatch(), $_SESSION['ProcessingDelivery']), "class='tableheader2'");
+if ($_SESSION['Items']->trans_no == 0) {
+       ref_cells(_("Reference"), 'ref', $_SESSION['Items']->reference, "class='tableheader2'");
+} else {
+       label_cells(_("Reference"), $_SESSION['Items']->reference, "class='tableheader2'");
+}
 
+label_cells(_("Delivery Notes:"),
+get_customer_trans_view_str(systypes::cust_dispatch(), array_keys($_SESSION['Items']->src_docs)), "class='tableheader2'");
 
-if (!isset($_POST['sales_type_id']))
+if (!isset($_POST['sales_type_id'])) {
        $_POST['sales_type_id'] = $_SESSION['Items']->default_sales_type;
-label_cell(_("Sales Type"), "class='tableheader2'");   
+}
+
+label_cell(_("Sales Type"), "class='tableheader2'");
 sales_types_list_cells(null, 'sales_type_id', $_POST['sales_type_id']);
 
 end_row();
 start_row();
 
-if (!isset($_POST['ship_via']))
+if (!isset($_POST['ship_via'])) {
        $_POST['ship_via'] = $_SESSION['Items']->ship_via;
-label_cell(_("Shipping Company"), "class='tableheader2'");     
+}
+label_cell(_("Shipping Company"), "class='tableheader2'");
 shippers_list_cells(null, 'ship_via', $_POST['ship_via']);
 
-if (!isset($_POST['InvoiceDate']) || !is_date($_POST['InvoiceDate']))
-{
+if (!isset($_POST['InvoiceDate']) || !is_date($_POST['InvoiceDate'])) {
        $_POST['InvoiceDate'] = Today();
-       if (!is_date_in_fiscalyear($_POST['InvoiceDate']))
+       if (!is_date_in_fiscalyear($_POST['InvoiceDate'])) {
                $_POST['InvoiceDate'] = end_fiscalyear();
+       }
 }
 
 date_cells(_("Date"), 'InvoiceDate', $_POST['InvoiceDate'], 0, 0, 0, "class='tableheader'");
-//end_table();
-
-//echo "</td><td>";// outer table
-
-//start_table("$table_style width=90%");
-
-if (!isset($_POST['due_date']) || !is_date($_POST['due_date']))
 
+if (!isset($_POST['due_date']) || !is_date($_POST['due_date'])) {
        $_POST['due_date'] = get_invoice_duedate($_SESSION['Items']->customer_id, $_POST['InvoiceDate']);
+}
 
 date_cells(_("Due Date"), 'due_date', $_POST['due_date'], 0, 0, 0, "class='tableheader'");
-//end_table();
 
-//echo "</td></tr>";
 end_row();
-end_table(); // outer table
+end_table();
 
 display_heading(_("Invoice Items"));
 
 start_table("$table_style width=80%");
 $th = array(_("Item Code"), _("Item Description"), _("Delivered"), _("Units"), _("Invoiced"),
        _("This Invoice"), _("Price"), _("Tax Type"), _("Discount"), _("Total"));
+
+if ($is_batch_invoice) {
+$th[] = _("DN");
+$th[] = "";
+}
+
+if ($is_edition) {
+$th[4] = _("Credited");
+}
+
 table_header($th);
 $k = 0;
 $has_marked = false;
 $show_qoh = true;
 
-foreach ($_SESSION['Items']->line_items as $line=>$ln_itm) 
-{
-       if($ln_itm->quantity==$ln_itm->qty_done) continue; //this line is fully delivered
-       alt_table_row_color($k);
+$dn_line_cnt = 0;
 
-       view_stock_status_cell($ln_itm->stock_id); // ?
+foreach ($_SESSION['Items']->line_items as $line=>$ln_itm) {
+       if ($ln_itm->quantity == $ln_itm->qty_done) {
+               continue; // this line was fully invoiced
+       }
+       alt_table_row_color($k);
+       view_stock_status_cell($ln_itm->stock_id);
 
        text_cells(null, 'Line'.$line.'Desc', $ln_itm->item_description, 30, 50);
        qty_cell($ln_itm->quantity);
        label_cell($ln_itm->units);
        qty_cell($ln_itm->qty_done);
 
-       if(count($_SESSION['Items']->trans_no)>1) {
-           // for batch invoices we can process only whole deliveries
-           qty_cell($ln_itm->qty_dispatched);
-           hidden('Line'.$line,$ln_itm->qty_dispatched );
-       } else
-           text_cells(null, 'Line'.$line, $ln_itm->qty_dispatched, 10, 10);
-
-       $display_discount_percent = number_format2($ln_itm->discount_percent*100,user_percent_dec()) . "%";
+       if ($is_batch_invoice) {
+               // for batch invoices we can only remove whole deliveries
+               echo '<td nowrap align=right>';
+               hidden('Line' . $line, $ln_itm->qty_dispatched );
+               echo number_format2($ln_itm->qty_dispatched, user_qty_dec()).'</td>';
+       } else {
+               text_cells(null, 'Line'.$line, $ln_itm->qty_dispatched, 10, 10);
+       }
+       $display_discount_percent = number_format2($ln_itm->discount_percent*100, user_percent_dec()) . "%";
 
        $line_total = ($ln_itm->qty_dispatched * $ln_itm->price * (1 - $ln_itm->discount_percent));
 
@@ -370,6 +362,16 @@ foreach ($_SESSION['Items']->line_items as $line=>$ln_itm)
        label_cell($display_discount_percent, "nowrap align=right");
        amount_cell($line_total);
 
+       if ($is_batch_invoice) {
+               if ($dn_line_cnt == 0) {
+                       $dn_line_cnt = $dspans[0];
+                       $dspans = array_slice($dspans, 1);
+                       label_cell($ln_itm->src_no, "rowspan=$dn_line_cnt class=oddrow");
+                       label_cell("<a href='" . $_SERVER['PHP_SELF'] . "?RemoveDN=".
+                               $ln_itm->src_no."'>" . _("Remove") . "</a>", "rowspan=$dn_line_cnt class=oddrow");
+               }
+               $dn_line_cnt--;
+       }
        end_row();
 }
 
@@ -378,47 +380,44 @@ depending on the business logic required this condition may not be required.
 It seems unfair to charge the customer twice for freight if the order
 was not fully delivered the first time ?? */
 
-if (!isset($_POST['ChargeFreightCost']) || $_POST['ChargeFreightCost'] == "") 
-{
-    if ($_SESSION['Items']->any_already_delivered() == 1) 
-    {
-       $_POST['ChargeFreightCost'] = 0;
-    } 
-    else 
-    {
-       $_POST['ChargeFreightCost'] = $_SESSION['Items']->freight_cost;
-    }
-    if (!is_numeric($_POST['ChargeFreightCost']))
-    {
-       $_POST['ChargeFreightCost'] = 0;
-    }
+if (!isset($_POST['ChargeFreightCost']) || $_POST['ChargeFreightCost'] == "") {
+       if ($_SESSION['Items']->any_already_delivered() == 1) {
+               $_POST['ChargeFreightCost'] = 0;
+       } else {
+               $_POST['ChargeFreightCost'] = $_SESSION['Items']->freight_cost;
+       }
+
+       if (!is_numeric($_POST['ChargeFreightCost'])) {
+               $_POST['ChargeFreightCost'] = 0;
+       }
 }
 
 start_row();
 
 small_amount_cells(_("Shipping Cost"), 'ChargeFreightCost', null, "colspan=9 align=right");
+if ($is_batch_invoice) {
+label_cell('', 'colspan=2');
+}
 
+end_row();
 $inv_items_total = $_SESSION['Items']->get_items_total_dispatch();
 
 $display_sub_total = number_format2($inv_items_total + $_POST['ChargeFreightCost'],user_price_dec());
 
-label_row(_("Sub-total"), $display_sub_total, "colspan=9 align=right","align=right");
+label_row(_("Sub-total"), $display_sub_total, "colspan=9 align=right","align=right", $is_batch_invoice ? 2 : 0);
 
-$taxes = $_SESSION['Items']->get_taxes($_SESSION['Items']->tax_group_id, $_POST['ChargeFreightCost']);
-$tax_total = display_edit_tax_items($taxes, 9);
+$taxes = $_SESSION['Items']->get_taxes($_POST['ChargeFreightCost']);
+$tax_total = display_edit_tax_items($taxes, 9, $_SESSION['Items']->tax_included, $is_batch_invoice ? 2:0);
 
 $display_total = number_format2(($inv_items_total + $_POST['ChargeFreightCost'] + $tax_total), user_price_dec());
 
-label_row(_("Invoice Total"), $display_total, "colspan=9 align=right","align=right");
+label_row(_("Invoice Total"), $display_total, "colspan=9 align=right","align=right", $is_batch_invoice ? 2 : 0);
 
 end_table(1);
 
-//if ($has_marked)
-//     display_note(_("Marked items have insufficient quantities in stock."), 0, 1, "class='red'");
-
 start_table($table_style2);
 
-textarea_row(_("Memo"), 'InvoiceText', null, 50, 4);
+textarea_row(_("Memo"), 'Comments', null, 50, 4);
 
 end_table(1);
 
@@ -427,8 +426,6 @@ submit_center_last('process_invoice', _("Process Invoice"));
 
 end_form();
 
-//---------------------------------------------------------------------------------------------
-
 end_page();
 
 ?>
index 0e38464f2a4fd0dd034bbd5e29407f769b930100..cd48b65805823dd7e8ea64af78d564572616a742 100644 (file)
@@ -3,20 +3,19 @@
 $path_to_root="..";
 $page_security = 3;
 include_once($path_to_root . "/includes/session.inc");
-
 include_once($path_to_root . "/includes/date_functions.inc");
-
 include_once($path_to_root . "/includes/ui.inc");
 include_once($path_to_root . "/includes/banking.inc");
 include_once($path_to_root . "/includes/data_checks.inc");
-
 include_once($path_to_root . "/sales/includes/sales_db.inc");
 
 $js = "";
-if ($use_popup_windows)
+if ($use_popup_windows) {
        $js .= get_js_open_window(900, 500);
-if ($use_date_picker)
+}
+if ($use_date_picker) {
        $js .= get_js_date_picker();
+}
 page(_("Customer Payment Entry"), false, false, "", $js);
 
 //----------------------------------------------------------------------------------------------
@@ -29,64 +28,58 @@ check_db_has_bank_trans_types(_("There are no bank payment types defined in the
 
 //----------------------------------------------------------------------------------------
 
-if (isset($_GET['AddedID'])) 
-{
+if (isset($_GET['AddedID'])) {
        $payment_no = $_GET['AddedID'];
 
        display_notification_centered(_("The customer payment has been successfully entered."));
 
-       display_note(get_gl_view_str(systypes::cust_payment(), $payment_no, _("View the GL Journal Entries for this Customer Payment")));
-       hyperlink_params($path_to_root . "/sales/allocations/customer_allocate.php", _("Allocate this Customer Payment"), "trans_no=$payment_no&trans_type=" . systypes::cust_payment());
-    hyperlink_no_params($path_to_root . "/sales/customer_payments.php", _("Enter Another Customer Payment"));
+       display_note(get_gl_view_str(12, $payment_no, _("View the GL Journal Entries for this Customer Payment")));
+
+       hyperlink_params($path_to_root . "/sales/allocations/customer_allocate.php", _("Allocate this Customer Payment"), "trans_no=$payment_no&trans_type=12");
+
+       hyperlink_no_params($path_to_root . "/sales/customer_payments.php", _("Enter Another Customer Payment"));
        br(1);
        end_page();
-       exit;
+       exit;
 }
 
 //----------------------------------------------------------------------------------------------
 
 function can_process()
 {
-       if (!isset($_POST['DateBanked']) || !is_date($_POST['DateBanked'])) 
-       {
+       if (!isset($_POST['DateBanked']) || !is_date($_POST['DateBanked'])) {
                display_error(_("The entered date is invalid. Please enter a valid date for the payment."));
                return false;
-       } 
-       elseif (!is_date_in_fiscalyear($_POST['DateBanked'])) 
-       {
+       } elseif (!is_date_in_fiscalyear($_POST['DateBanked'])) {
                display_error(_("The entered date is not in fiscal year."));
                return false;
        }
 
-       if (!references::is_valid($_POST['ref'])) 
-       {
+       if (!references::is_valid($_POST['ref'])) {
                display_error(_("You must enter a reference."));
                return false;
        }
 
-       if (!is_new_reference($_POST['ref'], systypes::cust_payment())) 
-       {
+       if (!is_new_reference($_POST['ref'], 12)) {
                display_error(_("The entered reference is already in use."));
                return false;
        }
 
-       if ((!is_numeric($_POST['amount']) || $_POST['amount'] < 0)) 
-       {
+       if ((!is_numeric($_POST['amount']) || $_POST['amount'] < 0)) {
                display_error(_("The entered amount is invalid or negative and cannot be processed."));
                return false;
        }
 
-       if (!isset($_POST['discount']) || ($_POST['discount'] == ""))
+       if (!isset($_POST['discount']) || ($_POST['discount'] == "")) {
                $_POST['discount'] = 0;
+       }
 
-       if (!is_numeric($_POST['discount'])) 
-       {
+       if (!is_numeric($_POST['discount'])) {
                display_error(_("The entered discount is not a valid number."));
                return false;
        }
 
-       if (($_POST['amount'] - $_POST['discount'] <= 0)) 
-       {
+       if (($_POST['amount'] - $_POST['discount'] <= 0)) {
                display_error(_("The balance of the amount and discout is zero or negative. Please enter valid amounts."));
                return false;
        }
@@ -97,18 +90,17 @@ function can_process()
 //----------------------------------------------------------------------------------------------
 
 // validate inputs
-if (isset($_POST['AddPaymentItem']))
-{
+if (isset($_POST['AddPaymentItem'])) {
 
-       if (!can_process())
+       if (!can_process()) {
                unset($_POST['AddPaymentItem']);
+       }
 }
 
 //----------------------------------------------------------------------------------------------
 
-if (isset($_POST['AddPaymentItem']))
-{
-       $payment_no = add_customer_payment($_POST['customer_id'], $_POST['BranchID'],
+if (isset($_POST['AddPaymentItem'])) {
+       $payment_no = write_customer_payment(0, $_POST['customer_id'], $_POST['BranchID'],
                $_POST['bank_account'], $_POST['DateBanked'], $_POST['ReceiptType'], $_POST['ref'],
                $_POST['amount'], $_POST['discount'], $_POST['memo_']);
 
@@ -131,7 +123,7 @@ function read_customer_data()
 
        $_POST['HoldAccount'] = $myrow["dissallow_invoices"];
        $_POST['pymt_discount'] = $myrow["pymt_discount"];
-       $_POST['ref'] = references::get_next(systypes::cust_payment());
+       $_POST['ref'] = references::get_next(12);
 }
 
 //-------------------------------------------------------------------------------------------------
@@ -146,78 +138,71 @@ function display_item_form()
 
        if (!isset($_POST['customer_id']))
                $_POST['customer_id'] = get_global_customer(false);
-       if (!isset($_POST['DateBanked']))
-       {
+       if (!isset($_POST['DateBanked'])) {
                $_POST['DateBanked'] = Today();
-               if (!is_date_in_fiscalyear($_POST['DateBanked']))
+               if (!is_date_in_fiscalyear($_POST['DateBanked'])) {
                        $_POST['DateBanked'] = end_fiscalyear();
-       }               
+               }
+       }
        customer_list_row(_("From Customer:"), 'customer_id', null, false, true);
 
-       if (db_customer_has_branches($_POST['customer_id'])) 
-       {
+       if (db_customer_has_branches($_POST['customer_id'])) {
                customer_branches_list_row(_("Branch:"), $_POST['customer_id'], 'BranchID', null, false, true, true);
-       } 
-       else 
-       {
+       } else {
                hidden('BranchID', reserved_words::get_any_numeric());
        }
 
-    read_customer_data();
+       read_customer_data();
 
-    set_global_customer($_POST['customer_id']);
+       set_global_customer($_POST['customer_id']);
 
-       if (isset($_POST['HoldAccount']) && $_POST['HoldAccount'] != 0)
-       {
+       if (isset($_POST['HoldAccount']) && $_POST['HoldAccount'] != 0) {
                echo "</table></table>";
                display_note(_("This customer account is on hold."), 0, 0, "class='redfb'");
-       }
-       else
-       {
-       $display_discount_percent = number_format2($_POST['pymt_discount']*100,user_price_dec()) . "%";
+       } else {
+               $display_discount_percent = number_format2($_POST['pymt_discount']*100,user_price_dec()) . "%";
 
-       amount_row(_("Amount:"), 'amount');
+               amount_row(_("Amount:"), 'amount');
 
-       amount_row(_("Amount of Discount:"), 'discount');
+               amount_row(_("Amount of Discount:"), 'discount');
 
-       label_row(_("Customer prompt payment discount :"), $display_discount_percent);
+               label_row(_("Customer prompt payment discount :"), $display_discount_percent);
 
-       date_row(_("Date of Deposit:"), 'DateBanked');
+               date_row(_("Date of Deposit:"), 'DateBanked');
 
-       echo "</table>";
-       echo "</td><td valign=top class='tableseparator'>"; // outer table
-       echo "<table>";
+               echo "</table>";
+               echo "</td><td valign=top class='tableseparator'>"; // outer table
+               echo "<table>";
 
-       bank_accounts_list_row(_("Into Bank Account:"), 'bank_account', null, true);
+               bank_accounts_list_row(_("Into Bank Account:"), 'bank_account', null, true);
 
-       $cust_currency = get_customer_currency($_POST['customer_id']);
-       $bank_currency = get_bank_account_currency($_POST['bank_account']);
+               $cust_currency = get_customer_currency($_POST['customer_id']);
+               $bank_currency = get_bank_account_currency($_POST['bank_account']);
 
-       if ($cust_currency != $bank_currency) 
-       {
+               if ($cust_currency != $bank_currency) {
                        exchange_rate_display($cust_currency, $bank_currency, $_POST['DateBanked']);
-       }
+               }
 
                bank_trans_types_list_row(_("Type:"), 'ReceiptType', null);
 
-       text_row(_("Reference:"), 'ref', null, 20, 40);
+               text_row(_("Reference:"), 'ref', null, 20, 40);
 
-       textarea_row(_("Memo:"), 'memo_', null, 22, 4);
+               textarea_row(_("Memo:"), 'memo_', null, 22, 4);
 
-       echo "</table>";
+               echo "</table>";
 
                echo "</td></tr>";
                end_table(); // outer table
 
-       if ($cust_currency != $bank_currency)
-               display_note(_("Amount and discount are in customer's currency."));
+               if ($cust_currency != $bank_currency)
+                       display_note(_("Amount and discount are in customer's currency."));
 
-       echo"<br>";
+               echo"<br>";
 
-       submit_center('AddPaymentItem', _("Add Payment"));
+               submit_center('AddPaymentItem', _("Add Payment"));
        }
 
-    echo "<br>";
+       echo "<br>";
 }
 
 //----------------------------------------------------------------------------------------------
index 25de205d1b4f280e12d5a20cbd0065f9c9caea78..0e355efb58e82b0e6ec989e0ce23dc2232ea3eba 100644 (file)
@@ -14,59 +14,211 @@ include_once($path_to_root . "/taxes/tax_calc.inc");
 
 class cart
 {
+       var $trans_type; // invoice, order, delivery note ...
+       var $trans_no = array();// array (num1=>ver1,..) or 0 for new
+       var $so_type = 0;               // for sales order: simple=0 template=1
+
+       var $line_items;  //array of objects of class line_details
 
-       var $line_items; /*array of objects of class line_details using the product id as the pointer */
+       var $src_docs = array();        // array of arrays(num1=>ver1,...) or 0 for no src
+       var $src_date;                  // src document date (for info only)
 
-       var $delivery_date;
+       var $document_date;
+       var $due_date;
        var $default_sales_type; // set to the customer's sales type
        var $sales_type_name; // set to customer's sales type name
+       var $tax_included;
+
        var $customer_currency; // set to the customer's currency
        var $default_discount; // set to the customer's discount %
-       var $trans_type; // invoice, order, delivery note ...
-       var $memo_; // memo_ on direct invoicing
+       var $customer_name;
+       var $customer_id;
+       var $Branch;
+       var $email;
 
        var $deliver_to;
        var $delivery_address;
        var $phone;
 
-       var $email;
        var $cust_ref;
+       var $reference;
        var $Comments;
        var $Location;
        var $location_name;
-       var $order_no; // the original order number     
-       var $trans_no;// transaction number
-
-       var $customer_name;
-       var $customer_id;
-       var $Branch;
-
-       var $orig_order_date;
+       var $order_no;          // the original order number
+       var $trans_link = 0;
 
        var $ship_via;
-       var $freight_cost;
+       var $freight_cost = 0;
 
        var $tax_group_id;
        var $tax_group_name;
-
-       function Cart($type = 'order')
-       {
+       var $tax_group_array = null; // saves db queries
+
+       //-------------------------------------------------------------------------
+       //
+       //  $trans_no==0 => open new/direct document
+       //  $trans_no!=0 && $view==false => read for view
+       //  $trans_no!=0 && $view==true => read for edit (qty update from parent doc)
+       //
+       function Cart($type, $trans_no=0, $view=false ) {
                /*Constructor function initialises a new shopping cart */
                $this->line_items = array();
                $this->default_sales_type = "";
-               $this->trans_type = $type;
+               $this->trans_type = 30;
+               $this->read($type, $trans_no, $view );
+
        }
 
-       function add_to_cart($stock_id, $qty, $price, $disc, $qty_done=0, $standard_cost=0, $description=null, $id=0)
+
+       function read($type, $trans_no=0, $view=false ) {
+
+       if (!is_array($trans_no)) $trans_no = array($trans_no);
+
+       if ($trans_no[0]) {
+               if ($type==30) { // sales order
+                       read_sales_order($trans_no[0], $this);
+                       if ($view) {    // prepare for DN/IV entry
+                               for($line_no=0; $line_no<count($this->line_items); $line_no++) {
+                                       $line= &$this->line_items[$line_no];
+                                       $line->qty_dispatched = $line->quantity-$line->qty_done;
+                               }
+                       }
+                       } else {        // derivative transaction
+                               read_sales_trans($type, $trans_no, $this);
+                               if ($this->order_no) { // free hand credit notes have no order_no
+                                       $sodata = get_sales_order_header($this->order_no);
+                                       $this->cust_ref = $sodata["customer_ref"];
+//set_customer($customer_name, $customer_id, $currency, $discount)
+//*                                    $this->customer_name = $sodata["name"];
+//*                                    $this->customer_currency = $sodata["curr_code"];
+//*                                    $this->Comments = $sodata["comments"];
+                                       $this->delivery_address = $sodata["delivery_address"];
+//                                     $this->location_name = $sodata["location_name"];
+//                                     $this->document_date = sql2date($myrow["ord_date"]);
+                               }
+                               if (!$view && ($type!=11 || $this->trans_link!=0)) {
+                                       $src_type = get_parent_type($type);
+                                       $src_details = 0;
+                                       if ($src_type==30) { // get src data from sales_orders
+                                               $this->src_docs = array( $sodata['order_no']=>$sodata['version']);
+                                               $srcdetails = get_sales_order_details($this->order_no);
+                                       } else {        // get src_data from debtor_trans
+                                               $this->src_docs = get_customer_trans_version($src_type, get_parent_trans($type,$trans_no[0]));
+                                               $srcdetails = get_customer_trans_details($src_type,array_keys($this->src_docs));
+                                       }
+                                       // calculate & save: qtys on other docs and free qtys on src doc
+                                       $line_no = 0;
+                                       for($line_no=0; $srcline = db_fetch($srcdetails); $line_no++) {
+                                               $sign = 1; // $type==13 ?  1 : -1; // this is strange debtor_trans atavism
+                                               $line = &$this->line_items[$line_no];
+
+                                               $line->qty_old = $line->qty_dispatched = $line->quantity;
+                                               $line->quantity += $sign*($srcline['quantity']-$srcline['qty_done']); // add free qty on src doc
+                                       }
+                               } else {
+                                       for($line_no=0; $line_no<count($this->line_items); $line_no++) {
+                                               $line= &$this->line_items[$line_no];
+                                               $line->qty_dispatched = $line->quantity;
+                                       }
+                               }
+                       }
+               } else {
+                       $this->trans_type = $type;
+                       $this->trans_no = 0;
+                       // set new sales document defaults here
+                       $this->customer_id='';
+                       $this->document_date = Today();
+                       if (!is_date_in_fiscalyear($this->document_date))
+                       $this->document_date = end_fiscalyear();
+                       $this->reference = references::get_next($this->trans_type);
+               }
+       }
+
+       //-------------------------------------------------------------------------
+       // Writing new/modified sales document to database.
+       // Makes parent documents for direct delivery/invoice by recurent call.
+
+       function write($policy=0) {
+               if (count($this->src_docs) == 0 && ($this->trans_type == 10 || $this->trans_type == 13)) {
+                       // direct document -> first add parent
+                       $src = $this; // make local copy of this cart
+                       $src->trans_type = get_parent_type($src->trans_type);
+                       $src->reference = 'auto';
+
+                       $src->write(1);
+                       $type = $this->trans_type;
+                       $ref = $this->reference;
+                       // re-read document
+                       $this->read($src->trans_type, key($src->trans_no), true);
+
+                       $this->reference = $ref;
+                       $this->trans_type = $type;
+                       $this->src_docs= $this->trans_no;
+                       $this->trans_no = 0;
+                       $this->order_no= $this->trans_type==13 ? key($src->trans_no) : $src->order_no;
+               }
+               switch($this->trans_type) {
+                       case 10:
+                               return write_sales_invoice($this);
+                       case 11:
+                               return write_credit_note($this, $policy);
+                       case 13:
+                               return write_sales_delivery($this, $policy);
+                       case 30:
+                               if ($this->trans_no==0) // new document
+                                       return add_sales_order($this);
+                               else
+                                       return update_sales_order($this);
+               }
+       }
+
+       function set_customer($customer_id, $customer_name, $currency, $discount)
        {
-               if (isset($stock_id) && $stock_id != "" && isset($qty)/* && $qty > 0*/)
-               {
-                       $this->line_items[] = new line_details($stock_id, $qty, $price, $disc, 
-                               $qty_done,  $standard_cost, $description, $id);
+               $this->customer_name = $customer_name;
+               $this->customer_id = $customer_id;
+               $this->default_discount = $discount;
+               $this->customer_currency = $currency;
+       }
+
+       function set_branch($branch_id, $tax_group_id, $tax_group_name, $phone='', $email='')
+       {
+               $this->Branch = $branch_id;
+               $this->phone = $phone;
+               $this->email = $email;
+               $this->tax_group_id = $tax_group_id;
+               $this->tax_group_array = get_tax_group_items_as_array($tax_group_id);
+       }
+
+       function set_sales_type($sales_type, $sales_name, $tax_included=0)
+       {
+               $this->default_sales_type = $sales_type;
+               $this->sales_type_name = $sales_name;
+               $this->tax_included = $tax_included;
+       }
+
+       function set_location($id, $name)
+       {
+               $this->Location = $id;
+               $this->location_name = $name;
+       }
+
+       function set_delivery($shipper, $destination, $address, $freight_cost=null)
+       {
+               $this->ship_via = $shipper;
+               $this->deliver_to = $destination;
+               $this->delivery_address = $address;
+               if (isset($freight_cost))
+                       $this->freight_cost = $freight_cost;
+       }
+
+       function add_to_cart($line_no,$stock_id, $qty, $price, $disc, $qty_done=0, $standard_cost=0, $description=null, $id=0, $src_no=0)
+       {
+               if (isset($stock_id) && $stock_id != "" && isset($qty)/* && $qty > 0*/) {
+                       $this->line_items[$line_no] = new line_details($stock_id, $qty, $price, $disc,
+                               $qty_done,  $standard_cost, $description, $id, $src_no);
                        return 1;
-               }
-               else
-               {
+               } else {
                        // shouldn't come here under normal circumstances
                        display_db_error("unexpected - adding an invalid item or null quantity", "", true);
                }
@@ -76,13 +228,12 @@ class cart
        function update_cart_item($line_no, $qty, $price, $disc)
        {
 
-               if ($qty > 0)
-               {
-                       $this->line_items[$line_no]->quantity = $qty;
-               }
+               $this->line_items[$line_no]->quantity = $qty;
+               $this->line_items[$line_no]->qty_dispatched = $qty;
                $this->line_items[$line_no]->price = $price;
                $this->line_items[$line_no]->discount_percent = $disc;
        }
+
        function update_add_cart_item_qty($line_no, $qty)
        {
                $this->line_items[$line_no]->quantity += $qty;
@@ -90,12 +241,12 @@ class cart
 
        function remove_from_cart($line_no)
        {
-                       unset($this->line_items[$line_no]);
+               unset($this->line_items[$line_no]);
        }
 
        function clear_items()
        {
-       unset($this->line_items);
+               unset($this->line_items);
                $this->line_items = array();
                $this->default_sales_type = "";
                $this->trans_no = 0;
@@ -104,64 +255,50 @@ class cart
 
        function count_items()
        {
-         $counter=0;
-         foreach($this->line_items as $line) {
-               if($line->quantity>$line->qty_done) $counter++;
-         }
+               $counter=0;
+               foreach ($this->line_items as $line) {
+                       if ($line->quantity!=$line->qty_done) $counter++;
+               }
                return $counter;
        }
 
-       function get_items_total_dispatch($tax_group_id=null)
+       function get_items_total()
        {
                $total = 0;
 
-               // preload the taxgroup !
-               if ($tax_group_id != null)
-                       $tax_group_array = get_tax_group_items_as_array($tax_group_id);
-               else
-                       $tax_group_array = null;
-
-               foreach ($this->line_items as $ln_itm)
-               {
-                       $total += ($ln_itm->qty_dispatched * $ln_itm->taxfree_price($tax_group_id, $tax_group_array) * (1 - $ln_itm->discount_percent));
+               foreach ($this->line_items as $ln_itm) {
+                       $price = $ln_itm->line_price();
+                       $total += ($ln_itm->quantity * $price * (1 - $ln_itm->discount_percent));
                }
                return $total;
        }
 
-       function has_items_dispatch()
+       function get_items_total_dispatch()
        {
-               foreach ($this->line_items as $ln_itm)
-               {
-                       if ($ln_itm->qty_dispatched > 0)
-                               return true;
+               $total = 0;
+
+               foreach ($this->line_items as $ln_itm) {
+                       $price = $ln_itm->line_price();
+                       $total += ($ln_itm->qty_dispatched * $price * (1 - $ln_itm->discount_percent));
                }
-               return false;
+               return $total;
        }
 
-       function get_items_total($tax_group_id=null)
+       function has_items_dispatch()
        {
-               $total = 0;
-
-               // preload the taxgroup !
-               if ($tax_group_id != null)
-                       $tax_group_array = get_tax_group_items_as_array($tax_group_id);
-               else
-                       $tax_group_array = null;
-
                foreach ($this->line_items as $ln_itm) {
-                       $total += ($ln_itm->quantity * $ln_itm->taxfree_price($tax_group_id, $tax_group_array) * (1 - $ln_itm->discount_percent));
+                       if ($ln_itm->qty_dispatched > 0)
+                               return true;
                }
-               return $total;
+               return false;
        }
 
        function any_already_delivered()
        {
-               /* Checks if there have been deliveries of line items */
+               /* Checks if there have been any line item processed */
 
-               foreach ($this->line_items as $stock_item)
-               {
-                       if ($stock_item->qty_done !=0)
-                       {
+               foreach ($this->line_items as $stock_item) {
+                       if ($stock_item->qty_done !=0) {
                                return 1;
                        }
                }
@@ -173,42 +310,63 @@ class cart
        function some_already_delivered($line_no)
        {
                /* Checks if there have been deliveries of a specific line item */
-               if (isset($this->line_items[$line_no]) && 
-                       $this->line_items[$line_no]->qty_done != 0)
-               {
+               if (isset($this->line_items[$line_no]) &&
+                       $this->line_items[$line_no]->qty_done != 0) {
                        return 1;
                }
                return 0;
        }
 
-    function get_taxes($tax_group_id=null, $shipping_cost=0)
-    {
-       $items = array();
-       $prices = array();
+       function get_taxes($shipping_cost=null)
+       {
+               $items = array();
+               $prices = array();
+               if($shipping_cost==null)
+                       $shipping_cost = $this->freight_cost;
 
-        if ($tax_group_id == null)
-               $tax_group_id = $this->tax_group_id;
+               foreach ($this->line_items as $ln_itm) {
+                       $items[] = $ln_itm->stock_id;
+                       $prices[] = ($ln_itm->qty_dispatched *
+                               $ln_itm->line_price()* (1 - $ln_itm->discount_percent));
+               }
 
-               // preload the taxgroup !
-               $tax_group_array = get_tax_group_items_as_array($tax_group_id);
+               $taxes = get_tax_for_items($items, $prices, $shipping_cost,
+               $this->tax_group_id, $this->tax_included,  $this->tax_group_array);
 
-        foreach ($this->line_items as $ln_itm)
-        {
-                       $items[] = $ln_itm->stock_id;
-                       $prices[] = ($ln_itm->qty_dispatched * $ln_itm->taxfree_price($tax_group_id, $tax_group_array) * (1 - $ln_itm->discount_percent));
-        }
+               return $taxes;
+       }
 
 
-        $taxes = get_tax_for_items($items, $prices, $shipping_cost, $tax_group_id, $tax_group_array);
+       function get_tax_free_shipping() {
 
-        return $taxes;
-    }
+               if ($this->tax_included==0)
+                       return $this->freight_cost;
+               else
+                       return ($this->freight_cost - $this->get_shipping_tax());
+       }
+
+       function get_shipping_tax() {
+
+               $tax_items = get_shipping_tax_as_array();
+               $tax_rate = 0;
+               if ($tax_items != null) {
+                       foreach ($tax_items as $item_tax) {
+                               $index = $item_tax['tax_type_id'];
+                               if (isset($this->tax_group_array[$index])) {
+                                       $tax_rate += $item_tax['rate'];
+                               }
+                       }
+               }
+               if($this->tax_included)
+                       return $this->freight_cost*$tax_rate/($tax_rate+100);
+               else
+                       return $this->freight_cost*$tax_rate/100;
+       }
 
 } /* end of class defintion */
 
 class line_details
 {
-       var $line_no;
        var $id;
        var $stock_id;
        var $item_description;
@@ -216,20 +374,22 @@ class line_details
        var $mb_flag;
        var $tax_type;
        var $tax_type_name;
-
+       var $src_no;    // number of src doc for this line
        var $quantity;
        var $price;
        var $discount_percent;
-       var $qty_done;  // quantity processed so far
-       var $qty_dispatched; // quantity selected to process 
+       var $qty_done;  // quantity processed on child documents
+       var $qty_dispatched; // quantity selected to process
+       var $qty_old=0; // quantity dispatched before edition
        var $standard_cost;
 
-       function line_details ($stock_id, $qty, $prc, $disc_percent,  
-               $qty_done, $standard_cost, $description, $id=0)
+       function line_details ($stock_id, $qty, $prc, $disc_percent,
+               $qty_done, $standard_cost, $description, $id=0, $src_no=0 )
        {
        /* Constructor function to add a new LineDetail object with passed params */
 
                $this->id = $id;
+               $this->src_no = $src_no;
                $item_row = get_item($stock_id);
 
                if ($item_row == null)
@@ -247,23 +407,18 @@ class line_details
 
                $this->stock_id = $stock_id;
                $this->quantity = $qty;
+               $this->qty_dispatched = $qty;
                $this->price = $prc;
                $this->discount_percent = $disc_percent;
                $this->qty_done = $qty_done;
                $this->standard_cost = $standard_cost;
        }
 
-       function full_price()
+       // get unit price as stated on document
+       function line_price()
        {
                return $this->price;
        }
-
-       function taxfree_price($tax_group_id, $tax_group_array=null)
-       {
-               if ($tax_group_id==null)
-                       return $this->price;
-               return get_tax_free_price_for_item($this->stock_id, $this->price, $tax_group_id, $tax_group_array);
-       }
 }
 
 ?>
index e06231030df7027db27415800c5207ee760e3e0e..5e403c51c79de6858bdf1246c5e436b9fc340d1b 100644 (file)
 <?php
+//------------------------------------------------------------------------------
+//     Retreive parent document number(s) for given transaction
+//
+function get_parent_trans($trans_type, $trans_no) {
+
+       $sql = 'SELECT trans_link FROM
+                       '.TB_PREF.'debtor_trans WHERE
+                       (trans_no=' .$trans_no. ' AND type='.$trans_type.' AND trans_link!=0)';
+
+       $result = db_query($sql, 'Parent document numbers cannot be retrieved');
+
+       if (db_num_rows($result)) {
+               $link = db_fetch($result);
+               return array($link['trans_link']);
+       }
+       if ($trans_type!=10) return 0;  // this is credit note with no parent invoice
+       // invoice: find batch invoice parent trans.
+       $sql = 'SELECT trans_no FROM
+                       '.TB_PREF.'debtor_trans WHERE
+                       (trans_link='.$trans_no.' AND type='. get_parent_type($trans_type) .')';
+
+       $result = db_query($sql, 'Delivery links cannot be retrieved');
+
+       $delivery = array();
+       if(db_num_rows($result)>0) {
+               while($link = db_fetch($result)) {
+                       $delivery[] = $link['trans_no'];
+               }
+       }
+       return count($delivery) ? $delivery : 0;
+}
 
 //----------------------------------------------------------------------------------------
+// Mark changes in debtor_trans_details
+//
+function update_customer_trans_version($type, $versions) {
+
+       $sql= 'UPDATE '.TB_PREF. 'debtor_trans SET version=version+1
+                       WHERE type='.$type. ' AND (';
+
+       foreach ($versions as $trans_no=>$version)
+               $where[] =      '(trans_no='.$trans_no.
+                       ' AND version='.$version.')';
+
+               $sql .= implode(' OR ', $where) .')';
+
+       return  db_query($sql, 'Concurrent editing conflict');
+}
+
+//----------------------------------------------------------------------------------------
+// Gets document header versions for transaction set of type $type
+// $trans_no = array(num1, num2,...);
+// returns array(num1=>ver1, num2=>ver2...)
+//
+function get_customer_trans_version($type, $trans_no) {
+       if (!is_array($trans_no))
+               $trans_no = array( $trans_no );
+
+       $sql= 'SELECT trans_no, version FROM '.TB_PREF. 'debtor_trans
+                       WHERE type='.$type.' AND (';
 
+       foreach ($trans_no as $key=>$trans)
+               $trans_no[$key] =       'trans_no='.$trans_no[$key];
+
+       $sql .= implode(' OR ', $trans_no) . ')';
+
+       $res = db_query($sql, 'document version retreival');
+
+       $vers = array();
+       while($mysql=db_fetch($res)) {
+               $vers[$mysql['trans_no']] = $mysql['version'];
+       }
+       return $vers;
+}
+//----------------------------------------------------------------------------------------
 // $Total, $Tax, $Freight, $discount all in customer's currency
 // date_ is display date (non-sql)
-
-function add_customer_trans($trans_type, $debtor_no, $BranchNo, 
-       $date_, $reference, $Total, $discount=0, $Tax=0, $Freight=0, 
-       $sales_type=0, $order_no=0, $trans_link=0, $ship_via="", $due_date=null,  
+function write_customer_trans($trans_type, $trans_no, $debtor_no, $BranchNo,
+       $date_, $reference, $Total, $discount=0, $Tax=0, $Freight=0, $FreightTax=0,
+       $sales_type=0, $order_no=0, $trans_link=0, $ship_via="", $due_date=null,
        $AllocAmt=0)
 {
-       $trans_no = get_next_trans_no($trans_type);
-       
+
        $curr = get_customer_currency($debtor_no);
-       $rate = get_exchange_rate_from_home_currency($curr, $date_);    
+       $rate = get_exchange_rate_from_home_currency($curr, $date_);
 
        $SQLDate = date2sql($date_);
        $SQLDueDate = date2sql($due_date);
 
+       if ($trans_no==0) {
+       $trans_no = get_next_trans_no($trans_type);
+
        $sql = "INSERT INTO ".TB_PREF."debtor_trans (
-               trans_no, type, 
-               debtor_no, branch_code, 
-               tran_date, due_date, 
-               reference, tpe, 
+               trans_no, type,
+               debtor_no, branch_code,
+               tran_date, due_date,
+               reference, tpe,
                order_, ov_amount, ov_discount,
-               ov_gst, ov_freight, rate,
-               ship_via, alloc, trans_link
+               ov_gst, ov_freight, ov_freight_tax,
+               rate, ship_via, alloc, trans_link
                ) VALUES ($trans_no, $trans_type, '$debtor_no', '$BranchNo',
                '$SQLDate', '$SQLDueDate', '$reference',
-               '$sales_type', $order_no, $Total, $discount, $Tax, $Freight, $rate, 
-               '$ship_via', $AllocAmt, $trans_link)";
-
+               '$sales_type', $order_no, $Total, $discount, $Tax, $Freight,
+               $FreightTax, $rate, '$ship_via', $AllocAmt, $trans_link)";
+       } else {        // may be optional argument should stay unchanged ?
+       $sql = "UPDATE ".TB_PREF."debtor_trans SET
+               debtor_no='$debtor_no' , branch_code='$BranchNo',
+               tran_date='$SQLDate', due_date='$SQLDueDate',
+               reference='$reference', tpe='$sales_type', order_=$order_no,
+               ov_amount=$Total, ov_discount=$discount, ov_gst=$Tax,
+               ov_freight=$Freight, ov_freight_tax=$FreightTax, rate=$rate,
+               ship_via='$ship_via', alloc=$AllocAmt, trans_link=$trans_link
+               WHERE trans_no=$trans_no AND type=$trans_type";
+       }
        db_query($sql, "The debtor transaction record could not be inserted");
-       
-       return $trans_no;       
+
+       return $trans_no;
 }
 
 //----------------------------------------------------------------------------------------
@@ -41,74 +123,74 @@ function add_customer_trans($trans_type, $debtor_no, $BranchNo,
 function get_customer_trans($trans_id, $trans_type)
 {
        $sql = "SELECT ".TB_PREF."debtor_trans.*,
-               ov_amount+ov_gst+ov_freight+ov_discount AS Total,   
-               ".TB_PREF."debtors_master.name AS DebtorName, ".TB_PREF."debtors_master.address, ".TB_PREF."debtors_master.email, 
+               ov_amount+ov_gst+ov_freight+ov_freight_tax+ov_discount AS Total,
+               ".TB_PREF."debtors_master.name AS DebtorName, ".TB_PREF."debtors_master.address, ".TB_PREF."debtors_master.email,
                ".TB_PREF."debtors_master.curr_code, ".TB_PREF."debtors_master.tax_id, ".TB_PREF."debtors_master.payment_terms ";
-       
-       if ($trans_type == systypes::cust_payment()) 
-       {
+
+       if ($trans_type == systypes::cust_payment()) {
                // it's a payment so also get the bank account
                $sql .= ", ".TB_PREF."bank_accounts.bank_name, ".TB_PREF."bank_accounts.bank_account_name,
-                       ".TB_PREF."bank_trans_types.name AS BankTransType ";  
-       }  
-       
-       if ($trans_type == 10 OR $trans_type == 11 OR $trans_type == 13) 
-       {
+                       ".TB_PREF."bank_trans_types.name AS BankTransType ";
+       }
+
+       if ($trans_type == 10 OR $trans_type == 11 OR $trans_type == 13) {
                // it's an invoice so also get the shipper and salestype
-               $sql .= ", ".TB_PREF."shippers.shipper_name, ".TB_PREF."sales_types.sales_type ";  
-       }       
-       
-       
-       $sql .= " FROM ".TB_PREF."debtor_trans, ".TB_PREF."debtors_master "; 
-
-       if ($trans_type == systypes::cust_payment()) 
-       {
+               $sql .= ", ".TB_PREF."shippers.shipper_name, "
+               .TB_PREF."sales_types.sales_type, "
+               .TB_PREF."sales_types.tax_included, "
+               .TB_PREF."cust_branch.*, "
+               .TB_PREF."debtors_master.discount, "
+               .TB_PREF."tax_groups.name AS tax_group_name, "
+               .TB_PREF."tax_groups.id AS tax_group_id ";
+       }
+
+
+       $sql .= " FROM ".TB_PREF."debtor_trans, ".TB_PREF."debtors_master ";
+
+       if ($trans_type == systypes::cust_payment()) {
                // it's a payment so also get the bank account
-               $sql .= ", ".TB_PREF."bank_trans, ".TB_PREF."bank_accounts, ".TB_PREF."bank_trans_types ";  
-       }       
-       
-       if ($trans_type == 10 OR $trans_type == 11 OR $trans_type == 13) 
-       {
+               $sql .= ", ".TB_PREF."bank_trans, ".TB_PREF."bank_accounts, ".TB_PREF."bank_trans_types ";
+       }
+
+       if ($trans_type == 10 OR $trans_type == 11 OR $trans_type == 13) {
                // it's an invoice so also get the shipper, salestypes
-               $sql .= ", ".TB_PREF."shippers, ".TB_PREF."sales_types ";  
-       }               
-       
-       $sql .= " WHERE ".TB_PREF."debtor_trans.trans_no=$trans_id 
+               $sql .= ", ".TB_PREF."shippers, ".TB_PREF."sales_types, ".TB_PREF."cust_branch, ".TB_PREF."tax_groups ";
+       }
+
+       $sql .= " WHERE ".TB_PREF."debtor_trans.trans_no=$trans_id
                AND ".TB_PREF."debtor_trans.type=$trans_type
                AND ".TB_PREF."debtor_trans.debtor_no=".TB_PREF."debtors_master.debtor_no";
-                                       
-       if ($trans_type == systypes::cust_payment()) 
-       {
+
+       if ($trans_type == systypes::cust_payment()) {
                // it's a payment so also get the bank account
                $sql .= " AND ".TB_PREF."bank_trans.trans_no =$trans_id
-                       AND ".TB_PREF."bank_trans.type=$trans_type      
+                       AND ".TB_PREF."bank_trans.type=$trans_type
                        AND ".TB_PREF."bank_trans_types.id = ".TB_PREF."bank_trans.bank_trans_type_id
-                       AND ".TB_PREF."bank_accounts.account_code=".TB_PREF."bank_trans.bank_act ";  
-       }                       
-       if ($trans_type == 10 OR $trans_type == 11 OR $trans_type == 13) 
-       {
+                       AND ".TB_PREF."bank_accounts.account_code=".TB_PREF."bank_trans.bank_act ";
+       }
+       if ($trans_type == 10 OR $trans_type == 11 OR $trans_type == 13) {
                // it's an invoice so also get the shipper
-               $sql .= " AND ".TB_PREF."shippers.shipper_id=".TB_PREF."debtor_trans.ship_via 
-                       AND ".TB_PREF."sales_types.id = ".TB_PREF."debtor_trans.tpe ";  
-       }                                       
-       
-       $result = db_query($sql, "Cannot retreive a debtor transaction");       
-       
-    if (db_num_rows($result) == 0) 
-    {
-       // can't return nothing
-       display_db_error("no debtor trans found for given params", $sql, true);
-       exit;
-    }
-    
-    if (db_num_rows($result) > 1) 
-    {
-       // can't return multiple
-       display_db_error("duplicate debtor transactions found for given params", $sql, true);
-       exit;
-    }  
-    
-    return db_fetch($result);          
+               $sql .= " AND ".TB_PREF."shippers.shipper_id=".TB_PREF."debtor_trans.ship_via
+                       AND ".TB_PREF."sales_types.id = ".TB_PREF."debtor_trans.tpe
+                       AND ".TB_PREF."cust_branch.branch_code = ".TB_PREF."debtor_trans.branch_code
+                       AND ".TB_PREF."cust_branch.tax_group_id = ".TB_PREF."tax_groups.id ";
+       }
+
+       $result = db_query($sql, "Cannot retreive a debtor transaction");
+
+       if (db_num_rows($result) == 0) {
+               // can't return nothing
+               display_db_error("no debtor trans found for given params", $sql, true);
+               exit;
+       }
+
+       if (db_num_rows($result) > 1) {
+               // can't return multiple
+               display_db_error("duplicate debtor transactions found for given params", $sql, true);
+               exit;
+       }
+
+       return db_fetch($result);
 }
 
 //----------------------------------------------------------------------------------------
@@ -116,24 +198,24 @@ function get_customer_trans($trans_id, $trans_type)
 function get_customer_transactions($extra_fields=null, $extra_conditions=null, $extra_tables=null)
 {
        $sql = "SELECT ".TB_PREF."debtor_trans.*,
-               ov_amount+ov_gst+ov_freight+ov_discount AS Total,   
+               ov_amount+ov_gst+ov_freight+ov_freight_tax+ov_discount AS Total,
                ".TB_PREF."debtors_master.name AS DebtorName, ".TB_PREF."debtors_master.address,
-               ".TB_PREF."debtors_master.curr_code ";
-                               
+               ".TB_PREF."debtors_master.curr_code, ".TB_PREF."debtor_trans.version ";
+
        if ($extra_fields)
-               $sql .= ", $extra_fields ";                     
-                               
+               $sql .= ", $extra_fields ";
+
        $sql .= " FROM ".TB_PREF."debtor_trans, ".TB_PREF."debtors_master ";
        if ($extra_tables)
                $sql .= ",$extra_tables ";
-                               
+
        $sql .= " WHERE ".TB_PREF."debtor_trans.debtor_no=".TB_PREF."debtors_master.debtor_no";
-                               
+
        if ($extra_conditions)
-               $sql .= " AND $extra_conditions ";      
-               
-       $sql .= " ORDER BY trans_no";   
-       
+               $sql .= " AND $extra_conditions ";
+
+       $sql .= " ORDER BY trans_no";
+
        return db_query($sql, "Cannot retreive debtor transactions");
 }
 
@@ -143,9 +225,10 @@ function exists_customer_trans($type, $type_no)
 {
        $sql = "SELECT trans_no FROM ".TB_PREF."debtor_trans WHERE type=$type
                AND trans_no=$type_no";
-       $result = db_query($sql, "Cannot retreive a debtor transaction");       
-       
-    return (db_num_rows($result) > 0);                         
+
+       $result = db_query($sql, "Cannot retreive a debtor transaction");
+
+       return (db_num_rows($result) > 0);
 }
 
 //----------------------------------------------------------------------------------------
@@ -155,26 +238,26 @@ function exists_customer_trans($type, $type_no)
 function get_customer_trans_order($type, $type_no)
 {
        $sql = "SELECT order_ FROM ".TB_PREF."debtor_trans WHERE type=$type AND trans_no=$type_no";
-       
+
        $result = db_query($sql, "The debtor transaction could not be queried");
-       
+
        $row = db_fetch_row($result);
-       
-       return $row[0]; 
+
+       return $row[0];
 }
 
 //----------------------------------------------------------------------------------------
 
 function get_customer_details_from_trans($type, $type_no)
 {
-       $sql = "SELECT ".TB_PREF."debtors_master.name, ".TB_PREF."debtors_master.curr_code, ".TB_PREF."cust_branch.br_name  
-               FROM ".TB_PREF."debtors_master,".TB_PREF."cust_branch,".TB_PREF."debtor_trans 
+       $sql = "SELECT ".TB_PREF."debtors_master.name, ".TB_PREF."debtors_master.curr_code, ".TB_PREF."cust_branch.br_name
+               FROM ".TB_PREF."debtors_master,".TB_PREF."cust_branch,".TB_PREF."debtor_trans
                WHERE ".TB_PREF."debtor_trans.type=$type AND ".TB_PREF."debtor_trans.trans_no=$type_no
-               AND ".TB_PREF."debtors_master.debtor_no = ".TB_PREF."debtor_trans.debtor_no 
+               AND ".TB_PREF."debtors_master.debtor_no = ".TB_PREF."debtor_trans.debtor_no
                AND     ".TB_PREF."cust_branch.branch_code = ".TB_PREF."debtor_trans.branch_code";
-       
+
        $result = db_query($sql, "could not get customer details from trans");
-       return db_fetch($result);                               
+       return db_fetch($result);
 }
 
 //----------------------------------------------------------------------------------------
@@ -182,9 +265,9 @@ function get_customer_details_from_trans($type, $type_no)
 function void_customer_trans($type, $type_no)
 {
        // clear all values and mark as void
-       $sql = "UPDATE ".TB_PREF."debtor_trans SET ov_amount=0, ov_discount=0, ov_gst=0, ov_freight=0, 
-               alloc=0 WHERE type=$type AND trans_no=$type_no";
-                       
+       $sql = "UPDATE ".TB_PREF."debtor_trans SET ov_amount=0, ov_discount=0, ov_gst=0, ov_freight=0,
+               ov_freight_tax=0, alloc=0, version=version+1 WHERE type=$type AND trans_no=$type_no";
+
        db_query($sql, "could not void debtor transactions for type=$type and trans_no=$type_no");
 }
 
@@ -192,8 +275,7 @@ function void_customer_trans($type, $type_no)
 
 function post_void_customer_trans($type, $type_no)
 {
-       switch ($type)
-       {
+       switch ($type) {
                case 10 :
                case 11 :
                        void_sales_invoice($type, $type_no);
@@ -201,7 +283,7 @@ function post_void_customer_trans($type, $type_no)
                case 13 :
                        void_sales_delivery($type, $type_no);
                        break;
-               case systypes::cust_payment() :
+               case 12 :
                        void_customer_payment($type, $type_no);
                        break;
        }
@@ -211,9 +293,10 @@ function post_void_customer_trans($type, $type_no)
 
 function get_customer_trans_link($type, $type_no)
 {
-  $row = db_query("SELECT trans_link from debtor_trans 
-       WHERE type=$type AND trans_no=$type_no", "could not get transaction link for type=$type and trans_no=$type_no");
- return $row[0];
+       $row = db_query("SELECT trans_link from ".TB_PREF."debtor_trans
+               WHERE type=$type AND trans_no=$type_no",
+               "could not get transaction link for type=$type and trans_no=$type_no");
+       return $row[0];
 }
 //----------------------------------------------------------------------------------------
 
index c3e021bc769e15844de9092b94887759392c2f9f..ebe79a56461cfbf27a88c18a96d577791dbbaa97 100644 (file)
@@ -2,28 +2,28 @@
 
 //----------------------------------------------------------------------------------------
 
-function add_customer_trans_detail_item_base($debtor_trans_type, $debtor_trans_no, $stock_id, $description, $quantity,
-       $unit_price, $unit_tax, $discount_percent, $standard_cost)
-{
-       $sql = "INSERT INTO ".TB_PREF."debtor_trans_details (debtor_trans_no, debtor_trans_type, stock_id, description, quantity, unit_price, unit_tax, discount_percent, standard_cost)
-               VALUES ($debtor_trans_no, $debtor_trans_type, '$stock_id', '$description', $quantity, $unit_price, $unit_tax, $discount_percent, $standard_cost)";
-
-       db_query($sql, "The debtor transaction detail could not be added");
-}
-
-//----------------------------------------------------------------------------------------
-
 function get_customer_trans_details($debtor_trans_type, $debtor_trans_no)
 {
-       $sql = "SELECT ".TB_PREF."debtor_trans_details.*, ".TB_PREF."debtor_trans_details.unit_price+".TB_PREF."debtor_trans_details.unit_tax AS FullUnitPrice,
+if (!is_array($debtor_trans_no))
+       $debtor_trans_no = array( 0=>$debtor_trans_no );
+
+       $sql = "SELECT ".TB_PREF."debtor_trans_details.*,
+               ".TB_PREF."debtor_trans_details.unit_price+".TB_PREF."debtor_trans_details.unit_tax AS FullUnitPrice,
                ".TB_PREF."debtor_trans_details.description As StockDescription,
                ".TB_PREF."stock_master.units
                FROM ".TB_PREF."debtor_trans_details,".TB_PREF."stock_master
-               WHERE debtor_trans_no=$debtor_trans_no
-               AND debtor_trans_type=$debtor_trans_type 
+               WHERE (";
+
+       $tr=array();
+       foreach ($debtor_trans_no as $trans_no)
+               $tr[] = 'debtor_trans_no='.$trans_no;
+
+       $sql .= implode(' OR ', $tr);
+
+
+       $sql.=  ") AND debtor_trans_type=$debtor_trans_type
                AND ".TB_PREF."stock_master.stock_id=".TB_PREF."debtor_trans_details.stock_id
                ORDER BY id";
-
        return db_query($sql, "The debtor transaction detail could not be queried");
 }
 
@@ -41,41 +41,6 @@ function void_customer_trans_details($type, $type_no)
        // clear the stock move items
        void_stock_move($type, $type_no);
 }
-
-//----------------------------------------------------------------------------------------
-
-function add_customer_trans_detail_item($debtor_trans_type, $debtor_trans_no, $stock_id, $description,
-       $Location, $date_, $quantity, $unit_price, $unit_tax, $discount_percent,
-       $reference, $std_cost)
-{
-       add_customer_trans_detail_item_base($debtor_trans_type, $debtor_trans_no, $stock_id, $description,
-               $quantity, $unit_price, $unit_tax, $discount_percent, $std_cost);
-
-    if($debtor_trans_type==13)
-       add_stock_move_customer($debtor_trans_type, $stock_id, $debtor_trans_no, $Location,
-               $date_, $reference, $quantity, $std_cost, 1, $unit_price+$unit_tax, $discount_percent);
-
-       return $std_cost;
-}
-
-//----------------------------------------------------------------------------------------
-
-function add_customer_trans_detail_item_writeoff($debtor_trans_type, $debtor_trans_no, $stock_id, $description,
-       $Location, $date_, $quantity, $unit_price, $unit_tax, $discount_percent,
-       $reference, $std_cost)
-{
-       $retCost = add_customer_trans_detail_item($debtor_trans_type, $debtor_trans_no, $stock_id, $description,
-               $Location, $date_, $quantity, $unit_price, $unit_tax, $discount_percent,
-               $reference,     $std_cost);
-
-       $reference = _("Write off") . " " . $reference;
-
-       add_stock_move_customer($debtor_trans_type, $stock_id, $debtor_trans_no, $Location,
-               $date_, $reference, -$quantity, $std_cost, 0, $unit_price+$unit_tax, $discount_percent);
-
-       return $retCost;
-}
-
 //----------------------------------------------------------------------------------------
 
 function add_customer_trans_tax_detail_item($debtor_trans_type, $debtor_trans_no,
@@ -95,6 +60,7 @@ function get_customer_trans_tax_details($debtor_trans_type, $debtor_trans_no)
                FROM ".TB_PREF."debtor_trans_tax_details,".TB_PREF."tax_types
                WHERE debtor_trans_no=$debtor_trans_no
                AND debtor_trans_type=$debtor_trans_type
+               AND amount != 0
                AND ".TB_PREF."tax_types.id = ".TB_PREF."debtor_trans_tax_details.tax_type_id";
 
        return db_query($sql, "The debtor transaction tax details could not be queried");
@@ -113,4 +79,27 @@ function void_customer_trans_tax_details($type, $type_no)
 
 //----------------------------------------------------------------------------------------
 
+function write_customer_trans_detail_item($debtor_trans_type, $debtor_trans_no, $stock_id, $description,
+       $quantity, $unit_price, $unit_tax, $discount_percent, $std_cost, $line_id=0)
+{
+       if ($line_id!=0)
+               $sql = "UPDATE ".TB_PREF."debtor_trans_details SET
+                       stock_id='$stock_id',
+                       description='$description',
+                       quantity=$quantity,
+                       unit_price=$unit_price,
+                       unit_tax=$unit_tax,
+                       discount_percent=$discount_percent,
+                       standard_cost=$std_cost WHERE
+                       id=$line_id";
+       else
+                       $sql = "INSERT INTO ".TB_PREF."debtor_trans_details (debtor_trans_no,
+                               debtor_trans_type, stock_id, description, quantity, unit_price,
+                               unit_tax, discount_percent, standard_cost)
+                       VALUES ($debtor_trans_no, $debtor_trans_type, '$stock_id', '$description',
+                               $quantity, $unit_price, $unit_tax, $discount_percent, $std_cost)";
+
+       db_query($sql, "The debtor transaction detail could not be written");
+}
+
 ?>
\ No newline at end of file
index 0a1c78f251123cfdfcb7c0e62d90f0be3dd43d42..88e867459cad62b09bdf404c6563012066b0f5fe 100644 (file)
@@ -26,7 +26,8 @@ function delete_cust_allocation($trans_id)
 
 function get_DebtorTrans_allocation_balance($trans_type, $trans_no)
 {
-       $sql = "SELECT (ov_amount+ov_gst+ov_freight-ov_discount-alloc) AS BalToAllocate 
+       
+       $sql = "SELECT (ov_amount+ov_gst+ov_freight+ov_freight_tax-ov_discount-alloc) AS BalToAllocate 
                FROM ".TB_PREF."debtor_trans WHERE trans_no=$trans_no AND type=$trans_type";
        $result = db_query($sql,"calculate the allocation");
        $myrow = db_fetch_row($result); 
@@ -84,15 +85,14 @@ function get_allocatable_from_cust_transactions($customer_id, $settled)
        $settled_sql = "";
        if (!$settled) 
        {
-               $settled_sql = " AND round(ABS(ov_amount+ov_gst+ov_freight+ov_discount)-alloc,6) > 0";
+               $settled_sql = " AND (round(ov_amount+ov_gst+ov_freight+ov_freight_tax-ov_discount-alloc,6) > 0)";
        }
-       
        $cust_sql = "";
        if ($customer_id != null)
-               $cust_sql = " AND ".TB_PREF."debtor_trans.debtor_no = $customer_id";            
+               $cust_sql = " AND ".TB_PREF."debtor_trans.debtor_no = $customer_id";
        
-       return get_customer_transactions("round(ABS(ov_amount+ov_gst+ov_freight+ov_discount)-alloc,6) <= 0 AS settled", 
-               "(type=" . systypes::cust_payment(). " OR type=11 OR type=2) AND (".TB_PREF."debtor_trans.ov_amount < 0) " . $settled_sql . $cust_sql); 
+       return get_customer_transactions("round(ov_amount+ov_gst+ov_freight+ov_freight_tax+ov_discount-alloc,6) <= 0 AS settled", 
+               "(type=12 OR type=11) AND (".TB_PREF."debtor_trans.ov_amount > 0) " . $settled_sql . $cust_sql);        
 }
 
 //-------------------------------------------------------------------------------------------------------------
@@ -110,8 +110,9 @@ function get_allocatable_to_cust_transactions($customer_id, $trans_no=null, $typ
        } 
        else 
        {
-               return get_customer_transactions(null, "round(ABS(ov_amount+ov_gst+ov_freight+ov_discount)-alloc,6) > 0
+               return get_customer_transactions(null, "round(ov_amount+ov_gst+ov_freight+ov_freight_tax+ov_discount-alloc,6) > 0
                        AND ".TB_PREF."debtor_trans.type != " . systypes::cust_payment() . "
+                       AND ".TB_PREF."debtor_trans.type != 13
                        AND ".TB_PREF."debtor_trans.debtor_no=$customer_id");
        }                                                                                                                       
 }
index 9915071af55141309745d5d30bd4930e2141dbab..012aff3ed79d42de3a50fc9fba0c22bade60720f 100644 (file)
@@ -10,25 +10,31 @@ function get_customer_details($customer_id, $to=null)
        $past1 = get_company_pref('past_due_days');
        $past2 = 2 * $past1;
        // removed - debtor_trans.alloc from all summations
+
+    $value = "IF(".TB_PREF."debtor_trans.type=11 OR ".TB_PREF."debtor_trans.type=12,
+       -1, 1) *". 
+      "(".TB_PREF."debtor_trans.ov_amount + ".TB_PREF."debtor_trans.ov_gst + "
+               .TB_PREF."debtor_trans.ov_freight + ".TB_PREF."debtor_trans.ov_freight_tax + "
+               .TB_PREF."debtor_trans.ov_discount)";
        
     $sql = "SELECT ".TB_PREF."debtors_master.name, ".TB_PREF."debtors_master.curr_code, ".TB_PREF."payment_terms.terms,
                ".TB_PREF."debtors_master.credit_limit, ".TB_PREF."credit_status.dissallow_invoices, ".TB_PREF."credit_status.reason_description,
 
-               Sum(".TB_PREF."debtor_trans.ov_amount + ".TB_PREF."debtor_trans.ov_gst + ".TB_PREF."debtor_trans.ov_freight + ".TB_PREF."debtor_trans.ov_discount) AS Balance,
+               Sum(".$value.") AS Balance,
 
                Sum(IF (".TB_PREF."payment_terms.days_before_due > 0,
                        CASE WHEN (TO_DAYS('$todate') - TO_DAYS(".TB_PREF."debtor_trans.tran_date)) >= ".TB_PREF."payment_terms.days_before_due 
                        THEN 
-                               ".TB_PREF."debtor_trans.ov_amount + ".TB_PREF."debtor_trans.ov_gst + ".TB_PREF."debtor_trans.ov_freight + ".TB_PREF."debtor_trans.ov_discount
-                       ELSE 0 END,
+                           $value
+                       ELSE 0 
+                       END,
 
                        CASE WHEN TO_DAYS('$todate') - TO_DAYS(DATE_ADD(DATE_ADD(".TB_PREF."debtor_trans.tran_date,
                                INTERVAL 1 MONTH), INTERVAL (".TB_PREF."payment_terms.day_in_following_month -
                                DAYOFMONTH(".TB_PREF."debtor_trans.tran_date)) DAY)) >= 0 
                        THEN 
-                               ".TB_PREF."debtor_trans.ov_amount + ".TB_PREF."debtor_trans.ov_gst + ".TB_PREF."debtor_trans.ov_freight + ".TB_PREF."debtor_trans.ov_discount 
-                       ELSE 
-                               0 
+                           $value
+                       ELSE 0 
                        END
 
                )) AS Due,
@@ -37,7 +43,7 @@ function get_customer_details($customer_id, $to=null)
                        CASE WHEN TO_DAYS('$todate') - TO_DAYS(".TB_PREF."debtor_trans.tran_date) > ".TB_PREF."payment_terms.days_before_due
                                AND TO_DAYS('$todate') - TO_DAYS(".TB_PREF."debtor_trans.tran_date) >= (".TB_PREF."payment_terms.days_before_due + $past1) 
                        THEN 
-                               ".TB_PREF."debtor_trans.ov_amount + ".TB_PREF."debtor_trans.ov_gst + ".TB_PREF."debtor_trans.ov_freight + ".TB_PREF."debtor_trans.ov_discount 
+                               $value
                        ELSE 
                                0 
                        END,
@@ -46,7 +52,7 @@ function get_customer_details($customer_id, $to=null)
                                INTERVAL 1  MONTH), INTERVAL (".TB_PREF."payment_terms.day_in_following_month -
                                DAYOFMONTH(".TB_PREF."debtor_trans.tran_date)) DAY)) >= $past1) 
                        THEN 
-                               ".TB_PREF."debtor_trans.ov_amount + ".TB_PREF."debtor_trans.ov_gst + ".TB_PREF."debtor_trans.ov_freight + ".TB_PREF."debtor_trans.ov_discount
+                               $value
                        ELSE 
                                0 
                        END
@@ -57,7 +63,7 @@ function get_customer_details($customer_id, $to=null)
                        CASE WHEN TO_DAYS('$todate') - TO_DAYS(".TB_PREF."debtor_trans.tran_date) > ".TB_PREF."payment_terms.days_before_due
                                AND TO_DAYS('$todate') - TO_DAYS(".TB_PREF."debtor_trans.tran_date) >= (".TB_PREF."payment_terms.days_before_due + $past2) 
                        THEN 
-                               ".TB_PREF."debtor_trans.ov_amount + ".TB_PREF."debtor_trans.ov_gst + ".TB_PREF."debtor_trans.ov_freight + ".TB_PREF."debtor_trans.ov_discount 
+                           $value
                        ELSE 
                                0 
                        END,
@@ -66,7 +72,7 @@ function get_customer_details($customer_id, $to=null)
                                INTERVAL 1  MONTH), INTERVAL (".TB_PREF."payment_terms.day_in_following_month - 
                                DAYOFMONTH(".TB_PREF."debtor_trans.tran_date)) DAY)) >= $past2) 
                        THEN 
-                               ".TB_PREF."debtor_trans.ov_amount + ".TB_PREF."debtor_trans.ov_gst + ".TB_PREF."debtor_trans.ov_freight + ".TB_PREF."debtor_trans.ov_discount
+                               $value
                        ELSE 
                                0 
                        END
@@ -83,6 +89,7 @@ function get_customer_details($customer_id, $to=null)
                         AND ".TB_PREF."debtors_master.credit_status = ".TB_PREF."credit_status.id
                         AND ".TB_PREF."debtors_master.debtor_no = $customer_id
                         AND ".TB_PREF."debtor_trans.tran_date <= '$todate'
+                        AND ".TB_PREF."debtor_trans.type <> 13
                         AND ".TB_PREF."debtors_master.debtor_no = ".TB_PREF."debtor_trans.debtor_no
 
                GROUP BY
@@ -95,7 +102,7 @@ function get_customer_details($customer_id, $to=null)
                          ".TB_PREF."credit_status.reason_description";
     
     $result = db_query($sql,"The customer details could not be retrieved");
-    
+
     if (db_num_rows($result) == 0)
     {
     
index b5755857280fc36b16fd6dc58459b52db0b43937..5197a9965064e2a2f9c1f2be240c7ba5bdbe88e9 100644 (file)
@@ -1,63 +1,66 @@
 <?php
-
-function add_customer_payment($customer_id, $branch_id, $bank_account, $date_, $receipt_type, $ref, 
-       $amount, $discount, $memo_)
+/*
+  Write/update customer payment.
+*/
+function write_customer_payment($trans_no, $customer_id, $branch_id, $bank_account,
+       $date_, $receipt_type, $ref, $amount, $discount, $memo_)
 {
        begin_transaction();
-   
+
        $company_record = get_company_prefs();
-   
-       $payment_no = add_customer_trans(systypes::cust_payment(), $customer_id, $branch_id, $date_, 
-       $ref, -($amount), -($discount));                        
-               
+
+       $payment_no = write_customer_trans(12, $trans_no,
+           $customer_id, $branch_id, $date_, $ref, $amount, $discount);
+
+       if ($trans_no != 0) {
+         delete_comments(12, $invoice_no);
+         void_bank_trans(12, $type_no, true);
+         void_gl_trans(12, $trans_no, true);
+         void_cust_allocations(12, $trans_no);
+       }
+
        /* Bank account entry first */
-       add_gl_trans_customer(systypes::cust_payment(), $payment_no, $date_, 
+       add_gl_trans_customer(12, $payment_no, $date_,
                $bank_account, 0, 0, $amount,  $customer_id,
                "Cannot insert a GL transaction for the bank account debit");
-                                                       
-       if ($branch_id != reserved_words::get_any_numeric()) 
-       {
+
+       if ($branch_id != reserved_words::get_any_numeric()) {
+
                $branch_data = get_branch_accounts($branch_id);
 
                $debtors_account = $branch_data["receivables_account"];
-               $discount_account = $branch_data["payment_discount_account"];           
-               
-       } 
-       else 
-       {
+               $discount_account = $branch_data["payment_discount_account"];
+
+       } else {
                $debtors_account = $company_record["debtors_act"];
                $discount_account = $company_record["default_prompt_payment_act"];
        }
-       
-       if (($discount + $amount) != 0)
-       {
+
+       if (($discount + $amount) != 0) {
                /* Now Credit Debtors account with receipts + discounts */
-               add_gl_trans_customer(systypes::cust_payment(), $payment_no, $date_, 
+               add_gl_trans_customer(12, $payment_no, $date_,
                        $debtors_account, 0, 0, -($discount + $amount), $customer_id,
-                       "Cannot insert a GL transaction for the debtors account credit");               
-       }       
-       
-       if ($discount != 0)
-       {
+                       "Cannot insert a GL transaction for the debtors account credit");
+       }
+
+       if ($discount != 0)     {
                /* Now Debit discount account with discounts allowed*/
-               add_gl_trans_customer(systypes::cust_payment(), $payment_no, $date_, 
+               add_gl_trans_customer(12, $payment_no, $date_,
                        $discount_account, 0, 0, $discount, $customer_id,
                        "Cannot insert a GL transaction for the payment discount debit");
        }
-       
+
        /*now enter the bank_trans entry */
-       add_bank_trans(systypes::cust_payment(), $payment_no, $bank_account, $ref, 
+       add_bank_trans(12, $payment_no, $bank_account, $ref,
                $date_, $receipt_type, $amount, payment_person_types::customer(), $customer_id,
-               get_customer_currency($customer_id));    
-                                               
-       add_comments(systypes::cust_payment(), $payment_no, $date_, $memo_);                                            
-                                               
-       add_forms_for_sys_type(systypes::cust_payment(), $payment_no, payment_person_types::customer(), $customer_id);  
-       
-       references::save_last($ref, systypes::cust_payment());                                    
+               get_customer_currency($customer_id));
+
+       add_comments(12, $payment_no, $date_, $memo_);
+
+       references::save_last($ref, 12);
 
        commit_transaction();
-       
+
        return $payment_no;
 }
 
@@ -66,13 +69,13 @@ function add_customer_payment($customer_id, $branch_id, $bank_account, $date_, $
 function void_customer_payment($type, $type_no)
 {
        begin_transaction();
-       
+
        void_bank_trans($type, $type_no, true);
        void_gl_trans($type, $type_no, true);
        void_cust_allocations($type, $type_no);
        void_customer_trans($type, $type_no);
-       
-       commit_transaction();                   
+
+       commit_transaction();
 }
 
 
index e0951cb6bdaada8bf8e6685e3f42b77cb601ebed..f5d66505b42ee6c403c2cd468da2725bb8b08fd9 100644 (file)
 <?php
 
 //----------------------------------------------------------------------------------------
-
-function add_credit_note($credit_items, $credit_date, $credit_type, $tax_group_id,
-       $charge_freight, $sales_type, $shipper, $reference, $memo_, $write_off_gl_code)
+// if ($writeoff_acc==0) return goods into $cart->Location
+// if src_docs!=0 => credit invoice else credit note
+//
+function write_credit_note($credit_note, $write_off_acc)
 {
-       begin_transaction();
-
-       $branch_data = get_branch_accounts($credit_items->Branch);
-
-       $credit_items_total = $credit_items->get_items_total($tax_group_id);
-
-    $tax_total = 0;
-    $taxes = $credit_items->get_taxes($tax_group_id, $charge_freight);
-    foreach ($taxes as $taxitem)
-       $tax_total +=  $taxitem['Value'];
+       $credit_invoice = count($credit_note->src_docs) ? key($credit_note->src_docs) : 0;
 
-       $credit_no = add_customer_trans(11, $credit_items->customer_id, $credit_items->Branch,
-       $credit_date, $reference, -($credit_items_total), 0, -$tax_total, -$charge_freight,
-       $sales_type, 0, $credit_items->ship_via);
 
-       foreach ($credit_items->line_items as $credit_line)
-       {
+       $credit_date = $credit_note->document_date;
+       $tax_group_id = $credit_note->tax_group_id;
 
-               if ($credit_line->quantity > 0)
-               {
-                       // the functions use qty_dispatched - so until that's fixed make sure it's set
-                       // or KABOOOOM
-                       $credit_line->qty_dispatched = $credit_line->quantity;
-
-                       add_gl_trans_credit_order_item($credit_items, $credit_line, $credit_no, $credit_date,
-                       $tax_group_id, $credit_type);
+       $trans_no = $credit_note->trans_no;
+       if (is_array($trans_no)) {
+               $trans_no = key($trans_no);
+       }
 
-               add_gl_trans_credit_costs($credit_items, $credit_line, $credit_no, $credit_date,
-                       $tax_group_id, $credit_type, $write_off_gl_code, $branch_data);
+       $credit_type = $write_off_acc == 0 ? 'Return' : 'Writeoff';
 
-                 } /*quantity credited is more than 0 */
-        } /*end of credit_line loop */
+       begin_transaction();
 
-       /*Post credit note transaction to GL credit debtors,
-       debit freight re-charged and debit sales */
+       $company_data = get_company_prefs();
+       $branch_data = get_branch_accounts($credit_note->Branch);
 
-       add_g_trans_credit_common($credit_items, $credit_no, $credit_date,
-               $credit_items_total, $charge_freight, $taxes, $tax_total, $branch_data);
+       $credit_note_total = $credit_note->get_items_total_dispatch();
+       $freight_tax = $credit_note->get_shipping_tax();
 
-       add_comments(11, $credit_no, $credit_date, $memo_);
+       $taxes = $credit_note->get_taxes();
 
-       add_forms_for_sys_type(11, $credit_no, $credit_items->Location);
+       $tax_total = 0;
+       foreach ($taxes as $taxitem) {
+               $tax_total +=  $taxitem['Value'];
+       }
 
-       references::save_last($reference, 11);
+       if ($credit_note->tax_included == 0) {
+           $items_added_tax = $tax_total-$freight_tax;
+           $freight_added_tax = $freight_tax;
+       } else {
+           $items_added_tax = 0;
+           $freight_added_tax = 0;
+       }
 
-       commit_transaction();
+//     $sales_order=$invoice->order_no;        //?
+//    if (is_array($sales_order)) $sales_order = $sales_order[0]; //?
 
-       return $credit_no;
-}
+       /*Now insert the Credit Note into the debtor_trans table with the allocations as calculated above*/
+       // all amounts in debtor's currency
+       $credit_no = write_customer_trans(11, $trans_no, $credit_note->customer_id,
+               $credit_note->Branch, $credit_date, $credit_note->reference,
+               $credit_note_total, 0, $items_added_tax,
+               $credit_note->freight_cost, $freight_added_tax,
+               $credit_note->default_sales_type,
+               $credit_note->order_no, $credit_invoice, $credit_note->ship_via
+               //, $credit_note->due_date
+               );
+
+       if ($trans_no==0) {
+               $credit_note->trans_no = array($credit_no=>0);
+               set_document_parent($credit_note);
+       } else {
+               delete_comments(11, $credit_no);
+               void_cust_allocations(11, $credit_no);
+               void_gl_trans(11, $credit_no, true);
+               void_stock_move(11, $credit_no);
+               void_customer_trans_tax_details(11, $credit_no);
+       }
 
-//----------------------------------------------------------------------------------------
+       if ($credit_invoice) {
+               $invoice_alloc_balance = get_DebtorTrans_allocation_balance(10, $credit_invoice);
+               update_customer_trans_version(get_parent_type(11), $credit_note->src_docs );
+               if ($invoice_alloc_balance > 0) {       /*the invoice is not already fully allocated */
+                       $total = $credit_note_total + $credit_note->freight_cost +
+                           $items_added_tax + $freight_added_tax;
+
+                       $allocate_amount = ($invoice_alloc_balance > $total) ? $total : $invoice_alloc_balance;
+                       /*Now insert the allocation record if > 0 */
+                       if ($allocate_amount != 0) {
+                               update_debtor_trans_allocation(10, $credit_invoice, $allocate_amount);
+                               update_debtor_trans_allocation(11, $credit_no, $allocate_amount); // ***
+                               add_cust_allocation($allocate_amount, 11, $credit_no, 10, $credit_invoice);
+                       }
+               }
+       }
 
-function credit_invoice($credit_items, $invoice_no, $order_no,
-       $default_dispatch_date, $credit_type, $tax_group_id,
-       $charge_freight, $reference, $memo_, $write_off_gl_code)
-{
-       begin_transaction();
+       foreach ($credit_note->line_items as $credit_line) {
 
-       $branch_data = get_branch_accounts($credit_items->Branch);
+               if ($credit_invoice && $credit_line->qty_dispatched!=$credit_line->qty_old ) {
+                       update_parent_line(11, $credit_line->id,($credit_line->qty_dispatched
+                                       -$credit_line->qty_old));
+               }
 
-       $invoice_alloc_balance = get_DebtorTrans_allocation_balance(10, $invoice_no);
+               $line_taxfree_price = get_tax_free_price_for_item($credit_line->stock_id, $credit_line->price,
+                 0, $credit_note->tax_included, $credit_note->tax_group_array);
 
-       $invoice_items_total = $credit_items->get_items_total_dispatch($tax_group_id);
+               $line_tax = get_full_price_for_item($credit_line->stock_id, $credit_line->price,
+                 0, $credit_note->tax_included, $credit_note->tax_group_array) - $line_taxfree_price;
 
-    $tax_total = 0;
-    $taxes = $credit_items->get_taxes($tax_group_id, $charge_freight);
-    foreach ($taxes as $taxitem)
-       $tax_total +=  $taxitem['Value'];
+               write_customer_trans_detail_item(11, $credit_no, $credit_line->stock_id,
+                       $credit_line->item_description, $credit_line->qty_dispatched,
+                       $credit_line->line_price(), $line_tax, $credit_line->discount_percent,
+                       $credit_line->standard_cost, $trans_no==0 ? 0:  $credit_line->id);
 
-       $allocate_amount = 0;
+               add_credit_movements_item(&$credit_note, &$credit_line, $credit_date,
+                       $credit_type, $line_taxfree_price+$line_tax, $credit_invoice);
 
-       if ($invoice_alloc_balance > 0)
-       {       /*the invoice is not already fully allocated */
+               add_gl_trans_credit_costs($credit_note, $credit_line, $credit_no,
+                   $credit_date, $credit_type, $write_off_acc, $branch_data);
+       } /*end of credit_line loop */
 
-               if ($invoice_alloc_balance > ($invoice_items_total + $charge_freight + $tax_total))
-               {
+       /*Post credit note transaction to GL credit debtors,
+       debit freight re-charged and debit sales */
 
-                       $allocate_amount = $invoice_items_total + $charge_freight + $tax_total;
-               }
-               else
-               {       /*the balance left to allocate is less than the credit note value */
-                       $allocate_amount = $invoice_alloc_balance;
-               }
+       if (($credit_note_total + $credit_note->freight_cost) != 0) {
 
-               update_debtor_trans_allocation(10, $invoice_no, $allocate_amount);
+               add_gl_trans_customer(11, $credit_no, $credit_date, $branch_data["receivables_account"], 0, 0,
+                       -($credit_note_total + $credit_note->freight_cost + $items_added_tax + $freight_added_tax),
+                       $credit_note->customer_id,
+                       "The total debtor GL posting for the credit note could not be inserted");
        }
 
-       /*Now insert the Credit Note into the debtor_trans table with the allocations as calculated above*/
-       // all amounts in debtor's currency
-
-       $credit_no = add_customer_trans(11, $credit_items->customer_id, $credit_items->Branch,
-       $default_dispatch_date, $reference,     -($invoice_items_total), 0, -$tax_total,
-       -$charge_freight, $credit_items->default_sales_type,    $order_no,
-       $credit_items->ship_via, "", $allocate_amount);
-
-       /*Now insert the allocation record if > 0 */
-       if ($allocate_amount != 0)
-       {
-               add_cust_allocation($allocate_amount, 11, $credit_no, 10, $invoice_no);
+       if ($credit_note->freight_cost !=0) {
+               add_gl_trans_customer(11, $credit_no, $credit_date, $company_data["freight_act"], 0, 0,
+                       $credit_note->get_tax_free_shipping(), $credit_note->customer_id,
+                       "The freight GL posting for this credit note could not be inserted");
        }
 
-       /* Update sales order details quantity invoiced less this credit quantity. */
-       foreach ($credit_items->line_items as $order_line)
-       {
-
-               if ($order_line->qty_dispatched >0)
-               {
-
-                       // always deduct the credited/returned quantities from the sales order
-                       dispatch_sales_order_item($order_no, $order_line->stock_id, -$order_line->qty_dispatched, $order_line->id);
-                       
-                       //if (($_POST['credit_type']=="Return") OR ($_POST['ItemsAction']==1))
-                       /*{
-                               $sql = "UPDATE ".TB_PREF."sales_order_details 
-                                                       SET qty_sent = qty_sent - " . $order_line->qty_dispatched . "
-                                               WHERE order_no = " . $order_no . " 
-                                               AND stk_code = '" . $order_line->stock_id . "'";
-                               $result = db_query($sql,"The sales order detail record could not be updated for the reduced quantity invoiced");
-                       }*/
-
-                       /*Now update sales_order_details for the quantity invoiced and the actual dispatch dates. */
-
-                       add_gl_trans_credit_order_item($credit_items, $order_line, $credit_no,
-                               $default_dispatch_date, $tax_group_id, $credit_type, $invoice_no);
+       foreach ($taxes as $taxitem) {
+               if ($taxitem['Value'] != 0) {
 
-               add_gl_trans_credit_costs($credit_items, $order_line, $credit_no, $default_dispatch_date,
-                       $tax_group_id, $credit_type, $write_off_gl_code, $branch_data);
-
-               } /*quantity dispatched is more than 0 */
-       } /*end of order_line loop */
-
-       add_g_trans_credit_common($credit_items, $credit_no, $default_dispatch_date,
-               $invoice_items_total, $charge_freight, $taxes, $tax_total, $branch_data);
+                       add_customer_trans_tax_detail_item(11, $credit_no, $taxitem['tax_type_id'],
+                               $taxitem['rate'], $credit_note->tax_included, $taxitem['Value']);
 
-       add_comments(11, $credit_no, $default_dispatch_date, $memo_);
+                       add_gl_trans_customer(11, $credit_no, $date_, $taxitem['sales_gl_code'], 0, 0,
+                               $taxitem['Value'], $credit_note->customer_id,
+                               "A tax GL posting for this credit note could not be inserted");
+               }
+       }
 
-       add_forms_for_sys_type(11, $credit_no);
+       add_comments(11, $credit_no, $credit_date, $credit_note->Comments);
 
-       references::save_last($reference, 11);
+       if ($trans_no == 0) {
+               references::save_last($credit_note->reference, 11);
+       }
 
        commit_transaction();
 
@@ -151,56 +150,50 @@ function credit_invoice($credit_items, $invoice_no, $order_no,
 }
 
 //----------------------------------------------------------------------------------------
-
-function add_gl_trans_credit_order_item(&$order, &$order_line, $credit_no, $date_, $tax_group_id,
-       $credit_type, $credited_invoice=0)
+// Insert a stock movement coming back in to show the credit note and
+//     a reversing stock movement to show the write off
+//
+function add_credit_movements_item(&$credit_note, &$credit_line, $date_,
+       $credit_type, $price, $credited_invoice=0)
 {
-       $line_taxfree_price = $order_line->taxfree_price($tax_group_id);
-       $line_tax = $order_line->full_price() - $line_taxfree_price;
 
-       if ($credit_type == "Return")
-       {
+       if ($credit_type == "Return") {
 
-               /* Insert stock movements for the stock coming back in - with unit cost */
+               $reference = "Return ";
+               if ($credited_invoice) {
+                       $reference .= "Ex Inv: " . $credited_invoice;
+               }
 
-               $reference = "";
-               if ($credited_invoice)
-                       $reference .= "Ex Inv: " . $credited_invoice;
+       } elseif ($credit_type == "WriteOff") {
 
-               add_customer_trans_detail_item(11, $credit_no, $order_line->stock_id,
-                       $order_line->item_description, $order->Location, $date_,
-                       $order_line->qty_dispatched, $line_taxfree_price, $line_tax,
-                       $order_line->discount_percent, $reference, $order_line->standard_cost);
+               $reference = "WriteOff ";
+               if ($credited_invoice)
+                       $reference .= "Ex Inv: " . $credited_invoice;
+
+       add_stock_move_customer(11,  $credit_line->stock_id,
+               key($credit_note->trans_no), $credit_note->Location,
+               $credit_note->document_date, $reference, -$credit_line->qty_dispatched,
+               $credit_line->standard_cost,  0, $price,
+               $credit_line->discount_percent);
+
+               }
+       add_stock_move_customer(11,  $credit_line->stock_id,
+               key($credit_note->trans_no), $credit_note->Location,
+               $credit_note->document_date, $reference, $credit_line->qty_dispatched,
+               $credit_line->standard_cost,  0, $price,
+               $credit_line->discount_percent);
 
        }
-       elseif ($credit_type == "WriteOff")
-       {
-          /*Insert a stock movement coming back in to show the credit note and
-               a reversing stock movement to show the write off
-               no mods to location stock records*/
-
-          $reference = "";
-          if ($credited_invoice)
-                       $reference .= "Ex Inv: " . $credited_invoice;
-
-               add_customer_trans_detail_item_writeoff(11, $credit_no, $order_line->stock_id,
-                       $order_line->item_description, $order->Location, $date_,
-                       $order_line->qty_dispatched, $line_taxfree_price, $line_tax,
-                       $order_line->discount_percent, $reference, $order_line->standard_cost);
-       }
-}
 
 //----------------------------------------------------------------------------------------
 
-function add_gl_trans_credit_costs($order, $order_line, $credit_no, $date_, $tax_group_id,
+function add_gl_trans_credit_costs($order, $order_line, $credit_no, $date_,
        $credit_type, $write_off_gl_code, &$branch_data)
 {
        $stock_gl_codes = get_stock_gl_code($order_line->stock_id);
 
        /* insert gl_trans to credit stock and debit cost of sales at standard cost*/
-       if ($order_line->standard_cost != 0)
-       {
-
+       if ($order_line->standard_cost != 0) {
                /*first the cost of sales entry*/
 
                add_gl_trans_std_cost(11, $credit_no, $date_, $stock_gl_codes["cogs_account"],
@@ -210,12 +203,9 @@ function add_gl_trans_credit_costs($order, $order_line, $credit_no, $date_, $tax
                        "The cost of sales GL posting could not be inserted");
 
                /*now the stock entry*/
-               if ($credit_type == "WriteOff")
-               {
+               if ($credit_type == "WriteOff") {
                        $stock_entry_account = $write_off_gl_code;
-               }
-               else
-               {
+               } else {
                        $stock_gl_code = get_stock_gl_code($order_line->stock_id);
                        $stock_entry_account = $stock_gl_code["inventory_account"];
                }
@@ -227,11 +217,15 @@ function add_gl_trans_credit_costs($order, $order_line, $credit_no, $date_, $tax
 
        } /* end of if GL and stock integrated and standard cost !=0 */
 
-       if ($order_line->price != 0)
-       {
+       if ($order_line->line_price() != 0) {
+
+               $line_taxfree_price =
+               get_tax_free_price_for_item($order_line->stock_id, $order_line->price,
+                 0, $order->tax_included, $order->tax_group_array);
+
+               $line_tax = get_full_price_for_item($order_line->stock_id, $order_line->price,
+                 0, $order->tax_included, $order->tax_group_array) - $line_taxfree_price;
 
-       $line_taxfree_price = $order_line->taxfree_price($tax_group_id);
-               $line_tax = $order_line->full_price() - $line_taxfree_price;
 
                //Post sales transaction to GL credit sales
 
@@ -239,8 +233,7 @@ function add_gl_trans_credit_costs($order, $order_line, $credit_no, $date_, $tax
                        ($line_taxfree_price * $order_line->qty_dispatched), $order->customer_id,
                        "The credit note GL posting could not be inserted");
 
-               if ($order_line->discount_percent != 0)
-               {
+               if ($order_line->discount_percent != 0) {
 
                        add_gl_trans_customer(11, $credit_no, $date_, $branch_data["sales_discount_account"], 0, 0,
                                -($line_taxfree_price * $order_line->qty_dispatched * $order_line->discount_percent),
@@ -248,49 +241,7 @@ function add_gl_trans_credit_costs($order, $order_line, $credit_no, $date_, $tax
                                "The credit note discount GL posting could not be inserted");
 
                } /*end of if discount !=0 */
-       } /*end of if sales integrated with debtors */
+       } /*if line_price!=0 */
 }
 
-//----------------------------------------------------------------------------------------
-
-function add_g_trans_credit_common($order, $credit_no, $date_,
-       $credit_items_total, $freight, $taxes, $tax_total, &$branch_data)
-{
-       $company_data = get_company_prefs();
-
-       /*Post credit note transaction to GL credit debtors,
-       debit freight re-charged and debit sales */
-
-       if (($credit_items_total + $freight + $tax_total) != 0)
-       {
-
-               add_gl_trans_customer(11, $credit_no, $date_, $branch_data["receivables_account"], 0, 0,
-                       -($credit_items_total + $freight + $tax_total), $order->customer_id,
-                       "The total debtor GL posting for the credit note could not be inserted");
-       }
-
-       if ($freight !=0)
-       {
-               add_gl_trans_customer(11, $credit_no, $date_, $company_data["freight_act"], 0, 0,
-                       $freight, $order->customer_id,
-                       "The freight GL posting for this credit note could not be inserted");
-       }
-
-    foreach ($taxes as $taxitem)
-    {
-       if ($taxitem['Value'] != 0)
-       {
-
-                       add_customer_trans_tax_detail_item(11, $credit_no, $taxitem['tax_type_id'],
-                               $taxitem['rate'], $taxitem['included_in_price'], $taxitem['Value']);
-
-               add_gl_trans_customer(11, $credit_no, $date_, $taxitem['sales_gl_code'], 0, 0,
-                       $taxitem['Value'], $order->customer_id,
-                       "A tax GL posting for this credit note could not be inserted");
-       }
-    }
-}
-
-//----------------------------------------------------------------------------------------
-
 ?>
\ No newline at end of file
index a53a8de0ffe9145e3a72a2ac40df64953a1e77ea..2367c7dabc4d5e6effcf2d8b3f49ed5d570314f6 100644 (file)
 <?php
+//-----------------------------------------------------------------------------
+// insert/update sales delivery
+//
+function write_sales_delivery(&$delivery,$bo_policy)
+{
 
-// $bo_policy = 0, cancel remaining quantities on order
-// = 1, backorder remaining quantities 
+       $trans_no = $delivery->trans_no;
+       if (is_array($trans_no)) $trans_no = key($trans_no);
 
-function add_sales_delivery(&$delivery, $date_, $due_date, $sales_order, $tax_group_id, 
-       $charge_shipping, $location, $ship_via, $sales_type, $reference, $memo_, $bo_policy)
-{
        begin_transaction();
-       
-       $company_data = get_company_prefs();
-       
-       $branch_data = get_branch_accounts($delivery->Branch);  
-       
-       $delivery_items_total = $delivery->get_items_total_dispatch($tax_group_id);
-       
-    $tax_total = 0;
-    $taxes = $delivery->get_taxes($tax_group_id, $charge_shipping);
-    foreach ($taxes as $taxitem)
-       $tax_total +=  $taxitem['Value'];
-
-       /*Now insert the debtor_trans */
-    $delivery_no = add_customer_trans(13, $delivery->customer_id, $delivery->Branch, $date_, 
-               $reference, $delivery_items_total, 0, $tax_total, $charge_shipping, 
-    $sales_type, $sales_order, 0, $ship_via, $due_date);
-       
-    // If balance of this delivery cancelled update sales order details quantity. 
-    foreach ($delivery->line_items as $delivery_line) 
-    {
-                       $line_taxfree_price = $delivery_line->taxfree_price($tax_group_id);
-                       /* add delivery details for _all_ lines */
-                       add_customer_trans_detail_item(13, $delivery_no, $delivery_line->stock_id,
-                               $delivery_line->item_description, $location, $date_, 
-                               -$delivery_line->qty_dispatched, $line_taxfree_price, 0,
-                               $delivery_line->discount_percent, $reference, $delivery_line->standard_cost);
-
-               if ($delivery_line->qty_dispatched != 0) 
-               {
-                       // Now update sales_order_details for the quantity delivered 
-                       dispatch_sales_order_item($sales_order, $delivery_line->stock_id, 
-                               $delivery_line->qty_dispatched, $delivery_line->id);
-                       
+
+       $delivery_items_total = $delivery->get_items_total_dispatch();
+       $freight_tax = $delivery->get_shipping_tax();
+
+// mark sales order for concurrency conflicts check
+       update_sales_order_version($delivery->src_docs);
+
+       $tax_total = 0;
+       $taxes = $delivery->get_taxes(); // all taxes with freight_tax
+
+       foreach ($taxes as $taxitem) {
+               $tax_total +=  $taxitem['Value'];
+       }
+       /* Insert/update the debtor_trans */
+       $delivery_no = write_customer_trans(13, $trans_no, $delivery->customer_id,
+               $delivery->Branch, $delivery->document_date, $delivery->reference,
+               $delivery_items_total, 0,
+               $delivery->tax_included ? 0 : $tax_total-$freight_tax,
+               $delivery->freight_cost,
+               $delivery->tax_included ? 0 : $freight_tax,
+               $delivery->default_sales_type, $delivery->order_no, 0,
+               $delivery->ship_via, $delivery->due_date);
+
+       if ($trans_no == 0) {
+               $delivery->trans_no = array($delivery_no=>0);
+       } else {
+               void_gl_trans(13, $delivery_no, true);
+               void_stock_move(13, $delivery_no);
+               delete_comments(13, $delivery_no);
+       }
+
+       foreach ($delivery->line_items as $delivery_line) {
+               $line_price = $delivery_line->line_price();
+               $line_taxfree_price = get_tax_free_price_for_item($delivery_line->stock_id,
+                       $delivery_line->price, 0, $delivery->tax_included,
+                       $delivery->tax_group_array);
+
+               $line_tax = get_full_price_for_item($delivery_line->stock_id, $delivery_line->price,
+                       0, $delivery->tax_included, $delivery->tax_group_array) - $line_taxfree_price;
+
+               /* add delivery details for all lines */
+               write_customer_trans_detail_item(13, $delivery_no, $delivery_line->stock_id,
+                       $delivery_line->item_description, $delivery_line->qty_dispatched,
+                       $delivery_line->line_price(), $line_tax,
+                       $delivery_line->discount_percent, $delivery_line->standard_cost,
+                       $trans_no ? $delivery_line->id : 0);
+
+       // Now update sales_order_details for the quantity delivered
+               if ($delivery_line->qty_old != $delivery_line->qty_dispatched)
+                       update_parent_line(13, $delivery_line->id,
+                               $delivery_line->qty_dispatched-$delivery_line->qty_old);
+
+               if ($delivery_line->qty_dispatched != 0) {
+                       add_stock_move_customer(13, $delivery_line->stock_id, $delivery_no,
+                               $delivery->Location, $delivery->document_date, $delivery->reference,
+                               -$delivery_line->qty_dispatched, $delivery_line->standard_cost,1,
+                               $line_price, $delivery_line->discount_percent);
+
+
                        $stock_gl_code = get_stock_gl_code($delivery_line->stock_id);
 
                        /* insert gl_trans to credit stock and debit cost of sales at standard cost*/
-                       if ($delivery_line->standard_cost != 0)
-                       {
+                       if ($delivery_line->standard_cost != 0) {
 
                                /*first the cost of sales entry*/
-                add_gl_trans_std_cost(13, $delivery_no, $date_, $stock_gl_code["cogs_account"], 
-                       $stock_gl_code["dimension_id"], $stock_gl_code["dimension2_id"], "", 
-                       $delivery_line->standard_cost * $delivery_line->qty_dispatched, 
-                       payment_person_types::customer(), $delivery->customer_id, 
+                               add_gl_trans_std_cost(13, $delivery_no,
+                               $delivery->document_date, $stock_gl_code["cogs_account"],
+                                       $stock_gl_code["dimension_id"], $stock_gl_code["dimension2_id"], "",
+                                       $delivery_line->standard_cost * $delivery_line->qty_dispatched,
+                                       payment_person_types::customer(), $delivery->customer_id,
                                        "The cost of sales GL posting could not be inserted");
-                                                                               
+
                                /*now the stock entry*/
                                //$stock_gl_code = get_stock_gl_code($order_line->stock_id);
-                               
-                add_gl_trans_std_cost(13, $delivery_no, $date_, $stock_gl_code["inventory_account"], 0, 0, "", 
-                       (-$delivery_line->standard_cost * $delivery_line->qty_dispatched), 
-                       payment_person_types::customer(), $delivery->customer_id, 
-                                       "The stock side of the cost of sales GL posting could not be inserted");                                
+
+                               add_gl_trans_std_cost(13, $delivery_no, $delivery->document_date,
+                                       $stock_gl_code["inventory_account"], 0, 0, "",
+                                       (-$delivery_line->standard_cost * $delivery_line->qty_dispatched),
+                                       payment_person_types::customer(), $delivery->customer_id,
+                                       "The stock side of the cost of sales GL posting could not be inserted");
 
                        } /* end of if GL and stock integrated and standard cost !=0 */
 
                } /*quantity dispatched is more than 0 */
        } /*end of order_line loop */
 
-       if ($bo_policy == 0)
-       {
+       if ($bo_policy == 0) {
                // if cancelling any remaining quantities
-               close_sales_order($sales_order);
+               close_sales_order($delivery->order_no);
+       }
+
+       // taxes - this is for printing purposes
+       foreach ($taxes as $taxitem) {
+               if ($taxitem['Value'] != 0) {
+                   add_customer_trans_tax_detail_item(13, $delivery_no, $taxitem['tax_type_id'],
+                               $taxitem['rate'], $delivery->tax_included, $taxitem['Value']);
+               }
+       }
+
+       add_comments(13, $delivery_no, $delivery->document_date, $delivery->Comments);
+
+       if ($trans_no == 0) {
+               // add_forms_for_sys_type(13, $delivery_no, $delivery->Location);
+               if ($delivery->reference!='auto')
+                       references::save_last($delivery->reference, 13);
        }
-    
-       add_comments(13, $delivery_no, $date_, $memo_);    
-       
-       add_forms_for_sys_type(13, $delivery_no, $location);
-       
-       references::save_last($reference, 13);  
-       
-       commit_transaction();   
+
+       commit_transaction();
 
        return $delivery_no;
 }
@@ -88,164 +126,32 @@ function add_sales_delivery(&$delivery, $date_, $due_date, $sales_order, $tax_gr
 function void_sales_delivery($type, $type_no)
 {
        begin_transaction();
-       
+
        void_gl_trans($type, $type_no, true);
-       
-       // for invoices and credits related to invoices, 
+
+       // for invoices and credits related to invoices,
        // reverse all the changes in the sales order
        $items_result = get_customer_trans_details($type, $type_no);
-       
+
        $order = get_customer_trans_order($type, $type_no);
-       
-       if ($order) 
-       {
-               while ($row = db_fetch($items_result))
-               {
-                       dispatch_sales_order_item($order, $row["stock_id"], $row["quantity"]);
+
+       if ($order) {
+               while ($row = db_fetch($items_result)) {
+                       update_parent_line(13, $row['id'], -$row['quantity']);
                }
        }
-       
+
        // clear details after they've been reversed in the sales order
        void_customer_trans_details($type, $type_no);
-       
-       void_customer_trans_tax_details($type, $type_no);       
-       
-       void_cust_allocations($type, $type_no);
-       
-       // do this last because other voidings can depend on it
-       // DO NOT MOVE THIS ABOVE VOIDING or we can end up with trans with alloc < 0
-       void_customer_trans($type, $type_no);   
-       
-       commit_transaction();                   
-}
 
-//----------------------------------------------------------------------------------------
+       void_customer_trans_tax_details($type, $type_no);
 
-function get_sales_delivery($trans_no)
-{
-       $sql = "SELECT ".TB_PREF."debtor_trans.*,
-       ".TB_PREF."cust_branch.*,
-       ".TB_PREF."debtors_master.name, 
-       ".TB_PREF."debtors_master.curr_code, 
-       ".TB_PREF."debtors_master.payment_terms, 
-       ".TB_PREF."debtors_master.discount, 
-       ".TB_PREF."sales_types.sales_type, 
-       ".TB_PREF."shippers.shipper_name,
-       ".TB_PREF."tax_groups.name AS tax_group_name , 
-       ".TB_PREF."tax_groups.id AS tax_group_id
-               FROM ".TB_PREF."debtor_trans, 
-                       ".TB_PREF."debtors_master, 
-                       ".TB_PREF."sales_types, 
-                       ".TB_PREF."tax_groups, 
-                       ".TB_PREF."cust_branch, 
-                       ".TB_PREF."shippers
-               WHERE   ".TB_PREF."debtor_trans.type=13
-                         AND ".TB_PREF."debtor_trans.tpe=".TB_PREF."sales_types.id
-                               AND ".TB_PREF."cust_branch.branch_code = ".TB_PREF."debtor_trans.branch_code
-                               AND ".TB_PREF."cust_branch.tax_group_id = ".TB_PREF."tax_groups.id
-                               AND ".TB_PREF."debtor_trans.debtor_no = ".TB_PREF."debtors_master.debtor_no
-                         AND ".TB_PREF."shippers.shipper_id = ".TB_PREF."debtor_trans.ship_via
-                               AND ".TB_PREF."debtor_trans.trans_no = ";
-                               
-       if(is_array($trans_no)) { //assume all transactions are for the same customer/branch
-           $sql .= $trans_no[0];
-       } else {
-           $sql .= $trans_no;
-       }
-
-       $result = db_query($sql, "delivery Retreival");
-
-       $num = db_num_rows($result);
-       if ($num > 1)
-       {
-               display_db_error("FATAL : delivery note query returned a duplicate - " . db_num_rows($result), $sql, true);
-       }
-       else if ($num == 1)
-       {
-               return db_fetch($result);
-       }
-       else
-               display_db_error("FATAL : delivery note search return nothing - " . db_num_rows($result), $sql, true);
-
-}
-
-//function get_sales_delivery_details($delivery) {
-//    if(!is_array($delivery)) {
-//
-//    }
-//}
-//--------------------------------------------------------------------------------------------------
-
-function read_sales_delivery($trans_no, &$cart)
-{
-       $myrow = get_sales_delivery($trans_no);
-
-       if(!is_array($trans_no)) $trans_no = array($trans_no);
-
-       $cart->customer_id = $myrow["debtor_no"];
-       $cart->Branch = $myrow["branch_code"];
-       $cart->customer_name = $myrow["name"];
-       $cart->cust_ref = $myrow["reference"];
-       $cart->default_sales_type =$myrow["tpe"];
-       $cart->sales_type_name =$myrow["sales_type"];
-       $cart->customer_currency = $myrow["curr_code"];
-       $cart->default_discount = $myrow["discount"];
-       $cart->order_no = $myrow["order_"];
-
-//     $cart->Comments = get_comments(13,$trans_no);
-
-       $cart->ship_via = $myrow["ship_via"];
-       $cart->deliver_to = $myrow["br_name"];
-       $cart->delivery_date = sql2date($myrow["due_date"]);
-       $cart->freight_cost = $myrow["ov_freight"];
-       $cart->delivery_address = $myrow["br_address"];
-       $cart->phone = $myrow["phone"];
-       $cart->email = $myrow["email"];
-
-//     $cart->Location = $myrow["location"]; 
-//     $cart->location_name = $myrow["location_name"];
-
-       $cart->orig_order_date = sql2date($myrow["tran_date"]);
-
-       $cart->tax_group_name = $myrow["tax_group_name"];
-       $cart->tax_group_id = $myrow["tax_group_id"];
-
-       $sql = "SELECT ".TB_PREF."debtor_trans_details.stock_id, unit_price, 
-               debtor_trans_no,
-               ".TB_PREF."debtor_trans_details.description,
-               ".TB_PREF."debtor_trans_details.id,
-               ".TB_PREF."debtor_trans_details.quantity, discount_percent,
-               qty_done, ".TB_PREF."stock_master.units,
-               ".TB_PREF."stock_master.material_cost + ".TB_PREF."stock_master.labour_cost + ".TB_PREF."stock_master.overhead_cost AS standard_cost
-               FROM ".TB_PREF."debtor_trans_details, ".TB_PREF."stock_master
-                       WHERE ".TB_PREF."debtor_trans_details.debtor_trans_type=13 AND
-                       " .TB_PREF."debtor_trans_details.stock_id = ".TB_PREF."stock_master.stock_id";
-
-           $sql .= ' AND (';
-           foreach($trans_no as $key=>$num) {
-               if($key!=0) $sql .= ' OR ';
-               $sql .= 'debtor_trans_no =' . $num;
-           }
-           $sql .= ') ORDER BY id';
-
-       $result = db_query($sql, "Retreive Delivery Note Items");
-
-       if (db_num_rows($result) > 0)
-       {
-
-               while ($myrow = db_fetch($result))
-               {
-                       $cart->add_to_cart($myrow["stock_id"],-$myrow["quantity"],
-                               $myrow["unit_price"], $myrow["discount_percent"],
-                                -$myrow["qty_done"], $myrow["standard_cost"], $myrow["description"],$myrow["id"]);
-               }
-       }
+       void_cust_allocations($type, $type_no);
 
-       foreach($cart->line_items as $key=>$line) 
-         $cart->line_items[$key]->qty_dispatched = 
-         $cart->line_items[$key]->quantity - $cart->line_items[$key]->qty_done; 
+       // do this last because other voidings can depend on it
+       // DO NOT MOVE THIS ABOVE VOIDING or we can end up with trans with alloc < 0
+       void_customer_trans($type, $type_no);
 
-       return true;
+       commit_transaction();
 }
-
 ?>
\ No newline at end of file
index 55dc0bb0308d2473753448f32b85d57cfc7e01ab..21ba9c5cc42b2b8512e887c92df0a304a9e20baa 100644 (file)
 <?php
-function set_invoice_links(&$cart, $invoice) {
-    if(count($cart->trans_no)==1) {
-         
-         $del = $cart->trans_no;
-         if(is_array($del)) $del = $del[0]; 
-         $sql = 'UPDATE '.TB_PREF.'debtor_trans SET trans_link = ' . $del .
-                 ' WHERE type=10 AND trans_no='.$invoice;
-         db_query($sql, 'Invoice link cannot be updated');    
-
-         foreach($cart->line_items as $line) {
-           if($line->quantity!=$line->qty_dispatched) {
-               // this is partial invoice
-               return 1;
-           }
-         }
-       
-       }
-
-    $sql = 'UPDATE '.TB_PREF.'debtor_trans SET trans_link = ' . $invoice .
-       ' WHERE type=13 AND (';
-
-    $deliveries = $cart->trans_no;
-       
-    foreach($deliveries as $key=>$del) 
-           $deliveries[$key] = 'trans_no='.$del;
-    $sql .= implode(' OR ', $deliveries) . ')';
-    
-    db_query($sql, 'Delivery links cannot be updated');
- return 0; // batch or complete invoice
-}
 
-function add_sales_invoice(&$cart, $date_, $due_date, $tax_group_id, 
-       $charge_shipping, $location, $ship_via, $sales_type, $reference, $memo_)
+//-----------------------------------------------------------------------------
+//     Add or update Sales Invoice
+//
+function write_sales_invoice(&$invoice)
 {
+
+       $trans_no = $invoice->trans_no;
+       if (is_array($trans_no))
+               $trans_no = key($trans_no);
+
+       $date_ = $invoice->document_date;
+       $charge_shipping =$invoice->freight_cost;
+
        begin_transaction();
-       
+
        $company_data = get_company_prefs();
-       
-       $branch_data = get_branch_accounts($cart->Branch);      
-       
-       $cart_items_total = $cart->get_items_total_dispatch($tax_group_id);
-
-       $delivery_no = $cart->trans_no;
-       if(is_array($delivery_no)) $delivery_no = 0;
-    
-    $tax_total = 0;
-    $taxes = $cart->get_taxes($tax_group_id, $charge_shipping);
-    foreach ($taxes as $taxitem)
-       $tax_total +=  $taxitem['Value'];
-
-       /*Now insert the debtor_trans */
-       $sales_order=$cart->order_no;
-       if(is_array($sales_order)) $sales_order = $sales_order[0]; // assume all crucial SO data are same for every delivery
-
-       $invoice_no = add_customer_trans(10, $cart->customer_id, $cart->Branch, $date_, 
-               $reference, $cart_items_total, 0, $tax_total, $charge_shipping, 
-       $sales_type, $sales_order, $delivery_no, $ship_via, $due_date);
-
-       set_invoice_links($cart,$invoice_no);
-       
-       // If balance of the order cancelled update sales order details quantity. 
-       foreach ($cart->line_items as $delivery_line) 
-       {
-
-               if ($delivery_line->qty_dispatched != 0) 
-               {
-                       
-                       $line_taxfree_price = $delivery_line->taxfree_price($tax_group_id);
-                       $line_tax = $delivery_line->full_price() - $line_taxfree_price;
-               
-                       // Now update delivery items for the quantity invoiced 
-                       invoice_delivery_item($delivery_line->id,$delivery_line->qty_dispatched);
-                       
-                       /* add invoice details and stock movements */
-
-                       add_customer_trans_detail_item(10, $invoice_no, $delivery_line->stock_id,
-                               $delivery_line->item_description, $location, $date_, 
-                               -$delivery_line->qty_dispatched, $line_taxfree_price, $line_tax,
-                               $delivery_line->discount_percent, $reference, $delivery_line->standard_cost);
-                                                                                               
-                       $stock_gl_code = get_stock_gl_code($delivery_line->stock_id);                                                                                           
-
-                       if ($delivery_line->price != 0)
-                       {
 
+       $branch_data = get_branch_accounts($invoice->Branch);
+
+       // offer price values without freight costs
+       $items_total = $invoice->get_items_total_dispatch();
+       $freight_tax = $invoice->get_shipping_tax();
+
+       $delivery_no = $invoice->src_docs;
+       if (is_array($delivery_no))
+               $delivery_no = 0;
+
+       update_customer_trans_version(get_parent_type(10), $invoice->src_docs);
+
+       $ov_gst = 0;
+       $taxes = $invoice->get_taxes(); // all taxes with freight_tax
+
+       foreach ($taxes as $taxitem) {
+               $ov_gst +=  $taxitem['Value'];
+       }
+
+       if($invoice->tax_included==0) {
+           $items_added_tax = $ov_gst-$freight_tax;
+           $freight_added_tax = $freight_tax;
+       } else {
+           $items_added_tax = 0;
+           $freight_added_tax = 0;
+       }
+
+       /* Insert/update the debtor_trans */
+       $sales_order = $invoice->order_no;
+       if (is_array($sales_order))
+                       $sales_order = $sales_order[0]; // assume all crucial SO data are same for every delivery
+
+       $invoice_no = write_customer_trans(10, $trans_no, $invoice->customer_id,
+               $invoice->Branch, $date_, $invoice->reference, $items_total, 0,
+               $items_added_tax, $invoice->freight_cost, $freight_added_tax,
+               $invoice->default_sales_type, $sales_order, $delivery_no,
+               $invoice->ship_via, $invoice->due_date);
+
+       if ($trans_no == 0) {
+               $invoice->trans_no = array($invoice_no=>0);
+               set_document_parent($invoice);
+       } else {
+               delete_comments(10, $invoice_no);
+               void_gl_trans(10, $invoice_no, true);
+               void_cust_allocations(10, $invoice_no); // ?
+               void_customer_trans_tax_details(10, $invoice_no);
+       }
+
+       foreach ($invoice->line_items as $invoice_line) {
+
+               $line_taxfree_price = get_tax_free_price_for_item($invoice_line->stock_id,
+                       $invoice_line->price, 0, $invoice->tax_included,
+                       $invoice->tax_group_array);
+
+               $line_tax = get_full_price_for_item($invoice_line->stock_id,
+                       $invoice_line->price, 0, $invoice->tax_included,
+                       $invoice->tax_group_array) - $line_taxfree_price;
+
+               write_customer_trans_detail_item(10, $invoice_no, $invoice_line->stock_id,
+                       $invoice_line->item_description, $invoice_line->qty_dispatched,
+                       $invoice_line->line_price(), $line_tax, $invoice_line->discount_percent,
+                       $invoice_line->standard_cost,
+                       $trans_no ? $invoice_line->id : 0);
+
+               // Update delivery items for the quantity invoiced
+               if ($invoice_line->qty_old != $invoice_line->qty_dispatched)
+                       update_parent_line(10, $invoice_line->id, ($invoice_line->qty_dispatched-$invoice_line->qty_old));
+
+               if ($invoice_line->qty_dispatched != 0) {
+                       $stock_gl_code = get_stock_gl_code($invoice_line->stock_id);
+
+                       if ($invoice_line->line_price() != 0) {
                                //Post sales transaction to GL credit sales
-                               
-         add_gl_trans_customer(10, $invoice_no, $date_, $stock_gl_code["sales_account"], 
-               $stock_gl_code["dimension_id"], $stock_gl_code["dimension2_id"], 
-                               (-$line_taxfree_price * $delivery_line->qty_dispatched), 
-                               $cart->customer_id, "The sales price GL posting could not be inserted");
-                               
-                               if ($delivery_line->discount_percent != 0)
-                               {
-                                       
-               add_gl_trans_customer(10, $invoice_no, $date_, 
-                                       $branch_data["sales_discount_account"], $stock_gl_code["dimension_id"], 
-                                       $stock_gl_code["dimension2_id"],
-                                       ($line_taxfree_price * $delivery_line->qty_dispatched * $delivery_line->discount_percent), 
-                                       $cart->customer_id, "The sales discount GL posting could not be inserted");                                                     
-                               } /*end of if discount !=0 */
-                       } /*end of if sales integrated with debtors */
 
+                                       add_gl_trans_customer(10, $invoice_no, $date_, $stock_gl_code["sales_account"],
+                                               $stock_gl_code["dimension_id"], $stock_gl_code["dimension2_id"],
+                                               (-$line_taxfree_price * $invoice_line->qty_dispatched),
+                                               $invoice->customer_id, "The sales price GL posting could not be inserted");
+
+                               if ($invoice_line->discount_percent != 0) {
+
+                                       add_gl_trans_customer(10, $invoice_no, $date_,
+                                               $branch_data["sales_discount_account"], $stock_gl_code["dimension_id"],
+                                               $stock_gl_code["dimension2_id"],
+                                               ($line_taxfree_price * $invoice_line->qty_dispatched * $invoice_line->discount_percent),
+                                               $invoice->customer_id, "The sales discount GL posting could not be inserted");
+                               } /*end of if discount !=0 */
+                       }
                } /*quantity dispatched is more than 0 */
        } /*end of delivery_line loop */
 
        /*Post debtors transaction to GL debit debtors, credit freight re-charged and credit sales */
-       if (($cart_items_total + $charge_shipping + $tax_total) != 0) 
-       {
-       add_gl_trans_customer(10, $invoice_no, $date_, $branch_data["receivables_account"], 0, 0,
-                       ($cart_items_total + $charge_shipping + $tax_total), 
-                       $cart->customer_id, "The total debtor GL posting could not be inserted");                               
+       if (($items_total + $charge_shipping) != 0) {
+               add_gl_trans_customer(10, $invoice_no, $date_, $branch_data["receivables_account"], 0, 0,
+                       ($items_total + $charge_shipping + $items_added_tax + $freight_added_tax),
+                       $invoice->customer_id, "The total debtor GL posting could not be inserted");
        }
-
-       if ($charge_shipping != 0) 
-       {
-       add_gl_trans_customer(10, $invoice_no, $date_, $company_data["freight_act"], 0, 0,
-                       (-$charge_shipping), $cart->customer_id, 
-                       "The freight GL posting could not be inserted");                                
+       if ($charge_shipping != 0) {
+               add_gl_trans_customer(10, $invoice_no, $date_, $company_data["freight_act"], 0, 0,
+                       -$invoice->get_tax_free_shipping(), $invoice->customer_id,
+                       "The freight GL posting could not be inserted");
        }
-       
-    foreach ($taxes as $taxitem) 
-    {
-       if ($taxitem['Value'] != 0) 
-       {
+       // post all taxes
+       foreach ($taxes as $taxitem) {
+               if ($taxitem['Value'] != 0) {
                        add_customer_trans_tax_detail_item(10, $invoice_no, $taxitem['tax_type_id'],
-                               $taxitem['rate'], $taxitem['included_in_price'], $taxitem['Value']);                    
-               
-               add_gl_trans_customer(10, $invoice_no, $date_, $taxitem['sales_gl_code'], 0, 0,
-                       (-$taxitem['Value']), $cart->customer_id, 
-                       "A tax GL posting could not be inserted");
-       }       
-    }  
-    
-       add_comments(10, $invoice_no, $date_, $memo_);    
-       
-       add_forms_for_sys_type(10, $invoice_no, $location);
-       
-       references::save_last($reference, 10);  
-       
-       commit_transaction();   
-       
+                               $taxitem['rate'], $invoice->tax_included, $taxitem['Value']);
+
+                       add_gl_trans_customer(10, $invoice_no, $date_, $taxitem['sales_gl_code'], 0, 0,
+                               (-$taxitem['Value']), $invoice->customer_id,
+                               "A tax GL posting could not be inserted");
+               }
+       }
+
+       add_comments(10, $invoice_no, $date_, $invoice->Comments);
+
+       if ($trans_no == 0) {
+               //add_forms_for_sys_type(10, $invoice_no, $invoice->Location);
+               references::save_last($invoice->reference, 10);
+       }
+
+       commit_transaction();
+
        return $invoice_no;
 }
 
@@ -149,51 +148,34 @@ function add_sales_invoice(&$cart, $date_, $due_date, $tax_group_id,
 function void_sales_invoice($type, $type_no)
 {
        begin_transaction();
-       
+
        void_bank_trans($type, $type_no, true);
        void_gl_trans($type, $type_no, true);
-       
-       // for invoices and credits related to invoices, 
+
+       // for invoices and credits related to invoices,
        // reverse all the changes in the sales order
        $items_result = get_customer_trans_details($type, $type_no);
-       
+
        $delivery = get_customer_trans_link($type, $type_no);
-       
-       if ($delivery) 
-       {
-               while ($row = db_fetch($items_result))
-               {
-                       invoice_delivery_item($row['id'], $row['quantity']);
+
+       if ($delivery) {
+               while ($row = db_fetch($items_result)) {
+                       update_parent_line(10, $row['id'], -$row['quantity']);
                }
        }
-       
+
        // clear details after they've been reversed in the sales order
        void_customer_trans_details($type, $type_no);
-       
-       void_customer_trans_tax_details($type, $type_no);       
-       
-       void_cust_allocations($type, $type_no);
-       
-       // do this last because other voidings can depend on it - especially voiding
-       // DO NOT MOVE THIS ABOVE VOIDING or we can end up with trans with alloc < 0
-       void_customer_trans($type, $type_no);   
-       
-       commit_transaction();                   
-}
 
-//--------------------------------------------------------------------------------------------------
-function invoice_delivery_item($id, $qty_dispatched) 
-{
-       $sql = "UPDATE ".TB_PREF."debtor_trans_details ";
+       void_customer_trans_tax_details($type, $type_no);
 
-       $sql .= "SET qty_done = qty_done - $qty_dispatched ";
+       void_cust_allocations($type, $type_no);
 
-       $sql .= " WHERE id=$id";
-//             AND debtor_trans_type = 13
-//             AND debtor_trans_no = $delivery_no
-//             AND stock_id = '$stock_id'";
+       // do this last because other voidings can depend on it - especially voiding
+       // DO NOT MOVE THIS ABOVE VOIDING or we can end up with trans with alloc < 0
+       void_customer_trans($type, $type_no);
 
-       db_query($sql, "The sales delivery detail record could not be updated");
+       commit_transaction();
 }
 
 ?>
\ No newline at end of file
index bd46233ae5ec9827719e06539be3b891d1b35479..a6c7610637fa06b4eae24b5a28aaaa3e437e9baa 100644 (file)
@@ -10,7 +10,7 @@ function get_demand_qty($stockid, $location)
                                        ".TB_PREF."sales_orders.from_stk_loc ='$location' AND
                                        ".TB_PREF."sales_order_details.stk_code = '$stockid'";
 
-    $TransResult = db_query($sql,"No transactions were returned");
+       $TransResult = db_query($sql,"No transactions were returned");
        $DemandRow = db_fetch($TransResult);
        return $DemandRow['QtyDemand'];
 }
@@ -18,20 +18,20 @@ function get_demand_qty($stockid, $location)
 function get_demand_asm_qty($stockid, $location)
 {
        $sql = "SELECT SUM((".TB_PREF."sales_order_details.quantity-".TB_PREF."sales_order_details.qty_sent)*".TB_PREF."bom.quantity)
-                                  AS Dem
-                                  FROM ".TB_PREF."sales_order_details,
+                               AS Dem
+                               FROM ".TB_PREF."sales_order_details,
                                                ".TB_PREF."sales_orders,
                                                ".TB_PREF."bom,
                                                ".TB_PREF."stock_master
-                                  WHERE ".TB_PREF."sales_order_details.stk_code=".TB_PREF."bom.parent AND
-                                  ".TB_PREF."sales_orders.order_no = ".TB_PREF."sales_order_details.order_no AND
-                                  ".TB_PREF."sales_orders.from_stk_loc='$location' AND
-                                  ".TB_PREF."sales_order_details.quantity-".TB_PREF."sales_order_details.qty_sent > 0 AND
-                                  ".TB_PREF."bom.component='$stockid' AND
-                                  ".TB_PREF."stock_master.stock_id=".TB_PREF."bom.parent AND
-                                  ".TB_PREF."stock_master.mb_flag='A'";
-
-    $TransResult = db_query($sql,"No transactions were returned");
+                               WHERE ".TB_PREF."sales_order_details.stk_code=".TB_PREF."bom.parent AND
+                               ".TB_PREF."sales_orders.order_no = ".TB_PREF."sales_order_details.order_no AND
+                               ".TB_PREF."sales_orders.from_stk_loc='$location' AND
+                               ".TB_PREF."sales_order_details.quantity-".TB_PREF."sales_order_details.qty_sent > 0 AND
+                               ".TB_PREF."bom.component='$stockid' AND
+                               ".TB_PREF."stock_master.stock_id=".TB_PREF."bom.parent AND
+                               ".TB_PREF."stock_master.mb_flag='A'";
+
+       $TransResult = db_query($sql,"No transactions were returned");
        if (db_num_rows($TransResult)==1)
        {
                $DemandRow = db_fetch_row($TransResult);
@@ -40,26 +40,23 @@ function get_demand_asm_qty($stockid, $location)
        else
                $DemandQty = 0.0;
 
-    return $DemandQty;
+       return $DemandQty;
 }
 
-function add_sales_order($order)
+function add_sales_order(&$order)
 {
        global $loc_notification, $path_to_root;
 
        begin_transaction();
 
-       if ($order->trans_type=='invoice')
-               $del_date = date2sql($order->orig_order_date);
-       else
-               $del_date = date2sql($order->delivery_date);
-
-       $sql = "INSERT INTO ".TB_PREF."sales_orders (debtor_no, branch_code, customer_ref, Comments, ord_date,
+       $del_date = date2sql($order->due_date);
+       $order_type = 0; // this is default on new order
+       $sql = "INSERT INTO ".TB_PREF."sales_orders (type, debtor_no, branch_code, customer_ref, comments, ord_date,
                order_type, ship_via, deliver_to, delivery_address, contact_phone,
                contact_email, freight_cost, from_stk_loc, delivery_date)
-               VALUES ('" . $order->customer_id . "', '" . $order->Branch . "', '".
+               VALUES ('" . $order_type . "', '" . $order->customer_id . "', '" . $order->Branch . "', '".
                        $order->cust_ref ."','". db_escape($order->Comments) ."','" .
-                       date2sql($order->orig_order_date) . "', '" .
+                       date2sql($order->document_date) . "', '" .
                        $order->default_sales_type . "', " .
                        $_POST['ship_via'] .",'" . $order->deliver_to . "', '" .
                        $order->delivery_address . "', '" .
@@ -70,6 +67,8 @@ function add_sales_order($order)
        db_query($sql, "order Cannot be Added");
 
        $order_no = db_insert_id();
+       $order->trans_no = array($order_no=>0);
+
        if ($loc_notification == 1)
        {
                include_once($path_to_root . "/inventory/includes/inventory_db.inc");
@@ -87,8 +86,8 @@ function add_sales_order($order)
                                WHERE ".TB_PREF."loc_stock.loc_code=".TB_PREF."locations.loc_code
                                AND ".TB_PREF."loc_stock.stock_id = '" . $line->stock_id . "'
                                AND ".TB_PREF."loc_stock.loc_code = '" . $order->Location . "'";
-                       $res = db_query($sql,"a location could not be retreived");
-                       $loc = db_fetch($res);
+                       $res = db_query($sql,"a location could not be retreived");
+                       $loc = db_fetch($res);
                        if ($loc['email'] != "")
                        {
                                $qoh = get_qoh_on_date($line->stock_id, $order->Location);
@@ -104,6 +103,7 @@ function add_sales_order($order)
                                }
                        }
                }
+
                $sql = "INSERT INTO ".TB_PREF."sales_order_details (order_no, stk_code, description, unit_price, quantity, discount_percent) VALUES (";
                $sql .= $order_no .
                                ",'$line->stock_id', '$line->item_description', $line->price,
@@ -156,28 +156,50 @@ function delete_sales_order($order_no)
 }
 
 //----------------------------------------------------------------------------------------
+// Mark changes in sales_order_details
+//
+function update_sales_order_version($order) 
+{
+  foreach ($order as $so_num => $so_ver) {
+  $sql= 'UPDATE '.TB_PREF.'sales_orders SET version=version+1 WHERE order_no='. $so_num.
+       ' AND version='.$so_ver;
+  db_query($sql, 'Concurrent editing conflict while sales order update');
+  }
+}
 
-function update_sales_order($order_no, $order)
+//----------------------------------------------------------------------------------------
+
+function update_sales_order($order)
 {
        global $loc_notification, $path_to_root;
 
-       $del_date = date2sql($order->delivery_date);
-       $ord_date = date2sql($order->orig_order_date);
+       $del_date = date2sql($order->due_date);
+       $ord_date = date2sql($order->document_date);
+       $order_no =  key($order->trans_no);
+       $version= current($order->trans_no);
 
        begin_transaction();
 
-       $sql = "UPDATE ".TB_PREF."sales_orders SET debtor_no = '" . $order->customer_id . "',
+       $sql = "UPDATE ".TB_PREF."sales_orders SET type =".$order->so_type." ,
+               debtor_no = '" . $order->customer_id . "',
                branch_code = '" . $order->Branch . "',
                customer_ref = '". $order->cust_ref ."',
-               Comments = '". db_escape($order->Comments) ."', ord_date = '" . $ord_date . "',
-               order_type = '" . $order->default_sales_type . "', ship_via = " . $order->ship_via .",
-               deliver_to = '" . $order->deliver_to . "', delivery_address = '" . $order->delivery_address . "',
+               comments = '". db_escape($order->Comments) ."',
+               ord_date = '" . $ord_date . "',
+               order_type = '" . $order->default_sales_type . "',
+               ship_via = " . $order->ship_via .",
+               deliver_to = '" . $order->deliver_to . "',
+               delivery_address = '" . $order->delivery_address . "',
                contact_phone = '" . $order->phone . "',
-               contact_email = '" . $order->email . "', freight_cost = " . $order->freight_cost .",
-               from_stk_loc = '" . $order->Location ."', delivery_date = '" . $del_date . "'
-               WHERE order_no=" . $order_no;
+               contact_email = '" . $order->email . "',
+               freight_cost = " . $order->freight_cost .",
+               from_stk_loc = '" . $order->Location ."',
+               delivery_date = '" . $del_date . "',
+               version = ".($version+1)."
+        WHERE order_no=" . $order_no ."
+        AND version=".$version;
 
-       db_query($sql, "order Cannot be Updated");
+       db_query($sql, "order Cannot be Updated, this can be concurrent edition conflict");
 
        $sql = "DELETE FROM ".TB_PREF."sales_order_details WHERE order_no =" . $order_no;
 
@@ -195,13 +217,16 @@ function update_sales_order($order_no, $order)
        {
                if ($loc_notification == 1 && is_inventory_item($line->stock_id))
                {
-                       $sql = "SELECT ".TB_PREF."loc_stock.*, ".TB_PREF."locations.location_name, ".TB_PREF."locations.email
-                               FROM ".TB_PREF."loc_stock, ".TB_PREF."locations
+                       $sql = "SELECT ".TB_PREF."loc_stock.*, "
+                                 .TB_PREF."locations.location_name, "
+                                 .TB_PREF."locations.email
+                               FROM ".TB_PREF."loc_stock, "
+                                 .TB_PREF."locations
                                WHERE ".TB_PREF."loc_stock.loc_code=".TB_PREF."locations.loc_code
-                               AND ".TB_PREF."loc_stock.stock_id = '" . $line->stock_id . "'
-                               AND ".TB_PREF."loc_stock.loc_code = '" . $order->Location . "'";
-                       $res = db_query($sql,"a location could not be retreived");
-                       $loc = db_fetch($res);
+                                AND ".TB_PREF."loc_stock.stock_id = '" . $line->stock_id . "'
+                                AND ".TB_PREF."loc_stock.loc_code = '" . $order->Location . "'";
+                       $res = db_query($sql,"a location could not be retreived");
+                       $loc = db_fetch($res);
                        if ($loc['email'] != "")
                        {
                                $qoh = get_qoh_on_date($line->stock_id, $order->Location);
@@ -217,8 +242,17 @@ function update_sales_order($order_no, $order)
                                }
                        }
                }
-               $sql = "INSERT INTO ".TB_PREF."sales_order_details (order_no, stk_code,  description, unit_price, quantity, discount_percent, qty_sent) VALUES (";
-               $sql .= $order_no . ",'" . $line->stock_id . "','" . $line->item_description . "', " . $line->price . ", " . $line->quantity . ", " . $line->discount_percent . ", " . $line->qty_done ." )";
+               $sql = "INSERT INTO ".TB_PREF."sales_order_details 
+                (order_no, stk_code,  description, unit_price, quantity, 
+                 discount_percent, qty_sent) 
+                VALUES (";
+               $sql .= $order_no . ",'"
+                 .$line->stock_id . "','"
+                 .$line->item_description . "', "
+                 .$line->price . ", "
+                 .$line->quantity . ", "
+                 .$line->discount_percent . ", "
+                 .$line->qty_done ." )";
 
                db_query($sql, "Old order Cannot be Inserted");
 
@@ -235,7 +269,9 @@ function update_sales_order($order_no, $order)
                $subject = _("Stocks below Re-Order Level at " . $loc['location_name']);
                $msg = "\n";
                for ($i = 0; $i < count($st_ids); $i++)
-                       $msg .= $st_ids[$i] . " " . $st_names[$i] . ", " . _("Re-Order Level") . ": " . $st_reorder[$i] . ", " . _("Below") . ": " . $st_num[$i] . "\n";
+                       $msg .= $st_ids[$i] . " " . $st_names[$i] . ", " 
+                         . _("Re-Order Level") . ": " . $st_reorder[$i] . ", " 
+                         . _("Below") . ": " . $st_num[$i] . "\n";
                $msg .= "\n" . _("Please reorder") . "\n\n";
                $msg .= $company['coy_name'];
                $mail->to($to);
@@ -247,20 +283,34 @@ function update_sales_order($order_no, $order)
 
 //----------------------------------------------------------------------------------------
 
-function get_sales_order($order_no)
+function get_sales_order_header($order_no)
 {
-       $sql = "SELECT ".TB_PREF."sales_orders.*, ".TB_PREF."debtors_master.name, ".TB_PREF."debtors_master.curr_code, ".TB_PREF."locations.location_name,
-               ".TB_PREF."debtors_master.payment_terms, ".TB_PREF."debtors_master.discount, ".TB_PREF."sales_types.sales_type, ".TB_PREF."shippers.shipper_name,
-               ".TB_PREF."tax_groups.name AS tax_group_name , ".TB_PREF."tax_groups.id AS tax_group_id
-               FROM ".TB_PREF."sales_orders, ".TB_PREF."debtors_master, ".TB_PREF."sales_types, ".TB_PREF."tax_groups, ".TB_PREF."cust_branch, ".TB_PREF."locations, ".TB_PREF."shippers
-                       WHERE ".TB_PREF."sales_orders.order_type=".TB_PREF."sales_types.id
-                               AND ".TB_PREF."cust_branch.branch_code = ".TB_PREF."sales_orders.branch_code
-                               AND ".TB_PREF."cust_branch.tax_group_id = ".TB_PREF."tax_groups.id
-                               AND ".TB_PREF."sales_orders.debtor_no = ".TB_PREF."debtors_master.debtor_no
-                               AND ".TB_PREF."locations.loc_code = ".TB_PREF."sales_orders.from_stk_loc
-                               AND ".TB_PREF."shippers.shipper_id = ".TB_PREF."sales_orders.ship_via
-                               AND ".TB_PREF."sales_orders.order_no = " . $order_no ;
-
+       $sql = "SELECT ".TB_PREF."sales_orders.*, "
+         .TB_PREF."debtors_master.name, "
+         .TB_PREF."debtors_master.curr_code, "
+         .TB_PREF."locations.location_name, "
+         .TB_PREF."debtors_master.payment_terms, "
+         .TB_PREF."debtors_master.discount, "
+         .TB_PREF."sales_types.sales_type, "
+         .TB_PREF."sales_types.id AS sales_type_id, "
+         .TB_PREF."sales_types.tax_included, "
+         .TB_PREF."shippers.shipper_name, "
+         .TB_PREF."tax_groups.name AS tax_group_name , "
+         .TB_PREF."tax_groups.id AS tax_group_id
+       FROM ".TB_PREF."sales_orders, "
+         .TB_PREF."debtors_master, "
+         .TB_PREF."sales_types, "
+         .TB_PREF."tax_groups, "
+         .TB_PREF."cust_branch, "
+         .TB_PREF."locations, "
+         .TB_PREF."shippers
+       WHERE ".TB_PREF."sales_orders.order_type=".TB_PREF."sales_types.id
+               AND ".TB_PREF."cust_branch.branch_code = ".TB_PREF."sales_orders.branch_code
+               AND ".TB_PREF."cust_branch.tax_group_id = ".TB_PREF."tax_groups.id
+               AND ".TB_PREF."sales_orders.debtor_no = ".TB_PREF."debtors_master.debtor_no
+               AND ".TB_PREF."locations.loc_code = ".TB_PREF."sales_orders.from_stk_loc
+               AND ".TB_PREF."shippers.shipper_id = ".TB_PREF."sales_orders.ship_via
+               AND ".TB_PREF."sales_orders.order_no = " . $order_no ;
        $result = db_query($sql, "order Retreival");
 
        $num = db_num_rows($result);
@@ -279,63 +329,64 @@ function get_sales_order($order_no)
 
 //----------------------------------------------------------------------------------------
 
+function get_sales_order_details($order_no) {
+       $sql = "SELECT id, stk_code, unit_price, "
+               .TB_PREF."sales_order_details.description,"
+               .TB_PREF."sales_order_details.quantity, 
+                 discount_percent,
+                 qty_sent as qty_done, "
+               .TB_PREF."stock_master.units,
+               ".TB_PREF."stock_master.material_cost + "
+                       .TB_PREF."stock_master.labour_cost + "
+                       .TB_PREF."stock_master.overhead_cost AS standard_cost
+       FROM ".TB_PREF."sales_order_details, ".TB_PREF."stock_master
+       WHERE ".TB_PREF."sales_order_details.stk_code = ".TB_PREF."stock_master.stock_id
+       AND order_no =" . $order_no . " ORDER BY id";
+
+       return db_query($sql, "Retreive order Line Items");
+}
+//----------------------------------------------------------------------------------------
+
 function read_sales_order($order_no, &$order)
 {
-       $myrow = get_sales_order($order_no);
+       $myrow = get_sales_order_header($order_no);
+
+       $order->trans_type = 30;
+       $order->so_type =  $myrow["type"];
+       $order->trans_no = array($order_no=> $myrow["version"]);
 
-       $order->trans_no = $order_no;
-       $order->customer_id = $myrow["debtor_no"];
-       $order->Branch = $myrow["branch_code"];
-       $order->customer_name = $myrow["name"];
+       $order->set_customer($myrow["debtor_no"], $myrow["name"], 
+         $myrow["curr_code"], $myrow["discount"]);
+
+       $order->set_branch($myrow["branch_code"], $myrow["tax_group_id"],
+         $myrow["tax_group_name"], $myrow["contact_phone"], $myrow["contact_email"]);
+
+       $order->set_sales_type($myrow["sales_type_id"], $myrow["sales_type"], $myrow["tax_included"]);
+
+       $order->set_location($myrow["from_stk_loc"], $myrow["location_name"]);
+
+       $order->set_delivery($myrow["ship_via"], $myrow["deliver_to"], 
+         $myrow["delivery_address"], $myrow["freight_cost"]);
+         
        $order->cust_ref = $myrow["customer_ref"];
        $order->default_sales_type =$myrow["order_type"];
-       $order->sales_type_name =$myrow["sales_type"];
-       $order->customer_currency = $myrow["curr_code"];
-       $order->default_discount = $myrow["discount"];
-
        $order->Comments = $myrow["comments"];
+       $order->due_date = sql2date($myrow["delivery_date"]);
+       $order->document_date = sql2date($myrow["ord_date"]);
 
-       $order->ship_via = $myrow["ship_via"];
-       $order->deliver_to = $myrow["deliver_to"];
-       $order->delivery_date = sql2date($myrow["delivery_date"]);
-       $order->freight_cost = $myrow["freight_cost"];
-       $order->delivery_address = $myrow["delivery_address"];
-       $order->phone = $myrow["contact_phone"];
-       $order->email = $myrow["contact_email"];
-       $order->Location = $myrow["from_stk_loc"];
-       $order->location_name = $myrow["location_name"];
-       $order->orig_order_date = sql2date($myrow["ord_date"]);
-
-       $order->tax_group_name = $myrow["tax_group_name"];
-       $order->tax_group_id = $myrow["tax_group_id"];
-
-       $sql = "SELECT id, stk_code, unit_price, ".TB_PREF."sales_order_details.description,
-               ".TB_PREF."sales_order_details.quantity, discount_percent,
-               qty_sent, ".TB_PREF."stock_master.units,
-               ".TB_PREF."stock_master.material_cost + ".TB_PREF."stock_master.labour_cost + ".TB_PREF."stock_master.overhead_cost AS standard_cost
-               FROM ".TB_PREF."sales_order_details, ".TB_PREF."stock_master
-                       WHERE ".TB_PREF."sales_order_details.stk_code = ".TB_PREF."stock_master.stock_id
-                               AND order_no =" . $order_no . " ORDER BY id";
-
-//             $sql .= "
-//                     AND ".TB_PREF."sales_order_details.quantity - ".TB_PREF."sales_order_details.qty_sent > 0 ";
-       $result = db_query($sql, "Retreive order Line Items");
-
+       $result = get_sales_order_details($order_no);
        if (db_num_rows($result) > 0)
        {
-
+               $line_no=0;
                while ($myrow = db_fetch($result))
                {
-                       $order->add_to_cart($myrow["stk_code"],$myrow["quantity"],
+                       $order->add_to_cart($line_no,$myrow["stk_code"],$myrow["quantity"],
                                $myrow["unit_price"], $myrow["discount_percent"],
-                                $myrow["qty_sent"], $myrow["standard_cost"], $myrow["description"], $myrow["id"] );
+                               $myrow["qty_done"], $myrow["standard_cost"], $myrow["description"], $myrow["id"] );
+               $line_no++;
                }
        }
 
- foreach($order->line_items as $key=>$line) 
-       $order->line_items[$key]->qty_dispatched = 
-       $order->line_items[$key]->quantity - $order->line_items[$key]->qty_done; 
-
        return true;
 }
 
@@ -359,21 +410,9 @@ function close_sales_order($order_no)
 {
        // set the quantity of each item to the already sent quantity. this will mark item as closed.
        $sql = "UPDATE ".TB_PREF."sales_order_details
-               SET quantity = qty_sent
-                       WHERE order_no = $order_no";
-
-       db_query($sql, "The sales order detail record could not be updated");
-}
-
-//----------------------------------------------------------------------------------------
-
-function dispatch_sales_order_item($order_no, $stock_id, $qty_dispatched, $id)
-{
-       $sql = "UPDATE ".TB_PREF."sales_order_details ";
-
-       $sql .= "SET qty_sent = qty_sent + $qty_dispatched ";
-
-       $sql .= " WHERE id = $id";
+               SET quantity = qty_sent,
+                       type = 0,
+                       WHERE order_no = $order_no";
 
        db_query($sql, "The sales order detail record could not be updated");
 }
@@ -386,21 +425,64 @@ function get_invoice_duedate($debtorno, $invdate)
        {
                return Today();
        }
-    $sql = "SELECT ".TB_PREF."debtors_master.debtor_no, ".TB_PREF."debtors_master.payment_terms, ".TB_PREF."payment_terms.* FROM ".TB_PREF."debtors_master,
-               ".TB_PREF."payment_terms WHERE ".TB_PREF."debtors_master.payment_terms = ".TB_PREF."payment_terms.terms_indicator AND
-               ".TB_PREF."debtors_master.debtor_no = '$debtorno'";
+       $sql = "SELECT ".TB_PREF."debtors_master.debtor_no, ".TB_PREF."debtors_master.payment_terms, ".TB_PREF."payment_terms.* FROM ".TB_PREF."debtors_master,
+               ".TB_PREF."payment_terms WHERE ".TB_PREF."debtors_master.payment_terms = ".TB_PREF."payment_terms.terms_indicator AND
+               ".TB_PREF."debtors_master.debtor_no = '$debtorno'";
 
-    $result = db_query($sql,"The customer details could not be retrieved");
-    $myrow = db_fetch($result);
+       $result = db_query($sql,"The customer details could not be retrieved");
+       $myrow = db_fetch($result);
 
-    if (db_num_rows($result) == 0)
-       return $invdate;
-    if ($myrow['day_in_following_month'] > 0)
-       $duedate = add_days(end_month($invdate), $myrow['day_in_following_month']);
+       if (db_num_rows($result) == 0)
+               return $invdate;
+       if ($myrow['day_in_following_month'] > 0)
+               $duedate = add_days(end_month($invdate), $myrow['day_in_following_month']);
        else
-       $duedate = add_days($invdate, $myrow['days_before_due']);
-    return $duedate;
+               $duedate = add_days($invdate, $myrow['days_before_due']);
+       return $duedate;
 }
 
+function get_customer_to_order($customer_id) {
+
+       // Now check to ensure this account is not on hold */
+       $sql = "SELECT ".TB_PREF."debtors_master.name, "
+                 .TB_PREF."debtors_master.address, "
+                 .TB_PREF."credit_status.dissallow_invoices, "
+                 .TB_PREF."debtors_master.sales_type AS salestype, "
+                 .TB_PREF."sales_types.sales_type, "
+                 .TB_PREF."sales_types.tax_included, "
+                 .TB_PREF."debtors_master.curr_code, "
+                 .TB_PREF."debtors_master.discount
+               FROM ".TB_PREF."debtors_master, "
+                 .TB_PREF."credit_status, "
+                 .TB_PREF."sales_types
+               WHERE ".TB_PREF."debtors_master.sales_type="
+                 .TB_PREF."sales_types.id
+               AND ".TB_PREF."debtors_master.credit_status=".TB_PREF."credit_status.id
+               AND ".TB_PREF."debtors_master.debtor_no = '" . $customer_id . "'";
+
+       $result =db_query($sql,"Customer Record Retreive");
+       return  db_fetch($result);
+}
 
+function get_branch_to_order($customer_id, $branch_id) {
+               
+       // the branch was also selected from the customer selection so default the delivery details from the customer branches table cust_branch. The order process will ask for branch details later anyway
+               $sql = "SELECT ".TB_PREF."cust_branch.br_name, "
+                       .TB_PREF."cust_branch.br_address, "
+                       .TB_PREF."cust_branch.br_post_address, "
+                       .TB_PREF."cust_branch.phone, "
+                       .TB_PREF."cust_branch.email,
+                         default_location, location_name, default_ship_via, "
+                       .TB_PREF."tax_groups.name AS tax_group_name, "
+                       .TB_PREF."tax_groups.id AS tax_group_id
+                       FROM ".TB_PREF."cust_branch, "
+                         .TB_PREF."tax_groups, "
+                         .TB_PREF."locations
+                       WHERE ".TB_PREF."cust_branch.tax_group_id = ".TB_PREF."tax_groups.id
+                               AND ".TB_PREF."locations.loc_code=default_location
+                               AND ".TB_PREF."cust_branch.branch_code='" . $branch_id . "'
+                               AND ".TB_PREF."cust_branch.debtor_no = '" . $customer_id . "'";
+
+           return db_query($sql,"Customer Branch Record Retreive");
+}
 ?>
\ No newline at end of file
index 96acf4fb6861165b378ce86a982d2999ea3838e6..338ae59b309b7ea48ae942dec5d16697304dc005 100644 (file)
@@ -1,15 +1,16 @@
 <?php
 
-function add_sales_type($name)
+function add_sales_type($name, $tax_included)
 {
-       $sql = "INSERT INTO ".TB_PREF."sales_types (sales_type) VALUES ('$name')";
+       $sql = "INSERT INTO ".TB_PREF."sales_types (sales_type,tax_included) VALUES ('$name','$tax_included')";
                
        db_query($sql, "could not add sales type");             
 }
 
-function update_sales_type($id, $name)
+function update_sales_type($id, $name, $tax_included)
 {
-       $sql = "UPDATE ".TB_PREF."sales_types SET sales_type = '$name' WHERE id = $id";
+       $sql = "UPDATE ".TB_PREF."sales_types SET sales_type = '$name',
+       tax_included =$tax_included WHERE id = $id";
        
        db_query($sql, "could not update sales type");                  
 }
index fce9f44e491c45bb3cd45a20495a2ff5698f612f..e3b3e5a34752fa304d8bef0e191487b6ded1b598 100644 (file)
@@ -1,9 +1,7 @@
 <?php
 
 include_once($path_to_root . "/includes/banking.inc");
-
 include_once($path_to_root . "/includes/db/inventory_db.inc");
-
 include_once($path_to_root . "/sales/includes/db/sales_order_db.inc");
 include_once($path_to_root . "/sales/includes/db/sales_credit_db.inc");
 include_once($path_to_root . "/sales/includes/db/sales_invoice_db.inc");
@@ -15,37 +13,34 @@ include_once($path_to_root . "/sales/includes/db/payment_db.inc");
 include_once($path_to_root . "/sales/includes/db/branches_db.inc");
 include_once($path_to_root . "/sales/includes/db/customers_db.inc");
 
-
 //----------------------------------------------------------------------------------------
-
 // $price in customer's currency
 // $quantity is used as is (if it's neg it's neg, if it's pos it's pos)
 // $std_cost is in home currency
 // $show_or_hide 1 show this item in invoice/credit views, 0 to hide it (used for write-off items)
 // $type is 10 (invoice) or 11 (credit)
 
-function add_stock_move_customer($type, $stock_id, $trans_id, $location, $date_, $reference, 
-       $quantity, $std_cost, $show_or_hide=1, $price=0, $discount_percent=0)
+function add_stock_move_customer($type, $stock_id, $trans_id, $location, $date_, $reference,
+       $quantity, $std_cost, $show_or_hide=1, $price=0, $discount_percent=0)
 {
-       return add_stock_move($type, $stock_id, $trans_id, $location, $date_, $reference, 
-               $quantity, $std_cost, 0, $show_or_hide, $price, $discount_percent, 
+       return add_stock_move($type, $stock_id, $trans_id, $location, $date_, $reference,
+               $quantity, $std_cost, 0, $show_or_hide, $price, $discount_percent,
                "The customer stock movement record cannot be inserted");
-}      
+}
 
 //----------------------------------------------------------------------------------------
-
 // add a debtor-related gl transaction
 // $date_ is display date (non-sql)
 // $amount is in CUSTOMER'S currency
 
-function add_gl_trans_customer($type, $type_no, $date_, $account, $dimension, $dimension2, 
+function add_gl_trans_customer($type, $type_no, $date_, $account, $dimension, $dimension2,
        $amount, $customer_id, $err_msg="")
 {
        if ($err_msg == "")
-               $err_msg = "The customer GL transaction could not be inserted"; 
-               
-       return add_gl_trans($type, $type_no, $date_, $account, $dimension, $dimension2, "", $amount, 
-               get_customer_currency($customer_id), 
+               $err_msg = "The customer GL transaction could not be inserted";
+
+       return add_gl_trans($type, $type_no, $date_, $account, $dimension, $dimension2, "", $amount,
+               get_customer_currency($customer_id),
                payment_person_types::customer(), $customer_id, $err_msg);
 }
 
@@ -53,13 +48,13 @@ function add_gl_trans_customer($type, $type_no, $date_, $account, $dimension, $d
 
 function get_price ($stock_id, $debtor_no)
 {
-       $sql = "SELECT ".TB_PREF."prices.price 
-               FROM ".TB_PREF."prices, ".TB_PREF."debtors_master 
+       $sql = "SELECT ".TB_PREF."prices.price
+               FROM ".TB_PREF."prices, ".TB_PREF."debtors_master
                WHERE ".TB_PREF."debtors_master.sales_type=".TB_PREF."prices.sales_type_id
-                       AND ".TB_PREF."debtors_master.debtor_no='" . $debtor_no . "' 
-                       AND ".TB_PREF."prices.stock_id = '" . $stock_id . "' 
+                       AND ".TB_PREF."debtors_master.debtor_no='" . $debtor_no . "'
+                       AND ".TB_PREF."prices.stock_id = '" . $stock_id . "'
                        AND ".TB_PREF."prices.curr_abrev = ".TB_PREF."debtors_master.curr_code";
-                                       
+
        $result = db_query($sql, "There was a problem retrieving the pricing information for the part $stock_id for customer");
 
        if (db_num_rows($result) != 0)
@@ -67,14 +62,175 @@ function get_price ($stock_id, $debtor_no)
                /*There is a price from one of the above so return that */
                $myrow = db_fetch_row($result);
                return $myrow[0];
-       } 
-       else 
+       }
+       else
        {
                return 0;
        }
-                       
+
 }
 
-//----------------------------------------------------------------------------------------
+//-----------------------------------------------------------------------------
+
+function set_document_parent($cart)
+{
+       $inv_no = key($cart->trans_no);
+
+       if (count($cart->src_docs) == 1) {
+
+       // if this child document has only one parent - update child link
+       $del_no = key($cart->src_docs);
+
+       $sql = 'UPDATE '.TB_PREF.'debtor_trans SET trans_link = ' . $del_no .
+               ' WHERE type='.$cart->trans_type.' AND trans_no='. $inv_no ;
+       db_query($sql, 'Child document link cannot be updated');
+
+       }
+       if ($cart->trans_type != 10)
+               return 0;
+
+       // the rest is batch invoice specific
+
+       foreach ($cart->line_items as $line) {
+               if ($line->quantity != $line->qty_dispatched) {
+                       return 1;       // this is partial invoice
+               }
+       }
+
+       $sql = 'UPDATE '.TB_PREF.'debtor_trans SET trans_link = ' . $inv_no .
+       ' WHERE type='.get_parent_type($cart->trans_type).' AND (';
+
+       $deliveries = array_keys($cart->src_docs);
+
+       foreach ($deliveries as $key=>$del)
+               $deliveries[$key] = 'trans_no='.$del;
+
+       $sql .= implode(' OR ', $deliveries) . ')';
+       db_query($sql, 'Delivery links cannot be updated');
+
+       return 0; // batch or complete invoice
+}
 
+//--------------------------------------------------------------------------------------------------
+function get_parent_type($type)
+{
+       $parent_types = array( 11=>10, 10=>13, 13=>30 );
+       return isset($parent_types[$type]) ?  $parent_types[$type] : 0;
+}
+
+//--------------------------------------------------------------------------------------------------
+function update_parent_line($doc_type, $line_id, $qty_dispatched)
+{
+       $doc_type = get_parent_type($doc_type);
+
+       //echo "update line: $line_id, $doc_type, $qty_dispatch";
+       if ($doc_type==0)
+               return false;
+       else {
+               if ($doc_type==30)
+                       $sql = "UPDATE ".TB_PREF."sales_order_details
+                               SET qty_sent = qty_sent + $qty_dispatched
+                               WHERE id=$line_id";
+               else
+                       $sql = "UPDATE ".TB_PREF."debtor_trans_details
+                               SET qty_done = qty_done + $qty_dispatched
+                               WHERE id=$line_id";
+       }
+       db_query($sql, "The parent document detail record could not be updated");
+       return true;
+}
+
+//--------------------------------------------------------------------------------------------------
+// find inventory location for given transaction
+//
+function get_location(&$cart)
+{
+       $sql = "SELECT ".TB_PREF."locations.* FROM ".TB_PREF."stock_moves,"
+               .TB_PREF."locations".
+               " WHERE type=".$cart->trans_type.
+               " AND trans_no=".key($cart->trans_no).
+               " AND qty!=0 ".
+               " AND ".TB_PREF."locations.loc_code=".TB_PREF."stock_moves.loc_code";
+       $result = db_query($sql, 'Retreiving inventory location');
+
+
+       if (db_num_rows($result)) {
+               return db_fetch($result);
+       }
+       return null;
+}
+//--------------------------------------------------------------------------------------------------
+// Generic read debtor transaction into cart
+//
+//     $trans_no - array of trans nums; special case trans_no==0 - new doc
+//
+function read_sales_trans($doc_type, $trans_no, &$cart)
+{
+       if (!is_array($trans_no) && $trans_no)
+                       $trans_no = array($trans_no);
+
+       $cart->trans_type = $doc_type;
+       if (!$trans_no) { // new document
+               $cart->trans_no = $trans_no;
+       } else {
+               // read header data from first document
+               $myrow = get_customer_trans($trans_no[0],$doc_type);
+               if (count($trans_no)>1)
+                       $cart->trans_no = get_customer_trans_version($doc_type, $trans_no);
+               else
+                       $cart->trans_no = array($trans_no[0]=>$myrow["version"]);
+
+               $cart->set_sales_type($myrow["tpe"], $myrow["sales_type"], $myrow["tax_included"]);
+
+               $cart->set_customer($myrow["debtor_no"], $myrow["DebtorName"],
+                       $myrow["curr_code"], $myrow["discount"]);
+
+               $cart->set_branch($myrow["branch_code"], $myrow["tax_group_id"],
+                       $myrow["tax_group_name"],       $myrow["phone"], $myrow["email"]);
+
+               $cart->reference = $myrow["reference"];
+               $cart->order_no = $myrow["order_"];
+               $cart->trans_link = $myrow["trans_link"];
+               $cart->due_date = sql2date($myrow["due_date"]);
+               $cart->document_date = sql2date($myrow["tran_date"]);
+
+               $cart->Comments = '';
+               foreach ( $trans_no as $trans ) {
+                       $coms =  get_comments($doc_type,$trans);
+                       while($row=db_fetch($coms)) {
+                               $text = $row['memo_'];
+                               if ($text!='') {
+                                       if ($cart->Comments!='')
+                                               $cart->Comments .= "\n";
+                                       $cart->Comments .= $text;
+                               }
+                       }
+               }
+
+               // FIX this should be calculated sum() for multiply parents
+
+               $cart->set_delivery($myrow["ship_via"], $myrow["br_name"],
+               $myrow["br_address"], $myrow["ov_freight"]);
+
+               $location = 0;
+               $myrow = get_location($cart); // find location from movement
+
+               if($myrow!=null) {
+                       $cart->set_location($myrow['loc_code'], $myrow['location_name']);
+               }
+
+               $result = get_customer_trans_details($doc_type,$trans_no);
+               if (db_num_rows($result) > 0) {
+                       for($line_no=0; $myrow = db_fetch($result); $line_no++) {
+                               $cart->add_to_cart($line_no,$myrow["stock_id"],$myrow["quantity"],
+                                       $myrow["unit_price"], $myrow["discount_percent"],
+                                       $myrow["qty_done"], $myrow["standard_cost"],
+                                       $myrow["StockDescription"],$myrow["id"], $myrow["debtor_trans_no"]);
+                       }
+               }
+       } // !newdoc
+
+       return true;
+}
+//----------------------------------------------------------------------------------------
 ?>
\ No newline at end of file
index a8abacab896ac79f81c51e770ccfeebcf4578bd3..64045bb155e78faddc5b1d1c2604bc30a5549cf7 100644 (file)
@@ -5,4 +5,27 @@ include_once($path_to_root . "/includes/date_functions.inc");
 include_once($path_to_root . "/includes/ui.inc");
 include_once($path_to_root . "/includes/banking.inc");
 
+//----------------------------------------------------------------------------
+// helper functions for script execution control
+//
+function processing_start()
+{
+    processing_end();
+    $_SESSION['Processing'] = $_SERVER['PHP_SELF'];
+}
+
+function processing_end()
+{
+    unset($_SESSION['Processing']);
+    if ( isset($_SESSION['Items']) ) {
+               unset($_SESSION['Items']->line_items);
+               unset($_SESSION['Items']);
+    }
+}
+
+function processing_active()
+{
+    return (isset($_SESSION['Processing']) && $_SESSION['Processing']==$_SERVER['PHP_SELF']);
+}
+
 ?>
\ No newline at end of file
index 9ee4d9c2280ee0a31bb61ef82c265392a25c5786..e63151fd08f5af6e7179b2262c56868ceb1bed1a 100644 (file)
@@ -1,9 +1,6 @@
 <?php
 /*
- To ma byæ co¶ do wywo³ywania reporting/rep107.php z odpowiednimi parametrami
+    This file is obsolete now.
 */
-function submit_print_invoice() {
- submit('PrintInvoice', _('Print invoice'), true);
-}
 
 ?>
\ No newline at end of file
index 7b7002291c11af3c9c1d3274ff6dc5d08ada8904..751d7bd30cb8ba7debccd5a31f573705375a86fb 100644 (file)
@@ -44,8 +44,12 @@ function display_credit_header(&$order)
 
        if (!isset($_POST['ref']))
                $_POST['ref'] = references::get_next(11);
+       if ($_SESSION['Items']->trans_no==0)
+           ref_row(_("Reference:"), 'ref');
+       else
+           label_row(_("Reference"), $_POST['ref'], "class='tableheader2'");
+       
 
-       ref_row(_("Reference:"), 'ref');
 
        echo "</table>";
 
@@ -75,13 +79,14 @@ function display_credit_header(&$order)
        echo "<table height='5'>";
 
        if (!isset($_POST['OrderDate']) || $_POST['OrderDate'] == "")
-               $_POST['OrderDate'] = $order->orig_order_date;
+               $_POST['OrderDate'] = $order->document_date;
 
        date_row(_("Date:"), 'OrderDate');
 
-       if (!isset($_POST['tax_group_id']) || $_POST['tax_group_id'] == "")
-               $_POST['tax_group_id'] = $order->tax_group_id;
-    tax_groups_list_row(_("Tax Group:"), 'tax_group_id', null, true);
+//     if (!isset($_POST['tax_group_id']) || $_POST['tax_group_id'] == "")
+//             $_POST['tax_group_id'] = $order->tax_group_id;
+//    tax_groups_list_row(_("Tax Group:"), 'tax_group_id', null, true);
+    shippers_list_row(_("Shipping Company:"), 'ShipperID', $order->ship_via);
 
        echo "</table>";
 
@@ -101,32 +106,39 @@ function display_credit_items($title, &$order)
        display_heading($title);
        start_table("$table_style width=90%");
        $th = array(_("Item Code"), _("Item Description"), _("Quantity"), _("Unit"),
-               _("Price"), _("Discount %"), _("Total"));
+               _("Price"), _("Discount %"), _("Total"),'');
+
+       if (count($order->line_items)) $th[]= '';
+
        table_header($th);
 
        $subtotal = 0;
        $k = 0;  //row colour counter
 
-       foreach ($order->line_items as $line)
+       foreach ($order->line_items as $line_no=>$line)
        {
+               $line_total =   $line->qty_dispatched * $line->price * (1 - $line->discount_percent);
+               if (!isset($_GET['Edit']))
+                       $id = -1;
+               else
+                       $id = $_GET['Edit'];
 
-               $line_total =   $line->quantity * $line->price * (1 - $line->discount_percent);
+                if ( $id != $line_no)
 
-               if (!isset($_GET['Edit']) || $_GET['Edit'] != $line->line_no)
                {
                alt_table_row_color($k);
 
                label_cell("<a target='_blank' href='$path_to_root/inventory/inquiry/stock_status.php?" . SID . "stock_id=" . $line->stock_id . "'>$line->stock_id</a>");
                label_cell($line->item_description);
-               qty_cell($line->quantity);
+               qty_cell($line->qty_dispatched);
                label_cell($line->units);
                amount_cell($line->price);
 
-                       amount_cell($line->discount_percent * 100);
+               amount_cell($line->discount_percent * 100);
                amount_cell($line_total);
 
-               edit_link_cell(SID . "Edit=$line->line_no");
-               delete_link_cell(SID . "Delete=$line->line_no");
+               edit_link_cell(SID . "Edit=$line_no");
+               delete_link_cell(SID . "Delete=$line_no");
 
                        //labelt_cell(get_tax_free_price_for_item($line->stock_id, $line_total, $_POST['tax_group_id']));
 
@@ -134,7 +146,7 @@ function display_credit_items($title, &$order)
                }
                else
                {
-                       credit_edit_item_controls($order, $line->stock_id);
+                       credit_edit_item_controls($order, $line_no);
                }
 
                $subtotal += $line_total;
@@ -151,9 +163,9 @@ function display_credit_items($title, &$order)
 
        text_row(_("Shipping"), 'ChargeFreightCost', $_POST['ChargeFreightCost'], 8, 8, "colspan=6 align=right");
 
-    $taxes = $order->get_taxes($_POST['tax_group_id'], $_POST['ChargeFreightCost']);
+    $taxes = $order->get_taxes($_POST['ChargeFreightCost']);
 
-       $tax_total = display_edit_tax_items($taxes, 6);
+       $tax_total = display_edit_tax_items($taxes, 6, $_SESSION['Items']->tax_included);
 
     $display_total = number_format2(($subtotal + $_POST['ChargeFreightCost'] + $tax_total), user_price_dec());
     label_row(_("Credit Note Total"), $display_total, "colspan=6 align=right","align=right");
@@ -163,37 +175,41 @@ function display_credit_items($title, &$order)
 
 //---------------------------------------------------------------------------------
 
-function credit_edit_item_controls(&$order, $stock_id=null)
+function credit_edit_item_controls(&$order, $line_no=-1)
 {
        start_row();
-
-       if (isset($_GET['Edit']) and $stock_id!=null)
+       if (isset($_GET['Edit']) && $line_no != -1)
        {
-               $line_no = $_GET['Edit'];
-               hidden('line_no', $line_no);
 
                if (!isset($_POST['stock_id']))
-                       $_POST['stock_id'] = $order->line_items[$line_no]->stock_id;
-               if (!isset($_POST['qty']) OR ($_POST['qty']==""))
-                       $_POST['qty'] = $order->line_items[$line_no]->quantity;
-               if (!isset($_POST['price']) OR ($_POST['price']==""))
-                       $_POST['price'] = $order->line_items[$line_no]->price;
-               if (!isset($_POST['Disc']) OR ($_POST['Disc']==""))
-                       $_POST['Disc'] = ($order->line_items[$line_no]->discount_percent)*100;
+                       $_POST['stock_id'] = $order->line_items[$_GET['Edit']]->stock_id;
+               if (!isset($_POST['qty']) || ($_POST['qty']==""))
+                       $_POST['qty'] = $order->line_items[$_GET['Edit']]->qty_dispatched;
+               if (!isset($_POST['price']) || ($_POST['price']==""))
+                       $_POST['price'] = $order->line_items[$_GET['Edit']]->price;
+               if (!isset($_POST['Disc']) || ($_POST['Disc']==""))
+                       $_POST['Disc'] = ($order->line_items[$_GET['Edit']]->discount_percent)*100;
 
-               $_POST['units'] = $order->line_items[$line_no]->units;
+               $_POST['units'] = $order->line_items[$_GET['Edit']]->units;
 
                hidden('stock_id', $_POST['stock_id']);
                label_cell($_POST['stock_id']);
-               label_cell($order->line_items[$line_no]->item_description);
+               label_cell($order->line_items[$_GET['Edit']]->item_description);
        }
        else
        {
-               hidden('line_no', ($_SESSION['credit_items']->lines_on_order + 1));
-       echo "<td colspan=2>";
-       stock_items_list('stock_id', null, false, true);
-       echo "</td>";
-
+               global $no_item_list; 
+               if ($no_item_list)
+               {
+                       echo "<td colspan=2>\n";
+                       stock_items_list('stock_id', null, false, true);
+                       echo "</td>\n";
+               }
+               else
+               {
+                 text_cells(null, "StockID2", "", 12, 10, "", "", "onkeyup='recalcAccounts();' onKeyDown='if (event.keyCode==13) event.keyCode=9;' onblur='return setAccount(0, true);'");
+                       stock_items_list_cells(null, 'stock_id', null, false, false, "onchange='return setAccount(1, true)'");
+               }
        $item_info = get_item_edit_info($_POST['stock_id']);
 
                $_POST['units'] = $item_info["units"];
@@ -206,15 +222,20 @@ function credit_edit_item_controls(&$order, $stock_id=null)
 
 
        text_cells(null, 'qty', $_POST['qty'], 13, 15);
+//     if ($order->trans_no!=0) {
+//             amount_cell($line_no==-1 ? 0 :$order->line_items[$line_no]->qty_done);
+//     }
        label_cell($_POST['units']);
        text_cells(null, 'price',  null, 13, 15);
        text_cells(null, 'Disc', $_POST['Disc'], 7, 5);
+
        amount_cell($_POST['qty'] * $_POST['price'] * (1 - $_POST['Disc']/100));
 
        if (isset($_GET['Edit']))
        {
        submit_cells('UpdateItem', _("Update"));
        submit_cells('CancelItemChanges', _("Cancel"));
+               hidden('LineNo', $line_no);
        }
        else
        {
@@ -240,7 +261,7 @@ function credit_options_controls()
 
                /*if the credit note is a return of goods then need to know which location to receive them into */
                if (!isset($_POST['Location']))
-                       $_POST['Location'] = $_SESSION['credit_items']->Location;
+                       $_POST['Location'] = $_SESSION['Items']->Location;
                locations_list_row(_("Items Returned to Location"), 'Location', $_POST['Location']);
 
        }
index c5a8d317d0923bf0da65efbed72fe7fcbc4816dc..ead41ed92fc165ad06f654e89e8d9d5e332f5f43 100644 (file)
@@ -17,7 +17,7 @@ function add_to_order(&$order, $new_item, $new_item_qty, $price, $discount)
                }
        }
     
-       $order->add_to_cart ($new_item, $new_item_qty, $price, $discount);
+       $order->add_to_cart (count($order->line_items),$new_item, $new_item_qty, $price, $discount);
 }
 
 //---------------------------------------------------------------------------------
@@ -25,69 +25,50 @@ function add_to_order(&$order, $new_item, $new_item_qty, $price, $discount)
 function get_customer_details_to_order(&$order, $customer_id, $branch_id)
 {
        $ret_error = "";
-       // Now check to ensure this account is not on hold */
-       $sql = "SELECT ".TB_PREF."debtors_master.name, ".TB_PREF."debtors_master.address, ".TB_PREF."credit_status.dissallow_invoices,
-               ".TB_PREF."debtors_master.sales_type AS salestype, ".TB_PREF."sales_types.sales_type, ".TB_PREF."debtors_master.curr_code,
-               ".TB_PREF."debtors_master.discount
-               FROM ".TB_PREF."debtors_master, ".TB_PREF."credit_status, ".TB_PREF."sales_types
-               WHERE ".TB_PREF."debtors_master.sales_type=".TB_PREF."sales_types.id
-                       AND ".TB_PREF."debtors_master.credit_status=".TB_PREF."credit_status.id
-                       AND ".TB_PREF."debtors_master.debtor_no = '" . $customer_id . "'";
 
-       $result =db_query($sql,"Customer Record Retreive");
-
-       $myrow = db_fetch($result);
-
-       $order->customer_id = $customer_id;
-       $order->Branch = $branch_id;
-       $order->customer_name = $myrow['name'];
+       $myrow = get_customer_to_order($customer_id);
+       
+       $name = $myrow['name'];
 
        if ($myrow['dissallow_invoices'] == 1)
                $ret_error = _("The selected customer account is currently on hold. Please contact the credit control personnel to discuss.");
 
-       if (!isset($_POST['branch_id']) || $_POST['branch_id'] == "") 
+/*     if (!isset($_POST['branch_id']) || $_POST['branch_id'] == "") 
        {
                $ret_error = _("The selected customer does not have any branches. Please create at least one branch.");
                unset($_POST['branch_id']);
-               $order->Branch = "";
+               $order->Branch = 0;
        }
+*/
+       $deliver = $myrow['address']; // in case no delivery address.
+
+       $order->set_customer($customer_id, $name, $myrow['curr_code'], $myrow['discount']);
 
-       # the sales type determines the price list to be used by default
-       $order->default_sales_type = $myrow['salestype'];
-       $order->sales_type_name = $myrow['sales_type'];
-       $order->customer_currency = $myrow['curr_code'];
-       $order->default_discount = $myrow['discount'];
-       $deliver = $myrow['address']; // in case no deliveraddress.
+       // the sales type determines the price list to be used by default
+    $order->set_sales_type($myrow['salestype'], $myrow['sales_type'], $myrow['tax_included']);
 
-       if ($order->Branch != "")
+//     if ($order->Branch != 0)
        {
-       # the branch was also selected from the customer selection so default the delivery details from the customer branches table cust_branch. The order process will ask for branch details later anyway
-               $sql = "SELECT ".TB_PREF."cust_branch.br_name, ".TB_PREF."cust_branch.br_post_address, phone, email,
-                       default_location, default_ship_via,
-                       ".TB_PREF."tax_groups.name AS tax_group_name, ".TB_PREF."tax_groups.id AS tax_group_id
-                       FROM ".TB_PREF."cust_branch, ".TB_PREF."tax_groups
-                               WHERE ".TB_PREF."cust_branch.tax_group_id = ".TB_PREF."tax_groups.id
-                                       AND ".TB_PREF."cust_branch.branch_code='" . $order->Branch . "'
-                                       AND ".TB_PREF."cust_branch.debtor_no = '" . $order->customer_id . "'";
-
-       $result = db_query($sql,"Customer Branch Record Retreive");
-
-       if (db_num_rows($result) == 0)
-       {
-                       return _("The selected customer and branch are not valid, or the customer does not have any branches.");
+               $result = get_branch_to_order($customer_id, $branch_id);
+
+           if (db_num_rows($result) == 0)
+           {
+                 return _("The selected customer and branch are not valid, or the customer does not have any branches.");
        }
 
        $myrow = db_fetch($result);
-       $order->deliver_to = $myrow["br_name"];
-       $order->delivery_address = $myrow["br_post_address"];
-       if (strlen($order->delivery_address) <= 1)
-               $order->delivery_address = $deliver;
-       $order->phone = $myrow["phone"];
-       $order->email = $myrow["email"];
-       $order->Location = $myrow["default_location"];
-       $order->ship_via = $myrow["default_ship_via"];
-               $order->tax_group_name = $myrow["tax_group_name"];
-               $order->tax_group_id = $myrow["tax_group_id"];
+
+               $order->set_branch($branch_id, $myrow["tax_group_id"],
+                 $myrow["tax_group_name"], $myrow["phone"], $myrow["email"]);
+
+       $address = $myrow["br_post_address"];
+
+       if (strlen($address) <= 1)      // if branch has no address 
+                 $address = $deliver;  // set sales order address
+
+               $order->set_location($myrow["default_location"], $myrow["location_name"]);
+               $order->set_delivery($myrow["default_ship_via"], $myrow["br_name"], 
+                 $address);
        }
 
        return $ret_error;
@@ -102,9 +83,14 @@ function display_order_summary($title, &$order, $editable_items=false)
        display_heading($title);
        start_table("$table_style colspan=7 width=90%");
        $th = array(_("Item Code"), _("Item Description"), _("Quantity"),
+                _("Delivered"),
                _("Unit"), _("Price"), _("Discount %"), _("Total"), "");
 
-       if(count($order->line_items)) $th[]= '';
+       if ($order->trans_no==0) {
+         unset( $th[3] );
+       }
+
+       if (count($order->line_items)) $th[]= '';
 
        table_header($th);      
 
@@ -114,12 +100,13 @@ function display_order_summary($title, &$order, $editable_items=false)
        foreach ($order->line_items as $line_no=>$stock_item) 
        {
 
-               $line_total = $stock_item->quantity * $stock_item->price * (1 - $stock_item->discount_percent);
+               $line_total = $stock_item->qty_dispatched * $stock_item->price * (1 - $stock_item->discount_percent);
  
                if (!isset($_GET['Edit']))
                        $id = -1;
                else
                        $id = $_GET['Edit'];
+
                if (!$editable_items || $id != $line_no)
                {
                alt_table_row_color($k);
@@ -127,7 +114,11 @@ function display_order_summary($title, &$order, $editable_items=false)
                        view_stock_status_cell($stock_item->stock_id);
                
                label_cell($stock_item->item_description);
-               qty_cell($stock_item->quantity);
+               qty_cell($stock_item->qty_dispatched);
+
+                       if ($order->trans_no!=0) 
+                 amount_cell($stock_item->qty_done);
+
                label_cell($stock_item->units);
                amount_cell($stock_item->price);
 
@@ -153,7 +144,7 @@ function display_order_summary($title, &$order, $editable_items=false)
                sales_order_item_controls($order);
 
        $display_total = number_format2($total,user_price_dec());
-       label_row(_("Total Excluding Tax/Shipping"), $display_total, "colspan=6 align=right",
+       label_row(_("Total Excluding Shipping"), $display_total, "colspan=6 align=right",
                "nowrap align=right");
 
        end_table();
@@ -174,47 +165,83 @@ function display_order_header(&$order, $editable, $date_text, $display_tax_group
        {
                // can't change the customer/branch if items already received on this order
                echo $order->customer_name . " - " . $order->deliver_to;
+           hidden('customer_id', $order->customer_id);
+           hidden('branch_id', $order->Branch);
        } 
        else 
        {
 
-        if (!isset($_POST['customer_id']) && (get_global_customer() != reserved_words::get_all()))
-               $_POST['customer_id'] = get_global_customer();
+           if (!isset($_POST['customer_id']) && (get_global_customer() != reserved_words::get_all()))
+                   $_POST['customer_id'] = get_global_customer();
 
-               customer_list_row(_("Customer:"), 'customer_id', null, false, true);
+           customer_list_row(_("Customer:"), 'customer_id', null, false, true);
 
-               if (!isset($_POST['delivery_date']))
-               {
-                       if ($order->trans_type=='invoice')
-                               $_POST['delivery_date'] = $_SESSION['Items']->delivery_date = 
+           if (!isset($_POST['delivery_date']))
+           {
+                       if ($order->trans_type==10)
+                               $_POST['delivery_date'] = $_SESSION['Items']->due_date = 
                                        get_invoice_duedate($_POST['customer_id'], $_POST['OrderDate']);
                        else    
-                               $_POST['delivery_date'] = $_SESSION['Items']->delivery_date = 
-                                       add_days($_POST['OrderDate'], 10);
-               }               
+                               $_POST['delivery_date'] = $_SESSION['Items']->due_date = 
+                                       add_days($_POST['OrderDate'], 10); // FIX this should be in company prefs
+           }           
                if ($order->customer_id != $_POST['customer_id']) 
-               {
+           {
                        // customer has changed
 
                        // delete all the order items - drastic but necessary because of
                        // change of currency, sales type, etc
-               $order->clear_items();
-
+       //      $order->clear_items();
                        // clear the branch selection
                        unset($_POST['branch_id']);
-               }
+           }
+           if (!isset($_POST['branch_id']))
+                       $_POST['branch_id'] = "";
 
                customer_branches_list_row(_("Branch:"), $_POST['customer_id'], 'branch_id', null, false, true, true);
 
-               if (!isset($_POST['branch_id']))
-                       $_POST['branch_id'] = "";
+       if (!isset($_POST['branch_id']) || $_POST['branch_id'] == "") 
+       {
+               $customer_error = _("The selected customer does not have any branches. Please create at least one branch.");
+               unset($_POST['branch_id']);
+               $order->Branch = 0;
+       } else 
+       
+       {
+
                //set_global_customer($_POST['customer_id']);
-               if (($order->customer_id != $_POST['customer_id']) || 
-                       ($order->Branch != $_POST['branch_id']))
-                       $customer_error = get_customer_details_to_order($order, $_POST['customer_id'], $_POST['branch_id']);
+           if (($order->customer_id != $_POST['customer_id']) || 
+               ($order->Branch != $_POST['branch_id'])) {
+                 $old_order = $order;
+                 $customer_error = get_customer_details_to_order($order, $_POST['customer_id'], $_POST['branch_id']);
+                 $_POST['Location'] = $order->Location;
+                 $_POST['deliver_to'] = $order->deliver_to;
+                 $_POST['delivery_address'] = $order->delivery_address;
+                 $_POST['phone'] = $order->phone;
+
+               // change prices if necessary
+               // what about discount in template case?
+                 if ( $old_order->customer_currency!=$order->customer_currency
+                   || $old_order->default_sales_type!=$order->default_sales_type
+               //  || $old_order->default_discount!=$order->default_discount
+                   ) {
+                       
+                   foreach ($order->line_items as $line_no=>$item) {
+                               $line = &$order->line_items[$line_no];
+                               $line->price = get_price($line->stock_id, $order->customer_id);
+               //              $line->discount_percent = $order->default_discount;
+                   }
+               }
+                 
+           }
+        }
+           set_global_customer($_POST['customer_id']);
+       }
 
-               set_global_customer($_POST['customer_id']);
+       if ($_SESSION['Items']->trans_type!=30) {
+               ref_cells(_("Reference").':', 'ref', null, "");
        }
+
        echo "</table>";
 
        echo "</td><td>"; // outer table
@@ -224,7 +251,7 @@ function display_order_header(&$order, $editable, $date_text, $display_tax_group
                echo "<table height='5'>";
                label_row(_("Customer Currency:"), $order->customer_currency);
                exchange_rate_display($order->customer_currency, get_company_currency(),        
-                       ($editable?$_POST['OrderDate']:$order->orig_order_date), $editable);
+                       ($editable?$_POST['OrderDate']:$order->document_date), $editable);
                echo "</table>";
                echo "</td><td>"; // outer table
        }
@@ -241,26 +268,26 @@ function display_order_header(&$order, $editable, $date_text, $display_tax_group
        if ($editable) 
        {
        if (!isset($_POST['OrderDate']) || $_POST['OrderDate'] == "")
-               $_POST['OrderDate'] = $order->orig_order_date;
+               $_POST['OrderDate'] = $order->document_date;
 
                date_row($date_text, 'OrderDate');
        }
        else 
        {
-               label_row($date_text, $order->orig_order_date);
-               hidden('OrderDate', $order->orig_order_date);
+               label_row($date_text, $order->document_date);
+               hidden('OrderDate', $order->document_date);
        }
 
        if ($display_tax_group) 
        {
-               if ($editable) 
+/*             if ($editable) 
                {
             if (!isset($_POST['tax_group_id']))
                $_POST['tax_group_id'] = $_SESSION['Items']->tax_group_id;
             tax_groups_list_row(_("Tax Group:"), 'tax_group_id', $_POST['tax_group_id'], true);
                } 
                else 
-               {
+*/             {
                        label_row(_("Tax Group:"), $order->tax_group_name);
                        hidden('tax_group_id', $_SESSION['Items']->tax_group_id);
                }
@@ -284,7 +311,7 @@ function sales_order_item_controls(&$order, $line_no=-1)
                if (!isset($_POST['stock_id']))
                        $_POST['stock_id'] = $order->line_items[$_GET['Edit']]->stock_id;
                if (!isset($_POST['qty']) || ($_POST['qty'] == ""))
-                       $_POST['qty'] = $order->line_items[$_GET['Edit']]->quantity;
+                       $_POST['qty'] = $order->line_items[$_GET['Edit']]->qty_dispatched;
                if (!isset($_POST['price']) || ($_POST['price'] == ""))
                        $_POST['price'] = $order->line_items[$_GET['Edit']]->price;
                if (!isset($_POST['Disc']) || ($_POST['Disc'] == ""))
@@ -306,7 +333,7 @@ function sales_order_item_controls(&$order, $line_no=-1)
                }
                else
                {
-                 text_cells(null, "StockID2", "", 12, 10, "", "", "onkeyup='recalcAccounts();' onKeyDown='if(event.keyCode==13) event.keyCode=9;' onblur='return setAccount(0, true);'");
+                 text_cells(null, "StockID2", "", 12, 10, "", "", "onkeyup='recalcAccounts();' onKeyDown='if (event.keyCode==13) event.keyCode=9;' onblur='return setAccount(0, true);'");
                        stock_items_list_cells(null, 'stock_id', null, false, false, "onchange='return setAccount(1, true)'");
                }
                $item_info = get_item_edit_info($_POST['stock_id']);
@@ -320,6 +347,10 @@ function sales_order_item_controls(&$order, $line_no=-1)
 
        text_cells(null, 'qty', $_POST['qty'], 12, 15);
 
+       if ($order->trans_no!=0) {
+               amount_cell($line_no==-1 ? 0 :$order->line_items[$line_no]->qty_done);
+       }
+
        label_cell($_POST['units']);
        amount_cells(null, 'price');
        text_cells(null, 'Disc', $_POST['Disc'], 7, 5);
@@ -346,16 +377,20 @@ function sales_order_item_controls(&$order, $line_no=-1)
 function display_delivery_details(&$order)
 {
        global $table_style2;
-
-       if ($order->trans_type=='invoice') 
+       if ($order->trans_type==10) 
+       {
+               $title = _("Delivery Details");
+               $delname = _("Due Date").':';
+       } 
+       elseif ($order->trans_type==13) 
        {
                $title = _("Invoice Delivery Details");
-               $delname = _("Due Date");
+               $delname = _("Invoice before").':';
        } 
        else 
        {
                $title = _("Order Delivery Details");
-               $delname = _("Required Delivery Date:");
+               $delname = _("Required Delivery Date").':';
        }
        display_heading($title);
     echo "<br>";
@@ -363,9 +398,12 @@ function display_delivery_details(&$order)
     echo "<tr valign=top><td>"; // outer table
 
     echo "<table>";
-    locations_list_row(_("Deliver from Location:"), 'Location', $order->Location);
 
-       date_row($delname, 'delivery_date', $order->delivery_date, 0, 0, 0);
+//     echo $order->Location, $_POST['Location'];
+
+    locations_list_row(_("Deliver from Location:"), 'Location', $_POST['Location']);
+
+       date_row($delname, 'delivery_date', $order->due_date, 0, 0, 0);
 
     text_row(_("Deliver To:"), 'deliver_to', $order->deliver_to, 40, 40);
 
@@ -384,8 +422,7 @@ function display_delivery_details(&$order)
     text_row(_("Shipping Charge:"), 'freight_cost', $order->freight_cost, 10, 10);
 
     shippers_list_row(_("Shipping Company:"), 'ship_via', $order->ship_via);
-       if ($_SESSION['Items']->trans_type=='delivery') 
-               textarea_row(_("Memo"), 'InvoiceText', null, 31, 3);
+
     echo "</table>";
 
     echo "</td></tr>";
index f8cc1afc04de81fa44aa78697e573d765b5fefd8..62cc4e9d694040fe2449db002acf3d98624a5c4e 100644 (file)
@@ -55,14 +55,16 @@ function get_transactions()
 
     $sql = "SELECT ".TB_PREF."debtor_trans.*,
                ".TB_PREF."debtors_master.name AS CustName, ".TB_PREF."debtors_master.curr_code AS CustCurrCode,
-       (".TB_PREF."debtor_trans.ov_amount + ".TB_PREF."debtor_trans.ov_gst + ".TB_PREF."debtor_trans.ov_freight + ".TB_PREF."debtor_trans.ov_discount)
+       (".TB_PREF."debtor_trans.ov_amount + ".TB_PREF."debtor_trans.ov_gst + "
+       .TB_PREF."debtor_trans.ov_freight + ".TB_PREF."debtor_trans.ov_freight_tax + ".TB_PREF."debtor_trans.ov_discount)
                AS TotalAmount,
                ".TB_PREF."debtor_trans.alloc AS Allocated,
                ((".TB_PREF."debtor_trans.type = 10)
                AND ".TB_PREF."debtor_trans.due_date < '" . date2sql(Today()) . "') AS OverDue
        FROM ".TB_PREF."debtor_trans, ".TB_PREF."debtors_master
        WHERE ".TB_PREF."debtors_master.debtor_no = ".TB_PREF."debtor_trans.debtor_no
-                       AND (".TB_PREF."debtor_trans.ov_amount + ".TB_PREF."debtor_trans.ov_gst + ".TB_PREF."debtor_trans.ov_freight + ".TB_PREF."debtor_trans.ov_discount != 0)
+                       AND (".TB_PREF."debtor_trans.ov_amount + ".TB_PREF."debtor_trans.ov_gst + "
+                       .TB_PREF."debtor_trans.ov_freight + ".TB_PREF."debtor_trans.ov_freight_tax + ".TB_PREF."debtor_trans.ov_discount != 0)
                AND ".TB_PREF."debtor_trans.tran_date >= '$data_after'
                AND ".TB_PREF."debtor_trans.tran_date <= '$date_to'";
 
@@ -88,7 +90,9 @@ function get_transactions()
        {
                $today =  date2sql(Today());
                $sql .= " AND ".TB_PREF."debtor_trans.due_date < '$today'
-                               AND (round(abs(".TB_PREF."debtor_trans.ov_amount + ".TB_PREF."debtor_trans.ov_gst + ".TB_PREF."debtor_trans.ov_freight + ".TB_PREF."debtor_trans.ov_discount) - ".TB_PREF."debtor_trans.alloc,6) > 0) ";
+                               AND (round(abs(".TB_PREF."debtor_trans.ov_amount + "
+                               .TB_PREF."debtor_trans.ov_gst + ".TB_PREF."debtor_trans.ov_freight + "
+                               .TB_PREF."debtor_trans.ov_freight_tax + ".TB_PREF."debtor_trans.ov_discount) - ".TB_PREF."debtor_trans.alloc,6) > 0) ";
        }
        }else
        {
@@ -98,7 +102,9 @@ function get_transactions()
 
        if (!check_value('showSettled')) 
        {
-               $sql .= " AND (round(abs(".TB_PREF."debtor_trans.ov_amount + ".TB_PREF."debtor_trans.ov_gst + ".TB_PREF."debtor_trans.ov_freight + ".TB_PREF."debtor_trans.ov_discount) - ".TB_PREF."debtor_trans.alloc,6) != 0) ";
+               $sql .= " AND (round(abs(".TB_PREF."debtor_trans.ov_amount + ".TB_PREF."debtor_trans.ov_gst + "
+               .TB_PREF."debtor_trans.ov_freight + ".TB_PREF."debtor_trans.ov_freight_tax + "
+               .TB_PREF."debtor_trans.ov_discount) - ".TB_PREF."debtor_trans.alloc,6) != 0) ";
        }
 
     $sql .= " ORDER BY ".TB_PREF."debtor_trans.tran_date";
index 69feee5fbb8b2bd5fea6ce23a9ed8a7181b662bb..57725f38ae833154923911d50a5d98c027d2f60e 100644 (file)
@@ -6,6 +6,7 @@ include_once($path_to_root . "/includes/session.inc");
 
 include_once($path_to_root . "/sales/includes/sales_ui.inc");
 include_once($path_to_root . "/sales/includes/sales_db.inc");
+include_once($path_to_root . "/reporting/includes/reporting.inc");
 
 $js = "";
 if ($use_popup_windows)
@@ -91,7 +92,8 @@ function get_transactions()
 
     $sql = "SELECT ".TB_PREF."debtor_trans.*,
                ".TB_PREF."debtors_master.name AS CustName, ".TB_PREF."debtors_master.curr_code AS CustCurrCode,
-               (".TB_PREF."debtor_trans.ov_amount + ".TB_PREF."debtor_trans.ov_gst + ".TB_PREF."debtor_trans.ov_freight + ".TB_PREF."debtor_trans.ov_discount)
+               (".TB_PREF."debtor_trans.ov_amount + ".TB_PREF."debtor_trans.ov_gst + "
+               .TB_PREF."debtor_trans.ov_freight + ".TB_PREF."debtor_trans.ov_freight_tax + ".TB_PREF."debtor_trans.ov_discount)
                AS TotalAmount, ".TB_PREF."debtor_trans.alloc AS Allocated,
                ((".TB_PREF."debtor_trans.type = 10)
                        AND ".TB_PREF."debtor_trans.due_date < '" . date2sql(Today()) . "') AS OverDue
@@ -130,7 +132,9 @@ function get_transactions()
        {
                $today =  date2sql(Today());
                $sql .= " AND ".TB_PREF."debtor_trans.due_date < '$today'
-                               AND (".TB_PREF."debtor_trans.ov_amount + ".TB_PREF."debtor_trans.ov_gst + ".TB_PREF."debtor_trans.ov_freight + ".TB_PREF."debtor_trans.ov_discount - ".TB_PREF."debtor_trans.alloc > 0) ";
+                               AND (".TB_PREF."debtor_trans.ov_amount + ".TB_PREF."debtor_trans.ov_gst + "
+                               .TB_PREF."debtor_trans.ov_freight_tax + ".TB_PREF."debtor_trans.ov_freight + "
+                               .TB_PREF."debtor_trans.ov_discount - ".TB_PREF."debtor_trans.alloc > 0) ";
        }
        }
 
@@ -164,12 +168,14 @@ if (db_num_rows($result) == 0)
 
 start_table("$table_style width='80%'");
 
-if ($_POST['customer_id'] == reserved_words::get_all())
        $th = array(_("Type"), _("#"), _("Order"), _("Reference"), _("Date"), _("Due Date"),
-               _("Customer"), _("Branch"), _("Currency"), _("Debit"), _("Credit"), "", "","");
-else           
-       $th = array(_("Type"), _("#"), _("Order"), _("Reference"), _("Date"), _("Due Date"),
-               _("Branch"), _("Debit"), _("Credit"), "", "","");
+               _("Customer"), _("Branch"), _("Currency"), _("Debit"), _("Credit"), "", "",""
+               /*,"" print */);
+
+if ($_POST['customer_id'] != reserved_words::get_all()) {
+  unset($th[6], $th[8]);
+}
+
 table_header($th);
 
 
@@ -193,14 +199,24 @@ while ($myrow = db_fetch($result))
 
        switch($myrow['type']) {
         case 10:
-                       $due_date_str = sql2date($myrow["due_date"]);
+               $due_date_str = sql2date($myrow["due_date"]);
                        /*Show a link to allow an invoice to be credited */
-                       // only allow crediting if it's not been totally allocated
-                       if ($myrow["TotalAmount"] - $myrow["Allocated"] > 0)
-                               $credit_me_str = "<a href='$path_to_root/sales/customer_credit_invoice.php?InvoiceNumber=" . $myrow["trans_no"] . "'>" . _("Credit This") . "</a>";
-                 $edit_page= $path_to_root.'/sales/customer_invoice.php?ModifyInvoice='
+                   // only allow crediting if it's not been totally allocated
+               if ($myrow["TotalAmount"] - $myrow["Allocated"] > 0)
+                       $credit_me_str = "<a href='$path_to_root/sales/customer_credit_invoice.php?InvoiceNumber=" . $myrow["trans_no"] . "'>" . _("Credit This") . "</a>";
+               $edit_page= $path_to_root.'/sales/customer_invoice.php?ModifyInvoice='
                                        . $myrow['trans_no']; 
-                       break;
+               break;
+
+        case 11:
+               if ($myrow['order_']==0) // free-hand credit note
+                   $edit_page= $path_to_root.'/sales/credit_note_entry.php?ModifyCredit='
+                                       . $myrow['trans_no']; 
+               else    // credit invoice
+                   $edit_page= $path_to_root.'/sales/customer_credit_invoice.php?ModifyCredit='
+                                       . $myrow['trans_no'];       
+               break;
+        
         case 13:
                $edit_page= $path_to_root.'/sales/customer_delivery.php?ModifyDelivery='
                                        . $myrow['trans_no']; break;
@@ -238,16 +254,20 @@ while ($myrow = db_fetch($result))
        label_cell($branch_name);
        if ($_POST['customer_id'] == reserved_words::get_all())
                label_cell($myrow["CustCurrCode"]);
-       display_debit_or_credit_cells($myrow["TotalAmount"]);
+       display_debit_or_credit_cells(
+           $myrow['type']==11 || $myrow['type']==12 ? 
+               -$myrow["TotalAmount"] : $myrow["TotalAmount"]);
+
        echo $gl_trans_str;
 
   label_cell($edit_page=='' ? '' :     "<a href='$edit_page'>" . _('Edit') . '</a>');
+//  label_cell(print_document_link($myrow['trans_no'], _("Print")));   
        
        if ($credit_me_str != "")
                label_cell($credit_me_str, "nowrap");
        else
                label_cell('');
-       
+
 //     if ($myrow["type"] == 10)
 //             label_cell($print_str, 'nowrap');
 //     else
index 0a08e3f01deeded2d4f98be28c01fc3f9e6b446f..2a0b017d88485a9913bed5a506abcfc4be71a4aa 100644 (file)
@@ -34,18 +34,18 @@ elseif (isset($_POST['selected_customer']))
 else
        $selected_customer = -1;
        
-if(isset($_POST['BatchInvoice'])) {
+if (isset($_POST['BatchInvoice'])) {
 
 // checking batch integrity
     $del_count = 0;
     foreach($_SESSION['Batch'] as $delivery) {
          $checkbox = 'Sel_'.$delivery['trans'];
-         if(check_value($checkbox)) {
-           if(!$del_count) {
+         if (check_value($checkbox)) {
+           if (!$del_count) {
                $del_customer = $delivery['cust'];
                $del_branch = $delivery['branch'];
            } else {
-               if($del_customer!=$delivery['cust'] || $del_branch != $delivery['branch']) {
+               if ($del_customer!=$delivery['cust'] || $del_branch != $delivery['branch']) {
                    $del_count=0; break;
                }
            }
@@ -54,7 +54,7 @@ if(isset($_POST['BatchInvoice'])) {
          }
     }
 
-    if(!$del_count) {
+    if (!$del_count) {
                display_error(_('For batch invoicing you should 
                    select at least one delivery. All items must be dispatched to
                    the same customer branch.'));
@@ -107,14 +107,17 @@ $sql = "SELECT ".TB_PREF."debtor_trans.trans_no, "
        .TB_PREF."debtor_trans.due_date, "
        .TB_PREF."sales_orders.customer_ref, "
        .TB_PREF."sales_orders.deliver_to, ";
-$sql .= " Sum(".TB_PREF."debtor_trans_details.qty_done-"
-                .TB_PREF."debtor_trans_details.quantity) AS Outstanding, ";
-$sql .= " Sum(".TB_PREF."debtor_trans_details.qty_done) AS Partial, ";
-
-$sql .= " Sum(-".TB_PREF."debtor_trans_details.unit_price*"
- .TB_PREF."debtor_trans_details.quantity*(1-"
- .TB_PREF."debtor_trans_details.discount_percent)) AS DeliveryValue
-       FROM "
+
+$sql .= " Sum(".TB_PREF."debtor_trans_details.quantity-"
+                .TB_PREF."debtor_trans_details.qty_done) AS Outstanding, ";
+
+$sql .= " Sum(".TB_PREF."debtor_trans_details.qty_done) AS Done, ";
+
+//$sql .= " Sum(".TB_PREF."debtor_trans_details.unit_price*"
+// .TB_PREF."debtor_trans_details.quantity*(1-"
+// .TB_PREF."debtor_trans_details.discount_percent)) AS DeliveryValue";
+$sql .= "(ov_amount+ov_gst+ov_freight+ov_freight_tax) AS DeliveryValue";
+$sql .=" FROM "
         .TB_PREF."sales_orders, "
         .TB_PREF."debtor_trans, "
         .TB_PREF."debtor_trans_details, "
@@ -153,7 +156,7 @@ else
                $sql .= " AND ".TB_PREF."sales_orders.from_stk_loc = '". $_POST['StockLocation'] . "' ";
 
        if ($_POST['OutstandingOnly'] == true) {
-        $sql .= " AND -".TB_PREF."debtor_trans_details.qty_done < -".TB_PREF."debtor_trans_details.quantity ";
+        $sql .= " AND ".TB_PREF."debtor_trans_details.qty_done < ".TB_PREF."debtor_trans_details.quantity ";
        }
        
        $sql .= " GROUP BY ".TB_PREF."debtor_trans.trans_no ";
@@ -167,7 +170,7 @@ else
 $result = db_query($sql,"No deliveries were returned");
 
 //-----------------------------------------------------------------------------------
-if(isset($_SESSION['Batch'])) {
+if (isset($_SESSION['Batch'])) {
     foreach($_SESSION['Batch'] as $trans=>$del) unset($_SESSION['Batch'][$trans]);
     unset($_SESSION['Batch']);
 }
@@ -187,7 +190,7 @@ if ($result)
        $k = 0; //row colour counter
        $overdue_items = false;
        while ($myrow = db_fetch($result)) 
-       {
+       { 
            $_SESSION['Batch'][] = array('trans'=>$myrow["trans_no"],
            'cust'=>$myrow["name"],'branch'=>$myrow["br_name"] );
            
@@ -216,7 +219,7 @@ if ($result)
                label_cell($formated_due_date);
                amount_cell($myrow["DeliveryValue"]);
                label_cell($myrow["curr_code"]);
-               if(!$myrow['Partial'])
+               if (!$myrow['Done'])
                    check_cells(null,'Sel_'. $myrow['trans_no'],0,false);
                else
                    label_cell("");
index e34e3ab9aaf41b1701837461a357bf144a247fb7..b5af5158fdf6123cac64536a5ffcd5b2896943a9 100644 (file)
@@ -14,15 +14,27 @@ if ($use_date_picker)
 
 if (isset($_GET['OutstandingOnly']) && ($_GET['OutstandingOnly'] == true)) 
 {
-       $_POST['OutstandingOnly'] = true;
-       page(_("Search Outstanding Sales Orders"), false, false, "", $js);
+       $_POST['order_view_mode'] = 'OutstandingOnly';
+       $_SESSION['page_title'] = _("Search Outstanding Sales Orders");
 } 
-else 
+elseif (isset($_GET['InvoiceTemplates']) && ($_GET['InvoiceTemplates'] == true)) 
+{
+       $_POST['order_view_mode'] = 'InvoiceTemplates';
+       $_SESSION['page_title'] = _("Search Template for Invoicing");
+} 
+elseif (isset($_GET['DeliveryTemplates']) && ($_GET['DeliveryTemplates'] == true)) 
+{
+       $_POST['order_view_mode'] = 'DeliveryTemplates';
+       $_SESSION['page_title'] = _("Select Template for Delivery");
+}
+elseif (!isset($_POST['order_view_mode']))
 {
-       $_POST['OutstandingOnly'] = false;
-       page(_("Search All Sales Orders"), false, false, "", $js);
+       $_POST['order_view_mode'] = false;
+       $_SESSION['page_title'] = _("Search All Sales Orders");
 }
 
+page($_SESSION['page_title'], false, false, "", $js);
+
 if (isset($_GET['selected_customer']))
 {
        $selected_customer = $_GET['selected_customer'];
@@ -35,22 +47,39 @@ else
        $selected_customer = -1;
        
 //-----------------------------------------------------------------------------------
+/*
+$action = $_SERVER['PHP_SELF'];
 
-start_form(false, false, $_SERVER['PHP_SELF'] ."?OutstandingOnly=" . $_POST['OutstandingOnly'] .SID);
+if ($_POST['order_view_mode']=='OutstandingOnly')
+{
+  $action .= "?OutstandingOnly=" . $_POST['order_view_mode']$_PO;
+}
+elseif ($_POST['order_view_mode']=='InvoiceTemplates')
+{
+  $action .= "?InvoiceTemplates=" . $_POST['InvoiceTemplates'];
+}
+elseif ($_POST['order_view_mode']=='DeliveryTemplates')
+{
+  $action .= "?DeliveryTemplates=" . $_POST['InvoiceTemplates'];
+}
+*/
+start_form(false, false, $_SERVER['PHP_SELF'] .SID);
 
 start_table("class='tablestyle_noborder'");
 start_row();
 ref_cells(_("#:"), 'OrderNumber');
-date_cells(_("from:"), 'OrdersAfterDate', null, -30);
-date_cells(_("to:"), 'OrdersToDate', null, 1);
-
+if ($_POST['order_view_mode']!='DeliveryTemplates' && $_POST['order_view_mode']!='InvoiceTemplates')
+{
+  date_cells(_("from:"), 'OrdersAfterDate', null, -30);
+  date_cells(_("to:"), 'OrdersToDate', null, 1);
+}
 locations_list_cells(_("Location:"), 'StockLocation', null, true);
 
 stock_items_list_cells(_("Item:"), 'SelectStockFromList', null, true);
 
 submit_cells('SearchOrders', _("Search"));
 
-hidden('OutstandingOnly', $_POST['OutstandingOnly']);
+hidden('order_view_mode', $_POST['order_view_mode']);
 
 end_row();
 
@@ -69,15 +98,27 @@ else
        unset($selected_stock_item);
 }
 
+//---------------------------------------------------------------------------------------------
+if (isset($_POST['ChangeTmpl']) && $_POST['ChangeTmpl']!=0) {
+  $sql = "UPDATE ".TB_PREF."sales_orders SET type = !type WHERE order_no=".$_POST['ChangeTmpl'];
+
+  db_query($sql, "Can't change sales order type");
+}
 //---------------------------------------------------------------------------------------------
 
 $sql = "SELECT ".TB_PREF."sales_orders.order_no, ".TB_PREF."debtors_master.curr_code, ".TB_PREF."debtors_master.name, ".TB_PREF."cust_branch.br_name,
-       ".TB_PREF."sales_orders.customer_ref, ".TB_PREF."sales_orders.ord_date, ".TB_PREF."sales_orders.deliver_to, ".TB_PREF."sales_orders.delivery_date, ";
+       ".TB_PREF."sales_orders.ord_date, ".TB_PREF."sales_orders.deliver_to, ".TB_PREF."sales_orders.delivery_date,
+       ".TB_PREF."sales_orders.type, ";
 $sql .= " Sum(".TB_PREF."sales_order_details.qty_sent) AS TotDelivered, ";
 $sql .= " Sum(".TB_PREF."sales_order_details.quantity) AS TotQuantity, ";
-
-$sql .= " Sum(".TB_PREF."sales_order_details.unit_price*".TB_PREF."sales_order_details.quantity*(1-".TB_PREF."sales_order_details.discount_percent)) AS OrderValue
-       FROM ".TB_PREF."sales_orders, ".TB_PREF."sales_order_details, ".TB_PREF."debtors_master, ".TB_PREF."cust_branch
+$sql .= " Sum(".TB_PREF."sales_order_details.unit_price*".TB_PREF."sales_order_details.quantity*(1-".TB_PREF."sales_order_details.discount_percent)) AS OrderValue, ";
+
+//if ($_POST['order_view_mode']=='InvoiceTemplates' || $_POST['order_view_mode']=='DeliveryTemplates')
+  $sql .= TB_PREF."sales_orders.comments, ";
+//else
+  $sql .= TB_PREF."sales_orders.customer_ref";
+  
+$sql .=        " FROM ".TB_PREF."sales_orders, ".TB_PREF."sales_order_details, ".TB_PREF."debtors_master, ".TB_PREF."cust_branch
                WHERE ".TB_PREF."sales_orders.order_no = ".TB_PREF."sales_order_details.order_no
                        AND ".TB_PREF."sales_orders.debtor_no = ".TB_PREF."debtors_master.debtor_no
                        AND ".TB_PREF."sales_orders.branch_code = ".TB_PREF."cust_branch.branch_code
@@ -90,13 +131,14 @@ if (isset($_POST['OrderNumber']) && $_POST['OrderNumber'] != "")
 } 
 else 
 {
-
+  if ($_POST['order_view_mode']!='DeliveryTemplates' && $_POST['order_view_mode']!='InvoiceTemplates')
+  {
        $date_after = date2sql($_POST['OrdersAfterDate']);
        $date_before = date2sql($_POST['OrdersToDate']);
 
        $sql .= " AND ".TB_PREF."sales_orders.ord_date >= '$date_after'";
        $sql .= " AND ".TB_PREF."sales_orders.ord_date <= '$date_before'";
-
+  }
        if ($selected_customer != -1)
                $sql .= " AND ".TB_PREF."sales_orders.debtor_no='" . $selected_customer . "'";
 
@@ -106,8 +148,10 @@ else
        if (isset($_POST['StockLocation']) && $_POST['StockLocation'] != reserved_words::get_all())
                $sql .= " AND ".TB_PREF."sales_orders.from_stk_loc = '". $_POST['StockLocation'] . "' ";
 
-       if ($_POST['OutstandingOnly'] == true)
+       if ($_POST['order_view_mode']=='OutstandingOnly')
                $sql .= " AND ".TB_PREF."sales_order_details.qty_sent < ".TB_PREF."sales_order_details.quantity";
+       elseif ($_POST['order_view_mode']=='InvoiceTemplates' || $_POST['order_view_mode']=='DeliveryTemplates')
+               $sql .= " AND ".TB_PREF."sales_orders.type=1";
 
        $sql .= " GROUP BY ".TB_PREF."sales_orders.order_no, ".TB_PREF."sales_orders.debtor_no, ".TB_PREF."sales_orders.branch_code,
                ".TB_PREF."sales_orders.customer_ref, ".TB_PREF."sales_orders.ord_date, ".TB_PREF."sales_orders.deliver_to";
@@ -125,8 +169,15 @@ if ($result)
 
        start_table("$table_style colspan=6 width=95%");
        $th = array(_("Order #"), _("Customer"), _("Branch"), _("Cust Order #"), _("Order Date"),
-               _("Required By"), _("Delivery To"), _("Order Total"), _("Currency"), "", "");
+               _("Required By"), _("Delivery To"), _("Order Total"), _("Currency"), _("Tmpl"),"");
+
+       if($_POST['order_view_mode']=='InvoiceTemplates' || $_POST['order_view_mode']=='DeliveryTemplates')
+       {
+               $th[3] = _('Description');
+       }
+
        table_header($th);
+start_form();
 
        $j = 1;
        $k = 0; //row colour counter
@@ -137,10 +188,10 @@ if ($result)
                $view_page = get_customer_trans_view_str(systypes::sales_order(), $myrow["order_no"]);
                $formated_del_date = sql2date($myrow["delivery_date"]);
                $formated_order_date = sql2date($myrow["ord_date"]);
-               $not_closed =  $myrow["TotDelivered"] < $myrow["TotQuantity"];
+//         $not_closed =  $myrow['type'] && ($myrow["TotDelivered"] < $myrow["TotQuantity"]);
 
        // if overdue orders, then highlight as so
-       if (date1_greater_date2(Today(), $formated_del_date) & $not_closed)
+       if ($myrow['type'] == 0 && date1_greater_date2(Today(), $formated_del_date))
        {
                 start_row("class='overduebg'");
                 $overdue_items = true;
@@ -153,25 +204,38 @@ if ($result)
                label_cell($view_page);
                label_cell($myrow["name"]);
                label_cell($myrow["br_name"]);
-               label_cell($myrow["customer_ref"]);
+         if($_POST['order_view_mode']=='InvoiceTemplates' || $_POST['order_view_mode']=='DeliveryTemplates')
+                 label_cell($myrow["comments"]);
+         else
+                 label_cell($myrow["customer_ref"]);
                label_cell($formated_order_date);
                label_cell($formated_del_date);
                label_cell($myrow["deliver_to"]);
                amount_cell($myrow["OrderValue"]);
                label_cell($myrow["curr_code"]);
-
-               if ($_POST['OutstandingOnly'] == true || $not_closed) 
+               if ($_POST['order_view_mode']=='OutstandingOnly'/* || $not_closed*/) 
                {
-               $modify_page = $path_to_root . "/sales/sales_order_entry.php?" . SID . "ModifyOrderNumber=" . $myrow["order_no"];
                $delivery_note = $path_to_root . "/sales/customer_delivery.php?" . SID . "OrderNumber=" .$myrow["order_no"];
-
-               label_cell("<a href='$modify_page'>" . _("Edit") . "</a>");
                label_cell("<a href='$delivery_note'>" . _("Dispatch") . "</a>");
                }
+               elseif ($_POST['order_view_mode']=='InvoiceTemplates')
+               {
+               $select_order= $path_to_root . "/sales/sales_order_entry.php?" . SID . "NewInvoice=" .$myrow["order_no"];
+               label_cell("<a href='$select_order'>" . _("Invoice") . "</a>");
+               }
+               elseif ($_POST['order_view_mode']=='DeliveryTemplates')
+               {
+                       $select_order= $path_to_root . "/sales/sales_order_entry.php?" . SID . "NewDelivery=" .$myrow["order_no"];
+               label_cell("<a href='$select_order'>" . _("Delivery") . "</a>");
+               }
                else
                {
-               label_cell("");
-               label_cell("");
+                 echo "<td><input ".($myrow["type"]==1 ? 'checked' : '')." type='checkbox' name='chgtpl" .$myrow["order_no"]. "' value='1'
+                  onclick='forms[1].ChangeTmpl.value= this.name.substr(6);
+                  this.form.submit();' ></td>";
+
+                 $modify_page = $path_to_root . "/sales/sales_order_entry.php?" . SID . "ModifyOrderNumber=" . $myrow["order_no"];
+                 label_cell("<a href='$modify_page'>" . _("Edit") . "</a>");
                }
                end_row();;
 
@@ -184,7 +248,8 @@ if ($result)
                //end of page full new headings if
        }
        //end of while loop
-
+  hidden('ChangeTmpl', 0);
+end_form();
        end_table();
 
    if ($overdue_items)
@@ -194,5 +259,4 @@ if ($result)
 echo "<br>";
 
 end_page();
-?>
-
+?>
\ No newline at end of file
index da495059a15d5e0aa572f4a9a35e817878f069db..f90ca55101dc8a39cb9ab5c14cf555a390a03d1b 100644 (file)
@@ -86,7 +86,7 @@ if (isset($_GET['delete']))
 $result = get_all_credit_status();
 
 start_table("$table_style width=40%");
-$th = array(_("Description"), _("Dissallow Invoices"));
+$th = array(_("Description"), _("Dissallow Invoices"),'','');
 table_header($th);
 
 $k = 0;
index 15e96e10e3a975c2a83b83a4efe9cd62b90d69b4..bad18a693cd4e623082b2f422f5f57462785930f 100644 (file)
@@ -36,7 +36,7 @@ function can_process()
 
 if (isset($_POST['ADD_ITEM']) && can_process()) 
 {
-       add_sales_type($_POST['sales_type']);
+       add_sales_type($_POST['sales_type'], isset($_POST['tax_included']));
        meta_forward($_SERVER['PHP_SELF']);     
 }
 
@@ -45,7 +45,7 @@ if (isset($_POST['ADD_ITEM']) && can_process())
 if (isset($_POST['UPDATE_ITEM']) && can_process()) 
 {
 
-       update_sales_type($selected_id, $_POST['sales_type']);
+       update_sales_type($selected_id, $_POST['sales_type'], isset($_POST['tax_included']) ? 1:0);
        meta_forward($_SERVER['PHP_SELF']);     
 } 
 
@@ -91,7 +91,7 @@ $result = get_all_sales_types();
 
 start_table("$table_style width=30%");
 
-$th = array (_("Type Name"), "", "");
+$th = array (_("Type Name"), 'Tax Incl', '','');
 table_header($th);
 $k = 0;
 
@@ -99,6 +99,7 @@ while ($myrow = db_fetch($result))
 {
        alt_table_row_color($k);
        label_cell($myrow["sales_type"]);       
+       label_cell($myrow["tax_included"] ? _('Yes'):_('No'), 'align=center');  
     edit_link_cell("selected_id=".$myrow["id"]);
     delete_link_cell("selected_id=".$myrow["id"]."&delete=1");
        end_row();
@@ -111,6 +112,8 @@ end_table();
 hyperlink_no_params($_SERVER['PHP_SELF'], _("New Sales type"));
 
 start_form();
+ if (!isset($_POST['tax_included']))
+       $_POST['tax_included'] = 0;
 
 start_table("$table_style2 width=30%");
 
@@ -120,11 +123,13 @@ if ($selected_id != -1)
        $myrow = get_sales_type($selected_id);
        
        $_POST['sales_type']  = $myrow["sales_type"];
+       $_POST['tax_included']  = $myrow["tax_included"];
        
        hidden('selected_id', $selected_id);
 } 
 
 text_row_ex(_("Sales Type Name:"), 'sales_type', 20);
+check_cells("Tax  included", 'tax_included', $_POST['tax_included']);
 
 end_table(1);
 
index d9e48f15a91cbd2a3c5d4438c1ffc1cc0aceaa33..1a5320d9b16423d5e10765aed95b24a15bdd33f6 100644 (file)
 <?php
+//-----------------------------------------------------------------------------
+//
+//     Entry/Modify Sales Order
+//     Entry Direct Delivery
+//     Entry Direct Invoice
+//
 
 $page_security = 1;
 $path_to_root="..";
+
 include_once($path_to_root . "/sales/includes/cart_class.inc");
 include_once($path_to_root . "/includes/session.inc");
 include_once($path_to_root . "/includes/data_checks.inc");
 include_once($path_to_root . "/sales/includes/sales_ui.inc");
 include_once($path_to_root . "/sales/includes/ui/sales_order_ui.inc");
 include_once($path_to_root . "/sales/includes/sales_db.inc");
+include_once($path_to_root . "/reporting/includes/reporting.inc");
 
 $js = get_js_form_entry("StockID2", "stock_id", "qty");
-if ($use_popup_windows)
+if ($use_popup_windows) {
        $js .= get_js_open_window(900, 500);
-if ($use_date_picker)
-       $js .= get_js_date_picker();
-
-if(isset($_GET['NewDelivery'])) {
-       $_SESSION['page_title'] = _("Sales Delivery"); 
-  create_cart('delivery',0);
 }
-elseif(isset($_GET['NewOrder'])) {
-       $_SESSION['page_title'] = _("Sales Order Entry"); 
-  create_cart('order',0);
+if ($use_date_picker) {
+       $js .= get_js_date_picker();
 }
-elseif(isset($_GET['ModifyOrderNumber'])) {
-       $_SESSION['page_title'] = _("Modifying Sales Order") . " #".$_GET['ModifyOrderNumber']; 
-  create_cart('order', $_GET['ModifyOrderNumber']);
+
+if (isset($_GET['NewDelivery']) && is_numeric($_GET['NewDelivery'])) {
+
+       $_SESSION['page_title'] = _("Direct Sales Delivery");
+       create_cart(13, $_GET['NewDelivery']);
+
+} elseif (isset($_GET['NewInvoice']) && is_numeric($_GET['NewInvoice'])) {
+
+       $_SESSION['page_title'] = _("Direct Sales Invoice");
+       create_cart(10, $_GET['NewInvoice']);
+
+} elseif (isset($_GET['ModifyOrderNumber']) && is_numeric($_GET['ModifyOrderNumber'])) {
+
+       $help_page_title = _('Modifying Sales Order');
+       $_SESSION['page_title'] = sprintf( _("Modifying Sales Order # %d"), $_GET['ModifyOrderNumber']);
+       create_cart(30, $_GET['ModifyOrderNumber']);
+
+} elseif (isset($_GET['NewOrder'])) {
+
+       $_SESSION['page_title'] = _("New Sales Order Entry");
+       create_cart(30, 0);
 }
 
-page($_SESSION['page_title'], false, false, "", $js); 
+page($_SESSION['page_title'], false, false, "", $js);
 
-//--------------------------------------------------------------------------------
-if (isset($_GET['AddedID'])) 
-{
+//-----------------------------------------------------------------------------
+
+if (isset($_GET['AddedID'])) {
        $order_no = $_GET['AddedID'];
-       $trans_type = systypes::sales_order();
+       print_hidden_script(30);
 
-       display_notification_centered(_("Order has been entered.") . " #$order_no");
+       display_notification_centered(sprintf( _("Order # %d has been entered."),$order_no));
 
-       display_note(get_trans_view_str($trans_type, $order_no, _("View this order")));
+       display_note(get_trans_view_str(30, $order_no, _("View This Order")));
+       echo '<br>';
+       display_note(print_document_link($order_no, _("Print This Order"), true, 30));
 
-       hyperlink_params($path_to_root . "/sales/customer_delivery.php", _("Make Delivery Against This Order"), "OrderNumber=$order_no");
+       hyperlink_params($path_to_root . "/sales/customer_delivery.php",
+               _("Make Delivery Against This Order"), "OrderNumber=$order_no");
 
-       hyperlink_params($_SERVER['PHP_SELF'], _("Enter a New Order"), "NewOrder=Yes");
+       hyperlink_params($_SERVER['PHP_SELF'], _("Enter a New Order"), "NewOrder=0");
 
        display_footer_exit();
-}
-//--------------------------------------------------------------------------------
 
-if (isset($_GET['UpdatedID'])) 
-{
+} elseif (isset($_GET['UpdatedID'])) {
        $order_no = $_GET['UpdatedID'];
-       $trans_type = systypes::sales_order();
+       print_hidden_script(30);
+
+       display_notification_centered(sprintf( _("Order # %d has been updated."),$order_no));
+
+       display_note(get_trans_view_str(30, $order_no, _("View This Order")));
+       echo '<br>';
+       display_note(print_document_link($order_no, _("Print This Order"), true, 30));
+
+       hyperlink_params($path_to_root . "/sales/customer_delivery.php",
+               _("Confirm Order Quantities and Make Delivery"), "OrderNumber=$order_no");
+
+       hyperlink_params($path_to_root . "/sales/inquiry/sales_orders_view.php",
+               _("Select A Different Order"), "OutstandingOnly=1");
+
+       display_footer_exit();
+
+} elseif (isset($_GET['AddedDN'])) {
+       $delivery = $_GET['AddedDN'];
+       print_hidden_script(13);
+
+       display_notification_centered(sprintf(_("Delivery # %d has been entered."),$delivery));
 
-       display_notification_centered(_('Order # ').$order_no. _( ' has been updated.'));
+       display_note(get_trans_view_str(13, $delivery, _("View This Delivery")));
+       echo '<br>';
+       display_note(print_document_link($delivery, _("Print Delivery Note"), true, 13));
 
-       display_note(get_trans_view_str($trans_type, $order_no, _("View this order")));
+       hyperlink_params($path_to_root . "/sales/customer_invoice.php",
+       _("Make Invoice Against This Delivery"), "DeliveryNumber=$delivery");
 
-       hyperlink_params($path_to_root . "/sales/customer_delivery.php", _("Confirm Order Quantities and Make Delivery"), "OrderNumber=$order_no");
+       if ((isset($_GET['Type']) && $_GET['Type'] == 1))
+       hyperlink_params("inquiry/sales_orders_view.php",
+               _("Enter a New Template Delivery"), "DeliveryTemplates=Yes");
+       else
+       hyperlink_params($_SERVER['PHP_SELF'], _("Enter a New Delivery"), "NewDelivery=0");
+
+       display_footer_exit();
+
+} elseif (isset($_GET['AddedDI'])) {
+       $invoice = $_GET['AddedDI'];
+       print_hidden_script(10);
 
-       hyperlink_params($path_to_root . "/sales/inquiry/sales_orders_view.php", _("Select A Different Order"), "OutstandingOnly=1");
+       display_notification_centered(sprintf(_("Invoice # %d has been entered."),$invoice));
+
+       display_note(get_trans_view_str(10, $invoice, _("View This Invoice")));
+       echo '<br>';
+       display_note(print_document_link($invoice, _("Print Sales Invoice"), true, 10));
+
+       if ((isset($_GET['Type']) && $_GET['Type'] == 1))
+       hyperlink_params("inquiry/sales_orders_view.php",
+               _("Enter a New Template Invoice"), "InvoiceTemplates=Yes");
+       else
+       hyperlink_params($_SERVER['PHP_SELF'], _("Enter a New Direct Invoice"), "NewInvoice=0");
 
        display_footer_exit();
 }
 
-//--------------------------------------------------------------------------------------------------
+//-----------------------------------------------------------------------------
 
 function copy_to_cart()
 {
-       if ($_SESSION['Items']->trans_type=='delivery')
-               $_SESSION['Items']->memo_ = $_POST['InvoiceText'];
+       $cart = &$_SESSION['Items'];
 
-       $_SESSION['Items']->orig_order_date = $_POST['OrderDate'];
-       $_SESSION['Items']->delivery_date = $_POST['delivery_date'];
-       $_SESSION['Items']->cust_ref = $_POST['cust_ref'];
-       $_SESSION['Items']->freight_cost = $_POST['freight_cost'];
-       $_SESSION['Items']->Comments = $_POST['Comments'];
-
-       $_SESSION['Items']->deliver_to = $_POST['deliver_to'];
-       $_SESSION['Items']->delivery_address = $_POST['delivery_address'];
-       $_SESSION['Items']->phone = $_POST['phone'];
-       $_SESSION['Items']->Location = $_POST['Location'];
-       $_SESSION['Items']->ship_via = $_POST['ship_via'];
+       if ($cart->trans_type!=30) {
+               $cart->reference = $_POST['ref'];
+       }
+       $cart->Comments =  str_replace("'", "\\'", $_POST['Comments']);
+
+       $cart->document_date = $_POST['OrderDate'];
+       $cart->due_date = $_POST['delivery_date'];
+       $cart->cust_ref = $_POST['cust_ref'];
+       $cart->freight_cost = $_POST['freight_cost'];
+       $cart->deliver_to = $_POST['deliver_to'];
+       $cart->delivery_address = $_POST['delivery_address'];
+       $cart->phone = $_POST['phone'];
+       $cart->Location = $_POST['Location'];
+       $cart->ship_via = $_POST['ship_via'];
 
        if (isset($_POST['email']))
-               $_SESSION['Items']->email =$_POST['email'];
-       else    
-               $_SESSION['Items']->email = '';
-
-       $_SESSION['Items']->customer_id = $_POST['customer_id'];
-       $_SESSION['Items']->Branch = $_POST['branch_id'];
+               $cart->email =$_POST['email'];
+       else
+               $cart->email = '';
+       $cart->customer_id      = $_POST['customer_id'];
+       $cart->Branch = $_POST['branch_id'];
 }
 
-//--------------------------------------------------------------------------------------------------
+//-----------------------------------------------------------------------------
 
 function copy_from_cart()
 {
-       if ($_SESSION['Items']->trans_type=='delivery')
-               $_POST['InvoiceText'] = $_SESSION['Items']->memo_;
-
-       $_POST['OrderDate'] = $_SESSION['Items']->orig_order_date;
-       $_POST['delivery_date'] = $_SESSION['Items']->delivery_date;
-       $_POST['cust_ref'] = $_SESSION['Items']->cust_ref;
-       $_POST['freight_cost'] = $_SESSION['Items']->freight_cost;
-       $_POST['Comments'] = $_SESSION['Items']->Comments;
-
-       $_POST['deliver_to'] = $_SESSION['Items']->deliver_to;
-       $_POST['delivery_address'] = $_SESSION['Items']->delivery_address;
-       $_POST['phone'] = $_SESSION['Items']->phone;
-       $_POST['Location'] = $_SESSION['Items']->Location;
-       $_POST['ship_via'] = $_SESSION['Items']->ship_via;
-
-       $_POST['customer_id'] = $_SESSION['Items']->customer_id;
-       $_POST['branch_id'] = $_SESSION['Items']->Branch;
-       
+       $cart = &$_SESSION['Items'];
+       if ($cart->trans_type!=30) {
+               $_POST['ref'] = $cart->reference;
+       }
+       $_POST['Comments'] = $cart->Comments;
+
+       $_POST['OrderDate'] = $cart->document_date;
+       $_POST['delivery_date'] = $cart->due_date;
+       $_POST['cust_ref'] = $cart->cust_ref;
+       $_POST['freight_cost'] = $cart->freight_cost;
+
+       $_POST['deliver_to'] = $cart->deliver_to;
+       $_POST['delivery_address'] = $cart->delivery_address;
+       $_POST['phone'] = $cart->phone;
+       $_POST['Location'] = $cart->Location;
+       $_POST['ship_via'] = $cart->ship_via;
+
+       $_POST['customer_id'] = $cart->customer_id;
+       $_POST['branch_id'] = $cart->Branch;
 }
 
+//--------------------------------------------------------------------------------
 
-function can_process()
-{
-           if ($_SESSION['Items']->trans_type=='delivery') 
-       {
-               $edate = _("The entered delivery date is invalid.");
-       } 
-       else 
-       {       
-               $edate = _("The entered order date is invalid.");
-       }       
-       if (!is_date($_POST['OrderDate'])) 
-       {
-               display_error($edate);
+function can_process() {
+       if (!is_date($_POST['OrderDate'])) {
+               display_error(_("The entered date is invalid."));
                return false;
        }
-       if (($_SESSION['Items']->trans_type=='delivery') && !is_date_in_fiscalyear($_POST['OrderDate'])) 
-       {
+       if ($_SESSION['Items']->trans_type!=30 && !is_date_in_fiscalyear($_POST['OrderDate'])) {
                display_error(_("The entered date is not in fiscal year"));
                return false;
        }
-       else
-       {
-               $_SESSION['Items']->orig_order_date = $_POST['OrderDate'];
-       }
-       if (count($_SESSION['Items']->line_items) == 0)
-       {
-               display_error(_("You must enter at least one line entry."));
+       if (count($_SESSION['Items']->line_items) == 0) {
+               display_error(_("You must enter at least one non empty item line."));
                return false;
        }
-       if (strlen($_POST['deliver_to']) <= 1)
-       {
+       if (strlen($_POST['deliver_to']) <= 1) {
                display_error(_("You must enter the person or company to whom delivery should be made to."));
                return false;
        }
-
-       if (strlen($_POST['delivery_address']) <= 1)
-       {
+       if (strlen($_POST['delivery_address']) <= 1) {
                display_error( _("You should enter the street address in the box provided. Orders cannot be accepted without a valid street address."));
                return false;
        }
@@ -161,209 +207,175 @@ function can_process()
        if ($_POST['freight_cost'] == "")
                $_POST['freight_cost'] = 0;
 
-       if (!is_numeric($_POST['freight_cost']))
-       {
+       if (!is_numeric($_POST['freight_cost'])) {
                display_error(_("The shipping cost entered is expected to be numeric."));
                return false;
        }
-
-       if (!is_date($_POST['delivery_date'])) 
-       {
+       if (!is_date($_POST['delivery_date'])) {
                display_error(_("The delivery date is invalid."));
                return false;
        }
-
-       if (date1_greater_date2($_SESSION['Items']->orig_order_date, $_POST['delivery_date'])) 
-       {
+       if (date1_greater_date2($_SESSION['Items']->document_date, $_POST['delivery_date'])) {
                display_error(_("The requested delivery date is before the date of the order."));
                return false;
        }
+       if ($_SESSION['Items']->trans_type != 30 && !references::is_valid($_POST['ref'])) {
+               display_error(_("You must enter a reference."));
+               return false;
+       }
 
-  return true;
+       return true;
 }
 
-//-----------------------------------------------------------------------------------------------------------
+//-----------------------------------------------------------------------------
 
-if (isset($_POST['ProcessOrder']) && can_process())
-{
- copy_to_cart(); 
- if($_SESSION['Items']->order_no == 0) {
-       $order_no = add_sales_order($_SESSION['Items']);
-       if ($_SESSION['Items']->trans_type=='delivery') 
-       {
-               $_SESSION['Items']->memo_ = $_POST['InvoiceText'];
-               $_SESSION['Items']->memo_ = str_replace("'", "\\'", $_SESSION['Items']->memo_);
-               $_SESSION['Items']->order_no = $order_no;
-
-               meta_forward("$path_to_root/sales/customer_delivery.php", "process_delivery=Yes");
-       } 
-       else 
-       {
-               meta_forward($_SERVER['PHP_SELF'], "AddedID=$order_no");
-       }
- } else { // store modified sales order
-       update_sales_order($_SESSION['Items']->order_no, $_SESSION['Items']);
-       $order_no = $_SESSION['Items']->order_no;
-       meta_forward($_SERVER['PHP_SELF'], "UpdatedID=$order_no");
- }
+if (isset($_POST['ProcessOrder']) && can_process()) {
+       copy_to_cart();
+
+       $modified = ($_SESSION['Items']->trans_no != 0);
+       $so_type = $_SESSION['Items']->so_type;
+
+       $_SESSION['Items']->write(1);
+
+       $trans_no = key($_SESSION['Items']->trans_no);
+       $trans_type = $_SESSION['Items']->trans_type;
+
+       processing_end();
+       if ($modified) {
+               meta_forward($_SERVER['PHP_SELF'], "UpdatedID=$trans_no");
+       } elseif ($trans_type == 30) {
+               meta_forward($_SERVER['PHP_SELF'], "AddedID=$trans_no");
+       } elseif ($trans_type == 10) {
+               meta_forward($_SERVER['PHP_SELF'], "AddedDI=$trans_no&Type=$so_type");
+       } else {
+               meta_forward($_SERVER['PHP_SELF'], "AddedDN=$trans_no&Type=$so_type");
+       }
 }
 
 //--------------------------------------------------------------------------------
 
-function check_item_data() 
+function check_item_data()
 {
-       if (!is_numeric($_POST['qty']) || $_POST['qty'] < 0 || $_POST['Disc'] > 100 || 
-               $_POST['Disc'] < 0)
-       {
+       if (!is_numeric($_POST['qty']) || $_POST['qty'] < 0 || $_POST['Disc'] > 100 || $_POST['Disc'] < 0) {
                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."));
                return false;
-       } 
-       else
-       if (!is_numeric($_POST['price']) || $_POST['price']<0)
-       {
+       } elseif (!is_numeric($_POST['price']) || $_POST['price'] < 0) {
+
                display_error( _("Price for item must be entered and can not be less then 0"));
                return false;
-       } 
-       else
-// should this be checked for delivery ?
-//         if($_SESSION['Items']->some_already_delivered($_POST['stock_id']) != 0 &&
-//             $_SESSION['Items']->line_items[$_POST['stock_id']]->price != $_POST['price']) 
-//     {
-//             display_error(_("The item you attempting to modify the price for has already had some quantity invoiced at the old price. The item unit price cannot be modified retrospectively."));
-//             return false;
-//     } 
-//     else
-//         if($_SESSION['Items']->some_already_delivered($_POST['stock_id']) != 0 && 
-//             $_SESSION['Items']->line_items[$_POST['stock_id']]->discount_percent != ($_POST['Disc']/100)) 
-//     {
-//             display_error(_("The item you attempting to modify has had some quantity invoiced at the old discount percent. The items discount cannot be modified retrospectively."));
-//             return false;
-//     } 
-//     else
-           if (isset($_POST['LineNo']) && isset($_SESSION['Items']->line_items[$_POST['LineNo']]) && $_SESSION['Items']->line_items[$_POST['LineNo']]->qty_done > $_POST['qty'])
-       {
-               display_error(_("You attempting to make the quantity ordered a quantity less than has already been delivered. The quantity delivered cannot be modified retrospectively."));
-               return false;
-       }       
-       return true;
+       } elseif (isset($_POST['LineNo']) && isset($_SESSION['Items']->line_items[$_POST['LineNo']])
+               && $_SESSION['Items']->line_items[$_POST['LineNo']]->qty_done > $_POST['qty']) {
+
+               display_error(_("You attempting to make the quantity ordered a quantity less than has already been delivered. The quantity delivered cannot be modified retrospectively."));
+               return false;
+       }
+       return true;
 }
 
-function handle_update_item() 
+//--------------------------------------------------------------------------------
+
+function handle_update_item()
 {
-    if($_POST['UpdateItem'] != '' && check_item_data())
-    {
-       $_SESSION['Items']->update_cart_item($_POST['LineNo'], $_POST['qty'], 
-               $_POST['price'], ($_POST['Disc'] / 100));
-    }
+       if ($_POST['UpdateItem'] != '' && check_item_data()) {
+               $_SESSION['Items']->update_cart_item($_POST['LineNo'], $_POST['qty'],
+                       $_POST['price'], ($_POST['Disc'] / 100));
+       }
 }
 
 //--------------------------------------------------------------------------------
 
-function handle_delete_item() 
-{   
-    if($_GET['Delete'] != "")
-    {
-       $line_no = $_GET['Delete']; 
-       if($_SESSION['Items']->some_already_delivered($line_no) == 0)
-       {
-               $_SESSION['Items']->remove_from_cart($line_no);
-       } 
-       else 
-       {
-               display_error(_("This item cannot be deleted because some of it has already been delivered."));
-       }
-    }
+function handle_delete_item()
+{
+       if ($_GET['Delete'] != ""){
+               $line_no = $_GET['Delete'];
+               if ($_SESSION['Items']->some_already_delivered($line_no) == 0) {
+                       $_SESSION['Items']->remove_from_cart($line_no);
+               } else {
+                       display_error(_("This item cannot be deleted because some of it has already been delivered."));
+               }
+       }
 }
 
 //--------------------------------------------------------------------------------
 
 function handle_new_item()
 {
-       if (!check_item_data())
-               return;
-       add_to_order($_SESSION['Items'], $_POST['stock_id'], $_POST['qty'], 
-               $_POST['price'], $_POST['Disc']/100);
+       if (!check_item_data()) {
+                       return;
+       }
+       add_to_order($_SESSION['Items'], $_POST['stock_id'], $_POST['qty'],
+               $_POST['price'], $_POST['Disc'] / 100);
 
        $_POST['StockID2'] = $_POST['stock_id'] = "";
 }
 
-//--------------------------------------------------------------------------------     
+//--------------------------------------------------------------------------------
 
 function  handle_cancel_order()
 {
        global $path_to_root;
-       
-    if ($_POST['CancelOrder'] != "") 
-    {
-       $ok_to_delete = 1;      //assume this in the first instance
-    
-               if (($_SESSION['Items']->order_no != 0) && sales_order_has_deliveries($_SESSION['Items']->order_no)) 
-               {
-                       $ok_to_delete = 0;
-                       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."));
+
+       if ($_POST['CancelOrder'] != "") {
+
+       if ($_SESSION['Items']->trans_type == 13) {
+                       display_note(_("Direct delivery entry has been cancelled as requested."), 1);
+                       hyperlink_params($path_to_root . "/sales/sales_order_entry.php",
+                                       _("Enter a New Sales Delivery"), SID . "&NewDelivery=0");
+       } elseif ($_SESSION['Items']->trans_type == 10) {
+                       display_note(_("Direct invoice entry has been cancelled as requested."), 1);
+                       hyperlink_params($path_to_root . "/sales/sales_order_entry.php",
+                                       _("Enter a New Sales Delivery"), SID . "&NewDelivery=0");
+       } else {
+               if ($_SESSION['Items']->trans_no != 0) {
+                       if (sales_order_has_deliveries(key($_SESSION['Items']->trans_no)))
+                               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."));
+                       else
+                               delete_sales_order(key($_SESSION['Items']->trans_no));
                }
-    
-       if ($ok_to_delete == 1)
-       {
-               if($_SESSION['Items']->order_no != 0)
-               {
-                       delete_sales_order($_SESSION['Items']->order_no);
-               }
-
-                       if ($_SESSION['Items']->trans_type=='delivery') 
-               {
-                display_note(_("This sales delivery has been cancelled as requested."), 1);
-                                hyperlink_params($path_to_root . "/sales/sales_order_entry.php", _("Enter a New Sales Delivery"), SID . "&NewDelivery=Yes");
-               } 
-               else  
-               {
-                display_note(_("This sales order has been cancelled as requested."), 1);
-                                hyperlink_params($path_to_root . "/sales/sales_order_entry.php", _("Enter a New Sales Order"), SID . "&NewOrder=Yes");
-               }
-               br(1);
-               end_page();                     
-               exit;
-       }
-    }
+
+                       display_note(_("This sales order has been cancelled as requested."), 1);
+                               hyperlink_params($path_to_root . "/sales/sales_order_entry.php",
+                               _("Enter a New Sales Order"), SID . "&NewOrder=Yes");
+               }
+               processing_end();
+               br(1);
+               end_page();
+               exit;
+       }
 }
-       
+
 //--------------------------------------------------------------------------------
 
-function create_cart($type, $trans_num) 
+function create_cart($type, $trans_no)
 {
-       /*New order entry - clear any existing order details from the Items object and initiate a newy*/
-       if (isset($_SESSION['Items']))
-       {
-               unset ($_SESSION['Items']->line_items);
-               unset ($_SESSION['Items']);
+       processing_start();
+       $doc_type = $type;
+
+       if($type != 30 && $trans_no != 0) { // this is template
+       $doc_type = 30;
+
+       $doc = new Cart(30, array($trans_no));
+       $doc->trans_type = $type;
+       $doc->trans_no = 0;
+
+       $doc->due_date = $doc->document_date = Today();
+       $doc->reference = references::get_next($doc->trans_type);
+       $doc->Comments='';
+       foreach($doc->line_items as $line_no => $line) {
+               $doc->line_items[$line_no]->qty_done = 0;
        }
-       
-       $_SESSION['Items'] = new cart($type);
-
-  if( $trans_num==0 ) { // new transaction
-        $_SESSION['Items']->customer_id = "";
-        $_POST['OrderDate'] = Today();         
-        $_SESSION['Items']->order_no = 0;      
-        if (!is_date_in_fiscalyear($_POST['OrderDate']))
-               $_POST['OrderDate'] = end_fiscalyear();
-        $_SESSION['Items']->orig_order_date = $_POST['OrderDate'];
-       } else { // read sales order to modify
-         $_SESSION['Items']->order_no = $trans_num;
-        /*read in all the selected order into the Items cart  */
-         read_sales_order($_SESSION['Items']->order_no, $_SESSION['Items']);
-               copy_from_cart(); // load POST variables
-  }
+       $_SESSION['Items'] = $doc;
+       } else
+       $_SESSION['Items'] = new Cart($type,array($trans_no));
+
+       copy_from_cart();
 }
 
 //--------------------------------------------------------------------------------
 
 if (isset($_POST['CancelOrder']))
-       handle_cancel_order();
+       handle_cancel_order();
 
-if (isset($_GET['Delete']) || isset($_GET['Edit']))
-       copy_from_cart();
-       
 if (isset($_GET['Delete']))
        handle_delete_item();
 
@@ -372,74 +384,59 @@ if (isset($_POST['UpdateItem']))
 
 if (isset($_POST['AddItem']))
        handle_new_item();
-       
-//--------------------------------------------------------------------------------     
+
+//--------------------------------------------------------------------------------
 
 check_db_has_stock_items(_("There are no inventory items defined in the system."));
 
-check_db_has_customer_branches(_("There are no customers, or there are no customers with branches. Please define customers and customer branches."));          
+check_db_has_customer_branches(_("There are no customers, or there are no customers with branches. Please define customers and customer branches."));
 
-if ($_SESSION['Items']->trans_type=='delivery') 
-{
+if ($_SESSION['Items']->trans_type == 10) {
+       $idate = _("Invoice Date:");
+       $orderitems = _("Sales Invoice Items");
+       $deliverydetails = _("Enter Delivery Details and Confirm Invoice");
+       $cancelorder = _("Cancel Invoice");
+       $porder = _("Place Invoice");
+} elseif ($_SESSION['Items']->trans_type == 13) {
        $idate = _("Delivery Date:");
        $orderitems = _("Delivery Note Items");
        $deliverydetails = _("Enter Delivery Details and Confirm Dispatch");
        $cancelorder = _("Cancel Delivery");
-} 
-else
-{
+       $porder = _("Place Delivery");
+} else {
        $idate = _("Order Date:");
        $orderitems = _("Sales Order Items");
        $deliverydetails = _("Enter Delivery Details and Confirm Order");
        $cancelorder = _("Cancel Order");
+       $porder = _("Place Order");
+       $corder = _("Commit Order Changes");
 }
 start_form(false, true);
 
-$customer_error = display_order_header($_SESSION['Items'], 
+$customer_error = display_order_header($_SESSION['Items'],
        ($_SESSION['Items']->any_already_delivered() == 0), $idate);
 
-if ($customer_error == "")
-{
+if ($customer_error == "") {
        start_table("$table_style width=80%", 10);
-       echo "<tr><td>";                
+       echo "<tr><td>";
        display_order_summary($orderitems, $_SESSION['Items'], true);
        echo "</td></tr>";
-       echo "<tr><td>";                
+       echo "<tr><td>";
        display_delivery_details($_SESSION['Items']);
        echo "</td></tr>";
-       end_table(1);           
-} 
-else
-{
-       display_error($customer_error);
-}
+       end_table(1);
 
-if ($_SESSION['Items']->trans_type=='delivery') 
-{
-       $porder = _("Place Delivery");
-       $corder = _("Commit Delivery Changes");
-       $eorder = _("Edit Delivery Items");
-} 
-else 
-{
-       $porder = _("Place Order");
-       $corder = _("Commit Order Changes");
-       $eorder = _("Edit Order Items");
-}
+       if ($_SESSION['Items']->trans_no == 0) {
+               submit_center_first('ProcessOrder', $porder);
+       } else {
+               submit_center_first('ProcessOrder', $corder);
+       }
 
-if ($_SESSION['Items']->order_no == 0)
-{
-       submit_center_first('ProcessOrder', $porder);
-} 
-else 
-{
-       submit_center_first('ProcessOrder', $corder);
+       submit_center_last('CancelOrder', $cancelorder);
+} else {
+       display_error($customer_error);
 }
-
-  submit_center_last('CancelOrder', $cancelorder);
-       
 end_form();
-
 //--------------------------------------------------------------------------------
 end_page();
 ?>
\ No newline at end of file
index 1e98a8e56f11e81a88e2c4dd3ebd2fc1c9fce689..e1e7326cbfd52352655830c60b30ed280f1c4e36 100644 (file)
@@ -27,7 +27,7 @@ $myrow = get_customer_trans($trans_id, 11);
 
 $branch = get_branch($myrow["branch_code"]);
 
-display_heading("<font color=red>" . _("CREDIT NOTE") . " #$trans_id</font>");
+display_heading("<font color=red>" . sprintf(_("CREDIT NOTE #%d"), $trans_id). "</font>");
 echo "<br>";
 
 start_table("$table_style2 width=95%");
@@ -90,8 +90,8 @@ if (db_num_rows($result) > 0)
 
                alt_table_row_color($k);
 
-               $net = ((1 - $myrow2["discount_percent"]) * $myrow2["FullUnitPrice"] * $myrow2["quantity"]);
-               $sub_total += $net;
+               $value = ((1 - $myrow2["discount_percent"]) * $myrow2["unit_price"] * $myrow2["quantity"]);
+               $sub_total += $value;
 
                if ($myrow2["discount_percent"] == 0)
                {
@@ -106,9 +106,9 @@ if (db_num_rows($result) > 0)
                label_cell($myrow2["StockDescription"]);
                qty_cell($myrow2["quantity"]);
                label_cell($myrow2["units"], "align=right");
-               amount_cell($myrow2["FullUnitPrice"]);
+               amount_cell($myrow2["unit_price"]);
                label_cell($display_discount, "align=right");
-               amount_cell($net);
+               amount_cell($value);
                end_row();
        } //end while there are line items to print out
 } 
@@ -116,10 +116,9 @@ else
        display_note(_("There are no line items on this credit note."), 1, 2);
 
 $display_sub_tot = number_format2($sub_total,user_price_dec());
-$display_freight = number_format2(-$myrow["ov_freight"],user_price_dec());
+$display_freight = number_format2($myrow["ov_freight"],user_price_dec());
 
-$display_tax = number_format2(-$myrow["ov_gst"],user_price_dec());
-$credit_total = -$myrow["ov_freight"]-$myrow["ov_gst"]-$myrow["ov_amount"];
+$credit_total = $myrow["ov_freight"]+$myrow["ov_gst"]+$myrow["ov_amount"]+$myrow["ov_freight_tax"];
 $display_total = number_format2($credit_total,user_price_dec());
 
 /*Print out the invoice text entered */
index 0d56ffc75456e569dd15cb04d317e8ea02d31672..84bf2288eea8b603431e46e64927cd78edd8adcc 100644 (file)
@@ -29,9 +29,9 @@ $myrow = get_customer_trans($trans_id, 13);
 
 $branch = get_branch($myrow["branch_code"]);
 
-$sales_order = get_sales_order($myrow["order_"]);
+$sales_order = get_sales_order_header($myrow["order_"]);
 
-display_heading(_("DISPATCH NOTE") .' '. _('#').$trans_id);
+display_heading(sprintf(_("DISPATCH NOTE #%d"),$trans_id));
 
 echo "<br>";
 start_table("$table_style2 width=95%");
@@ -111,8 +111,8 @@ if (db_num_rows($result) > 0)
                if($myrow2['quantity']==0) continue;
                alt_table_row_color($k);
 
-               $net = ((1 - $myrow2["discount_percent"]) * $myrow2["FullUnitPrice"] * -$myrow2["quantity"]);
-               $sub_total += $net;
+               $value = ((1 - $myrow2["discount_percent"]) * $myrow2["unit_price"] * $myrow2["quantity"]);
+               $sub_total += $value;
 
            if ($myrow2["discount_percent"] == 0)
            {
@@ -125,11 +125,11 @@ if (db_num_rows($result) > 0)
 
        label_cell($myrow2["stock_id"]);
        label_cell($myrow2["StockDescription"]);
-        qty_cell(-$myrow2["quantity"]);
+        qty_cell($myrow2["quantity"]);
         label_cell($myrow2["units"], "align=right");
-        amount_cell($myrow2["FullUnitPrice"]);
+        amount_cell($myrow2["unit_price"]);
         label_cell($display_discount, "nowrap align=right");
-        amount_cell($net);
+        amount_cell($value);
        end_row();
        } //end while there are line items to print out
 
@@ -148,7 +148,7 @@ label_row(_("Shipping"), $display_freight, "colspan=6 align=right", "nowrap alig
 $tax_items = get_customer_trans_tax_details(13, $trans_id);
 display_customer_trans_tax_details($tax_items, 6);
 
-$display_total = number_format2($myrow["ov_freight"]+$myrow["ov_amount"],user_price_dec());
+$display_total = number_format2($myrow["ov_freight"]+$myrow["ov_amount"]+$myrow["ov_freight_tax"]+$myrow["ov_gst"],user_price_dec());
 
 label_row(_("TOTAL VALUE"), $display_total, "colspan=6 align=right",
        "nowrap align=right");
index 498eb4e2420bc310a37324374951ab8354c7f859..90820a79b2fa16125bab8ddcd49d98a463fbbf1d 100644 (file)
@@ -29,9 +29,9 @@ $myrow = get_customer_trans($trans_id, 10);
 
 $branch = get_branch($myrow["branch_code"]);
 
-$sales_order = get_sales_order($myrow["order_"]);
+$sales_order = get_sales_order_header($myrow["order_"]);
 
-display_heading(_("SALES INVOICE") . " #$trans_id");
+display_heading(sprintf(_("SALES INVOICE #%d"),$trans_id));
 
 echo "<br>";
 start_table("$table_style2 width=95%");
@@ -65,8 +65,8 @@ start_table("$table_style width=100%");
 $th = array(_("Delivered To"));
 table_header($th);
 
-//label_row(null, $sales_order["deliver_to"] . "<br>" . nl2br($sales_order["delivery_address"]),
-//     "nowrap");
+label_row(null, $sales_order["deliver_to"] . "<br>" . nl2br($sales_order["delivery_address"]),
+       "nowrap");
 end_table();
 
 echo "</td><td>"; // outer table
@@ -108,11 +108,11 @@ if (db_num_rows($result) > 0)
        $sub_total = 0;
        while ($myrow2 = db_fetch($result))
        {
-
+           if($myrow2["quantity"]==0) continue;
                alt_table_row_color($k);
 
-               $net = ((1 - $myrow2["discount_percent"]) * $myrow2["FullUnitPrice"] * -$myrow2["quantity"]);
-               $sub_total += $net;
+               $value = ((1 - $myrow2["discount_percent"]) * $myrow2["unit_price"] * $myrow2["quantity"]);
+               $sub_total += $value;
 
            if ($myrow2["discount_percent"] == 0)
            {
@@ -125,11 +125,11 @@ if (db_num_rows($result) > 0)
 
            label_cell($myrow2["stock_id"]);
                label_cell($myrow2["StockDescription"]);
-        qty_cell(-$myrow2["quantity"]);
+        qty_cell($myrow2["quantity"]);
         label_cell($myrow2["units"], "align=right");
-        amount_cell($myrow2["FullUnitPrice"]);
+        amount_cell($myrow2["unit_price"]);
         label_cell($display_discount, "nowrap align=right");
-        amount_cell($net);
+        amount_cell($value);
                end_row();
        } //end while there are line items to print out
 
@@ -148,7 +148,7 @@ label_row(_("Shipping"), $display_freight, "colspan=6 align=right", "nowrap alig
 $tax_items = get_customer_trans_tax_details(10, $trans_id);
 display_customer_trans_tax_details($tax_items, 6);
 
-$display_total = number_format2($myrow["ov_freight"]+$myrow["ov_gst"]+$myrow["ov_amount"],user_price_dec());
+$display_total = number_format2($myrow["ov_freight"]+$myrow["ov_gst"]+$myrow["ov_amount"]+$myrow["ov_freight_tax"],user_price_dec());
 
 label_row(_("TOTAL INVOICE"), $display_total, "colspan=6 align=right",
        "nowrap align=right");
index 94e4d4f93331ecf3f3f76524df57097cdf8c7152..16a8c5806f944dccffef68f2f21ab8c2c1c9028b 100644 (file)
@@ -17,7 +17,7 @@ if (isset($_GET["trans_no"]))
 
 $receipt = get_customer_trans($trans_id, systypes::cust_payment());
 
-display_heading(_("Customer Payment") . " #$trans_id");
+display_heading(sprintf(_("Customer Payment #%d"),$trans_id));
 
 echo "<br>";
 start_table("$table_style width=80%");
index e717e4bed8033f551f636dc7c259850fab4bc8e2..32cd1b7440c28f33820f0bd93a05df4d80eefda8 100644 (file)
@@ -16,17 +16,14 @@ if ($use_popup_windows)
 
 page(_("View Sales Order"), true, false, "", $js);
 
-display_heading(_("Sales Order") . " #" . $_GET['trans_no']);
+display_heading(sprintf(_("Sales Order #%d"),$_GET['trans_no']));
 
 if (isset($_SESSION['Items']))
 {
        unset ($_SESSION['Items']);
 }
 
-$_SESSION['Items'] = new cart;
-
-/*read in all the selected order into the Items cart  */
-read_sales_order($_GET['trans_no'], $_SESSION['Items']);
+$_SESSION['Items'] = new Cart(30, $_GET['trans_no'], true);
 
 start_table("$table_style2 width=95%", 5);
 echo "<tr valign=top><td>";
@@ -47,8 +44,8 @@ label_cells(_("Customer Order Ref."), $_SESSION['Items']->cust_ref, "class='tabl
 label_cells(_("Deliver To Branch"), $_SESSION['Items']->deliver_to, "class='tableheader2'");
 end_row();
 start_row();
-label_cells(_("Ordered On"), $_SESSION['Items']->orig_order_date, "class='tableheader2'");
-label_cells(_("Requested Delivery"), $_SESSION['Items']->delivery_date, "class='tableheader2'");
+label_cells(_("Ordered On"), $_SESSION['Items']->document_date, "class='tableheader2'");
+label_cells(_("Requested Delivery"), $_SESSION['Items']->due_date, "class='tableheader2'");
 end_row();
 start_row();
 label_cells(_("Order Currency"), $_SESSION['Items']->customer_currency, "class='tableheader2'");
@@ -82,7 +79,7 @@ while ($del_row = db_fetch($result))
 
        alt_table_row_color($k);
 
-       $this_total = $del_row["ov_freight"] + $del_row["ov_gst"] + $del_row["ov_amount"];
+       $this_total = $del_row["ov_freight"]+ $del_row["ov_amount"] + $del_row["ov_freight_tax"]  + $del_row["ov_gst"] ;
        $delivery_total += $this_total;
 
        label_cell(get_customer_trans_view_str($del_row["type"], $del_row["trans_no"]));
@@ -115,7 +112,7 @@ while ($inv_row = db_fetch($result))
 
        alt_table_row_color($k);
 
-       $this_total = $inv_row["ov_freight"] + $inv_row["ov_gst"] + $inv_row["ov_amount"];
+       $this_total = $inv_row["ov_freight"] + $inv_row["ov_freight_tax"]  + $inv_row["ov_gst"] + $inv_row["ov_amount"];
        $invoices_total += $this_total;
 
        label_cell(get_customer_trans_view_str($inv_row["type"], $inv_row["trans_no"]));
@@ -147,7 +144,7 @@ while ($credits_row = db_fetch($result))
 
        alt_table_row_color($k);
 
-       $this_total = $credits_row["ov_freight"] + $credits_row["ov_gst"] + $credits_row["ov_amount"];
+       $this_total = $credits_row["ov_freight"] + $credits_row["ov_freight_tax"]  + $credits_row["ov_gst"] + $credits_row["ov_amount"];
        $credits_total += $this_total;
 
        label_cell(get_customer_trans_view_str($credits_row["type"], $credits_row["trans_no"]));
@@ -202,7 +199,7 @@ $display_total = number_format2($items_total + $_SESSION['Items']->freight_cost,
 
 label_row(_("Shipping"), number_format2($_SESSION['Items']->freight_cost,user_price_dec()),
        "align=right colspan=6", "nowrap align=right");
-label_row(_("Total Excluding Tax"), $display_total, "align=right colspan=6",
+label_row(_("Total Order Value"), $display_total, "align=right colspan=6",
        "nowrap align=right");
 
 end_table(2);