Stable merged into unstable again (due to failure on binary file during previous...
authorJanusz Dobrowolski <janusz@frontaccouting.eu>
Sat, 3 Mar 2012 21:35:40 +0000 (22:35 +0100)
committerJanusz Dobrowolski <janusz@frontaccouting.eu>
Sat, 3 Mar 2012 21:35:40 +0000 (22:35 +0100)
87 files changed:
1  2 
admin/db/fiscalyears_db.inc
admin/gl_setup.php
gl/gl_bank.php
gl/includes/db/gl_db_banking.inc
gl/includes/ui/gl_journal_ui.inc
gl/manage/close_period.php
includes/data_checks.inc
includes/date_functions.inc
includes/db/audit_trail_db.inc
includes/db/inventory_db.inc
includes/main.inc
includes/session.inc
includes/types.inc
includes/ui/ui_controls.inc
install/lang/new_language_template/LC_MESSAGES/empty.po
inventory/adjustments.php
inventory/cost_update.php
inventory/includes/db/items_trans_db.inc
inventory/inquiry/stock_movements.php
inventory/inquiry/stock_status.php
inventory/manage/items.php
manufacturing/includes/db/work_order_issues_db.inc
manufacturing/includes/db/work_order_produce_items_db.inc
manufacturing/includes/db/work_orders_db.inc
manufacturing/includes/db/work_orders_quick_db.inc
manufacturing/work_order_entry.php
manufacturing/work_order_issue.php
purchasing/includes/db/grn_db.inc
purchasing/includes/db/invoice_db.inc
purchasing/includes/db/po_db.inc
purchasing/includes/db/supp_trans_db.inc
purchasing/includes/db/suppalloc_db.inc
purchasing/includes/db/suppliers_db.inc
purchasing/includes/po_class.inc
purchasing/includes/supp_trans_class.inc
purchasing/includes/ui/invoice_ui.inc
purchasing/includes/ui/po_ui.inc
purchasing/inquiry/po_search_completed.php
purchasing/inquiry/supplier_inquiry.php
purchasing/manage/suppliers.php
purchasing/po_entry_items.php
purchasing/supplier_credit.php
purchasing/supplier_payment.php
purchasing/view/view_supp_invoice.php
reporting/includes/class.pdf.inc
reporting/includes/doctext.inc
reporting/includes/excel_report.inc
reporting/rep107.php
reporting/rep109.php
reporting/rep110.php
reporting/rep111.php
reporting/rep112.php
reporting/rep202.php
reporting/rep209.php
reporting/rep210.php
reporting/rep305.php
reporting/rep601.php
reporting/rep701.php
reporting/rep708.php
reporting/rep709.php
reporting/reports_main.php
sales/create_recurrent_invoices.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/branches_db.inc
sales/includes/db/cust_trans_db.inc
sales/includes/db/customers_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/inquiry/customer_inquiry.php
sales/inquiry/sales_orders_view.php
sales/manage/customer_branches.php
sales/manage/customers.php
sales/sales_order_entry.php
sales/view/view_sales_order.php
sql/alter2.3.php
sql/en_US-demo.sql
sql/en_US-new.sql
taxes/tax_calc.inc
update.html
version.php

index 8cb84044cc5c910c6d81ab643ea0ffd2ba32f0ee,c605c064d2b0aae5bd7abdf9d541ea1f304f99ee..9ace5d195ee0b3c684a1f1a811dae7cb56803ed1
@@@ -180,7 -180,7 +180,7 @@@ function open_year($year
        $from = sql2date($myrow['begin']);
  
        begin_transaction();
 -      open_transactions($from);
 +      close_transactions(add_days($from, -1));
        commit_transaction();
  }
  
@@@ -337,29 -337,21 +337,28 @@@ function delete_this_fiscalyear($select
        db_query($sql, "Could not delete exchange rates");
        $sql = "DELETE FROM ".TB_PREF."budget_trans WHERE tran_date <= '$to'";
        db_query($sql, "Could not delete exchange rates");
--      
 -      $sql = "SELECT account, SUM(amount) AS amount FROM ".TB_PREF."gl_trans WHERE tran_date <= '$to' GROUP by account";
 +      $sql = "SELECT account, SUM(amount) AS amount, person_type_id, person_id FROM "
 +              .TB_PREF."gl_trans WHERE tran_date <= '$to' GROUP by account, person_type_id, person_id";
-       $sql = "SELECT account, SUM(amount) AS amount FROM ".TB_PREF."gl_trans WHERE tran_date <= '$to' GROUP by account";
        $result = db_query($sql, "Could not retrieve gl trans");
        $trans_no = get_next_trans_no(ST_JOURNAL);
 +
 +      $last_account='';
        $new = false;
        while ($row = db_fetch($result))
        {
 -              $sql = "DELETE FROM ".TB_PREF."gl_trans WHERE tran_date <= '$to' AND account = '{$row['account']}'";
 -              db_query($sql, "Could not delete gl trans");
 -              if (is_account_balancesheet($row['account']))
 +              if ($last_account != $row['account']) // deletes all subledgers postings, so do it once for account
 +              {
 +                      $sql = "DELETE FROM ".TB_PREF."gl_trans WHERE tran_date <= '$to' AND account = '{$row['account']}'";
 +                      db_query($sql, "Could not delete gl trans");
 +                      $last_account = $row['account'];
 +              }
 +              if (is_account_balancesheet($row['account']) && $row['amount'])
                {
 -                      $sql = "INSERT INTO ".TB_PREF."gl_trans (type, type_no, tran_date, account, memo_, amount) VALUES
 -                              (".ST_JOURNAL.", $trans_no, '$to', '{$row['account']}', '$ref', {$row['amount']})";
 +                      $sql = "INSERT INTO ".TB_PREF."gl_trans (type, type_no, tran_date, account, memo_, amount, person_type_id, person_id) VALUES
 +                              (".ST_JOURNAL.", $trans_no, '$to', '{$row['account']}', '$ref', {$row['amount']}, "
 +                              .db_escape($row['person_type_id'], true).", ".db_escape($row['person_id'], true).")";
                        db_query($sql, "Could not insert gl trans");
+                       $new = true;
                }
        }
        if ($new)
diff --combined admin/gl_setup.php
index 1263be92747f82cce2063156f1beb066c195d0cd,1ef3e40e06c3272f150606f0907dee47161b4604..fe494679a0ea6ff885175eceacacecfcf2810945
@@@ -67,7 -67,7 +67,7 @@@ if (isset($_POST['submit']) && can_proc
                'default_prompt_payment_act', 'default_inventory_act', 'default_cogs_act',
                'default_adj_act', 'default_inv_sales_act', 'default_assembly_act', 'legal_text',
                'past_due_days', 'default_workorder_required', 'default_dim_required',
 -              'default_delivery_required', 'grn_clearing_act',
 +              'default_delivery_required', 'grn_clearing_act', 'tax_algorithm',
                'allow_negative_stock'=> 0, 'accumulate_shipping'=> 0,
                'po_over_receive' => 0.0, 'po_over_charge' => 0.0, 'default_credit_limit'=>0.0
  )));
@@@ -83,6 -83,11 +83,10 @@@ start_form()
  start_outer_table(TABLESTYLE2);
  
  table_section(1);
 -
+ if (get_company_pref('grn_clearing_act') === null) { // available form 2.3.1, can be not defined on pre-2.4 installations
+       set_company_pref('grn_clearing_act', 'glsetup.purchase', 'varchar', 15, 0);
+       refresh_sys_prefs();
+ }
  
  $myrow = get_company_prefs();
  
@@@ -95,7 -100,6 +99,7 @@@ $_POST['pyt_discount_act']  = $myrow["p
  
  $_POST['exchange_diff_act'] = $myrow["exchange_diff_act"];
  $_POST['bank_charge_act'] = $myrow["bank_charge_act"];
 +$_POST['tax_algorithm'] = $myrow["tax_algorithm"];
  $_POST['default_sales_act'] = $myrow["default_sales_act"];
  $_POST['default_sales_discount_act']  = $myrow["default_sales_discount_act"];
  $_POST['default_prompt_payment_act']  = $myrow["default_prompt_payment_act"];
@@@ -137,8 -141,6 +141,8 @@@ gl_all_accounts_list_row(_("Exchange Va
  
  gl_all_accounts_list_row(_("Bank Charges Account:"), 'bank_charge_act', $_POST['bank_charge_act']);
  
 +tax_algorithm_list_row(_("Tax Algorithm:"), 'tax_algorithm', $_POST['tax_algorithm']);
 +
  //---------------
  
  table_section_title(_("Customers and Sales"));
diff --combined gl/gl_bank.php
index 9dc73c54b30d1adcfa5ff700e933a805ec32c550,97f67ddcb9815f7d123358d9ede77175a8467ded..58479d5bee8bed7f6ccd39efda69f8227fa64251
@@@ -22,6 -22,7 +22,7 @@@ include_once($path_to_root . "/includes
  include_once($path_to_root . "/gl/includes/ui/gl_bank_ui.inc");
  include_once($path_to_root . "/gl/includes/gl_db.inc");
  include_once($path_to_root . "/gl/includes/gl_ui.inc");
+ include_once($path_to_root . "/admin/db/attachments_db.inc");
  
  $js = '';
  if ($use_popup_windows)
@@@ -143,8 -144,6 +144,8 @@@ function create_cart($type, $trans_no
                unset ($_SESSION['pay_items']);
        }
  
 +      check_is_closed($type, $trans_no);
 +
        $cart = new items_cart($type);
      $cart->order_id = $trans_no;
  
                // apply exchange rate
                foreach($cart->gl_items as $line_no => $line)
                        $cart->gl_items[$line_no]->amount *= $ex_rate;
 -              
 +
        } else {
                $cart->reference = $Refs->get_next($cart->trans_type);
                $cart->tran_date = new_doc_date();
@@@ -265,7 -264,7 +266,7 @@@ if (isset($_POST['Process'])
        }
        elseif (!is_date_in_fiscalyear($_POST['date_']))
        {
 -              display_error(_("The entered date is not in fiscal year."));
 +              display_error(_("The entered date is out of fiscal year or is closed for further data entry."));
                set_focus('date_');
                $input_error = 1;
        } 
@@@ -295,7 -294,7 +296,7 @@@ if (isset($_POST['Process'])
                $_SESSION['pay_items']->trans_type, $_SESSION['pay_items']->order_id, $_POST['bank_account'],
                $_SESSION['pay_items'], $_POST['date_'],
                $_POST['PayType'], $_POST['person_id'], get_post('PersonDetailID'),
 -              $_POST['ref'], $_POST['memo_'], true);
 +              $_POST['ref'], $_POST['memo_'], false);
  
        $trans_type = $trans[0];
        $trans_no = $trans[1];
index 608f4e8ce71c6129fce1e765081acd057911166a,4a88583a24a73138d080699f128edbbfa5f934ae..0650a0c654ceafd40c6bb60a5ca984a016ebdb97
@@@ -116,6 -116,7 +116,6 @@@ function get_account_home_balance($pers
  }
  //------------- New helper functions for revaluation of customer/supplier currencies 2011-05-08 Joe Hunt.
  
 -
  function add_exchange_variation_all($date=null, $ref="", $memo)
  {
        global $Refs;
                }
        }
        //------------- END
 -              
 +
        commit_transaction();
        return array(($exchanged ? $trans_no : 0), $je);
  }
@@@ -251,8 -252,8 +251,7 @@@ function add_bank_transfer($from_accoun
        if ($SysPrefs->auto_currency_revaluation())
        {
                $currency = get_bank_account_currency($to_account);
-               if ($exchanged || add_exchange_variation($trans_no1, $date_, $to_account, $to_gl_account,
 -      
+               if (add_exchange_variation($trans_no1, $date_, $to_account, $to_gl_account,     
                        $currency, PT_MISC, $person_id))
                        $exchanged = true;
        }
@@@ -305,7 -306,6 +304,7 @@@ function write_bank_transaction($trans_
                'person_type_id', 'person_id', 'person_detail_id', 'ref', 'memo_', 'use_transaction'),
                $args);
        hook_db_prewrite($args, $trans_type);
 +
        $aid = 0;
        if ($trans_no) {
                $old_trans = $trans_no;
  
        return array($trans_type, $trans_no);
  }
 -
 -?>
index f9e5585c975669d0c32ab96227828aa5041ca007,8c4aec6ae44d2b27e7db29c0c6013add32e4a7b4..d68f09140bbb951795a7687dc129fc8f905fe647
@@@ -43,9 -43,9 +43,9 @@@ function display_order_header(&$Order
        {
                table_section(3, "40%");
                start_row();
 -              quick_entries_list_cells(_("Quick Entry").":", 'person_id', null, QE_JOURNAL, true);
 -              $qid = get_quick_entry(get_post('person_id'));
 -              if (list_updated('person_id')) {
 +              quick_entries_list_cells(_("Quick Entry").":", 'quick', null, QE_JOURNAL, true);
 +              $qid = get_quick_entry(get_post('quick'));
 +              if (list_updated('quick')) {
                        unset($_POST['totamount']); // enable default
                $Ajax->activate('totamount');
                }
@@@ -63,7 -63,7 +63,7 @@@
                end_row();
  
        }
 -              
 +
        end_outer_table(1);
  }
  
@@@ -77,9 -77,6 +77,9 @@@ function display_gl_items($title, &$ord
  
        $dim = get_company_pref('use_dimension');
  
 +      $sub_type = is_subledger_account(get_post('code_id'));
 +      $has_subaccounts = $order->has_sub_accounts();
 +
      div_start('items_table');
        start_table(TABLESTYLE, "colspan=7 width=95%");
        if ($dim == 2)
                        _("Debit"), _("Credit"), _("Memo"), "");
  
        if (count($order->gl_items)) $th[] = '';
 +      if ($sub_type || $has_subaccounts)
 +              array_insert($th, 2, _("Counterparty"));
  
 -      table_header($th);      
 +      table_header($th);
  
        $k = 0;
  
        $id = find_submit('Edit');
 +      if ($id == -1) 
 +              $id = get_post('Index', -1);
 +
        foreach ($order->gl_items as $line => $item) 
        {
                if ($id != $line)
                {
                alt_table_row_color($k);
  
 -                      label_cells($item->code_id, $item->description);
 +                      $acc = $item->code_id . ($item->person_id ? sprintf(' %05d', $item->person_id) : '');
 +                      label_cells($acc, $item->description);
 +
 +                      label_cell($item->person_name);
 +
                if ($dim >= 1)
                                label_cell(get_dimension_string($item->dimension_id, true));
                if ($dim > 1)
                {
                        amount_cell(abs($item->amount));
                        label_cell("");
 -              }       
 +              }
                else
                {
                        label_cell("");
                } 
                else 
                {
 -                      gl_edit_item_controls($order, $dim, $line);
 +                      gl_edit_item_controls($order, $dim, $item->person_id, $line);
                }
        }
  
        if ($id == -1)
 -              gl_edit_item_controls($order, $dim);
 +              gl_edit_item_controls($order, $dim, $sub_type);
  
        if ($order->count_gl_items()) 
        {
  
  //---------------------------------------------------------------------------------
  
 -function gl_edit_item_controls(&$order, $dim, $Index=null)
 +function gl_edit_item_controls(&$order, $dim, $sub_accounts, $Index=null)
  {
        global $Ajax;
        start_row();
  
        $id = find_submit('Edit');
 +      if ($id == -1) 
 +              $continue = $id = get_post('Index', -1);
 +
        if ($Index != -1 && $Index == $id)
        {
            // Modifying an existing row
                $item = $order->gl_items[$Index];
 -              $_POST['code_id'] = $item->code_id;
 -              $_POST['dimension_id'] = $item->dimension_id;
 -              $_POST['dimension2_id'] = $item->dimension2_id;
 -              if ($item->amount > 0)
 +              if (!isset($continue))
                {
 -                      $_POST['AmountDebit'] = price_format($item->amount);
 -                      $_POST['AmountCredit'] = "";
 +                      $_POST['code_id'] = $item->code_id;
 +                      $_POST['dimension_id'] = $item->dimension_id;
 +                      $_POST['dimension2_id'] = $item->dimension2_id;
 +                      $_POST['person_id'] = $item->person_id;
 +                      if ($item->amount > 0)
 +                      {
 +                              $_POST['AmountDebit'] = price_format($item->amount);
 +                              $_POST['AmountCredit'] = "";
 +                      }
 +                      else
 +                      {
 +                              $_POST['AmountDebit'] = "";
 +                              $_POST['AmountCredit'] = price_format(abs($item->amount));
 +                      }
 +                      $_POST['description'] = $item->description;
 +                      $_POST['LineMemo'] = $item->reference;
                }
 -              else
 -              {
 -                      $_POST['AmountDebit'] = "";
 -                      $_POST['AmountCredit'] = price_format(abs($item->amount));
 -              }       
 -              $_POST['description'] = $item->description;
 -              $_POST['LineMemo'] = $item->reference;
 -
                hidden('Index', $id);
                $skip_bank = !$_SESSION["wa_current_user"]->can_access('SA_BANKJOURNAL');
 -              echo gl_all_accounts_list('code_id', null, $skip_bank, true);
 +              echo gl_all_accounts_list('code_id', null, $skip_bank, true, _('[Select account]'), true, false, false);
 +
 +              if (is_subledger_account(get_post('code_id')))
 +              {
 +                      subledger_list_cells(null, 'person_id', get_post('code_id'));
 +              } elseif ($order->has_sub_accounts())
 +                      label_cell('');
                if ($dim >= 1) 
                        dimensions_list_cells(null, 'dimension_id', null, true, " ", false, 1);
                if ($dim > 1) 
        }
        else
        {
 -          // Adding a new row
 -              $_POST['AmountDebit'] = '';  //price_format(0);
 -              $_POST['AmountCredit'] = ''; //price_format(0);
 -              $_POST['dimension_id'] = 0;
 -              $_POST['dimension2_id'] = 0;
 -              //$_POST['LineMemo'] = ""; // let memo go to next line Joe Hunt 2010-05-30
 -              $_POST['_code_id_edit'] = "";
 -              $_POST['code_id'] = "";
 +
 +              if (!list_updated('code_id'))
 +              {
 +                  // Adding a new row
 +                      $_POST['AmountDebit'] = '';  //price_format(0);
 +                      $_POST['AmountCredit'] = ''; //price_format(0);
 +                      $_POST['dimension_id'] = 0;
 +                      $_POST['dimension2_id'] = 0;
 +                      //$_POST['LineMemo'] = ""; // let memo go to next line Joe Hunt 2010-05-30
 +                      $_POST['_code_id_edit'] = "";
 +                      $_POST['code_id'] = "";
 +              }
                if(isset($_POST['_code_id_update'])) {
 -                          $Ajax->activate('code_id');
 +                  $Ajax->activate('code_id');
                }
 -              
 +
                $skip_bank = !$_SESSION["wa_current_user"]->can_access('SA_BANKJOURNAL');
 -              echo gl_all_accounts_list('code_id', null, $skip_bank, true);
 +              echo gl_all_accounts_list('code_id', null, $skip_bank, true, _('[Select account]'), true, false, false);
 +
 +              if ($sub_accounts)
 +              {
 +                      subledger_list_cells(null, 'person_id', get_post('code_id'));
 +              }
 +              elseif ($order->has_sub_accounts())
 +                      label_cell('');
 +
                if ($dim >= 1)
                        dimensions_list_cells(null, 'dimension_id', null, true, " ", false, 1);
                if ($dim > 1)
@@@ -277,8 -241,8 +277,3 @@@ function gl_options_controls(
  
          echo "</table>";
  }
--
--
--//---------------------------------------------------------------------------------
--
--?>
index fa21d00b05fdc4f22108fccf3326440bfa6fe739,0000000000000000000000000000000000000000..fc057c25827bb85c22e91ad5837dc3994ab7ddbb
mode 100644,000000..100644
--- /dev/null
@@@ -1,108 -1,0 +1,109 @@@
-       if (!is_date_in_fiscalyears($date, false))
 +<?php
 +/**********************************************************************
 +    Copyright (C) FrontAccounting, LLC.
 +      Released under the terms of the GNU General Public License, GPL, 
 +      as published by the Free Software Foundation, either version 3 
 +      of the License, or (at your option) any later version.
 +    This program is distributed in the hope that it will be useful,
 +    but WITHOUT ANY WARRANTY; without even the implied warranty of
 +    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
 +    See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
 +***********************************************************************/
 +
 +$page_security = 'SA_GLCLOSE';
 +$path_to_root = "../..";
 +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 . "/admin/db/fiscalyears_db.inc");
 +
 +$js = "";
 +if ($use_date_picker)
 +      $js .= get_js_date_picker();
 +page(_($help_context = "Closing GL Transactions"), false, false, "", $js);
 +
 +//---------------------------------------------------------------------------------------------
 +function check_data()
 +{
 +      global $Refs, $allow_gl_reopen;
 +      
 +      if (!is_date($_POST['date']) || date1_greater_date2($_POST['date'], Today()))
 +      {
 +              display_error( _("The entered date is invalid."));
 +              set_focus('date');
 +              return false;
 +      }
++      if (!is_date_in_fiscalyears($_POST['date'], false))
 +      {
 +              display_error(_("Selected date is not in fiscal year or the year is closed."));
 +              set_focus('date');
 +              return false;
 +      }
 +      if (date1_greater_date2(sql2date(get_company_pref('gl_closing_date')), $_POST['date']))
 +      {
 +              if (!$allow_gl_reopen) {
 +                      display_error(_("The entered date is earlier than date already selected as closing date."));
 +                      set_focus('date');
 +                      return false;
 +              } elseif (!user_check_access('SA_GLREOPEN')) {
 +                      display_error(_("You are not allowed to reopen already closed transactions."));
 +                      set_focus('date');
 +                      return false;
 +              }
 +      }
 +      return true;
 +}
 +
 +//---------------------------------------------------------------------------------------------
 +
 +function handle_submit()
 +{
 +      if (!check_data())
 +              return;
 +
 +      if (!close_transactions($_POST['date']))
 +      {
 +              display_notification(
 +                      sprintf( _("All transactions resulting in GL accounts changes up to %s has been closed for further edition."),
 +                      sql2date(get_company_pref('gl_closing_date'))) );
 +      }
 +
 +}
 +
 +
 +//---------------------------------------------------------------------------------------------
 +
 +function clear_data()
 +{
 +      unset($_POST['date_']);
 +}
 +
 +//---------------------------------------------------------------------------------------------
 +
 +if (get_post('submit'))
 +      handle_submit();
 +else
 +      display_note(_("Using this feature you can prevent entering new transactions <br>
 +      and disable edition of already entered transactions up to specified date.<br>
 +      Only transactions which can generate GL postings are subject to the constraint."));
 +
 +//---------------------------------------------------------------------------------------------
 +
 +br(1);
 +start_form();
 +start_table(TABLESTYLE2);
 +if (!isset($_POST['date'])) {
 +      $cdate = sql2date(get_company_pref('gl_closing_date'));
 +      $_POST['date'] = $cdate ;// ? end_month(add_months($cdate, 1)) : Today();
 +}
 +date_row(_("End date of closing period:"), 'date');
 +end_table(1);
 +
 +submit_center('submit', _("Close Transactions"), true, false);
 +end_form();
 +
 +end_page();
 +
 +?>
diff --combined includes/data_checks.inc
index 543a7d5936edb3767cdef001198cfd60fe343a95,798e84c4b5c10070a4526a2ccbc7a2ad987b0898..f50e94540319f94d40b1a684c2e93f7de3751081
@@@ -485,17 -485,5 +485,16 @@@ function check_num($postname, $min=null
      return 1;
  }
  
 -
 -?>
 +function check_is_closed($type, $type_no, $msg=null)
 +{
 +      global $systypes_array;
 +      
 +    if (($type_no > 0) && is_closed_trans($type, $type_no))
 +    {
 +      if (!$msg)
 +              $msg = sprintf(_("%s #%s is closed for further edition."), $systypes_array[$type], $type_no);
 +      display_error($msg, true);
 +      end_page();
 +      exit;
 +    }
 +}
index 343e56ad3540aa746c64012ccef5a655f7971b82,6f8379e072877bbf9413f274ca29366da2af68a6..d1aacdf8302f7fbbf80da6089a8b16e86b19fda3
@@@ -160,29 -160,26 +160,29 @@@ function is_date_in_fiscalyear($date, $
        global $path_to_root;
        include_once($path_to_root . "/admin/db/fiscalyears_db.inc");
  
 -    //Chaitanya
 -    if ($convert)
 -        $date2 = sql2date($date);
 -    else
 -        $date2 = $date;
 -
 -    if ($_SESSION["wa_current_user"]->can_access('SA_MULTIFISCALYEARS')) // allow all open years for this one
 -        return is_date_in_fiscalyears($date2, false); 
 -
 -    $myrow = get_current_fiscalyear();
 -    if ($myrow['closed'] == 1)
 -        return 0;
 -    
 -    $begin = sql2date($myrow['begin']);
 -    $end = sql2date($myrow['end']);
 -    if (date1_greater_date2($begin, $date2) || date1_greater_date2($date2, $end))
 -    {
 -        return 0;
 -    }
 -    return 1;
 +      if ($convert)
 +              $date2 = sql2date($date);
 +      else
 +              $date2 = $date;
 +
 +      if (user_check_access('SA_MULTIFISCALYEARS')) // allow all open years for this one
 +              return is_date_in_fiscalyears($date2, false);
 +
 +      if (is_date_closed($date2))
 +              return 0;
 +      $myrow = get_current_fiscalyear();
 +      $begin = sql2date($myrow['begin']);
 +      $end = sql2date($myrow['end']);
 +      if (date1_greater_date2($begin, $date2) || date1_greater_date2($date2, $end))
 +      {
 +              return 0;
 +      }
 +      return 1;
 +}
 +
 +function is_date_closed($date)
 +{
 +      return !date1_greater_date2($date, sql2date(get_company_pref('gl_closing_date')));
  }
  
  function begin_fiscalyear()
@@@ -348,7 -345,7 +348,6 @@@ and converts to a yyyy/mm/dd format *
  
        $date_ = trim($date_);
      $year = $month = $day = 0;
--
      // Split up the date by the separator based on "how" to split it
      if ($how == 0) // MMDDYYYY
          list($month, $day, $year) = explode($sep, $date_);
index e19a659e7f13b8e0f6f43c695fe3a45ca9ba8838,f9efe9a01861a2d3016dbdbf21e7c4d1fcec4904..c25fdc5111526228c42f858afa8ed8756123b524
  
  function add_audit_trail($trans_type, $trans_no, $trans_date, $descr='')
  {
 +      $date = date2sql($trans_date);
        $sql = "INSERT INTO ".TB_PREF."audit_trail"
 -              . " (type, trans_no, user, fiscal_year, gl_date, description, gl_seq)
 +              . " (type, trans_no, user, gl_date, description)
                        VALUES(".db_escape($trans_type).", ".db_escape($trans_no).","
 -                      . $_SESSION["wa_current_user"]->user. ","
 -                      . get_company_pref('f_year') .","
 -                      . "'". date2sql($trans_date) ."',"
 -                      . db_escape($descr). ", 0)";
 +                      . $_SESSION["wa_current_user"]->user . ","
 +                      . "'$date',". db_escape($descr). ")";
  
        db_query($sql, "Cannot add audit info");
--      
 -      // all audit records beside latest one should have gl_seq set to NULL
 +      // all audit records beside just inserted one should have gl_seq set to NULL
        // to avoid need for subqueries (not existing in MySQL 3) all over the code
 -      $sql = "UPDATE ".TB_PREF."audit_trail SET gl_seq = NULL"
 +      $sql = "UPDATE ".TB_PREF."audit_trail audit LEFT JOIN ".TB_PREF."fiscal_year year ON year.begin<='$date' AND year.end>='$date'
 +              SET audit.gl_seq = IF(audit.id=".db_insert_id().", 0, NULL),"
 +              ."audit.fiscal_year=year.id"
                . " WHERE type=".db_escape($trans_type)." AND trans_no="
 -              .db_escape($trans_no)." AND id!=".db_insert_id();
 +              . db_escape($trans_no);
  
        db_query($sql, "Cannot update audit gl_seq");
  }
@@@ -59,18 -58,14 +58,18 @@@ function get_audit_trail_last($trans_ty
        and reindex     journal.
  */
  function close_transactions($todate) {
 +
 +      begin_transaction();
 +
        $errors = 0;
 -      $sql = "SELECT DISTINCT a.id, a.gl_date, a.fiscal_year"
 +      // select only those audit trail records which produce any GL postings
 +      $sql = "SELECT a.id, gl.tran_date, a.fiscal_year, a.gl_seq,
 +               gl.tran_date <= '". date2sql($todate) ."' as closed"
                ." FROM ".TB_PREF."gl_trans gl"
                ." LEFT JOIN ". TB_PREF."audit_trail a ON 
                        (gl.type=a.type AND gl.type_no=a.trans_no)"
 -              . " WHERE gl_date<='". date2sql($todate) ."'"
 -              . " AND NOT ISNULL(gl_seq)"
 -              . " ORDER BY a.fiscal_year, a.gl_date, a.id";
 +              . " WHERE NOT ISNULL(a.gl_seq) AND gl.amount!=0"        // skip old audit records and voided transactions
 +              . " GROUP BY  a.id, gl.tran_date, a.fiscal_year, a.gl_seq ORDER BY a.fiscal_year, gl.tran_date, a.id";
  
        $result = db_query($sql, "Cannot select transactions for closing");
  
                        }
                        if ($last_year != $row['fiscal_year']) {
                                $last_year = $row['fiscal_year'];
 -                              $counter = 1; // reset counter on fiscal year change
 -                      } else
 -                              $counter++;
 -                      $sql2 = "UPDATE ".TB_PREF."audit_trail SET"
 -                              . " gl_seq=$counter"
 -                              . " WHERE id=".$row['id'];
 -                                                                                      
 -                      db_query($sql2, "Cannot reindex journal");
 +                              $counter = 0; // reset counter on fiscal year change
 +                      }
-                       
++
 +                      $seq = $row['closed'] ? ++$counter : 0;
 +                      if ($row['gl_seq'] != $seq)     { // update transaction status only when gl_seq has changed
 +                              $sql2 = "UPDATE ".TB_PREF."audit_trail SET"
 +                                      . " gl_seq=$seq"
 +                                      . " WHERE id=".$row['id'];
 +                              db_query($sql2, "Cannot reindex journal");
 +                      }
                }
        }
 -      
++
        if ($errors) 
                display_warning(_("Some transactions journal GL postings were not indexed due to lack of audit trail record."));
 -}
 -
 -/*
 -      Reopen all transactions for edition up from date $fromdate
 -*/
 -function open_transactions($fromdate) {
 -
 -      $sql = "SELECT a.id, a.gl_date, a.fiscal_year"
 -              ." FROM ".TB_PREF."gl_trans gl"
 -              ." LEFT JOIN ". TB_PREF."audit_trail a ON 
 -                      (gl.type=a.type AND gl.type_no=a.trans_no)"
 -              . " WHERE gl_date>='". date2sql($fromdate) ."'"
 -              . " AND !ISNULL(gl_seq)"
 -              . " ORDER BY a.fiscal_year, a.gl_date, a.id";
 -
 -      $result = db_query($sql, "Cannot select transactions for openning");
 +      else
 +              update_company_prefs(array('gl_closing_date'=> date2sql($todate)));
 +      commit_transaction();
  
 -      if (db_num_rows($result)) {
 -              $last_year = 0;
 -
 -              while ($row = db_fetch($result)) {
 -                      if ($row['fiscal_year'] == null) {
 -                              continue;
 -                      }
 -                      $sql2 = "UPDATE ".TB_PREF."audit_trail SET"
 -                              . " gl_seq=0"
 -                              . " WHERE id=".$row['id'];
 -                                                                                      
 -                      db_query($sql2, "Cannot clear journal order");
 -              }
 -      }
 +      return $errors;
  }
 +
  /*
        Closed transactions have gl_seq number assigned.
  */
  function is_closed_trans($type, $trans_no) {
 +
 +      $cdate = get_company_pref('gl_closing_date');
 +      if (!$cdate)
 +              return false;
 +
 +// FIXME: gl_date can be badly entered for some transactions due to bug in previous FA versions 
        $sql = "SELECT  gl_seq  FROM ".TB_PREF."audit_trail"
                . " WHERE type=".db_escape($type)
                ." AND trans_no=".db_escape($trans_no)
 -              ." AND gl_seq>0";
 +              ." AND gl_date<='$cdate'"; // date is stored in sql format
 +//            ." AND (gl_date<='$cdate'" // some transaction can be not sequenced due to 0 amount, however after edition this could change
 +//            ." OR gl_seq>0)";
  
        $res = db_query($sql, "Cannot check transaction");
  
        return db_num_rows($res);
  }
  
  ?>
index 80f552e919b535fa624e06c88cb5664311bede90,068c1645ee7451e48f1f63c7d8ec975bc52e9098..e0ea2ef7646f00d33338e2ab29246d0561b5dcf0
@@@ -140,9 -140,9 +140,9 @@@ function last_negative_stock_trans_id($
                        $negative_trans_id = $myrow['trans_id'];
                }
                if ($qty >= 0)
 -                      $flag = 0;      
 +                      $flag = 0;
        }
 -              
 +
        if ($flag == 1)
                return $negative_trans_id;
        else 
@@@ -166,29 -166,29 +166,29 @@@ function get_deliveries_between($stock_
  function get_deliveries_from_trans($stock_id, $from)
  {
        // -ve qty is delivery either by ST_CUSTDELIVERY or inventory adjustment
 -    //Price for GRN and SUPPCREDIT and std_cost for other trans_types\r
 -    $sql = "SELECT SUM(-qty), SUM(-qty*IF(type=".ST_SUPPRECEIVE." OR type=".ST_SUPPCREDIT.", price, standard_cost))\r
 -        FROM ".TB_PREF."stock_moves\r
 -        WHERE stock_id=".db_escape($stock_id)." AND qty < 0 AND\r
 +    //Price for GRN and SUPPCREDIT and std_cost for other trans_types
 +    $sql = "SELECT SUM(-qty), SUM(-qty*IF(type=".ST_SUPPRECEIVE." OR type=".ST_SUPPCREDIT.", price, standard_cost))
 +        FROM ".TB_PREF."stock_moves
 +        WHERE stock_id=".db_escape($stock_id)." AND qty < 0 AND
              trans_id>='$from' GROUP BY stock_id";
        $result = db_query($sql, "The deliveries could not be updated");
        $row = db_fetch_row($result);
+       
 -    $sql = "SELECT IF(type=".ST_SUPPRECEIVE." OR type=".ST_SUPPCREDIT.", price, standard_cost)\r
 -        FROM ".TB_PREF."stock_moves\r
 -        WHERE stock_id=".db_escape($stock_id)\r
 -            ." AND trans_id ='$from'";\r
 -    $result = db_query($sql, "The deliveries could not be updated");\r
 +    $sql = "SELECT IF(type=".ST_SUPPRECEIVE." OR type=".ST_SUPPCREDIT.", price, standard_cost)
 +        FROM ".TB_PREF."stock_moves
 +        WHERE stock_id=".db_escape($stock_id)
 +            ." AND trans_id ='$from'";
 +    $result = db_query($sql, "The deliveries could not be updated");
      $cost = db_fetch_row($result);
 -      
 +
        // Adjusting QOH valuation 
        $sql = "SELECT SUM(qty) FROM ".TB_PREF."stock_moves
                WHERE stock_id=".db_escape($stock_id)." AND
                        trans_id<'$from' GROUP BY stock_id";
        $result = db_query($sql, "The deliveries could not be updated");
        $qoh = db_fetch_row($result);
--      
 -      $qty = $row[0] - $qoh[0]; //QOH prior to -ve stock is subtracted\r
++
 +      $qty = $row[0] - $qoh[0]; //QOH prior to -ve stock is subtracted
        $final_cost = $row[1] - $qoh[0]*$cost[0];
        
        return array($qty,$final_cost); 
@@@ -234,7 -234,7 +234,7 @@@ function adjust_deliveries($stock_id, $
                $new_purchase_cost = $row[0] * $material_cost;
                $purchase_diff = $new_purchase_cost - $old_purchase_cost;
        }
 -      
 +
        $diff =  $sales_diff - $purchase_diff;
        
        if ($diff != 0)
@@@ -271,10 -271,10 +271,10 @@@ function get_stock_gl_code($stock_id
  }
  
  //-----------------------------------------------------------------------------------------
 -\r
 +
  function handle_negative_inventory($stock_id, $quantity, $standard_cost, $date_)
  {
 -      //If negative adjustment result in negative or zero inventory \r
 +      //If negative adjustment result in negative or zero inventory
        //then difference should be adjusted
        $qoh = get_qoh_on_date($stock_id);
  
@@@ -381,16 -381,18 +381,16 @@@ function get_stock_moves($type, $type_n
  
  function void_stock_move($type, $type_no)
  {
 -   
      $sql = "SELECT stock_id, standard_cost, loc_code, tran_date, reference, person_id, visible, discount_percent, price, 
        sum(qty) qty FROM ".TB_PREF."stock_moves WHERE type=".db_escape($type)." AND trans_no=".db_escape($type_no)." 
        GROUP BY stock_id, standard_cost, loc_code, tran_date, reference, person_id, visible, discount_percent, price HAVING sum(qty) <> 0";
  
 -
      $result = db_query($sql, "Could not void stock moves");
      while ($row = db_fetch($result))
      {
                //Skip cost averaging of service items
                if (is_inventory_item($row["stock_id"]))
 -              {        
 +              {
                        // The cost has to be adjusted.
                        // Transaction rates are stored either as price or standard_cost depending on types
                        $types = array(ST_SUPPCREDIT, ST_SUPPRECEIVE);
                        update_average_material_cost(0, $row["stock_id"],
                                $trans_rate, -$row["qty"], sql2date($row["tran_date"]));
                }
 -              
 +
                //Post stock move for service items also
          add_stock_move($type, $row["stock_id"], $type_no, $row["loc_code"],
                sql2date($row["tran_date"]), $row["reference"], -$row["qty"]
                        , $row["standard_cost"], $row["person_id"], $row["visible"],
                $row["price"], $row["discount_percent"]);
 -    }\r
 +    }
  }
  
  //--------------------------------------------------------------------------------------------------
@@@ -428,8 -430,8 +428,3 @@@ function get_location_name($loc_code
  
        display_db_error("could not retreive the location name for $loc_code", $sql, true);
  }
--
--//--------------------------------------------------------------------------------------------------
--
--
--?>
diff --combined includes/main.inc
index 8f2b3c33d56ea3912b97e3579d6b9488b45c9aa4,8f2b3c33d56ea3912b97e3579d6b9488b45c9aa4..98143cf9843626965a97036f555bf0008be2baff
@@@ -22,21 -22,21 +22,24 @@@ include_once($path_to_root . "/includes
  include_once($path_to_root . "/admin/db/users_db.inc");
  include_once($path_to_root . "/includes/ui/ui_view.inc");
  include_once($path_to_root . "/includes/ui/ui_controls.inc");
--      
++
++$page_nested = -1;
++
  function page($title, $no_menu=false, $is_index=false, $onload="", $js="", $script_only=false, $css='')
  {
  
--      global $path_to_root, $page_security;
++      global $path_to_root, $page_security, $page_nested;
  
++      if (++$page_nested) return;
  
        $hide_menu = $no_menu;
  
--      include($path_to_root . "/includes/page/header.inc");
++      include_once($path_to_root . "/includes/page/header.inc");
  
        page_header($title, $no_menu, $is_index, $onload, $js, $css);
        check_page_security($page_security);
  //    error_box();
--      if($script_only) {              
++      if($script_only) {
                echo '<noscript>';
                echo display_heading(_('This page is usable only with javascript enabled browsers.'));
                echo '</noscript>';
  
  function end_page($no_menu=false, $is_index=false, $final_screen=false, $type_no=0, $trans_no=0)
  {
--      global $path_to_root;
++      global $path_to_root, $page_nested;
++
++      if ($page_nested-- > 0) return;
  
        if (!$is_index && function_exists('hyperlink_back'))
                hyperlink_back(true, $no_menu, $type_no, $trans_no, $final_screen);
        div_end();      // end of _page_body section
  
--      include($path_to_root . "/includes/page/footer.inc");
++      include_once($path_to_root . "/includes/page/footer.inc");
        page_footer($no_menu, $is_index);
  }
  
diff --combined includes/session.inc
index 592d4644f6106d60516b03ea4e046bc605585eff,7cd9d749fe3dcec85b13a5b0f4d43e62fab8f401..98ed4677ccba50aab299aa3e16ae525a76ec968e
@@@ -102,6 -102,7 +102,7 @@@ class SessionManage
                return true;
        }
  }
  function output_html($text)
  {
        global $before_box, $Ajax, $messages;
@@@ -293,8 -294,6 +294,8 @@@ foreach ($installed_extensions as $ext
  
  ini_set('session.gc_maxlifetime', 36000); // 10hrs
  
 +hook_session_start(@$_POST["company_login_name"]);
 +
  $Session_manager = new SessionManager();
  $Session_manager->sessionStart('FA'.md5(dirname(__FILE__)));
  
@@@ -318,7 -317,6 +319,7 @@@ $_SESSION['language']->set_language($_S
  include_once($path_to_root . "/includes/access_levels.inc");
  include_once($path_to_root . "/version.php");
  include_once($path_to_root . "/includes/main.inc");
 +include_once($path_to_root . "/includes/app_entries.inc");
  
  // Ajax communication object
  $Ajax = new Ajax();
@@@ -398,3 -396,5 +399,3 @@@ $SysPrefs = &$_SESSION['SysPrefs']
  // POST vars cleanup needed for direct reuse.
  // We quote all values later with db_escape() before db update.
  $_POST = strip_quotes($_POST);
 -
 -?>
diff --combined includes/types.inc
index ec06fbaa62379cf8bc756bc45e2f29dbdab71f0d,79ef8be71c01699d87a8daf242fee733ad718fe3..94d5c4e026391ecf95fb7180025e63560fa7167b
@@@ -137,80 -137,6 +137,79 @@@ function payment_person_name($type, $pe
        }
  }
  
 +//
 +//    Returns counterparty (supplier/customer) name for selected transaction.
 +//
 +function get_counterparty_name($trans_type, $trans_no, $full=true)
 +{
 +      switch($trans_type)
 +      {
 +              case ST_SALESORDER:
 +              case ST_SALESQUOTE:
 +                      $sql = "SELECT order.customer_id as person_id, debtor.name as name
 +                      FROM ".TB_PREF."sales_orders order, ".TB_PREF."debtors_master debtor
 +                      WHERE order_no=".db_escape($trans_no)." AND trans_type=".db_escape($trans_type)
 +                      ." AND order.debtor_no=debtor.debtor_no";
 +                      break;
 +              case ST_SALESINVOICE :
 +              case ST_CUSTCREDIT :
 +              case ST_CUSTPAYMENT :
 +              case ST_CUSTDELIVERY :
 +                      $sql = "SELECT trans.debtor_no as person_id, debtor.name as name
 +                      FROM ".TB_PREF."debtor_trans trans, ".TB_PREF."debtors_master debtor
 +                      WHERE trans_no=".db_escape($trans_no)." AND type=".db_escape($trans_type)
 +                      ." AND trans.debtor_no=debtor.debtor_no";
 +                      break;
 +
 +              case ST_PURCHORDER :
 +                      $sql = "SELECT order.supplier_id as person_id, supp.supp_name as name
 +                      FROM ".TB_PREF."purch_orders order, ".TB_PREF."suppliers supp
 +                      WHERE order_no=".db_escape($trans_no)
 +                      ." AND order.supplier_id=supp.supplier_id";
 +                      break;
 +
 +              case ST_SUPPINVOICE :
 +              case ST_SUPPCREDIT :
 +              case ST_SUPPAYMENT :
 +                      $sql = "SELECT trans.supplier_id as person_id, supp.supp_name as name
 +                      FROM ".TB_PREF."supp_trans trans, ".TB_PREF."suppliers supp
 +                      WHERE trans_no=".db_escape($trans_no)." AND type=".db_escape($trans_type)
 +                      ." AND trans.supplier_id=supp.supplier_id";
 +                      break;
 +
 +              case ST_SUPPRECEIVE :
 +                      $sql = "SELECT trans.supplier_id as person_id, supp.supp_name as name
 +                      FROM ".TB_PREF."grn_batch trans, ".TB_PREF."suppliers supp
 +                      WHERE id=".db_escape($trans_no)
 +                      ." AND trans.supplier_id=supp.supplier_id";
 +                      break;
 +
 +              case ST_JOURNAL:        // FIXME - this one can have multiply counterparties of various types depending on person_type_id
 +
 +              default: 
 +              /*      // internal operations
 +              case ST_WORKORDER :
 +              case ST_INVADJUST : // GRN/DN returns ?
 +              case ST_BANKTRANSFER :
 +              case ST_LOCTRANSFER :
 +              case ST_MANUISSUE :
 +              case ST_MANURECEIVE :
 +              case ST_COSTUPDATE :
 +              case ST_BANKPAYMENT :   // generic bank transactions
 +              case ST_BANKDEPOSIT :*/
 +                      return null;
 +      }
 +
 +      $result = db_query($sql, 'cannot retrieve counterparty name');
 +      if (db_num_rows($result))
 +      {
 +              $row = db_fetch($result);
 +              return sprintf("[%05s] %s", $row['person_id'], $row['name']);
 +      }
 +
 +      return '';
 +}
 +
  function payment_person_has_items($type) {
        switch ($type)
        {
@@@ -245,7 -171,6 +244,7 @@@ define('WO_ADVANCED', 2)
  
  define('WO_LABOUR', 0);
  define('WO_OVERHEAD', 1);
 +define('WO_MATERIALS', 2);
  
  //----------------------------------------------------------------------------------
  //    GL account classes
@@@ -301,19 -226,6 +300,19 @@@ define('PTT_CASH', 2)
  define('PTT_DAYS', 3);
  define('PTT_FOLLOWING', 4);
  
 +//----------------------------------------------------------------------------------
 +// Tax calculation algorithms used in als and purchase (depends on supplier's invoicing software)
 +
 +define('TCA_TOTALS', 1); // taxes are calculated from respective net totals for all lines
 +define('TCA_LINES', 2); // taxes calculated for every line, then summed
 +//
 +//    Bank account owner types
 +//
 +define('BO_UNKNOWN', 0);
 +define('BO_COMPANY', 1);
 +define('BO_CUSTBRANCH', 2);
 +define('BO_SUPPLIER', 3);
 +
  include_once($path_to_root . '/includes/sysnames.inc');
  
  ?>
index d2e094ae45e7e462bb2d67a7969e42c4182f9ea5,bbe4c7f5142f3680055589e48ecbe906daaca390..0639124a5a236a4f6170ca70b57c0c7a5b637dd8
@@@ -32,10 -32,10 +32,15 @@@ function get_post($name, $dflt=''
                                ((!isset($_POST[$name]) || $_POST[$name] === '') ? $dflt : $_POST[$name]);
  }
  //---------------------------------------------------------------------------------
++$form_nested = -1;
  
  function start_form($multi=false, $dummy=false, $action="", $name="")
  {
        // $dummy - leaved for compatibility with 2.0 API
++      global $form_nested;
++
++      if (++$form_nested) return;
++
  
        if ($name != "")
                $name = "name='$name'";
@@@ -53,7 -53,7 +58,9 @@@
  
  function end_form($breaks=0)
  {
--      global $Ajax;
++      global $Ajax, $form_nested;
++
++      if ($form_nested-- > 0) return;
  
        $_SESSION['csrf_token'] = hash('sha256', uniqid(mt_rand(), true));
        if ($breaks)
@@@ -470,7 -470,7 +477,7 @@@ function set_editor($type, $input, $cal
  
        $Editors[$key] = array( $path_to_root . $popup_editors[$type][0], $input, 
                $popup_editors[$type][3], $popup_editors[$type][4]);
 -      
 +
        $help = 'F' . ($key - 111) . ' - ';
        $help .= $popup_editors[$type][2];
        $Pagehelp[] = $help;
index a874adedc353d4376a8c52eecda6e5f55d98e2d1,b82bd46a4fa36b77d39205ecfc2e7ec393b948e3..804d5ae202a8c9e176402edb869cfac220715293
@@@ -8,451 -8,489 +8,495 @@@ msgid "
  msgstr ""
  "Project-Id-Version: PACKAGE VERSION\n"
  "Report-Msgid-Bugs-To: \n"
- "POT-Creation-Date: 2010-08-13 15:12+0200\n"
++"POT-Creation-Date: 2012-02-29 09:49+0100\n"
  "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
  "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
  "Language-Team: LANGUAGE <LL@li.org>\n"
+ "Language: \n"
  "MIME-Version: 1.0\n"
- "Content-Type: text/plain; charset=CHARSET\n"
+ "Content-Type: text/plain; charset=ISO-8859-2\n"
  "Content-Transfer-Encoding: 8bit\n"
  
- #: ../install/index.php:20 ../install/index.php:40
 -#: install/index.php:20 install/index.php:40
++#: install/index.php:20 install/index.php:41
  msgid "FrontAccouting ERP Installation Wizard"
  msgstr ""
  
- #: ../install/index.php:41
 -#: install/index.php:41
++#: install/index.php:42
  #, php-format
  msgid "Step %d: %s"
  msgstr ""
  
- #: ../install/index.php:48
 -#: install/index.php:48
++#: install/index.php:49
  msgid "Chart of accounts"
  msgstr ""
  
- #: ../install/index.php:48 ../install/index.php:75
 -#: install/index.php:48 install/index.php:75
++#: install/index.php:49 install/index.php:76
  msgid "Encoding"
  msgstr ""
  
- #: ../install/index.php:48 ../install/index.php:75
 -#: install/index.php:48 install/index.php:75
++#: install/index.php:49 install/index.php:76
  msgid "Description"
  msgstr ""
  
- #: ../install/index.php:48 ../install/index.php:75
 -#: install/index.php:48 install/index.php:75
++#: install/index.php:49 install/index.php:76
  msgid "Install"
  msgstr ""
  
- #: ../install/index.php:65 ../install/index.php:93
 -#: install/index.php:65 install/index.php:93
++#: install/index.php:66 install/index.php:94
  msgid "Installed"
  msgstr ""
  
- #: ../install/index.php:75
 -#: install/index.php:75
++#: install/index.php:76
  msgid "Language"
  msgstr ""
  
- #: ../install/index.php:156
 -#: install/index.php:123
++#: install/index.php:124
+ msgid ""
+ "Cannot connect to database. User or password is invalid or you have no "
+ "permittions to create database."
+ msgstr ""
 -#: install/index.php:159
++#: install/index.php:160
  msgid "Cannot save system configuration file 'config.php'."
  msgstr ""
  
- #: ../install/index.php:173
 -#: install/index.php:166
++#: install/index.php:167
  msgid "Cannot open 'config_db.php' configuration file."
  msgstr ""
  
- #: ../install/index.php:176
 -#: install/index.php:169
++#: install/index.php:170
  msgid "Cannot write to the 'config_db.php' configuration file."
  msgstr ""
  
- #: ../install/index.php:179
 -#: install/index.php:172
++#: install/index.php:173
  msgid ""
  "Configuration file 'config_db.php' is not writable. Change its permissions "
  "so it is, then re-run installation step."
  msgstr ""
  
- #: ../install/index.php:217
+ #: install/index.php:211
  msgid "Host name cannot be empty."
  msgstr ""
  
- #: ../install/index.php:221
+ #: install/index.php:215
  msgid "Database user name cannot be empty."
  msgstr ""
  
- #: ../install/index.php:225
+ #: install/index.php:219
  msgid "Database name cannot be empty."
  msgstr ""
  
- #: ../install/index.php:277
+ #: install/index.php:272
  msgid "Company name cannot be empty."
  msgstr ""
  
- #: ../install/index.php:281
+ #: install/index.php:276
  msgid "Company admin name cannot be empty."
  msgstr ""
  
- #: ../install/index.php:285
+ #: install/index.php:280
  msgid "Company admin password cannot be empty."
  msgstr ""
  
- #: ../install/index.php:289
+ #: install/index.php:284
  msgid "Company admin passwords differ."
  msgstr ""
  
- #: ../install/index.php:321
+ #: install/index.php:316
  msgid "System Diagnostics"
  msgstr ""
  
- #: ../install/index.php:323
+ #: install/index.php:318
  msgid "Select install wizard language:"
  msgstr ""
  
- #: ../install/index.php:329
+ #: install/index.php:324
  msgid ""
  "All application preliminary requirements seems to be correct. Please press "
  "Continue button below."
  msgstr ""
  
- #: ../install/index.php:330 ../install/index.php:356 ../install/index.php:363
- #: ../install/index.php:370 ../install/index.php:389
+ #: install/index.php:325 install/index.php:351 install/index.php:358
 -#: install/index.php:365 install/index.php:384
++#: install/index.php:365 install/index.php:389
  msgid "Continue >>"
  msgstr ""
  
- #: ../install/index.php:332
+ #: install/index.php:327
  msgid ""
  "Application cannot be installed. Please fix problems listed below in red, "
  "and press Refresh button."
  msgstr ""
  
- #: ../install/index.php:333
+ #: install/index.php:328
  msgid "Refresh"
  msgstr ""
  
- #: ../install/index.php:343
+ #: install/index.php:338
  msgid "Database Server Settings"
  msgstr ""
  
- #: ../install/index.php:345
+ #: install/index.php:340
  msgid "Server Host:"
  msgstr ""
  
- #: ../install/index.php:346
+ #: install/index.php:341
  msgid "Database User:"
  msgstr ""
  
- #: ../install/index.php:347
+ #: install/index.php:342
  msgid "Database Password:"
  msgstr ""
  
- #: ../install/index.php:348
+ #: install/index.php:343
  msgid "Database Name:"
  msgstr ""
  
- #: ../install/index.php:349
+ #: install/index.php:344
  msgid "Use '0_' Table Prefix:"
  msgstr ""
  
- #: ../install/index.php:349 ../includes/system_tests.inc:38
- #: ../includes/system_tests.inc:113 ../includes/system_tests.inc:126
+ #: install/index.php:344 includes/system_tests.inc:38
+ #: includes/system_tests.inc:113 includes/system_tests.inc:126
  msgid "Yes"
  msgstr ""
  
- #: ../install/index.php:349 ../includes/system_tests.inc:38
- #: ../includes/system_tests.inc:113 ../includes/system_tests.inc:126
+ #: install/index.php:344 includes/system_tests.inc:38
+ #: includes/system_tests.inc:113 includes/system_tests.inc:126
  msgid "No"
  msgstr ""
  
- #: ../install/index.php:350
+ #: install/index.php:345
  msgid "Install Additional Language Packs from FA Repository:"
  msgstr ""
  
- #: ../install/index.php:351
+ #: install/index.php:346
  msgid "Install Additional COAs from FA Repository:"
  msgstr ""
  
- #: ../install/index.php:353
+ #: install/index.php:348
  msgid ""
  "Use table prefix if you share selected database for more than one FA company."
  msgstr ""
  
- #: ../install/index.php:354
+ #: install/index.php:349
  msgid ""
  "Do not select additional langs nor COAs if you have no working internet "
  "connection right now. You can install them later."
  msgstr ""
  
- #: ../install/index.php:355 ../install/index.php:362 ../install/index.php:369
- #: ../install/index.php:388
+ #: install/index.php:350 install/index.php:357 install/index.php:364
 -#: install/index.php:383
++#: install/index.php:388
  msgid "<< Back"
  msgstr ""
  
- #: ../install/index.php:360
+ #: install/index.php:355
  msgid "User Interface Languages Selection"
  msgstr ""
  
- #: ../install/index.php:367
+ #: install/index.php:362
  msgid "Charts of Accounts Selection"
  msgstr ""
  
- #: ../install/index.php:379
 -#: install/index.php:374
++#: install/index.php:379
  msgid "Company Settings"
  msgstr ""
  
- #: ../install/index.php:381
 -#: install/index.php:376
++#: install/index.php:381
  msgid "Company Name:"
  msgstr ""
  
- #: ../install/index.php:382
 -#: install/index.php:377
++#: install/index.php:382
  msgid "Admin Login:"
  msgstr ""
  
- #: ../install/index.php:383
 -#: install/index.php:378
++#: install/index.php:383
  msgid "Admin Password:"
  msgstr ""
  
- #: ../install/index.php:384
 -#: install/index.php:379
++#: install/index.php:384
  msgid "Reenter Password:"
  msgstr ""
  
- #: ../install/index.php:385
 -#: install/index.php:380
++#: install/index.php:385
  msgid "Select Chart of Accounts:"
  msgstr ""
  
- #: ../install/index.php:386
 -#: install/index.php:381
++#: install/index.php:386
  msgid "Select Default Language:"
  msgstr ""
  
- #: ../install/index.php:393
 -#: install/index.php:388
++#: install/index.php:393
  msgid "FrontAccounting ERP has been installed successsfully."
  msgstr ""
  
- #: ../install/index.php:394
 -#: install/index.php:389
++#: install/index.php:394
  msgid "Please do not forget to remove install wizard folder."
  msgstr ""
  
- #: ../install/index.php:396
 -#: install/index.php:392
++#: install/index.php:397
  msgid "Click here to start."
  msgstr ""
  
- #: ../includes/system_tests.inc:15
+ #: includes/system_tests.inc:15
  msgid "Info"
  msgstr ""
  
- #: ../includes/system_tests.inc:16
+ #: includes/system_tests.inc:16
  msgid "Optional"
  msgstr ""
  
- #: ../includes/system_tests.inc:17
+ #: includes/system_tests.inc:17
  msgid "Recommended"
  msgstr ""
  
- #: ../includes/system_tests.inc:18
+ #: includes/system_tests.inc:18
  msgid "Required "
  msgstr ""
  
- #: ../includes/system_tests.inc:24
+ #: includes/system_tests.inc:24
  msgid "MySQL version"
  msgstr ""
  
- #: ../includes/system_tests.inc:28
+ #: includes/system_tests.inc:28
  msgid "Upgrade MySQL server to version at least 4.1"
  msgstr ""
  
- #: ../includes/system_tests.inc:35
+ #: includes/system_tests.inc:35
  msgid "PHP MySQL extension"
  msgstr ""
  
- #: ../includes/system_tests.inc:40
+ #: includes/system_tests.inc:40
  msgid "Your PHP has to have MySQL extension enabled."
  msgstr ""
  
- #: ../includes/system_tests.inc:46
+ #: includes/system_tests.inc:46
  msgid "PHP version"
  msgstr ""
  
- #: ../includes/system_tests.inc:50
+ #: includes/system_tests.inc:50
  msgid "Upgrade PHP to version at least 4.3.3"
  msgstr ""
  
- #: ../includes/system_tests.inc:57
+ #: includes/system_tests.inc:57
  msgid "Server system"
  msgstr ""
  
- #: ../includes/system_tests.inc:67
+ #: includes/system_tests.inc:67
  msgid "Session save path"
  msgstr ""
  
- #: ../includes/system_tests.inc:79
+ #: includes/system_tests.inc:79
  msgid "Removed install wizard folder"
  msgstr ""
  
- #: ../includes/system_tests.inc:82
+ #: includes/system_tests.inc:82
  msgid "Not removed"
  msgstr ""
  
- #: ../includes/system_tests.inc:83
+ #: includes/system_tests.inc:83
  msgid "Remove or rename install wizard folder for security reasons."
  msgstr ""
  
- #: ../includes/system_tests.inc:90
+ #: includes/system_tests.inc:90
  msgid "Browser type"
  msgstr ""
  
- #: ../includes/system_tests.inc:94
+ #: includes/system_tests.inc:94
  msgid "Any browser is supported"
  msgstr ""
  
- #: ../includes/system_tests.inc:101
+ #: includes/system_tests.inc:101
  msgid "Http server type"
  msgstr ""
  
- #: ../includes/system_tests.inc:105
+ #: includes/system_tests.inc:105
  msgid "Any server is supported"
  msgstr ""
  
- #: ../includes/system_tests.inc:112
+ #: includes/system_tests.inc:112
  msgid "Native gettext"
  msgstr ""
  
- #: ../includes/system_tests.inc:116
+ #: includes/system_tests.inc:116
  msgid "In case of no gettext support, php emulation is used"
  msgstr ""
  
- #: ../includes/system_tests.inc:124
+ #: includes/system_tests.inc:124
  msgid "Debugging mode"
  msgstr ""
  
- #: ../includes/system_tests.inc:128
+ #: includes/system_tests.inc:128
  msgid "To switch debugging on set $go_debug>0 in config.php file"
  msgstr ""
  
- #: ../includes/system_tests.inc:137
+ #: includes/system_tests.inc:137
  msgid "Error logging"
  msgstr ""
  
- #: ../includes/system_tests.inc:145
+ #: includes/system_tests.inc:145
  msgid "Disabled"
  msgstr ""
  
- #: ../includes/system_tests.inc:148
+ #: includes/system_tests.inc:148
  msgid "To switch error logging set $error_logging in config.php file"
  msgstr ""
  
- #: ../includes/system_tests.inc:151
+ #: includes/system_tests.inc:151
  msgid "Log file is not writeable"
  msgstr ""
  
- #: ../includes/system_tests.inc:161
+ #: includes/system_tests.inc:161
  msgid "Current database version"
  msgstr ""
  
- #: ../includes/system_tests.inc:165
+ #: includes/system_tests.inc:165
  msgid "Database structure seems to be not upgraded to current version"
  msgstr ""
  
- #: ../includes/system_tests.inc:180
+ #: includes/system_tests.inc:180
  msgid "Company subdirectories consistency"
  msgstr ""
  
- #: ../includes/system_tests.inc:193 ../includes/system_tests.inc:200
- #: ../includes/system_tests.inc:208 ../includes/system_tests.inc:225
- #: ../includes/system_tests.inc:340 ../includes/system_tests.inc:349
- #: ../includes/system_tests.inc:358
+ #: includes/system_tests.inc:193 includes/system_tests.inc:200
+ #: includes/system_tests.inc:208 includes/system_tests.inc:225
+ #: includes/system_tests.inc:340 includes/system_tests.inc:349
+ #: includes/system_tests.inc:358
  #, php-format
  msgid "'%s' is not writeable"
  msgstr ""
  
- #: ../includes/system_tests.inc:221
+ #: includes/system_tests.inc:221
  msgid "Temporary directory"
  msgstr ""
  
- #: ../includes/system_tests.inc:233
+ #: includes/system_tests.inc:233
  msgid "Language configuration consistency"
  msgstr ""
  
- #: ../includes/system_tests.inc:242
+ #: includes/system_tests.inc:242
  msgid "Languages folder should be writeable."
  msgstr ""
  
- #: ../includes/system_tests.inc:251
+ #: includes/system_tests.inc:251
  msgid "Languages configuration file should be writeable."
  msgstr ""
  
- #: ../includes/system_tests.inc:270
+ #: includes/system_tests.inc:270
  #, php-format
  msgid "Missing %s translation file."
  msgstr ""
  
- #: ../includes/system_tests.inc:275
+ #: includes/system_tests.inc:275
  #, php-format
  msgid "Missing system locale: %s"
  msgstr ""
  
- #: ../includes/system_tests.inc:288
+ #: includes/system_tests.inc:288
  msgid "Main config file"
  msgstr ""
  
- #: ../includes/system_tests.inc:295 ../includes/system_tests.inc:317
+ #: includes/system_tests.inc:295 includes/system_tests.inc:317
  #, php-format
  msgid "Can't write '%s' file. Check FA directory write permissions."
  msgstr ""
  
- #: ../includes/system_tests.inc:296 ../includes/system_tests.inc:318
+ #: includes/system_tests.inc:296 includes/system_tests.inc:318
  #, php-format
  msgid "'%s' file exists."
  msgstr ""
  
- #: ../includes/system_tests.inc:300
+ #: includes/system_tests.inc:300
  #, php-format
  msgid "'%s' file should be read-only"
  msgstr ""
  
- #: ../includes/system_tests.inc:309
+ #: includes/system_tests.inc:309
  msgid "Database auth file"
  msgstr ""
  
- #: ../includes/system_tests.inc:322
+ #: includes/system_tests.inc:322
  #, php-format
  msgid ""
  "'%s' file should be read-only if you do not plan to add or change companies"
  msgstr ""
  
- #: ../includes/system_tests.inc:333
+ #: includes/system_tests.inc:333
  msgid "Extensions system"
  msgstr ""
  
- #: ../includes/system_tests.inc:363
+ #: includes/system_tests.inc:363
  msgid "Extensions configuration files and directories should be writeable"
  msgstr ""
  
- #: ../includes/system_tests.inc:375
+ #: includes/system_tests.inc:375
  #, php-format
  msgid "Non-standard theme directory '%s' is not writable"
  msgstr ""
  
- #: ../includes/system_tests.inc:385
+ #: includes/system_tests.inc:385
  msgid ""
  "OpenSSL PHP extension have to be enabled to use extension repository system."
  msgstr ""
  
- #: ../includes/system_tests.inc:388
+ #: includes/system_tests.inc:388
  msgid ""
  "OpenSSL have to be available on your server to use extension repository "
  "system."
  msgstr ""
  
- #: ../includes/system_tests.inc:411
+ #: includes/system_tests.inc:411
  msgid "Test"
  msgstr ""
  
- #: ../includes/system_tests.inc:411
+ #: includes/system_tests.inc:411
  msgid "Test type"
  msgstr ""
  
- #: ../includes/system_tests.inc:411
+ #: includes/system_tests.inc:411
  msgid "Value"
  msgstr ""
  
- #: ../includes/system_tests.inc:411
+ #: includes/system_tests.inc:411
  msgid "Comments"
  msgstr ""
  
- #: ../includes/system_tests.inc:435
+ #: includes/system_tests.inc:435
  msgid "Ok"
  msgstr ""
 -#: includes/packages.inc:295
+ #: includes/packages.inc:190
+ #, php-format
+ msgid "No key field '%s' in file '%s'"
+ msgstr ""
 -#: includes/packages.inc:311
++#: includes/packages.inc:295 includes/packages.inc:329
++#, php-format
++msgid "Cannot delete outdated '%s' file."
++msgstr ""
++
++#: includes/packages.inc:299
+ msgid "Release file in repository is invalid, or public key is outdated."
+ msgstr ""
 -#: includes/packages.inc:325
++#: includes/packages.inc:316
+ msgid "Repository version does not match application version."
+ msgstr ""
 -#: includes/packages.inc:358
++#: includes/packages.inc:333
+ #, php-format
+ msgid ""
+ "Security alert: broken index file in repository '%s'. Please inform "
+ "repository administrator about this issue."
+ msgstr ""
 -#: includes/packages.inc:613 includes/packages.inc:664
++#: includes/packages.inc:366
+ #, php-format
+ msgid ""
+ "Security alert: broken package '%s' in repository. Please inform repository "
+ "administrator about this issue."
+ msgstr ""
++#: includes/packages.inc:621 includes/packages.inc:672
+ #, php-format
+ msgid "Package '%s' not found."
+ msgstr ""
index 384dd30ce63bb4adc2e674a1f509b56b44a3420c,cba646365a9e7e7e91688e09f77f3d31881edb3c..51edf4d4ed86495b9390c7176c64bbf8be80bc5c
@@@ -47,6 -47,8 +47,8 @@@ if (isset($_GET['AddedID'])
  
        hyperlink_no_params($_SERVER['PHP_SELF'], _("Enter &Another Adjustment"));
  
+       hyperlink_params("$path_to_root/admin/attachments.php", _("Add an Attachment"), "filterType=$trans_type&trans_no=$trans_no");
        display_footer_exit();
  }
  //--------------------------------------------------------------------------------------------------
@@@ -111,7 -113,7 +113,7 @@@ function can_process(
        } 
        elseif (!is_date_in_fiscalyear($_POST['AdjDate'])) 
        {
 -              display_error(_("The entered date is not in fiscal year."));
 +              display_error(_("The entered date is out of fiscal year or is closed for further data entry."));
                set_focus('AdjDate');
                return false;
        } else {
index 03db733e309f9a1840015dfc4196fbb85e18b18f,b5ee125dd966fab6f3094b8360c60692e950d428..0e39a0c050c33f6fe5799b5e79f9bf40b46ed728
@@@ -38,8 -38,8 +38,8 @@@ if (isset($_GET['stock_id'])
  if (isset($_POST['UpdateData']))
  {
  
-       $old_cost = $_POST['OldMaterialCost'] + $_POST['OldLabourCost']
-           + $_POST['OldOverheadCost'];
+       $old_cost = get_standard_cost($_POST['stock_id']);
 -     
++
        $new_cost = input_num('material_cost') + input_num('labour_cost')
             + input_num('overhead_cost');
  
@@@ -83,24 -83,15 +83,15 @@@ if (!isset($_POST['stock_id'])
        $_POST['stock_id'] = get_global_stock_item();
  
  echo "<center>" . _("Item:"). "&nbsp;";
- echo stock_costable_items_list('stock_id', $_POST['stock_id'], false, true);
+ //echo stock_costable_items_list('stock_id', $_POST['stock_id'], false, true);
+ echo stock_items_list('stock_id', $_POST['stock_id'], false, true);
  
  echo "</center><hr>";
  set_global_stock_item($_POST['stock_id']);
  
- $sql = "SELECT description, units, material_cost, labour_cost,
-       overhead_cost, mb_flag
-       FROM ".TB_PREF."stock_master
-       WHERE stock_id=".db_escape($_POST['stock_id']) . "
-       GROUP BY description, units, material_cost, labour_cost, overhead_cost, mb_flag";
- $result = db_query($sql);
- check_db_error("The cost details for the item could not be retrieved", $sql);
+ $myrow = get_item($_POST['stock_id']);
  
- $myrow = db_fetch($result);
  div_start('cost_table');
- hidden("OldMaterialCost", $myrow["material_cost"]);
- hidden("OldLabourCost", $myrow["labour_cost"]);
- hidden("OldOverheadCost", $myrow["overhead_cost"]);
  
  start_table(TABLESTYLE2);
  $dec1 = $dec2 = $dec3 = 0;
index 7292814d35c38d95e0f52befcb6dbd8227d9ce05,78930e81d9bce8ca9dc4132646aa25fa9664ef0e..923d18c4f79f5dc65690186196360203e78f1f16
@@@ -16,13 -16,22 +16,22 @@@ function stock_cost_update($stock_id, $
  {
        $mb_flag = get_mb_flag($stock_id);
      
+       $update_no = -1;
      if (is_service($mb_flag))
      {
-       display_db_error("Cannot do cost update for Service item : $stock_id", "");     
+       //display_db_error("Cannot do cost update for Service item : $stock_id", "");   
+               
+               //Chaitanya
+               $sql = "UPDATE ".TB_PREF."stock_master SET material_cost=".db_escape($material_cost)."
+               WHERE stock_id=".db_escape($stock_id);
+               
+               db_query($sql,"The cost details for the inventory item could not be updated");
+               
+               return $update_no;
+               
      }         
        
-       $update_no = -1;
-       
        begin_transaction();
        
        $sql = "UPDATE ".TB_PREF."stock_master SET material_cost=".db_escape($material_cost).", 
        $qoh = get_qoh_on_date($_POST['stock_id']);
        
        $date_ = Today();
+       if (!is_date_in_fiscalyear($date_))
+               $date_ = end_fiscalyear();
        if ($qoh > 0)
        {
-     
-               $update_no = get_next_trans_no(ST_COSTUPDATE);
-               if (!is_date_in_fiscalyear($date_))
-                       $date_ = end_fiscalyear();
-          
-               $stock_gl_code = get_stock_gl_code($stock_id);
                $new_cost = $material_cost + $labour_cost + $overhead_cost;
  
-               add_gl_trans_std_cost(ST_COSTUPDATE, $update_no, $date_, $stock_gl_code["inventory_account"], 0, 0, $memo_, 
-                       $value_of_change);
 +              $value_of_change = $qoh * ($new_cost - $last_cost);
 +
 +              $memo_ = "Cost was " . $last_cost . " changed to " . $new_cost . " x quantity on hand of $qoh";
 +              add_gl_trans_std_cost(ST_COSTUPDATE, $update_no, $date_, $stock_gl_code["adjustment_account"], 
 +                      $stock_gl_code["dimension_id"], $stock_gl_code["dimension2_id"], $memo_, (-$value_of_change));     
 +
 -              }               
+               $value_of_change = round2($qoh * ($new_cost - $last_cost), user_price_dec());
+               if ($value_of_change != 0)
+               {
+                       $stock_gl_code = get_stock_gl_code($stock_id);
+                       $update_no = get_next_trans_no(ST_COSTUPDATE);
+                       $memo_ = "Cost was " . $last_cost . " changed to " . $new_cost . " x quantity on hand of $qoh";
+                       add_gl_trans_std_cost(ST_COSTUPDATE, $update_no, $date_, $stock_gl_code["adjustment_account"], 
+                               $stock_gl_code["dimension_id"], $stock_gl_code["dimension2_id"], $memo_, (-$value_of_change));     
+                       add_gl_trans_std_cost(ST_COSTUPDATE, $update_no, $date_, $stock_gl_code["inventory_account"], 0, 0, $memo_, 
+                               $value_of_change);
++              }
        }
  
        add_audit_trail(ST_COSTUPDATE, $update_no, $date_);
index 1dd1382733810d280c45e26ea2db506279e8ff2d,2c5aa0e044b6c77a139190e9850f43a56288c590..417b5df5c6ad7b9440e95aa89d970998bd1879c7
@@@ -18,13 -18,15 +18,12 @@@ include_once($path_to_root . "/includes
  include_once($path_to_root . "/sales/includes/sales_db.inc");
  
  include_once($path_to_root . "/includes/ui.inc");
 -if (!@$_GET['popup'])
 -{
 -      $js = "";
 -      if ($use_popup_windows)
 -              $js .= get_js_open_window(800, 500);
 -      if ($use_date_picker)
 -              $js .= get_js_date_picker();
 -      page(_($help_context = "Inventory Item Movement"), @$_GET['popup'], false, "", $js);
 -}     
 +$js = "";
 +if ($use_popup_windows)
 +      $js .= get_js_open_window(800, 500);
 +if ($use_date_picker)
 +      $js .= get_js_date_picker();
- page(_($help_context = "Inventory Item Movement"), false, false, "", $js);
++page(_($help_context = "Inventory Item Movement"), @$_GET['popup'], false, "", $js);
  //------------------------------------------------------------------------------------------------
  
  check_db_has_stock_items(_("There are no items defined in the system."));
@@@ -39,14 -41,16 +38,15 @@@ if (isset($_GET['stock_id'])
        $_POST['stock_id'] = $_GET['stock_id'];
  }
  
 -if (!@$_GET['popup'])
 -      start_form();
 +start_form();
  
  if (!isset($_POST['stock_id']))
        $_POST['stock_id'] = get_global_stock_item();
  
  start_table(TABLESTYLE_NOBORDER);
  start_row();
- stock_items_list_cells(_("Item:"), 'stock_id', $_POST['stock_id']);
 -if (!@$_GET['popup'])
++if (!$page_nested)
+       stock_costable_items_list_cells(_("Item:"), 'stock_id', $_POST['stock_id']);
  end_row();
  end_table();
  
@@@ -61,7 -65,8 +61,8 @@@ date_cells(_("To:"), 'BeforeDate')
  submit_cells('ShowMoves',_("Show Movements"),'',_('Refresh Inquiry'), 'default');
  end_row();
  end_table();
- end_form();
+ if (!@$_GET['popup'])
+       end_form();
  
  set_global_stock_item($_POST['stock_id']);
  
@@@ -185,6 -190,7 +186,6 @@@ end_row()
  
  end_table(1);
  div_end();
 -if (!@$_GET['popup'])
 -      end_page(@$_GET['popup'], false, false);
 +end_page();
  
  ?>
index 1ccbca0db1d0273e3a1e5fc7a13ff48486b4803e,b6965d2961c78602852f29db014ef7ac9d65eb5b..146422fa6bfc5772fa8a924b0f364314901806e9
@@@ -13,13 -13,16 +13,11 @@@ $page_security = 'SA_ITEMSSTATVIEW'
  $path_to_root = "../..";
  include_once($path_to_root . "/includes/session.inc");
  
- if (isset($_GET['stock_id'])){
 -if (!@$_GET['popup'])
 -{
 -      if (isset($_GET['stock_id'])){
 -              page(_($help_context = "Inventory Item Status"), true);
 -      } else {
 -              page(_($help_context = "Inventory Item Status"));
 -      }
 -}
++page(_($help_context = "Inventory Item Status"));
++
+ if (isset($_GET['stock_id']))
        $_POST['stock_id'] = $_GET['stock_id'];
-       page(_($help_context = "Inventory Item Status"), true);
- } else {
-       page(_($help_context = "Inventory Item Status"));
- }
 +
  include_once($path_to_root . "/includes/date_functions.inc");
  include_once($path_to_root . "/includes/ui.inc");
  include_once($path_to_root . "/includes/manufacturing.inc");
@@@ -33,13 -36,17 +31,16 @@@ if (list_updated('stock_id')
  
  check_db_has_stock_items(_("There are no items defined in the system."));
  
 -if (!@$_GET['popup'])
 -      start_form();
 +start_form();
  
  if (!isset($_POST['stock_id']))
        $_POST['stock_id'] = get_global_stock_item();
  
- echo "<center> " . _("Item:"). " ";
- echo stock_items_list('stock_id', $_POST['stock_id'], false, true);
 -if (!@$_GET['popup'])
++if (!$page_nested)
+ {
+       echo "<center> " . _("Item:"). " ";
+       echo stock_costable_items_list('stock_id', $_POST['stock_id'], false, true);
 -}     
++}
  echo "<br>";
  
  echo "<hr></center>";
@@@ -115,7 -122,10 +116,7 @@@ while ($myrow = db_fetch($loc_details)
  
  end_table();
  div_end();
 -if (!@$_GET['popup'])
 -{
 -      end_form();
 -      end_page(@$_GET['popup'], false, false);
 -}     
 +end_form();
 +end_page();
  
  ?>
index 1391b825da10ae35f305a6165b31454b3535f813,666486f08b94ddd1295210e20c122d80e8547feb..70572f59fed52f10d7245ca162d4941a38af1864
  $page_security = 'SA_ITEM';
  $path_to_root = "../..";
  include($path_to_root . "/includes/session.inc");
- page(_($help_context = "Items"), @$_REQUEST['popup']);
 +
 -page(_($help_context = "Items"), false, false, "", $js);
+ $js = "";
+ if ($use_popup_windows)
+       $js .= get_js_open_window(900, 500);
+ if ($use_date_picker)
+       $js .= get_js_date_picker();
+       
++page(_($help_context = "Items"), @$_REQUEST['popup'], false, "", $js);
++
  
  include_once($path_to_root . "/includes/date_functions.inc");
  include_once($path_to_root . "/includes/ui.inc");
@@@ -27,26 -32,22 +34,22 @@@ $new_item = get_post('stock_id')=='' |
  
  if (isset($_GET['stock_id']))
  {
-       $_POST['stock_id'] = $stock_id = $_GET['stock_id'];
- }
- elseif (isset($_POST['stock_id']))
- {
-       $stock_id = $_POST['stock_id'];
+       $_POST['stock_id'] = $_GET['stock_id'];
  }
+ $stock_id = get_post('stock_id');
  if (list_updated('stock_id')) {
-       $_POST['NewStockID'] = get_post('stock_id');
+       $_POST['NewStockID'] = $stock_id = get_post('stock_id');
      clear_data();
        $Ajax->activate('details');
        $Ajax->activate('controls');
  }
  
  if (get_post('cancel')) {
-       $_POST['NewStockID'] = $_POST['stock_id'] = '';
+       $_POST['NewStockID'] = $stock_id = $_POST['stock_id'] = '';
      clear_data();
        set_focus('stock_id');
        $Ajax->activate('_page_body');
  }
  if (list_updated('category_id') || list_updated('mb_flag')) {
        $Ajax->activate('details');
  }
@@@ -63,10 -64,20 +66,20 @@@ if (isset($_FILES['pic']) && $_FILES['p
        }       
        $filename .= "/".item_img_name($stock_id).".jpg";
        
-        //But check for the worst 
-       if (strtoupper(substr(trim($_FILES['pic']['name']), strlen($_FILES['pic']['name']) - 3)) != 'JPG')
+       //But check for the worst 
+       if ((list($width, $height, $type, $attr) = getimagesize($_FILES['pic']['tmp_name'])) !== false)
+               $imagetype = $type;
+       else
+               $imagetype = false;
+       //$imagetype = exif_imagetype($_FILES['pic']['tmp_name']);
+       if ($imagetype != IMAGETYPE_GIF && $imagetype != IMAGETYPE_JPEG && $imagetype != IMAGETYPE_PNG)
+       {       //File type Check
+               display_warning( _('Only graphics files can be uploaded'));
+               $upload_file ='No';
+       }       
+       elseif (@strtoupper(substr(trim($_FILES['pic']['name']), @in_array(strlen($_FILES['pic']['name']) - 3)), array('JPG','PNG','GIF')))
        {
-               display_warning(_('Only jpg files are supported - a file extension of .jpg is expected'));
+               display_warning(_('Only graphics files are supported - a file extension of .jpg, .png or .gif is expected'));
                $upload_file ='No';
        } 
        elseif ( $_FILES['pic']['size'] > ($max_image_size * 1024)) 
                display_warning(_('The file size is over the maximum allowed. The maximum size allowed in KB is') . ' ' . $max_image_size);
                $upload_file ='No';
        } 
 +      elseif ( $_FILES['pic']['type'] == "text/plain" ) 
 +      {  //File type Check
 +              display_warning( _('Only graphics files can be uploaded'));
 +              $upload_file ='No';
 +      } 
        elseif (file_exists($filename))
        {
                $result = unlink($filename);
@@@ -137,7 -143,7 +150,7 @@@ if (isset($_POST['addupdate'])
        }
        elseif (strstr($_POST['NewStockID'], " ") || strstr($_POST['NewStockID'],"'") || 
                strstr($_POST['NewStockID'], "+") || strstr($_POST['NewStockID'], "\"") || 
-               strstr($_POST['NewStockID'], "&")) 
+               strstr($_POST['NewStockID'], "&") || strstr($_POST['NewStockID'], "\t")
        {
                $input_error = 1;
                display_error( _('The item code cannot contain any of the following characters -  & + OR a space OR quotes'));
  
  if (get_post('clone')) {
        unset($_POST['stock_id']);
+       $stock_id = '';
        unset($_POST['inactive']);
        set_focus('NewStockID');
        $Ajax->activate('_page_body');
@@@ -239,198 -246,242 +253,241 @@@ if (isset($_POST['delete']) && strlen($
                $Ajax->activate('_page_body');
        }
  }
- //-------------------------------------------------------------------------------------------- 
- start_form(true);
  
if (db_has_stock_items()
function item_settings(&$stock_id
  {
-       start_table(TABLESTYLE_NOBORDER);
-       start_row();
-     stock_items_list_cells(_("Select an item:"), 'stock_id', null,
-         _('New item'), true, check_value('show_inactive'));
-       $new_item = get_post('stock_id')=='';
-       check_cells(_("Show inactive:"), 'show_inactive', null, true);
-       end_row();
-       end_table();
+       global $SysPrefs, $path_to_root, $new_item, $pic_height;
  
-       if (get_post('_show_inactive_update')) {
-               $Ajax->activate('stock_id');
-               set_focus('stock_id');
+       start_outer_table(TABLESTYLE2);
+       table_section(1);
+       table_section_title(_("Item"));
+       //------------------------------------------------------------------------------------
+       if ($new_item) 
+       {
+               text_row(_("Item Code:"), 'NewStockID', null, 21, 20);
+               $_POST['inactive'] = 0;
+       } 
+       else 
+       { // Must be modifying an existing item
+               if (get_post('NewStockID') != get_post('stock_id') || get_post('addupdate')) { // first item display
+                       $_POST['NewStockID'] = $_POST['stock_id'];
+                       $myrow = get_item($_POST['NewStockID']);
+                       $_POST['long_description'] = $myrow["long_description"];
+                       $_POST['description'] = $myrow["description"];
+                       $_POST['category_id']  = $myrow["category_id"];
+                       $_POST['tax_type_id']  = $myrow["tax_type_id"];
+                       $_POST['units']  = $myrow["units"];
+                       $_POST['mb_flag']  = $myrow["mb_flag"];
+                       $_POST['sales_account'] =  $myrow['sales_account'];
+                       $_POST['inventory_account'] = $myrow['inventory_account'];
+                       $_POST['cogs_account'] = $myrow['cogs_account'];
+                       $_POST['adjustment_account']    = $myrow['adjustment_account'];
+                       $_POST['assembly_account']      = $myrow['assembly_account'];
+                       $_POST['dimension_id']  = $myrow['dimension_id'];
+                       $_POST['dimension2_id'] = $myrow['dimension2_id'];
+                       $_POST['no_sale']       = $myrow['no_sale'];
+                       $_POST['del_image'] = 0;        
+                       $_POST['inactive'] = $myrow["inactive"];
+                       $_POST['editable'] = $myrow["editable"];
+               }
+               label_row(_("Item Code:"),$_POST['NewStockID']);
+               hidden('NewStockID', $_POST['NewStockID']);
+               set_focus('description');
        }
- }
  
- div_start('details');
- start_outer_table(TABLESTYLE2);
+       text_row(_("Name:"), 'description', null, 52, 200);
  
table_section(1);
      textarea_row(_('Description:'), 'long_description', null, 42, 3);
  
- table_section_title(_("Item"));
+       stock_categories_list_row(_("Category:"), 'category_id', null, false, $new_item);
+       if ($new_item && (list_updated('category_id') || !isset($_POST['units']))) {
+               $category_record = get_item_category($_POST['category_id']);
+               $_POST['tax_type_id'] = $category_record["dflt_tax_type"];
+               $_POST['units'] = $category_record["dflt_units"];
+               $_POST['mb_flag'] = $category_record["dflt_mb_flag"];
+               $_POST['inventory_account'] = $category_record["dflt_inventory_act"];
+               $_POST['cogs_account'] = $category_record["dflt_cogs_act"];
+               $_POST['sales_account'] = $category_record["dflt_sales_act"];
+               $_POST['adjustment_account'] = $category_record["dflt_adjustment_act"];
+               $_POST['assembly_account'] = $category_record["dflt_assembly_act"];
+               $_POST['dimension_id'] = $category_record["dflt_dim1"];
+               $_POST['dimension2_id'] = $category_record["dflt_dim2"];
+               $_POST['no_sale'] = $category_record["dflt_no_sale"];
+               $_POST['editable'] = 0;
  
- //------------------------------------------------------------------------------------
- if ($new_item) 
- {
-       text_row(_("Item Code:"), 'NewStockID', null, 21, 20);
-       $_POST['inactive'] = 0;
- } 
- else 
- { // Must be modifying an existing item
-       if (get_post('NewStockID') != get_post('stock_id')) { // first item display
-               $_POST['NewStockID'] = $_POST['stock_id'];
-               $myrow = get_item($_POST['NewStockID']);
-               $_POST['long_description'] = $myrow["long_description"];
-               $_POST['description'] = $myrow["description"];
-               $_POST['category_id']  = $myrow["category_id"];
-               $_POST['tax_type_id']  = $myrow["tax_type_id"];
-               $_POST['units']  = $myrow["units"];
-               $_POST['mb_flag']  = $myrow["mb_flag"];
-               $_POST['sales_account'] =  $myrow['sales_account'];
-               $_POST['inventory_account'] = $myrow['inventory_account'];
-               $_POST['cogs_account'] = $myrow['cogs_account'];
-               $_POST['adjustment_account']    = $myrow['adjustment_account'];
-               $_POST['assembly_account']      = $myrow['assembly_account'];
-               $_POST['dimension_id']  = $myrow['dimension_id'];
-               $_POST['dimension2_id'] = $myrow['dimension2_id'];
-               $_POST['no_sale']       = $myrow['no_sale'];
-               $_POST['del_image'] = 0;        
-               $_POST['inactive'] = $myrow["inactive"];
-               $_POST['editable'] = $myrow["editable"];
        }
-       label_row(_("Item Code:"),$_POST['NewStockID']);
-       hidden('NewStockID', $_POST['NewStockID']);
-       set_focus('description');
- }
+       $fresh_item = !isset($_POST['NewStockID']) || $new_item 
+               || check_usage($_POST['stock_id'],false);
  
text_row(_("Name:"), 'description', null, 52, 200);
      item_tax_types_list_row(_("Item Tax Type:"), 'tax_type_id', null);
  
textarea_row(_('Description:'), 'long_description', null, 42, 3);
      stock_item_types_list_row(_("Item Type:"), 'mb_flag', null, $fresh_item);
  
stock_categories_list_row(_("Category:"), 'category_id', null, false, $new_item);
      stock_units_list_row(_('Units of Measure:'), 'units', null, $fresh_item);
  
- if ($new_item && (list_updated('category_id') || !isset($_POST['units']))) {
+       check_row(_("Editable description:"), 'editable');
  
-       $category_record = get_item_category($_POST['category_id']);
+       check_row(_("Exclude from sales:"), 'no_sale');
  
-       $_POST['tax_type_id'] = $category_record["dflt_tax_type"];
-       $_POST['units'] = $category_record["dflt_units"];
-       $_POST['mb_flag'] = $category_record["dflt_mb_flag"];
-       $_POST['inventory_account'] = $category_record["dflt_inventory_act"];
-       $_POST['cogs_account'] = $category_record["dflt_cogs_act"];
-       $_POST['sales_account'] = $category_record["dflt_sales_act"];
-       $_POST['adjustment_account'] = $category_record["dflt_adjustment_act"];
-       $_POST['assembly_account'] = $category_record["dflt_assembly_act"];
-       $_POST['dimension_id'] = $category_record["dflt_dim1"];
-       $_POST['dimension2_id'] = $category_record["dflt_dim2"];
-       $_POST['no_sale'] = $category_record["dflt_no_sale"];
-       $_POST['editable'] = 0;
+       table_section(2);
  
- }
- $fresh_item = !isset($_POST['NewStockID']) || $new_item 
-       || check_usage($_POST['stock_id'],false);
+       $dim = get_company_pref('use_dimension');
+       if ($dim >= 1)
+       {
+               table_section_title(_("Dimensions"));
+               dimensions_list_row(_("Dimension")." 1", 'dimension_id', null, true, " ", false, 1);
+               if ($dim > 1)
+                       dimensions_list_row(_("Dimension")." 2", 'dimension2_id', null, true, " ", false, 2);
+       }
+       if ($dim < 1)
+               hidden('dimension_id', 0);
+       if ($dim < 2)
+               hidden('dimension2_id', 0);
+       table_section_title(_("GL Accounts"));
  
item_tax_types_list_row(_("Item Tax Type:"), 'tax_type_id', null);
      gl_all_accounts_list_row(_("Sales Account:"), 'sales_account', $_POST['sales_account']);
  
- stock_item_types_list_row(_("Item Type:"), 'mb_flag', null, $fresh_item);
+       if (!is_service($_POST['mb_flag'])) 
+       {
+               gl_all_accounts_list_row(_("Inventory Account:"), 'inventory_account', $_POST['inventory_account']);
+               gl_all_accounts_list_row(_("C.O.G.S. Account:"), 'cogs_account', $_POST['cogs_account']);
+               gl_all_accounts_list_row(_("Inventory Adjustments Account:"), 'adjustment_account', $_POST['adjustment_account']);
+       }
+       else 
+       {
+               gl_all_accounts_list_row(_("C.O.G.S. Account:"), 'cogs_account', $_POST['cogs_account']);
+               hidden('inventory_account', $_POST['inventory_account']);
+               hidden('adjustment_account', $_POST['adjustment_account']);
+       }
  
- stock_units_list_row(_('Units of Measure:'), 'units', null, $fresh_item);
  
- check_row(_("Editable description:"), 'editable');
+       if (is_manufactured($_POST['mb_flag']))
+               gl_all_accounts_list_row(_("Item Assembly Costs Account:"), 'assembly_account', $_POST['assembly_account']);
+       else
+               hidden('assembly_account', $_POST['assembly_account']);
  
check_row(_("Exclude from sales:"), 'no_sale');
      table_section_title(_("Other"));
  
- table_section(2);
+       // Add image upload for New Item  - by Joe
+       file_row(_("Image File (.jpg)") . ":", 'pic', 'pic');
+       // Add Image upload for New Item  - by Joe
+       $stock_img_link = "";
+       $check_remove_image = false;
+       if (isset($_POST['NewStockID']) && file_exists(company_path().'/images/'
+               .item_img_name($_POST['NewStockID']).".jpg")) 
+       {
+        // 31/08/08 - rand() call is necessary here to avoid caching problems. Thanks to Peter D.
+               $stock_img_link .= "<img id='item_img' alt = '[".$_POST['NewStockID'].".jpg".
+                       "]' src='".company_path().'/images/'.item_img_name($_POST['NewStockID']).
+                       ".jpg?nocache=".rand()."'"." height='$pic_height' border='0'>";
+               $check_remove_image = true;
+       } 
+       else 
+       {
+               $stock_img_link .= _("No image");
+       }
  
- $dim = get_company_pref('use_dimension');
- if ($dim >= 1)
- {
-       table_section_title(_("Dimensions"));
+       label_row("&nbsp;", $stock_img_link);
+       if ($check_remove_image)
+               check_row(_("Delete Image:"), 'del_image');
+       record_status_list_row(_("Item status:"), 'inactive');
+       end_outer_table(1);
+       div_start('controls');
+       if (!isset($_POST['NewStockID']) || $new_item) 
+       {
+               submit_center('addupdate', _("Insert New Item"), true, '', 'default');
+       } 
+       else 
+       {
+               submit_center_first('addupdate', _("Update Item"), '', 
+                       @$_REQUEST['popup'] ? true : 'default');
+               submit_return('select', get_post('stock_id'), 
+                       _("Select this items and return to document entry."), 'default');
+               submit('clone', _("Clone This Item"), true, '', true);
+               submit('delete', _("Delete This Item"), true, '', true);
+               submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');
+       }
  
-       dimensions_list_row(_("Dimension")." 1", 'dimension_id', null, true, " ", false, 1);
-       if ($dim > 1)
-               dimensions_list_row(_("Dimension")." 2", 'dimension2_id', null, true, " ", false, 2);
+       div_end();
  }
- if ($dim < 1)
-       hidden('dimension_id', 0);
- if ($dim < 2)
-       hidden('dimension2_id', 0);
  
- table_section_title(_("GL Accounts"));
+ //-------------------------------------------------------------------------------------------- 
  
gl_all_accounts_list_row(_("Sales Account:"), 'sales_account', $_POST['sales_account']);
start_form(true);
  
- if (!is_service($_POST['mb_flag'])) 
+ if (db_has_stock_items()) 
  {
-       gl_all_accounts_list_row(_("Inventory Account:"), 'inventory_account', $_POST['inventory_account']);
-       gl_all_accounts_list_row(_("C.O.G.S. Account:"), 'cogs_account', $_POST['cogs_account']);
-       gl_all_accounts_list_row(_("Inventory Adjustments Account:"), 'adjustment_account', $_POST['adjustment_account']);
+       start_table(TABLESTYLE_NOBORDER);
+       start_row();
+     stock_items_list_cells(_("Select an item:"), 'stock_id', null,
+         _('New item'), true, check_value('show_inactive'));
+       $new_item = get_post('stock_id')=='';
+       check_cells(_("Show inactive:"), 'show_inactive', null, true);
+       end_row();
+       end_table();
+       if (get_post('_show_inactive_update')) {
+               $Ajax->activate('stock_id');
+               set_focus('stock_id');
+       }
  }
- else 
+ else
  {
-       gl_all_accounts_list_row(_("C.O.G.S. Account:"), 'cogs_account', $_POST['cogs_account']);
-       hidden('inventory_account', $_POST['inventory_account']);
-       hidden('adjustment_account', $_POST['adjustment_account']);
+       hidden('stock_id', get_post('stock_id'));
  }
  
+ div_start('details');
  
- if (is_manufactured($_POST['mb_flag']))
-       gl_all_accounts_list_row(_("Item Assembly Costs Account:"), 'assembly_account', $_POST['assembly_account']);
- else
-       hidden('assembly_account', $_POST['assembly_account']);
- table_section_title(_("Other"));
- // Add image upload for New Item  - by Joe
- file_row(_("Image File (.jpg)") . ":", 'pic', 'pic');
- // Add Image upload for New Item  - by Joe
- $stock_img_link = "";
- $check_remove_image = false;
- if (isset($_POST['NewStockID']) && file_exists(company_path().'/images/'
-       .item_img_name($_POST['NewStockID']).".jpg")) 
- {
-  // 31/08/08 - rand() call is necessary here to avoid caching problems. Thanks to Peter D.
-       $stock_img_link .= "<img id='item_img' alt = '[".$_POST['NewStockID'].".jpg".
-               "]' src='".company_path().'/images/'.item_img_name($_POST['NewStockID']).
-               ".jpg?nocache=".rand()."'"." height='$pic_height' border='0'>";
-       $check_remove_image = true;
- } 
- else 
- {
-       $stock_img_link .= _("No image");
- }
+ $stock_id = get_post('stock_id');
+ if (!$stock_id)
+       unset($_POST['_tabs_sel']); // force settings tab for new customer
  
- label_row("&nbsp;", $stock_img_link);
- if ($check_remove_image)
-       check_row(_("Delete Image:"), 'del_image');
+ tabbed_content_start('tabs', array(
+               'settings' => array(_('&General settings'), $stock_id),
+               'movement' => array(_('&Transactions'), $stock_id),
+               'status' => array(_('&Status'), $stock_id),
+       ));
        
- record_status_list_row(_("Item status:"), 'inactive');
- end_outer_table(1);
- div_end();
- div_start('controls');
- if (!isset($_POST['NewStockID']) || $new_item) 
- {
-       submit_center('addupdate', _("Insert New Item"), true, '', 'default');
- } 
- else 
- {
-       submit_center_first('addupdate', _("Update Item"), '', 
-               @$_REQUEST['popup'] ? true : 'default');
-       submit_return('select', get_post('stock_id'), 
-               _("Select this items and return to document entry."), 'default');
-       submit('clone', _("Clone This Item"), true, '', true);
-       submit('delete', _("Delete This Item"), true, '', true);
      submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');
- }
+       switch (get_post('_tabs_sel')) {
+               default:
+               case 'settings':
+                       item_settings($stock_id); 
+                       break;
+               case 'movement':
+                       $_GET['stock_id'] = $stock_id;
+                       $_GET['popup'] = 1;
+                       include_once($path_to_root."/inventory/inquiry/stock_movements.php");
+                       break;
+               case 'status':
+                       $_GET['stock_id'] = $stock_id;
+                       $_GET['popup'] = 1;
+                       include_once($path_to_root."/inventory/inquiry/stock_status.php");
+                       break;
+       };
br();
+ tabbed_content_end();
  
  div_end();
 -
  hidden('popup', @$_REQUEST['popup']);
  end_form();
  
  //------------------------------------------------------------------------------------
  
- end_page();
+ end_page(@$_REQUEST['popup']);
  ?>
index 28167da7da3c9b7a43354280431229af03b06b49,ca2f4a86883b5d213f556cc460a5c738b3b41275..8b7f7f7db36c82d2ef12b505807a5f3b295743b9
@@@ -55,9 -55,11 +55,11 @@@ function add_work_order_issue($woid, $r
                if ($to_work_order)
                        $item->quantity = -$item->quantity;
  
+               //Chaitanya: Stamp the standard_cost
+               $standard_cost = get_standard_cost($item->stock_id);
                // insert a -ve stock move for each item
                add_stock_move(ST_MANUISSUE, $item->stock_id, $number,
-                       $location, $date_, $memo_, -$item->quantity, 0);
+                       $location, $date_, $memo_, -$item->quantity, $standard_cost);
  
                $sql = "INSERT INTO ".TB_PREF."wo_issue_items (issue_id, stock_id, qty_issued)
                        VALUES (".db_escape($number).", ".db_escape($item->stock_id).", "
                $issue_cost = $standard_cost * $item->quantity;
                $issue = get_stock_gl_code($item->stock_id);
          $stockitem = get_item($item->stock_id);
-         $total_cost += add_gl_trans_std_cost(ST_WORKORDER, $woid, $date_, $issue["inventory_account"], 0, 0,
 -              
++
+               //Chaitanya : Compatibility for Service Items
+               if (!is_service($issue["mb_flag"]))
+                       $ivaccount = $issue["inventory_account"];
+               else
+                       $ivaccount = $issue["cogs_account"];            
 -              
++
+         $total_cost += add_gl_trans_std_cost(ST_WORKORDER, $woid, $date_, $ivaccount, 0, 0,
                  $date_.": "._("Issue of")." ".$stockitem["description"], -$issue_cost);                       
                $issue_total += $issue_cost;
        }       
        if ($issue_total != 0)
-               add_issue_cost($details['stock_id'], $details['units_reqd'], $date_, $issue_total);
+               //Chaitanya : Apply cost to QOH as adjustment only
+               add_issue_cost($details['stock_id'], $details['units_reqd'], $date_, $issue_total, true);
        $issue = get_stock_gl_code($details['stock_id']);
      $stockitem = get_item($details['stock_id']);
      add_gl_trans_std_cost(ST_WORKORDER, $woid, $date_, $issue["inventory_account"],
@@@ -156,18 -166,63 +166,63 @@@ function void_work_order_issue($type_no
  {
        begin_transaction();
        hook_db_prevoid(ST_MANUISSUE, $type_no);
 -      
 +
+       //Chaitanya : Skip processing already voided entry i.e. explicitly voided
+       $void_entry = get_voided_entry(ST_MANUISSUE, $type_no);
+       if ($void_entry)
+               return;
        // void the actual issue items and their quantities
        $sql = "UPDATE ".TB_PREF."wo_issue_items Set qty_issued = 0 WHERE issue_id="
                .db_escape($type_no);
        db_query($sql,"A work order issue item could not be voided");
  
-       // void all related stock moves
-       void_stock_move(ST_MANUISSUE, $type_no);
        // void any related gl trans
-       void_gl_trans(ST_MANUISSUE, $type_no, true);
+       //Chaitanya : Nothing happens due to next statement as all gl postings are done against WO
+       //void_gl_trans(ST_MANUISSUE, $type_no, true);
+       
+       //Chaitanya : Reverse the gl posting
+       $issue = get_work_order_issue($type_no);
+       $manf_stock_id = $issue["stock_id"];
+       $date_ = sql2date($issue["issue_date"]);
+       $woid = $issue["workorder_id"];
 -              
++
+       $result = get_stock_moves(ST_MANUISSUE, $type_no);
+       $total_cost = 0;
+       $issue_total = 0;
+       while ($myrow = db_fetch($result))
+       {
+               $issue_cost = $myrow["qty"]*$myrow["standard_cost"];
+               $issue = get_stock_gl_code($myrow["stock_id"]);
+         $stockitem = get_item($myrow["stock_id"]);
 -              
++
+               //Chaitanya : Compatibility for Service Items
+               if (!is_service($issue["mb_flag"]))
+                       $ivaccount = $issue["inventory_account"];
+               else
 -                      $ivaccount = $issue["cogs_account"];            
 -              
++                      $ivaccount = $issue["cogs_account"];
++
+               if ($issue_cost != 0)
+               {
+                       $total_cost += add_gl_trans_std_cost(ST_WORKORDER, $woid, $date_, $ivaccount, 0, 0,
+                               $date_.": "._("Reversed the issue of")." ".$stockitem["description"],
 -                              -$issue_cost);                  
++                              -$issue_cost);
+                       $issue_total += $issue_cost;
+               }
+       }
+       if ($issue_total != 0)
+               //Chaitanya : Revese cost effect on manfactured stock item as adjustment only
+               add_issue_cost($manf_stock_id, 0, $date_, $issue_total, true);
+       $issue = get_stock_gl_code($manf_stock_id);
+     $stockitem = get_item($manf_stock_id);
+       if ($total_cost != 0)
+               add_gl_trans_std_cost(ST_WORKORDER, $woid, $date_, $issue["inventory_account"],
+                       0, 0, $date_.": "._("Reversed the issue to")." ".$stockitem["description"], 
+                       -$total_cost);  
 -      
++
+       //Chaitanya : Shifted below void all related stock moves
+       void_stock_move(ST_MANUISSUE, $type_no);
 -      
 +
        commit_transaction();
  }
  
index 9b2095c076141fdce58e949a8ab2c5ed1999d4d7,38af2add9b98efd04427682b1d22abdcb67aa694..dcac240cb831ba4020f5b989cac60b7672c86a85
@@@ -44,20 -44,29 +44,28 @@@ function work_order_produce($woid, $ref
        db_query($sql,"A work order manufacture could not be added");
  
        $id = db_insert_id();
 -      
 +
        // -------------------------------------------------------------------------
  
        work_order_quick_costs($woid, $details["stock_id"], $quantity, $date_, $id);
 -      
        // -------------------------------------------------------------------------
 -      }       
+       // Chaitanya: stamp BOM cost to finished item
+       $m_cost = 0;
+     $result = get_bom($details["stock_id"]);
+       while ($bom_item = db_fetch($result))
+       {
+               $standard_cost = get_standard_cost($bom_item['component']);
+               $m_cost += ($bom_item['quantity'] * $standard_cost);
++      }
        // insert a +ve stock move for the item being manufactured
        // negative means "unproduce" or unassemble
        add_stock_move(ST_MANURECEIVE, $details["stock_id"], $id,
-               $details["loc_code"], $date_, $ref, $quantity, 0);
+               $details["loc_code"], $date_, $ref, $quantity, $m_cost);
        // update wo quantity and close wo if requested
        work_order_update_finished_quantity($woid, $quantity, $close_wo);
  
        if ($memo_)
                add_comments(ST_MANURECEIVE, $id, $date_, $memo_);
  
@@@ -109,24 -118,56 +117,55 @@@ function void_work_order_produce($type_
  {
        begin_transaction();
        hook_db_prevoid(ST_MANURECEIVE, $type_no);
 -      
 +
+       //Chaitanya : Skip processing already voided entry i.e. explicitly voided
+       $void_entry = get_voided_entry(ST_MANURECEIVE, $type_no);
+       if ($void_entry)
+               return; 
        $row = get_work_order_produce($type_no);
  
        // deduct the quantity of this production from the parent work order
        work_order_update_finished_quantity($row["workorder_id"], -$row["quantity"]);
  
-       work_order_quick_costs($row['workorder_id'], $row['stock_id'], -$row['quantity'], sql2date($row['date_']), $type_no);
+       //Chaitanya : skipped this step as BOM may have got changed
+       //work_order_quick_costs($row['workorder_id'], $row['stock_id'], -$row['quantity'], sql2date($row['date_']), $type_no);
  
 -              
+       // void any related gl trans
+       //Chaitanya : Nothing happens due to next statement as all gl postings are done against WO
+       //void_gl_trans(ST_MANURECEIVE, $type_no, true);
+       
+       $woid = $row["workorder_id"];
+       $date_ = sql2date($row["date_"]);
+               
+       $result = get_stock_moves(ST_MANURECEIVE, $type_no);
+       while ($myrow = db_fetch($result))
+       {
+               $issue_cost = $myrow["qty"]*$myrow["standard_cost"];
+               $issue = get_stock_gl_code($myrow["stock_id"]);
+         $stockitem = get_item($myrow["stock_id"]);
 -                      $ivaccount = $issue["cogs_account"];            
 -              
++
+               //Chaitanya : Compatibility for Service Items
+               if (!is_service($issue["mb_flag"]))
+                       $ivaccount = $issue["inventory_account"];
+               else
 -      }       
 -                      
++                      $ivaccount = $issue["cogs_account"];
++
+               if ($issue_cost != 0)
+               {
+                       add_gl_trans_std_cost(ST_WORKORDER, $woid, $date_, $ivaccount, 0, 0,
+                               $date_.": "._("Reversed the production ")." ".$stockitem["description"],
+                               -$issue_cost);
+               }
++      }
        // clear the production record
        $sql = "UPDATE ".TB_PREF."wo_manufacture SET quantity=0 WHERE id=".db_escape($type_no);
 -      db_query($sql, "Cannot void a wo production");                  
 -      
 +      db_query($sql, "Cannot void a wo production");
 +
+       //Chaitanya : Shifted below
        // void all related stock moves
        void_stock_move(ST_MANURECEIVE, $type_no);
  
-       // void any related gl trans
-       void_gl_trans(ST_MANURECEIVE, $type_no, true);
        commit_transaction();
  }
  
index e63aae816441fc0e0f7852c7117aee8bb5ef66f0,2aed7c1912876680a39523f78f77e181dc342497..eb31056809b6c4f81d88bc4b8b9faacfbce5ed2c
@@@ -9,6 -9,210 +9,6 @@@
      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
      See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
  ***********************************************************************/
 -//--------------------------------------------------------------------------------------
 -
 -function add_material_cost($stock_id, $qty, $date_, $advanced=false)
 -{
 -      $m_cost = 0;
 -    $result = get_bom($stock_id);
 -      while ($bom_item = db_fetch($result))
 -      {
 -              $standard_cost = get_standard_cost($bom_item['component']);
 -              $m_cost += ($bom_item['quantity'] * $standard_cost);
 -      }
 -      $bom_cost = $m_cost;
 -      
 -      $sql = "SELECT material_cost, labour_cost, overhead_cost FROM ".TB_PREF."stock_master WHERE stock_id = "
 -              .db_escape($stock_id);
 -      $result = db_query($sql);
 -      $myrow = db_fetch($result);
 -      $material_cost =  $myrow['material_cost'];
 -      
 -      if ($advanced)
 -      {
 -              //reduce overhead_cost and labour_cost from price as those will remain as is
 -              $m_cost = $m_cost - $myrow['labour_cost'] - $myrow['overhead_cost'];
 -      }
 -      
 -      $qoh = get_qoh_on_date($stock_id);
 -      $cost_adjust = false;
 -      if ($qoh < 0)
 -      {
 -              if ($qoh + $qty >= 0)
 -                      $cost_adjust = true;
 -              $qoh = 0;
 -      }               
 -      if ($qoh + $qty != 0)   
 -              $material_cost = ($qoh * $material_cost + $qty * $m_cost) /     ($qoh + $qty);
 -      
 -      if ($advanced && $cost_adjust) // new 2010-02-10
 -              adjust_deliveries($stock_id, $bom_cost, $date_);        
 -      
 -      $sql = "UPDATE ".TB_PREF."stock_master SET material_cost=".db_escape($material_cost)."
 -                  WHERE stock_id=".db_escape($stock_id);
 -      db_query($sql,"The cost details for the inventory item could not be updated");
 -}
 -
 -function add_overhead_cost($stock_id, $qty, $date_, $costs, $adj_only=false)
 -{
 -      if ($qty != 0)
 -              $costs /= $qty;
 -      $sql = "SELECT overhead_cost FROM ".TB_PREF."stock_master WHERE stock_id = "
 -              .db_escape($stock_id);
 -      $result = db_query($sql);
 -      $myrow = db_fetch($result);
 -      $overhead_cost =  $myrow['overhead_cost'];
 -      $qoh = get_qoh_on_date($stock_id);
 -      if ($qoh < 0)
 -              $qoh = 0;
 -      if ($adj_only)
 -      {
 -              if ($qty != 0)
 -                      $costs = $qty * $costs;
 -              if ($qoh>0)
 -                      $overhead_cost = ($qoh * $overhead_cost + $costs) / $qoh;
 -              else // Journal Entry if QOH is 0/negative \r
 -              {
 -                      global $Refs;
 -
 -                      $id = get_next_trans_no(ST_JOURNAL);
 -                      $ref = $Refs->get_next(ST_JOURNAL);
 -                      
 -                      $stock_gl_code = get_stock_gl_code($stock_id);
 -                      $memo = "WO Overhead cost settlement JV for zero/negative respository of ".$stock_id;
 -                      //Reverse the inventory effect if $qoh <=0
 -                      add_gl_trans_std_cost(ST_JOURNAL, $id, $date_, 
 -                              $stock_gl_code["inventory_account"],
 -                              $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'], $memo, 
 -                              -$costs);
 -                      //GL Posting to inventory adjustment account
 -                      add_gl_trans_std_cost(ST_JOURNAL, $id, $date_, 
 -                              $stock_gl_code["adjustment_account"],
 -                              $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'], $memo,
 -                              $costs);
 -                              
 -                      add_audit_trail(ST_JOURNAL, $id, $date_);
 -                      add_comments(ST_JOURNAL, $id, $date_, $memo);
 -                      $Refs->save(ST_JOURNAL, $id, $ref);     
 -              }
 -      }
 -      else
 -      {               
 -              if ($qoh + $qty != 0)   
 -                      $overhead_cost = ($qoh * $overhead_cost + $qty * $costs) /      ($qoh + $qty);
 -      }
 -      $sql = "UPDATE ".TB_PREF."stock_master SET overhead_cost=".db_escape($overhead_cost)."
 -              WHERE stock_id=".db_escape($stock_id);
 -      db_query($sql,"The cost details for the inventory item could not be updated");
 -}
 -
 -function add_labour_cost($stock_id, $qty, $date_, $costs, $adj_only=false)
 -{
 -      if ($qty != 0)
 -              $costs /= $qty;
 -      $sql = "SELECT labour_cost FROM ".TB_PREF."stock_master WHERE stock_id = "
 -              .db_escape($stock_id);
 -      $result = db_query($sql);
 -      $myrow = db_fetch($result);
 -      $labour_cost =  $myrow['labour_cost'];
 -      $qoh = get_qoh_on_date($stock_id);
 -      if ($qoh < 0)
 -              $qoh = 0;
 -      if ($adj_only)
 -      {
 -              if ($qty != 0)
 -                      $costs = $qty * $costs;
 -              if ($qoh>0)
 -                      $labour_cost = ($qoh * $labour_cost + $costs) / $qoh;   
 -              else // Journal Entry if QOH is 0/negative \r
 -              {
 -                      global $Refs;
 -
 -                      $id = get_next_trans_no(ST_JOURNAL);
 -                      $ref = $Refs->get_next(ST_JOURNAL);
 -                      
 -                      $stock_gl_code = get_stock_gl_code($stock_id);
 -                      $memo = "WO labour cost settlement JV for zero/negative respository of ".$stock_id;
 -                      //Reverse the inventory effect if $qoh <=0
 -                      add_gl_trans_std_cost(ST_JOURNAL, $id, $date_, 
 -                              $stock_gl_code["inventory_account"],
 -                              $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'], $memo, 
 -                              -$costs);
 -                      //GL Posting to inventory adjustment account
 -                      add_gl_trans_std_cost(ST_JOURNAL, $id, $date_, 
 -                              $stock_gl_code["adjustment_account"],
 -                              $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'], $memo,
 -                              $costs);
 -                              
 -                      add_audit_trail(ST_JOURNAL, $id, $date_);
 -                      add_comments(ST_JOURNAL, $id, $date_, $memo);
 -                      $Refs->save(ST_JOURNAL, $id, $ref);     
 -              }
 -      }
 -      else
 -      {               
 -              if ($qoh + $qty != 0)   
 -                      $labour_cost = ($qoh * $labour_cost + $qty * $costs) /  ($qoh + $qty);
 -      }       \r
 -      $sql = "UPDATE ".TB_PREF."stock_master SET labour_cost=".db_escape($labour_cost)."
 -              WHERE stock_id=".db_escape($stock_id);
 -      db_query($sql,"The cost details for the inventory item could not be updated");
 -}
 -
 -function add_issue_cost($stock_id, $qty, $date_, $costs, $adj_only=false)
 -{
 -      if ($qty != 0)
 -              $costs /= $qty;
 -      $sql = "SELECT material_cost FROM ".TB_PREF."stock_master WHERE stock_id = "
 -              .db_escape($stock_id);
 -      $result = db_query($sql);
 -      $myrow = db_fetch($result);
 -      $material_cost =  $myrow['material_cost'];
 -      $qoh = get_qoh_on_date($stock_id);
 -      if ($qoh < 0)
 -              $qoh = 0;
 -      if ($adj_only)
 -      {
 -              if ($qty != 0)
 -                      $costs = $qty * $costs;
 -              if ($qoh>0)
 -                      $material_cost = $costs / $qoh;
 -              else // Journal Entry if QOH is 0/negative\r
 -              {
 -                      global $Refs;
 -
 -                      $id = get_next_trans_no(ST_JOURNAL);
 -                      $ref = $Refs->get_next(ST_JOURNAL);
 -                      
 -                      $stock_gl_code = get_stock_gl_code($stock_id);
 -                      $memo = "WO Issue settlement JV for zero/negative respository of ".$stock_id;
 -                      //Reverse the inventory effect if $qoh <=0
 -                      add_gl_trans_std_cost(ST_JOURNAL, $id, $date_, 
 -                              $stock_gl_code["inventory_account"],
 -                              $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'], $memo, 
 -                              -$costs);
 -                      //GL Posting to inventory adjustment account
 -                      add_gl_trans_std_cost(ST_JOURNAL, $id, $date_, 
 -                              $stock_gl_code["adjustment_account"],
 -                              $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'], $memo,
 -                              $costs);
 -                              
 -                      add_audit_trail(ST_JOURNAL, $id, $date_);
 -                      add_comments(ST_JOURNAL, $id, $date_, $memo);
 -                      $Refs->save(ST_JOURNAL, $id, $ref);     
 -              }
 -      }
 -      else
 -      {
 -              if ($qoh + $qty != 0)   
 -                      $material_cost = ($qty * $costs) /      ($qoh + $qty);
 -      }       \r
 -      $sql = "UPDATE ".TB_PREF."stock_master SET material_cost=material_cost+"
 -              .db_escape($material_cost)
 -              ." WHERE stock_id=".db_escape($stock_id);
 -      db_query($sql,"The cost details for the inventory item could not be updated");
 -}
 -
  function add_work_order($wo_ref, $loc_code, $units_reqd, $stock_id,
        $type, $date_, $required_by, $memo_, $costs, $cr_acc, $labour, $cr_lab_acc)
  {
        $args->woid = 0;
        hook_db_prewrite($args, ST_WORKORDER);
  
 +      add_material_cost($stock_id, $units_reqd, $date_);
 +
        $date = date2sql($date_);
        $required = date2sql($required_by);
  
@@@ -61,9 -263,6 +61,9 @@@ function update_work_order($woid, $loc_
                'date_', 'required_by', 'memo_'), $args);
        hook_db_prewrite($args, ST_WORKORDER);
  
 +      add_material_cost($_POST['old_stk_id'], -$_POST['old_qty'], $date_);
 +      add_material_cost($stock_id, $units_reqd, $date_);
 +
        $date = date2sql($date_);
        $required = date2sql($required_by);
  
@@@ -87,8 -286,6 +87,8 @@@ function delete_work_order($woid
        begin_transaction();
        hook_db_prevoid(ST_WORKORDER, $woid);
  
 +      add_material_cost($_POST['stock_id'], -$_POST['quantity'], $_POST['date_']);
 +
        // delete the work order requirements
        delete_wo_requirements($woid);
  
@@@ -173,7 -370,7 +173,7 @@@ function release_work_order($woid, $rel
        create_wo_requirements($woid, $stock_id);
  
        add_comments(ST_WORKORDER, $woid, $releaseDate, $memo_);
-       add_audit_trail(ST_WORKORDER, $woid, $myrow['date_'], _("Released."));
 -      add_audit_trail(ST_WORKORDER, $woid, $releaseDate,_("Released."));
++      add_audit_trail(ST_WORKORDER, $woid, sql2date($myrow['date_']), _("Released."));
  
        commit_transaction();
  }
@@@ -217,16 -414,6 +217,16 @@@ function void_work_order($woid
        $work_order = get_work_order($woid);
        if (!($work_order["type"] == WO_ADVANCED))
        {
 +              $date = sql2date($work_order['date_']);
 +              $qty = $work_order['units_reqd'];
 +              add_material_cost($work_order['stock_id'], -$qty, $date); // remove avg. cost for qty
 +              $cost = get_gl_wo_cost($woid, WO_LABOUR); // get the labour cost and reduce avg cost
 +              if ($cost != 0)
 +                      add_labour_cost($work_order['stock_id'], -$qty, $date, $cost);
 +              $cost = get_gl_wo_cost($woid, WO_OVERHEAD); // get the overhead cost and reduce avg cost
 +              if ($cost != 0)
 +                      add_overhead_cost($work_order['stock_id'], -$qty, $date, $cost);
 +
                $sql = "UPDATE ".TB_PREF."workorders SET closed=1,units_reqd=0,units_issued=0 WHERE id = "
                        .db_escape($woid);
                db_query($sql, "The work order couldn't be voided");
                // void all related stock moves
                void_stock_move(ST_WORKORDER, $woid);
  
 -              // void any related bank/gl trans
 -              void_bank_trans(ST_WORKORDER, $woid, true);
 +              void_wo_costing($woid);
  
                // clear the requirements units received
                void_wo_requirements($woid);
        {
                // void everything inside the work order : issues, productions, payments
                $date = sql2date($work_order['date_']);
 -              
 +              add_material_cost($work_order['stock_id'], -$work_order['units_reqd'], $date); // remove avg. cost for qty
                $result = get_work_order_productions($woid); // check the produced quantity
                $qty = 0;
                while ($row = db_fetch($result))
                {
 -                      void_work_order_produce($row['id']);
 +                      $qty += $row['quantity'];
 +                      // clear the production record
 +                      $sql = "UPDATE ".TB_PREF."wo_manufacture SET quantity=0 WHERE id=".$$row['id'];
 +                      db_query($sql, "Cannot void a wo production");
                        
 -                      //Post voided entry if not prevoided explicitly
 -                      $void_entry = get_voided_entry(ST_MANURECEIVE, $row['id']);
 -                      if ($void_entry)
 -                              continue;
 -                      $memo_ = _("Voiding Work Order Trans # ").$woid;
 -                      add_audit_trail(ST_MANURECEIVE, $row['id'], today(), _("Voided.")."\n".$memo_);
 -                      add_voided_entry(ST_MANURECEIVE, $row['id'], today(), $memo_);\r
 +                      void_stock_move(ST_MANURECEIVE, $row['id']); // and void the stock moves; 
                }
 -\r
 -              $result = get_work_order_issues($woid);
 +              $result = get_additional_issues($woid); // check the issued quantities
                $cost = 0;
                $issue_no = 0;
                while ($row = db_fetch($result))
                {
 -                      void_work_order_issue($row['issue_no']);
 -                      
 -                      //Post voided entry if not prevoided explicitly
 -                      $void_entry = get_voided_entry(ST_MANUISSUE, $row['issue_no']);
 -                      if ($void_entry)
 -                              continue;
 -                      $memo_ = _("Voiding Work Order Trans # ").$woid;
 -                      add_audit_trail(ST_MANUISSUE, $row['issue_no'], today(), _("Voided.")."\n".$memo_);
 -                      add_voided_entry(ST_MANUISSUE, $row['issue_no'], today(), $memo_);                              
 -              }
 +                      $std_cost = get_standard_cost($row['stock_id']);
 +                      $icost = $std_cost * $row['qty_issued'];
 +                      $cost += $icost;
 +                      if ($issue_no == 0)
 +                              $issue_no = $row['issue_no'];
 +                      // void the actual issue items and their quantities
 +                      $sql = "UPDATE ".TB_PREF."wo_issue_items SET qty_issued = 0 WHERE issue_id="
 +                              .db_escape($row['id']);
 +                      db_query($sql,"A work order issue item could not be voided");
 +              }       
 +              if ($issue_no != 0)
 +                      void_stock_move(ST_MANUISSUE, $issue_no); // and void the stock moves 
 +              if ($cost != 0)
 +                      add_issue_cost($work_order['stock_id'], -$qty, $date, $cost);
  
 -              //Adust avg labour cost\r
 -              $cost = get_gl_wo_cost($woid, WO_LABOUR); \r
 +              $cost = get_gl_wo_cost($woid, WO_LABOUR); // get the labour cost and reduce avg cost
                if ($cost != 0)
 -                      add_labour_cost($work_order['stock_id'], 1, $date, -$cost, true);
 -                      \r
 -              //Adust avg overhead cost\r
 -              $cost = get_gl_wo_cost($woid, WO_OVERHEAD); \r
 +                      add_labour_cost($work_order['stock_id'], -$qty, $date, $cost);
 +              $cost = get_gl_wo_cost($woid, WO_OVERHEAD); // get the overhead cost and reduce avg cost
                if ($cost != 0)
 -                      add_overhead_cost($work_order['stock_id'], 1, $date, -$cost, true);
 +                      add_overhead_cost($work_order['stock_id'], -$qty, $date, $cost);
                
                $sql = "UPDATE ".TB_PREF."workorders SET closed=1,units_reqd=0,units_issued=0 WHERE id = "
                        .db_escape($woid);
                // void all related stock moves
                void_stock_move(ST_WORKORDER, $woid);
  
 -              // void any related bank/gl trans
 -              void_bank_trans(ST_WORKORDER, $woid, true);
 +              void_wo_costing($wo);
  
                // clear the requirements units received
                void_wo_requirements($woid);
index 5654caeb3d70ad07c38a6e616a98b0a5b2c42844,9b869d0a1b935d6a94372450e139c3d02c110084..bcf9688f0ef015e1d5270a564042ed5b91c95664
@@@ -66,12 -66,29 +66,12 @@@ function add_work_order_quick($wo_ref, 
          db_query($sql, "The work order requirements could not be added");
  
                // insert a -ve stock move for each item
 -              // Chaitanya: Updated to record price and cost as std_cost for work order issued item
 -              $UnitCost = get_standard_cost($bom_item["component"]);
                add_stock_move(ST_WORKORDER, $bom_item["component"], $woid,
 -                      $bom_item["loc_code"], $date_, $wo_ref, -$item_quantity, $UnitCost, 0, 1, $UnitCost);
 -      }
 -      
 -      // -------------------------------------------------------------------------
 -      //Negative Stock Handling
 -      $qoh = get_qoh_on_date($stock_id);
 -      $cost_adjust = false;
 -      if ($qoh < 0)
 -      {
 -              if ($qoh + $units_reqd > 0)
 -                      $cost_adjust = true;
 +                      $bom_item["loc_code"], $date_, $wo_ref, -$item_quantity, 0);
        }
  
 +
        // -------------------------------------------------------------------------
 -      
 -      //Negative Stock Handling First; Prior to add_stock_move
 -      if ($cost_adjust)
 -              adjust_deliveries($stock_id, get_standard_cost($stock_id), $date_);
 -              
 -      // -------------------------------------------------------------------------    
  
        // insert a +ve stock move for the item being manufactured
        add_stock_move(ST_WORKORDER, $stock_id, $woid,  $loc_code, $date_,
@@@ -80,8 -97,8 +80,8 @@@
        // -------------------------------------------------------------------------
  
        work_order_quick_costs($woid, $stock_id, $units_reqd, $date_, 0, $costs, $cr_acc, $labour, $cr_lab_acc);
 -              
 -      //--------------------------------------------------------------------------
 +
 +      // -------------------------------------------------------------------------
  
        add_comments(ST_WORKORDER, $woid, $date_, $memo_);
  
@@@ -103,9 -120,10 +103,9 @@@ function work_order_quick_costs($woid, 
  
        // credit all the components
        $total_cost = 0;
 -      //Chaitanya : capture the exact i.e. non-rounded cost to avoid rounding error amplification
 -      $total_material_cost = 0;
        while ($bom_item = db_fetch($result))
        {
 +
                $bom_accounts = get_stock_gl_code($bom_item["component"]);
  
                $bom_cost = $bom_item["ComponentCost"] * $units_reqd;
                        $memo = $date_.": ".$memo; 
                        update_wo_requirement_issued($woid, $bom_item['component'], $bom_item["quantity"] * $units_reqd);                       
                        // insert a -ve stock move for each item
 -                      // Chaitanya: Updated to record price and cost as std_cost for work order issued item
 -                      $UnitCost = get_standard_cost($bom_item["component"]);                  
                        add_stock_move(ST_MANURECEIVE, $bom_item["component"], $advanced,
 -                              $bom_item["loc_code"], $date_, "", -$bom_item["quantity"] * $units_reqd, $UnitCost, 0, 1, $UnitCost);
 +                              $bom_item["loc_code"], $date_, "", -$bom_item["quantity"] * $units_reqd, 0);
                }
 -              
 -              //Chaitanya : Compatibility for Service Items
 -              if (!is_service($bom_accounts["mb_flag"]))
 -                      $ivaccount = $bom_accounts["inventory_account"];
 -              else
 -                      $ivaccount = $bom_accounts["cogs_account"];
 -              $total_cost += add_gl_trans_std_cost(ST_WORKORDER, $woid, $date_, $ivaccount, 0, 0,
 +              $total_cost += add_gl_trans_std_cost(ST_WORKORDER, $woid, $date_, $bom_accounts["inventory_account"], 0, 0,
                        $memo, -$bom_cost);
 -              $total_material_cost += $bom_cost;
 +
        }
++      $item_accounts = get_stock_gl_code($stock_id);
        if ($advanced)
        {
 -              //Chaitanya: Material cost added at time of production as per BOM at the time and in adjustment mode.
 -              add_material_cost($stock_id, $units_reqd, $date_, true);        
 -      
                $wo = get_work_order($woid);
                // also take the additional issues
                // moved to work_order_issues_db.inc
                if ($issue_total != 0)
                        add_issue_cost($stock_id, $units_reqd, $date_, $issue_total);
                */      
 -              
 -              // Logic moved to work_order_costs.php
 -              /*
                $lcost = get_gl_wo_cost($woid, WO_LABOUR);
                add_labour_cost($stock_id, $units_reqd, $date_, $lcost * $units_reqd / $wo['units_reqd']);
                $ocost = get_gl_wo_cost($woid, WO_OVERHEAD);
 -              add_overhead_cost($stock_id, $units_reqd, $date_, $ocost * $units_reqd / $wo['units_reqd']); */
 -      }
 -      // credit additional costs
 -      $item_accounts = get_stock_gl_code($stock_id);
 -      if ($costs != 0.0)
 -      {
 -              add_gl_trans_std_cost(ST_WORKORDER, $woid, $date_, $cr_acc,
 -                      0, 0, $wo_cost_types[WO_OVERHEAD], -$costs, PT_WORKORDER, WO_OVERHEAD);
 -              $is_bank_to = is_bank_account($cr_acc);
 -      if ($is_bank_to)
 -      {
 -              add_bank_trans(ST_WORKORDER, $woid, $is_bank_to, "",
 -                      $date_, -$costs, PT_WORKORDER, WO_OVERHEAD, get_company_currency(),
 -                      "Cannot insert a destination bank transaction");
 -      }
 -                      
 -              add_gl_trans_std_cost(ST_WORKORDER, $woid, $date_, $item_accounts["assembly_account"],
 -                      $item_accounts["dimension_id"], $item_accounts["dimension2_id"], $wo_cost_types[WO_OVERHEAD], $costs, 
 -                      PT_WORKORDER, WO_OVERHEAD);
 -      }
 -      if ($labour != 0.0)
 -      {
 -              add_gl_trans_std_cost(ST_WORKORDER, $woid, $date_, $cr_lab_acc,
 -                      0, 0, $wo_cost_types[WO_LABOUR], -$labour, PT_WORKORDER, WO_LABOUR);
 -              $is_bank_to = is_bank_account($cr_lab_acc);
 -      if ($is_bank_to)
 -      {
 -              add_bank_trans(ST_WORKORDER, $woid, $is_bank_to, "",
 -                      $date_, -$labour, PT_WORKORDER, WO_LABOUR, get_company_currency(),
 -                      "Cannot insert a destination bank transaction");
 -      }
 -                      
 -              add_gl_trans_std_cost(ST_WORKORDER, $woid, $date_, $item_accounts["assembly_account"],
 -                      $item_accounts["dimension_id"], $item_accounts["dimension2_id"], $wo_cost_types[WO_LABOUR], $labour, 
 -                      PT_WORKORDER, WO_LABOUR);
 +              add_overhead_cost($stock_id, $units_reqd, $date_, $ocost * $units_reqd / $wo['units_reqd']);
 +
 +      } else { // only for quick
 +              // credit additional costs
-               $item_accounts = get_stock_gl_code($stock_id);
 +
 +              if ($costs != 0.0)
 +              {
 +                      add_wo_costs_journal($woid, $costs, WO_OVERHEAD, $cr_acc, $item_accounts["assembly_account"],
 +                              $date_, $item_accounts["dimension_id"], $item_accounts["dimension2_id"]);
 +              }
 +              if ($labour != 0.0) // only for quick
 +              {
 +                      add_wo_costs_journal($woid, $labour, WO_LABOUR, $cr_lab_acc, $item_accounts["assembly_account"],
 +                              $date_, $item_accounts["dimension_id"], $item_accounts["dimension2_id"]);
 +              }
        }
        // debit total components $total_cost
        $stockitem = get_item($stock_id);
        if ($advanced)
                $memo = $date_.": ".$memo;
      add_gl_trans_std_cost(ST_WORKORDER, $woid, $date_, $item_accounts["inventory_account"],
 -        0, 0, $memo, -$total_cost);   
 -              
 -      //Chaitanya : Update cost of the manufactured item in stock moves table
 -      $UnitWOCost = ($total_material_cost + $costs + $labour)/$units_reqd;
 -      update_stock_move(ST_WORKORDER, $woid, $stock_id, $UnitWOCost);         
 +        0, 0, $memo, -$total_cost);
  }
  
  //--------------------------------------------------------------------------------------
index 68b10f6a57a14f2e7e70396538c2a6e79a4a5894,ce96abaa43743aa1647798fd634fb82898e5ab61..af7bf947e43a24a57413754a60258c15d5945905
@@@ -65,6 -65,7 +65,7 @@@ if (isset($_GET['AddedID'])
        display_note(get_gl_view_str($stype, $id, _("View the GL Journal Entries for this Work Order")), 1);
        $ar = array('PARAM_0' => $_GET['date'], 'PARAM_1' => $_GET['date'], 'PARAM_2' => $stype); 
        display_note(print_link(_("Print the GL Journal Entries for this Work Order"), 702, $ar), 1);
+               hyperlink_params("$path_to_root/admin/attachments.php", _("Add an Attachment"), "filterType=$stype&trans_no=$id");
        }
        
        safe_exit();
@@@ -156,7 -157,7 +157,7 @@@ function can_process(
        }
        elseif (!is_date_in_fiscalyear($_POST['date_']))
        {
 -              display_error(_("The entered date is not in fiscal year."));
 +              display_error(_("The entered date is out of fiscal year or is closed for further data entry."));
                set_focus('date_');
                return false;
        }
                }
                //elseif (!is_date_in_fiscalyear($_POST['RequDate']))
                //{
 -              //      display_error(_("The entered date is not in fiscal year."));
 +              //  display_error(_("The entered date is out of fiscal year or is closed for further data entry."));
                //      return false;
                //}
        if (isset($selected_id))
@@@ -351,7 -352,8 +352,8 @@@ if (isset($selected_id)
  
        $_POST['wo_ref'] = $myrow["wo_ref"];
        $_POST['stock_id'] = $myrow["stock_id"];
-       $_POST['quantity'] = qty_format($myrow["units_reqd"], $_POST['stock_id'], $dec);
+       //$_POST['quantity'] = qty_format($myrow["units_reqd"], $_POST['stock_id'], $dec);
+       $_POST['quantity'] = $myrow["units_reqd"];
        $_POST['StockLocation'] = $myrow["loc_code"];
        $_POST['released'] = $myrow["released"];
        $_POST['closed'] = $myrow["closed"];
index 77863d2767043a15d258244c22625233365a54cf,c7d1cd7cc5d43b15b14f31652f880f078e541d01..b5d6e4cc1f0058d6d264f1780b6039a1154fbcaf
@@@ -11,7 -11,6 +11,7 @@@
  ***********************************************************************/
  $page_security = 'SA_MANUFISSUE';
  $path_to_root = "..";
 +
  include_once($path_to_root . "/includes/ui/items_cart.inc");
  
  include_once($path_to_root . "/includes/session.inc");
@@@ -27,7 -26,6 +27,7 @@@ if ($use_popup_windows
        $js .= get_js_open_window(800, 500);
  if ($use_date_picker)
        $js .= get_js_date_picker();
 +
  page(_($help_context = "Issue Items to Work Order"), false, false, "", $js);
  
  //-----------------------------------------------------------------------------------------------
@@@ -64,13 -62,14 +64,11 @@@ function handle_new_order(
                unset ($_SESSION['issue_items']);
        }
  
--     Session_register("issue_items");
--
-      $_SESSION['issue_items'] = new items_cart(28);
+      $_SESSION['issue_items'] = new items_cart(ST_MANUISSUE);
       $_SESSION['issue_items']->order_id = $_GET['trans_no'];
  }
  
  //-----------------------------------------------------------------------------------------------
 -
  function can_process()
  {
        global $Refs;
@@@ -83,7 -82,7 +81,7 @@@
        } 
        elseif (!is_date_in_fiscalyear($_POST['date_'])) 
        {
 -              display_error(_("The entered date is not in fiscal year."));
 +              display_error(_("The entered date is out of fiscal year or is closed for further data entry."));
                set_focus('date_');
                return false;
        }
@@@ -94,7 -93,7 +92,7 @@@
                return false;
        }
  
-       if (!is_new_reference($_POST['ref'], 28)) 
+       if (!is_new_reference($_POST['ref'], ST_MANUISSUE)) 
        {
                display_error(_("The entered reference is already in use."));
                set_focus('ref');
        $failed_item = $_SESSION['issue_items']->check_qoh($_POST['Location'], $_POST['date_'], !$_POST['IssueType']);
        if ($failed_item != -1) 
        {
 +              $item = $_SESSION['issue_items']->line_items[$failed_item];
        display_error( _("The issue cannot be processed because an entered item would cause a negative inventory balance :") .
 -              " " . $failed_item->stock_id . " - " .  $failed_item->item_description);
 +              " " . $item->stock_id . " - " .  $item->item_description);
                return false;
        }
  
@@@ -138,7 -136,7 +136,7 @@@ if (isset($_POST['Process']) && can_pro
  
  function check_item_data()
  {
-       if (!check_num('qty', 0))
+       if (input_num('qty') == 0 || !check_num('qty', 0))
        {
                display_error(_("The quantity entered is negative or invalid."));
                set_focus('qty');
@@@ -201,6 -199,7 +199,7 @@@ if (isset($_POST['UpdateItem'])
  if (isset($_POST['CancelItemChanges'])) {
        line_start_focus();
  }
  //-----------------------------------------------------------------------------------------------
  
  if (isset($_GET['trans_no']))
index d1c35452b4bcb20eddd897a7e54c30c031eaa290,a31bc2ec83665bc9ebe9ff0a3dcfa47c7f96889f..00e088e0fbc489aa884ac5216080e0fa79c139b5
  //------------------- update average material cost ------------------------------------------ Joe Hunt Mar-03-2008
  function update_average_material_cost($supplier, $stock_id, $price, $qty, $date, $adj_only=false)
  {
 -    //8-OCT-2011 : Skip negative inventory adjustment for case of adjust_only\r
 -    if (is_inventory_item($stock_id) && !$adj_only) \r
+       //Handle if inventory will become negative
++    //8-OCT-2011 : Skip negative inventory adjustment for case of adjust_only
++    if (is_inventory_item($stock_id) && !$adj_only)
+         handle_negative_inventory($stock_id, $qty, $price, $date);    
        // probably this function should be optimized
        // passing transaction cart as argument. This would
        // save a couple of db calls like get_supplier()
@@@ -26,9 -31,6 +31,6 @@@
                $price = get_tax_free_price_for_item($stock_id, $price, $supp['tax_group_id'],
                        $supp['tax_included']);
  
-       //$dec = user_price_dec();
-       //price_decimal_format($price, $dec);
-       //$price = round2($price, $dec);
        if ($currency != null)
        {
                $ex_rate = get_exchange_rate_to_home_currency($currency, $date);
        }       
        else
                $price_in_home_currency = $price;
-       $sql = "SELECT material_cost FROM ".TB_PREF."stock_master WHERE stock_id=".db_escape($stock_id);
 -      
++
+       $price_in_home_currency_ = $price_in_home_currency;
+       
+       $sql = "SELECT mb_flag, material_cost, labour_cost, overhead_cost FROM ".TB_PREF."stock_master WHERE stock_id=".db_escape($stock_id);
        $result = db_query($sql);
        $myrow = db_fetch($result);
        $material_cost = $myrow['material_cost'];
-       if ($price > -0.0001 && $price < 0.0001)
-               return $material_cost;
+       
 -      //Price adjustment for manufactured item\r
 -      if (!$adj_only && $myrow['mb_flag'] == 'M') \r
++      //Price adjustment for manufactured item
++      if (!$adj_only && $myrow['mb_flag'] == 'M') 
+       {
+               $standard_cost = get_standard_cost($stock_id);
+               //reduce overhead_cost and labour_cost from price as those will remain as is
+               $price_in_home_currency = $price_in_home_currency - $myrow['labour_cost'] - $myrow['overhead_cost'];
+       }
 -      
++
        if ($adj_only)
                $exclude = ST_CUSTDELIVERY;
        else
                $exclude = 0;
        $cost_adjust = false;
-       //$qoh = get_qoh_on_date($stock_id, null, $date, $exclude);
++
        $qoh = get_qoh_on_date($stock_id);
-       
        if ($adj_only)
        {
                if ($qoh > 0)
        {
                if ($qoh < 0)
                {
-                       if ($qoh + $qty > 0)
+                       if ($qoh + $qty >= 0)
                                $cost_adjust = true;
                        $qoh = 0;
                }
-               if ($qoh + $qty != 0)
+               if ($qoh + $qty > 0)
 -                      $material_cost 
 -= ($qoh * $material_cost + $qty * $price_in_home_currency) /  ($qoh + $qty);
 -      }       
 -      
 +                      $material_cost = ($qoh * $material_cost + $qty * $price_in_home_currency) /     ($qoh + $qty);
-       }       
-       //$material_cost = round2($material_cost, $dec);
-       
-       if ($cost_adjust) // new 2010-02-10
-               adjust_deliveries($stock_id, $material_cost, $date);
++      }
++
+       if ($cost_adjust) // new 2010-02-10 //Chaitanya : Material_cost replaced with price
+               adjust_deliveries($stock_id, $price_in_home_currency_, $date);
        $sql = "UPDATE ".TB_PREF."stock_master SET material_cost=".db_escape($material_cost)."
                WHERE stock_id=".db_escape($stock_id);
        db_query($sql,"The cost details for the inventory item could not be updated");
@@@ -106,10 -117,10 +117,10 @@@ function add_grn(&$po
                                if ($clearing_act)
                                        $total += add_gl_trans_supplier(ST_SUPPRECEIVE, $grn, $date_, $stock_gl_code["inventory_account"],
                                                $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'],
-                                               $order_line->receive_qty * $order_line->taxfree_charge_price($po), $po->supplier_id);
 -                                              $order_line->receive_qty * $order_line->taxfree_charge_price($po), $po->supplier_id, '', 0, $order_line->stock_id);\r
 -                              update_average_material_cost($po->supplier_id, $order_line->stock_id, $order_line->price,\r
++                                              $order_line->receive_qty * $order_line->taxfree_charge_price($po), $po->supplier_id, '', 0, $order_line->stock_id);
 +                              update_average_material_cost($po->supplier_id, $order_line->stock_id, $order_line->price,
                                        $order_line->receive_qty, $date_);
--                      }               
++                      }
                        //----------------------------------------------------------------------------------------------------------------
                        if ($order_line->qty_received == 0)
                        {
                        /* Update location stock records - NB  a po cannot be entered for a service/kit parts done automatically */
                        add_stock_move(ST_SUPPRECEIVE, $order_line->stock_id, $grn, $po->Location, $date_, "",
                                $order_line->receive_qty, $order_line->standard_cost,
-                       $po->supplier_id, 1, $order_line->price);
 -                      $po->supplier_id, 1, $order_line->taxfree_charge_price($po));\r
++                      $po->supplier_id, 1, $order_line->taxfree_charge_price($po));
  
                } /*quantity received is != 0 */
        } /*end of order_line loop */
@@@ -170,11 -181,12 +181,12 @@@ function add_grn_batch($po_number, $sup
  //-------------------------------------------------------------------------------------------------------------
  
  function add_grn_detail_item($grn_batch_id, $po_detail_item, $item_code, $description, $standard_unit_cost,
-       $quantity_received, $price)
+       $quantity_received, $price, $quantity)
  {
        $sql = "UPDATE ".TB_PREF."purch_order_details
          SET quantity_received = quantity_received + ".db_escape($quantity_received).",
          std_cost_unit=".db_escape($standard_unit_cost).",
+         quantity_ordered=".db_escape($quantity).",
          act_price=".db_escape($price)."
          WHERE po_detail_item = ".db_escape($po_detail_item);
  
@@@ -239,63 -251,45 +251,54 @@@ function set_grn_item_credited(&$entere
      add_stock_move(ST_SUPPCREDIT, $entered_grn->item_code, $transno, $myrow['loc_code'], $date, "",
                $entered_grn->this_quantity_inv, $mcost, $supplier, 1, $entered_grn->chg_price);
  }
- /*
-       Returns selected  grn items:
-       
-       $grn_batch_id != 0  - only items for selected grn
-       $supplier_id!=''    - only items for selected supplier
-       $outsanding_only==true - only not fully invoiced items
-       $is_invoiced_only==true - only those which are at least partially invoiced
-       $invoice_no!=0 - for selected invoice(s)
-       $begin!='' or $end!='' - within selected delivery time range
- */
  function get_grn_items($grn_batch_id=0, $supplier_id="", $outstanding_only=false,
        $is_invoiced_only=false, $invoice_no=0, $begin="", $end="")
  {
 -    $sql = "SELECT ".TB_PREF."grn_batch.*, ".TB_PREF."grn_items.*, "
 -      .TB_PREF."purch_order_details.unit_price,"
 -      .TB_PREF."purch_order_details.act_price,"
 -      .TB_PREF."purch_order_details.quantity_ordered,"
 -              .TB_PREF."purch_order_details.std_cost_unit, units
 -      FROM ".TB_PREF."grn_batch, ".TB_PREF."grn_items, "
 -      .TB_PREF."purch_order_details, ".TB_PREF."stock_master";
 -    if ($invoice_no != 0)
 -      $sql .= ", ".TB_PREF."supp_invoice_items";
 -    $sql .= " WHERE ".TB_PREF."grn_items.grn_batch_id=".TB_PREF."grn_batch.id
 -              AND ".TB_PREF."grn_items.po_detail_item=".TB_PREF."purch_order_details.po_detail_item";
 -      if ($invoice_no != 0)
 -              $sql .= " AND ".TB_PREF."supp_invoice_items.supp_trans_type=".ST_SUPPINVOICE." AND 
 -                      ".TB_PREF."supp_invoice_items.supp_trans_no=$invoice_no AND
 -                      ".TB_PREF."grn_items.id=".TB_PREF."supp_invoice_items.grn_item_id";
 -      $sql .= " AND ".TB_PREF."stock_master.stock_id=".TB_PREF."grn_items.item_code ";
 +    $sql = "SELECT grn.*, grn_item.*,
 +              grn_item.quantity_inv".($invoice_no ? "-invoice_item.quantity" : '')."  quantity_inv,
 +      po_item.unit_price,
 +      po_item.act_price,
 +      po_item.quantity_ordered,
 +      po_item.std_cost_unit, units
 +      FROM    ".TB_PREF."grn_batch grn, "
 +                      .TB_PREF."purch_order_details po_item, "
 +                      .TB_PREF."stock_master stock_item,"
 +                              .TB_PREF."grn_items grn_item ";
 + 
 +    if ($invoice_no != 0) {
 +      $sql .= " LEFT JOIN ".TB_PREF."supp_invoice_items invoice_item ON ";
 +
 +              $inv_cond = "invoice_item.supp_trans_type=".ST_SUPPINVOICE." AND invoice_item.supp_trans_no ";
 +              if (is_array($invoice_no))
 +                      $inv_cond .= " IN (".implode(',' , $invoice_no) . ")";
 +              else
 +                      $inv_cond .= " = $invoice_no";
 +              $sql .= "($inv_cond) AND grn_item.id=invoice_item.grn_item_id";
 +      }
 +    $sql .= " WHERE grn_item.grn_batch_id=grn.id
 +              AND grn_item.po_detail_item=po_item.po_detail_item";
 +
 +      if ($outstanding_only)
 +      $sql .= " AND (".($invoice_no ? "$inv_cond OR ":'')."grn_item.qty_recd - grn_item.quantity_inv > 0)";
 +
 +      $sql .= " AND stock_item.stock_id=grn_item.item_code ";
  
        if ($begin != "")
 -              $sql .= " AND ".TB_PREF."grn_batch.delivery_date>='".date2sql($begin)."'";
 +              $sql .= " AND grn.delivery_date>='".date2sql($begin)."'";
        if ($end != "")
 -              $sql .= " AND ".TB_PREF."grn_batch.delivery_date<='".date2sql($end)."'";
 +              $sql .= " AND grn.delivery_date<='".date2sql($end)."'";
        if ($grn_batch_id != 0)
 -              $sql .= " AND ".TB_PREF."grn_batch.id=".db_escape($grn_batch_id)
 -                      ." AND ".TB_PREF."grn_items.grn_batch_id=".db_escape($grn_batch_id);
 +              $sql .= " AND grn.id=".db_escape($grn_batch_id)
 +                      ." AND grn_item.grn_batch_id=".db_escape($grn_batch_id);
  
        if ($is_invoiced_only)
 -              $sql .= " AND ".TB_PREF."grn_items.quantity_inv > 0";
 -
 -      if ($outstanding_only)
 -      $sql .= " AND ".TB_PREF."grn_items.qty_recd - ".TB_PREF."grn_items.quantity_inv > 0";
 +              $sql .= " AND grn_item.quantity_inv > 0";
  
        if ($supplier_id != "")
 -              $sql .= " AND ".TB_PREF."grn_batch.supplier_id =".db_escape($supplier_id);
 +              $sql .= " AND grn.supplier_id =".db_escape($supplier_id);
  
 -      $sql .= " ORDER BY ".TB_PREF."grn_batch.delivery_date, ".TB_PREF."grn_batch.id, ".TB_PREF."grn_items.id";
 +      $sql .= " ORDER BY grn.delivery_date, grn.id, grn_item.id";
  
        return db_query($sql, "Could not retreive GRNS");
  }
@@@ -329,7 -323,8 +332,8 @@@ function read_grn_items_to_order($grn_b
  
                while ($myrow = db_fetch($result))
                {
+                       if ($myrow['qty_recd'] == 0 && $myrow['quantity_inv'] == 0)
+                               continue; // 2011-01-18 Joe Hunt. We will not have empty credited rows.
                        if (is_null($myrow["units"]))
                        {
                                $units = "";
index 33cfd8710fd31f0c8cc4d263f0513492fef4380c,3ffc35d3abc23a8ac628a5a5f2f9074bb51f1096..0f7f9b53d01d7365c32166de61407e4ffc74573c
@@@ -16,14 -16,13 +16,14 @@@ include_once($path_to_root . "/purchasi
  function read_supplier_details_to_trans(&$supp_trans, $supplier_id)
  {
        $sql = "SELECT supp.supp_name, terms.terms, terms.days_before_due,
 -              terms.day_in_following_month, supp.tax_included,
 +              terms.day_in_following_month, supp.tax_included, supp.tax_algorithm,
                supp.tax_group_id, tax_group.name AS tax_group_name,
                supp.credit_limit - Sum(IFNULL(IF(trans.type=".ST_SUPPCREDIT.", -1, 1) 
                        * (ov_amount + ov_gst + ov_discount),0)) as cur_credit
 -              FROM ".TB_PREF."suppliers supp 
 -                      LEFT JOIN ".TB_PREF."supp_trans trans ON supp.supplier_id = trans.supplier_id, "
 -                      .TB_PREF."payment_terms terms, ".TB_PREF."tax_groups tax_group
 +              FROM ".TB_PREF."suppliers supp LEFT JOIN "
 +                      .TB_PREF."supp_trans trans ON supp.supplier_id = trans.supplier_id, "
 +                      .TB_PREF."payment_terms terms, "
 +                      .TB_PREF."tax_groups tax_group
                WHERE supp.tax_group_id = tax_group.id
                AND supp.payment_terms=terms.terms_indicator
                AND supp.supplier_id = ".db_escape($supplier_id)." GROUP BY supp.supp_name";
  
        $myrow = db_fetch($result);
  
 +    if ($supp_trans->tran_date == "")
 +    {
 +              $supp_trans->tran_date = Today();
 +
 +              if (!is_date_in_fiscalyear($supp_trans->tran_date))
 +                      $supp_trans->tran_date = end_fiscalyear();
 +      }
 +      if ($supp_trans->supplier_id != $supplier_id)
 +          get_duedate_from_terms($supp_trans);
 +
      $supp_trans->supplier_id = $supplier_id;
      $supp_trans->tax_included = $myrow['tax_included'];
 +    $supp_trans->tax_algorithm = $supp_trans->stored_algorithm = $myrow['tax_algorithm'];
      $supp_trans->supplier_name = $myrow['supp_name'];
        $supp_trans->terms = array( 
                'description' => $myrow['terms'],
                'days_before_due' => $myrow['days_before_due'], 
                'day_in_following_month' => $myrow['day_in_following_month'] );
--              
++
        $supp_trans->credit = $myrow['cur_credit'];
  
        $supp_trans->tax_description = $myrow['tax_group_name'];
        $supp_trans->tax_group_id = $myrow['tax_group_id'];
  
 -    if ($supp_trans->tran_date == "")
 -    {
 -              $supp_trans->tran_date = Today();
 -              if (!is_date_in_fiscalyear($supp_trans->tran_date))
 -                      $supp_trans->tran_date = end_fiscalyear();
 -      }
 -    //if ($supp_trans->due_date=="") {
 -    //        get_duedate_from_terms($supp_trans);
 -    //}
 -    get_duedate_from_terms($supp_trans);
  }
  
--//--------------------------------------------------------------------------------------------------
--
++//-------------------------------------------------------------------------------------------------
++//    Updates invoiced quantity in PO and GRN line, and act_price in PO
++//  Returns:
++// if chg_price is set:        previous act_price, delivery date and unit_price from PO
++//
  function update_supp_received_items_for_invoice($id, $po_detail_item, $qty_invoiced, $chg_price=null)
  {
        if ($chg_price != null)
@@@ -116,22 -114,16 +119,22 @@@ function get_diff_in_home_currency($sup
  }
  //----------------------------------------------------------------------------------------
  
 -function add_supp_invoice($supp_trans, $invoice_no=0) // do not receive as ref because we change locally
 +function add_supp_invoice(&$supp_trans) // do not receive as ref because we change locally
  {
        global $Refs;
  
        //$company_currency = get_company_currency();
 +      $trans_no = $supp_trans->trans_no;
 +      $trans_type = $supp_trans->trans_type;
        /*Start an sql transaction */
        begin_transaction();
 -      hook_db_prewrite($supp_trans, $supp_trans->trans_type);
 +      hook_db_prewrite($supp_trans, $trans_type);
        $tax_total = 0;
      $taxes = $supp_trans->get_taxes($supp_trans->tax_group_id);
 +      if ($trans_no) {
 +              void_transaction($trans_type, $trans_no, Today(), _("Document reentered."));
 +              $Refs->restore_last($trans_type, $trans_no);
 +      }
  
      foreach ($taxes as $n => $taxitem)
      {
        $tax_total += $taxes[$n]['Value'];
      }
  
 -      $invoice_items_total = $supp_trans->get_items_total();
 +      $invoice_items_total = $supp_trans->get_items_total(); // get total with/without tax dep. on tax_included
  //    $invoice_items_total = $supp_trans->get_total_taxfree($supp_trans->tax_group_id);
  
        if($supp_trans->tax_included==0) {
                $item_added_tax = $tax_total;
        } else {
                $item_added_tax = 0;
 -              
        }
  
 -      $trans_type = $supp_trans->trans_type;
 -      
        if ($trans_type == ST_SUPPCREDIT)
-       { 
+       {
                // let's negate everything because it's a credit note
                $invoice_items_total = -$invoice_items_total;
                $tax_total = -$tax_total;
      /*First insert the invoice into the supp_trans table*/
        $invoice_id = write_supp_trans($trans_type, 0, $supp_trans->supplier_id, $date_, $supp_trans->due_date,
                $supp_trans->reference, $supp_trans->supp_reference,
 -              $invoice_items_total, $item_added_tax, $supp_trans->ov_discount, "", 0, $supp_trans->tax_included);
 +              $invoice_items_total, $item_added_tax, $supp_trans->ov_discount, "", 0, $supp_trans->tax_included,
 +              $supp_trans->tax_algorithm);
 +
 +
 +      $supp_trans->trans_no = $invoice_id;
  
        $total = 0;
      /* Now the control account */
                        $trans_type, $invoice_id, $entered_gl_code->amount,
                        $ex_rate, $date_, $supp_trans->supp_reference, $supp_trans->tax_included);
      }
 -    
 +
      $clearing_act = get_company_pref('grn_clearing_act');
      foreach ($supp_trans->grn_items as $line_no => $entered_grn)
      {
                $line_taxfree = $entered_grn->taxfree_charge_price($supp_trans->tax_group_id);
                $line_tax = $entered_grn->full_charge_price($supp_trans->tax_group_id) - $line_taxfree;
                $stock_gl_code = get_stock_gl_code($entered_grn->item_code);
 -              
 +
        if ($trans_type == ST_SUPPCREDIT)
                {
                        $iv_act = (is_inventory_item($entered_grn->item_code) ? $stock_gl_code["inventory_account"] : 
                        //$old_price = $old[0];
                         
                        $old_price = $old[2];
+                       // adjust for tax included.
+                       $old_price = get_tax_free_price_for_item($entered_grn->item_code, $old_price,
+                               $supp_trans->tax_group_id, $entered_grn->tax_included);                 
  
                        /*
                        If statement is removed. Should always check for deliveries nomatter if there has been a price change. 
                        */
-                       //if ($old_price != $entered_grn->chg_price) // price-change, so update
+                       //if ($old_price != $line_taxfree) // price-change, so update
                        //{
-                       //$diff = $entered_grn->chg_price - $old_price;
+                       //$diff = $line_taxfree - $old_price;
                        $old_date = sql2date($old[1]);
                        if (!is_inventory_item($entered_grn->item_code))
                                $total += add_gl_trans_supplier($trans_type, $invoice_id, $date_, $iv_act,
                                        $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'],
                                        $entered_grn->this_quantity_inv * $old_price, $supp_trans->supplier_id, "", $ex_rate);
                                $diff = get_diff_in_home_currency($supp_trans->supplier_id, $old_date, $date_, $old_price, 
-                                       $entered_grn->chg_price);       
-                       
+                                       $line_taxfree); 
 -                      
++
                                // always return due to change in currency.
+                               /*$mat_cost = update_average_material_cost(null, $entered_grn->item_code,
+                                       $diff, $entered_grn->this_quantity_inv, $old_date, true); */
                                $mat_cost = update_average_material_cost(null, $entered_grn->item_code,
                                        $diff, $entered_grn->this_quantity_inv, null, true);
                                
                                        $total += add_gl_trans($trans_type, $invoice_id, $date_,        $stock_gl_code["inventory_account"],
                                                $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'], 'GRN Provision',
                                                $diff_amt, null, null, null,
-                                               "The general ledger transaction could not be added for the GRN of the inventory item"); 
+                                               "The general ledger transaction could not be added for the GRN of the inventory item");
+                                       //Chaitanya
+                                       //If QOH is 0 or negative then update_average_material_cost will be skipped
+                                       //Thus difference in PO and Supp Invoice should be handled separately
+                                       
+                                       $qoh = get_qoh_on_date($entered_grn->item_code);
+                                       if ($qoh <= 0)
+                                       {
+                                               global $Refs;
+                                               //Chaitanya : Post a journal entry
+                                               $id = get_next_trans_no(ST_JOURNAL);
+                                               $ref = $Refs->get_next(ST_JOURNAL);
+                                               $stock_id = $entered_grn->item_code;
+                                               $stock_gl_code = get_stock_gl_code($stock_id);
+                                               $memo = _("Supplier invoice adjustment for zero inventory of ").$stock_id." "._("Invoice")." ".$supp_trans->reference;
+                                               //Reverse the inventory effect if $qoh <=0
+                                               add_gl_trans_std_cost(ST_JOURNAL, $id, $date_, 
+                                                       $stock_gl_code["inventory_account"],
+                                                       $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'],
+                                                       $memo, -$entered_grn->this_quantity_inv * $diff);
+                                               //GL Posting to inventory adjustment account
+                                               add_gl_trans_std_cost(ST_JOURNAL, $id, $date_, 
+                                                       $stock_gl_code["adjustment_account"],
+                                                       $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'],
+                                                       $memo, $entered_grn->this_quantity_inv * $diff);
+                                               
+                                               add_audit_trail(ST_JOURNAL, $id, $date_);
+                                               add_comments(ST_JOURNAL, $id, $date_, $memo);
+                                               $Refs->save(ST_JOURNAL, $id, $ref);                                             
+                                       }                                       
+                                       
+                                       /*$qoh = get_qoh_on_date($entered_grn->item_code);
+                                       if ($qoh <= 0)
+                                       {
+                                               $memo = "Diff. in cost: ".$diff;
+                                               //Reverse the inventory effect if $qoh <=0
+                                               add_gl_trans_supplier($trans_type, $invoice_id, $date_, 
+                                               $stock_gl_code["inventory_account"],
+                                               $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'],
+                                               -$entered_grn->this_quantity_inv * $diff, $supp_trans->supplier_id, "", null, $memo);
+                                               //GL Posting to inventory adjustment account
+                                               add_gl_trans_supplier($trans_type, $invoice_id, $date_, 
+                                               $stock_gl_code["adjustment_account"],
+                                               $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'],
+                                               $entered_grn->this_quantity_inv * $diff, $supp_trans->supplier_id, "", null, $memo);                                            
+                                       }*/                             
                                        
                                        //add_gl_trans($trans_type, $invoice_id, $date_,        $stock_gl_code["cogs_account"],
                                        //      0, 0, 'GRN Provision', -$diff_amt, null, null, null,
                                                "The general ledger transaction could not be added for the price variance of the inventory item");
                                }               
                                update_stock_move_pid(ST_CUSTDELIVERY, $entered_grn->item_code, $old_date, $date_, 0, $mat_cost);
-                       } */
+                       } 
                        if (is_inventory_item($entered_grn->item_code))
                                update_stock_move_pid(ST_SUPPRECEIVE, $entered_grn->item_code, $old_date, $old_date, $supp_trans->supplier_id, $mat_cost);
+                       */      
                //}
                }
        // ----------------------------------------------------------------------
                                $taxitem['tax_type_id'], $taxitem['rate'], $supp_trans->tax_included, $taxitem['Value'],
                                $taxitem['Net'], $ex_rate, $date_, $supp_trans->supp_reference);
  
--              if ($trans_type == ST_SUPPCREDIT)
--                      $taxitem['Value'] = -$taxitem['Value'];
--              $total += add_gl_trans_supplier($trans_type, $invoice_id, $date_,
--                      $taxitem['purchasing_gl_code'], 0, 0, $taxitem['Value'],
--                      $supp_trans->supplier_id,
--                      "A general ledger transaction for the tax amount could not be added");
++                      if (isset($taxitem['purchasing_gl_code']))
++                      {
++                      if ($trans_type == ST_SUPPCREDIT)
++                              $taxitem['Value'] = -$taxitem['Value'];
++                      $total += add_gl_trans_supplier($trans_type, $invoice_id, $date_,
++                              $taxitem['purchasing_gl_code'], 0, 0, $taxitem['Value'],
++                              $supp_trans->supplier_id,
++                              "A general ledger transaction for the tax amount could not be added");
++                      }
        }
      }
        
  
        $Refs->save($trans_type, $invoice_id, $supp_trans->reference);
  
 -      if ($invoice_no != 0)
 +      if ($supp_trans->src_docs)
        {
 -              $invoice_alloc_balance = get_supp_trans_allocation_balance(ST_SUPPINVOICE, $invoice_no);
 +              $invoice_alloc_balance = get_supp_trans_allocation_balance(ST_SUPPINVOICE, $supp_trans->src_docs);
                if ($invoice_alloc_balance > 0) 
                {       //the invoice is not already fully allocated 
  
 -                      $trans = get_supp_trans($invoice_no, ST_SUPPINVOICE);
 +                      $trans = get_supp_trans($supp_trans->src_docs, ST_SUPPINVOICE);
                        $total = $trans['Total'];
  
                        $allocate_amount = ($invoice_alloc_balance > $total) ? $total : $invoice_alloc_balance;
                        /*Now insert the allocation record if > 0 */
                        if ($allocate_amount != 0) 
                        {
 -                              update_supp_trans_allocation(ST_SUPPINVOICE, $invoice_no, $allocate_amount);
 +                              update_supp_trans_allocation(ST_SUPPINVOICE, $supp_trans->src_docs, $allocate_amount);
                                update_supp_trans_allocation(ST_SUPPCREDIT, $invoice_id, $allocate_amount); // ***
 -                              add_supp_allocation($allocate_amount, ST_SUPPCREDIT, $invoice_id, ST_SUPPINVOICE, $invoice_no,
 +                              add_supp_allocation($allocate_amount, ST_SUPPCREDIT, $invoice_id, ST_SUPPINVOICE, $supp_trans->src_docs,
                                        $date_);
                                // Exchange Variations Joe Hunt 2008-09-20 ////////////////////////////////////////
  
 -                              exchange_variation(ST_SUPPCREDIT, $invoice_id, ST_SUPPINVOICE, $invoice_no, $date_,
 +                              exchange_variation(ST_SUPPCREDIT, $invoice_id, ST_SUPPINVOICE, $supp_trans->src_docs, $date_,
                                        $allocate_amount, PT_SUPPLIER);
  
                                ///////////////////////////////////////////////////////////////////////////
                }
        }
  
 -      $supp_trans->trans_no = $invoice_id;
        hook_db_postwrite($supp_trans, $supp_trans->trans_type);
      commit_transaction();
  
@@@ -387,8 -432,10 +446,10 @@@ function get_po_invoices_credits($po_nu
                FROM ".TB_PREF."supp_trans, ".TB_PREF."supp_invoice_items, "
                .TB_PREF."purch_order_details, ".TB_PREF."purch_orders
                WHERE ".TB_PREF."supp_invoice_items.supp_trans_no = ".TB_PREF."supp_trans.trans_no
+               AND ".TB_PREF."supp_invoice_items.supp_trans_type = ".TB_PREF."supp_trans.type
                AND ".TB_PREF."supp_invoice_items.po_detail_item_id = ".TB_PREF."purch_order_details.po_detail_item
                AND ".TB_PREF."purch_orders.supplier_id = ".TB_PREF."supp_trans.supplier_id
+               AND ".TB_PREF."purch_orders.order_no = ".TB_PREF."purch_order_details.order_no
                AND ".TB_PREF."purch_order_details.order_no = ".db_escape($po_number);
  
        return db_query($sql, "The invoices/credits for the po $po_number could not be retreived");
  
  function read_supp_invoice($trans_no, $trans_type, &$supp_trans)
  {
 -      $sql = "SELECT ".TB_PREF."supp_trans.*, supp_name FROM ".TB_PREF."supp_trans,".TB_PREF."suppliers
 +      $sql = "SELECT ".TB_PREF."supp_trans.*, supp_name 
 +              FROM ".TB_PREF."supp_trans,".TB_PREF."suppliers
                WHERE trans_no = ".db_escape($trans_no)." AND type = ".db_escape($trans_type)."
                AND ".TB_PREF."suppliers.supplier_id=".TB_PREF."supp_trans.supplier_id";
 +
        $result = db_query($sql, "Cannot retreive a supplier transaction");
  
        if (db_num_rows($result) == 1)
                $supp_trans->supplier_name = $trans_row["supp_name"];
                $supp_trans->tran_date = sql2date($trans_row["tran_date"]);
                $supp_trans->due_date = sql2date($trans_row["due_date"]);
-               //$supp_trans->Comments = $trans_row["TransText"];
                $supp_trans->Comments = get_comments_string($trans_type, $trans_no);
                $supp_trans->reference = $trans_row["reference"];
                $supp_trans->supp_reference = $trans_row["supp_reference"];
                $supp_trans->ov_discount = $trans_row["ov_discount"];
                $supp_trans->ov_gst = $trans_row["ov_gst"];
                $supp_trans->tax_included = $trans_row["tax_included"];
 +              $supp_trans->stored_algorithm = $supp_trans->tax_algorithm = $trans_row["tax_algorithm"];
  
                $id = $trans_row["trans_no"];
  
                if ($details_row["gl_code"] == 0)
                {
                        $supp_trans->add_grn_to_trans($details_row["grn_item_id"], $details_row["po_detail_item_id"], $details_row["stock_id"],
 -                                      $details_row["description"], 0, 0, $details_row["quantity"], 0, $details_row["FullUnitPrice"],
 +                                      $details_row["description"], 
 +                                      $details_row['qty_recd'],
 +                                      $details_row['quantity_inv']-$details_row["quantity"],
 +                                      $details_row["quantity"], 0, $details_row["FullUnitPrice"],
                                        0, 0);
                }
                else
@@@ -508,14 -548,18 +568,17 @@@ function void_supp_invoice($type, $type
                                $batch = get_grn_batch_from_item($details_row["grn_item_id"]);  
                                $grn = get_grn_batch($batch);
                        if ($type == ST_SUPPCREDIT) // credit note 2009-06-14 Joe Hunt Must restore the po and grn
 -                      {       
 +                      {       // We must get the corresponding invoice item to check for price chg.
                                        $match = get_matching_invoice_item($details_row["stock_id"], $details_row["po_detail_item_id"]);
-                                       if ($match !== false)
 -                                      
+                                       //Chaitanya : Skipped costing block & handle in void_stock_move
+                                       // We must get the corresponding invoice item to check for price chg.
+                                       /*if ($match !== false)
                                                $mat_cost = update_average_material_cost($grn["supplier_id"], $details_row["stock_id"],  
                                                        $match["unit_price"], -$details_row["quantity"], sql2date($match['tran_date']), $match['tran_date'] !== $trans['tran_date']);
                                        else            
                                                $mat_cost = update_average_material_cost($grn["supplier_id"], $details_row["stock_id"],  
-                                                       $details_row["FullUnitPrice"], -$details_row["quantity"], $old_date, $old[1] !== $trans['tran_date']);
+                                                       $details_row["FullUnitPrice"], -$details_row["quantity"], $old_date, $old[1] !== $trans['tran_date']);*/
 -                                                      
++
                                        $sql = "UPDATE ".TB_PREF."purch_order_details
                                        SET quantity_ordered = quantity_ordered + ".-$details_row["quantity"].", ";
                                if ($match !== false)
                                        // Only adjust the avg for the diff
                                        $mat_cost = update_average_material_cost(null, $details_row["stock_id"],
                                                $diff, -$details_row["quantity"], $old_date, true);
+                                               
+                                       //Chaitanya : Reverse effect
+                                       //If QOH is 0 or negative then update_average_material_cost will be skipped
+                                       //Thus difference in PO and Supp Invoice should be handled separately
+                                       
+                                       $qoh = get_qoh_on_date($details_row["stock_id"]);
+                                       if ($diff*$details_row["quantity"] !=0 && $qoh <= 0)
+                                       {
+                                               global $Refs;
+                                               //Chaitanya : Post a journal entry
+                                               $id = get_next_trans_no(ST_JOURNAL);
+                                               $ref = $Refs->get_next(ST_JOURNAL);
+                                               $stock_id = $details_row["stock_id"];
+                                               $stock_gl_code = get_stock_gl_code($stock_id);
+                                               $memo = "Reversing Supplier invoice adjustment for zero inventory of ".$stock_id." Invoice: ".$trans['reference'];
+                                               //Reverse the inventory effect if $qoh <=0
+                                               add_gl_trans_std_cost(ST_JOURNAL, $id, $old_date, 
+                                                       $stock_gl_code["inventory_account"],
+                                                       $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'],
+                                                       $memo, $details_row["quantity"] * $diff);
+                                               //GL Posting to inventory adjustment account
+                                               add_gl_trans_std_cost(ST_JOURNAL, $id, $old_date, 
+                                                       $stock_gl_code["adjustment_account"],
+                                                       $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'],
+                                                       $memo, -$details_row["quantity"] * $diff);
+                                               
+                                               add_audit_trail(ST_JOURNAL, $id, $old_date);
+                                               add_comments(ST_JOURNAL, $id, $old_date, $memo);
+                                               $Refs->save(ST_JOURNAL, $id, $ref);                                             
+                                       }       
                                }
-                               $deliveries = get_deliveries_between($details_row["stock_id"], $old_date, $date_);
+                               /*$deliveries = get_deliveries_between($details_row["stock_id"], $old_date, $date_);
                                if ($deliveries[0] != 0) // have deliveries been done during the period?
                                {
                                        update_stock_move_pid(ST_CUSTDELIVERY, $details_row["stock_id"], $old_date, $date_, 0, $mat_cost);
                                }
                                update_stock_move_pid(ST_SUPPRECEIVE, $details_row["stock_id"], $old_date, $old_date, $grn['supplier_id'], $mat_cost);
+                               */
                }
          }
        }
@@@ -576,62 -652,47 +671,66 @@@ function is_reference_already_there($su
  
  function remove_not_invoice_item($id)
  {
 -    begin_transaction();
 +      begin_transaction();
  
-       $myrow = get_grn_item_detail($id);
+     $myrow = get_grn_item_detail($id);
  
-       $grn = get_grn_batch($myrow['grn_batch_id']);
+     $grn = get_grn_batch($myrow['grn_batch_id']);
 -    
++
+     $supp = get_supplier($grn["supplier_id"]);
  
 -    $sql = "UPDATE ".TB_PREF."purch_order_details
 -        SET quantity_received = qty_invoiced, quantity_ordered = qty_invoiced WHERE po_detail_item = ".$myrow["po_detail_item"];
 -    db_query($sql, "The quantity invoiced of the purchase order line could not be updated");
 +      $sql = "UPDATE ".TB_PREF."purch_order_details
 +              SET quantity_received = qty_invoiced, quantity_ordered = qty_invoiced WHERE po_detail_item = ".$myrow["po_detail_item"];
 +      db_query($sql, "The quantity invoiced of the purchase order line could not be updated");
  
-       $sql = "UPDATE ".TB_PREF."grn_items
-               SET qty_recd = quantity_inv WHERE id = ".$myrow["id"];
-       db_query($sql, "The quantity invoiced off the items received record could not be updated");
-       update_average_material_cost($grn["supplier_id"], $myrow["item_code"],
-               $myrow["unit_price"], -$myrow["QtyOstdg"], Today());
-       add_stock_move(ST_SUPPRECEIVE, $myrow["item_code"], $myrow['grn_batch_id'], $grn['loc_code'], sql2date($grn["delivery_date"]), "",
-               -$myrow["QtyOstdg"], $myrow['std_cost_unit'], $grn["supplier_id"], 1, $myrow['unit_price']);
-               
+     $sql = "UPDATE ".TB_PREF."grn_items
+         SET qty_recd = quantity_inv WHERE id = ".$myrow["id"];
+     db_query($sql, "The quantity invoiced off the items received record could not be updated");
+     update_average_material_cost($grn["supplier_id"], $myrow["item_code"],
+         $myrow["unit_price"], -$myrow["QtyOstdg"], Today());
+         
+     $price = $myrow['unit_price'];
+     if ($supp['tax_included'])
+         $price = get_tax_free_price_for_item($myrow['item_code'], $myrow['unit_price'], $supp['tax_group_id'], $supp['tax_included']);        
+     add_stock_move(ST_SUPPRECEIVE, $myrow["item_code"], $myrow['grn_batch_id'], $grn['loc_code'], sql2date($grn["delivery_date"]), "",
+         -$myrow["QtyOstdg"], $myrow['std_cost_unit'], $grn["supplier_id"], 1, $price);
+         
      $clearing_act = get_company_pref('grn_clearing_act');
-       if ($clearing_act) {    // otherwise GRN clearing account is not used
-               if (is_inventory_item($myrow['item_code']))
-               {
-               $total = 0;
-                       $stock_gl_code = get_stock_gl_code($myrow['item_code']);
-                       $date = sql2date($grn["delivery_date"]);
-                       $total += add_gl_trans_supplier(ST_SUPPRECEIVE, $myrow['grn_batch_id'], $date, $stock_gl_code["inventory_account"],
-                               $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'],
-                               -$myrow['QtyOstdg'] * $myrow['unit_price'], $grn["supplier_id"], "", 0, _("GRN Removal"));
-                       $total += add_gl_trans_supplier(ST_SUPPRECEIVE, $myrow['grn_batch_id'], $date, $clearing_act,
-                               0, 0, -$total, null, "", 0, _("GRN Removal"));
-               }       
-       }
+     if ($clearing_act) {    // otherwise GRN clearing account is not used
+         if (is_inventory_item($myrow['item_code']))
+         {
+             $total = 0;
+             $stock_gl_code = get_stock_gl_code($myrow['item_code']);
+             $date = sql2date($grn["delivery_date"]);
+             $total += add_gl_trans_supplier(ST_SUPPRECEIVE, $myrow['grn_batch_id'], $date, $stock_gl_code["inventory_account"],
+                 $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'],
+                 -$myrow['QtyOstdg'] * $price, $grn["supplier_id"], "", 0, _("GRN Removal"));
+             $total += add_gl_trans_supplier(ST_SUPPRECEIVE, $myrow['grn_batch_id'], $date, $clearing_act,
+                 0, 0, -$total, null, "", 0, _("GRN Removal"));
+         }    
+     }
  
-       commit_transaction();
+     commit_transaction();
  }
 -?>
 +
 +function find_src_invoices($cart)
 +{
 +      $invoices = $po_ids = array();
 +      foreach($cart->grn_items as $item)
 +              $po_ids[] = "'$item->po_detail_item'";  // credit item lines
 +
 +      if (count($po_ids)) {
 +              $sql = "SELECT DISTINCT trans.trans_no, trans.reference, trans.supp_reference
 +                      FROM ".TB_PREF."supp_invoice_items items
 +                      LEFT JOIN ".TB_PREF."supp_trans trans ON trans.trans_no=items.supp_trans_no AND trans.`type`=items.supp_trans_type
 +                      WHERE items.po_detail_item_id IN (" . implode(',', $po_ids). ")"." AND items.supp_trans_type=20";
 +              $result = db_query($sql, "cannot find source invoice details");
 +              while ($rec = db_fetch($result))
 +              {
 +                      $invoices[$rec['trans_no']] = $rec['supp_reference']; // array($rec['reference'], $rec['supp_reference']);
 +              }
 +      }
 +      return $invoices;
 +}
- ?>
index fd34fef16f0d605fec0b63dd2018b66972206f0e,e841d5e8caa34208d56c97069d823a5e096939f1..45810f1da0b9050b430457a06aaf3f0d64cb0370
@@@ -98,21 -98,22 +98,21 @@@ function update_po(&$po_obj
      foreach ($po_obj->line_items as $po_line)
      {
        $sql = "INSERT INTO ".TB_PREF."purch_order_details (po_detail_item, order_no, item_code, 
-               description, delivery_date, unit_price, quantity_ordered) VALUES ("
+               description, delivery_date, unit_price, quantity_ordered, quantity_received) VALUES ("
                        .db_escape($po_line->po_detail_rec ? $po_line->po_detail_rec : 0). ","
                        .$po_obj->order_no . ","
                        .db_escape($po_line->stock_id). ","
                        .db_escape($po_line->item_description). ",'"
                        .date2sql($po_line->req_del_date) . "',"
                        .db_escape($po_line->price) . ", "
-                       .db_escape($po_line->quantity) . ")";
+                       .db_escape($po_line->quantity) . ", "
+                       .db_escape($po_line->qty_received) . ")";
 -              
                db_query($sql, "One of the purchase order detail records could not be updated");
      }
  
        // add_comments(ST_PURCHORDER, $po_obj->order_no, $po_obj->orig_order_date, $po_obj->Comments);
  
-       add_audit_trail(ST_PURCHORDER, $po_obj->order_no, $po_obj->orig_order_date, _("Updated."));
+       add_audit_trail($po_obj->trans_type, $po_obj->order_no, Today(), _("Updated."));
        hook_db_postwrite($po_obj, ST_PURCHORDER);
        commit_transaction();
  
  
  function read_po_header($order_no, &$order)
  {
 -      $sql = "SELECT ".TB_PREF."purch_orders.*, ".TB_PREF."suppliers.supp_name, ".TB_PREF."suppliers.tax_group_id,
 -              ".TB_PREF."suppliers.curr_code, ".TB_PREF."locations.location_name
 +      $sql = "SELECT ".TB_PREF."purch_orders.*, "
 +              .TB_PREF."suppliers.*, "
 +              .TB_PREF."locations.location_name 
                FROM ".TB_PREF."purch_orders, ".TB_PREF."suppliers, ".TB_PREF."locations
                WHERE ".TB_PREF."purch_orders.supplier_id = ".TB_PREF."suppliers.supplier_id
                AND ".TB_PREF."locations.loc_code = into_stock_location
  
                $order->trans_type = ST_PURCHORDER;
                $order->order_no = $order_no;
--              
++
                $order->set_supplier($myrow["supplier_id"], $myrow["supp_name"], $myrow["curr_code"],
 -                      $myrow['tax_group_id'], $myrow["tax_included"]);
 +                      $myrow['tax_group_id'], $myrow["tax_included"], @$myrow["tax_algorithm"]);
  
                $order->credit = get_current_supp_credit($order->supplier_id);
  
@@@ -269,6 -269,8 +269,8 @@@ function get_sql_for_po_search_complete
                AND porder.supplier_id = supplier.supplier_id
                AND location.loc_code = porder.into_stock_location ";
  
+       if (isset($_GET['supplier_id']))
+               $sql .= "AND supplier.supplier_id=".@$_GET['supplier_id']." ";
        if (isset($order_number) && $order_number != "")
        {
                $sql .= "AND porder.reference LIKE ".db_escape('%'. $order_number . '%');
index 0574ee51d5885a3cae327383f2aaef144036bd05,b5b93d9e7be0d2e8bbb330baae140e4fa7a3c4a3..8a7464d79fc4f1a65b0bf4826d7820ad06dccdd3
@@@ -14,7 -14,7 +14,7 @@@
  //    FIXME - this should be revised for transaction update case.
  //
  function write_supp_trans($type, $trans_no, $supplier_id, $date_, $due_date, $reference, $supp_reference,
 -      $amount, $amount_tax, $discount, $err_msg="", $rate=0, $included=0)
 +      $amount, $amount_tax, $discount, $err_msg="", $rate=0, $included=0, $tax_algorithm = null)
  {
        $new = $trans_no==0;
        $date = date2sql($date_);
  
  
        $sql = "INSERT INTO ".TB_PREF."supp_trans (trans_no, type, supplier_id, tran_date, due_date,
 -              reference, supp_reference, ov_amount, ov_gst, rate, ov_discount, tax_included) ";
 +              reference, supp_reference, ov_amount, ov_gst, rate, ov_discount, tax_included, tax_algorithm) ";
        $sql .= "VALUES (".db_escape($trans_no).", ".db_escape($type)
        .", ".db_escape($supplier_id).", '$date', '$due_date',
                ".db_escape($reference).", ".db_escape($supp_reference).", ".db_escape($amount)
 -              .", ".db_escape($amount_tax).", ".db_escape($rate).", ".db_escape($discount).", ".db_escape($included).")";
 +              .", ".db_escape($amount_tax).", ".db_escape($rate).", ".db_escape($discount).", ".db_escape($included).
 +              ", ".db_escape($tax_algorithm, true).")";
  
        if ($err_msg == "")
                $err_msg = "Cannot insert a supplier transaction record";
@@@ -154,7 -153,7 +154,7 @@@ function post_void_supp_trans($type, $t
                return true;
        }
  
-       if ($type == SUPPRECEIVE)
+       if ($type == ST_SUPPRECEIVE)
        {
                return void_grn($type_no);
        }
@@@ -180,7 -179,7 +180,7 @@@ function get_sql_for_supplier_inquiry(
        (trans.ov_amount + trans.ov_gst  + trans.ov_discount) AS TotalAmount, 
                trans.alloc AS Allocated,
                ((trans.type = ".ST_SUPPINVOICE." OR trans.type = ".ST_SUPPCREDIT.") AND trans.due_date < '" . date2sql(Today()) . "') AS OverDue,
-       (ABS(trans.ov_amount + trans.ov_gst  + trans.ov_discount - trans.alloc) <= 0.005) AS Settled
+       (ABS(trans.ov_amount + trans.ov_gst  + trans.ov_discount) - trans.alloc <= ".FLOAT_COMP_DELTA.") AS Settled
        FROM ".TB_PREF."supp_trans as trans, ".TB_PREF."suppliers as supplier
        WHERE supplier.supplier_id = trans.supplier_id
        AND trans.tran_date >= '$date_after'
index f9eed1a86c0a9caf6decb11fc4d9c8dd4f1e1429,535e66c5a0208a3b79a44cc50e0447da8e51c1c3..6091e42e9092901d9ba2b50ffd990be80c126281
@@@ -103,8 -103,8 +103,8 @@@ function get_alloc_supp_sql($extra_fiel
        $sql = "SELECT
                trans.type,
                trans.trans_no,
-               trans.reference,
-               trans.tran_date,
+               IF(trans.supp_reference='',trans.reference,trans.supp_reference) as reference,
+               trans.tran_date,
                supplier.supp_name, 
                supplier.curr_code, 
                ov_amount+ov_gst+ov_discount AS Total,
                trans.due_date,
                trans.supplier_id,
                supplier.address";
- /*    $sql = "SELECT trans.*,
-               ov_amount+ov_gst+ov_discount AS Total,
-               supplier.supp_name, supplier.address,
-               supplier.curr_code ";
- */
        if ($extra_fields)
                $sql .= ", $extra_fields ";
  
  
        if ($extra_conditions)
                $sql .= " AND $extra_conditions";
 -      
 +
        return $sql;
  }
  
@@@ -173,9 -169,32 +169,33 @@@ function get_allocatable_to_supp_transa
                        AND trans.supplier_id=".db_escape($supplier_id));
        }
  
-       return db_query($sql." ORDER BY trans_no", "Cannot retreive alloc to transactions");
+       return db_query($sql." ORDER BY due_date", "Cannot retreive alloc to transactions");
+ }
+ //-------------------------------------------------------------------------------------------------------------
+ function get_allocatable_from_supp_transactions($supplier_id, $trans_no=null, $type=null)
+ {
+       if ($trans_no != null && $type!= null)
+       {
+               $sql = get_alloc_supp_sql("amt, supp_reference", "trans.trans_no = alloc.trans_no_from
+                       AND trans.type = alloc.trans_type_from
+                       AND alloc.trans_no_to=".db_escape($trans_no)."
+                       AND alloc.trans_type_to=".db_escape($type)."
+                       AND trans.supplier_id=".db_escape($supplier_id),
+                       TB_PREF."supp_allocations as alloc");
+       }
+       else
+       {
+               $sql = get_alloc_supp_sql(null, "round(ABS(ov_amount+ov_gst+ov_discount)-alloc,6) > 0
+                       AND trans.type != ".ST_SUPPAYMENT."
+                       AND trans.supplier_id=".db_escape($supplier_id));
+       }
+       return db_query($sql." ORDER BY due_date", "Cannot retreive alloc to transactions");
  }
  
++
  function get_sql_for_supplier_allocation_inquiry()
  {
        $date_after = date2sql($_POST['TransAfterDate']);
                supplier.curr_code, 
        (trans.ov_amount + trans.ov_gst  + trans.ov_discount) AS TotalAmount, 
                trans.alloc AS Allocated,
-               ((trans.type = ".ST_SUPPINVOICE." OR trans.type = ".ST_SUPPCREDIT.") AND trans.due_date < '" . date2sql(Today()) . "') AS OverDue
+               ((trans.type = ".ST_SUPPINVOICE." OR trans.type = ".ST_SUPPCREDIT.") AND trans.due_date < '" . date2sql(Today()) . "') AS OverDue,
+               trans.supplier_id
        FROM "
                        .TB_PREF."supp_trans as trans, "
                        .TB_PREF."suppliers as supplier
index 04228e9d5a721dd5fc5a12fc22421d0662fb6cee,dd9e49c906fa3cbb4689ba5e95e2387d368555e3..61cf2bdce8a8194ab8e4bdda72024cbffa38679d
  function add_supplier($supp_name, $supp_ref, $address, $supp_address, $gst_no,
        $website, $supp_account_no, $bank_account, $credit_limit, $dimension_id, $dimension2_id, 
        $curr_code, $payment_terms, $payable_account, $purchase_account, $payment_discount_account, 
 -      $notes, $tax_group_id, $tax_included)
 +      $notes, $tax_group_id, $tax_included, $tax_algorithm)
  {
        $sql = "INSERT INTO ".TB_PREF."suppliers (supp_name, supp_ref, address, supp_address, gst_no, website,
                supp_account_no, bank_account, credit_limit, dimension_id, dimension2_id, curr_code,
                payment_terms, payable_account, purchase_account, payment_discount_account, notes, 
 -              tax_group_id, tax_included)
 -              VALUES (".db_escape($supp_name). ", "
 +              tax_group_id, tax_included, tax_algorithm)
 +              VALUES (".db_escape($_POST['supp_name']). ", "
                .db_escape($supp_ref). ", "
                .db_escape($address) . ", "
                .db_escape($supp_address) . ", "
@@@ -27,7 -27,7 +27,7 @@@
                .db_escape($website). ", "
                .db_escape($supp_account_no). ", "
                .db_escape($bank_account). ", "
 -              .db_escape($credit_limit). ", "
 +              .$credit_limit. ", "
                .db_escape($dimension_id). ", "
                .db_escape($dimension2_id). ", "
                .db_escape($curr_code). ", "
@@@ -37,8 -37,7 +37,8 @@@
                .db_escape($payment_discount_account). ", "
                .db_escape($notes). ", "
                .db_escape($tax_group_id). ", "
 -              .db_escape($tax_included). ")";
 +              .db_escape($tax_included). ", "
 +              .db_escape($tax_algorithm). ")";
  
        db_query($sql,"The supplier could not be added");
  }
@@@ -46,7 -45,7 +46,7 @@@
  function update_supplier($supplier_id, $supp_name, $supp_ref, $address, $supp_address, $gst_no, 
        $website, $supp_account_no, $bank_account, $credit_limit, $dimension_id, $dimension2_id, 
        $curr_code, $payment_terms, $payable_account, $purchase_account, $payment_discount_account, 
 -      $notes, $tax_group_id, $tax_included)
 +      $notes, $tax_group_id, $tax_included, $tax_algorithm)
  {
        $sql = "UPDATE ".TB_PREF."suppliers SET supp_name=".db_escape($supp_name) . ",
                supp_ref=".db_escape($supp_ref) . ",
@@@ -66,8 -65,7 +66,8 @@@
                payment_discount_account=".db_escape($payment_discount_account) . ",
                notes=".db_escape($notes) . ",
                tax_group_id=".db_escape($tax_group_id). ",
 -              tax_included=".db_escape($tax_included)
 +              tax_included=".db_escape($tax_included).",
 +              tax_algorithm=".db_escape($tax_algorithm)
                ." WHERE supplier_id = ".db_escape($supplier_id);
  
        db_query($sql,"The supplier could not be updated");
@@@ -79,7 -77,7 +79,7 @@@ function delete_supplier($supplier_id
        db_query($sql,"check failed");
  }
  
- function get_supplier_details($supplier_id, $to=null)
+ function get_supplier_details($supplier_id, $to=null, $all=true)
  {
  
        if ($to == null)
        $past2 = 2 * $past1;
        // removed - supp_trans.alloc from all summations
  
-     $value = "(trans.ov_amount + trans.ov_gst + trans.ov_discount)";
+       if ($all)
+       $value = "(trans.ov_amount + trans.ov_gst + trans.ov_discount)";
+     else      
+       $value = "IF (trans.type=".ST_SUPPINVOICE." OR trans.type=".ST_BANKDEPOSIT.",
+               (trans.ov_amount + trans.ov_gst + trans.ov_discount - trans.alloc),
+               (trans.ov_amount + trans.ov_gst + trans.ov_discount + trans.alloc))";
        $due = "IF (trans.type=".ST_SUPPINVOICE." OR trans.type=".ST_SUPPCREDIT.",trans.due_date,trans.tran_date)";
      $sql = "SELECT supp.supp_name, supp.curr_code, ".TB_PREF."payment_terms.terms,
  
  
                WHERE
                         supp.payment_terms = ".TB_PREF."payment_terms.terms_indicator
-                        AND supp.supplier_id = $supplier_id
-               GROUP BY
+                        AND supp.supplier_id = $supplier_id ";
+       if (!$all)
+               $sql .= "AND ABS(trans.ov_amount + trans.ov_gst + trans.ov_discount) - trans.alloc > ".FLOAT_COMP_DELTA." ";  
+       $sql .= "GROUP BY
                          supp.supp_name,
                          ".TB_PREF."payment_terms.terms,
                          ".TB_PREF."payment_terms.days_before_due,
                          ".TB_PREF."payment_terms.day_in_following_month";
--
-     $result = db_query($sql,"The supplier details could not be retrieved");
+     $result = db_query($sql,"The customer details could not be retrieved");
      $supp = db_fetch($result);
  
      return $supp;
@@@ -175,12 -179,4 +180,10 @@@ function is_new_supplier($id
  
        return !key_in_foreign_table($id, $tables, 'supplier_id');
  }
 -?>
 +
 +function update_supp_tax_algorithm($supplier_id, $tax_algorithm)
 +{
 +      $sql = "UPDATE ".TB_PREF."suppliers SET tax_algorithm=".db_escape($tax_algorithm)
 +              . " WHERE supplier_id=".db_escape($supplier_id);
 +      return db_query($sql, "cannot update supplier's tax calculation algorithm");
 +}
- ?>
index 840569271349a309d4a6184fcedf351417bd8a98,b767e9ea9261f66e9ee64245c4f9067bae4bd475..c9ec00df2f32362d5ca993b480c1e699026266f4
@@@ -32,8 -32,6 +32,8 @@@ class purch_orde
        var $tax_group_id;
        var $tax_group_array = null; // saves db queries
        var $tax_included; // type of prices
 +      var $tax_algorithm;
 +      var $stored_algorithm; // copy to find the change after invoice in processed
        var $terms;
        
        var $reference;
                $this->lines_on_order = $this->order_no = $this->supplier_id = 0;
        }
        
 -      function set_supplier($supplier_id, $supplier_name, $curr_code, $tax_group_id, $tax_included)
 +      function set_supplier($supplier_id, $supplier_name, $curr_code, $tax_group_id, $tax_included, $tax_algorithm)
        {
                $this->supplier_id = $supplier_id;
                $this->supplier_name = $supplier_name;
                $this->curr_code = $curr_code;
                $this->tax_group_id = $tax_group_id;
                $this->tax_included = $tax_included;
 +              $this->stored_algorithm = $this->tax_algorithm = $tax_algorithm;
                $this->tax_group_array = get_tax_group_items_as_array($tax_group_id);
        }
        
                        $prices[] = round($ln_itm->price * ($receival ? $ln_itm->receive_qty : $ln_itm->quantity),  user_price_dec());
                }
                $taxes = get_tax_for_items($items, $prices, $shipping_cost,
 -                $this->tax_group_id, $this->tax_included,  $this->tax_group_array);
 +                $this->tax_group_id, $this->tax_included,  $this->tax_group_array, $this->tax_algorithm);
        // Adjustment for swiss franken, we always have 5 rappen = 1/20 franken
            if ($this->curr_code == 'CHF') {
                        $val = $taxes['1']['Value'];
 -                      $val1 = (floatval((intval(round(($val*20),0)))/20));
 -                      $taxes['1']['Value'] = $val1;
 +                      $taxes['1']['Value'] = (floatval((intval(round(($val*20),0)))/20));
                } 
                return $taxes;
        }
  
                if (!$this->tax_included ) {
                        $taxes = get_tax_for_items($items, $prices, 0, $this->tax_group_id,
 -                      $this->tax_included,  $this->tax_group_array);
 +                      $this->tax_included,  $this->tax_group_array, $this->tax_algorithm);
  
                        foreach($taxes as $tax)
                                $total += round($tax['Value'], $dec);
index 60e5b7edadb00c95c402d96594d0c82f2e1af7fc,130354d7142516a28303246d7f4e9cf7fd2da9da..8178d30d1094affee1bf159c88b1058ebdbe7f8f
@@@ -28,12 -28,10 +28,12 @@@ class supp_tran
        var $tax_included;
        
        var $trans_type;        // invoice or credit
 +      var $trans_no;
  
        var $Comments;
        var $tran_date;
        var $due_date;
 +      var $src_docs = array();                // source invoice for this credit note (if any)
  
        var $supp_reference;
        var $reference;
        var $ov_gst;
        var $gl_codes_counter=0;
        var $credit = 0;
 +      var $tax_algorithm;
 +      var $stored_algorithm;
 +      var $currency;
  
 -      function supp_trans($trans_type)
 +      function supp_trans($trans_type, $trans_no=0)
        {
+               $this->trans_type = $trans_type;
                /*Constructor function initialises a new Supplier Transaction object */
 -              $this->grn_items = array();
 -              $this->gl_codes = array();
 +              $this->read($trans_type, $trans_no);
 +      }
 +
 +      function read($trans_type, $trans_no)
 +      {
 +              $this->trans_type = $trans_type;
 +              $this->trans_no = $trans_no;
 +              $this->grn_items = array();
 +              $this->gl_codes = array();
 +              if ($trans_no) {
 +                      read_supp_invoice($trans_no, $trans_type, $this);
 +                      if ($trans_type == ST_SUPPCREDIT)
 +                      {
 +                              $this->src_docs = find_src_invoices($trans_no);
 +                      }
 +                      read_supplier_details_to_trans($this, $this->supplier_id);
 +              }
        }
  
        function add_grn_to_trans($grn_item_id, $po_detail_item, $item_code, $item_description, 
@@@ -75,7 -56,6 +76,7 @@@
                $this->grn_items[$grn_item_id] = new grn_item($grn_item_id, $po_detail_item, 
                        $item_code, $item_description, $qty_recd, $prev_quantity_inv, $this_quantity_inv, 
                        $order_price, $chg_price, $std_cost_unit, $gl_code, $this->tax_included);
 +              $this->src_docs = find_src_invoices($this);
                return 1;
        }
  
          if ($tax_group_id == null)
                $tax_group_id = $this->tax_group_id;
          $taxes = get_tax_for_items($items, $prices, $shipping_cost, $tax_group_id, 
 -              $this->tax_included);
 +              $this->tax_included, null, $this->tax_algorithm);
  
  ///////////////// Joe Hunt 2009.08.18
  
                }       
                return $total;
      }
 -
 +      //
 +      //      Returns transaction total 
 +      //
        function get_items_total()
        {
                $total = 0;
index 5d28ec6015e3fe086d3bd388715caf4018cc6668,67a02e668b110fb7a1db73a2019e86d8fed820db..298fcb828f33d9fb665673fad6b7d7f481b0af4f
@@@ -19,7 -19,6 +19,7 @@@ function copy_from_trans(&$supp_trans
        $_POST['supp_reference'] = $supp_trans->supp_reference;
        $_POST['reference'] = $supp_trans->reference;
        $_POST['supplier_id'] = $supp_trans->supplier_id;
 +      $_POST['tax_algorithm'] = $supp_trans->tax_algorithm;
  }
  
  //--------------------------------------------------------------------------------------------------
@@@ -31,8 -30,6 +31,8 @@@ function copy_to_trans(&$supp_trans
        $supp_trans->due_date = $_POST['due_date'];
        $supp_trans->supp_reference = $_POST['supp_reference'];
        $supp_trans->reference = $_POST['reference'];
 +      if (isset($_POST['tax_algorithm']))
 +          $supp_trans->tax_algorithm = $_POST['tax_algorithm'];
  
        $supp_trans->ov_amount = 0; /* for starters */
        if (count($supp_trans->grn_items) > 0)
@@@ -68,28 -65,19 +68,28 @@@ function invoice_header(&$supp_trans
  
        table_section(1);
  
 -      if (isset($_POST['invoice_no']))
 +      if ($supp_trans->trans_type == ST_SUPPCREDIT && $supp_trans->src_docs)
        {
 -              $trans = get_supp_trans($_POST['invoice_no'], ST_SUPPINVOICE);
 -              $_POST['supplier_id'] = $trans['supplier_id'];
 -              $supp = $trans['supplier_name'] . " - " . $trans['SupplierCurrCode'];
 +//            $trans = get_supp_trans($_POST['invoice_no'], ST_SUPPINVOICE);
 +//            $trans = get_supp_trans($supp_trans->supplier_id, ST_SUPPINVOICE);
 +//            $_POST['supplier_id'] = $trans['supplier_id'];
 +//            $supp = $trans['supplier_name'] . " - " . $trans['SupplierCurrCode'];
 +
 +              $_POST['supplier_id'] = $supp_trans->supplier_id;
 +              $supp = $supp_trans->supplier_name." - ".$supp_trans->currency;
                label_row(_("Supplier:"), $supp.hidden('supplier_id', $_POST['supplier_id'], false));
 -      }       
 +      }
        else
        {
        if (!isset($_POST['supplier_id']) && (get_global_supplier() != ALL_TEXT))
                $_POST['supplier_id'] = get_global_supplier();
  
 -              supplier_list_row(_("Supplier:"), 'supplier_id', $_POST['supplier_id'], false, true);
 +              if (!$supp_trans->trans_no)
 +                      supplier_list_row(_("Supplier:"), 'supplier_id', $_POST['supplier_id'], false, true);
 +              else
 +                      label_row(_("Supplier:"), $supp_trans->supplier_name
 +                      .($supp_trans->currency ? ' - '.$supp_trans->currency  : '')
 +                      .hidden('supplier_id', $_POST['supplier_id'], false));
        }
        if ($supp_trans->supplier_id != $_POST['supplier_id'])
        {
  
        ref_row(_("Reference:"), 'reference', '', $Refs->get_next($supp_trans->trans_type));
  
 -      if (isset($_POST['invoice_no']))
 +      if ($supp_trans->trans_type == ST_SUPPCREDIT)
        {
 -              label_row(_("Supplier's Ref.:"), $_POST['invoice_no'].hidden('invoice_no', $_POST['invoice_no'], false).hidden('supp_reference', $_POST['invoice_no'], false));
 -      }       
 -      else
 -              text_row(_("Supplier's Ref.:"), 'supp_reference', $_POST['supp_reference'], 20, 60);
 +              label_row(_("Source Invoices:"), implode(',' , $supp_trans->src_docs),'','','src_docs');
 +      }
 +              text_row(_("Supplier's Ref.:"), 'supp_reference', $_POST['supp_reference'], 20, 60);
  
        table_section(2, "33%");
  
  
  function invoice_totals(&$supp_trans)
  {
 +      global $Ajax;
 +
        copy_to_trans($supp_trans);
  
        $dim = get_company_pref('use_dimension');
        $colspan = ($dim == 2 ? 7 : ($dim == 1 ? 6 : 5));
 +      div_start('tax_table');
        start_table(TABLESTYLE, "width=95%");
        label_row(_("Sub-total:"), price_format( $supp_trans->ov_amount), "colspan=$colspan align=right", "align=right");
  
  
      end_table(1);
      start_table(TABLESTYLE2);
 +    tax_algorithm_list_row(_("Tax algorithm:"), 'tax_algorithm', null, true);
 +      if (list_updated('tax_algorithm')) {
 +              $supp_trans->tax_algorithm = $_POST['tax_algorithm'];
 +          $Ajax->activate('tax_table');
 +      }
      textarea_row(_("Memo:"), "Comments", null, 50, 3);
      end_table(1);
 +      div_end();
  }
  
  //--------------------------------------------------------------------------------------------------
@@@ -339,14 -319,15 +339,14 @@@ function display_gl_items(&$supp_trans
  
  function display_grn_items_for_selection(&$supp_trans, $k)
  {
 -
 -      if ($supp_trans->trans_type == ST_SUPPINVOICE)
 -              $result = get_grn_items(0, $supp_trans->supplier_id, true);
 +      if ($supp_trans->trans_type == ST_SUPPINVOICE)  // outstanding grns and eventually for selected invoice
 +              $result = get_grn_items(0, $supp_trans->supplier_id, true, false, $supp_trans->trans_no);
        else
 -      {
 +      { // only invoiced
                if (isset($_POST['receive_begin']) && isset($_POST['receive_end']))
                        $result = get_grn_items(0, $supp_trans->supplier_id, false, true, 0, $_POST['receive_begin'], $_POST['receive_end']);
 -              else if (isset($_POST['invoice_no']))
 -                      $result = get_grn_items(0, $supp_trans->supplier_id, false, true, $_POST['invoice_no']);
 +              else if ($supp_trans->src_docs)
 +                      $result = get_grn_items(0, $supp_trans->supplier_id, false, true, array_keys($supp_trans->src_docs));
                else    
                        $result = get_grn_items(0, $supp_trans->supplier_id, false, true);
        }
                        $grn_already_on_invoice = true;
                }
        }
 +
        if ($grn_already_on_invoice == false)
        {
  
                        alt_table_row_color($k);
  
                        $n = $myrow["id"];
 -              label_cell(get_trans_view_str(25, $myrow["grn_batch_id"]).
 -              hidden('qty_recd'.$n, $myrow["qty_recd"], false).
 -              hidden('item_code'.$n, $myrow["item_code"], false).
 -              hidden('item_description'.$n, $myrow["description"], false).
 -              hidden('prev_quantity_inv'.$n, $myrow['quantity_inv'], false).
 -              hidden('order_price'.$n, $myrow['unit_price'], false).
 -              hidden('std_cost_unit'.$n, $myrow['std_cost_unit'], false).
 -              hidden('po_detail_item'.$n, $myrow['po_detail_item'], false).
 -              hidden('location'.$n, $myrow["loc_code"], false));
 +              label_cell(get_trans_view_str(ST_SUPPRECEIVE, $myrow["grn_batch_id"]));
 +              label_cell($myrow["id"].
 +              hidden('qty_recd'.$n, $myrow["qty_recd"], false).
 +              hidden('item_code'.$n, $myrow["item_code"], false).
 +              hidden('item_description'.$n, $myrow["description"], false).
 +              hidden('prev_quantity_inv'.$n, $myrow['quantity_inv'], false).
 +              hidden('order_price'.$n, $myrow['unit_price'], false).
 +              hidden('std_cost_unit'.$n, $myrow['std_cost_unit'], false).
 +              hidden('po_detail_item'.$n, $myrow['po_detail_item'], false));
                label_cell(get_trans_view_str(ST_PURCHORDER, $myrow["purch_order_no"]));
              label_cell($myrow["item_code"]);
              label_cell($myrow["description"]);
              if ($supp_trans->trans_type == ST_SUPPINVOICE)
                qty_cells(null, 'this_quantity_inv'.$n, number_format2($myrow["qty_recd"] - $myrow["quantity_inv"], $dec), 
                        null, null, $dec);
 -            else              
 +            else
                qty_cells(null, 'This_QuantityCredited'.$n, number_format2(max($myrow["quantity_inv"], 0), $dec), 
                        null, null, $dec);
 -            $dec2 = 0;                
 +            $dec2 = 0;
              if ($supp_trans->trans_type == ST_SUPPINVOICE)
              {
                amount_cells(null, 'ChgPrice'.$n, price_decimal_format($myrow["unit_price"], $dec2), null, null, $dec2);
                if (($supp_trans->trans_type == ST_SUPPINVOICE) && $_SESSION["wa_current_user"]->can_access('SA_GRNDELETE')) {  // Added 2008-10-18 by Joe Hunt. Special access rights needed.
                        submit_cells('void_item_id'.$n, _("Remove"), '', _("WARNING! Be careful with removal. The operation is executed immediately and cannot be undone !!!"), true);
                                submit_js_confirm('void_item_id'.$n,
 -                                      _('You are about to remove all yet non-invoiced items from selected delivery line. This operation also irreversibly changes related order line. Do you want to continue ?'));
 +                                      sprintf(_('You are about to remove all yet non-invoiced items from delivery line #%d. This operation also irreversibly changes related order line. Do you want to continue ?'), $n));
                        }
                        end_row();
        }
@@@ -459,28 -439,28 +459,28 @@@ function display_grn_items(&$supp_trans
                        $heading = _("Received Items Charged on this Invoice");
                else
                        $heading = _("Received Items Credited on this Note");
 -      }               
 +      }
  
        display_heading($heading);
  
        if ($mode == 1)
        {
 -              if ($supp_trans->trans_type == ST_SUPPCREDIT && !isset($_POST['invoice_no']))
 +              if ($supp_trans->trans_type == ST_SUPPCREDIT)
                {
                        echo "</td>";
                        date_cells(_("Received between"), 'receive_begin', "", null, -30, 0, 0, "valign=middle");
                        date_cells(_("and"), 'receive_end', '', null, 1, 0, 0, "valign=middle");
                        submit_cells('RefreshInquiry', _("Search"),'',_('Refresh Inquiry'), true);
                        echo "<td>";
 -              }       
 -                      
 +              }
 +
                if ($heading2 != "")
                {
                        display_note($heading2, 0, 0, "class='overduefg'");
 -              }       
 +              }
                echo "</td><td width=10% align='right'>";
                submit('InvGRNAll', _("Add All Items"), true, false,true);
 -      }       
 +      }
  
        end_outer_table(0, false);
  
        start_table(TABLESTYLE, "width=95%");
        if ($mode == 1)
        {
 -      $th = array(_("Delivery"), _("P.O."), _("Item"), _("Description"),
 +      $th = array(_("Delivery"), _("Sequence #"), _("P.O."), _("Item"), _("Description"),
                _("Received On"), _("Quantity Received"), _("Quantity Invoiced"),
                _("Qty Yet To Invoice"), $supp_trans->tax_included ? _("Price after Tax") : _("Price before Tax"), 
                _("Total"), "");
                alt_table_row_color($k);
  
                        $grn_batch = get_grn_batch_from_item($entered_grn->id);
 -              label_cell(get_trans_view_str(ST_SUPPRECEIVE,$grn_batch));
 +              label_cell(get_trans_view_str(ST_SUPPRECEIVE, $grn_batch));
                if ($mode == 1)
                {
 -                              $row = get_grn_batch($grn_batch);
 -                              label_cell($row['purch_order_no']); // PO
 -                      }
 +                              label_cell($entered_grn->id);
 +                              $row = get_grn_batch($grn_batch);
 +                              label_cell(get_trans_view_str(ST_PURCHORDER, $row["purch_order_no"])); // PO
 +                      }       
                        label_cell($entered_grn->item_code);
                        label_cell($entered_grn->item_description);
              $dec = get_qty_dec($entered_grn->item_code);
              if ($mode == 1)
              {
-               label_cell("");
-                               qty_cell($entered_grn->qty_recd, false, $dec);
+                       label_cell(sql2date($row['delivery_date']));
+                               qty_cell($entered_grn->qty_recd, false, $dec);
                                qty_cell($entered_grn->prev_quantity_inv, false, $dec);
              }
                        qty_cell(abs($entered_grn->this_quantity_inv), true, $dec);
index 33e7df4c985fc4d1852b33ebbff278cf9651b7f3,ec5ad432683a4dfbb8503c4511739eedfdb1abdb..617e78e48eabf38fe27cada73ed04d256f33d7a7
@@@ -19,14 -19,13 +19,14 @@@ function copy_from_cart(
  
        $_POST['supplier_id'] = $cart->supplier_id;
        $_POST['OrderDate'] = $cart->orig_order_date;
 -      if ($cart->trans_type==ST_SUPPINVOICE)
 +      if ($cart->trans_type == ST_SUPPINVOICE)
                $_POST['due_date'] = $cart->due_date;
      $_POST['supp_ref'] = $cart->supp_ref;
      $_POST['ref'] = $cart->reference;
        $_POST['Comments'] = $cart->Comments;
      $_POST['StkLocation'] = $cart->Location;
      $_POST['delivery_address'] = $cart->delivery_address;
 +    $_POST['tax_algorithm'] = $cart->tax_algorithm;
  }
  
  function copy_to_cart()
  
        $cart->supplier_id = $_POST['supplier_id'];     
        $cart->orig_order_date = $_POST['OrderDate'];
 -      if ($cart->trans_type==ST_SUPPINVOICE)
 +      if ($cart->trans_type == ST_SUPPINVOICE)
                $cart->due_date = $_POST['due_date'];
        $cart->reference = $_POST['ref'];
        $cart->supp_ref = $_POST['supp_ref'];
        $cart->Comments = $_POST['Comments'];   
        $cart->Location = $_POST['StkLocation'];
        $cart->delivery_address = $_POST['delivery_address'];
 +      if (isset($_POST['tax_algorithm']))
 +          $cart->tax_algorithm = $_POST['tax_algorithm'];
  }
  // ------------------------------------------------------------------------------
  
  function get_supplier_details_to_order(&$order, $supplier_id)
  {
 -      $sql = "SELECT curr_code, supp_name, tax_group_id, supp.tax_included,
 +      $sql = "SELECT curr_code, supp_name, tax_group_id, supp.tax_included, supp.tax_algorithm,
                        supp.credit_limit - Sum(IFNULL(IF(trans.type=".ST_SUPPCREDIT.", -1, 1) 
                                * (ov_amount + ov_gst + ov_discount),0)) as cur_credit,
                                terms.terms, terms.days_before_due, terms.day_in_following_month
@@@ -74,7 -71,7 +74,7 @@@
        $_POST['curr_code'] = $myrow["curr_code"];
  
        $order->set_supplier($supplier_id, $myrow["supp_name"], $myrow["curr_code"], 
 -              $myrow["tax_group_id"], $myrow["tax_included"]);
 +              $myrow["tax_group_id"], $myrow["tax_included"], $myrow["tax_algorithm"]);
  }
  
  //---------------------------------------------------------------------------------------------------
@@@ -133,7 -130,6 +133,7 @@@ function display_po_header(&$order
                get_supplier_details_to_order($order, $_POST['supplier_id']); 
            get_duedate_from_terms($order);
                $_POST['due_date'] = $order->due_date;
 +              $_POST['tax_algorithm'] = $order->tax_algorithm;
  
                // supplier default price update
                foreach ($order->line_items as $line_no=>$item) {
                }
            $Ajax->activate('items_table');
            $Ajax->activate('due_date');
 +          $Ajax->activate('tax_algorithm');
        }
        set_global_supplier($_POST['supplier_id']);
  
@@@ -402,7 -397,9 +402,9 @@@ function po_item_controls(&$order, &$ro
        {
  //            hidden('line_no', ($_SESSION['PO']->lines_on_order + 1));
  
-               stock_purchasable_items_list_cells(null, 'stock_id', null, false, true, true);
+               //Chaitanya : Manufcatured item can be purchased
+               stock_items_list_cells(null, 'stock_id', null, false, true, true);
+               //stock_purchasable_items_list_cells(null, 'stock_id', null, false, true, true);
                if (list_updated('stock_id')) {
                            $Ajax->activate('price');
                            $Ajax->activate('units');
        label_cell($_POST['units'], '', 'units');
        if ($order->trans_type == ST_PURCHORDER)
                date_cells(null, 'req_del_date', '', null, 0, 0, 0);
-       amount_cells(null, 'price', null, null, null, $dec2);
+       if ($qty_rcvd > 0)
+       {
+               amount_decimal_cell($_POST['price']);
+               hidden('price', $_POST['price']);
+       }       
+       else    
+               amount_cells(null, 'price', null, null, null, $dec2);
  
        //$line_total = $_POST['qty'] * $_POST['price'] * (1 - $_POST['Disc'] / 100);
        $line_total = round(input_num('qty') * input_num('price'),  user_price_dec());
index ba77bf7a91222026e43ef12ea5b15f57192fb59e,9925ac6399a393387a286074b120a8e11c0e1492..90d869aa907acbe5cf0452e0e4047e293b59913b
  ***********************************************************************/
  $page_security = 'SA_SUPPTRANSVIEW';
  $path_to_root="../..";
- include($path_to_root . "/includes/db_pager.inc");
- include($path_to_root . "/includes/session.inc");
+ include_once($path_to_root . "/includes/db_pager.inc");
+ include_once($path_to_root . "/includes/session.inc");
  
- include($path_to_root . "/purchasing/includes/purchasing_ui.inc");
+ include_once($path_to_root . "/purchasing/includes/purchasing_ui.inc");
  include_once($path_to_root . "/reporting/includes/reporting.inc");
 -if (!@$_GET['popup'])
 -{
 -      $js = "";
 -      if ($use_popup_windows)
 -              $js .= get_js_open_window(900, 500);
 -      if ($use_date_picker)
 -              $js .= get_js_date_picker();
 -      page(_($help_context = "Search Purchase Orders"), false, false, "", $js);
 -}
 +$js = "";
 +if ($use_popup_windows)
 +      $js .= get_js_open_window(900, 500);
 +if ($use_date_picker)
 +      $js .= get_js_date_picker();
 +page(_($help_context = "Search Purchase Orders"), false, false, "", $js);
 +
  if (isset($_GET['order_number']))
  {
        $order_number = $_GET['order_number'];
@@@ -53,7 -55,8 +53,7 @@@ if (get_post('SearchOrders')
  }
  //---------------------------------------------------------------------------------------------
  
 -if (!@$_GET['popup'])
 -      start_form();
 +start_form();
  
  start_table(TABLESTYLE_NOBORDER);
  start_row();
@@@ -98,9 -101,11 +98,13 @@@ function trans_view($trans
  
  function edit_link($row) 
  {
-   return pager_link( _("Edit"),
-       "/purchasing/po_entry_items.php?" . SID 
-       . "ModifyOrderNumber=" . $row["order_no"], ICON_EDIT);
 -      if (@$_GET['popup'])
++      global $page_nested;
++
++      if ($page_nested)
+               return '';
+       return pager_link( _("Edit"),
+               "/purchasing/po_entry_items.php?" . SID 
+               . "ModifyOrderNumber=" . $row["order_no"], ICON_EDIT);
  }
  
  function prt_link($row)
@@@ -136,6 -141,9 +140,6 @@@ $table->width = "80%"
  
  display_db_pager($table);
  
 -if (!@$_GET['popup'])
 -{
 -      end_form();
 -      end_page();
 -}     
 +end_form();
 +end_page();
  ?>
index 3a341abeef10f1e29e70a25420644afee84975d1,ffb264b523420876cef4ae6fe3ca936e884faa09..af6c2216623c06cd168d7d8cd735143f5dfdfaca
  ***********************************************************************/
  $page_security = 'SA_SUPPTRANSVIEW';
  $path_to_root = "../..";
- include($path_to_root . "/includes/db_pager.inc");
- include($path_to_root . "/includes/session.inc");
+ include_once($path_to_root . "/includes/db_pager.inc");
+ include_once($path_to_root . "/includes/session.inc");
  
- include($path_to_root . "/purchasing/includes/purchasing_ui.inc");
- include($path_to_root . "/reporting/includes/reporting.inc");
+ include_once($path_to_root . "/purchasing/includes/purchasing_ui.inc");
+ include_once($path_to_root . "/reporting/includes/reporting.inc");
  
 -if (!@$_GET['popup'])
 -{
 -      $js = "";
 -      if ($use_popup_windows)
 -              $js .= get_js_open_window(900, 500);
 -      if ($use_date_picker)
 -              $js .= get_js_date_picker();
 -      page(_($help_context = "Supplier Inquiry"), isset($_GET['supplier_id']), false, "", $js);
 -}
 +$js = "";
 +if ($use_popup_windows)
 +      $js .= get_js_open_window(900, 500);
 +if ($use_date_picker)
 +      $js .= get_js_date_picker();
 +page(_($help_context = "Supplier Inquiry"), isset($_GET['supplier_id']), false, "", $js);
 +
  if (isset($_GET['supplier_id'])){
        $_POST['supplier_id'] = $_GET['supplier_id'];
  }
@@@ -36,7 -38,8 +36,7 @@@ if (isset($_GET['ToDate']))
  
  //------------------------------------------------------------------------------------------------
  
 -if (!@$_GET['popup'])
 -      start_form();
 +start_form();
  
  if (!isset($_POST['supplier_id']))
        $_POST['supplier_id'] = get_global_supplier();
@@@ -44,7 -47,8 +44,8 @@@
  start_table(TABLESTYLE_NOBORDER);
  start_row();
  
- supplier_list_cells(_("Select a supplier:"), 'supplier_id', null, true);
 -if (!@$_GET['popup'])
 -      supplier_list_cells(_("Select a supplier:"), 'supplier_id', null, true, false, false, !@$_GET['popup']);
++if (!$page_nested)
++      supplier_list_cells(_("Select a supplier:"), 'supplier_id', null, true, false, false, true);
  
  date_cells(_("From:"), 'TransAfterDate', '', null, -30);
  date_cells(_("To:"), 'TransToDate');
@@@ -89,7 -93,7 +90,7 @@@ function display_supplier_summary($supp
  div_start('totals_tbl');
  if (($_POST['supplier_id'] != "") && ($_POST['supplier_id'] != ALL_TEXT))
  {
-       $supplier_record = get_supplier_details($_POST['supplier_id']);
+       $supplier_record = get_supplier_details($_POST['supplier_id'], $_POST['TransToDate']);
      display_supplier_summary($supplier_record);
  }
  div_end();
@@@ -105,6 -109,6 +106,7 @@@ function systype_name($dummy, $type
        global $systypes_array;
        return $systypes_array[$type];
  }
++div_end();
  
  function trans_view($trans)
  {
@@@ -123,6 -127,8 +125,10 @@@ function gl_view($row
  
  function credit_link($row)
  {
 -      if (@$_GET['popup'])
++      global $page_nested;
++
++      if ($page_nested)
+               return '';
        return $row['type'] == ST_SUPPINVOICE && $row["TotalAmount"] - $row["Allocated"] > 0 ?
                pager_link(_("Credit This"),
                        "/purchasing/supplier_credit.php?New=1&invoice_no=".
@@@ -145,20 -151,15 +151,20 @@@ function fmt_credit($row
  
  function prt_link($row)
  {
-       if ($row['type'] == ST_SUPPAYMENT || $row['type'] == ST_BANKPAYMENT) 
+       if ($row['type'] == ST_SUPPAYMENT || $row['type'] == ST_BANKPAYMENT || $row['type'] == ST_SUPPCREDIT
                return print_document_link($row['trans_no']."-".$row['type'], _("Print Remittance"), true, ST_SUPPAYMENT, ICON_PRINT);
  }
  
- function edit_link($row)
- {
-       return edit_trans_link($row['type'], $row['trans_no']);
- }
  function check_overdue($row)
  {
        return $row['OverDue'] == 1
                && (abs($row["TotalAmount"]) - $row["Allocated"] != 0);
  }
++
++function edit_link($row)
++{
++      return edit_trans_link($row['type'], $row['trans_no']);
++}
  //------------------------------------------------------------------------------------------------
  
  $sql = get_sql_for_supplier_inquiry();
@@@ -176,8 -177,7 +182,8 @@@ $cols = array
                        _("Credit") => array('align'=>'right', 'insert'=>true,'fun'=>'fmt_credit'), 
                        array('insert'=>true, 'fun'=>'gl_view'),
                        array('insert'=>true, 'fun'=>'credit_link'),
 -                      array('insert'=>true, 'fun'=>'prt_link')
 +                      array('insert'=>true, 'fun'=>'prt_link'),
 +                      array('insert'=>true, 'fun'=>'edit_link')
                        );
  
  if ($_POST['supplier_id'] != ALL_TEXT)
        $cols[_("Supplier")] = 'skip';
        $cols[_("Currency")] = 'skip';
  }
--//------------------------------------------------------------------------------------------------
--
  
  /*show a table of the transactions returned by the sql */
  $table =& new_db_pager('trans_tbl', $sql, $cols);
@@@ -196,7 -196,9 +200,7 @@@ $table->width = "85%"
  
  display_db_pager($table);
  
 -if (!@$_GET['popup'])
 -{
 -      end_form();
 -      end_page(@$_GET['popup'], false, false);
 -}
 +end_form();
 +end_page();
 +
  ?>
index ca34975ea5a96765756e3fc7d5b23441a8c1e690,edfad13a6d9d3021e8f5d3c29a33b5b30a9e87f7..287849ff9d765c980a9fb1d73fa9da04aa6cff6c
  ***********************************************************************/
  $page_security = 'SA_SUPPLIER';
  $path_to_root = "../..";
- include($path_to_root . "/includes/session.inc");
+ include($path_to_root . "/includes/db_pager.inc");
+ include_once($path_to_root . "/includes/session.inc");
+ $js = "";
+ if ($use_popup_windows)
+       $js .= get_js_open_window(900, 500);
+ if ($use_date_picker)
+       $js .= get_js_date_picker();
  
- page(_($help_context = "Suppliers"), @$_REQUEST['popup']);
+ page(_($help_context = "Suppliers"), @$_REQUEST['popup'], false, "", $js);
  
  include_once($path_to_root . "/includes/ui.inc");
  include_once($path_to_root . "/includes/ui/contacts_view.inc");
@@@ -29,7 -35,7 +35,7 @@@ $supplier_id = get_post('supplier_id')
  //--------------------------------------------------------------------------------------------
  function supplier_settings(&$supplier_id)
  {
-       
        start_outer_table(TABLESTYLE2);
  
        table_section(1);
@@@ -55,7 -61,6 +61,7 @@@
                $_POST['credit_limit']  = price_format($myrow["credit_limit"]);
                $_POST['tax_group_id'] = $myrow["tax_group_id"];
                $_POST['tax_included'] = $myrow["tax_included"];
 +              $_POST['tax_algorithm'] = $myrow["tax_algorithm"];
                $_POST['payable_account']  = $myrow["payable_account"];
                $_POST['purchase_account']  = $myrow["purchase_account"];
                $_POST['payment_discount_account'] = $myrow["payment_discount_account"];
@@@ -69,7 -74,6 +75,7 @@@
                $_POST['dimension_id'] = 0;
                $_POST['dimension2_id'] = 0;
                $_POST['tax_included'] = 0;
 +              $_POST['tax_algorithm'] = 1;
                $_POST['sales_type'] = -1;
                $_POST['gst_no'] = $_POST['bank_account'] = '';
                $_POST['payment_terms']  = '';
        tax_groups_list_row(_("Tax Group:"), 'tax_group_id', null);
        text_row(_("Our Customer No:"), 'supp_account_no', null, 42, 40);
  
-       if (!$supplier_id) {
-               table_section_title(_("Contact Data"));
-               text_row(_("Contact Person:"), 'contact', null, 42, 40);
-               text_row(_("Phone Number:"), 'phone', null, 32, 30);
-               text_row(_("Secondary Phone Number:"), 'phone2', null, 32, 30);
-               text_row(_("Fax Number:"), 'fax', null, 32, 30);
-               email_row(_("E-mail:"), 'email', null, 35, 55);
-               languages_list_row(_("Document Language:"), 'rep_lang', null, _('System default'));
-       }
        table_section_title(_("Purchasing"));
        text_row(_("Bank Name/Account:"), 'bank_account', null, 42, 40);
        amount_row(_("Credit Limit:"), 'credit_limit', null);
        payment_terms_list_row(_("Payment Terms:"), 'payment_terms', null);
        //
        // tax_included option from supplier record is used directly in update_average_cost() function,
 -      // therefore we can't edit the option after any transaction waas done for the supplier.
 +      // therefore we can't edit the option after any transaction was done for the supplier.
        //
        if (is_new_supplier($supplier_id))
                check_row(_("Prices contain tax included:"), 'tax_included');
                hidden('tax_included');
                label_row(_("Prices contain tax included:"), $_POST['tax_included'] ? _('Yes') : _('No'));
        }
 +      tax_algorithm_list_row(_("Tax Calculation Algorithm:"), 'tax_algorithm', null);
 +
 +      if (!$supplier_id) table_section(2);
 +
        table_section_title(_("Accounts"));
        gl_all_accounts_list_row(_("Accounts Payable Account:"), 'payable_account', $_POST['payable_account']);
        gl_all_accounts_list_row(_("Purchase Account:"), 'purchase_account', $_POST['purchase_account'],
                false, false, _("Use Item Inventory/COGS Account"));
        gl_all_accounts_list_row(_("Purchase Discount Account:"), 'payment_discount_account', $_POST['payment_discount_account']);
-       if ($supplier_id) table_section(2);
+       if (!$supplier_id) {
+               table_section_title(_("Contact Data"));
+               text_row(_("Phone Number:"), 'phone', null, 32, 30);
+               text_row(_("Secondary Phone Number:"), 'phone2', null, 32, 30);
++              table_section_title(_("Contact Data"));
++              text_row(_("Fax Number:"), 'fax', null, 32, 30);
++              email_row(_("E-mail:"), 'email', null, 35, 55);
++              languages_list_row(_("Document Language:"), 'rep_lang', null, _('System default'));
+       }
 -
 -      table_section(2);
        $dim = get_company_pref('use_dimension');
        if ($dim >= 1)
        {
                hidden('dimension_id', 0);
        if ($dim < 2)
                hidden('dimension2_id', 0);
++      table_section(2);
  
  
        table_section_title(_("Addresses"));
        textarea_row(_("General Notes:"), 'notes', null, 35, 5);
        if ($supplier_id)
                record_status_list_row(_("Supplier status:"), 'inactive');
 -      else {
 -              table_section_title(_("Contact Data"));
 -              text_row(_("Contact Person:"), 'contact', null, 42, 40);
 -              text_row(_("Fax Number:"), 'fax', null, 32, 30);
 -              email_row(_("E-mail:"), 'email', null, 35, 55);
 -              languages_list_row(_("Document Language:"), 'rep_lang', null, _('System default'));
 -      }
        end_outer_table(1);
  
        div_start('controls');
@@@ -212,7 -214,7 +216,7 @@@ if (isset($_POST['submit'])
                                $_POST['website'], $_POST['supp_account_no'], $_POST['bank_account'], 
                                input_num('credit_limit', 0), $_POST['dimension_id'], $_POST['dimension2_id'], $_POST['curr_code'],
                                $_POST['payment_terms'], $_POST['payable_account'], $_POST['purchase_account'], $_POST['payment_discount_account'],
 -                              $_POST['notes'], $_POST['tax_group_id'], @$_POST['tax_included']);
 +                              $_POST['notes'], $_POST['tax_group_id'], @$_POST['tax_included'], get_post('tax_algorithm'));
                        update_record_status($_POST['supplier_id'], $_POST['inactive'],
                                'suppliers', 'supplier_id');
  
                                $_POST['gst_no'], $_POST['website'], $_POST['supp_account_no'], $_POST['bank_account'], 
                                input_num('credit_limit',0), $_POST['dimension_id'], $_POST['dimension2_id'],
                                $_POST['curr_code'], $_POST['payment_terms'], $_POST['payable_account'], $_POST['purchase_account'],
 -                              $_POST['payment_discount_account'], $_POST['notes'], $_POST['tax_group_id'], check_value('tax_included'));
 +                              $_POST['payment_discount_account'], $_POST['notes'], $_POST['tax_group_id'], check_value('tax_included'), get_post('tax_algorithm'));
  
                        $supplier_id = $_POST['supplier_id'] = db_insert_id();
  
@@@ -303,6 -305,8 +307,8 @@@ if (!$supplier_id
  tabbed_content_start('tabs', array(
                'settings' => array(_('&General settings'), $supplier_id),
                'contacts' => array(_('&Contacts'), $supplier_id),
+               'transactions' => array(_('&Transactions'), $supplier_id),
+               'orders' => array(_('Purchase &Orders'), $supplier_id),
        ));
        
        switch (get_post('_tabs_sel')) {
                        $contacts = new contacts('contacts', $supplier_id, 'supplier');
                        $contacts->show();
                        break;
+               case 'transactions':
+                       $_GET['supplier_id'] = $supplier_id;
+                       $_GET['popup'] = 1;
+                       include_once($path_to_root."/purchasing/inquiry/supplier_inquiry.php");
+                       break;
                case 'orders':
+                       $_GET['supplier_id'] = $supplier_id;
+                       $_GET['popup'] = 1;
+                       include_once($path_to_root."/purchasing/inquiry/po_search_completed.php");
+                       break;
        };
  br();
  tabbed_content_end();
  hidden('popup', @$_REQUEST['popup']);
  end_form();
  
- end_page();
+ end_page(@$_REQUEST['popup']);
  
  ?>
index 294d4be50a57a3236b5a6977f82f4960c2051b48,a23b7a0754b94603dc9e8e1d22931b4d6df3f337..388eb772158c7449dee682d35dfc5b0d8e91705c
@@@ -57,9 -57,6 +57,9 @@@ if (isset($_GET['ModifyOrderNumber']) &
  
  page($_SESSION['page_title'], false, false, "", $js);
  
 +if (isset($_GET['ModifyOrderNumber']))
 +      check_is_closed(ST_PURCHORDER, $_GET['ModifyOrderNumber']);
 +
  //---------------------------------------------------------------------------------------------------
  
  check_db_has_suppliers(_("There are no suppliers defined in the system."));
@@@ -330,26 -327,28 +330,27 @@@ function can_commit(
                set_focus('supplier_id');
                return false;
        } 
--      
++
        if (!is_date($_POST['OrderDate'])) 
        {
                display_error(_("The entered order date is invalid."));
                set_focus('OrderDate');
                return false;
        } 
 -      
 -      if ($_SESSION['PO']->trans_type != ST_PURCHORDER && !is_date_in_fiscalyear($_POST['OrderDate'])) 
 -      {
 -              display_error(_("The entered date is not in fiscal year"));
 +      if (($_SESSION['PO']->trans_type == ST_SUPPRECEIVE || $_SESSION['PO']->trans_type == ST_SUPPINVOICE) 
 +              && !is_date_in_fiscalyear($_POST['OrderDate'])) {
 +              display_error(_("The entered date is out of fiscal year or is closed for further data entry."));
                set_focus('OrderDate');
                return false;
        }
        if (($_SESSION['PO']->trans_type==ST_SUPPINVOICE) && !is_date($_POST['due_date'])) 
        {
                display_error(_("The entered due date is invalid."));
                set_focus('due_date');
                return false;
        } 
--      
++
        if (!$_SESSION['PO']->order_no) 
        {
        if (!$Refs->is_valid(get_post('ref'))) 
                        set_focus('ref');
                return false;
        } 
--      
++
        if (!is_new_reference(get_post('ref'), $_SESSION['PO']->trans_type)) 
        {
                display_error(_("The entered reference is already in use."));
                return false;
        }
        }
--      
++
        if ($_SESSION['PO']->trans_type == ST_SUPPINVOICE && !$Refs->is_valid(get_post('supp_ref'))) 
        {
                display_error(_("You must enter a supplier's invoice reference."));
                set_focus('supp_ref');
                return false;
        }
+       if ($_SESSION['PO']->trans_type==ST_SUPPINVOICE 
+               && is_reference_already_there($_SESSION['PO']->supplier_id, get_post('supp_ref'), $_SESSION['PO']->order_no))
+       {
+               display_error(_("This invoice number has already been entered. It cannot be entered again.") . " (" . get_post('supp_ref') . ")");
+               set_focus('supp_ref');
+               return false;
+       }
        if ($_SESSION['PO']->trans_type == ST_PURCHORDER && get_post('delivery_address') == '')
        {
                display_error(_("There is no delivery address specified."));
  
  function handle_commit_order()
  {
 +      global $Refs, $type_shortcuts;
 +
        $cart = &$_SESSION['PO'];
  
        if (can_commit()) {
                        }
                        $order_no = add_po($cart);
                        new_doc_date($cart->orig_order_date); 
+               $cart->order_no = $order_no;
  
                        if ($cart->trans_type == ST_PURCHORDER) {
                                unset($_SESSION['PO']);
                        $inv->reference = $ref;
                        $inv->supp_reference = $cart->supp_ref;
                        $inv->tax_included = $cart->tax_included;
 +                      $inv->tax_algorithm = $cart->tax_algorithm;
 +                      $inv->stored_algorithm = $cart->stored_algorithm;
                        $supp = get_supplier($cart->supplier_id);
                        $inv->tax_group_id = $supp['tax_group_id'];
 -//                    $inv->ov_discount 'this isn't used at all'
 -                      $inv->ov_amount = $inv->ov_gst = 0;
 -                      
 +                      $total = 0;
++
                        foreach($cart->line_items as $key => $line) {
                                $inv->add_grn_to_trans($line->grn_item_id, $line->po_detail_rec, $line->stock_id,
                                        $line->item_description, $line->receive_qty, 0, $line->receive_qty,
                                        $line->price, $line->price, true, get_standard_cost($line->stock_id), '');
 -                              $inv->ov_amount += round2(($line->receive_qty * $line->price), user_price_dec());
 +                              $total += round2(($line->receive_qty * $line->price), user_price_dec());
                        }
 -                      $taxes = $inv->get_taxes($inv->tax_group_id, 0, false);
 -                      foreach( $taxes as $taxitem) {
 -                              $inv->ov_gst += round2($taxitem['Value'], user_price_dec());
 +                      if (!$inv->tax_included) {
 +                              $taxes = $inv->get_taxes($inv->tax_group_id, 0, false, $inv->tax_algorithm);
 +                              foreach( $taxes as $taxitem) {
 +                                      $total += $taxitem['Value'];
 +                              }
                        }
 +
                        $inv_no = add_supp_invoice($inv);
 -                      commit_transaction(); // save PO+GRN+PI
 -                      // FIXME payment for cash terms. (Needs cash account selection)
 +                      // presume supplier data need correction
 +                      if ($inv->stored_algorithm != $inv->tax_algorithm)
 +                              update_supp_tax_algorithm($inv->supplier_id, $inv->tax_algorithm);
 +
 +                      if (get_post('cash_account')) {
 +
 +                              $pmt_no = add_supp_payment($inv->supplier_id, $inv->tran_date, get_post('cash_account'),
 +                                      $total, 0,      $Refs->get_next(ST_SUPPAYMENT), 
 +                                      _('Payment for:').$inv->supp_reference .' ('.$type_shortcuts[ST_SUPPINVOICE].$inv_no.')');
 +                              add_supp_allocation($total, ST_SUPPAYMENT, $pmt_no, ST_SUPPINVOICE, $inv_no, $inv->tran_date);
 +                              update_supp_trans_allocation(ST_SUPPINVOICE, $inv_no, $total);
 +                              update_supp_trans_allocation(ST_SUPPAYMENT, $pmt_no, $total);
 +
 +                      }
 +
 +                      commit_transaction(); // save PO+GRN+PI(+SP)
 +
                        unset($_SESSION['PO']);
                        meta_forward($_SERVER['PHP_SELF'], "AddedPI=$inv_no");
                }
@@@ -528,17 -515,6 +538,17 @@@ echo "<br>"
  display_po_items($_SESSION['PO']);
  
  start_table(TABLESTYLE2);
 +
 +if (list_updated('tax_algorithm')) {
 +      $_SESSION['PO']->tax_algorithm = $_POST['tax_algorithm'];
 +    $Ajax->activate('items_table');
 +}
 +
 +if ($_SESSION['PO']->trans_type == ST_SUPPINVOICE) {
 +      tax_algorithm_list_row(_("Tax algorithm:"), 'tax_algorithm', null, true);
 +      cash_accounts_list_row(_("Payment:"), 'cash_account', null, false, _('Delayed'));
 +}
 +
  textarea_row(_("Memo:"), 'Comments', null, 70, 4);
  
  end_table(1);
index 0f75493a3717088b8e2faf09b8bc917dab910ac3,038f50857d60e409647be029c6f4dbfb2ef23e15..e4805768230b53374c9aa4566b118ba7f3e63996
@@@ -25,47 -25,12 +25,47 @@@ if ($use_popup_windows
        $js .= get_js_open_window(900, 500);
  if ($use_date_picker)
        $js .= get_js_date_picker();
 -page(_($help_context = "Supplier Credit Note"), false, false, "", $js);
  
  //----------------------------------------------------------------------------------------
  
  check_db_has_suppliers(_("There are no suppliers defined in the system."));
  
 +if (isset($_GET['ModifyCredit']))
 +      check_is_closed(ST_SUPPINVOICE, $_GET['ModifyCredit']);
 +
 +//---------------------------------------------------------------------------------------------------
 +
 +if (isset($_GET['New']))
 +{
 +      if (isset( $_SESSION['supp_trans']))
 +      {
 +              unset ($_SESSION['supp_trans']->grn_items);
 +              unset ($_SESSION['supp_trans']->gl_codes);
 +              unset ($_SESSION['supp_trans']);
 +      }
 +
 +      if (isset($_GET['invoice_no']))
 +      {
 +              $_SESSION['supp_trans'] = new supp_trans(ST_SUPPINVOICE, $_GET['invoice_no']);
 +              $_SESSION['supp_trans']->src_doc = $_GET['invoice_no'];
 +
 +
 +              $_SESSION['supp_trans']->trans_type = ST_SUPPCREDIT;
 +              $_SESSION['supp_trans']->trans_no = 0;
 +              $_SESSION['supp_trans']->supp_reference = '';
 +              //              $_SESSION['supp_trans']->supp_reference = $_POST['invoice_no'] = $_GET['invoice_no'];
 +              $help_context = "Supplier Credit Note";
 +              $_SESSION['page_title'] = _("Supplier Credit Note");
 +
 +              $_SESSION['supp_trans'] = new supp_trans(ST_SUPPCREDIT);
 +      } elseif (isset($_GET['ModifyInvoice'])) {
 +              $help_context = 'Modifying Purchase Invoice';
 +              $_SESSION['page_title'] = sprintf( _("Modifying Supplier Credit # %d"), $_GET['ModifyCredit']);
 +              $_SESSION['supp_trans'] = new supp_trans(ST_SUPPCREDIT, $_GET['ModifyCredit']);
 +      }
++}
 +page($_SESSION['page_title'], false, false, "", $js);
 +
  //---------------------------------------------------------------------------------------------------------------
  
  if (isset($_GET['AddedID'])) 
  
      hyperlink_params($_SERVER['PHP_SELF'], _("Enter Another Credit Note"), "New=1");
        hyperlink_params("$path_to_root/admin/attachments.php", _("Add an Attachment"), "filterType=$trans_type&trans_no=$invoice_no");
--      
 -      display_footer_exit();
 -}
 -
 -//---------------------------------------------------------------------------------------------------
 -
 -if (isset($_GET['New']))
 -{
 -      if (isset( $_SESSION['supp_trans']))
 -      {
 -              unset ($_SESSION['supp_trans']->grn_items);
 -              unset ($_SESSION['supp_trans']->gl_codes);
 -              unset ($_SESSION['supp_trans']);
 -      }
 -      $_SESSION['supp_trans'] = new supp_trans(ST_SUPPCREDIT);
 -      if (isset($_GET['invoice_no']))
 -      {
 -              $_SESSION['supp_trans']->supp_reference = $_POST['invoice_no'] = $_GET['invoice_no'];
 -      }
 +      display_footer_exit();
  }
  
  function clear_fields()
  {
        global $Ajax;
@@@ -109,7 -91,7 +108,7 @@@ if (isset($_POST['ClearFields'])
        clear_fields();
  }
  
 -if (isset($_POST['AddGLCodeToTrans'])){
 +if (isset($_POST['AddGLCodeToTrans'])) {
  
        $Ajax->activate('gl_items');
        $input_error = false;
  
  function check_data()
  {
-       global $total_grn_value, $total_gl_value, $Refs;
-       
+       global $total_grn_value, $total_gl_value, $Refs, $SysPrefs;
 -      
++
        if (!$_SESSION['supp_trans']->is_valid_trans_to_post())
        {
                display_error(_("The credit note cannot be processed because the there are no items or values on the invoice.  Credit notes are expected to have a charge."));
                return false;
        }
  
 -      if (!is_new_reference($_SESSION['supp_trans']->reference, ST_SUPPCREDIT)) 
 +      if (!is_new_reference($_SESSION['supp_trans']->reference, ST_SUPPCREDIT, $_SESSION['supp_trans']->trans_no))
        {
                display_error(_("The entered reference is already in use."));
                set_focus('reference');
        } 
        elseif (!is_date_in_fiscalyear($_SESSION['supp_trans']->tran_date)) 
        {
 -              display_error(_("The entered date is not in fiscal year."));
 +              display_error(_("The entered date is out of fiscal year or is closed for further data entry."));
                set_focus('tran_date');
                return false;
        }
                return false;
        }
  
+       if (!$SysPrefs->allow_negative_stock()) {
+               foreach ($_SESSION['supp_trans']->grn_items as $n => $item) {
+                       if (is_inventory_item($item->item_code))
+                       {
+                               $qoh = get_qoh_on_date($item->item_code, null, $_SESSION['supp_trans']->tran_date);
+                               if ($item->qty_recd > $qoh)
+                               {
+                                       $stock = get_item($item->item_code);
+                                       display_error(_("The return cannot be processed because there is an insufficient quantity for item:") .
+                                               " " . $stock['stock_id'] . " - " . $stock['description'] . " - " .
+                                               _("Quantity On Hand") . " = " . number_format2($qoh, get_qty_dec($stock['stock_id'])));
+                                       return false;
+                               }
+                               return true;
+                       }
+               }
+       }
        return true;
  }
  
@@@ -220,7 -219,10 +236,10 @@@ function handle_commit_credit_note(
        if (!check_data())
                return;
  
-       $invoice_no = add_supp_invoice($_SESSION['supp_trans']);
+       if (isset($_POST['invoice_no']))
+               $invoice_no = add_supp_invoice($_SESSION['supp_trans'], $_POST['invoice_no']);
+       else
+               $invoice_no = add_supp_invoice($_SESSION['supp_trans']);
  
      $_SESSION['supp_trans']->clear_items();
      unset($_SESSION['supp_trans']);
@@@ -237,6 -239,7 +256,7 @@@ if (isset($_POST['PostCreditNote'])
  
  function check_item_data($n)
  {
        if (!check_num('This_QuantityCredited'.$n, 0))
        {
                display_error(_("The quantity to credit must be numeric and greater than zero."));
index 7bafd736055368eb21506929efa22bfdfb49af3b,ed8f5a089a9c50302c9e7614358e2e68b31fe496..6d9992a68666b0f87ffb2de0dda65ae89a09808a
@@@ -59,6 -59,7 +59,7 @@@ if (isset($_POST['_DatePaid_changed'])
  
  if (list_updated('supplier_id') || list_updated('bank_account')) {
    $_SESSION['alloc']->read();
+   $_POST['memo_'] = $_POST['amount'] = '';
    $Ajax->activate('alloc_tbl');
  }
  //----------------------------------------------------------------------------------------
@@@ -77,7 -78,7 +78,7 @@@ if (!isset($_POST['bank_account'])) { /
                        $_POST['memo_'] = $inv['supp_reference'];
                        foreach($_SESSION['alloc']->allocs as $line => $trans) {
                                if ($trans->type == ST_SUPPINVOICE && $trans->type_no == $_GET['PInvoice']) {
-                                       $_POST['amount'] = 
+                                       $_POST['amount'] =
                                                $_SESSION['alloc']->amount = price_format($_SESSION['alloc']->allocs[$line]->amount);
                                        $_SESSION['alloc']->allocs[$line]->current_allocated =
                                                $_SESSION['alloc']->allocs[$line]->amount;
@@@ -87,7 -88,6 +88,6 @@@
                        unset($inv);
                } else
                        display_error(_("Invalid purchase invoice number."));
        }
  }
  if (isset($_GET['AddedID'])) {
@@@ -182,7 -182,7 +182,7 @@@ function check_inputs(
        } 
        elseif (!is_date_in_fiscalyear($_POST['DatePaid'])) 
        {
 -              display_error(_("The entered date is not in fiscal year."));
 +              display_error(_("The entered date is out of fiscal year or is closed for further data entry."));
                set_focus('DatePaid');
                return false;
        }
@@@ -273,9 -273,14 +273,14 @@@ start_form()
      supplier_list_row(_("Payment To:"), 'supplier_id', null, false, true);
  
        set_global_supplier($_POST['supplier_id']);
--      
++
+       if (!list_updated('bank_account'))
+               $_POST['bank_account'] = get_default_supplier_bank_account($_POST['supplier_id']);              
 -      
++
      bank_accounts_list_row(_("From Bank Account:"), 'bank_account', null, true);
 -      
 +
+       bank_balance_row($_POST['bank_account']);
        table_section(2);
  
      ref_row(_("Reference:"), 'ref', '', $Refs->get_next(ST_SUPPAYMENT));
        end_outer_table(1); // outer table
  
        if ($bank_currency == $supplier_currency) {
-       div_start('alloc_tbl');
+               div_start('alloc_tbl');
                show_allocatable(false);
-       div_end();
+               div_end();
        }
  
        start_table(TABLESTYLE, "width=60%");
index b13ef4160dca923e95bb2d263f7dbf47a8a8f9f5,025e6581ef0631b454e268e92def09729802873d..ad7030aaaadf47bdba28d5f7f00853c08c7d67b8
@@@ -13,6 -13,6 +13,7 @@@ $page_security = 'SA_SUPPTRANSVIEW'
  $path_to_root = "../..";
  
  include_once($path_to_root . "/purchasing/includes/purchasing_db.inc");
++include_once($path_to_root . "/includes/ui/items_cart.inc");
  include_once($path_to_root . "/includes/session.inc");
  
  include_once($path_to_root . "/purchasing/includes/purchasing_ui.inc");
@@@ -69,11 -69,17 +70,17 @@@ display_supp_trans_tax_details($tax_ite
  
  $display_total = number_format2($supp_trans->ov_amount + $supp_trans->ov_gst,user_price_dec());
  
--label_row(_("TOTAL INVOICE"), $display_total, "colspan=1 align=right", "nowrap align=right");
++label_row(_("TOTAL INVOICE").' ('.$supplier_curr_code.')', $display_total, "colspan=1 align=right", "nowrap align=right");
  
  end_table(1);
  
- is_voided_display(ST_SUPPINVOICE, $trans_no, _("This invoice has been voided."));
+ $voided = is_voided_display(ST_SUPPINVOICE, $trans_no, _("This invoice has been voided."));
+ if (!$voided) 
+ {
+       display_allocations_to(PT_SUPPLIER, $supp_trans->supplier_id, ST_SUPPINVOICE, $trans_no, 
+               ($supp_trans->ov_amount + $supp_trans->ov_gst));
+ }
  
  end_page(true, false, false, ST_SUPPINVOICE, $trans_no);
  
index 44b62b4326d6b0c3664eda439f9ab5f11d8e9bd3,300cd40194987856fee4080535f9f81ba44f86ff..9bc222d3eaa82ef13e0d5f65e58d0bdc9458af39
@@@ -79,21 -79,21 +79,21 @@@ class Cpdf extends FPDI 
        */
        function SetLang($code=null) 
        {
-               global $installed_languages, $dflt_lang, $path_to_root, $local_path_to_root;
+               global $installed_languages, $dflt_lang, $path_to_root, $local_path_to_root, $GetText;
  
                if (!$code)
                        $code = $dflt_lang;
  
                $lang = array_search_value($code, $installed_languages, 'code');
-               $_SESSION['get_text']->set_language($lang['code'], strtoupper($lang['encoding']));
+               $GetText->set_language($lang['code'], strtoupper($lang['encoding']));
  
                // $local_path_to_root is  set inside find_custom_file.
                // Select extension domain if po file is provided
                // otherwise use global translation.
                if (file_exists($local_path_to_root.'/lang/'.$lang['code'].'/LC_MESSAGES/'.$lang['code'].'.po'))
-                       $_SESSION['get_text']->add_domain($lang['code'], $local_path_to_root . "/lang");
+                       $GetText->add_domain($lang['code'], $local_path_to_root . "/lang");
                else
-                       $_SESSION['get_text']->add_domain($lang['code'], $path_to_root . "/lang", @$lang['version']);
+                       $GetText->add_domain($lang['code'], $path_to_root . "/lang", @$lang['version']);
                // re-read translated sys names.
                include($path_to_root.'/includes/sysnames.inc');
  
                                        default :               $fontname = "freesans5";        break;
                                }
                        }
-                       // else use built-in adobe fonts helvetica.
+                       elseif ($this->encoding === "ISO-8859-13")
+             {
+                 switch ($this->l['a_meta_language'])
+                 {
+                     default :        $fontname = "freesans13";     break;
+                 }
 -            }                 
++            }
+             // else use built-in adobe fonts helvetica.
                }
                $this->SetFont($fontname, $style);
        }
index 4f52bd2cb22ad6c69cfc2a2a53df6127f80dfe7a,7044cee4572eaa352406610d92d10b1ede016a04..f279283b10a93e50ae63c6d2cb20ba20495f7b7f
      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
      See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
  ***********************************************************************/
- if (isset($header2type))
- {
-       $doc_Cust_no = _("Cust no");
-       $doc_Date = _("Date");
-       if ($doctype == ST_PURCHORDER || $doctype == ST_SUPPAYMENT) // Purchase Order
-       {
-               $doc_Charge_To = _("Order To");
-               if ($doctype == ST_PURCHORDER)
-                       $doc_Delivered_To = _("Deliver To");
-               else    
-                       $doc_Delivered_To = _("Charge To");
-       }
-       else
-       {
-               if ($doctype == ST_CUSTPAYMENT)
-                       $doc_Charge_To = _("With thanks from");
-               else    
-                       $doc_Charge_To = _("Charge To");
-               $doc_Delivered_To = _("Delivered To");
-       }       
-       $doc_Shipping_Company = _("Shipping Company");
-       if ($doctype == ST_SALESQUOTE)
-               $doc_Due_Date = _("Valid until");
-       elseif ($doctype == ST_SALESORDER)
-               $doc_Due_Date = _("Delivery Date");
-       else
-               $doc_Due_Date = _("Due Date");
-       $doc_Your_Ref = _("Your Ref");
-       if ($doctype == ST_WORKORDER)
-       {
-               $doc_Our_Ref = _("Type");
-               $doc_Your_VAT_no = _("Manufactured Item");
-               $doc_Payment_Terms = _("Required By");
-               $doc_Customers_Ref = _("Reference");
-               $doc_Our_Order_No = _("Into Location");
-               $doc_Due_Date = _("Quantity");
-       }       
-       else
-       {
-               if ($doctype == ST_SUPPAYMENT || $doctype == ST_CUSTPAYMENT)
-                       $doc_Our_Ref = _("Type");
-               else    
-                       $doc_Our_Ref = _("Sales Person");
-               $doc_Your_VAT_no = _("Your VAT no.");
-               $doc_Payment_Terms = _("Payment Terms");
-               $doc_Customers_Ref = _("Customers Reference");
-               $doc_Our_Order_No = _("Our Order No");
-       }
-       $doc_Our_VAT_no = _("Our VAT No.");
-       $doc_Domicile = _("Domicile");
-       $doc_Extra = "";
-       if($doctype == ST_CUSTDELIVERY || $doctype == ST_SALESQUOTE || $doctype == ST_PURCHORDER || $doctype == ST_SALESORDER ||
-               $doctype == ST_SUPPAYMENT || $doctype == ST_CUSTPAYMENT) {
-               if ($doctype == ST_CUSTPAYMENT)
-                       $doc_Extra = _("* Subject to Realisation of the Cheque.");
-               $doc_Bank_Account = '';
-               $doc_Please_Quote = _("All amounts stated in");
-   } else {
-        $doc_Bank_Account = _("Bank Account");
-        $doc_Please_Quote = $doctype==ST_SALESINVOICE ? 
-        _("Please quote Invoice no. when paying. All amounts stated in") :
-        _("Please quote Credit no. when paying. All amounts stated in");
-       }
-       $doc_Address = _("Address");
-       $doc_Phone_Fax_Email = _("Phone/Fax/Email");
-       $doc_Bank = _("Bank");
-       $doc_Payment_Link = _("You can pay through");
-       if ($doctype == ST_SALESQUOTE || $doctype == ST_PURCHORDER || $doctype == ST_SALESORDER || $doctype == ST_SALESINVOICE || 
-               $doctype == ST_CUSTCREDIT || $doctype == ST_CUSTDELIVERY || $doctype == ST_WORKORDER || $doctype == ST_SUPPAYMENT || 
-               $doctype == ST_CUSTPAYMENT)
+ /*****
+ *
+ *     Set document type dependent elements of common page layout.
+ *
+ */
+       $Addr1 = array(
+                       'title' => _("Charge To"),
+                       'name' => @$this->formData['br_name'] ? $this->formData['br_name'] : @$this->formData['DebtorName'],
+                       'address' => @$this->formData['br_address'] ? $this->formData['br_address'] : @$this->formData['address']
+       );
+       $Addr2 = array(
+                       'title' => _("Delivered To"),
+                       'name' => @$this->formData['deliver_to'],
+                       'address' => @$this->formData['delivery_address']
+       );
+       // default item column headers
+       $this->headers = array(_("Item Code"), _("Item Description"), _("Quantity"),
+               _("Unit"), _("Price"), _("Discount %"), _("Total"));
+       // for links use 'text' => 'url'
+       $Footer[0] = _("All amounts stated in") . " - " . @$this->formData['curr_code'];
+       switch ($this->formData['doctype'])
        {
-               if ($doctype == ST_SALESQUOTE)
+               case ST_SALESQUOTE:
                        $this->title = _("SALES QUOTATION");
-               elseif ($doctype == ST_PURCHORDER)
-                       $this->title = _("PURCHASE ORDER");
-               elseif ($doctype == ST_CUSTDELIVERY)
-                       $this->title = ($packing_slip==1 ? _("PACKING SLIP") : _("DELIVERY NOTE"));
-               elseif ($doctype == ST_SALESORDER)
+                       $this->formData['document_name'] =_("Quotation No.");
+                       $this->formData['document_date'] = $this->formData['ord_date'];
+                       $this->formData['document_number'] = $print_invoice_no == 0 && isset($this->formData['reference'])
+                               ? $this->formData['reference'] : $this->formData['order_no'];
+                       $aux_info = array(
+                               _("Customers Reference") => $this->formData["customer_ref"],
+                               _("Sales Person") => get_salesman_name($this->formData['salesman']),
+                               _("Your VAT no.") => $this->formData['tax_id'],
+                               _("Our Quotation No") => $this->formData['order_no'],
+                               _("Valid until") => sql2date($this->formData['delivery_date']),
+                       );
+                       break;
+               case ST_SALESORDER:
                        $this->title = ($print_as_quote==1 ? _("QUOTE") : _("SALES ORDER"));
-               elseif ($doctype == ST_SALESINVOICE)
+                       $this->formData['document_name'] =_("Order No.");
+                       $this->formData['document_date'] = $this->formData['ord_date'];
+                       $this->formData['document_number'] = $print_invoice_no == 0 && isset($this->formData['reference'])
+                               ? $this->formData['reference'] : $this->formData['order_no'];
+                       $this->formData['document_amount'] = $this->formData['order_no'];
+                       $aux_info = array(
+                               _("Customers Reference") => $this->formData["customer_ref"],
+                               _("Sales Person") => get_salesman_name($this->formData['salesman']),
+                               _("Your VAT no.") => $this->formData['tax_id'],
+                               _("Our Order No") => $this->formData['order_no'],
+                               _("Delivery Date") => sql2date($this->formData['delivery_date']),
+                       );
+                       break;
+               case ST_CUSTDELIVERY:
+                       $this->title = ($packing_slip==1 ? _("PACKING SLIP") : _("DELIVERY NOTE"));
+                       $this->formData['document_name'] = _("Delivery Note No.");
+                       if (@$packing_slip)
+                               $Payment_Terms = '';
+                       $ref = $this->formData['order_'];
+                       if ($print_invoice_no == 0)
+                       {
+                               $ref = get_reference(ST_SALESORDER, $this->formData['order_']);
+                               if (!$ref)
+                                       $ref = $this->formData['order_'];
+                       }
+                       $aux_info = array(
+                               _("Customers Reference") => $this->formData["customer_ref"],
+                               _("Sales Person") => get_salesman_name($this->formData['salesman']),
+                               _("Your VAT no.") => $this->formData['tax_id'],
+                               _("Our Order No") => $ref,
+                               _("To Be Invoiced Before") => sql2date($this->formData['due_date']),
+                       );
+                       break;
+               case ST_CUSTCREDIT:
+                       $this->title = _("CREDIT NOTE");
+                       $this->formData['document_name'] =_("Credit No.");
+                       $Footer[0] = _("Please quote Credit no. when paying. All amounts stated in") . " - " . $this->formData['curr_code'];
+                       $aux_info = array(
+                               _("Customers Reference") => @$this->formData["customer_ref"],
+                               _("Sales Person") => get_salesman_name($this->formData['salesman']),
+                               _("Your VAT no.") => $this->formData['tax_id'],
+                               _("Our Order No") => $this->formData['order_'],
+                               _("Due Date") => '',
+                       );
+                       break;
+               case ST_SALESINVOICE:
                        $this->title = _("INVOICE");
-               elseif ($doctype == ST_WORKORDER)
-                       $this->title = _("WORK ORDER");
-               elseif ($doctype == ST_SUPPAYMENT)
+                       $this->formData['document_name'] =_("Invoice No.");
+                       $this->formData['domicile'] = $this->company['domicile'];
+                       $Footer[0] = _("Please quote Invoice no. when paying. All amounts stated in"). " - " . $this->formData['curr_code'];
+                       $deliveries = get_sales_parent_numbers(ST_SALESINVOICE, $this->formData['trans_no']);
+                       if ($print_invoice_no == 0)
+                       {
+                               foreach($deliveries as $n => $delivery) {
+                                       $deliveries[$n] = get_reference(ST_CUSTDELIVERY, $delivery);
+                               }
+                       }
+                       $aux_info = array(
+                               _("Customers Reference") => $this->formData["customer_ref"],
+                               _("Sales Person") => get_salesman_name($this->formData['salesman']),
+                               _("Your VAT no.") => $this->formData['tax_id'],
+                               _("Delivery Note No.") => implode(',', $deliveries),
+                               _("Due Date") => sql2date($this->formData['due_date']),
+                       );
+                       break;
+               case ST_SUPPAYMENT:
+                       global $systypes_array;
                        $this->title = _("REMITTANCE");
-               elseif ($doctype == ST_CUSTPAYMENT)
-                       $this->title = _("RECEIPT");
-               else
-                       $this->title = _("CREDIT NOTE");
-               if ($doctype == ST_PURCHORDER)
+                       $this->formData['document_name'] =_("Remittance No.");
+                       $Addr1['title'] = _("Order To");
+                       $Addr1['name'] = $this->formData['supp_name'];
+                       $Addr1['address'] = $this->formData['address'];
+                       $Addr2['title'] = _("Charge To");
+                       $Addr2['name'] = '';
+                       $Addr2['address'] = '';
+                       $aux_info = array(
+                               _("Customers Reference") => $this->formData['supp_account_no'],
+                               _("Type") =>$systypes_array[$this->formData["type"]],
+                               _("Your VAT no.") => $this->formData['tax_id'],
+                               _("Our Order No") => '',
+                               _("Due Date") => sql2date($this->formData['tran_date']),
+                       );
+                       $this->headers = array(_("Trans Type"), _("#"), _("Date"), _("Due Date"), _("Total Amount"), _("Left to Allocate"), _("This Allocation"));
+                       break;
+               case ST_PURCHORDER:
+                       $this->title = _("PURCHASE ORDER");
+                       $this->formData['document_name'] =_("Purchase Order No.");
+                       $Addr1['title'] = _("Order To");
+                       $Addr1['name'] = $this->formData['supp_name'];
+                       $Addr1['address'] = $this->formData['address'];
+                       $Addr2['title'] = _("Deliver To");
+                       $Addr2['name'] = $this->company['coy_name'];
+                       //$Addr2['address'] = $this->company['postal_address']; No, don't destroy delivery address!
+                       $this->formData['document_date'] = $this->formData['ord_date'];
+                       $this->formData['document_number'] = $print_invoice_no == 0 && isset($this->formData['reference'])
+                               ? $this->formData['reference'] : $this->formData['order_no'];
+                       $aux_info = array(
+                               _("Customers Reference") => $this->formData['supp_account_no'],
+                               _("Sales Person") => '',
+                               _("Your VAT no.") => '',
+                               _("Our Order No") => '',
+                               _("Due Date") => '',
+                       );
                        $this->headers = array(_("Item Code"), _("Item Description"),
                                _("Delivery Date"), _("Quantity"),      _("Unit"), _("Price"), _("Total"));
-               elseif ($doctype == ST_WORKORDER)
+                       break;
+               case ST_CUSTPAYMENT:
+                       global $systypes_array;
+                       $this->title = _("RECEIPT");
+                       $this->formData['document_name'] =_("Receipt No.");
+                       $Addr1['title'] = _("With thanks from");
+                       $aux_info = array(
+                               _("Customers Reference") => $this->formData["debtor_ref"],
+                               _("Type") =>$systypes_array[$this->formData["type"]],
+                               _("Your VAT no.") => $this->formData['tax_id'],
+                               _("Our Order No") => $this->formData['order_'],
+                               _("Due Date") => sql2date($this->formData['tran_date']),
+                       );
+                       $this->headers = array(_("Trans Type"), _("#"), _("Date"), _("Due Date"), _("Total Amount"), _("Left to Allocate"), _("This Allocation"));
+                       break;
+               case ST_WORKORDER:
+                       global $wo_types_array;
+                       $this->title = _("WORK ORDER");
+                       $this->formData['document_name'] =_("Work Order No.");
+                       $this->formData['document_date'] = $this->formData['date_'];
+                       $this->formData['document_number'] = $this->formData['id'];
+                       $Addr1['name'] = $this->formData['location_name'];
+                       $Addr1['address'] = $this->formData['delivery_address'];
+                       $aux_info = array(
+                               _("Reference") => $this->formData['wo_ref'],
+                               _("Type") => $wo_types_array[$this->formData["type"]],
+                               _("Manufactured Item") => $this->formData["StockItemName"],
+                               _("Into Location") => $this->formData["location_name"],
+                               _("Quantity") => $this->formData["units_issued"],
+                       );
+                       $Payment_Terms = _("Required By").": ".sql2date($this->formData["required_by"]);
                        $this->headers = array(_("Item Code"), _("Item Description"),
                                _("From Location"), _("Work Centre"),   _("Unit Quantity"), _("Total Quantity"), _("Units Issued"));
-               elseif ($doctype == ST_SUPPAYMENT || $doctype == ST_CUSTPAYMENT)
-                       $this->headers = array(_("Trans Type"), _("#"), _("Date"), _("Due Date"), _("Total Amount"), _("Left to Allocate"), _("This Allocation"));
-               else
-                       $this->headers = array(_("Item Code"), _("Item Description"),   _("Quantity"),
-                               _("Unit"), _("Price"), _("Discount %"), _("Total"));
-       }
-       else if ($doctype == ST_STATEMENT)
-       {
-               $this->title = _("STATEMENT");
-               $this->headers = array(_("Trans Type"), _("#"), _("Date"), _("DueDate"), _("Charges"),
-                       _("Credits"), _("Allocated"), _("Outstanding"));
+                       unset($Footer[0]);
+                       break;
+               case ST_STATEMENT:
+                       $this->formData['document_name'] = '';
+                       $this->formData['domicile'] = $this->company['domicile'];
+                       $Payment_Terms = '';
+                       $this->title = _("STATEMENT");
+                       $aux_info = array(
+                               _("Customers Reference") => '',
+                               _("Sales Person") => '',
+                               _("Your VAT no.") => $this->formData['tax_id'],
+                               _("Our Order No") => '',
+                               _("Delivery Date") => '',
+                       );
+                       $this->headers = array(_("Trans Type"), _("#"), _("Date"), _("DueDate"), _("Charges"),
+                               _("Credits"), _("Allocated"), _("Outstanding"));
        }
- }
- if (isset($emailtype))
- {
-       $doc_Dear_Sirs = _("Dear");
-       $doc_AttachedFile = _("Attached you will find ");
-       $doc_Kindest_regards = _("Kindest regards");
-       $doc_Payment_Link = _("You can pay through");
- }
- if (isset($header2type) || isset($linetype))
- {
-       $doc_Invoice_no = ($doctype==ST_CUSTDELIVERY ? _("Delivery Note No.") : 
-               ($doctype == ST_CUSTPAYMENT ? _("Receipt No.") :
-               ($doctype == ST_SUPPAYMENT ? _("Remittance No.") :
-               ($doctype == ST_PURCHORDER ? _("Purchase Order No.") :
-               ($doctype == ST_SALESORDER ? _("Order No.") :
-               ($doctype == ST_SALESQUOTE ? _("Quotation No.") :
-               ($doctype == ST_SALESINVOICE ? _("Invoice No.") :
-               ($doctype == ST_WORKORDER ? _("Work Order No.") : _("Credit No.")))))))));
-       $doc_Delivery_no = _("Delivery Note No.");
-       $doc_Order_no = _("Order No.");
- }
- if (isset($linetype))
- {
-       if ($doctype == ST_SALESQUOTE || $doctype == ST_PURCHORDER || $doctype == ST_SALESORDER || 
-               $doctype == ST_SALESINVOICE || $doctype == ST_CUSTCREDIT || $doctype == ST_CUSTDELIVERY)
+       // default values
+       if (!isset($this->formData['document_date']))
+               $this->formData['document_date'] = $this->formData['tran_date'];
+       if (!isset($this->formData['document_number']))
+               $this->formData['document_number'] = $print_invoice_no == 0 && isset($this->formData['reference'])
+                       ? $this->formData['reference'] : @$this->formData['trans_no'];
+       if (!isset($Payment_Terms))
        {
-               $doc_Sub_total = _("Sub-total");
-               $doc_Shipping = _("Shipping");
-               $doc_Included = _("Included");
-               $doc_Amount = _("Amount");
-               $doc_TOTAL_INVOICE = $doctype ==ST_SALESINVOICE ? _("TOTAL INVOICE") : _("TOTAL CREDIT");
-               $doc_TOTAL_ORDER = _("TOTAL ORDER EX VAT");
-               $doc_TOTAL_ORDER2 = _("TOTAL ORDER VAT INCL.");
-               $doc_TOTAL_PO = _("TOTAL PO");
-               $doc_TOTAL_DELIVERY = _("TOTAL DELIVERY INCL. VAT");
+               $id = $this->formData['payment_terms'];
+               $sql = "SELECT terms FROM ".TB_PREF."payment_terms WHERE terms_indicator=".db_escape($id);
+               $result = db_query($sql,"could not get paymentterms");
+               $row = db_fetch($result);
+               $Payment_Terms = _("Payment Terms") . ': ' . $row["terms"];
        }
-       elseif ($doctype == ST_SUPPAYMENT || $doctype == ST_CUSTPAYMENT)
+       // footer generic content
+       if (@$this->formData['bank_name'])
+               $Footer[] = _("Bank"). ": ".$this->formData['bank_name']. ", " . _("Bank Account") . ": " . $this->formData['bank_account_number'];
+       if (@$this->formData['payment_service'])        //payment link
        {
-               $doc_Towards = _("As advance / full / part / payment towards:");
-               $doc_by_Cheque = _("By Cash / Cheque* / Draft No.");
-               $doc_Dated = _("Dated");
-               $doc_Drawn = _("Drawn on Bank");
-               $doc_Drawn_Branch = _("Branch");
-               $doc_Received = _("Received / Sign");
-               $doc_Total_Allocated = _("Total Allocated");
-               $doc_Left_To_Allocate = _("Left to Allocate");
-               if ($doctype == ST_CUSTPAYMENT)
-                       $doc_Total_Payment = _("TOTAL RECEIPT");
-               else    
-                       $doc_Total_Payment = _("TOTAL REMITTANCE");
+               $amt = number_format($this->formData["ov_freight"] + $this->formData["ov_gst"] + $this->formData["ov_amount"], user_price_dec());
+               $service = $this->formData['payment_service'];
+               $url = payment_link($service, array(
+                       'company_email' => $this->company['email'],
+                       'amount' => $amt,
+                       'currency' => $this->formData['curr_code'],
+                       'comment' => $this->title . " " . $this->formData['reference']
+                       ));
+               $Footer[_("You can pay through"). " $service: "] = "$url";
        }
-       elseif ($doctype == ST_STATEMENT)
+       if ($this->formData['doctype'] == ST_CUSTPAYMENT)
+               $Footer[] = _("* Subject to Realisation of the Cheque.");
+       if ($this->params['comments'] != '')
+               $Footer[] = $this->params['comments'];
+       if (($this->formData['doctype'] == ST_SALESINVOICE || $this->formData['doctype'] == ST_STATEMENT) && $this->company['legal_text'] != "") 
        {
-               $doc_Outstanding = _("Outstanding Transactions");
-               $doc_Current = _("Current");
-               $doc_Total_Balance = _("Total Balance");
-               $doc_Statement = _("Statement");
-               $doc_as_of = _("as of");
-               $doc_Days = _("Days");
-               $doc_Over = _("Over");
+               foreach(explode("\n", $this->company['legal_text']) as $line)
+                       $Footer[] = $line;
        }
- }
 -
--?>
index 996d290c42338960b9c7794f0ac69009f06401bc,33ac54a529448ee627444c4679e9dd357a41b567..7d1379b43676d9bb45929b6173ac95cfed7ad060
@@@ -693,8 -693,9 +693,8 @@@ class FrontReport extends Spreadsheet_E
                return ($px / $unit_offset_length);
        }       
  
-       function End($email=0, $subject=null, $myrow=null, $doctype = 0)
+       function End($email=0, $subject='')
        {
 -              global $path_to_root;
                ++$this->y;
                for ($i = 0; $i < $this->numcols; $i++)
                        $this->sheet->writeBlank($this->y, $i, $this->formatFooter);
                        }
                        closedir($d);
                }
-               meta_forward($_SERVER['PHP_SELF'], "xls=1&filename=$this->filename&unique=$this->unique_name");
+               meta_forward($path_to_root.'/reporting/prn_redirect.php', "xls=1&filename=$this->filename&unique=$this->unique_name");
                exit();
        }
  }
diff --combined reporting/rep107.php
index e2a50b331b25028912153126a80e8022eed38d2f,5e044f2898df54935a36d3daf75de299c4b10cde..36acff5abcd21e3ca7e592cc14fa3ae72ae8a496
@@@ -32,7 -32,7 +32,7 @@@ print_invoices()
  
  function print_invoices()
  {
-       global $path_to_root, $alternative_tax_include_on_docs, $suppress_tax_rates;
+       global $path_to_root, $alternative_tax_include_on_docs, $suppress_tax_rates, $no_zero_lines_amount;
        
        include_once($path_to_root . "/reporting/includes/pdf_report.inc");
  
        $to = $_POST['PARAM_1'];
        $currency = $_POST['PARAM_2'];
        $email = $_POST['PARAM_3'];
-       $paylink = $_POST['PARAM_4'];
+       $pay_service = $_POST['PARAM_4'];
        $comments = $_POST['PARAM_5'];
  
-       if ($from == null)
-               $from = 0;
-       if ($to == null)
-               $to = 0;
+       if (!$from || !$to) return;
        $dec = user_price_dec();
  
        $fno = explode("-", $from);
        $tno = explode("-", $to);
+       $from = min($fno[0], $tno[0]);
+       $to = max($fno[0], $tno[0]);
  
        $cols = array(4, 60, 225, 300, 325, 385, 450, 515);
  
                $rep->Font();
                $rep->Info($params, $cols, null, $aligns);
        }
-       for ($i = $fno[0]; $i <= $tno[0]; $i++)
+       for ($i = $from; $i <= $to; $i++)
        {
-               for ($j = ST_SALESINVOICE; $j <= ST_CUSTCREDIT; $j++)
-               {
-                       if (isset($_POST['PARAM_6']) && $_POST['PARAM_6'] != $j)
+                       if (!exists_customer_trans(ST_SALESINVOICE, $i))
                                continue;
-                       if (!exists_customer_trans($j, $i))
-                               continue;
-                       $sign = $j==ST_SALESINVOICE ? 1 : -1;
-                       $myrow = get_customer_trans($i, $j);
+                       $sign = 1;
+                       $myrow = get_customer_trans($i, ST_SALESINVOICE);
                        $baccount = get_default_bank_account($myrow['curr_code']);
                        $params['bankaccount'] = $baccount['id'];
  
                        $branch = get_branch($myrow["branch_code"]);
-                       $branch['disable_branch'] = $paylink; // helper
-                       if ($j == ST_SALESINVOICE)
-                               $sales_order = get_sales_order_header($myrow["order_"], ST_SALESORDER);
-                       else
-                               $sales_order = null;
+                       $sales_order = get_sales_order_header($myrow["order_"], ST_SALESORDER);
                        if ($email == 1)
                        {
                                $rep = new FrontReport("", "", user_pagesize());
                            $rep->SetHeaderType('Header2');
                                $rep->currency = $cur;
                                $rep->Font();
-                               if ($j == ST_SALESINVOICE)
-                               {
-                                       $rep->title = _('INVOICE');
-                                       $rep->filename = "Invoice" . $myrow['reference'] . ".pdf";
-                               }
-                               else
-                               {
-                                       $rep->title = _('CREDIT NOTE');
-                                       $rep->filename = "CreditNote" . $myrow['reference'] . ".pdf";
-                               }
+                               $rep->title = _('INVOICE');
+                               $rep->filename = "Invoice" . $myrow['reference'] . ".pdf";
                                $rep->Info($params, $cols, null, $aligns);
                        }
                        else
-                               $rep->title = ($j == ST_SALESINVOICE) ? _('INVOICE') : _('CREDIT NOTE');
-                       $contacts = get_branch_contacts($branch['branch_code'], 'invoice', $branch['debtor_no']);
-                       $rep->SetCommonData($myrow, $branch, $sales_order, $baccount, $j, $contacts);
+                               $rep->title = _('INVOICE');
+                       $contacts = get_branch_contacts($branch['branch_code'], 'invoice', $branch['debtor_no'], false);
+                       $baccount['payment_service'] = $pay_service;
+                       $rep->SetCommonData($myrow, $branch, $sales_order, $baccount, ST_SALESINVOICE, $contacts);
                        $rep->NewPage();
-                       $result = get_customer_trans_details($j, $i);
+                       $result = get_customer_trans_details(ST_SALESINVOICE, $i);
                        $SubTotal = 0;
                        while ($myrow2=db_fetch($result))
                        {
                                if ($myrow2["quantity"] == 0)
                                        continue;
-                                       
                                $Net = round2($sign * ((1 - $myrow2["discount_percent"]) * $myrow2["unit_price"] * $myrow2["quantity"]),
                                   user_price_dec());
                                $SubTotal += $Net;
                                $rep->TextColLines(1, 2, $myrow2['StockDescription'], -2);
                                $newrow = $rep->row;
                                $rep->row = $oldrow;
-                               $rep->TextCol(2, 3,     $DisplayQty, -2);
-                               $rep->TextCol(3, 4,     $myrow2['units'], -2);
-                               $rep->TextCol(4, 5,     $DisplayPrice, -2);
-                               $rep->TextCol(5, 6,     $DisplayDiscount, -2);
-                               $rep->TextCol(6, 7,     $DisplayNet, -2);
+                               if ($Net != 0.0 || !is_service($myrow2['mb_flag']) || !isset($no_zero_lines_amount) || $no_zero_lines_amount == 0)
+                               {
+                                       $rep->TextCol(2, 3,     $DisplayQty, -2);
+                                       $rep->TextCol(3, 4,     $myrow2['units'], -2);
+                                       $rep->TextCol(4, 5,     $DisplayPrice, -2);
+                                       $rep->TextCol(5, 6,     $DisplayDiscount, -2);
+                                       $rep->TextCol(6, 7,     $DisplayNet, -2);
 -                              }       
++                              }
                                $rep->row = $newrow;
                                //$rep->NewLine(1);
                                if ($rep->row < $rep->bottomMargin + (15 * $rep->lineHeight))
                                        $rep->NewPage();
                        }
  
-                       $comments = get_comments($j, $i);
-                       if ($comments && db_num_rows($comments))
+                       $memo = get_comments_string(ST_SALESINVOICE, $i);
+                       if ($memo != "")
                        {
                                $rep->NewLine();
-                       while ($comment=db_fetch($comments))
-                               $rep->TextColLines(0, 6, $comment['memo_'], -2);
+                               $rep->TextColLines(1, 5, $memo, -2);
                        }
  
                        $DisplaySubTot = number_format2($SubTotal,$dec);
                        $DisplayFreight = number_format2($sign*$myrow["ov_freight"],$dec);
  
                $rep->row = $rep->bottomMargin + (15 * $rep->lineHeight);
-                       $linetype = true;
-                       $doctype = $j;
-                       include($path_to_root . "/reporting/includes/doctext.inc");
+                       $doctype = ST_SALESINVOICE;
  
-                       $rep->TextCol(3, 6, $doc_Sub_total, -2);
+                       $rep->TextCol(3, 6, _("Sub-total"), -2);
                        $rep->TextCol(6, 7,     $DisplaySubTot, -2);
                        $rep->NewLine();
-                       $rep->TextCol(3, 6, $doc_Shipping, -2);
+                       $rep->TextCol(3, 6, _("Shipping"), -2);
                        $rep->TextCol(6, 7,     $DisplayFreight, -2);
                        $rep->NewLine();
-                       $tax_items = get_trans_tax_details($j, $i);
+                       $tax_items = get_trans_tax_details(ST_SALESINVOICE, $i);
                        $first = true;
                while ($tax_item = db_fetch($tax_items))
                {
-                               if ($tax_item['amount'] == 0)
-                                       continue;
+                       if ($tax_item['amount'] == 0)
+                               continue;
                        $DisplayTax = number_format2($sign*$tax_item['amount'], $dec);
--                      
++
                        if (isset($suppress_tax_rates) && $suppress_tax_rates == 1)
                                $tax_type_name = $tax_item['tax_type_name'];
                        else
                                                $first = false;
                                }
                                else
-                                               $rep->TextCol(3, 7, $doc_Included . " " . $tax_type_name . $doc_Amount . ": " . $DisplayTax, -2);
+                                               $rep->TextCol(3, 7, _("Included") . " " . $tax_type_name . _("Amount") . ": " . $DisplayTax, -2);
                                }
                        else
                        {
                                }
                                $rep->NewLine();
                }
                $rep->NewLine();
                        $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(3, 6, _("TOTAL INVOICE"), - 2);
                        $rep->TextCol(6, 7, $DisplayTotal, -2);
-                       $words = price_in_words($myrow['Total'], $j);
+                       $words = price_in_words($myrow['Total'], ST_SALESINVOICE);
                        if ($words != "")
                        {
                                $rep->NewLine(1);
                                $rep->TextCol(1, 7, $myrow['curr_code'] . ": " . $words, - 2);
-                       }       
+                       }
                        $rep->Font();
                        if ($email == 1)
                        {
-                               $myrow['dimension_id'] = $paylink; // helper for pmt link
-                               $rep->End($email, $doc_Invoice_no . " " . $myrow['reference'], $myrow, $j);
+                               $rep->End($email);
                        }
-               }
        }
        if ($email == 0)
                $rep->End();
diff --combined reporting/rep109.php
index c775bb907769c08b2e787a57e7816e7d4af0cc72,c8b4a1ef3e782f8ac34fc86df9d67742fa5d13e0..08990e10babfbe463828ef9225cff3e3e14802bf
@@@ -33,7 -33,7 +33,7 @@@ $print_as_quote = 0
  
  function print_sales_orders()
  {
-       global $path_to_root, $print_as_quote;
+       global $path_to_root, $print_as_quote, $no_zero_lines_amount;
  
        include_once($path_to_root . "/reporting/includes/pdf_report.inc");
  
@@@ -98,7 -98,7 +98,7 @@@
                else
                        $rep->title = ($print_as_quote==1 ? _("QUOTE") : _("SALES ORDER"));
  
-               $contacts = get_branch_contacts($branch['branch_code'], 'order', $branch['debtor_no']);
+               $contacts = get_branch_contacts($branch['branch_code'], 'order', $branch['debtor_no'], false);
                $rep->SetCommonData($myrow, $branch, $myrow, $baccount, ST_SALESORDER, $contacts);
                $rep->NewPage();
  
                        $rep->TextColLines(1, 2, $myrow2['description'], -2);
                        $newrow = $rep->row;
                        $rep->row = $oldrow;
-                       $rep->TextCol(2, 3,     $DisplayQty, -2);
-                       $rep->TextCol(3, 4,     $myrow2['units'], -2);
-                       $rep->TextCol(4, 5,     $DisplayPrice, -2);
-                       $rep->TextCol(5, 6,     $DisplayDiscount, -2);
-                       $rep->TextCol(6, 7,     $DisplayNet, -2);
+                       if ($Net != 0.0 || !is_service($myrow2['mb_flag']) || !isset($no_zero_lines_amount) || $no_zero_lines_amount == 0)
+                       {
+                               $rep->TextCol(2, 3,     $DisplayQty, -2);
+                               $rep->TextCol(3, 4,     $myrow2['units'], -2);
+                               $rep->TextCol(4, 5,     $DisplayPrice, -2);
+                               $rep->TextCol(5, 6,     $DisplayDiscount, -2);
+                               $rep->TextCol(6, 7,     $DisplayNet, -2);
 -                      }       
++                      }
                        $rep->row = $newrow;
                        //$rep->NewLine(1);
                        if ($rep->row < $rep->bottomMargin + (15 * $rep->lineHeight))
                $DisplayFreight = number_format2($myrow["freight_cost"],$dec);
  
                $rep->row = $rep->bottomMargin + (15 * $rep->lineHeight);
-               $linetype = true;
                $doctype = ST_SALESORDER;
-               include($path_to_root . "/reporting/includes/doctext.inc");
  
-               $rep->TextCol(3, 6, $doc_Sub_total, -2);
+               $rep->TextCol(3, 6, _("Sub-total"), -2);
                $rep->TextCol(6, 7,     $DisplaySubTot, -2);
                $rep->NewLine();
-               $rep->TextCol(3, 6, $doc_Shipping, -2);
+               $rep->TextCol(3, 6, _("Shipping"), -2);
                $rep->TextCol(6, 7,     $DisplayFreight, -2);
                $rep->NewLine();
  
                $DisplayTotal = number_format2($myrow["freight_cost"] + $SubTotal, $dec);
                if ($myrow['tax_included'] == 0) {
-                       $rep->TextCol(3, 6, $doc_TOTAL_ORDER, - 2);
+                       $rep->TextCol(3, 6, _("TOTAL ORDER EX VAT"), - 2);
                        $rep->TextCol(6, 7,     $DisplayTotal, -2);
                        $rep->NewLine();
                }
                $first = true;
                foreach($tax_items as $tax_item)
                {
-                       if ($tax_item['amount'] == 0)
+                       if ($tax_item['Value'] == 0)
                                continue;
                        $DisplayTax = number_format2($tax_item['Value'], $dec);
  
-                       if (isset($suppress_tax_rates) && $suppress_tax_rates == 1)
-                               $tax_type_name = $tax_item['tax_type_name'];
-                       else
-                               $tax_type_name = $tax_item['tax_type_name']." (".$tax_item['rate']."%) ";
+                       $tax_type_name = $tax_item['tax_type_name'];
  
                        if ($myrow['tax_included'])
                        {
                                        $first = false;
                                }
                                else
-                                       $rep->TextCol(3, 7, $doc_Included . " " . $tax_type_name . $doc_Amount . ": " . $DisplayTax, -2);
+                                       $rep->TextCol(3, 7, _("Included") . " " . $tax_type_name . " " . _("Amount"). ": " . $DisplayTax, -2);
                        }
                        else
                        {
  
                $DisplayTotal = number_format2($myrow["freight_cost"] + $SubTotal, $dec);
                $rep->Font('bold');
-               $rep->TextCol(3, 6, $doc_TOTAL_ORDER2, - 2);
+               $rep->TextCol(3, 6, _("TOTAL ORDER VAT INCL."), - 2);
                $rep->TextCol(6, 7,     $DisplayTotal, -2);
                $words = price_in_words($myrow["freight_cost"] + $SubTotal, ST_SALESORDER);
                if ($words != "")
                $rep->Font();
                if ($email == 1)
                {
-                       $rep->End($email, $doc_Invoice_no . " " . $i, $myrow);
+                       $rep->End($email);
                }
        }
        if ($email == 0)
diff --combined reporting/rep110.php
index 06857a8da97770581c4570ac11e61bd45337f5d8,7b9318d0e845ac9ecd2920aa87580bb3d5456b78..856da3240a51fb35ccea69f6d235f177731e354a
@@@ -34,7 -34,7 +34,7 @@@ print_deliveries()
  
  function print_deliveries()
  {
-       global $path_to_root, $packing_slip, $alternative_tax_include_on_docs, $suppress_tax_rates;
+       global $path_to_root, $packing_slip, $alternative_tax_include_on_docs, $suppress_tax_rates, $no_zero_lines_amount;
  
        include_once($path_to_root . "/reporting/includes/pdf_report.inc");
  
        $packing_slip = $_POST['PARAM_3'];
        $comments = $_POST['PARAM_4'];
  
-       if ($from == null)
-               $from = 0;
-       if ($to == null)
-               $to = 0;
+       if (!$from || !$to) return;
        $dec = user_price_dec();
  
        $fno = explode("-", $from);
        $tno = explode("-", $to);
+       $from = min($fno[0], $tno[0]);
+       $to = max($fno[0], $tno[0]);
  
        $cols = array(4, 60, 225, 300, 325, 385, 450, 515);
  
@@@ -74,7 -74,7 +74,7 @@@
                $rep->Info($params, $cols, null, $aligns);
        }
  
-       for ($i = $fno[0]; $i <= $tno[0]; $i++)
+       for ($i = $from; $i <= $to; $i++)
        {
                        if (!exists_customer_trans(ST_CUSTDELIVERY, $i))
                                continue;
                        }
                        else
                                $rep->title = _('DELIVERY NOTE');
-                       $contacts = get_branch_contacts($branch['branch_code'], 'delivery', $branch['debtor_no']);
+                       $contacts = get_branch_contacts($branch['branch_code'], 'delivery', $branch['debtor_no'], false);
                        $rep->SetCommonData($myrow, $branch, $sales_order, '', ST_CUSTDELIVERY, $contacts);
                        $rep->NewPage();
  
                        {
                                if ($myrow2["quantity"] == 0)
                                        continue;
--                                      
++
                                $Net = round2(((1 - $myrow2["discount_percent"]) * $myrow2["unit_price"] * $myrow2["quantity"]),
                                   user_price_dec());
                                $SubTotal += $Net;
                                $rep->TextColLines(1, 2, $myrow2['StockDescription'], -2);
                                $newrow = $rep->row;
                                $rep->row = $oldrow;
-                               $rep->TextCol(2, 3,     $DisplayQty, -2);
-                               $rep->TextCol(3, 4,     $myrow2['units'], -2);
-                               if ($packing_slip == 0)
+                               if ($Net != 0.0  || !is_service($myrow2['mb_flag']) || !isset($no_zero_lines_amount) || $no_zero_lines_amount == 0)
 -                              {                       
 +                              {
-                                       $rep->TextCol(4, 5,     $DisplayPrice, -2);
-                                       $rep->TextCol(5, 6,     $DisplayDiscount, -2);
-                                       $rep->TextCol(6, 7,     $DisplayNet, -2);
-                               }       
+                                       $rep->TextCol(2, 3,     $DisplayQty, -2);
+                                       $rep->TextCol(3, 4,     $myrow2['units'], -2);
+                                       if ($packing_slip == 0)
+                                       {
+                                               $rep->TextCol(4, 5,     $DisplayPrice, -2);
+                                               $rep->TextCol(5, 6,     $DisplayDiscount, -2);
+                                               $rep->TextCol(6, 7,     $DisplayNet, -2);
+                                       }
 -                              }       
++                              }
                                $rep->row = $newrow;
                                //$rep->NewLine(1);
                                if ($rep->row < $rep->bottomMargin + (15 * $rep->lineHeight))
                                        $rep->NewPage();
                        }
  
-                       $comments = get_comments(ST_CUSTDELIVERY, $i);
-                       if ($comments && db_num_rows($comments))
+                       $memo = get_comments_string(ST_CUSTDELIVERY, $i);
+                       if ($memo != "")
                        {
                                $rep->NewLine();
-                       while ($comment=db_fetch($comments))
-                               $rep->TextColLines(0, 6, $comment['memo_'], -2);
+                               $rep->TextColLines(1, 5, $memo, -2);
                        }
  
                        $DisplaySubTot = number_format2($SubTotal,$dec);
                        $DisplayFreight = number_format2($myrow["ov_freight"],$dec);
  
                $rep->row = $rep->bottomMargin + (15 * $rep->lineHeight);
-                       $linetype = true;
                        $doctype=ST_CUSTDELIVERY;
-                       include($path_to_root . "/reporting/includes/doctext.inc");
                        if ($packing_slip == 0)
                        {
-                               $rep->TextCol(3, 6, $doc_Sub_total, -2);
+                               $rep->TextCol(3, 6, _("Sub-total"), -2);
                                $rep->TextCol(6, 7,     $DisplaySubTot, -2);
                                $rep->NewLine();
-                               $rep->TextCol(3, 6, $doc_Shipping, -2);
+                               $rep->TextCol(3, 6, _("Shipping"), -2);
                                $rep->TextCol(6, 7,     $DisplayFreight, -2);
                                $rep->NewLine();
                                $tax_items = get_trans_tax_details(ST_CUSTDELIVERY, $i);
                                                        $first = false;
                                        }
                                        else
-                                                       $rep->TextCol(3, 7, $doc_Included . " " . $tax_type_name . $doc_Amount . ": " . $DisplayTax, -2);
+                                                       $rep->TextCol(3, 7, _("Included") . " " . $tax_type_name . _("Amount") . ": " . $DisplayTax, -2);
                                        }
                                else
                                {
                                $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);
+                               $rep->TextCol(3, 6, _("TOTAL DELIVERY INCL. VAT"), - 2);
                                $rep->TextCol(6, 7,     $DisplayTotal, -2);
                                $words = price_in_words($myrow['Total'], ST_CUSTDELIVERY);
                                if ($words != "")
                        }       
                        if ($email == 1)
                        {
-                               $rep->End($email, $doc_Delivery_no . " " . $myrow['reference'], $myrow, ST_CUSTDELIVERY);
+                               $rep->End($email);
                        }
        }
        if ($email == 0)
diff --combined reporting/rep111.php
index 02285fca2452857bf62adac6119761a67dfd3a39,2662fca59d1221403d0a4cdff2785a063b24c8ac..be0c48c0c55a4007b23c22f4a0874918ac7926ba
@@@ -23,6 -23,7 +23,7 @@@ include_once($path_to_root . "/includes
  include_once($path_to_root . "/includes/date_functions.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 . "/taxes/tax_calc.inc");
  
  //----------------------------------------------------------------------------------------------------
  
@@@ -30,7 -31,7 +31,7 @@@ print_sales_quotations()
  
  function print_sales_quotations()
  {
-       global $path_to_root, $print_as_quote, $print_invoice_no;
+       global $path_to_root, $print_as_quote, $print_invoice_no, $no_zero_lines_amount;
  
        include_once($path_to_root . "/reporting/includes/pdf_report.inc");
  
                        $rep->Info($params, $cols, null, $aligns);
                }
                $rep->title = _("SALES QUOTATION");
-               $contacts = get_branch_contacts($branch['branch_code'], 'order', $branch['debtor_no']);
+               $contacts = get_branch_contacts($branch['branch_code'], 'order', $branch['debtor_no'], false);
                $rep->SetCommonData($myrow, $branch, $myrow, $baccount, ST_SALESQUOTE, $contacts);
                //$rep->headerFunc = 'Header2';
                $rep->NewPage();
  
                $result = get_sales_order_details($i, ST_SALESQUOTE);
                $SubTotal = 0;
+               $items = $prices = array();
                while ($myrow2=db_fetch($result))
                {
                        $Net = round2(((1 - $myrow2["discount_percent"]) * $myrow2["unit_price"] * $myrow2["quantity"]),
                           user_price_dec());
+                       $prices[] = $Net;
+                       $items[] = $myrow2['stk_code'];
                        $SubTotal += $Net;
                        $DisplayPrice = number_format2($myrow2["unit_price"],$dec);
                        $DisplayQty = number_format2($myrow2["quantity"],get_qty_dec($myrow2['stk_code']));
                        $rep->TextColLines(1, 2, $myrow2['description'], -2);
                        $newrow = $rep->row;
                        $rep->row = $oldrow;
-                       $rep->TextCol(2, 3,     $DisplayQty, -2);
-                       $rep->TextCol(3, 4,     $myrow2['units'], -2);
-                       $rep->TextCol(4, 5,     $DisplayPrice, -2);
-                       $rep->TextCol(5, 6,     $DisplayDiscount, -2);
-                       $rep->TextCol(6, 7,     $DisplayNet, -2);
+                       if ($Net != 0.0 || !is_service($myrow2['mb_flag']) || !isset($no_zero_lines_amount) || $no_zero_lines_amount == 0)
+                       {
+                               $rep->TextCol(2, 3,     $DisplayQty, -2);
+                               $rep->TextCol(3, 4,     $myrow2['units'], -2);
+                               $rep->TextCol(4, 5,     $DisplayPrice, -2);
+                               $rep->TextCol(5, 6,     $DisplayDiscount, -2);
+                               $rep->TextCol(6, 7,     $DisplayNet, -2);
 -                      }       
++                      }
                        $rep->row = $newrow;
                        //$rep->NewLine(1);
                        if ($rep->row < $rep->bottomMargin + (15 * $rep->lineHeight))
                $DisplaySubTot = number_format2($SubTotal,$dec);
                $DisplayFreight = number_format2($myrow["freight_cost"],$dec);
  
--              $rep->row = $rep->bottomMargin + (15 * $rep->lineHeight);
-               $linetype = true;
                $doctype = ST_SALESQUOTE;
-               include($path_to_root . "/reporting/includes/doctext.inc");
  
-               $rep->TextCol(3, 6, $doc_Sub_total, -2);
+               $rep->TextCol(3, 6, _("Sub-total"), -2);
                $rep->TextCol(6, 7,     $DisplaySubTot, -2);
                $rep->NewLine();
-               $rep->TextCol(3, 6, $doc_Shipping, -2);
+               $rep->TextCol(3, 6, _("Shipping"), -2);
                $rep->TextCol(6, 7,     $DisplayFreight, -2);
                $rep->NewLine();
+               $DisplayTotal = number_format2($myrow["freight_cost"] + $SubTotal, $dec);
+               if ($myrow['tax_included'] == 0) {
+                       $rep->TextCol(3, 6, _("TOTAL ORDER EX VAT"), - 2);
+                       $rep->TextCol(6, 7,     $DisplayTotal, -2);
+                       $rep->NewLine();
+               }
+               $tax_items = get_tax_for_items($items, $prices, $myrow["freight_cost"],
+                 $myrow['tax_group_id'], $myrow['tax_included'],  null);
+               $first = true;
+               foreach($tax_items as $tax_item)
+               {
+                       if ($tax_item['Value'] == 0)
+                               continue;
+                       $DisplayTax = number_format2($tax_item['Value'], $dec);
+                       $tax_type_name = $tax_item['tax_type_name'];
+                       if ($myrow['tax_included'])
+                       {
+                               if (isset($alternative_tax_include_on_docs) && $alternative_tax_include_on_docs == 1)
+                               {
+                                       if ($first)
+                                       {
+                                               $rep->TextCol(3, 6, _("Total Tax Excluded"), -2);
+                                               $rep->TextCol(6, 7,     number_format2($sign*$tax_item['net_amount'], $dec), -2);
+                                               $rep->NewLine();
+                                       }
+                                       $rep->TextCol(3, 6, $tax_type_name, -2);
+                                       $rep->TextCol(6, 7,     $DisplayTax, -2);
+                                       $first = false;
+                               }
+                               else
+                                       $rep->TextCol(3, 7, _("Included") . " " . $tax_type_name . " " . _("Amount") . ": " . $DisplayTax, -2);
+                       }
+                       else
+                       {
+                               $SubTotal += $tax_item['Value'];
+                               $rep->TextCol(3, 6, $tax_type_name, -2);
+                               $rep->TextCol(6, 7,     $DisplayTax, -2);
+                       }
+                       $rep->NewLine();
+               }
+               $rep->NewLine();
                $DisplayTotal = number_format2($myrow["freight_cost"] + $SubTotal, $dec);
                $rep->Font('bold');
-               if ($myrow['tax_included'] == 0)
-                       $rep->TextCol(3, 6, $doc_TOTAL_ORDER, - 2);
-               else    
-                       $rep->TextCol(3, 6, $doc_TOTAL_ORDER2, - 2);
+               $rep->TextCol(3, 6, _("TOTAL ORDER VAT INCL."), - 2);
                $rep->TextCol(6, 7,     $DisplayTotal, -2);
                $words = price_in_words($myrow["freight_cost"] + $SubTotal, ST_SALESQUOTE);
                if ($words != "")
                {
                        if ($print_invoice_no == 1)
                                $myrow['reference'] = $i;
-                       $rep->End($email, $doc_Invoice_no . " " . $myrow['reference'], $myrow);
+                       $rep->End($email);
                }
        }
        if ($email == 0)
diff --combined reporting/rep112.php
index b5238a2673769c14432e0dec3df9af9d55443976,ba6c94653b4571ccf24f83b4ff94a1294ad7efd4..c510160a1566486adaae4f7f0a74e27917c1a148
@@@ -71,14 -71,14 +71,14 @@@ function print_receipts(
        $currency = $_POST['PARAM_2'];
        $comments = $_POST['PARAM_3'];
  
-       if ($from == null)
-               $from = 0;
-       if ($to == null)
-               $to = 0;
+       if (!$from || !$to) return;
        $dec = user_price_dec();
  
        $fno = explode("-", $from);
        $tno = explode("-", $to);
+       $from = min($fno[0], $tno[0]);
+       $to = max($fno[0], $tno[0]);
  
        $cols = array(4, 85, 150, 225, 275, 360, 450, 515);
  
        $rep->Font();
        $rep->Info($params, $cols, null, $aligns);
  
-       for ($i = $fno[0]; $i <= $tno[0]; $i++)
+       for ($i = $from; $i <= $to; $i++)
        {
                if ($fno[0] == $tno[0])
                        $types = array($fno[1]);
                else
-                       $types = array(ST_BANKDEPOSIT, ST_CUSTPAYMENT, ST_CUSTCREDIT);
+                       $types = array(ST_BANKDEPOSIT, ST_CUSTPAYMENT);
                foreach ($types as $j)
                {
                        $myrow = get_receipt($j, $i);
                        if (!$myrow)
--                              continue;                       
-                       $baccount = get_default_bank_account($myrow['curr_code']);
-                       $params['bankaccount'] = $baccount['id'];
++                              continue;
+                       $res = get_bank_trans($j, $i);
+                       $baccount = db_fetch($res);
+                       $params['bankaccount'] = $baccount['bank_act'];
  
                        $rep->title = _('RECEIPT');
                        $contacts = get_branch_contacts($myrow['branch_code'], 'invoice', $myrow['debtor_no']);
                        $rep->NewPage();
                        $result = get_allocations_for_receipt($myrow['debtor_no'], $myrow['type'], $myrow['trans_no']);
  
-                       $linetype = true;
                        $doctype = ST_CUSTPAYMENT;
-                       include($path_to_root . "/reporting/includes/doctext.inc");
  
                        $total_allocated = 0;
-                       $rep->TextCol(0, 4,     $doc_Towards, -2);
+                       $rep->TextCol(0, 4,     _("As advance / full / part / payment towards:"), -2);
                        $rep->NewLine(2);
--                      
++
                        while ($myrow2=db_fetch($result))
                        {
                                $rep->TextCol(0, 1,     $systypes_array[$myrow2['type']], -2);
                                        $rep->NewPage();
                        }
  
+                       $memo = get_comments_string($j, $i);
+                       if ($memo != "")
+                       {
+                               $rep->NewLine();
+                               $rep->TextColLines(1, 5, $memo, -2);
+                       }
                        $rep->row = $rep->bottomMargin + (15 * $rep->lineHeight);
  
-                       $rep->TextCol(3, 6, $doc_Total_Allocated, -2);
+                       $rep->TextCol(3, 6, _("Total Allocated"), -2);
                        $rep->AmountCol(6, 7, $total_allocated, $dec, -2);
                        $rep->NewLine();
-                       $rep->TextCol(3, 6, $doc_Left_To_Allocate, -2);
+                       $rep->TextCol(3, 6, _("Left to Allocate"), -2);
                        $rep->AmountCol(6, 7, $myrow['Total'] - $total_allocated, $dec, -2);
                        $rep->NewLine();
                        $rep->Font('bold');
-                       $rep->TextCol(3, 6, $doc_Total_Payment, - 2);
+                       $rep->TextCol(3, 6, _("TOTAL RECEIPT"), - 2);
                        $rep->AmountCol(6, 7, $myrow['Total'], $dec, -2);
                        $words = price_in_words($myrow['Total'], ST_CUSTPAYMENT);
                        if ($words != "")
                        {
                                $rep->NewLine(1);
                                $rep->TextCol(0, 7, $myrow['curr_code'] . ": " . $words, - 2);
--                      }       
++                      }
                        $rep->Font();
                        $rep->NewLine();
-                       $rep->TextCol(6, 7, $doc_Received, - 2);
+                       $rep->TextCol(6, 7, _("Received / Sign"), - 2);
                        $rep->NewLine();
-                       $rep->TextCol(0, 2, $doc_by_Cheque, - 2);
+                       $rep->TextCol(0, 2, _("By Cash / Cheque* / Draft No."), - 2);
                        $rep->TextCol(2, 4, "______________________________", - 2);
-                       $rep->TextCol(4, 5, $doc_Dated, - 2);
+                       $rep->TextCol(4, 5, _("Dated"), - 2);
                        $rep->TextCol(5, 6, "__________________", - 2);
                        $rep->NewLine(1);
-                       $rep->TextCol(0, 2, $doc_Drawn, - 2);
+                       $rep->TextCol(0, 2, _("Drawn on Bank"), - 2);
                        $rep->TextCol(2, 4, "______________________________", - 2);
-                       $rep->TextCol(4, 5, $doc_Drawn_Branch, - 2);
+                       $rep->TextCol(4, 5, _("Branch"), - 2);
                        $rep->TextCol(5, 6, "__________________", - 2);
                        $rep->TextCol(6, 7, "__________________");
--              }       
++              }
        }
        $rep->End();
  }
diff --combined reporting/rep202.php
index 2eb27559689efe240c53f395c0a60089ea79f773,6bbf6d92c02fb1f53f13d0a559bfe49a6b373b88..5901260596b53b878a93ff35f6fbdbbb1bb163b2
@@@ -29,14 -29,19 +29,19 @@@ print_aged_supplier_analysis()
  
  //----------------------------------------------------------------------------------------------------
  
- function get_invoices($supplier_id, $to)
+ function get_invoices($supplier_id, $to, $all=true)
  {
        $todate = date2sql($to);
        $PastDueDays1 = get_company_pref('past_due_days');
        $PastDueDays2 = 2 * $PastDueDays1;
  
        // Revomed allocated from sql
-     $value = "(".TB_PREF."supp_trans.ov_amount + ".TB_PREF."supp_trans.ov_gst + ".TB_PREF."supp_trans.ov_discount)";
+       if ($all)
+       $value = "(".TB_PREF."supp_trans.ov_amount + ".TB_PREF."supp_trans.ov_gst + ".TB_PREF."supp_trans.ov_discount)";
 -    else      
++    else
+       $value = "IF (".TB_PREF."supp_trans.type=".ST_SUPPINVOICE." OR ".TB_PREF."supp_trans.type=".ST_BANKDEPOSIT.", 
+       (".TB_PREF."supp_trans.ov_amount + ".TB_PREF."supp_trans.ov_gst + ".TB_PREF."supp_trans.ov_discount - ".TB_PREF."supp_trans.alloc),
+       (".TB_PREF."supp_trans.ov_amount + ".TB_PREF."supp_trans.ov_gst + ".TB_PREF."supp_trans.ov_discount + ".TB_PREF."supp_trans.alloc))";
        $due = "IF (".TB_PREF."supp_trans.type=".ST_SUPPINVOICE." OR ".TB_PREF."supp_trans.type=".ST_SUPPCREDIT.",".TB_PREF."supp_trans.due_date,".TB_PREF."supp_trans.tran_date)";
        $sql = "SELECT ".TB_PREF."supp_trans.type,
                ".TB_PREF."supp_trans.reference,
                        AND ".TB_PREF."suppliers.supplier_id = ".TB_PREF."supp_trans.supplier_id
                        AND ".TB_PREF."supp_trans.supplier_id = $supplier_id
                        AND ".TB_PREF."supp_trans.tran_date <= '$todate'
-                       AND ABS(".TB_PREF."supp_trans.ov_amount + ".TB_PREF."supp_trans.ov_gst + ".TB_PREF."supp_trans.ov_discount) > 0.004
-                       ORDER BY ".TB_PREF."supp_trans.tran_date";
+                       AND ABS(".TB_PREF."supp_trans.ov_amount + ".TB_PREF."supp_trans.ov_gst + ".TB_PREF."supp_trans.ov_discount) > ".FLOAT_COMP_DELTA." ";
+       if (!$all)
+               $sql .= "AND ABS(".TB_PREF."supp_trans.ov_amount + ".TB_PREF."supp_trans.ov_gst + ".TB_PREF."supp_trans.ov_discount) - ".TB_PREF."supp_trans.alloc > ".FLOAT_COMP_DELTA." ";  
+       $sql .= "ORDER BY ".TB_PREF."supp_trans.tran_date";
  
  
        return db_query($sql, "The supplier details could not be retrieved");
@@@ -70,11 -77,12 +77,12 @@@ function print_aged_supplier_analysis(
      $to = $_POST['PARAM_0'];
      $fromsupp = $_POST['PARAM_1'];
      $currency = $_POST['PARAM_2'];
-       $summaryOnly = $_POST['PARAM_3'];
-     $no_zeros = $_POST['PARAM_4'];
-     $graphics = $_POST['PARAM_5'];
-     $comments = $_POST['PARAM_6'];
-       $destination = $_POST['PARAM_7'];
+       $show_all = $_POST['PARAM_3'];
+       $summaryOnly = $_POST['PARAM_4'];
+     $no_zeros = $_POST['PARAM_5'];
+     $graphics = $_POST['PARAM_6'];
+     $comments = $_POST['PARAM_7'];
+       $destination = $_POST['PARAM_8'];
  
        if ($destination)
                include_once($path_to_root . "/reporting/includes/excel_report.inc");
@@@ -86,7 -94,7 +94,7 @@@
                $pg = new graph();
        }
  
-       if ($fromsupp == ALL_NUMERIC)
+       if ($fromsupp == ALL_TEXT)
                $from = _('All');
        else
                $from = get_supplier_name($fromsupp);
  
        if ($no_zeros) $nozeros = _('Yes');
        else $nozeros = _('No');
+       if ($show_all) $show = _('Yes');
+       else $show = _('No');
  
        $PastDueDays1 = get_company_pref('past_due_days');
        $PastDueDays2 = 2 * $PastDueDays1;
                                2 => array('text' => _('Supplier'), 'from' => $from, 'to' => ''),
                                3 => array('text' => _('Currency'),'from' => $currency,'to' => ''),
                                4 => array('text' => _('Type'), 'from' => $summary,'to' => ''),
-                               5 => array('text' => _('Suppress Zeros'), 'from' => $nozeros, 'to' => ''));
+                     5 => array('text' => _('Show Also Allocated'), 'from' => $show, 'to' => ''),              
+                               6 => array('text' => _('Suppress Zeros'), 'from' => $nozeros, 'to' => ''));
  
        if ($convert)
                $headers[2] = _('currency');
        $pastdue2 = _('Over') . " " . $PastDueDays2 . " " . _('Days');
  
        $sql = "SELECT supplier_id, supp_name AS name, curr_code FROM ".TB_PREF."suppliers";
-       if ($fromsupp != ALL_NUMERIC)
+       if ($fromsupp != ALL_TEXT)
                $sql .= " WHERE supplier_id=".db_escape($fromsupp);
        $sql .= " ORDER BY supp_name";
        $result = db_query($sql, "The suppliers could not be retrieved");
                if ($convert) $rate = get_exchange_rate_from_home_currency($myrow['curr_code'], $to);
                else $rate = 1.0;
  
-               $supprec = get_supplier_details($myrow['supplier_id'], $to);
-               foreach ($supprec as $i => $value)
-                       $supprec[$i] *= $rate;
+               $supprec = get_supplier_details($myrow['supplier_id'], $to, $show_all);
+               if (!$supprec)
+                       continue;
+               $supprec['Balance'] *= $rate;
+               $supprec['Due'] *= $rate;
+               $supprec['Overdue1'] *= $rate;
+               $supprec['Overdue2'] *= $rate;
  
                $str = array($supprec["Balance"] - $supprec["Due"],
                        $supprec["Due"]-$supprec["Overdue1"],
                        $supprec["Overdue2"],
                        $supprec["Balance"]);
  
-               if ($no_zeros && array_sum($str) == 0) continue;
+               if ($no_zeros && floatcmp(array_sum($str), 0) == 0) continue;
  
                $rep->fontSize += 2;
                $rep->TextCol(0, 2,     $myrow['name']);
                $rep->NewLine(1, 2);
                if (!$summaryOnly)
                {
-                       $res = get_invoices($myrow['supplier_id'], $to);
+                       $res = get_invoices($myrow['supplier_id'], $to, $show_all);
                if (db_num_rows($res)==0)
                                continue;
                $rep->Line($rep->row + 4);
diff --combined reporting/rep209.php
index 51156d73c65b9bbc6440dd9486eef07d64e934bb,c7eed103c8092c3a15968f0185a3f04b70f8b778..1131a350464478182e6962f7ad57ceccc7042dfd
@@@ -34,7 -34,7 +34,7 @@@ print_po()
  function get_po($order_no)
  {
        $sql = "SELECT ".TB_PREF."purch_orders.*, ".TB_PREF."suppliers.supp_name,  "
 -              .TB_PREF."suppliers.supp_account_no,".TB_PREF."suppliers.tax_included,
 +              .TB_PREF."suppliers.supp_account_no,".TB_PREF."suppliers.tax_included,".TB_PREF."suppliers.tax_algorithm,
                ".TB_PREF."suppliers.curr_code, ".TB_PREF."suppliers.payment_terms, ".TB_PREF."locations.location_name,
                ".TB_PREF."suppliers.address, ".TB_PREF."suppliers.contact, ".TB_PREF."suppliers.tax_group_id
                FROM ".TB_PREF."purch_orders, ".TB_PREF."suppliers, ".TB_PREF."locations
@@@ -58,7 -58,7 +58,7 @@@ function get_po_details($order_no
  
  function print_po()
  {
-       global $path_to_root;
+       global $path_to_root, $show_po_item_codes;
  
        include_once($path_to_root . "/reporting/includes/pdf_report.inc");
  
                        $DisplayPrice = price_decimal_format($myrow2["unit_price"],$dec2);
                        $DisplayQty = number_format2($myrow2["quantity_ordered"],get_qty_dec($myrow2['item_code']));
                        $DisplayNet = number_format2($Net,$dec);
-                       //$rep->TextCol(0, 1,   $myrow2['item_code'], -2);
-                       $rep->TextCol(0, 2,     $myrow2['description'], -2);
+                       if ($show_po_item_codes) {
+                               $rep->TextCol(0, 1,     $myrow2['item_code'], -2);
+                               $rep->TextCol(1, 2,     $myrow2['description'], -2);
+                       } else
+                               $rep->TextCol(0, 2,     $myrow2['description'], -2);
                        $rep->TextCol(2, 3,     sql2date($myrow2['delivery_date']), -2);
                        $rep->TextCol(3, 4,     $DisplayQty, -2);
                        $rep->TextCol(4, 5,     $myrow2['units'], -2);
                $DisplaySubTot = number_format2($SubTotal,$dec);
  
                $rep->row = $rep->bottomMargin + (15 * $rep->lineHeight);
-               $linetype = true;
                $doctype = ST_PURCHORDER;
-               include($path_to_root . "/reporting/includes/doctext.inc");
  
-               $rep->TextCol(3, 6, $doc_Sub_total, -2);
+               $rep->TextCol(3, 6, _("Sub-total"), -2);
                $rep->TextCol(6, 7,     $DisplaySubTot, -2);
                $rep->NewLine();
  
                $tax_items = get_tax_for_items($items, $prices, 0,
 -                $myrow['tax_group_id'], $myrow['tax_included'],  null);
 +                $myrow['tax_group_id'], $myrow['tax_included'],  null, $myrow['tax_algorithm']);
                $first = true;
                foreach($tax_items as $tax_item)
                {
-                       if ($tax_item['amount'] == 0)
+                       if ($tax_item['Value'] == 0)
                                continue;
                        $DisplayTax = number_format2($tax_item['Value'], $dec);
  
 -                      $tax_type_name = $tax_item['tax_type_name'];
 +                      if (isset($suppress_tax_rates) && $suppress_tax_rates == 1)
 +                              $tax_type_name = $tax_item['tax_type_name'];
 +                      else
 +                              $tax_type_name = $tax_item['tax_type_name']." (".$tax_item['rate']."%) ";
  
                        if ($myrow['tax_included'])
                        {
                                        $first = false;
                                }
                                else
-                                       $rep->TextCol(3, 7, $doc_Included . " " . $tax_type_name . $doc_Amount . ": " . $DisplayTax, -2);
+                                       $rep->TextCol(3, 7, _("Included") . " " . $tax_type_name . _("Amount") . ": " . $DisplayTax, -2);
                        }
                        else
                        {
                $rep->NewLine();
                $DisplayTotal = number_format2($SubTotal, $dec);
                $rep->Font('bold');
-               $rep->TextCol(3, 6, $doc_TOTAL_PO, - 2);
+               $rep->TextCol(3, 6, _("TOTAL PO"), - 2);
                $rep->TextCol(6, 7,     $DisplayTotal, -2);
                $words = price_in_words($SubTotal, ST_PURCHORDER);
                if ($words != "")
  
                        if ($myrow['reference'] == "")
                                $myrow['reference'] = $myrow['order_no'];
-                       $rep->End($email, $doc_Order_no . " " . $myrow['reference'], $myrow);
+                       $rep->End($email);
                }
        }
        if ($email == 0)
diff --combined reporting/rep210.php
index 7f6b53b65e20c5e23e3b65faec3a36a629b20af7,136f0d2c9fe355b542fc8dd06cbad64d5f112d27..9d8b8d7ddfbf9b0a0c71d3a3115fcf38631a7412
@@@ -71,14 -71,14 +71,14 @@@ function print_remittances(
        $email = $_POST['PARAM_3'];
        $comments = $_POST['PARAM_4'];
  
-       if ($from == null)
-               $from = 0;
-       if ($to == null)
-               $to = 0;
+       if (!$from || !$to) return;
        $dec = user_price_dec();
  
        $fno = explode("-", $from);
        $tno = explode("-", $to);
+       $from = min($fno[0], $tno[0]);
+       $to = max($fno[0], $tno[0]);
  
        $cols = array(4, 85, 150, 225, 275, 360, 450, 515);
  
@@@ -98,7 -98,7 +98,7 @@@
                $rep->Info($params, $cols, null, $aligns);
        }
  
-       for ($i = $fno[0]; $i <= $tno[0]; $i++)
+       for ($i = $from; $i <= $to; $i++)
        {
                if ($fno[0] == $tno[0])
                        $types = array($fno[1]);
                {
                        $myrow = get_remittance($j, $i);
                        if (!$myrow)
--                              continue;                       
-                       $baccount = get_default_bank_account($myrow['curr_code']);
-                       $params['bankaccount'] = $baccount['id'];
++                              continue;
+                       $res = get_bank_trans($j, $i);
+                       $baccount = db_fetch($res);
+                       $params['bankaccount'] = $baccount['bank_act'];
  
                        if ($email == 1)
                        {
                        $rep->NewPage();
                        $result = get_allocations_for_remittance($myrow['supplier_id'], $myrow['type'], $myrow['trans_no']);
  
-                       $linetype = true;
                        $doctype = ST_SUPPAYMENT;
-                       include($path_to_root . "/reporting/includes/doctext.inc");
  
                        $total_allocated = 0;
-                       $rep->TextCol(0, 4,     $doc_Towards, -2);
+                       $rep->TextCol(0, 4,     _("As advance / full / part / payment towards:"), -2);
                        $rep->NewLine(2);
--                      
++
                        while ($myrow2=db_fetch($result))
                        {
                                $rep->TextCol(0, 1,     $systypes_array[$myrow2['type']], -2);
                                        $rep->NewPage();
                        }
  
+                       $memo = get_comments_string($j, $i);
+                       if ($memo != "")
+                       {
+                               $rep->NewLine();
+                               $rep->TextColLines(1, 5, $memo, -2);
+                       }
                        $rep->row = $rep->bottomMargin + (15 * $rep->lineHeight);
  
-                       $rep->TextCol(3, 6, $doc_Total_Allocated, -2);
+                       $rep->TextCol(3, 6, _("Total Allocated"), -2);
                        $rep->AmountCol(6, 7, $total_allocated, $dec, -2);
                        $rep->NewLine();
-                       $rep->TextCol(3, 6, $doc_Left_To_Allocate, -2);
+                       $rep->TextCol(3, 6, _("Left to Allocate"), -2);
                        $myrow['Total'] *= -1;
                        $rep->AmountCol(6, 7, $myrow['Total'] - $total_allocated, $dec, -2);
                        $rep->NewLine();
                        $rep->Font('bold');
-                       $rep->TextCol(3, 6, $doc_Total_Payment, - 2);
+                       $rep->TextCol(3, 6, _("TOTAL REMITTANCE"), - 2);
                        $rep->AmountCol(6, 7, $myrow['Total'], $dec, -2);
                        $words = price_in_words($myrow['Total'], ST_SUPPAYMENT);
                        if ($words != "")
                        {
                                $rep->NewLine(2);
                                $rep->TextCol(1, 7, $myrow['curr_code'] . ": " . $words, - 2);
--                      }       
++                      }
                        $rep->Font();
                        if ($email == 1)
                        {
                                $myrow['DebtorName'] = $myrow['supp_name'];
-                               $rep->End($email, $doc_Order_no . " " . $myrow['reference'], $myrow);
+                               $rep->End($email);
                        }
--              }       
++              }
        }
        if ($email == 0)
                $rep->End();
diff --combined reporting/rep305.php
index 6711d9b7f4257bb7f1a8e42b9432a671760a478f,1471ae66c1e46c59862948bf4f0a755e4b43ab81..3fdef19ed092cc2e6bb77db024158198afa3f707
@@@ -33,24 -33,47 +33,47 @@@ function getTransactions($from, $to
  {
        $from = date2sql($from);
        $to = date2sql($to);
--      
-       $sql = "SELECT DISTINCT ".TB_PREF."grn_batch.supplier_id, 
++
+       $sql = "SELECT ".TB_PREF."grn_batch.id batch_no,
+                       ".TB_PREF."grn_batch.supplier_id, 
              ".TB_PREF."purch_order_details.*,
-             ".TB_PREF."stock_master.description, ".TB_PREF."stock_master.inactive
+             ".TB_PREF."stock_master.description,
+                       ".TB_PREF."grn_items.qty_recd,
+                       ".TB_PREF."grn_items.quantity_inv,
+                       ".TB_PREF."grn_items.id grn_item_id
          FROM ".TB_PREF."stock_master,
              ".TB_PREF."purch_order_details,
-             ".TB_PREF."grn_batch
+             ".TB_PREF."grn_batch,
+                       ".TB_PREF."grn_items 
          WHERE ".TB_PREF."stock_master.stock_id=".TB_PREF."purch_order_details.item_code
          AND ".TB_PREF."grn_batch.purch_order_no=".TB_PREF."purch_order_details.order_no
-         AND ".TB_PREF."purch_order_details.quantity_received>0
+               AND ".TB_PREF."grn_batch.id = ".TB_PREF."grn_items.grn_batch_id 
+               AND ".TB_PREF."grn_items.po_detail_item = ".TB_PREF."purch_order_details.po_detail_item
+         AND ".TB_PREF."grn_items.qty_recd>0
          AND ".TB_PREF."grn_batch.delivery_date>='$from'
          AND ".TB_PREF."grn_batch.delivery_date<='$to'
          ORDER BY ".TB_PREF."stock_master.stock_id, ".TB_PREF."grn_batch.delivery_date";       
--      
++
      return db_query($sql,"No transactions were returned");
  
  }
  
+ function getSuppInvDetails($grn_item_id)
+ {
+       $sql = "SELECT
+                       ".TB_PREF."supp_invoice_items.supp_trans_no inv_no,
+                       ".TB_PREF."supp_invoice_items.quantity inv_qty,
+                       ".TB_PREF."supp_invoice_items.unit_price inv_price
+                       FROM ".TB_PREF."grn_items, ".TB_PREF."supp_invoice_items
+                       WHERE ".TB_PREF."grn_items.id = ".TB_PREF."supp_invoice_items.grn_item_id
+                       AND ".TB_PREF."grn_items.po_detail_item = ".TB_PREF."supp_invoice_items.po_detail_item_id
+                       AND ".TB_PREF."grn_items.item_code = ".TB_PREF."supp_invoice_items.stock_id
+                       AND ".TB_PREF."supp_invoice_items.grn_item_id = ".$grn_item_id."
+                       ORDER BY ".TB_PREF."supp_invoice_items.id asc";
+       return db_query($sql,"No transactions were returned");
+ }
  //----------------------------------------------------------------------------------------------------
  
  function print_grn_valuation()
  
      $dec = user_price_dec();
  
-       $cols = array(0, 75, 225, 275, 345, 390, 445,   515);
-       $headers = array(_('Stock ID'), _('Description'), _('PO No'), _('Qty Received'), _('Unit Price'), _('Actual Price'), _('Total'));
+       $cols = array(0, 75, 225, 260, 295, 330, 370, 410, 455, 515);
+       $headers = array(_('Stock ID'), _('Description'), _('PO No'), _('GRN')."#", _('Inv')."#", _('Qty'), _('Inv Price'), _('PO Price'), _('Total'));
  
-       $aligns = array('left', 'left', 'left', 'right', 'right', 'right', 'right');
+       $aligns = array('left', 'left', 'left', 'left', 'left', 'right', 'right', 'right', 'right');
  
      $params =   array(        0 => $comments,
                                    1 => array('text' => _('Period'),'from' => $from, 'to' => $to));
                                $rep->Line($rep->row  - 4);
                                $rep->NewLine(2);
                                $rep->TextCol(0, 3, _('Total'));
-                               $rep->AmountCol(3, 4, $qtotal, $qdec);
-                               $rep->AmountCol(6, 7, $total, $dec);
+                               $rep->AmountCol(5, 6, $qtotal, $qdec);
+                               $rep->AmountCol(8, 9, $total, $dec);
                                $rep->NewLine();
                                $total = $qtotal = 0;
                        }
  
                $rep->NewLine();
                $rep->TextCol(0, 1, $trans['item_code']);
-               $rep->TextCol(1, 2, $trans['description'].($trans['inactive']==1 ? " ("._("Inactive").")" : ""), -1);
+               $rep->TextCol(1, 2, $trans['description']);
                $rep->TextCol(2, 3, $trans['order_no']);
                $qdec = get_qty_dec($trans['item_code']);
-               $rep->AmountCol(3, 4, $trans['quantity_received'], $qdec);
-               $rep->AmountCol(4, 5, $trans['unit_price'], $dec);
-               $rep->AmountCol(5, 6, $trans['act_price'], $dec);
-               $amt = round2($trans['quantity_received'] * $trans['act_price'], $dec);
-               $rep->AmountCol(6, 7, $amt, $dec);
-               $total += $amt;
-               $qtotal += $trans['quantity_received'];
-               $grandtotal += $amt;
+               $rep->TextCol(3, 4, $trans['batch_no']);
 -              
++
+               if ($trans['quantity_inv'])
+               {
+                       $suppinv = getSuppInvDetails($trans['grn_item_id']);
+                       while ($inv=db_fetch($suppinv))
+                       {       
+                               $inv['inv_price'] *= $rate;
+                               $rep->TextCol(4, 5, $inv['inv_no']);
+                               $rep->AmountCol(5, 6, $inv['inv_qty'], $qdec);
+                               $rep->AmountCol(6, 7, $inv['inv_price'], $dec);
+                               $rep->AmountCol(7, 8, $trans['unit_price'], $dec);
+                               $amt = round2($inv['inv_qty'] * $inv['inv_price'], $dec);
+                               $rep->AmountCol(8, 9, $amt, $dec);
+                               $rep->NewLine();
+                               $total += $amt;
+                               $qtotal += $inv['inv_qty'];
+                               $grandtotal += $amt;
+                       }
+               }
+       
+               if ($trans['qty_recd'] - $trans['quantity_inv'] !=0 )
+               {
+                       $rep->TextCol(4, 5, "--");
+                       $rep->AmountCol(5, 6, $trans['qty_recd'] - $trans['quantity_inv'], $qdec);
+                       $rep->AmountCol(7, 8, $trans['unit_price'], $dec);
+                       $amt = round2(($trans['qty_recd'] - $trans['quantity_inv']) * $trans['unit_price'], $dec);
+                       $rep->AmountCol(8, 9, $amt, $dec);
+                       $total += $amt;
+                       $qtotal += $trans['qty_recd'] - $trans['quantity_inv'];
+                       $grandtotal += $amt;
+               }
+               else
+                       $rep->NewLine(-1);
        }
        if ($stock_id != '')
        {
                $rep->Line($rep->row  - 4);
                $rep->NewLine(2);
                $rep->TextCol(0, 3, _('Total'));
-               $rep->AmountCol(3, 4, $qtotal, $qdec);
-               $rep->AmountCol(6, 7, $total, $dec);
+               $rep->AmountCol(5, 6, $qtotal, $qdec);
+               $rep->AmountCol(8, 9, $total, $dec);
                $rep->Line($rep->row  - 4);
                $rep->NewLine(2);
-               $rep->TextCol(0, 6, _('Grand Total'));
-               $rep->AmountCol(6, 7, $grandtotal, $dec);
+               $rep->TextCol(0, 7, _('Grand Total'));
+               $rep->AmountCol(8, 9, $grandtotal, $dec);
        }
  
        $rep->Line($rep->row  - 4);
diff --combined reporting/rep601.php
index 7ad92bcb6c4b0279cc6c677e1bb583502deaab54,1d47bc78a1510ca4e201862ab6cdff147e2709bb..1cedff0df8f07ef669516ba0d638e2a13f4d7c9e
@@@ -118,7 -118,7 +118,7 @@@ function print_bank_transactions(
                                $rep->TextCol(1, 2,     $myrow['trans_no']);
                                $rep->TextCol(2, 3,     $myrow['ref']);
                                $rep->DateCol(3, 4,     $myrow["trans_date"], true);
-                               $rep->TextCol(4, 5,     get_counterparty_name($myrow["type"], $myrow["type_no"], false));
 -                              $rep->TextCol(4, 5,     payment_person_name($myrow["person_type_id"],$myrow["person_id"], false));
++                              $rep->TextCol(4, 5,     get_counterparty_name($myrow["type"], $myrow["trans_no"], false));
                                if ($myrow['amount'] > 0.0)
                                {
                                        $rep->AmountCol(5, 6, abs($myrow['amount']), $dec);
diff --combined reporting/rep701.php
index b4f54c9603ea093ed7716cd2ea0151fbc4505270,30e6aa05595ae67b6a58affc4482625bcae367da..2bfffade74b2ee4bb6ff385933db231422bb5263
@@@ -25,10 -25,10 +25,10 @@@ include_once($path_to_root . "/gl/inclu
  
  //----------------------------------------------------------------------------------------------------
  
- function display_type ($type, $typename, &$dec, &$rep, $showbalance)
+ function display_type ($type, $typename, &$dec, &$rep, $showbalance, $level)
  {
        $printtitle = 0; //Flag for printing type name  
--      
++
        //Get Accounts directly under this group/type
        $result = get_gl_accounts(null, null, $type);   
        while ($account=db_fetch($result))
                //Print Type Title if it has atleast one non-zero account       
                if (!$printtitle)
                {
 -                      }               
+                       $prefix = '';
+                       for ($sp=1; $sp<=$level; $sp++)
+                       {
+                               $prefix .= '         ';
++                      }
                        $printtitle = 1;
                        $rep->row -= 4;
-                       $rep->Font('bold');
                        $rep->TextCol(0, 1, $type);
-                       $rep->TextCol(1, 4, $typename);
-                       $rep->Font();
+                       $rep->TextCol(1, 4, $prefix.$typename);
                        $rep->row -= 4;
                        $rep->Line($rep->row);
                        $rep->NewLine();                
                        $balance = get_gl_trans_from_to($begin, ToDay(), $account["account_code"], 0);
                }
                $rep->TextCol(0, 1,     $account['account_code']);
-               $rep->TextCol(1, 2,     $account['account_name']);
+               $rep->TextCol(1, 2,     $prefix.$account['account_name']);
                $rep->TextCol(2, 3,     $account['account_code2']);
                if ($showbalance == 1)  
                        $rep->AmountCol(3, 4, $balance, $dec);
                $rep->NewLine();
        }
--              
++
        //Get Account groups/types under this group/type
        $result = get_account_types(false, false, $type);
        while ($accounttype=db_fetch($result))
@@@ -76,8 -79,8 +79,8 @@@
                        $rep->Line($rep->row);
                        $rep->NewLine();                
                }
-               display_type($accounttype["id"], $accounttype["name"], $dec, $rep, $showbalance);
+               $nextlevel = $level + 1;
+               display_type($accounttype["id"], $accounttype["name"].' ('.$typename.')', $dec, $rep, $showbalance, $nextlevel);
        }
  }
  
@@@ -128,7 -131,7 +131,7 @@@ function print_Chart_of_Accounts(
                $typeresult = get_account_types(false, $class['cid'], -1);
                while ($accounttype=db_fetch($typeresult))
                {
-                       display_type($accounttype["id"], $accounttype["name"], $dec, $rep, $showbalance);
+                       display_type($accounttype["id"], $accounttype["name"], $dec, $rep, $showbalance, 0);
                }
                $rep->NewLine();
        }
diff --combined reporting/rep708.php
index 2095602919aaf7e4ed3b9df4bdf75ba591dde530,979ca2e1e4a45bffa0d9e871a8627e209f11b8b7..9ff9b2964783a21f4966185605b06ed8d5fe2c38
@@@ -19,11 -19,111 +19,111 @@@ $page_security = 'SA_GLANALYTIC'
  $path_to_root="..";
  
  include_once($path_to_root . "/includes/session.inc");
+ include_once($path_to_root . "/admin/db/fiscalyears_db.inc");
  include_once($path_to_root . "/includes/ui.inc");
  include_once($path_to_root . "/includes/date_functions.inc");
  include_once($path_to_root . "/includes/data_checks.inc");
  include_once($path_to_root . "/gl/includes/gl_db.inc");
  
+ $pdeb = $pcre = $cdeb = $ccre = $tdeb = $tcre = $pbal = $cbal = $tbal = 0;
+ //----------------------------------------------------------------------------------------------------
+ function display_type ($type, $typename, &$dec, &$rep, $from, $to, $zero, $balances, $dimension, $dimension2)
+ {
+       global $pdeb, $pcre, $cdeb, $ccre, $tdeb, $tcre, $pbal, $cbal, $tbal;
+       
+       $printtitle = 0; //Flag for printing type name  
+       
+       //Get Accounts directly under this group/type
+       $accounts = get_gl_accounts(null, null, $type); 
+       
+       $begin = get_fiscalyear_begin_for_date($from);
+       if (date1_greater_date2($begin, $from))
+               $begin = $from;
+       $begin = add_days($begin, -1);
+       while ($account=db_fetch($accounts))
+       {
+               //Print Type Title if it has atleast one non-zero account       
+               if (!$printtitle)
+               {       
+                       $rep->row -= 4;
+                       $rep->TextCol(0, 8, _("Group")." - ".$type ." - ".$typename);   
+                       $printtitle = 1;
+                       $rep->row -= 4;
+                       $rep->Line($rep->row);
+                       $rep->NewLine();                        
+               }
+               
+               $prev = get_balance($account["account_code"], $dimension, $dimension2, $begin, $from, false, false);
+               $curr = get_balance($account["account_code"], $dimension, $dimension2, $from, $to, true, true);
+               $tot = get_balance($account["account_code"], $dimension, $dimension2, $begin, $to, false, true);
+               if ($zero == 0 && !$prev['balance'] && !$curr['balance'] && !$tot['balance'])
+                       continue;
+               $rep->TextCol(0, 1, $account['account_code']);
+               $rep->TextCol(1, 2,     $account['account_name']);
+               if ($balances != 0)
+               {
+                       if ($prev['balance'] >= 0.0)
+                               $rep->AmountCol(2, 3, $prev['balance'], $dec);
+                       else
+                               $rep->AmountCol(3, 4, abs($prev['balance']), $dec);
+                       if ($curr['balance'] >= 0.0)
+                               $rep->AmountCol(4, 5, $curr['balance'], $dec);
+                       else
+                               $rep->AmountCol(5, 6, abs($curr['balance']), $dec);
+                       if ($tot['balance'] >= 0.0)
+                               $rep->AmountCol(6, 7, $tot['balance'], $dec);
+                       else
+                               $rep->AmountCol(7, 8, abs($tot['balance']), $dec);
+               }
+               else
+               {
+                       $rep->AmountCol(2, 3, $prev['debit'], $dec);
+                       $rep->AmountCol(3, 4, $prev['credit'], $dec);
+                       $rep->AmountCol(4, 5, $curr['debit'], $dec);
+                       $rep->AmountCol(5, 6, $curr['credit'], $dec);
+                       $rep->AmountCol(6, 7, $tot['debit'], $dec);
+                       $rep->AmountCol(7, 8, $tot['credit'], $dec);
+                       $pdeb += $prev['debit'];
+                       $pcre += $prev['credit'];
+                       $cdeb += $curr['debit'];
+                       $ccre += $curr['credit'];
+                       $tdeb += $tot['debit'];
+                       $tcre += $tot['credit'];
+               }       
+               $pbal += $prev['balance'];
+               $cbal += $curr['balance'];
+               $tbal += $tot['balance'];
+               $rep->NewLine();
+               if ($rep->row < $rep->bottomMargin + $rep->lineHeight)
+               {
+                       $rep->Line($rep->row - 2);
+                       $rep->NewPage();
+               }
+       }
+               
+       //Get Account groups/types under this group/type
+       $result = get_account_types(false, false, $type);
+       while ($accounttype=db_fetch($result))
+       {
+               //Print Type Title if has sub types and not previously printed
+               if (!$printtitle)
+               {
+                       $rep->row -= 4;
+                       $rep->TextCol(0, 8, _("Group")." - ".$type ." - ".$typename);   
+                       $printtitle = 1;
+                       $rep->row -= 4;
+                       $rep->Line($rep->row);
+                       $rep->NewLine();                
+               }
+               display_type($accounttype["id"], $accounttype["name"].' ('.$typename.')', $dec, $rep, $from, $to, $zero, $balances, $dimension, $dimension2);
+       }
+ }
  //----------------------------------------------------------------------------------------------------
  
  print_trial_balance();
  function print_trial_balance()
  {
        global $path_to_root;
+       global $pdeb, $pcre, $cdeb, $ccre, $tdeb, $tcre, $pbal, $cbal, $tbal;
  
        $dim = get_company_pref('use_dimension');
        $dimension = $dimension2 = 0;
                include_once($path_to_root . "/reporting/includes/pdf_report.inc");
        $dec = user_price_dec();
  
-       //$cols2 = array(0, 50, 230, 330, 430, 530);
        $cols2 = array(0, 50, 190, 310, 430, 530);
        //-------------0--1---2----3----4----5--
  
  
        $aligns2 = array('left', 'left', 'left', 'left', 'left');
  
-       //$cols = array(0, 50, 200, 250, 300,   350, 400, 450, 500,     550);
        $cols = array(0, 50, 150, 210, 270,     330, 390, 450, 510,     570);
-       //------------0--1---2----3----4----5----6----7----8----9--
+       //------------0--1---2----3----4----5----6----7----8--
  
        $headers = array(_('Account'), _('Account Name'), _('Debit'), _('Credit'), _('Debit'),
                _('Credit'), _('Debit'), _('Credit'));
        $rep->Font();
        $rep->Info($params, $cols, $headers, $aligns, $cols2, $headers2, $aligns2);
        $rep->NewPage();
 -      
 +
-       $accounts = get_gl_accounts();
-       $pdeb = $pcre = $cdeb = $ccre = $tdeb = $tcre = $pbal = $cbal = $tbal = 0;
-       $begin = begin_fiscalyear();
-       if (date1_greater_date2($begin, $from))
-               $begin = $from;
-       $begin = add_days($begin, -1);
-       while ($account=db_fetch($accounts))
+       $classresult = get_account_classes(false);
+       while ($class = db_fetch($classresult))
        {
-               $prev = get_balance($account["account_code"], $dimension, $dimension2, $begin, $from, false, false);
-               $curr = get_balance($account["account_code"], $dimension, $dimension2, $from, $to, true, true);
-               $tot = get_balance($account["account_code"], $dimension, $dimension2, $begin, $to, false, true);
-               if ($zero == 0 && !$prev['balance'] && !$curr['balance'] && !$tot['balance'])
-                       continue;
-               $rep->TextCol(0, 1, $account['account_code']);
-               $rep->TextCol(1, 2,     $account['account_name']);
-               if ($balances != 0)
-               {
-                       if ($prev['balance'] >= 0.0)
-                               $rep->AmountCol(2, 3, $prev['balance'], $dec);
-                       else
-                               $rep->AmountCol(3, 4, abs($prev['balance']), $dec);
-                       if ($curr['balance'] >= 0.0)
-                               $rep->AmountCol(4, 5, $curr['balance'], $dec);
-                       else
-                               $rep->AmountCol(5, 6, abs($curr['balance']), $dec);
-                       if ($tot['balance'] >= 0.0)
-                               $rep->AmountCol(6, 7, $tot['balance'], $dec);
-                       else
-                               $rep->AmountCol(7, 8, abs($tot['balance']), $dec);
-               }
-               else
-               {
-                       $rep->AmountCol(2, 3, $prev['debit'], $dec);
-                       $rep->AmountCol(3, 4, $prev['credit'], $dec);
-                       $rep->AmountCol(4, 5, $curr['debit'], $dec);
-                       $rep->AmountCol(5, 6, $curr['credit'], $dec);
-                       $rep->AmountCol(6, 7, $tot['debit'], $dec);
-                       $rep->AmountCol(7, 8, $tot['credit'], $dec);
-                       $pdeb += $prev['debit'];
-                       $pcre += $prev['credit'];
-                       $cdeb += $curr['debit'];
-                       $ccre += $curr['credit'];
-                       $tdeb += $tot['debit'];
-                       $tcre += $tot['credit'];
-                       
-               }       
-               $pbal += $prev['balance'];
-               $cbal += $curr['balance'];
-               $tbal += $tot['balance'];
+               $rep->Font('bold');
+               $rep->TextCol(0, 1, $class['cid']);
+               $rep->TextCol(1, 4, $class['class_name']);
+               $rep->Font();
                $rep->NewLine();
  
-               if ($rep->row < $rep->bottomMargin + $rep->lineHeight)
+               //Get Account groups/types under this group/type with no parents
+               $typeresult = get_account_types(false, $class['cid'], -1);
+               while ($accounttype=db_fetch($typeresult))
                {
-                       $rep->Line($rep->row - 2);
-                       $rep->NewPage();
+                       display_type($accounttype["id"], $accounttype["name"], $dec, $rep, $from, $to,  $zero, $balances, $dimension, $dimension2);
                }
+               $rep->NewLine();
        }
        $rep->Line($rep->row);
        $rep->NewLine();
        $rep->Font('bold');
  
-       //$prev = get_balance(null, $dimension, $dimension2, $begin, $from, false, false);
-       //$curr = get_balance(null, $dimension, $dimension2, $from, $to, true, true);
-       //$tot = get_balance(null, $dimension, $dimension2, $begin, $to, false, true);
        if ($balances == 0)
        {
                $rep->TextCol(0, 2, _("Total"));
        else
                $rep->AmountCol(7, 8, abs($tbal), $dec);
        $rep->NewLine();
--              
-       $rep->Line($rep->row);
-       if (($pbal = round2($pbal, $dec)) != 0.0)
++
+       $rep->Line($rep->row + 10);
+       if (($pbal = round2($pbal, $dec)) != 0.0 && $dimension == 0 && $dimension2 == 0)
        {
                $rep->NewLine(2);
                $rep->Font();
diff --combined reporting/rep709.php
index e52f293395c08b265a20e203b0eb4cce09a88daa,dbe25e5bd59e82f1472f06b0c566ee4e9f055baf..c3cd8e193a4f46ad550e37a477392fb4c8e552c8
@@@ -33,11 -33,13 +33,13 @@@ function getTaxTransactions($from, $to
        $fromdate = date2sql($from);
        $todate = date2sql($to);
  
-       $sql = "SELECT taxrec.*, taxrec.amount*ex_rate AS amount,
+       $sql = "SELECT tt.name as taxname, taxrec.*, taxrec.amount*ex_rate AS amount,
                    taxrec.net_amount*ex_rate AS net_amount,
                                IF(ISNULL(supp.supp_name), debt.name, supp.supp_name) as name,
                                branch.br_name
                FROM ".TB_PREF."trans_tax_details taxrec
+               LEFT JOIN ".TB_PREF."tax_types tt
+                       ON taxrec.tax_type_id=tt.id
                LEFT JOIN ".TB_PREF."supp_trans strans
                        ON taxrec.trans_no=strans.trans_no AND taxrec.trans_type=strans.type
                LEFT JOIN ".TB_PREF."suppliers as supp ON strans.supplier_id=supp.supplier_id
@@@ -49,7 -51,7 +51,7 @@@
                        AND taxrec.trans_type <> ".ST_CUSTDELIVERY."
                        AND taxrec.tran_date >= '$fromdate'
                        AND taxrec.tran_date <= '$todate'
-               ORDER BY taxrec.tran_date";
+               ORDER BY taxrec.trans_type, taxrec.tran_date, taxrec.trans_no, taxrec.ex_rate";
  //display_error($sql);
      return db_query($sql,"No transactions were returned");
  }
@@@ -71,8 -73,8 +73,8 @@@ function getTaxInfo($id
  
  function print_tax_report()
  {
-       global $path_to_root, $trans_dir, $systypes_array;
-       
+       global $path_to_root, $trans_dir, $Hooks, $systypes_array;
 -      
++
        $from = $_POST['PARAM_0'];
        $to = $_POST['PARAM_1'];
        $summaryOnly = $_POST['PARAM_2'];
                                                1 => array('text' => _('Period'), 'from' => $from, 'to' => $to),
                                                2 => array('text' => _('Type'), 'from' => $summary, 'to' => ''));
  
-       $cols = array(0, 100, 130, 180, 290, 370, 420, 470, 520);
+       $cols = array(0, 80, 130, 180, 270, 350, 400, 430, 480, 485, 520);
  
        $headers = array(_('Trans Type'), _('Ref'), _('Date'), _('Name'), _('Branch Name'),
-               _('Net'), _('Rate'), _('Tax'));
-       $aligns = array('left', 'left', 'left', 'left', 'left', 'right', 'right', 'right');
+               _('Net'), _('Rate'), _('Tax'), '', _('Name'));
+       $aligns = array('left', 'left', 'left', 'left', 'left', 'right', 'right', 'right', 'right','left');
        $rep->Font();
        $rep->Info($params, $cols, $headers, $aligns);
        if (!$summaryOnly)
                        $trans['net_amount'] *= -1;
                        $trans['amount'] *= -1;
                }
--              
++
                if (!$summaryOnly)
                {
                        $rep->TextCol(0, 1, $systypes_array[$trans['trans_type']]);
                        $rep->AmountCol(5, 6, $trans['net_amount'], $dec);
                        $rep->AmountCol(6, 7, $trans['rate'], $dec);
                        $rep->AmountCol(7, 8, $trans['amount'], $dec);
 -                      
 +
+                       $rep->TextCol(9, 10, $trans['taxname']);
                        $rep->NewLine();
  
                        if ($rep->row < $rep->bottomMargin + $rep->lineHeight)
index baeeba36f6141a78718853a0ec89f0a0a0940836,ca27855618aaf47e3298a5fa06d0624075d365f1..e91353097171e968f7aeaa4112cde2d03ddb8fe6
@@@ -42,6 -42,7 +42,7 @@@ $reports->addReport(RC_CUSTOMER, 102, _
        array(  _('End Date') => 'DATE',
                        _('Customer') => 'CUSTOMERS_NO_FILTER',
                        _('Currency Filter') => 'CURRENCY',
+                       _('Show Also Allocated') => 'YES_NO',
                        _('Summary Only') => 'YES_NO',
                        _('Suppress Zeros') => 'YES_NO',
                        _('Graphics') => 'GRAPHIC',
@@@ -55,6 -56,12 +56,12 @@@ $reports->addReport(RC_CUSTOMER, 103, _
                        _('Activity Less Than') => 'TEXT',
                        _('Comments') => 'TEXTBOX',
                        _('Destination') => 'DESTINATION'));
+ $reports->addReport(RC_CUSTOMER, 114, _('Sales &Summary Report'),
+       array(  _('Start Date') => 'DATEBEGINTAX',
+                       _('End Date') => 'DATEENDTAX',
+                       _('Tax Id Only') => 'YES_NO',
+                       _('Comments') => 'TEXTBOX',
+                       _('Destination') => 'DESTINATION'));
  $reports->addReport(RC_CUSTOMER, 104, _('&Price Listing'),
        array(  _('Currency Filter') => 'CURRENCY',
                        _('Inventory Category') => 'CATEGORIES',
@@@ -77,13 -84,20 +84,20 @@@ $reports->addReport(RC_CUSTOMER, 106, _
                        _('Summary Only') => 'YES_NO',
                        _('Comments') => 'TEXTBOX',
                        _('Destination') => 'DESTINATION'));
- $reports->addReport(RC_CUSTOMER, 107, _('Print &Invoices/Credit Notes'),
+ $reports->addReport(RC_CUSTOMER, 107, _('Print &Invoices'),
        array(  _('From') => 'INVOICE',
                        _('To') => 'INVOICE',
                        _('Currency Filter') => 'CURRENCY',
                        _('email Customers') => 'YES_NO',
                        _('Payment Link') => 'PAYMENT_LINK',
                        _('Comments') => 'TEXTBOX'));
+ $reports->addReport(RC_CUSTOMER, 113, _('Print &Credit Notes'),
+       array(  _('From') => 'CREDIT',
+                       _('To') => 'CREDIT',
+                       _('Currency Filter') => 'CURRENCY',
+                       _('email Customers') => 'YES_NO',
+                       _('Payment Link') => 'PAYMENT_LINK',
+                       _('Comments') => 'TEXTBOX'));
  $reports->addReport(RC_CUSTOMER, 110, _('Print &Deliveries'),
        array(  _('From') => 'DELIVERY',
                        _('To') => 'DELIVERY',
  $reports->addReport(RC_CUSTOMER, 108, _('Print &Statements'),
        array(  _('Customer') => 'CUSTOMERS_NO_FILTER',
                        _('Currency Filter') => 'CURRENCY',
-                       _('Show Outstanding Only') => 'YES_NO',
+                       _('Show Also Allocated') => 'YES_NO',
                        _('Email Customers') => 'YES_NO',
                        _('Comments') => 'TEXTBOX'));
  $reports->addReport(RC_CUSTOMER, 109, _('&Print Sales Orders'),
@@@ -109,12 -123,6 +123,6 @@@ $reports->addReport(RC_CUSTOMER, 111, _
                        _('Currency Filter') => 'CURRENCY',
                        _('Email Customers') => 'YES_NO',
                        _('Comments') => 'TEXTBOX'));
- $reports->addReport(RC_CUSTOMER, 111, _('&Print Sales Quotations'),
-       array(  _('From') => 'QUOTATIONS',
-                       _('To') => 'QUOTATIONS',
-                       _('Currency Filter') => 'CURRENCY',
-                       _('Email Customers') => 'YES_NO',
-                       _('Comments') => 'TEXTBOX'));
  $reports->addReport(RC_CUSTOMER, 112, _('Print Receipts'),
        array(  _('From') => 'RECEIPT',
                        _('To') => 'RECEIPT',
@@@ -134,6 -142,7 +142,7 @@@ $reports->addReport(RC_SUPPLIER, 202, _
        array(  _('End Date') => 'DATE',
                        _('Supplier') => 'SUPPLIERS_NO_FILTER',
                        _('Currency Filter') => 'CURRENCY',
+                       _('Show Also Allocated') => 'YES_NO',
                        _('Summary Only') => 'YES_NO',
                        _('Suppress Zeros') => 'YES_NO',
                        _('Graphics') => 'GRAPHIC',
@@@ -156,7 -165,7 +165,7 @@@ $reports->addReport(RC_SUPPLIER, 209, _
                        _('Currency Filter') => 'CURRENCY',
                        _('Email Customers') => 'YES_NO',
                        _('Comments') => 'TEXTBOX'));
--$reports->addReport(RC_SUPPLIER, 210, _('Print Remittances'),
++$reports->addReport(RC_SUPPLIER, 210, _('Print Remi&ttances'),
        array(  _('From') => 'REMITTANCE',
                        _('To') => 'REMITTANCE',
                        _('Currency Filter') => 'CURRENCY',
  $reports->addReportClass(_('Inventory'), RC_INVENTORY);
  
  $reports->addReport(RC_INVENTORY,  301, _('Inventory &Valuation Report'),
-       array(  _('Inventory Category') => 'CATEGORIES',
 -      array(  _('End Date') => 'DATE',        
++      array(  _('End Date') => 'DATE',
+                       _('Inventory Category') => 'CATEGORIES',
                        _('Location') => 'LOCATIONS',
                        _('Summary Only') => 'YES_NO',
                        _('Comments') => 'TEXTBOX',
@@@ -224,18 -234,13 +234,13 @@@ if ($dim > 0
        //              _('Comments'),'TEXTBOX')));
  }
  $reports->addReportClass(_('Banking'), RC_BANKING);
- $reports->addReport(RC_BANKING,  601, _('Bank &Statement'),
- array(        _('Bank Accounts') => 'BANK_ACCOUNTS',
-               _('Start Date') => 'DATEBEGINM',
-               _('End Date') => 'DATEENDM',
-               _('Comments') => 'TEXTBOX',
-               _('Destination') => 'DESTINATION'));
- $reports->addReport(RC_BANKING, 602, _('Bank Statement w/&Reconcile'),
+       $reports->addReport(RC_BANKING,  601, _('Bank &Statement'),
        array(  _('Bank Accounts') => 'BANK_ACCOUNTS',
                        _('Start Date') => 'DATEBEGINM',
                        _('End Date') => 'DATEENDM',
                        _('Comments') => 'TEXTBOX',
                        _('Destination') => 'DESTINATION'));
  $reports->addReportClass(_('General Ledger'), RC_GL);
  $reports->addReport(RC_GL, 701, _('Chart of &Accounts'),
        array(  _('Show Balances') => 'YES_NO',
index cfe424b494aa4bb606d6356f1f4a7571bcdb3d87,ee92d03b9327e5d472125473a626a369b5595be7..5b13f04dc39c5fce6dc49e726dadb256c1aff08f
@@@ -23,7 -23,7 +23,7 @@@ if ($use_popup_windows
  
  page(_($help_context = "Create and Print Recurrent Invoices"), false, false, "", $js);
  
- function create_recurrent_invoices($customer_id, $branch_id, $order_no, $tmpl_no)
+ function create_recurrent_invoices($customer_id, $branch_id, $order_no, $tmpl_no, $date, $from, $to)
  {
        global $Refs;
  
  
        $doc->trans_type = ST_SALESORDER;
        $doc->trans_no = 0;
-       $doc->document_date = Today(); // 2006-06-15. Added so Invoices and Deliveries get current day
+       $doc->document_date = $date; 
  
        $doc->due_date = get_invoice_duedate($doc->payment, $doc->document_date);
        $doc->reference = $Refs->get_next($doc->trans_type);
-       //$doc->Comments='';
+       $doc->Comments = sprintf(_("Recurrent Invoice covers period %s - %s."), $from, add_days($to, -1));
  
        foreach ($doc->line_items as $line_no=>$item) {
                $line = &$doc->line_items[$line_no];
        $cart->trans_type = ST_SALESINVOICE;
        $cart->reference = $Refs->get_next($cart->trans_type);
        $invno = $cart->write(1);
-       update_last_sent_recurrent_invoice($tmpl_no, $cart->document_date);
+       update_last_sent_recurrent_invoice($tmpl_no, $to);
        return $invno;
  }
  
if (isset($_GET['recurrent']))
function calculate_from($myrow)
  {
+       if ($myrow["last_sent"] == '0000-00-00')
+               $from = sql2date($myrow["begin"]);
+       else
+               $from = sql2date($myrow["last_sent"]);
+       return $from;   
+ }
+ $id = find_submit("create");
+ if ($id != -1)
+ {
+       $Ajax->activate('_page_body');
        $date = Today();
        if (is_date_in_fiscalyear($date))
        {
                $invs = array();
-               $myrow = get_recurrent_invoice($_GET['recurrent']);
+               $myrow = get_recurrent_invoice($id);
+               $from = calculate_from($myrow);
+               $to = add_months($from, $myrow['monthly']);
+               $to = add_days($to, $myrow['days']);
                if ($myrow['debtor_no'] == 0)
                {
                        $cust = get_cust_branches_from_group($myrow['group_no']);
                        while ($row = db_fetch($cust))
                        {
-                               $invs[] = create_recurrent_invoices($row['debtor_no'], $row['branch_code'], $myrow['order_no'], $myrow['id']);
+                               $invs[] = create_recurrent_invoices($row['debtor_no'], $row['branch_code'], $myrow['order_no'], $myrow['id'],
+                                       $date, $from, $to);
                        }       
                }
                else
                {
-                       $invs[] = create_recurrent_invoices($myrow['debtor_no'], $myrow['group_no'], $myrow['order_no'], $myrow['id']);
+                       $invs[] = create_recurrent_invoices($myrow['debtor_no'], $myrow['group_no'], $myrow['order_no'], $myrow['id'],
+                               $date, $from, $to);
                }
                if (count($invs) > 0)
                {
                }
                else 
                        $min = $max = 0;
-               display_notification(sprintf(_("%s recurrent invoice(s) created, # $min - # $max."), count($invs)));
+               display_notification(sprintf(_("%s recurrent invoice(s) created, # %s - # %s."), count($invs), $min, $max));
                if (count($invs) > 0)
                {
                        $ar = array('PARAM_0' => $min."-".ST_SALESINVOICE,      'PARAM_1' => $max."-".ST_SALESINVOICE, 'PARAM_2' => "",
                                'PARAM_3' => 0, 'PARAM_4' => 0, 'PARAM_5' => "", 'PARAM_6' => ST_SALESINVOICE);
-                       display_note(print_link(_("&Print Recurrent Invoices # $min - # $max"), 107, $ar), 0, 1);
-                       $ar['PARAM_3'] = 1; 
-                       display_note(print_link(_("&Email Recurrent Invoices # $min - # $max"), 107, $ar), 0, 1);
+                       display_note(print_link(sprintf(_("&Print Recurrent Invoices # %s - # %s"), $min, $max), 107, $ar), 0, 1);
+                       $ar['PARAM_3'] = 1; // email
+                       display_note(print_link(sprintf(_("&Email Recurrent Invoices # %s - # %s"), $min, $max), 107, $ar), 0, 1);
                }
        }
        else
 -              display_error(_("The entered date is not in fiscal year."));
 +              display_error(_("The entered date is out of fiscal year or is closed for further data entry."));
  }
  
  $result = get_recurrent_invoices();
  
+ start_form();
  start_table(TABLESTYLE, "width=70%");
  $th = array(_("Description"), _("Template No"),_("Customer"),_("Branch")."/"._("Group"),_("Days"),_("Monthly"),_("Begin"),_("End"),_("Last Created"),"");
  table_header($th);
@@@ -104,13 -121,10 +121,10 @@@ while ($myrow = db_fetch($result)
  {
        $begin = sql2date($myrow["begin"]);
        $end = sql2date($myrow["end"]);
-       $last_sent = sql2date($myrow["last_sent"]);
-       if ($myrow['monthly'] > 0)
-               $due_date = begin_month($last_sent);
-       else
-               $due_date = $last_sent;
-       $due_date = add_months($due_date, $myrow['monthly']);
+       $last_sent = calculate_from($myrow);
+       $due_date = add_months($last_sent, $myrow['monthly']);
        $due_date = add_days($due_date, $myrow['days']);
        $overdue = date1_greater_date2($today, $due_date) && date1_greater_date2($today, $begin)
                && date1_greater_date2($end, $today);
        if ($overdue)
        label_cell($myrow['monthly']);
        label_cell($begin);
        label_cell($end);
-       label_cell($last_sent);
+       label_cell(($myrow['last_sent']=="0000-00-00")?"":$last_sent);
        if ($overdue)
-               label_cell("<a href='$path_to_root/sales/create_recurrent_invoices.php?recurrent=" . $myrow["id"] . "'>" . _("Create Invoices") . "</a>");
+               button_cell("create".$myrow["id"], _("Create Invoices"), "", ICON_DOC);
        else
                label_cell("");
        end_row();
  }
  end_table();
+ end_form();
  if ($due)
        display_note(_("Marked items are due."), 1, 0, "class='overduefg'");
  else
index b80a66f3cf1947bf7ee70d2678db8b4f99602f39,de84ba09f8e0133846d7ae231766d38ed8b83115..7fc278a82643a698fd9542b3841b7ecc7b5f11ec
@@@ -74,6 -74,8 +74,8 @@@ if (isset($_GET['AddedID'])) 
  
        hyperlink_params($_SERVER['PHP_SELF'], _("Enter Another &Credit Note"), "NewCredit=yes");
  
+       hyperlink_params("$path_to_root/admin/attachments.php", _("Add an Attachment"), "filterType=$trans_type&trans_no=$credit_no");
        display_footer_exit();
  } else
        check_edit_conflicts();
@@@ -94,7 -96,7 +96,7 @@@ function copy_to_cn(
        $cart->Comments = $_POST['CreditText'];
        $cart->document_date = $_POST['OrderDate'];
        $cart->freight_cost = input_num('ChargeFreightCost');
-       $cart->Location = $_POST["Location"];
+       $cart->Location = (isset($_POST["Location"]) ? $_POST["Location"] : "");
        $cart->sales_type = $_POST['sales_type_id'];
        if ($cart->trans_no == 0)
                $cart->reference = $_POST['ref'];
@@@ -126,7 -128,7 +128,7 @@@ function copy_from_cn(
  function handle_new_credit($trans_no)
  {
        processing_start();
-       $_SESSION['Items'] = new Cart(11,$trans_no);
+       $_SESSION['Items'] = new Cart(ST_CUSTCREDIT,$trans_no);
        copy_from_cn();
  }
  
@@@ -156,7 -158,7 +158,7 @@@ function can_process(
                set_focus('OrderDate');
                $input_error = 1;
        } elseif (!is_date_in_fiscalyear($_POST['OrderDate'])) {
 -              display_error(_("The entered date is not in fiscal year."));
 +              display_error(_("The entered date is out of fiscal year or is closed for further data entry."));
                set_focus('OrderDate');
                $input_error = 1;
        }
@@@ -255,7 -257,7 +257,7 @@@ if (isset($_POST['CancelItemChanges'])
  //-----------------------------------------------------------------------------
  
  if (!processing_active()) {
-       handle_new_credit();
+       handle_new_credit(0);
  }
  
  //-----------------------------------------------------------------------------
index c46215389ae56f464bfe160dd5f60cf91cfae23f,18318e566db3d9f945123e6a6a156c4596df7cfa..d9a6542499cf858f240fc9e8c320df34a4ce62a8
@@@ -59,6 -59,8 +59,8 @@@ if (isset($_GET['AddedID'])) 
  
        display_note(get_gl_view_str($trans_type, $credit_no, _("View the GL &Journal Entries for this Credit Note")),1);
  
+       hyperlink_params("$path_to_root/admin/attachments.php", _("Add an Attachment"), "filterType=$trans_type&trans_no=$credit_no");
        display_footer_exit();
  
  } elseif (isset($_GET['UpdatedID'])) {
@@@ -90,7 -92,7 +92,7 @@@ function can_process(
                set_focus('CreditDate');
                return false;
        } elseif (!is_date_in_fiscalyear($_POST['CreditDate'])) {
 -              display_error(_("The entered date is not in fiscal year."));
 +              display_error(_("The entered date is out of fiscal year or is closed for further data entry."));
                set_focus('CreditDate');
                return false;
        }
  
  if (isset($_GET['InvoiceNumber']) && $_GET['InvoiceNumber'] > 0) {
  
-     $ci = new Cart(ST_SALESINVOICE, $_GET['InvoiceNumber'], true);
-     $ci->trans_type = ST_CUSTCREDIT;
-     $ci->src_docs = $ci->trans_no;
-     $ci->src_date = $ci->document_date;
-     $ci->trans_no = 0;
-     $ci->document_date = new_doc_date();
-     $ci->reference = $Refs->get_next(ST_CUSTCREDIT);
-     for ($line_no=0; $line_no<count($ci->line_items); $line_no++) {
-       $ci->line_items[$line_no]->qty_dispatched = '0';
-     }
-     $_SESSION['Items'] = $ci;
+     $_SESSION['Items'] = new Cart(ST_SALESINVOICE, $_GET['InvoiceNumber'], true);
        copy_from_cart();
  
  } elseif ( isset($_GET['ModifyCredit']) && $_GET['ModifyCredit']>0) {
  
-       check_is_closed(ST_CUSTCREDIT,$_GET['ModifyCredit']);
-       $_SESSION['Items'] = new Cart(ST_CUSTCREDIT,$_GET['ModifyCredit']);
+       $_SESSION['Items'] = new Cart(ST_CUSTCREDIT, $_GET['ModifyCredit']);
        copy_from_cart();
  
  } elseif (!processing_active()) {
@@@ -165,10 -153,10 +153,10 @@@ function check_quantities(
                                $_SESSION['Items']->line_items[$line_no]->qty_dispatched =
                                  input_num('Line'.$line_no);
                        }
+                       else {
+                               $ok = 0;
+                       }
                }
-               else {
-                       $ok = 0;
-               }
  
                if (isset($_POST['Line'.$line_no.'Desc'])) {
                        $line_desc = $_POST['Line'.$line_no.'Desc'];
@@@ -187,7 -175,7 +175,7 @@@ function copy_to_cart(
        $cart->ship_via = $_POST['ShipperID'];
        $cart->freight_cost = input_num('ChargeFreightCost');
        $cart->document_date =  $_POST['CreditDate'];
-       $cart->Location = $_POST['Location'];
+       $cart->Location = (isset($_POST['Location']) ? $_POST['Location'] : "");
        $cart->Comments = $_POST['CreditText'];
        if ($_SESSION['Items']->trans_no == 0)
                $cart->reference = $_POST['ref'];
@@@ -218,11 -206,13 +206,13 @@@ if (isset($_POST['ProcessCredit']) && c
        if ($new_credit) new_doc_date($_SESSION['Items']->document_date);
      $credit_no = $_SESSION['Items']->write($_POST['WriteOffGLCode']);
  
-       processing_end();
-       if ($new_credit) {
-               meta_forward($_SERVER['PHP_SELF'], "AddedID=$credit_no");
-       } else {
-               meta_forward($_SERVER['PHP_SELF'], "UpdatedID=$credit_no");
+       if($credit_no) {
+               processing_end();
+               if ($new_credit) {
+                       meta_forward($_SERVER['PHP_SELF'], "AddedID=$credit_no");
+               } else {
+                       meta_forward($_SERVER['PHP_SELF'], "UpdatedID=$credit_no");
+               }
        }
  }
  
index 2208a455c6b093539576f0c47c31560799c08288,30e359193d6e25253d0ac1ed60d4084b235cb30b..df8bad06d9ebd4016d13e8f24174a1cf90420c50
@@@ -89,31 -89,21 +89,22 @@@ if (isset($_GET['OrderNumber']) && $_GE
  
        $ord = new Cart(ST_SALESORDER, $_GET['OrderNumber'], true);
  
-       /*read in all the selected order into the Items cart  */
        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 = ST_CUSTDELIVERY;
-       $ord->src_docs = $ord->trans_no;
-       $ord->order_no = key($ord->trans_no);
-       $ord->trans_no = 0;
-       $ord->reference = $Refs->get_next(ST_CUSTDELIVERY);
-       $ord->document_date = new_doc_date();
-       $cust = get_customer($ord->customer_id);
-       // 2010-09-03 Joe Hunt
-       $ord->dimension_id = $cust['dimension_id'];
-       $ord->dimension2_id = $cust['dimension2_id'];
+       // Adjust Shipping Charge based upon previous deliveries TAM
+       adjust_shipping_charge($ord, $_GET['OrderNumber']);
+  
        $_SESSION['Items'] = $ord;
        copy_from_cart();
  
  } elseif (isset($_GET['ModifyDelivery']) && $_GET['ModifyDelivery'] > 0) {
  
 -      $_SESSION['Items'] = new Cart(ST_CUSTDELIVERY, $_GET['ModifyDelivery']);
 +      check_is_closed(ST_CUSTDELIVERY, $_GET['ModifyDelivery']);
 +      $_SESSION['Items'] = new Cart(ST_CUSTDELIVERY,$_GET['ModifyDelivery']);
  
        if ($_SESSION['Items']->count_items() == 0) {
                hyperlink_params($path_to_root . "/sales/inquiry/sales_orders_view.php",
@@@ -160,7 -150,7 +151,7 @@@ function check_data(
        }
  
        if (!is_date_in_fiscalyear($_POST['DispatchDate'])) {
 -              display_error(_("The entered date of delivery is not in fiscal year."));
 +              display_error(_("The entered date is out of fiscal year or is closed for further data entry."));
                set_focus('DispatchDate');
                return false;
        }
@@@ -279,24 -269,35 +270,35 @@@ function check_quantities(
  
  function check_qoh()
  {
-       global $SysPrefs;
-       if (!$SysPrefs->allow_negative_stock()) {
-               foreach ($_SESSION['Items']->line_items as $itm) {
-                       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;
-                               }
-                       }
-               }
-       }
-       return true;
+     global $SysPrefs;
+     $dn = &$_SESSION['Items'];
+     $newdelivery = ($dn->trans_no==0);
+     if (!$SysPrefs->allow_negative_stock()) {
+         foreach ($_SESSION['Items']->line_items as $itm) {
+             if ($itm->qty_dispatched && has_stock_holding($itm->mb_flag)) {
+                 $qoh_by_date = get_qoh_on_date($itm->stock_id, $_POST['Location'], $_POST['DispatchDate']);
+                 $qoh_abs = get_qoh_on_date($itm->stock_id, $_POST['Location'], null);
+                 //If editing current delivery delivered qty should be added 
+                 if (!$newdelivery)
+                 {
+                     $delivered = get_already_delivered($itm->stock_id, $_POST['Location'], key($dn->trans_no));
 -                    
++
+                     $qoh_abs = $qoh_abs - $delivered;
+                     $qoh_by_date = $qoh_by_date - $delivered;
+                 }
+                 $qoh = ($qoh_by_date < $qoh_abs ? $qoh_by_date : $qoh_abs); 
+                 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()) {
index 84d2673f62e5ca1e4113a300ce0ab2c9b8d9424f,9c9e171bddd11612f00a90a3add294bb0939bd6b..5bebcb7498ec398b67bc67d25fe315ee9ea3f385
@@@ -63,6 -63,8 +63,8 @@@ if (isset($_GET['AddedID'])) 
  
        hyperlink_params("$path_to_root/sales/inquiry/sales_deliveries_view.php", _("Select Another &Delivery For Invoicing"), "OutstandingOnly=1");
  
+       hyperlink_params("$path_to_root/admin/attachments.php", _("Add an Attachment"), "filterType=$trans_type&trans_no=$invoice_no");
        display_footer_exit();
  
  } elseif (isset($_GET['UpdatedID']))  {
@@@ -110,6 -112,7 +112,7 @@@ if ( (isset($_GET['DeliveryNumber']) &
        } else {
                $src = array($_GET['DeliveryNumber']);
        }
        /*read in all the selected deliveries into the Items cart  */
        $dn = new Cart(ST_CUSTDELIVERY, $src, true);
  
                die ("<br><b>" . _("There are no delivered items with a quantity left to invoice. There is nothing left to invoice.") . "</b>");
        }
  
-       $dn->trans_type = ST_SALESINVOICE;
-       $dn->src_docs = $dn->trans_no;
-       $dn->trans_no = 0;
-       $dn->reference = $Refs->get_next(ST_SALESINVOICE);
-       $dn->due_date = get_invoice_duedate($dn->payment, $dn->document_date);
        $_SESSION['Items'] = $dn;
        copy_from_cart();
  
  } elseif (isset($_GET['ModifyInvoice']) && $_GET['ModifyInvoice'] > 0) {
  
 +      check_is_closed(ST_SALESINVOICE, $_GET['ModifyInvoice']);
 +
        if ( get_sales_parent_numbers(ST_SALESINVOICE, $_GET['ModifyInvoice']) == 0) { // 1.xx compatibility hack
                echo"<center><br><b>" . _("There are no delivery notes for this invoice.<br>
                Most likely this invoice was created in Front Accounting version prior to 2.0
  
        end_page();
        exit;
- } elseif (!check_quantities()) {
+ } elseif (!isset($_POST['process_invoice']) && !check_quantities()) {
        display_error(_("Selected quantity cannot be less than quantity credited nor more than quantity not invoiced yet."));
  }
  if (isset($_POST['Update'])) {
@@@ -235,6 -230,8 +232,8 @@@ function copy_to_cart(
        $cart->Comments = $_POST['Comments'];
        if ($_SESSION['Items']->trans_no == 0)
                $cart->reference = $_POST['ref'];
+       $cart->dimension_id =  $_POST['dimension_id'];
+       $cart->dimension2_id =  $_POST['dimension2_id'];
  
  }
  //-----------------------------------------------------------------------------
@@@ -250,6 -247,8 +249,8 @@@ function copy_from_cart(
        $_POST['cart_id'] = $cart->cart_id;
        $_POST['ref'] = $cart->reference;
        $_POST['payment'] = $cart->payment;
+       $_POST['dimension_id'] = $cart->dimension_id;
+       $_POST['dimension2_id'] = $cart->dimension2_id;
  }
  
  //-----------------------------------------------------------------------------
@@@ -265,7 -264,7 +266,7 @@@ function check_data(
        }
  
        if (!is_date_in_fiscalyear($_POST['InvoiceDate'])) {
 -              display_error(_("The entered invoice date is not in fiscal year."));
 +              display_error(_("The entered date is out of fiscal year or is closed for further data entry."));
                set_focus('InvoiceDate');
                return false;
        }
@@@ -330,6 -329,16 +331,16 @@@ if (isset($_POST['process_invoice']) &
        }
  }
  
+ if(list_updated('payment')) {
+       $order = &$_SESSION['Items'];
+       $order->payment = get_post('payment');
+       $order->payment_terms = get_payment_terms($order->payment);
+       $order->due_date = get_invoice_duedate($order->payment, $order->document_date);
+       if ($order->payment_terms['cash_sale']) {
+               $_POST['Location'] = $order->Location = $order->pos['pos_location'];
+               $order->location_name = $order->pos['location_name'];
+       }
+ }
  // find delivery spans for batch invoice display
  $dspans = array();
  $lastdn = ''; $spanlen=1;
@@@ -369,7 -378,6 +380,6 @@@ if ($dim > 0
  label_cells(_("Customer"), $_SESSION['Items']->customer_name, "class='tableheader2'");
  label_cells(_("Branch"), get_branch_name($_SESSION['Items']->Branch), "class='tableheader2'");
  if ($_SESSION['Items']->pos['credit_sale'] || $_SESSION['Items']->pos['cash_sale']) {
-  // editable payment type
        $paymcat = !$_SESSION['Items']->pos['cash_sale'] ? PM_CREDIT :
                (!$_SESSION['Items']->pos['credit_sale'] ? PM_CASH : PM_ANY);
        label_cells(_("Payment terms:"), sale_payment_list('payment', $paymcat),
@@@ -393,8 -401,15 +403,15 @@@ label_cells(_("Sales Type"), $_SESSION[
  
  label_cells(_("Currency"), $_SESSION['Items']->customer_currency, "class='tableheader2'");
  // 2010-09-03 Joe Hunt
- if ($dim > 0) 
-       label_cells(_("Dimension"), get_dimension_string($_SESSION['Items']->dimension_id), "class='tableheader2'");
+ //if ($dim > 0) 
+ //    label_cells(_("Dimension"), get_dimension_string($_SESSION['Items']->dimension_id), "class='tableheader2'");
+ if ($dim > 0) {
+       label_cell(_("Dimension").":", "class='tableheader2'");
+       $_POST['dimension_id'] = $_SESSION['Items']->dimension_id;
+       dimensions_list_cells(null, 'dimension_id', null, true, ' ', false, 1, false);
+ }             
+ else
+       hidden('dimension_id', 0);
  
  end_row();
  start_row();
@@@ -420,11 -435,19 +437,19 @@@ if (!isset($_POST['due_date']) || !is_d
  }
  
  date_cells(_("Due Date"), 'due_date', '', null, 0, 0, 0, "class='tableheader2'");
+ /*
  if ($dim > 1) 
        label_cells(_("Dimension"). " 2", get_dimension_string($_SESSION['Items']->dimension2_id), "class='tableheader2'");
  else if ($dim > 0)
        label_cell("&nbsp;", "colspan=2");
+ */
+ if ($dim > 1) {
+       label_cell(_("Dimension")." 2:", "class='tableheader2'");
+       $_POST['dimension2_id'] = $_SESSION['Items']->dimension2_id;
+       dimensions_list_cells(null, 'dimension2_id', null, true, ' ', false, 2, false);
+ }             
+ else
+       hidden('dimension2_id', 0);
  end_row();
  end_table();
  
index 1bf8e196fbb8651ec097eb839d7eba4dc8427292,f5d1f011a5e9a1ec4347023e295c3c45bf721738..e268dd22d73f75d0160416ab27bbb6b05e958ee6
@@@ -39,6 -39,35 +39,35 @@@ check_db_has_customers(_("There are no 
  check_db_has_bank_accounts(_("There are no bank accounts defined in the system."));
  
  //----------------------------------------------------------------------------------------
+ if (isset($_GET['customer_id']))
+ {
+       $_POST['customer_id'] = $_GET['customer_id'];
+ }
+ if (!isset($_POST['bank_account']))
+ { // first page call
+       $_SESSION['alloc'] = new allocation(ST_CUSTPAYMENT,0);
+       if (isset($_GET['SInvoice'])) {
+               //  get date and supplier
+               $inv = get_customer_trans($_GET['SInvoice'], ST_SALESINVOICE);
+               if($inv) {
+                       $_POST['customer_id'] = $inv['debtor_no'];
+                       $_POST['DateBanked'] = sql2date($inv['tran_date']);
+                       foreach($_SESSION['alloc']->allocs as $line => $trans) {
+                               if ($trans->type == ST_SALESINVOICE && $trans->type_no == $_GET['SInvoice']) {
+                                       $_POST['amount'] =
+                                               $_SESSION['alloc']->amount = price_format($_SESSION['alloc']->allocs[$line]->amount);
+                                       $_SESSION['alloc']->allocs[$line]->current_allocated =
+                                               $_SESSION['alloc']->allocs[$line]->amount;
+                                       break;
+                               }
+                       }
+                       unset($inv);
+               } else
+                       display_error(_("Invalid sales invoice number."));
+       }
+ }
  
  if (list_updated('BranchID')) {
        // when branch is selected via external editor also customer can change
@@@ -56,6 -85,7 +85,7 @@@ if (!isset($_POST['DateBanked'])) 
        }
  }
  
  if (isset($_GET['AddedID'])) {
        $payment_no = $_GET['AddedID'];
  
  
        display_note(get_gl_view_str(ST_CUSTPAYMENT, $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"));
+       
+       display_footer_exit();
+ }
+ elseif (isset($_GET['UpdatedID'])) {
+       $payment_no = $_GET['UpdatedID'];
+       display_notification_centered(_("The customer payment has been successfully updated."));
+       submenu_print(_("&Print This Receipt"), ST_CUSTPAYMENT, $payment_no."-".ST_CUSTPAYMENT, 'prtopt');
+       display_note(get_gl_view_str(ST_CUSTPAYMENT, $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"));
@@@ -78,7 -123,7 +123,7 @@@ function can_process(
  {
        global $Refs;
  
-       if (!get_post('customer_id')) 
+       if (!get_post('customer_id'))
        {
                display_error(_("There is no customer selected."));
                set_focus('customer_id');
                set_focus('DateBanked');
                return false;
        } elseif (!is_date_in_fiscalyear($_POST['DateBanked'])) {
 -              display_error(_("The entered date is not in fiscal year."));
 +              display_error(_("The entered date is out of fiscal year or is closed for further data entry."));
                set_focus('DateBanked');
                return false;
        }
                return false;
        }
  
-       if (!is_new_reference($_POST['ref'], ST_CUSTPAYMENT)) {
+       //Chaitanya : 13-OCT-2011 - To support Edit feature
+       if (isset($_POST['trans_no']) && $_POST['trans_no'] == 0 && (!is_new_reference($_POST['ref'], ST_CUSTPAYMENT))) {
                display_error(_("The entered reference is already in use."));
                set_focus('ref');
                return false;
        }
+       //Avoid duplicate reference while modifying
+       elseif ($_POST['ref'] != $_POST['old_ref'] && !is_new_reference($_POST['ref'], ST_CUSTPAYMENT))
+       {
+               display_error( _("The entered reference is already in use."));
+               set_focus('ref');
+               return false;
+       }
  
        if (!check_num('amount', 0)) {
                display_error(_("The entered amount is invalid or negative and cannot be processed."));
@@@ -183,8 -236,22 +236,22 @@@ if (isset($_POST['_customer_id_button']
  if (isset($_POST['_DateBanked_changed'])) {
    $Ajax->activate('_ex_rate');
  }
- if (list_updated('customer_id') || list_updated('bank_account')) {
+ //Chaitanya : 13-OCT-2011 - To support Edit feature
+ if (isset($_POST['ref']) && $_SESSION['alloc']->trans_no == 0) // added by Joe to fix the browser back button
+ {
+       $tno = get_customer_trans_from_ref(ST_CUSTPAYMENT, $_POST['ref']);
+       if ($tno != false)
+       {
+               display_error( _("The entered reference is already in use."));
+               display_footer_exit();
+       }
 -}             
++}
+ $new = $_SESSION['alloc']->trans_no == 0;
+ if (list_updated('customer_id') || ($new && list_updated('bank_account'))) {
    $_SESSION['alloc']->read();
+   $_POST['memo_'] = $_POST['amount'] = $_POST['discount'] = '';
    $Ajax->activate('alloc_tbl');
  }
  //----------------------------------------------------------------------------------------------
@@@ -201,40 -268,94 +268,94 @@@ if (isset($_POST['AddPaymentItem'])) 
  
        new_doc_date($_POST['DateBanked']);
  
-       $payment_no = write_customer_payment(0, $_POST['customer_id'], $_POST['BranchID'],
+       //Chaitanya : 13-OCT-2011 - To support Edit feature
+       $payment_no = write_customer_payment($_SESSION['alloc']->trans_no, $_POST['customer_id'], $_POST['BranchID'],
                $_POST['bank_account'], $_POST['DateBanked'], $_POST['ref'],
                input_num('amount'), input_num('discount'), $_POST['memo_'], $rate, input_num('charge'));
  
        $_SESSION['alloc']->trans_no = $payment_no;
        $_SESSION['alloc']->write();
+       
+       unset($_POST);
+       unset($_SESSION);
  
-       meta_forward($_SERVER['PHP_SELF'], "AddedID=$payment_no");
+       //Chaitanya : 13-OCT-2011 - To support Edit feature
+       //meta_forward($_SERVER['PHP_SELF'], "AddedID=$payment_no");
+       meta_forward($_SERVER['PHP_SELF'], $new ? "AddedID=$payment_no" : "UpdatedID=$payment_no");
  }
  
  //----------------------------------------------------------------------------------------------
  
  function read_customer_data()
  {
-       global $Refs;
+       global $Refs, $new;
  
        $myrow = get_customer_habit($_POST['customer_id']);
  
        $_POST['HoldAccount'] = $myrow["dissallow_invoices"];
        $_POST['pymt_discount'] = $myrow["pymt_discount"];
-       $_POST['ref'] = $Refs->get_next(ST_CUSTPAYMENT);
+       //Chaitanya : 13-OCT-2011 - To support Edit feature
+       //If page is called first time and New entry fetch the nex reference number
+       if ($new && !isset($_POST['charge'])) 
+               $_POST['ref'] = $Refs->get_next(ST_CUSTPAYMENT);
  }
  
+ //----------------------------------------------------------------------------------------------
+ $new = 1;
+ $old_ref = 0;
+ //Chaitanya : 13-OCT-2011 - To support Edit feature
+ if (isset($_GET['trans_no']) && $_GET['trans_no'] > 0 )
+       $_POST['trans_no'] = $_GET['trans_no'];
+ //Read data
+ if (isset($_POST['trans_no']) && $_POST['trans_no'] > 0 )
+ {     
+       $new = 0;
+       $myrow = get_customer_trans($_POST['trans_no'], ST_CUSTPAYMENT);
+       $_POST['customer_id'] = $myrow["debtor_no"];
+       $_POST['customer_name'] = $myrow["DebtorName"];
+       $_POST['BranchID'] = $myrow["branch_code"];
+       $_POST['bank_account'] = $myrow["bank_act"];
+       $_POST['ref'] =  $myrow["reference"];
+       $old_ref = $myrow["reference"];
+       //$_POST['charge'] =  $myrow[""];
+       $_POST['DateBanked'] =  sql2date($myrow['tran_date']);
+       $_POST["amount"] = price_format($myrow['Total'] - $myrow['ov_discount']);
+       $_POST["discount"] = price_format($myrow['ov_discount']);
+       $_POST["memo_"] = get_comments_string(ST_CUSTPAYMENT,$_POST['trans_no']);
+ }
+ else
+       $_POST['trans_no'] = 0;
  //----------------------------------------------------------------------------------------------
  
  start_form();
  
+       hidden('trans_no', $_POST['trans_no']);
+       hidden('old_ref', $old_ref);
        start_outer_table(TABLESTYLE2, "width=60%", 5);
        table_section(1);
  
-       customer_list_row(_("From Customer:"), 'customer_id', null, false, true);
-       if (!isset($_POST['bank_account'])) // first page call
-                 $_SESSION['alloc'] = new allocation(ST_CUSTPAYMENT,0);
+       if ($new)
+               customer_list_row(_("From Customer:"), 'customer_id', null, false, true);
+       else {
+               label_cells(_("From Customer:"), $_POST['customer_name'], "class='label'");
+               hidden('customer_id', $_POST['customer_id']);
+       }
  
+       if (!isset($_POST['charge'])) // first page call
+       {
+               //Prepare allocation cart 
+               if (isset($_POST['trans_no']) && $_POST['trans_no'] > 0 )
+                       $_SESSION['alloc'] = new allocation(ST_CUSTPAYMENT,$_POST['trans_no']);
+               else
+               {
+                       $_SESSION['alloc'] = new allocation(ST_CUSTPAYMENT,0);
+                       $Ajax->activate('alloc_tbl');
+               }
+       }
+       
        if (db_customer_has_branches($_POST['customer_id'])) {
                customer_branches_list_row(_("Branch:"), $_POST['customer_id'], 'BranchID', null, false, true, true);
        } else {
        read_customer_data();
  
        set_global_customer($_POST['customer_id']);
-       if (isset($_POST['HoldAccount']) && $_POST['HoldAccount'] != 0) {
-               end_outer_table();
-               display_error(_("This customer account is on hold."));
-       } else {
-               $display_discount_percent = percent_format($_POST['pymt_discount']*100) . "%";
-               table_section(2);
+       if (isset($_POST['HoldAccount']) && $_POST['HoldAccount'] != 0) 
+               display_warning(_("This customer account is on hold."));
+       $display_discount_percent = percent_format($_POST['pymt_discount']*100) . "%";
  
-               bank_accounts_list_row(_("Into Bank Account:"), 'bank_account', null, true);
+       table_section(2);
+       if (!list_updated('bank_account'))
+               $_POST['bank_account'] = get_default_customer_bank_account($_POST['customer_id']);      
  
 -
+       //Chaitanya : 13-OCT-2011 - Is AJAX call really needed ???
+       //bank_accounts_list_row(_("Into Bank Account:"), 'bank_account', null, true);
+       bank_accounts_list_row(_("Into Bank Account:"), 'bank_account', null, false);
+       text_row(_("Reference:"), 'ref', null, 20, 40);
  
-               text_row(_("Reference:"), 'ref', null, 20, 40);
+       table_section(3);
  
-               table_section(3);
+       date_row(_("Date of Deposit:"), 'DateBanked', '', true, 0, 0, 0, null, true);
  
-               date_row(_("Date of Deposit:"), 'DateBanked', '', true, 0, 0, 0, null, true);
-               $comp_currency = get_company_currency();
-               $cust_currency = get_customer_currency($_POST['customer_id']);
-               $bank_currency = get_bank_account_currency($_POST['bank_account']);
+       $comp_currency = get_company_currency();
+       $cust_currency = get_customer_currency($_POST['customer_id']);
+       $bank_currency = get_bank_account_currency($_POST['bank_account']);
  
-               if ($cust_currency != $bank_currency) {
-                       exchange_rate_display($bank_currency, $cust_currency, $_POST['DateBanked'], ($bank_currency == $comp_currency));
-               }
+       if ($cust_currency != $bank_currency) {
+               exchange_rate_display($bank_currency, $cust_currency, $_POST['DateBanked'], ($bank_currency == $comp_currency));
+       }
  
-               amount_row(_("Bank Charge:"), 'charge');
+       amount_row(_("Bank Charge:"), 'charge');
  
-               end_outer_table(1);
+       end_outer_table(1);
  
-               if ($cust_currency == $bank_currency) {
-                       div_start('alloc_tbl');
-                       show_allocatable(false);
-                       div_end();
-               }
+       if ($cust_currency == $bank_currency) {
+               div_start('alloc_tbl');
+               show_allocatable(false);
+               div_end();
+       }
  
-               start_table(TABLESTYLE, "width=60%");
+       start_table(TABLESTYLE, "width=60%");
  
-               label_row(_("Customer prompt payment discount :"), $display_discount_percent);
-               amount_row(_("Amount of Discount:"), 'discount');
+       label_row(_("Customer prompt payment discount :"), $display_discount_percent);
+       amount_row(_("Amount of Discount:"), 'discount');
  
-               amount_row(_("Amount:"), 'amount');
+       amount_row(_("Amount:"), 'amount');
  
-               textarea_row(_("Memo:"), 'memo_', null, 22, 4);
-               end_table(1);
+       textarea_row(_("Memo:"), 'memo_', null, 22, 4);
+       end_table(1);
  
-               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."));
  
-               br();
+       br();
  
+       if (isset($_POST['trans_no']) && $_POST['trans_no'] > 0 )
+               submit_center('AddPaymentItem', _("Update Payment"), true, '', 'default');
+       else
                submit_center('AddPaymentItem', _("Add Payment"), true, '', 'default');
-       }
  
        br();
  
index 46f8d5009436fa31661a8b86d8b42655aed4b96b,cc7d15675b660a8437f6f08c7e8fbd94c0d6d58c..062d9bad732a49529f6b417d2af54dce4e625a9f
@@@ -64,9 -64,7 +64,9 @@@ class car
        var $tax_group_array = null; // saves db queries
        var $price_factor;       // ditto for price calculations
  
 -      var     $pos;                   // user assigned POS (contains cash accont number/name)
 +      var     $pos;                   // user assigned POS
 +      var $cash_account;
 +      var $account_name;
        var $cash_discount;     // not used as of FA 2.1
        var $dimension_id;
        var $dimension2_id;
        //-------------------------------------------------------------------------
        //
        //  $trans_no==0 => open new/direct document
 -      //  $trans_no!=0 && $prep_child==false => update with parent constarints for reedition
 -      //  $trans_no!=0 && $prep_child==true => prepare for child doc entry
 +      //  $trans_no!=0 && $no_edit==false => update with parent constarints for reedition
 +      //  $trans_no!=0 && $no_edit==true => read only: for view, or later child doc entry
        //
-       function Cart($type, $trans_no=0, $no_edit=false) {
+       function Cart($type, $trans_no=0, $prep_child=false) {
                /*Constructor function initialises a new shopping cart */
                $this->line_items = array();
                $this->sales_type = "";
@@@ -91,7 -89,7 +91,7 @@@
                $this->dimension_id = 0;
                $this->dimension2_id = 0;
                $this->pos = get_sales_point(user_pos());
-               $this->read($type, $trans_no, $no_edit);
+               $this->read($type, $trans_no, $prep_child);
                $this->cart_id = uniqid('');
        }
        
                }
                unset($line);
                
-               if ($type == ST_CUSTDELIVERY)
+               if ($type == ST_CUSTDELIVERY) {
                        $this->order_no = key($this->trans_no);
+                       $cust = get_customer($this->customer_id);
+                       $this->dimension_id = $cust['dimension_id'];
+                       $this->dimension2_id = $cust['dimension2_id'];
+               }
                if ($type == ST_SALESINVOICE) {
                        $this->due_date = get_invoice_duedate($this->payment, $this->document_date);
                }
        function set_parent_constraints($sodata, $src_no) {
  
                $srcdetails = get_sales_parent_lines($this->trans_type, $src_no);
-               
                $src_type = get_parent_type($this->trans_type);
-               if ($src_type == ST_SALESORDER || $src_type == 0) {
-                       $this->src_docs = array( $sodata['order_no']=>$sodata['version']);
-               } else {        // get src_data from debtor_trans
-                       $srcnum = array();
-                       while ($line = db_fetch($srcdetails)) {
-                               $srcnum[] = $line['debtor_trans_no'];
-                       }
-                       $this->src_docs = get_customer_trans_version($src_type, array_values($srcnum));
-               }
                // calculate & save: qtys on other docs and free qtys on src doc
-               $line_no = 0;
+               $line_no = 0; $src_docs = array();
                // Loop speed optimisation below depends on fact 
                // that child line_items contains subset of parent lines in _the_same_ order !
-               while ($line_no < count($this->line_items) && $srcline = db_fetch($srcdetails)) {
+               while (($line_no < count($this->line_items)) && ($srcline = db_fetch($srcdetails))) {
                        $line = &$this->line_items[$line_no];
+                       $src_docs[] = $src_type == ST_SALESORDER ?  $srcline['order_no'] : $srcline['debtor_trans_no'];
                        if ($srcline['id'] == $line->src_id) {
                                if ($this->trans_type == ST_SALESINVOICE)
                                        $line->src_no = $srcline['debtor_trans_no'];
                                $line->quantity += $srcline['quantity'] - 
                                        ($src_type==ST_SALESORDER ? $srcline['qty_sent'] : $srcline['qty_done']); // add free qty on src doc
                                $line_no++;
-                               break;
                        }
                }
+               if ($src_type == ST_SALESORDER || $src_type == 0) {
+                       $this->src_docs = array( $sodata['order_no']=>$sodata['version']);
+               } else {
+                       // get src_data from debtor_trans
+                       $this->src_docs = get_customer_trans_version($src_type, array_unique($src_docs));
+               }
        }
        //-------------------------------------------------------------------------
        // Reading document into cart
        //
-       function read($type, $trans_no = 0, $no_edit=false) {
+       function read($type, $trans_no=0, $prep_child=false) {
  
                global $SysPrefs, $Refs;
  
                        if ($type == ST_SALESORDER || $type == ST_SALESQUOTE) { // sales order || sales quotation
                                read_sales_order($trans_no[0], $this, $type);
                        } else {        // other type of sales transaction
-                                       read_sales_trans($type, $trans_no, $this);
+                                       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, ST_SALESORDER);
                                                $this->cust_ref = $sodata["customer_ref"];
                                                $this->delivery_to = $sodata["deliver_to"];
                                                $this->delivery_address = $sodata["delivery_address"];
                                        // child transaction reedition - update with parent info unless it is freehand
-                                               if (!$no_edit)
-                                                       $this->set_parent_constraints($sodata, $trans_no[0]);
+                                       if (!$prep_child) // this is read for view/reedition
+                                               $this->set_parent_constraints($sodata, $trans_no[0]);
                                        }
                        }
-                       // prepare qtys for derivative document entry (not used in display)
-                       if($no_edit) {
-                               for($line_no = 0; $line_no < count($this->line_items); $line_no++) {
-                                       $line = &$this->line_items[$line_no];
-                                       $line->src_id = $line->id; // save src line ids for update
-                                       $line->qty_dispatched = $line->quantity - $line->qty_done;
-                               }
-                       }
+                       // convert document into child and prepare qtys for entry
+                       if ($prep_child)
+                               $this->prepare_child();
                } else { // new document
                                $this->trans_type = $type;
                                $this->trans_no = 0;
                                  $this->customer_id = get_global_customer();
                                else
                                  $this->customer_id = '';
-                               $this->document_date =  new_doc_date();
+                               $this->document_date = new_doc_date();
                                if (!is_date_in_fiscalyear($this->document_date))
                                        $this->document_date = end_fiscalyear();
                                $this->reference = $Refs->get_next($this->trans_type);
        // Writing new/modified sales document to database.
        // Makes parent documents for direct delivery/invoice by recurent call.
        // $policy - 0 or 1:  writeoff/return for IV, back order/cancel for DN
 -      function write($policy=0) { 
 +      function write($policy=0) {
                begin_transaction(); // prevents partial database changes in case of direct delivery/invoice
                if (count($this->src_docs) == 0 && ($this->trans_type == ST_SALESINVOICE || $this->trans_type == ST_CUSTDELIVERY)) {
                        // this is direct document - first add parent
-                       $src = (PHP_VERSION<5) ? $this : clone( $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;
                        $date = $this->document_date;
-                       // re-read document
-                       $this->read($src->trans_type, key($src->trans_no), true);
+                       $due_date = $this->due_date;
+                       $this->trans_type = get_parent_type($this->trans_type);
+                       $this->reference = 'auto'; 
+                       $trans_no = $this->write(1); 
+                       // re-read parent document converting it to child
+                       $this->read($this->trans_type, $trans_no, true); 
                        $this->document_date = $date;
                        $this->reference = $ref;
-                       $this->trans_type = $type;
-                       $this->src_docs= $this->trans_no;
-                       $this->trans_no = 0;
-                       $this->order_no= $this->trans_type==ST_CUSTDELIVERY ? key($src->trans_no) : $src->order_no;
+                       $this->due_date = $due_date;
                }
                $this->reference = @html_entity_decode($this->reference, ENT_QUOTES);
                $this->Comments = @html_entity_decode($this->Comments, ENT_QUOTES);
                if ($this->payment_terms['cash_sale']) {
                        $this->Location = $this->pos['pos_location'];
                        $this->location_name = $this->pos['location_name'];
-                       $this->cash_account = $this->pos['pos_account'];
-                       $this->account_name = $this->pos['bank_account_name'];
                }
                $this->credit = get_current_cust_credit($customer_id);
        }
        function get_shipping_tax()
        {
  
 -              $tax_items = get_shipping_tax_as_array();
 +              $tax_items = get_shipping_tax_as_array($this->tax_group_id);
                $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])) {
+                               if (isset($this->tax_group_array[$index]['rate'])) {
                                        $tax_rate += $item_tax['rate'];
                                }
                        }
index a9683a27bf8281a51f60576ca81928f879a85ea0,c02b74c2d8ad81747cbbd572c69a099555774e3b..09b1fbe4f28af171c013cd574c5bbc028b5bdf9c
  function add_branch($customer_id, $br_name, $br_ref, $br_address, $salesman, $area, 
        $tax_group_id, $sales_account, $sales_discount_account, $receivables_account, 
        $payment_discount_account, $default_location, $br_post_address, $disable_trans, $group_no,
 -      $default_ship_via, $notes)
 +      $default_ship_via, $notes, $bank_account)
  {
        $sql = "INSERT INTO ".TB_PREF."cust_branch (debtor_no, br_name, branch_ref, br_address,
                salesman, area, tax_group_id, sales_account, receivables_account, payment_discount_account, 
                sales_discount_account, default_location,
 -              br_post_address, disable_trans, group_no, default_ship_via, notes)
 +              br_post_address, disable_trans, group_no, default_ship_via, notes, bank_account)
                VALUES (".db_escape($customer_id). ",".db_escape($br_name) . ", "
                        .db_escape($br_ref) . ", "
                        .db_escape($br_address) . ", ".db_escape($salesman) . ", "
                        .db_escape($disable_trans) . ", "
                        .db_escape($group_no) . ", "
                        .db_escape($default_ship_via). ", "
 -                      .db_escape($notes).")";
 +                      .db_escape($notes). ", "
 +                      .db_escape($bank_account, true).")";
        db_query($sql,"The branch record could not be added");
  }
  
  function update_branch($customer_id, $branch_code, $br_name, $br_ref, $br_address,
        $salesman, $area, $tax_group_id, $sales_account, $sales_discount_account, $receivables_account, 
        $payment_discount_account, $default_location, $br_post_address, $disable_trans, $group_no,
 -      $default_ship_via, $notes)
 +      $default_ship_via, $notes, $bank_account)
  {
        $sql = "UPDATE ".TB_PREF."cust_branch SET br_name = " . db_escape($br_name) . ",
                branch_ref = " . db_escape($br_ref) . ",
@@@ -57,8 -56,7 +57,8 @@@
                disable_trans=".db_escape($disable_trans) . ",
                group_no=".db_escape($group_no) . ", 
                default_ship_via=".db_escape($default_ship_via) . ",
 -              notes=".db_escape($notes) . "
 +              notes=".db_escape($notes) . ",
 +              bank_account=".db_escape($bank_account, true)."
                WHERE branch_code =".db_escape($branch_code) . "
                AND debtor_no=".db_escape($customer_id);
        db_query($sql,"The branch record could not be updated");
@@@ -166,7 -164,7 +166,7 @@@ function get_sql_for_customer_branches(
                AND b.debtor_no = ".db_escape($_POST['customer_id']);
  
        if (!get_post('show_inactive')) $sql .= " AND !b.inactive";
-       $sql .= " ORDER BY branch_ref";
+       $sql .= " GROUP BY b.branch_code ORDER BY branch_ref";
  
        return $sql;
  }
index 09b635fc9ea0f02e74ddc8bbfd6621b72d2aac9c,bf28fe604863b255ec56bd2ab67e3237bc4e1f90..a07bdc4f692b18f17ca8909da84ca835002ee1ca
@@@ -43,7 -43,7 +43,7 @@@ function get_customer_trans_version($ty
        $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'];
@@@ -56,7 -56,7 +56,7 @@@
  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, $ship_via=0, $due_date="",
 -      $AllocAmt=0, $rate=0, $dimension_id=0, $dimension2_id=0, $payment_terms=null)
 +      $AllocAmt=0, $rate=0, $dimension_id=0, $dimension2_id=0, $payment_terms=null, $tax_included=0)
  {
        $new = $trans_no==0;
        $curr = get_customer_currency($debtor_no);
        if ($trans_type == ST_BANKPAYMENT)
                $Total = -$Total;
  
-       if ($new) {
-       $trans_no = get_next_trans_no($trans_type);
+     if ($new || !exists_customer_trans($trans_type, $trans_no))
+     {
+         if ($new)
+         $trans_no = get_next_trans_no($trans_type);
  
        $sql = "INSERT INTO ".TB_PREF."debtor_trans (
                trans_no, type,
@@@ -83,7 -85,7 +85,7 @@@
                order_, ov_amount, ov_discount,
                ov_gst, ov_freight, ov_freight_tax,
                rate, ship_via, alloc,
 -              dimension_id, dimension2_id, payment_terms
 +              dimension_id, dimension2_id, payment_terms, tax_included
                ) VALUES (".db_escape($trans_no).", ".db_escape($trans_type).",
                ".db_escape($debtor_no).", ".db_escape($BranchNo).",
                '$SQLDate', '$SQLDueDate', ".db_escape($reference).",
@@@ -91,8 -93,7 +93,8 @@@
                ".db_escape($Freight).",
                $FreightTax, $rate, ".db_escape($ship_via).", $AllocAmt,
                ".db_escape($dimension_id).", ".db_escape($dimension2_id).", "
 -              .db_escape($payment_terms, true).")";
 +              .db_escape($payment_terms, true).", "
 +              .db_escape($tax_included).")";
        } else {        // may be optional argument should stay unchanged ?
        $sql = "UPDATE ".TB_PREF."debtor_trans SET
                debtor_no=".db_escape($debtor_no)." , branch_code=".db_escape($BranchNo).",
                ov_freight=".db_escape($Freight).", ov_freight_tax=$FreightTax, rate=$rate,
                ship_via=".db_escape($ship_via).", alloc=$AllocAmt,
                dimension_id=".db_escape($dimension_id).", dimension2_id=".db_escape($dimension2_id).",
 -              payment_terms=".db_escape($payment_terms)."
 +              payment_terms=".db_escape($payment_terms).",
 +              tax_included=".db_escape($tax_included)."
                WHERE trans_no=".db_escape($trans_no)." AND type=".db_escape($trans_type);
        }
        db_query($sql, "The debtor transaction record could not be inserted");
@@@ -124,7 -124,8 +126,8 @@@ function get_customer_trans($trans_id, 
  
        if ($trans_type == ST_CUSTPAYMENT) {
                // it's a payment so also get the bank account
-               $sql .= ", ".TB_PREF."bank_accounts.bank_name, ".TB_PREF."bank_accounts.bank_account_name,
+               // Chaitanya : Added bank_act to support Customer Payment Edit
+               $sql .= ",bank_act,".TB_PREF."bank_accounts.bank_name, ".TB_PREF."bank_accounts.bank_account_name,
                        ".TB_PREF."bank_accounts.account_type AS BankTransType ";
        }
  
                // it's a payment so also get the bank account
                $sql .= " AND ".TB_PREF."bank_trans.trans_no =".db_escape($trans_id)."
                        AND ".TB_PREF."bank_trans.type=$trans_type
+                       AND ".TB_PREF."bank_trans.amount != 0
                        AND ".TB_PREF."bank_accounts.id=".TB_PREF."bank_trans.bank_act ";
        }
        if ($trans_type == ST_SALESINVOICE || $trans_type == ST_CUSTCREDIT || $trans_type == ST_CUSTDELIVERY) {
@@@ -204,6 -206,19 +208,19 @@@ function exists_customer_trans($type, $
  
  //----------------------------------------------------------------------------------------
  
+ function get_customer_trans_from_ref($type, $ref)
+ {
+       $sql = "SELECT trans_no FROM ".TB_PREF."debtor_trans WHERE type=".db_escape($type)."
+               AND reference=".db_escape($ref);
+       $result = db_query($sql, "Cannot retreive a debtor transaction");
+       $row = db_fetch_row($result);
+       return $row[0];
+ }
+ //----------------------------------------------------------------------------------------
  // retreives the related sales order for a given trans
  
  function get_customer_trans_order($type, $type_no)
@@@ -317,7 -332,7 +334,7 @@@ function get_sql_for_customer_inquiry(
        {
                if ($_POST['filterType'] == '1')
                {
-                       $sql .= " AND (trans.type = ".ST_SALESINVOICE." OR trans.type = ".ST_BANKPAYMENT.") ";
+                       $sql .= " AND (trans.type = ".ST_SALESINVOICE.") ";
                }
                elseif ($_POST['filterType'] == '2')
                {
                elseif ($_POST['filterType'] == '3')
                {
                        $sql .= " AND (trans.type = " . ST_CUSTPAYMENT 
-                                       ." OR trans.type = ".ST_BANKDEPOSIT.") ";
+                                       ." OR trans.type = ".ST_BANKDEPOSIT." OR trans.type = ".ST_BANKPAYMENT.") ";
                }
                elseif ($_POST['filterType'] == '4')
                {
index bd5b8d34583d578cbd52ef80ba43df2b31ee16c0,3a67e4edb895d29189e5307c8e526ff328066ca9..21ce5e41e871791fbf20d96f99a70ad6baed339b
@@@ -24,7 -24,7 +24,6 @@@ function add_customer($CustName, $cust_
                " . db_escape($credit_status) . ", ".db_escape($payment_terms) . ", " . $discount . ", 
                " . $pymt_discount . ", " . $credit_limit 
                 .", ".db_escape($sales_type).", ".db_escape($notes) . ")";
--
        db_query($sql,"The customer could not be added");
  }
  
@@@ -61,7 -61,7 +60,7 @@@ function delete_customer($customer_id
        commit_transaction();
  }
  
- function get_customer_details($customer_id, $to=null)
+ function get_customer_details($customer_id, $to=null, $all=true)
  {
  
        if ($to == null)
        $past1 = get_company_pref('past_due_days');
        $past2 = 2 * $past1;
        // removed - debtor_trans.alloc from all summations
-     $value = "IFNULL(IF(trans.type=11 OR trans.type=12 OR trans.type=2, -1, 1) 
-       * (trans.ov_amount + trans.ov_gst + trans.ov_freight + trans.ov_freight_tax + trans.ov_discount),0)";
+       if ($all)
+       $value = "IFNULL(IF(trans.type=11 OR trans.type=12 OR trans.type=2, -1, 1) 
+               * (trans.ov_amount + trans.ov_gst + trans.ov_freight + trans.ov_freight_tax + trans.ov_discount),0)";
+     else              
+       $value = "IFNULL(IF(trans.type=11 OR trans.type=12 OR trans.type=2, -1, 1) 
+               * (trans.ov_amount + trans.ov_gst + trans.ov_freight + trans.ov_freight_tax + trans.ov_discount - 
+               trans.alloc),0)";
        $due = "IF (trans.type=10, trans.due_date, trans.tran_date)";
      $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,
                WHERE
                         ".TB_PREF."debtors_master.payment_terms = ".TB_PREF."payment_terms.terms_indicator
                         AND ".TB_PREF."debtors_master.credit_status = ".TB_PREF."credit_status.id
-                        AND ".TB_PREF."debtors_master.debtor_no = ".db_escape($customer_id)."
-               GROUP BY
+                        AND ".TB_PREF."debtors_master.debtor_no = ".db_escape($customer_id)." ";
+       if (!$all)
+               $sql .= "AND ABS(trans.ov_amount + trans.ov_gst + trans.ov_freight + trans.ov_freight_tax + trans.ov_discount - trans.alloc) > ".FLOAT_COMP_DELTA." ";  
+       $sql .= "GROUP BY
                          ".TB_PREF."debtors_master.name,
                          ".TB_PREF."payment_terms.terms,
                          ".TB_PREF."payment_terms.days_before_due,
index 869dc538accd3e148b33764763cc5ce5ff607be8,d5be9c44b0b16a4a00d7b7e9637ac43f038d6187..0fb76057b1d9e059dbfe548be44132032e73545f
@@@ -17,13 -17,8 +17,13 @@@ function write_credit_note(&$credit_not
  {
        global $Refs;
  
 -      $credit_invoice =       is_array($credit_note->src_docs) ?
 -               reset(array_keys($credit_note->src_docs)) : $credit_note->src_docs;
 +      if (is_array($credit_note->src_docs))
 +      {
 +              $docs = array_keys($credit_note->src_docs);
 +              $credit_invoice = reset($docs);
 +      }
 +      else
 +              $credit_invoice = $credit_note->src_docs;
  
        $credit_date = $credit_note->document_date;
        $tax_group_id = $credit_note->tax_group_id;
@@@ -79,7 -74,7 +79,7 @@@
                $credit_note->freight_cost, $freight_added_tax,
                $credit_note->sales_type, $credit_note->order_no, $credit_note->ship_via,
                null, $alloc, 0, $credit_note->dimension_id, $credit_note->dimension2_id,
 -              $credit_note->payment); 
 +              $credit_note->payment, $credit_note->tax_included); 
                // 2008-06-14 extra $alloc, 2008-11-12 dimension_id Joe Hunt
  
        if ($trans_no==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,
        $credit_type, $price, $credited_invoice=0)
  {
  
+     //Chaitanya : Stamp current cost in stock moves $credit_line does not fetch cost
+     $curr_std_cost = get_standard_cost($credit_line->stock_id);
        if ($credit_type == "Return") {
  
                $reference = "Return ";
                if ($credited_invoice)
                        $reference .= "Ex Inv: " . $credited_invoice;
  
-       add_stock_move_customer(ST_CUSTCREDIT,  $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(ST_CUSTCREDIT,  $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(ST_CUSTCREDIT,  $credit_line->stock_id,
+               key($credit_note->trans_no), $credit_note->Location,
+               $credit_note->document_date, $reference, -$credit_line->qty_dispatched,
+               $curr_std_cost,  0, $price,
+               $credit_line->discount_percent);
  
        }
+     add_stock_move_customer(ST_CUSTCREDIT,  $credit_line->stock_id,
+         key($credit_note->trans_no), $credit_note->Location,
+         $credit_note->document_date, $reference, $credit_line->qty_dispatched,
+         $curr_std_cost,  0, $price,
+         $credit_line->discount_percent);
+ }
  
  //----------------------------------------------------------------------------------------
  
index 8f1c48718c2e440bde837942e73eea83cbfa4c0b,f92feca5b02622541dcddf3a48563d0f883ddaa3..f74afa20ee4a8c474102fb085905cb5487144cb9
@@@ -46,7 -46,7 +46,7 @@@ function write_sales_delivery(&$deliver
                $delivery->tax_included ? 0 : $freight_tax,
                $delivery->sales_type, $delivery->order_no,
                $delivery->ship_via, $delivery->due_date, 0, 0, $delivery->dimension_id, 
 -              $delivery->dimension2_id, $delivery->payment);
 +              $delivery->dimension2_id, $delivery->payment, $delivery->tax_included);
  
        if ($trans_no == 0) {
                $delivery->trans_no = array($delivery_no=>0);
@@@ -67,7 -67,7 +67,7 @@@
                $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;
  
-               if ($trans_no != 0) // Inserted 2008-09-25 Joe Hunt
+               //if ($trans_no != 0) // Inserted 2008-09-25 Joe Hunt. This condition is removed after experience by Chaitanya
                        $delivery_line->standard_cost = get_standard_cost($delivery_line->stock_id);
  
                /* add delivery details for all lines */
        return $delivery_no;
  }
  
+ //--------------------------------------------------------------------------------------------------
+ function adjust_shipping_charge(&$delivery, $trans_no)
+ {
+       $sql = "SELECT sum(ov_freight) as freight FROM ".TB_PREF."debtor_trans WHERE order_ = $trans_no AND type = " . ST_CUSTDELIVERY . " AND debtor_no = " . $delivery->customer_id;
+       $result = db_query($sql, "Can not find delivery notes");
+       $row = db_fetch_row($result);
+       if (!$row[0]) $freight = 0;
+       else $freight = $row[0];
+       if ($freight < $delivery->freight_cost) $delivery->freight_cost = $delivery->freight_cost - $freight;
+       else $delivery->freight_cost = 0;
+ }
  //--------------------------------------------------------------------------------------------------
  
  function void_sales_delivery($type, $type_no, $transactions=true)
  
        if ($order) {
                $auto = (get_reference(ST_SALESORDER, $order) == "auto");
-               $order_items = get_sales_order_details($order, ST_SALESORDER);
                while ($row = db_fetch($items_result)) {
-                       $order_line = db_fetch($order_items);
-                       update_parent_line(ST_CUSTDELIVERY, $order_line['id'], -$row['quantity'], $auto);
+                       update_parent_line(ST_CUSTDELIVERY, $row['src_id'], -$row['quantity'], $auto);
                }
        }
  
index a13109f0e7c91dd37ee8fc13b55d95f49cc53d0c,558b2159aba0159fd9a1bad9c8e0a000ad275cfd..ecaf4466f9bb5f6d1b42c195d56cad1bcac13613
@@@ -64,7 -64,7 +64,7 @@@ function write_sales_invoice(&$invoice
                $items_added_tax, $invoice->freight_cost, $freight_added_tax,
                $invoice->sales_type, $sales_order, $invoice->ship_via, 
                $invoice->due_date, 0, 0, $invoice->dimension_id, 
 -              $invoice->dimension2_id, $invoice->payment); 
 +              $invoice->dimension2_id, $invoice->payment, $invoice->tax_included); 
                // 2008-06-14 extra $alloc, 2008-11-12 added dimension_id Joe Hunt
  
        if ($trans_no == 0) {
        }
        $total = 0;
        foreach ($invoice->line_items as $line_no => $invoice_line) {
+               $qty = $invoice_line->qty_dispatched;
                $line_taxfree_price = get_tax_free_price_for_item($invoice_line->stock_id,
-                       $invoice_line->price, 0, $invoice->tax_included,
+                       $invoice_line->price * $qty, 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_line->price * $qty, 0, $invoice->tax_included,
                        $invoice->tax_group_array) - $line_taxfree_price;
  
                write_customer_trans_detail_item(ST_SALESINVOICE, $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->line_price(), $qty ? $line_tax/$qty : 0, $invoice_line->discount_percent,
                        $invoice_line->standard_cost, $invoice_line->src_id,
                        $trans_no ? $invoice_line->id : 0);
  
                                $dim2 = ($invoice->dimension2_id != $customer['dimension2_id'] ? $invoice->dimension2_id : 
                                        ($customer['dimension2_id'] != 0 ? $customer["dimension2_id"] : $stock_gl_code["dimension2_id"]));
                                $total += add_gl_trans_customer(ST_SALESINVOICE, $invoice_no, $date_, $sales_account, $dim, $dim2,
-                                       (-$line_taxfree_price * $invoice_line->qty_dispatched),
+                                       -$line_taxfree_price ,
                                        $invoice->customer_id, "The sales price GL posting could not be inserted");
  
                                if ($invoice_line->discount_percent != 0) {
  
                                        $total += add_gl_trans_customer(ST_SALESINVOICE, $invoice_no, $date_,
                                                $branch_data["sales_discount_account"], $dim, $dim2,
-                                               ($line_taxfree_price * $invoice_line->qty_dispatched * $invoice_line->discount_percent),
+                                               ($line_taxfree_price * $invoice_line->discount_percent),
                                                $invoice->customer_id, "The sales discount GL posting could not be inserted");
                                } /*end of if discount !=0 */
                        }
                                $taxitem['rate'], $invoice->tax_included, $taxitem['Value'],
                                 $taxitem['Net'], $ex_rate, $date_, $invoice->reference);
  
--                      $total += add_gl_trans_customer(ST_SALESINVOICE, $invoice_no, $date_, $taxitem['sales_gl_code'], 0, 0,
--                              (-$taxitem['Value']), $invoice->customer_id,
--                              "A tax GL posting could not be inserted");
++                      if (isset($taxitem['sales_gl_code']))
++                              $total += add_gl_trans_customer(ST_SALESINVOICE, $invoice_no, $date_, $taxitem['sales_gl_code'], 0, 0,
++                                      (-$taxitem['Value']), $invoice->customer_id,
++                                      "A tax GL posting could not be inserted");
                }
        }
  
  
        if ($trans_no == 0) {
                $Refs->save(ST_SALESINVOICE, $invoice_no, $invoice->reference);
-               if ($invoice->payment_terms['cash_sale']) {
+               if ($invoice->payment_terms['cash_sale'] && $invoice->pos['pos_account']) {
                        $amount = $items_total + $items_added_tax + $invoice->freight_cost 
                                + $freight_added_tax;
  
                        // and change line below.
                        $discount = 0; // $invoice->cash_discount*$amount;
                        $pmtno = write_customer_payment(0, $invoice->customer_id, 
-                               $invoice->Branch, $invoice->cash_account, $date_,
+                               $invoice->Branch, $invoice->pos['pos_account'], $date_,
                                $Refs->get_next(ST_CUSTPAYMENT), $amount-$discount, $discount,
                                _('Cash invoice').' '.$invoice_no);
                        add_cust_allocation($amount, ST_CUSTPAYMENT, $pmtno, ST_SALESINVOICE, $invoice_no);
@@@ -209,7 -209,7 +210,7 @@@ function void_sales_invoice($type, $typ
                {
                        
                        $srcdetails = get_sales_parent_lines($type, $type_no);
-                       while ($row = db_fetch($src_details)) {
+                       while ($row = db_fetch($srcdetails)) {
                                update_parent_line($type, $row['id'], -$row['quantity']);
                        }
                }
index eb5665ab71c46165a324d3da8c31661bc826855d,e4eaa5c15a4d69908b393cad61ea32a49e6feb6b..386e3b86b2a1213d8d6419ab2ad9998d0efa4056
@@@ -87,11 -87,13 +87,16 @@@ function add_sales_order(&$order
                                $line->discount_percent)";
                db_query($sql, "order Details Cannot be Added");
  
+       // Now mark quotation line as processed
+               if ($order->trans_type == ST_SALESORDER && $line->src_id)
+                       update_parent_line(ST_SALESORDER, $line->src_id, $line->qty_dispatched); // clear all the quote despite all or the part was ordered
        } /* inserted line items into sales order details */
+       add_audit_trail($order->trans_type, $order_no, $order->document_date);
+       $Refs->save($order->trans_type, $order_no, $order->reference);
  
 +      add_audit_trail($order->trans_type, $order_no, $order->document_date);
 +      $Refs->save($order->trans_type, $order_no, $order->reference);
 +
        hook_db_postwrite($order, $order->trans_type);
        commit_transaction();
  
@@@ -283,7 -285,8 +288,8 @@@ function get_sales_order_header($order_
          ."stype.tax_included, "
          ."ship.shipper_name, "
          ."tax_group.name AS tax_group_name , "
-         ."tax_group.id AS tax_group_id "
+         ."tax_group.id AS tax_group_id, "
+         ."cust.tax_id "
        ."FROM ".TB_PREF."sales_orders sorder, "
          .TB_PREF."debtors_master cust,"
          .TB_PREF."sales_types stype, "
@@@ -324,8 -327,9 +330,9 @@@ function get_sales_order_details($order
                .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.units,"
+               .TB_PREF."stock_master.mb_flag,"
+               .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
@@@ -486,17 -490,17 +493,17 @@@ function get_branch_to_order($customer_
            return db_query($sql,"Customer Branch Record Retreive");
  }
  
- function get_sql_for_sales_orders_view($selected_customer, $trans_type)
+ function get_sql_for_sales_orders_view($selected_customer, $trans_type, $trans_no, $filter, 
+       $stock_item=null, $from='', $to='', $ref='', $location='', $customer_id=ALL_TEXT)
  {
-       global $selected_stock_item;
-       
        $sql = "SELECT 
                        sorder.order_no,
                        sorder.reference,
                        debtor.name,
                        branch.br_name,"
-                       .($_POST['order_view_mode']=='InvoiceTemplates' 
-                               || $_POST['order_view_mode']=='DeliveryTemplates' ?
+                       .($filter=='InvoiceTemplates' 
+                               || $filter=='DeliveryTemplates' ?
                         "sorder.comments, " : "sorder.customer_ref, ")
                        ."sorder.ord_date,
                        sorder.delivery_date,
                        AND sorder.branch_code = branch.branch_code
                        AND debtor.debtor_no = branch.debtor_no";
  
-       if (isset($_POST['OrderNumber']) && $_POST['OrderNumber'] != "")
+       if (isset($trans_no) && $trans_no != "")
        {
                // search orders with number like 
-               $number_like = "%".$_POST['OrderNumber'];
-               $sql .= " AND sorder.order_no LIKE ".db_escape($number_like)
                              ." GROUP BY sorder.order_no";
+               $number_like = "%".$trans_no;
+               $sql .= " AND sorder.order_no LIKE ".db_escape($number_like);
//                            ." GROUP BY sorder.order_no";
        }
-       elseif (isset($_POST['OrderReference']) && $_POST['OrderReference'] != "")
+       elseif ($ref != "")
        {
                // search orders with reference like 
-               $number_like = "%".$_POST['OrderReference']."%";
-               $sql .= " AND sorder.reference LIKE ".db_escape($number_like)
                              ." GROUP BY sorder.order_no";
+               $number_like = "%".$ref."%";
+               $sql .= " AND sorder.reference LIKE ".db_escape($number_like);
//                            ." GROUP BY sorder.order_no";
        }
        else    // ... or select inquiry constraints
        {
-               if ($_POST['order_view_mode']!='DeliveryTemplates' && $_POST['order_view_mode']!='InvoiceTemplates')
+               if ($filter!='DeliveryTemplates' && $filter!='InvoiceTemplates' && $filter!='OutstandingOnly')
                {
-                       $date_after = date2sql($_POST['OrdersAfterDate']);
-                       $date_before = date2sql($_POST['OrdersToDate']);
+                       $date_after = date2sql($from);
+                       $date_before = date2sql($to);
  
                        $sql .=  " AND sorder.ord_date >= '$date_after'"
                                        ." AND sorder.ord_date <= '$date_before'";
                }
+       }
                if ($trans_type == ST_SALESQUOTE && !check_value('show_all'))
-                       $sql .= " AND sorder.delivery_date >= '".date2sql(Today())."'";
+                       $sql .= " AND sorder.delivery_date >= '".date2sql(Today())."' AND line.qty_sent=0"; // show only outstanding, not realized quotes
                if ($selected_customer != -1)
                        $sql .= " AND sorder.debtor_no=".db_escape($selected_customer);
  
-               if (isset($selected_stock_item))
-                       $sql .= " AND line.stk_code=".db_escape($selected_stock_item);
+               if (isset($stock_item))
+                       $sql .= " AND line.stk_code=".db_escape($stock_item);
  
-               if (isset($_POST['StockLocation']) && $_POST['StockLocation'] != ALL_TEXT)
-                       $sql .= " AND sorder.from_stk_loc = ".db_escape($_POST['StockLocation']);
+               if ($location)
+                       $sql .= " AND sorder.from_stk_loc = ".db_escape($location);
  
-               if ($_POST['order_view_mode']=='OutstandingOnly')
+               if ($filter=='OutstandingOnly')
                        $sql .= " AND line.qty_sent < line.quantity";
-               elseif ($_POST['order_view_mode']=='InvoiceTemplates' || $_POST['order_view_mode']=='DeliveryTemplates')
+               elseif ($filter=='InvoiceTemplates' || $filter=='DeliveryTemplates')
                        $sql .= " AND sorder.type=1";
 -                      
 +
+               //Chaiatanya : New Filter
+               if ($customer_id != ALL_TEXT)
+                       $sql .= " AND sorder.debtor_no = ".db_escape($customer_id);             
                $sql .= " GROUP BY sorder.order_no,
                                        sorder.debtor_no,
                                        sorder.branch_code,
                                        sorder.customer_ref,
                                        sorder.ord_date,
                                        sorder.deliver_to";
-       }
        return $sql;
  }
  ?>
index bcafeecc13c1b1d799a22271e3ca2db8c5ef2340,3ebc84b5c0b624034f7904947c314836bb126cb5..d8a000c1866431d7d4ba3fc857adfe104a9b805f
  ***********************************************************************/
  $page_security = 'SA_SALESTRANSVIEW';
  $path_to_root = "../..";
- include($path_to_root . "/includes/db_pager.inc");
+ include_once($path_to_root . "/includes/db_pager.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");
  include_once($path_to_root . "/reporting/includes/reporting.inc");
  
 -if (!@$_GET['popup'])
 -{
 -      $js = "";
 -      if ($use_popup_windows)
 -              $js .= get_js_open_window(900, 500);
 -      if ($use_date_picker)
 -              $js .= get_js_date_picker();
 -      page(_($help_context = "Customer Transactions"), isset($_GET['customer_id']), false, "", $js);
 -}
 +$js = "";
 +if ($use_popup_windows)
 +      $js .= get_js_open_window(900, 500);
 +if ($use_date_picker)
 +      $js .= get_js_date_picker();
 +page(_($help_context = "Customer Transactions"), isset($_GET['customer_id']), false, "", $js);
  
  if (isset($_GET['customer_id']))
  {
        $_POST['customer_id'] = $_GET['customer_id'];
@@@ -33,7 -35,8 +32,7 @@@
  
  //------------------------------------------------------------------------------------------------
  
 -if (!@$_GET['popup'])
 -      start_form();
 +start_form();
  
  if (!isset($_POST['customer_id']))
        $_POST['customer_id'] = get_global_customer();
@@@ -41,7 -44,8 +40,8 @@@
  start_table(TABLESTYLE_NOBORDER);
  start_row();
  
- customer_list_cells(_("Select a customer: "), 'customer_id', null, true);
 -if (!@$_GET['popup'])
++if (!$page_nested)
+       customer_list_cells(_("Select a customer: "), 'customer_id', null, true, false, false, !@$_GET['popup']);
  
  date_cells(_("From:"), 'TransAfterDate', '', null, -30);
  date_cells(_("To:"), 'TransToDate', '', null, 1);
@@@ -154,6 -158,8 +154,10 @@@ function fmt_credit($row
  
  function credit_link($row)
  {
 -      if (@$_GET['popup'])
++      global $page_nested;
++      
++      if ($page_nested)
+               return '';
        return $row['type'] == ST_SALESINVOICE && $row["Outstanding"] > 0 ?
                pager_link(_("Credit This") ,
                        "/sales/customer_credit_invoice.php?InvoiceNumber=". $row['trans_no'], ICON_CREDIT):'';
  
  function edit_link($row)
  {
- /*    $str = '';
-       switch($row['type']) {
-       case ST_SALESINVOICE:
-               if (get_voided_entry(ST_SALESINVOICE, $row["trans_no"]) === false && $row['Allocated'] == 0)
-                       $str = "/sales/customer_invoice.php?ModifyInvoice=".$row['trans_no'];
-               break;
-       case ST_CUSTCREDIT:
-               if (get_voided_entry(ST_CUSTCREDIT, $row["trans_no"]) === false && $row['Allocated'] == 0) // 2008-11-19 Joe Hunt
-               {        
-                       if ($row['order_']==0) // free-hand credit note
-                           $str = "/sales/credit_note_entry.php?ModifyCredit=".$row['trans_no'];
-                       else    // credit invoice
-                           $str = "/sales/customer_credit_invoice.php?ModifyCredit=".$row['trans_no'];
-               }           
-               break;
-        case ST_CUSTDELIVERY:
-               if (get_voided_entry(ST_CUSTDELIVERY, $row["trans_no"]) === false)
-                       $str = "/sales/customer_delivery.php?ModifyDelivery=".$row['trans_no'];
-               break;
-       }
-       if ($str != '')
- */            return edit_trans_link($row['type'], $row['trans_no'], $row['type']==ST_CUSTCREDIT && $row['order_']==0 ?
-                       "/sales/credit_note_entry.php?ModifyCredit=%d" : 0);
 -      $str = '';
++      global $page_nested;
 -      if (@$_GET['popup'])
++      $str = '';
++      if ($page_nested)
+               return '';
 -      switch($row['type']) {
 -      case ST_SALESINVOICE:
 -              if (get_voided_entry(ST_SALESINVOICE, $row["trans_no"]) === false && $row['Allocated'] == 0)
 -                      $str = "/sales/customer_invoice.php?ModifyInvoice=".$row['trans_no'];
 -              break;
 -      case ST_CUSTCREDIT:
 -              if (get_voided_entry(ST_CUSTCREDIT, $row["trans_no"]) === false && $row['Allocated'] == 0) // 2008-11-19 Joe Hunt
 -              {        
 -                      if ($row['order_']==0) // free-hand credit note
 -                          $str = "/sales/credit_note_entry.php?ModifyCredit=".$row['trans_no'];
 -                      else    // credit invoice
 -                          $str = "/sales/customer_credit_invoice.php?ModifyCredit=".$row['trans_no'];
 -              }           
 -              break;
 -      case ST_CUSTDELIVERY:
 -              if (get_voided_entry(ST_CUSTDELIVERY, $row["trans_no"]) === false)
 -                      $str = "/sales/customer_delivery.php?ModifyDelivery=".$row['trans_no'];
 -              break;
 -      case ST_CUSTPAYMENT:
 -              if (get_voided_entry(ST_CUSTPAYMENT, $row["trans_no"]) === false)
 -                      $str = "/sales/customer_payments.php?trans_no=".$row['trans_no'];
 -              break;
 -      }               
 -      if ($str != "" && !is_closed_trans($row['type'], $row["trans_no"]))
 -              return pager_link(_('Edit'), $str, ICON_EDIT);
 -      return '';      
++
++      return edit_trans_link($row['type'], $row['trans_no'], $row['type']==ST_CUSTCREDIT && $row['order_']==0 ?
++              "/sales/credit_note_entry.php?ModifyCredit=%d" : 0);
  }
  
  function prt_link($row)
  function check_overdue($row)
  {
        return $row['OverDue'] == 1
-               && (abs($row["TotalAmount"]) - $row["Allocated"] != 0);
+               && floatcmp($row["TotalAmount"], $row["Allocated"]) != 0;
  }
  //------------------------------------------------------------------------------------------------
  $sql = get_sql_for_customer_inquiry();
@@@ -242,7 -254,9 +230,6 @@@ $table->width = "85%"
  
  display_db_pager($table);
  
 -if (!@$_GET['popup'])
 -{
 -      end_form();
 -      end_page(@$_GET['popup'], false, false);
 -}
 +end_form();
 +end_page();
  ?>
index 53de2699fbf05f87d8ee84d2084972640247423c,f59be9c028bb5de375939bc49421bd8c3b1dbdb1..281e3a5f548482877ac3c35e68fb556357e3172b
@@@ -11,9 -11,9 +11,9 @@@
  ***********************************************************************/
  $path_to_root = "../..";
  
- include($path_to_root . "/includes/db_pager.inc");
- include($path_to_root . "/includes/session.inc");
- include($path_to_root . "/sales/includes/sales_ui.inc");
+ include_once($path_to_root . "/includes/db_pager.inc");
+ include_once($path_to_root . "/includes/session.inc");
+ include_once($path_to_root . "/sales/includes/sales_ui.inc");
  include_once($path_to_root . "/reporting/includes/reporting.inc");
  
  $page_security = 'SA_SALESTRANSVIEW';
@@@ -25,12 -25,6 +25,6 @@@ set_page_security( @$_POST['order_view_
                        'InvoiceTemplates' => 'SA_SALESINVOICE')
  );
  
- $js = "";
- if ($use_popup_windows)
-       $js .= get_js_open_window(900, 600);
- if ($use_date_picker)
-       $js .= get_js_date_picker();
  if (get_post('type'))
        $trans_type = $_POST['type'];
  elseif (isset($_GET['type']) && $_GET['type'] == ST_SALESQUOTE)
@@@ -66,7 -60,16 +60,13 @@@ els
        $_POST['order_view_mode'] = "Quotations";
        $_SESSION['page_title'] = _($help_context = "Search All Sales Quotations");
  }
 -if (!@$_GET['popup'])
 -{
 -      $js = "";
 -      if ($use_popup_windows)
 -              $js .= get_js_open_window(900, 600);
 -      if ($use_date_picker)
 -              $js .= get_js_date_picker();
 -      page($_SESSION['page_title'], false, false, "", $js);
 -}
++$js = "";
++if ($use_popup_windows)
++      $js .= get_js_open_window(900, 600);
++if ($use_date_picker)
++      $js .= get_js_date_picker();
 +page($_SESSION['page_title'], false, false, "", $js);
  
  if (isset($_GET['selected_customer']))
  {
@@@ -118,6 -121,8 +118,10 @@@ function prt_link($row
  
  function edit_link($row) 
  {
 -      if (@$_GET['popup'])\r
 -              return '';\r
++      global $page_nested;
++      
++      if ($page_nested)
++              return '';
        global $trans_type;
        $modify = ($trans_type == ST_SALESORDER ? "ModifyOrderNumber" : "ModifyQuotationNumber");
    return pager_link( _("Edit"),
@@@ -159,9 -164,11 +163,12 @@@ function order_link($row
  
  function tmpl_checkbox($row)
  {
--      global $trans_type;
++      global $trans_type, $page_nested;
        if ($trans_type == ST_SALESQUOTE)
                return '';
 -      if (@$_GET['popup'])\r
 -              return '';\r
++
++      if ($page_nested)
++              return '';
        $name = "chgtpl" .$row['order_no'];
        $value = $row['type'] ? 1:0;
  
@@@ -194,50 -201,46 +201,45 @@@ if (isset($_POST['Update']) && isset($_
                        change_tpl_flag($id);
  }
  
+ $show_dates = !in_array($_POST['order_view_mode'], array('OutstandingOnly', 'InvoiceTemplates', 'DeliveryTemplates'));
  //---------------------------------------------------------------------------------------------
  //    Order range form
  //
- if (get_post('_OrderNumber_changed')) // enable/disable selection controls
+ if (get_post('_OrderNumber_changed') || get_post('_OrderReference_changed')) // enable/disable selection controls
  {
-       $disable = get_post('OrderNumber') !== '';
+       $disable = get_post('OrderNumber') !== '' || get_post('OrderReference') !== '';
  
-       if ($_POST['order_view_mode']!='DeliveryTemplates' 
-               && $_POST['order_view_mode']!='InvoiceTemplates') {
+       if ($show_dates) {
                        $Ajax->addDisable(true, 'OrdersAfterDate', $disable);
                        $Ajax->addDisable(true, 'OrdersToDate', $disable);
        }
-       $Ajax->addDisable(true, 'StockLocation', $disable);
-       $Ajax->addDisable(true, '_SelectStockFromList_edit', $disable);
-       $Ajax->addDisable(true, 'SelectStockFromList', $disable);
-       if ($disable) {
-               $Ajax->addFocus(true, 'OrderNumber');
-       } else
-               $Ajax->addFocus(true, 'OrdersAfterDate');
  
        $Ajax->activate('orders_tbl');
  }
  
 -if (!@$_GET['popup'])\r
 -      start_form();
 +start_form();
  
  start_table(TABLESTYLE_NOBORDER);
  start_row();
  ref_cells(_("#:"), 'OrderNumber', '',null, '', true);
- if ($_POST['order_view_mode'] != 'DeliveryTemplates' && $_POST['order_view_mode'] != 'InvoiceTemplates')
+ ref_cells(_("Ref"), 'OrderReference', '',null, '', true);
+ if ($show_dates)
  {
-       ref_cells(_("Ref"), 'OrderReference', '',null, '', true);
        date_cells(_("from:"), 'OrdersAfterDate', '', null, -30);
        date_cells(_("to:"), 'OrdersToDate', '', null, 1);
  }
  locations_list_cells(_("Location:"), 'StockLocation', null, true);
- end_row();
- end_table();
  
- start_table(TABLESTYLE_NOBORDER);
- start_row();
+ if($show_dates) {
+       end_row();
+       end_table();
  
+       start_table(TABLESTYLE_NOBORDER);
+       start_row();
+ }
  stock_items_list_cells(_("Item:"), 'SelectStockFromList', null, true);
 -if (!@$_GET['popup'])\r
 -      customer_list_cells(_("Select a customer: "), 'customer_id', null, true);\r
++if (!@$_GET['popup'])
++      customer_list_cells(_("Select a customer: "), 'customer_id', null, true);
  if ($trans_type == ST_SALESQUOTE)
        check_cells(_("Show All:"), 'show_all');
  
@@@ -251,7 -254,8 +253,8 @@@ end_table(1)
  //---------------------------------------------------------------------------------------------
  //    Orders inquiry table
  //
- $sql = get_sql_for_sales_orders_view($selected_customer, $trans_type);
+ $sql = get_sql_for_sales_orders_view($selected_customer, $trans_type, $_POST['OrderNumber'], $_POST['order_view_mode'],
 -      @$selected_stock_item, @$_POST['OrdersAfterDate'], @$_POST['OrdersToDate'], @$_POST['OrderReference'], $_POST['StockLocation'], $_POST['customer_id']);\r
++      @$selected_stock_item, @$_POST['OrdersAfterDate'], @$_POST['OrdersToDate'], @$_POST['OrderReference'], $_POST['StockLocation'], $_POST['customer_id']);
  
  if ($trans_type == ST_SALESORDER)
        $cols = array(
@@@ -281,9 -285,11 +284,11 @@@ els
                'Type' => 'skip',
                _("Currency") => array('align'=>'center')
        );
 -if ($_POST['order_view_mode'] == 'OutstandingOnly') {\r
 -      //array_substitute($cols, 3, 1, _("Cust Order Ref"));\r
 -      array_append($cols, array(\r
 -              array('insert'=>true, 'fun'=>'dispatch_link'),\r
 -              array('insert'=>true, 'fun'=>'edit_link')));\r
 +if ($_POST['order_view_mode'] == 'OutstandingOnly') {
 +      //array_substitute($cols, 3, 1, _("Cust Order Ref"));
-       array_append($cols, array(array('insert'=>true, 'fun'=>'dispatch_link')));
++      array_append($cols, array(
++              array('insert'=>true, 'fun'=>'dispatch_link'),
++              array('insert'=>true, 'fun'=>'edit_link')));
  
  } elseif ($_POST['order_view_mode'] == 'InvoiceTemplates') {
        array_substitute($cols, 3, 1, _("Description"));
@@@ -316,6 -322,9 +321,6 @@@ $table->width = "80%"
  display_db_pager($table);
  submit_center('Update', _("Update"), true, '', null);
  
 -if (!@$_GET['popup'])\r
 -{
 -      end_form();
 -      end_page();
 -}\r
 +end_form();
 +end_page();
  ?>
index 6e61b52be23c07641d834b3e644b80f20f167c12,e3b1565fba697ddbb21f6c6feab7bcfcc67adfed..374d2f57d74fc1512645f382fd976d5b2658b1b9
@@@ -81,7 -81,7 +81,7 @@@ if ($Mode=='ADD_ITEM' || $Mode=='UPDATE
                                $_POST['br_address'], $_POST['salesman'], $_POST['area'], $_POST['tax_group_id'], $_POST['sales_account'],
                                $_POST['sales_discount_account'], $_POST['receivables_account'], $_POST['payment_discount_account'],
                                $_POST['default_location'], $_POST['br_post_address'], $_POST['disable_trans'], $_POST['group_no'],
 -                              $_POST['default_ship_via'], $_POST['notes']);
 +                              $_POST['default_ship_via'], $_POST['notes'], $_POST['bank_account']);
  //                    update_record_status($_POST['supplier_id'], $_POST['inactive'],
  //                            'cust_branch', 'branch_code');
  
@@@ -93,7 -93,7 +93,7 @@@
                                $_POST['br_address'], $_POST['salesman'], $_POST['area'], $_POST['tax_group_id'], $_POST['sales_account'],
                                $_POST['sales_discount_account'], $_POST['receivables_account'], $_POST['payment_discount_account'],
                                $_POST['default_location'], $_POST['br_post_address'], 0, $_POST['group_no'],
 -                              $_POST['default_ship_via'], $_POST['notes']);
 +                              $_POST['default_ship_via'], $_POST['notes'], $_POST['bank_account']);
                        $selected_id = db_insert_id();
  
                        add_crm_person($_POST['contact_name'], $_POST['contact_name'], '', $_POST['br_post_address'], 
@@@ -204,7 -204,6 +204,7 @@@ function branch_settings($selected_id) 
                    $_POST['payment_discount_account'] = $myrow['payment_discount_account'];
                        $_POST['group_no']  = $myrow["group_no"];
                        $_POST['notes']  = $myrow["notes"];
 +                      $_POST['bank_account']  = $myrow["bank_account"];
  
                }
        }
  
                        // We use the Item Sales Account as default!
                    // $_POST['sales_account'] = $company_record["default_sales_act"];
 -                  $_POST['sales_account'] = $_POST['notes']  = '';
 +                  $_POST['sales_account'] = $_POST['notes']  = $_POST['bank_account'] = '';
                    $_POST['sales_discount_account'] = $company_record['default_sales_discount_act'];
                    $_POST['receivables_account'] = $company_record['debtors_act'];
                    $_POST['payment_discount_account'] = $company_record['default_prompt_payment_act'];
        gl_all_accounts_list_row(_("Sales Discount Account:"), 'sales_discount_account');
        gl_all_accounts_list_row(_("Accounts Receivable Account:"), 'receivables_account', null, true);
        gl_all_accounts_list_row(_("Prompt Payment Discount Account:"), 'payment_discount_account');
 +      text_row(_("Bank Account Number:"), 'bank_account', null, 30, 60);
  
        table_section(2);
  
@@@ -345,6 -343,6 +345,6 @@@ tabbed_content_end()
  
  end_form();
  
- end_page();
+ end_page(@$_REQUEST['popup']);
  
  ?>
index 133505304e1b962ae7ee23b283e6044d020e5d98,41c642ac760ae5e964c9c0e00157c7491c258ad9..af14b9a6af09421cd6bad62a1f3b60b31bfe701e
  $page_security = 'SA_CUSTOMER';
  $path_to_root = "../..";
  
 -include($path_to_root . "/includes/db_pager.inc");
++include_once($path_to_root . "/includes/db_pager.inc");
  include_once($path_to_root . "/includes/session.inc");
- page(_($help_context = "Customers"), @$_REQUEST['popup']); 
+ $js = "";
+ if ($use_popup_windows)
+       $js .= get_js_open_window(900, 500);
+ if ($use_date_picker)
+       $js .= get_js_date_picker();
+       
+ page(_($help_context = "Customers"), @$_REQUEST['popup'], false, "", $js); 
  
  include_once($path_to_root . "/includes/date_functions.inc");
  include_once($path_to_root . "/includes/banking.inc");
@@@ -72,7 -79,7 +79,7 @@@ function can_process(
  
  function handle_submit(&$selected_id)
  {
-       global $path_to_root, $Ajax;
+       global $path_to_root, $Ajax, $auto_create_branch;
  
        if (!can_process())
                return;
                        input_num('credit_limit'), $_POST['sales_type'], $_POST['notes']);
  
                $selected_id = $_POST['customer_id'] = db_insert_id();
+          
+               if (isset($auto_create_branch) && $auto_create_branch == 1)
+               {
+               add_branch($selected_id, $_POST['CustName'], $_POST['cust_ref'],
+                 $_POST['address'], $_POST['salesman'], $_POST['area'], $_POST['tax_group_id'], '',
+                 get_company_pref('default_sales_discount_act'), get_company_pref('debtors_act'), get_company_pref('default_prompt_payment_act'),
+                 get_company_pref('default location'), $_POST['address'], 0, 0, get_company_pref('default_ship_via'), $_POST['notes']);
+                 
+               $selected_branch = db_insert_id();
+         
+                       add_crm_person($_POST['CustName'], $_POST['cust_ref'], '', $_POST['address'], 
+                               $_POST['phone'], $_POST['phone2'], $_POST['fax'], $_POST['email'], '', '');
+                       add_crm_contact('cust_branch', 'general', $selected_branch, db_insert_id());
+               }
                commit_transaction();
  
                display_notification(_("A new customer has been added."));
+               if (isset($auto_create_branch) && $auto_create_branch == 1)
+                       display_notification(_("A default Branch has been automatically created, please check default Branch values by using link below."));
+               
                $Ajax->activate('_page_body');
        }
  }
@@@ -121,21 -147,21 +147,21 @@@ if (isset($_POST['delete'])
  
        // PREVENT DELETES IF DEPENDENT RECORDS IN 'debtor_trans'
  
-       if (key_in_foreign_table($selected_id, 'debtor_trans', 'debtor_no', true))
+       if (key_in_foreign_table($selected_id, 'debtor_trans', 'debtor_no'))
        {
                $cancel_delete = 1;
                display_error(_("This customer cannot be deleted because there are transactions that refer to it."));
        } 
        else 
        {
-               if (key_in_foreign_table($selected_id, 'sales_orders', 'debtor_no', true))
+               if (key_in_foreign_table($selected_id, 'sales_orders', 'debtor_no'))
                {
                        $cancel_delete = 1;
                        display_error(_("Cannot delete the customer record because orders have been created against it."));
                } 
                else 
                {
-                       if (key_in_foreign_table($selected_id, 'cust_branch', 'debtor_no', true))
+                       if (key_in_foreign_table($selected_id, 'cust_branch', 'debtor_no'))
                        {
                                $cancel_delete = 1;
                                display_error(_("Cannot delete this customer because there are branch records set up against it."));
  
  function customer_settings($selected_id) 
  {
-       global $SysPrefs, $path_to_root;
+       global $SysPrefs, $path_to_root, $auto_create_branch;
        
        if (!$selected_id) 
        {
-               $_POST['CustName'] = $_POST['cust_ref'] = $_POST['address'] = $_POST['tax_id']  = '';
-               $_POST['dimension_id'] = 0;
-               $_POST['dimension2_id'] = 0;
-               $_POST['sales_type'] = -1;
-               $_POST['curr_code']  = get_company_currency();
-               $_POST['credit_status']  = -1;
-               $_POST['payment_terms']  = $_POST['notes']  = '';
-               $_POST['discount']  = $_POST['pymt_discount'] = percent_format(0);
-               $_POST['credit_limit']  = price_format($SysPrefs->default_credit_limit());
+               if (list_updated('customer_id') || !isset($_POST['CustName'])) {
+                       $_POST['CustName'] = $_POST['cust_ref'] = $_POST['address'] = $_POST['tax_id']  = '';
+                       $_POST['dimension_id'] = 0;
+                       $_POST['dimension2_id'] = 0;
+                       $_POST['sales_type'] = -1;
+                       $_POST['curr_code']  = get_company_currency();
+                       $_POST['credit_status']  = -1;
+                       $_POST['payment_terms']  = $_POST['notes']  = '';
+                       $_POST['discount']  = $_POST['pymt_discount'] = percent_format(0);
+                       $_POST['credit_limit']  = price_format($SysPrefs->default_credit_limit());
+               }
        }
        else 
        {
  
        if($selected_id)
                record_status_list_row(_("Customer status:"), 'inactive');
+       elseif (isset($auto_create_branch) && $auto_create_branch == 1)
+       {
+               table_section_title(_("Branch"));
+               text_row(_("Phone:"), 'phone', null, 32, 30);
+               text_row(_("Secondary Phone Number:"), 'phone2', null, 32, 30);
+               text_row(_("Fax Number:"), 'fax', null, 32, 30);
+               email_row(_("E-mail:"), 'email', null, 35, 55);
+       }
        table_section(2);
  
        table_section_title(_("Sales"));
        }
  
        textarea_row(_("General Notes:"), 'notes', null, 35, 5);
+       if (!$selected_id && isset($auto_create_branch) && $auto_create_branch == 1)
+       {
+               table_section_title(_("Branch"));
+               sales_persons_list_row( _("Sales Person:"), 'salesman', null);
+               sales_areas_list_row( _("Sales Area:"), 'area', null);
+               tax_groups_list_row(_("Tax Group:"), 'tax_group_id', null);
+       }
        end_outer_table(1);
  
        div_start('controls');
@@@ -299,6 -341,8 +341,8 @@@ if (!$selected_id
  tabbed_content_start('tabs', array(
                'settings' => array(_('&General settings'), $selected_id),
                'contacts' => array(_('&Contacts'), $selected_id),
+               'transactions' => array(_('&Transactions'), $selected_id),
+               'orders' => array(_('Sales &Orders'), $selected_id),
        ));
        
        switch (get_post('_tabs_sel')) {
                        $contacts = new contacts('contacts', $selected_id, 'customer');
                        $contacts->show();
                        break;
 -                      $_GET['popup'] = 1;
+               case 'transactions':
+                       $_GET['customer_id'] = $selected_id;
+                       include_once($path_to_root."/sales/inquiry/customer_inquiry.php");
+                       break;
                case 'orders':
 -                      $_GET['popup'] = 1;
+                       $_GET['customer_id'] = $selected_id;
+                       include_once($path_to_root."/sales/inquiry/sales_orders_view.php");
+                       break;
        };
  br();
  tabbed_content_end();
  
  hidden('popup', @$_REQUEST['popup']);
  end_form();
- end_page();
+ end_page(@$_REQUEST['popup']);
  
  ?>
index 7b067dd59918d922be77ecfc3b1fc655884ff2b5,fd9723dfe6841dc5695e4be418563529014ebb9e..25d804fd5bf572ef14d0cdb3e779ff2e62545cd0
@@@ -87,7 -87,6 +87,7 @@@ if (isset($_GET['NewDelivery']) && is_n
  }
  
  page($_SESSION['page_title'], false, false, "", $js);
 +
  //-----------------------------------------------------------------------------
  
  if (list_updated('branch_id')) {
@@@ -224,6 -223,8 +224,8 @@@ if (isset($_GET['AddedID'])) 
                submenu_option(_("Enter a &New Direct Invoice"),
                        "/sales/sales_order_entry.php?NewInvoice=0");
  
+       submenu_option(_("Add an Attachment"), "/admin/attachments.php?filterType=".ST_SALESINVOICE."&trans_no=$invoice");
        display_footer_exit();
  } else
        check_edit_conflicts();
@@@ -238,27 -239,30 +240,30 @@@ function copy_to_cart(
        $cart->Comments =  $_POST['Comments'];
  
        $cart->document_date = $_POST['OrderDate'];
- //    if ($cart->trans_type == ST_SALESINVOICE) {
+       $newpayment = false;
        if (isset($_POST['payment']) && ($cart->payment != $_POST['payment'])) {
                $cart->payment = $_POST['payment'];
                $cart->payment_terms = get_payment_terms($_POST['payment']);
+               $newpayment = true;
        }
        if ($cart->payment_terms['cash_sale']) {
-               $cart->due_date = $cart->document_date;
-               $cart->phone = $cart->cust_ref = $cart->delivery_address = '';
-               $cart->freight_cost = input_num('freight_cost');
-               $cart->ship_via = 1;
-               $cart->deliver_to = '';//$_POST['deliver_to'];
+               if ($newpayment) {
+                       $cart->due_date = $cart->document_date;
+                       $cart->phone = $cart->cust_ref = $cart->delivery_address = '';
+                       $cart->ship_via = 1;
+                       $cart->deliver_to = '';
+               }
        } else {
                $cart->due_date = $_POST['delivery_date'];
                $cart->cust_ref = $_POST['cust_ref'];
-               $cart->freight_cost = input_num('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'];
        }
+       $cart->Location = $_POST['Location'];
+       $cart->freight_cost = input_num('freight_cost');
        if (isset($_POST['email']))
                $cart->email =$_POST['email'];
        else
        $cart->customer_id      = $_POST['customer_id'];
        $cart->Branch = $_POST['branch_id'];
        $cart->sales_type = $_POST['sales_type'];
-       // POS
        if ($cart->trans_type!=ST_SALESORDER && $cart->trans_type!=ST_SALESQUOTE) { // 2008-11-12 Joe Hunt
                $cart->dimension_id = $_POST['dimension_id'];
                $cart->dimension2_id = $_POST['dimension2_id'];
-       }       
+       }
  }
  
  //-----------------------------------------------------------------------------
@@@ -338,7 -342,7 +343,7 @@@ function can_process() 
                return false;
        }
        if ($_SESSION['Items']->trans_type!=ST_SALESORDER && $_SESSION['Items']->trans_type!=ST_SALESQUOTE && !is_date_in_fiscalyear($_POST['OrderDate'])) {
 -              display_error(_("The entered date is not in fiscal year"));
 +              display_error(_("The entered date is out of fiscal year or is closed for further data entry."));
                set_focus('OrderDate');
                return false;
        }
        }
  
  
-               if (strlen($_POST['delivery_address']) <= 1) {
+               if ($_SESSION['Items']->trans_type != ST_SALESQUOTE && 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."));
                        set_focus('delivery_address');
                        return false;
  
  //-----------------------------------------------------------------------------
  
+ if (isset($_POST['update'])) {
+       copy_to_cart();
+       $Ajax->activate('items_table');
+ }
  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);
        if (count($messages)) { // abort on failure or error messages are lost
                $Ajax->activate('_page_body');
        }
  }
  
- if (isset($_POST['update'])) {
-       $Ajax->activate('items_table');
- }
  //--------------------------------------------------------------------------------
  
  function check_item_data()
                }
                return true;
        }
+       $cost_home = get_standard_cost(get_post('stock_id')); // Added 2011-03-27 Joe Hunt
+       $cost = $cost_home / get_exchange_rate_from_home_currency($_SESSION['Items']->customer_currency, $_SESSION['Items']->document_date);
+       if (input_num('price') < $cost)
+       {
+               $dec = user_price_dec();
+               $curr = $_SESSION['Items']->customer_currency;
+               $price = number_format2(input_num('price'), $dec);
+               if ($cost_home == $cost)
+                       $std_cost = number_format2($cost_home, $dec);
+               else
+               {
+                       $price = $curr . " " . $price;
+                       $std_cost = $curr . " " . number_format2($cost, $dec);
+               }
+               display_warning(sprintf(_("Price %s is below Standard Cost %s"), $price, $std_cost));
+       }       
        return true;
  }
  
@@@ -588,11 -610,7 +611,7 @@@ function create_cart($type, $trans_no
        if (isset($_GET['NewQuoteToSalesOrder']))
        {
                $trans_no = $_GET['NewQuoteToSalesOrder'];
-               $doc = new Cart(ST_SALESQUOTE, $trans_no);
-               $doc->trans_no = 0;
-               $doc->trans_type = ST_SALESORDER;
-               $doc->reference = $Refs->get_next($doc->trans_type);
-               $doc->document_date = $doc->due_date = new_doc_date();
+               $doc = new Cart(ST_SALESQUOTE, $trans_no, true);
                $doc->Comments = _("Sales Quotation") . " # " . $trans_no;
                $_SESSION['Items'] = $doc;
        }       
                        $doc->line_items[$line_no]->qty_done = 0;
                }
                $_SESSION['Items'] = $doc;
-       } else {
+       } else
                $_SESSION['Items'] = new Cart($type, array($trans_no));
-       }
        copy_from_cart();
  }
  
index ff88393cf4c5b86e9f2fae197397ee7f0efaba14,405f1d6653589024b7e0fe315783a511644136f6..712c5470981912b20319bbf9d06120b90a07db7c
@@@ -39,19 -39,20 +39,20 @@@ if (isset($_SESSION['View'])
        unset ($_SESSION['View']);
  }
  
 -$_SESSION['View'] = new Cart($_GET['trans_type'], $_GET['trans_no']);
 +$_SESSION['View'] = new Cart($_GET['trans_type'], $_GET['trans_no'], true);
  
  start_table(TABLESTYLE2, "width=95%", 5);
- echo "<tr valign=top><td>";
- display_heading2(_("Order Information"));
  if ($_GET['trans_type'] != ST_SALESQUOTE)
  {
+       echo "<tr valign=top><td>";
+       display_heading2(_("Order Information"));
        echo "</td><td>";
        display_heading2(_("Deliveries"));
        echo "</td><td>";
        display_heading2(_("Invoices/Credits"));
+       echo "</td></tr>";
  }     
- echo "</td></tr>";
  
  echo "<tr valign=top><td>";
  
diff --combined sql/alter2.3.php
index c4071f974556e360b71ac35b89a27b7c2c0f5aaf,2a517deb7321b79314cfa9ab6812bfaef9de01e3..7705f261fd221251ee7c96f935282e82354a887a
@@@ -24,18 -24,19 +24,19 @@@ class fa2_3 
        //      Install procedure. All additional changes 
        //      not included in sql file should go here.
        //
 -      function install($pref, $force) 
 +      function install($company, $force) 
        {
                global $db_version, $dflt_lang;
  
+               $this->preconf = $this->fix_extensions();
                if (!$this->preconf)
                        return false;
  
                if (!$this->beta) {
                        // all specials below are already done on 2.3beta
  
 -                      $sql = "SELECT debtor_no, payment_terms FROM {$pref}debtors_master";
 -              
 +                      $sql = "SELECT debtor_no, payment_terms FROM ".TB_PREF."debtors_master";
-               
++
                        $result = db_query($sql);
                        if (!$result) {
                                display_error("Cannot read customers"
@@@ -44,7 -45,7 +45,7 @@@
                        }
                        // update all sales orders and transactions with customer std payment terms
                        while($cust = db_fetch($result)) {
 -                              $sql = "UPDATE {$pref}debtor_trans SET "
 +                              $sql = "UPDATE ".TB_PREF."debtor_trans SET "
                                        ."payment_terms = '" .$cust['payment_terms']
                                        ."' WHERE debtor_no='".$cust['debtor_no']."'";
                                if (db_query($sql)==false) {
@@@ -52,7 -53,7 +53,7 @@@
                                        .':<br>'. db_error_msg($db));
                                        return false;
                                }
 -                              $sql = "UPDATE {$pref}sales_orders SET "
 +                              $sql = "UPDATE ".TB_PREF."sales_orders SET "
                                        ."payment_terms = '" .$cust['payment_terms']
                                        ."' WHERE debtor_no='".$cust['debtor_no']."'";
                                if (db_query($sql)==false) {
                                        return false;
                                }
                        }
 -                      if (!$this->update_totals($pref)) {
 +                      if (!$this->update_totals()) {
                                display_error("Cannot update order totals");
                                return false;
                        }
 -                      if (!$this->update_line_relations($pref)) {
 +                      if (!$this->update_line_relations()) {
                                display_error("Cannot update sales document links");
                                return false;
                        }
  
                        foreach($dropcol as $table => $columns)
                                foreach($columns as $col) {
 -                                      if (db_query("ALTER TABLE `{$pref}{$table}` DROP `$col`")==false) {
 +                                      if (db_query("ALTER TABLE `".TB_PREF."{$table}` DROP `$col`")==false) {
                                                display_error("Cannot drop {$table}.{$col} column:<br>".db_error_msg($db));
                                                return false;
                                        }
                                }
                        // remove old preferences table after upgrade script has been executed
 -                      $sql = "DROP TABLE IF EXISTS `{$pref}company`";
 +                      $sql = "DROP TABLE IF EXISTS `".TB_PREF."company`";
                        if (!db_query($sql))
                                return false;
                }
                $this->update_lang_cfg();
 -              return  update_company_prefs(array('version_id'=>$db_version), $pref);
 +              return  update_company_prefs(array('version_id'=>$db_version));
        }
        //
        //      Checking before install
        //
        function installed($pref) {
                $this->beta = !check_table($pref, 'suppliers', 'tax_included');
-               $this->preconf = $this->fix_extensions();
  
                $n = 1; // number of patches to be installed
                $patchcnt = 0;
        /*
                Update order totals
        */
 -      function update_totals($pref)
 +      function update_totals()
        {
                global $path_to_root;
  
                include_once("$path_to_root/sales/includes/cart_class.inc");
                include_once("$path_to_root/purchasing/includes/po_class.inc");
                $cart = new cart(ST_SALESORDER);
 -              $sql = "SELECT order_no, trans_type FROM {$pref}sales_orders";
 +              $sql = "SELECT order_no, trans_type FROM ".TB_PREF."sales_orders";
                $orders = db_query($sql);
                if (!$orders)
                        return false;
                while ($order = db_fetch($orders)) {
                        read_sales_order($order['order_no'], $cart, $order['trans_type']);
 -                      $result = db_query("UPDATE {$pref}sales_orders 
 +                      $result = db_query("UPDATE ".TB_PREF."sales_orders 
                                SET total=".$cart->get_trans_total()
                                ." WHERE order_no=".$order[0]);
                        unset($cart->line_items);
                }
                unset($cart);
                $cart = new purch_order();
 -              $sql = "SELECT order_no FROM {$pref}purch_orders";
 +              $sql = "SELECT order_no FROM ".TB_PREF."purch_orders";
                $orders = db_query($sql);
                if (!$orders)
                         return false;
                while ($order_no = db_fetch($orders)) {
                        read_po($order_no[0], $cart);
 -                      $result = db_query("UPDATE {$pref}purch_orders SET total=".$cart->get_trans_total());
 +                      $result = db_query("UPDATE ".TB_PREF."purch_orders SET total=".$cart->get_trans_total());
                        unset($cart->line_items);
                }
                return true;
                there can be sales documents with lines not properly linked to parents. This rare 
                cases will be described in error log.
        */
 -      function update_line_relations($pref)
 +      function update_line_relations()
        {
                global $path_to_root, $systypes_array;
  
                require_once("$path_to_root/includes/sysnames.inc");
                
 -              $sql =  "SELECT d.type, trans_no, order_ FROM {$pref}debtor_trans d
 -                      LEFT JOIN {$pref}voided v ON d.type=v.type AND d.trans_no=v.id
 +              $sql =  "SELECT d.type, trans_no, order_ FROM ".TB_PREF."debtor_trans d
 +                      LEFT JOIN ".TB_PREF."voided v ON d.type=v.type AND d.trans_no=v.id
                                WHERE ISNULL(v.type) AND 
                                (d.type=".ST_CUSTDELIVERY
                                ." OR d.type=".ST_SALESINVOICE
                                if ($src_line['stock_id'] == $doc_line['stock_id']
                                        && ($src_line['quantity'] >= $doc_line['quantity'])) {
  
 -                                      $sql = "UPDATE {$pref}debtor_trans_details SET src_id = {$src_line['id']}
 +                                      $sql = "UPDATE ".TB_PREF."debtor_trans_details SET src_id = {$src_line['id']}
                                                WHERE id = {$doc_line['id']}";
                                        if (!db_query($sql))
                                                return false;
diff --combined sql/en_US-demo.sql
index 5fb4f57d9b0f358d182c0da2ec8b6c67623c7680,205355a05ef59888b40807b8724ee53a30b26a89..159ab6c28fd9d9e29370c7085a0e7fd724172f1c
@@@ -611,7 -611,6 +611,7 @@@ CREATE TABLE IF NOT EXISTS `0_cust_bran
    `br_post_address` tinytext NOT NULL,
    `group_no` int(11) NOT NULL default '0',
    `notes` tinytext NOT NULL,
 +  `bank_account` varchar(60) DEFAULT NULL,
    `inactive` tinyint(1) NOT NULL default '0',
    PRIMARY KEY  (`branch_code`,`debtor_no`),
    KEY `branch_code` (`branch_code`),
  -- Dumping data for table `0_cust_branch`
  --
  
 -INSERT INTO `0_cust_branch` VALUES(1, 1, 'Beefeater Ltd.', 'Beefeater', '', 1, 1, 'Main Branch', 'DEF', 2, '', '4510', '1200', '4500', 1, 0, 'Address 1\nAddress 2\nAddress 3', 0, '', 0);
 -INSERT INTO `0_cust_branch` VALUES(2, 2, 'Ghostbusters Corp.', 'Ghostbusters', 'Address 1\nAddress 2\nAddress 3', 1, 1, 'Main Branch', 'DEF', 1, '', '4510', '1200', '4500', 1, 0, 'Address 1\nAddress 2\nAddress 3', 0, '', 0);
 -INSERT INTO `0_cust_branch` VALUES(3, 3, 'Brezan', 'Brezan', 'Address 1\nAddress 2\nAddress 3', 1, 1, 'Main Branch', 'DEF', 1, '', '4510', '1200', '4500', 1, 0, 'Address 1\nAddress 2\nAddress 3', 0, '', 0);
 +INSERT INTO `0_cust_branch` VALUES(1, 1, 'Beefeater Ltd.', 'Beefeater', '', 1, 1, 'Main Branch', 'DEF', 2, '', '4510', '1200', '4500', 1, 0, 'Address 1\nAddress 2\nAddress 3', 0, '', '', 0);
 +INSERT INTO `0_cust_branch` VALUES(2, 2, 'Ghostbusters Corp.', 'Ghostbusters', 'Address 1\nAddress 2\nAddress 3', 1, 1, 'Main Branch', 'DEF', 1, '', '4510', '1200', '4500', 1, 0, 'Address 1\nAddress 2\nAddress 3', 0, '','', 0);
 +INSERT INTO `0_cust_branch` VALUES(3, 3, 'Brezan', 'Brezan', 'Address 1\nAddress 2\nAddress 3', 1, 1, 'Main Branch', 'DEF', 1, '', '4510', '1200', '4500', 1, 0, 'Address 1\nAddress 2\nAddress 3', 0, '', '', 0);
  
  -- --------------------------------------------------------
  
@@@ -693,7 -692,6 +693,7 @@@ CREATE TABLE IF NOT EXISTS `0_debtor_tr
    `dimension_id` int(11) NOT NULL default '0',
    `dimension2_id` int(11) NOT NULL default '0',
    `payment_terms` int(11) default NULL,
 +  `tax_included` tinyint(1) unsigned NOT NULL default '0',
    PRIMARY KEY  (`type`,`trans_no`),
    KEY `debtor_no` (`debtor_no`,`branch_code`),
    KEY `tran_date` (`tran_date`)
  -- Dumping data for table `0_debtor_trans`
  --
  
 -INSERT INTO `0_debtor_trans` VALUES(17, 10, 0, 2, 2, '2009-06-21', '2009-06-22', '1', 1, 2, 50, 2.5, 0, 0, 0, 0, 1, 1, 0, 0, 4);
 -INSERT INTO `0_debtor_trans` VALUES(18, 10, 1, 3, 3, '2009-06-21', '2009-07-01', '2', 2, 3, 35.89, 1.79, 0, 0, 0, 37.68, 1.3932, 1, 2, 0, 3);
 -INSERT INTO `0_debtor_trans` VALUES(19, 10, 0, 2, 2, '2009-06-21', '2009-06-22', '3', 1, 5, 50, 0, 5, 0, 0, 0, 1, 1, 0, 0, 4);
 -INSERT INTO `0_debtor_trans` VALUES(3, 11, 0, 3, 3, '2009-06-21', '0000-00-00', '1', 2, 3, 35.89, 1.79, 0, 0, 0, 37.68, 1.3932, 1, 2, 0, 3);
 -INSERT INTO `0_debtor_trans` VALUES(2, 13, 0, 1, 1, '2009-06-21', '2009-06-22', '1', 2, 1, 60.8, 0, 10, 0, 0, 0, 1.6445729799917, 1, 0, 0, 3);
 -INSERT INTO `0_debtor_trans` VALUES(3, 13, 1, 2, 2, '2009-06-21', '2009-06-22', 'auto', 1, 2, 50, 2.5, 0, 0, 0, 0, 1, 1, 0, 0, 4);
 -INSERT INTO `0_debtor_trans` VALUES(4, 13, 1, 3, 3, '2009-06-21', '2009-07-01', 'auto', 2, 3, 35.89, 1.79, 0, 0, 0, 0, 1.3932, 1, 2, 0, 3);
 -INSERT INTO `0_debtor_trans` VALUES(5, 13, 1, 2, 2, '2009-06-21', '2009-06-22', 'auto', 1, 5, 50, 0, 5, 0, 0, 0, 1, 1, 0, 0, 4);
 +INSERT INTO `0_debtor_trans` VALUES(17, 10, 0, 2, 2, '2009-06-21', '2009-06-22', '1', 1, 2, 50, 2.5, 0, 0, 0, 0, 1, 1, 0, 0, 4, 0);
 +INSERT INTO `0_debtor_trans` VALUES(18, 10, 1, 3, 3, '2009-06-21', '2009-07-01', '2', 2, 3, 35.89, 1.79, 0, 0, 0, 37.68, 1.3932, 1, 2, 0, 3, 0);
 +INSERT INTO `0_debtor_trans` VALUES(19, 10, 0, 2, 2, '2009-06-21', '2009-06-22', '3', 1, 5, 50, 0, 5, 0, 0, 0, 1, 1, 0, 0, 4, 0);
 +INSERT INTO `0_debtor_trans` VALUES(3, 11, 0, 3, 3, '2009-06-21', '0000-00-00', '1', 2, 3, 35.89, 1.79, 0, 0, 0, 37.68, 1.3932, 1, 2, 0, 3, 0);
 +INSERT INTO `0_debtor_trans` VALUES(2, 13, 0, 1, 1, '2009-06-21', '2009-06-22', '1', 2, 1, 60.8, 0, 10, 0, 0, 0, 1.6445729799917, 1, 0, 0, 3, 0);
 +INSERT INTO `0_debtor_trans` VALUES(3, 13, 1, 2, 2, '2009-06-21', '2009-06-22', 'auto', 1, 2, 50, 2.5, 0, 0, 0, 0, 1, 1, 0, 0, 4, 0);
 +INSERT INTO `0_debtor_trans` VALUES(4, 13, 1, 3, 3, '2009-06-21', '2009-07-01', 'auto', 2, 3, 35.89, 1.79, 0, 0, 0, 0, 1.3932, 1, 2, 0, 3, 0);
 +INSERT INTO `0_debtor_trans` VALUES(5, 13, 1, 2, 2, '2009-06-21', '2009-06-22', 'auto', 1, 5, 50, 0, 5, 0, 0, 0, 1, 1, 0, 0, 4, 0);
  
  -- --------------------------------------------------------
  
@@@ -828,6 -826,7 +828,7 @@@ CREATE TABLE IF NOT EXISTS `0_fiscal_ye
  INSERT INTO `0_fiscal_year` VALUES(1, '2008-01-01', '2008-12-31', 1);
  INSERT INTO `0_fiscal_year` VALUES(2, '2009-01-01', '2009-12-31', 1);
  INSERT INTO `0_fiscal_year` VALUES(3, '2010-01-01', '2010-12-31', 0);
+ INSERT INTO `0_fiscal_year` VALUES(4, '2011-01-01', '2011-12-31', 0);
  
  --
  -- Table structure for table `0_gl_trans`
@@@ -1368,8 -1367,7 +1369,8 @@@ CREATE TABLE IF NOT EXISTS `0_purch_ord
    `quantity_ordered` double NOT NULL default '0',
    `quantity_received` double NOT NULL default '0',
    PRIMARY KEY  (`po_detail_item`),
 -  KEY `order` (`order_no`,`po_detail_item`)
 +  KEY `order` (`order_no`,`po_detail_item`),
 +  KEY `itemcode` (`item_code`)
  ) ENGINE=InnoDB  AUTO_INCREMENT=6 ;
  
  --
@@@ -1574,8 -1572,7 +1575,8 @@@ CREATE TABLE IF NOT EXISTS `0_sales_ord
    `quantity` double NOT NULL default '0',
    `discount_percent` double NOT NULL default '0',
    PRIMARY KEY  (`id`),
 -  KEY `sorder` (`trans_type`,`order_no`)
 +  KEY `sorder` (`trans_type`,`order_no`),
 +  KEY `stkcode` (`stk_code`)
  ) ENGINE=InnoDB  AUTO_INCREMENT=6 ;
  
  --
@@@ -1881,7 -1878,6 +1882,7 @@@ CREATE TABLE IF NOT EXISTS `0_suppliers
    `curr_code` char(3) default NULL,
    `payment_terms` int(11) default NULL,
    `tax_included` tinyint(1) NOT NULL default '0',
 +  `tax_algorithm` tinyint(1) NOT NULL default '1',
    `dimension_id` int(11) default '0',
    `dimension2_id` int(11) default '0',
    `tax_group_id` int(11) default NULL,
  -- Dumping data for table `0_suppliers`
  --
  
 -INSERT INTO `0_suppliers` VALUES(1, 'Junk Beer ApS', 'Junk Beer', 'Mailing 1\nMailing 2\nMailing 3', 'Address 1\nAddress 2\nAddress 3', '123456', 'Contact', '111', '', '', 'DKK', 3, 0, 1, 0, 2, 1000, '', '2100', '5060', 'A supplier with junk beers.', 0);
 -INSERT INTO `0_suppliers` VALUES(2, 'Lucky Luke Inc.', 'Lucky Luke', 'Mailing 1\nMailing 2\nMailing 3', 'Address 1\nAddress 2\nAddress 3', '654321', 'Luke', '333', '', '', 'USD', 3, 0, 0, 0, 1, 500, '', '2100', '5060', '', 0);
 -INSERT INTO `0_suppliers` VALUES(3, 'Money Makers Ltd.', 'Money Makers', 'Mailing 1\nMailing 2\nMailing 3', 'Address 1\nAddress 2\nAddress 3', '987654', 'Makers', '222', '', '', 'GBP', 3, 0, 0, 0, 2, 300, '', '2100', '5060', '', 0);
 +INSERT INTO `0_suppliers` VALUES(1, 'Junk Beer ApS', 'Junk Beer', 'Mailing 1\nMailing 2\nMailing 3', 'Address 1\nAddress 2\nAddress 3', '123456', 'Contact', '111', '', '', 'DKK', 3, 0, 1, 1, 0, 2, 1000, '', '2100', '5060', 'A supplier with junk beers.', 0);
 +INSERT INTO `0_suppliers` VALUES(2, 'Lucky Luke Inc.', 'Lucky Luke', 'Mailing 1\nMailing 2\nMailing 3', 'Address 1\nAddress 2\nAddress 3', '654321', 'Luke', '333', '', '', 'USD', 3, 0, 1, 0, 0, 1, 500, '', '2100', '5060', '', 0);
 +INSERT INTO `0_suppliers` VALUES(3, 'Money Makers Ltd.', 'Money Makers', 'Mailing 1\nMailing 2\nMailing 3', 'Address 1\nAddress 2\nAddress 3', '987654', 'Makers', '222', '', '', 'GBP', 3, 0, 1, 0, 0, 2, 300, '', '2100', '5060', '', 0);
  
  -- --------------------------------------------------------
  
@@@ -1984,7 -1980,6 +1985,7 @@@ CREATE TABLE IF NOT EXISTS `0_supp_tran
    `rate` double NOT NULL default '1',
    `alloc` double NOT NULL default '0',
    `tax_included` tinyint(1) NOT NULL default '0',
 +  `tax_algorihm` tinyint(1) NOT NULL default '1',
    PRIMARY KEY  (`type`,`trans_no`),
    KEY `supplier_id` (`supplier_id`),
    KEY `SupplierID_2` (`supplier_id`,`supp_reference`),
  -- Dumping data for table `0_supp_trans`
  --
  
 -INSERT INTO `0_supp_trans` VALUES(7, 20, 2, '1', '5t', '2009-06-21', '2009-07-01', 3300, 0, 165, 1, 3465, 0);
 -INSERT INTO `0_supp_trans` VALUES(8, 20, 2, '2', 'cc', '2009-06-21', '2009-07-01', 20, 0, 0, 1, 0, 0);
 -INSERT INTO `0_supp_trans` VALUES(4, 22, 2, '1', '', '2009-06-21', '2009-06-21', -3465, 0, 0, 1, 3465, 0);
 +INSERT INTO `0_supp_trans` VALUES(7, 20, 2, '1', '5t', '2009-06-21', '2009-07-01', 3300, 0, 165, 1, 3465, 0, 1);
 +INSERT INTO `0_supp_trans` VALUES(8, 20, 2, '2', 'cc', '2009-06-21', '2009-07-01', 20, 0, 0, 1, 0, 0, 1);
 +INSERT INTO `0_supp_trans` VALUES(4, 22, 2, '1', '', '2009-06-21', '2009-06-21', -3465, 0, 0, 1, 3465, 0, 1);
  
  -- --------------------------------------------------------
  
@@@ -2012,7 -2007,7 +2013,7 @@@ CREATE TABLE IF NOT EXISTS `0_sys_prefs
    `category` varchar(30) default NULL,
    `type` varchar(20) NOT NULL default '',
    `length` smallint(6) default NULL,
 -  `value` tinytext,
 +  `value` text,
    PRIMARY KEY  (`name`),
    KEY `category` (`category`)
  ) ENGINE=MyISAM;
@@@ -2034,7 -2029,7 +2035,7 @@@ INSERT INTO `0_sys_prefs` VALUES('coy_l
  INSERT INTO `0_sys_prefs` VALUES('domicile', 'setup.company', 'varchar', 55, '');
  INSERT INTO `0_sys_prefs` VALUES('curr_default', 'setup.company', 'char', 3, 'USD');
  INSERT INTO `0_sys_prefs` VALUES('use_dimension', 'setup.company', 'tinyint', 1, '1');
 -INSERT INTO `0_sys_prefs` VALUES('f_year', 'setup.company', 'int', 11, '4');
 +INSERT INTO `0_sys_prefs` VALUES('f_year', 'setup.company', 'int', 11, '3');
  INSERT INTO `0_sys_prefs` VALUES('no_item_list', 'setup.company', 'tinyint', 1, '0');
  INSERT INTO `0_sys_prefs` VALUES('no_customer_list', 'setup.company', 'tinyint', 1, '0');
  INSERT INTO `0_sys_prefs` VALUES('no_supplier_list', 'setup.company', 'tinyint', 1, '0');
@@@ -2048,7 -2043,6 +2049,7 @@@ INSERT INTO `0_sys_prefs` VALUES('profi
  INSERT INTO `0_sys_prefs` VALUES('retained_earnings_act', 'glsetup.general', 'varchar', 15, '3590');
  INSERT INTO `0_sys_prefs` VALUES('bank_charge_act', 'glsetup.general', 'varchar', 15, '5690');
  INSERT INTO `0_sys_prefs` VALUES('exchange_diff_act', 'glsetup.general', 'varchar', 15, '4450');
 +INSERT INTO `0_sys_prefs` VALUES('tax_algorithm', 'glsetup.general', 'tinyint', 1, '1');
  INSERT INTO `0_sys_prefs` VALUES('default_credit_limit', 'glsetup.customer', 'int', 11, '1000');
  INSERT INTO `0_sys_prefs` VALUES('accumulate_shipping', 'glsetup.customer', 'tinyint', 1, '0');
  INSERT INTO `0_sys_prefs` VALUES('legal_text', 'glsetup.customer', 'tinytext', 0, '');
@@@ -2165,6 -2159,7 +2166,6 @@@ DROP TABLE IF EXISTS `0_tax_groups`
  CREATE TABLE IF NOT EXISTS `0_tax_groups` (
    `id` int(11) NOT NULL auto_increment,
    `name` varchar(60) NOT NULL default '',
 -  `tax_shipping` tinyint(1) NOT NULL default '0',
    `inactive` tinyint(1) NOT NULL default '0',
    PRIMARY KEY  (`id`),
    UNIQUE KEY `name` (`name`)
  -- Dumping data for table `0_tax_groups`
  --
  
 -INSERT INTO `0_tax_groups` VALUES(1, 'Tax', 0, 0);
 -INSERT INTO `0_tax_groups` VALUES(2, 'Tax Exempt', 0, 0);
 +INSERT INTO `0_tax_groups` VALUES(1, 'Tax', 0);
 +INSERT INTO `0_tax_groups` VALUES(2, 'Tax Exempt', 0);
  
  -- --------------------------------------------------------
  
@@@ -2187,7 -2182,7 +2188,7 @@@ DROP TABLE IF EXISTS `0_tax_group_items
  CREATE TABLE IF NOT EXISTS `0_tax_group_items` (
    `tax_group_id` int(11) NOT NULL default '0',
    `tax_type_id` int(11) NOT NULL default '0',
 -  `rate` double NOT NULL default '0',
 +  `tax_shipping` tinyint(1) NOT NULL default '0',
    PRIMARY KEY  (`tax_group_id`,`tax_type_id`)
  ) ENGINE=InnoDB;
  
  -- Dumping data for table `0_tax_group_items`
  --
  
 -INSERT INTO `0_tax_group_items` VALUES(1, 1, 5);
 +INSERT INTO `0_tax_group_items` VALUES(1, 1, 1);
  
  -- --------------------------------------------------------
  
diff --combined sql/en_US-new.sql
index baad176f17338d5fa8c852cd12d7a264440e4300,a866a6f7e7b4587df8f57d3d2eeb70b91b3e1f95..09fe3108c6d170333a64605a80fc550fa1867a75
@@@ -576,7 -576,6 +576,7 @@@ CREATE TABLE IF NOT EXISTS `0_cust_bran
    `br_post_address` tinytext NOT NULL,
    `group_no` int(11) NOT NULL default '0',
    `notes` tinytext NOT NULL,
 +  `bank_account` varchar(60) DEFAULT NULL,
    `inactive` tinyint(1) NOT NULL default '0',
    PRIMARY KEY  (`branch_code`,`debtor_no`),
    KEY `branch_code` (`branch_code`),
@@@ -652,7 -651,6 +652,7 @@@ CREATE TABLE IF NOT EXISTS `0_debtor_tr
    `dimension_id` int(11) NOT NULL default '0',
    `dimension2_id` int(11) NOT NULL default '0',
    `payment_terms` int(11) default NULL,
 +  `tax_included` tinyint(1) unsigned NOT NULL default '0',
    PRIMARY KEY  (`type`,`trans_no`),
    KEY `debtor_no` (`debtor_no`,`branch_code`),
    KEY `tran_date` (`tran_date`)
@@@ -766,6 -764,7 +766,7 @@@ CREATE TABLE IF NOT EXISTS `0_fiscal_ye
  INSERT INTO `0_fiscal_year` VALUES(1, '2008-01-01', '2008-12-31', 0);
  INSERT INTO `0_fiscal_year` VALUES(2, '2009-01-01', '2009-12-31', 0);
  INSERT INTO `0_fiscal_year` VALUES(3, '2010-01-01', '2010-12-31', 0);
+ INSERT INTO `0_fiscal_year` VALUES(4, '2011-01-01', '2011-12-31', 0);
  
  --
  -- Table structure for table `0_gl_trans`
@@@ -1197,8 -1196,7 +1198,8 @@@ CREATE TABLE IF NOT EXISTS `0_purch_ord
    `quantity_ordered` double NOT NULL default '0',
    `quantity_received` double NOT NULL default '0',
    PRIMARY KEY  (`po_detail_item`),
 -  KEY `order` (`order_no`,`po_detail_item`)
 +  KEY `order` (`order_no`,`po_detail_item`),
 +  KEY `itemcode` (`item_code`)
  ) ENGINE=InnoDB AUTO_INCREMENT=1 ;
  
  --
@@@ -1391,8 -1389,7 +1392,8 @@@ CREATE TABLE IF NOT EXISTS `0_sales_ord
    `quantity` double NOT NULL default '0',
    `discount_percent` double NOT NULL default '0',
    PRIMARY KEY  (`id`),
 -  KEY `sorder` (`trans_type`,`order_no`)
 +  KEY `sorder` (`trans_type`,`order_no`),
 +  KEY `stkcode` (`stk_code`)
  ) ENGINE=InnoDB AUTO_INCREMENT=1 ;
  
  --
@@@ -1652,7 -1649,6 +1653,7 @@@ CREATE TABLE IF NOT EXISTS `0_suppliers
    `curr_code` char(3) default NULL,
    `payment_terms` int(11) default NULL,
    `tax_included` tinyint(1) NOT NULL default '0',
 +  `tax_algorithm` tinyint(1) NOT NULL default '1',
    `dimension_id` int(11) default '0',
    `dimension2_id` int(11) default '0',
    `tax_group_id` int(11) default NULL,
@@@ -1746,7 -1742,6 +1747,7 @@@ CREATE TABLE IF NOT EXISTS `0_supp_tran
    `rate` double NOT NULL default '1',
    `alloc` double NOT NULL default '0',
    `tax_included` tinyint(1) NOT NULL default '0',
 +  `tax_algorihm` tinyint(1) NOT NULL default '1',
    PRIMARY KEY  (`type`,`trans_no`),
    KEY `supplier_id` (`supplier_id`),
    KEY `SupplierID_2` (`supplier_id`,`supp_reference`),
@@@ -1771,7 -1766,7 +1772,7 @@@ CREATE TABLE IF NOT EXISTS `0_sys_prefs
    `category` varchar(30) default NULL,
    `type` varchar(20) NOT NULL default '',
    `length` smallint(6) default NULL,
 -  `value` tinytext,
 +  `value` text,
    PRIMARY KEY  (`name`),
    KEY `category` (`category`)
  ) ENGINE=MyISAM;
@@@ -1793,7 -1788,7 +1794,7 @@@ INSERT INTO `0_sys_prefs` VALUES('coy_l
  INSERT INTO `0_sys_prefs` VALUES('domicile', 'setup.company', 'varchar', 55, '');
  INSERT INTO `0_sys_prefs` VALUES('curr_default', 'setup.company', 'char', 3, 'USD');
  INSERT INTO `0_sys_prefs` VALUES('use_dimension', 'setup.company', 'tinyint', 1, '1');
 -INSERT INTO `0_sys_prefs` VALUES('f_year', 'setup.company', 'int', 11, '4');
 +INSERT INTO `0_sys_prefs` VALUES('f_year', 'setup.company', 'int', 11, '3');
  INSERT INTO `0_sys_prefs` VALUES('no_item_list', 'setup.company', 'tinyint', 1, '0');
  INSERT INTO `0_sys_prefs` VALUES('no_customer_list', 'setup.company', 'tinyint', 1, '0');
  INSERT INTO `0_sys_prefs` VALUES('no_supplier_list', 'setup.company', 'tinyint', 1, '0');
@@@ -1807,7 -1802,6 +1808,7 @@@ INSERT INTO `0_sys_prefs` VALUES('profi
  INSERT INTO `0_sys_prefs` VALUES('retained_earnings_act', 'glsetup.general', 'varchar', 15, '3590');
  INSERT INTO `0_sys_prefs` VALUES('bank_charge_act', 'glsetup.general', 'varchar', 15, '5690');
  INSERT INTO `0_sys_prefs` VALUES('exchange_diff_act', 'glsetup.general', 'varchar', 15, '4450');
 +INSERT INTO `0_sys_prefs` VALUES('tax_algorithm', 'glsetup.general', 'tinyint', 1, '1');
  INSERT INTO `0_sys_prefs` VALUES('default_credit_limit', 'glsetup.customer', 'int', 11, '1000');
  INSERT INTO `0_sys_prefs` VALUES('accumulate_shipping', 'glsetup.customer', 'tinyint', 1, '0');
  INSERT INTO `0_sys_prefs` VALUES('legal_text', 'glsetup.customer', 'tinytext', 0, '');
@@@ -1924,6 -1918,7 +1925,6 @@@ DROP TABLE IF EXISTS `0_tax_groups`
  CREATE TABLE IF NOT EXISTS `0_tax_groups` (
    `id` int(11) NOT NULL auto_increment,
    `name` varchar(60) NOT NULL default '',
 -  `tax_shipping` tinyint(1) NOT NULL default '0',
    `inactive` tinyint(1) NOT NULL default '0',
    PRIMARY KEY  (`id`),
    UNIQUE KEY `name` (`name`)
  -- Dumping data for table `0_tax_groups`
  --
  
 -INSERT INTO `0_tax_groups` VALUES(1, 'Tax', 0, 0);
 -INSERT INTO `0_tax_groups` VALUES(2, 'Tax Exempt', 0, 0);
 +INSERT INTO `0_tax_groups` VALUES(1, 'Tax', 0);
 +INSERT INTO `0_tax_groups` VALUES(2, 'Tax Exempt', 0);
  
  -- --------------------------------------------------------
  
@@@ -1946,7 -1941,7 +1947,7 @@@ DROP TABLE IF EXISTS `0_tax_group_items
  CREATE TABLE IF NOT EXISTS `0_tax_group_items` (
    `tax_group_id` int(11) NOT NULL default '0',
    `tax_type_id` int(11) NOT NULL default '0',
 -  `rate` double NOT NULL default '0',
 +  `tax_shipping` tinyint(1) NOT NULL default '0',
    PRIMARY KEY  (`tax_group_id`,`tax_type_id`)
  ) ENGINE=InnoDB;
  
  -- Dumping data for table `0_tax_group_items`
  --
  
 -INSERT INTO `0_tax_group_items` VALUES(1, 1, 5);
 +INSERT INTO `0_tax_group_items` VALUES(1, 1, 5, 1);
  
  -- --------------------------------------------------------
  
diff --combined taxes/tax_calc.inc
index dbb7999e46f0548cf576ac9380755533abf13f37,4c4b9f37c5a7ea047e6a4d908d3a3c7f5502c107..27b1ccfadeca21a750a35021d06aede635a18ee7
@@@ -18,7 -18,6 +18,6 @@@ include_once($path_to_root . "/taxes/db
  // returns the price of a given item minus any included taxes
  // for item $stock_id with line price $price,
  // with applicable tax rates $tax_group_array or group id $tax_group
- //
  
  function get_tax_free_price_for_item($stock_id, $price, $tax_group, $tax_included, $tax_group_array=null)
  {
        //print_r($ret_tax_array);
  
        $tax_array = get_taxes_for_item($stock_id, $ret_tax_array);
++
        // if no exemptions or taxgroup is empty, then no included/excluded taxes
        if ($tax_array == null)
                return $price;
-       
-       $tax_multiplier = 0;
-       // loop for all taxes
  
+       // to avoid rounding errors we have to just subtract taxes from tax_included price.
+       $tax_multiplier = 0;
        foreach ($tax_array as $taxitem) 
        {
                $tax_multiplier += $taxitem["rate"];
        }
  
-       return round($price / (1 + ($tax_multiplier / 100)),  user_price_dec());
+       $tax = 0;
+       foreach ($tax_array as $taxitem)
+       {
+               $tax += round($price*$taxitem['rate']/(100+$tax_multiplier), user_price_dec());
+       }
+       return $price-$tax;
  }
  //
  //    Full price (incl. VAT) for item $stock_id with line price $price,
@@@ -77,7 -79,7 +80,7 @@@ function get_full_price_for_item($stock
        if ($tax_array == null)
                return $price;
        
-       $tax_multiplier = 0;    
+       $tax_multiplier = 0;
  
        // loop for all items
  
@@@ -116,7 -118,7 +119,7 @@@ function get_taxes_for_item($stock_id, 
        foreach ($tax_group_items_array as $tax_group_item) 
        { 
                
-               $skip = false;                  
+               $skip = false;
                
                // if it's in the exemptions, skip
                foreach ($item_tax_type_exemptions as $exemption) 
  //-----------------------------------------------------------------------------------
  // return an array of (tax_type_id, tax_type_name, sales_gl_code, purchasing_gl_code, rate, included_in_price, Value) 
  
 -function get_tax_for_items($items, $prices, $shipping_cost, $tax_group, $tax_included=null, $tax_items_array=null)
 +function get_tax_for_items($items, $prices, $shipping_cost, $tax_group, $tax_included=null, $tax_items_array=null, $tax_algorithm = null)
  {
 +      if (!$tax_algorithm)
 +              $tax_algorithm = get_company_pref('tax_algorithm');
        // first create and set an array with all the tax types of the tax group
        if($tax_items_array!=null)
          $ret_tax_array = $tax_items_array;
        else
          $ret_tax_array = get_tax_group_items_as_array($tax_group);
  
++      $dec = user_price_dec();
++
++      $fully_exempt = true;
        foreach($ret_tax_array as $k=>$t)
++      {
++              if ($t['rate'] !== null)
++                      $fully_exempt = false;
                $ret_tax_array[$k]['Net'] = 0;
++      }
  
++      $ret_tax_array['exempt'] = array('Value'=>0, 'Net'=>0, 'rate' => null, 'tax_type_id' => '');
        $dec = user_price_dec();
        // loop for all items
        for ($i = 0; $i < count($items); $i++)
        {
                $item_taxes = get_taxes_for_item($items[$i], $ret_tax_array);
--              if ($item_taxes != null) 
++              if ($item_taxes == null || $fully_exempt) 
 +              {
++                        $ret_tax_array['exempt']['Value'] += round2(0, $dec);
++                        $ret_tax_array['exempt']['Net'] += $prices[$i];
++              }
++              else
+               {
+                       $tax_multiplier = 0;
+                       foreach ($item_taxes as $taxitem) 
+                       {
+                               $tax_multiplier += $taxitem['rate'];
+                       }
                        foreach ($item_taxes as $item_tax) 
                        {
                                if ($item_tax['rate'] !== null) {
                                        $index = $item_tax['tax_type_id'];
-                                       if($tax_included==1) {// 2008-11-26 Joe Hunt Taxes are stored without roundings
-                                         $nprice = get_tax_free_price_for_item($items[$i], $prices[$i], $tax_group, $tax_included, null, $item_tax['tax_type_id']);
-                                         $ret_tax_array[$index]['Value'] += $nprice*$item_tax['rate']/100;
-                                         $ret_tax_array[$index]['Net'] += $nprice;
+                                       if ($tax_included == 1) {
+                                         $ret_tax_array[$index]['Value'] += round2($prices[$i]*$item_tax['rate']/(100+$tax_multiplier), $dec);
+                                         $ret_tax_array[$index]['Net'] += round2($prices[$i]*100/(100+$tax_multiplier), $dec);
                                        } else {
--                                        $ret_tax_array[$index]['Value'] += ($prices[$i] * $item_tax['rate'] / 100);
++                                        $ret_tax_array[$index]['Value'] += round2($prices[$i] * $item_tax['rate'] / 100, $dec);
                                          $ret_tax_array[$index]['Net'] += $prices[$i];
                                        }
                                }
                        }
                }
        }
-       
 -
        // add the shipping taxes, only if non-zero, and only if tax group taxes shipping
        if ($shipping_cost != 0) 
        {
 -              $item_taxes = get_shipping_tax_as_array();
 +              $item_taxes = get_shipping_tax_as_array($tax_group);
                if ($item_taxes != null) 
                {
                        if ($tax_included == 1)
                                                $tax_rate += $item_tax['rate'];
                                        }
                                }
-                               $shipping_net = round2($shipping_cost / (1 + ($tax_rate / 100)), $dec);
-                       }       
+                               $shipping_net = round2($shipping_cost*100/(100+$tax_rate), $dec);
+                       }
                        foreach ($item_taxes as $item_tax) 
                        {
                                $index = $item_tax['tax_type_id'];
                                if ($item_tax['rate'] !== null && $ret_tax_array[$index]['rate'] !== null) {
-                                         if($tax_included==1) {// 2008-11-26 Joe Hunt Taxes are stored without roundings
-                                               $ret_tax_array[$index]['Value'] += ($shipping_net * $item_tax['rate'] / 100);
+                                         if($tax_included==1) {
+                                           $ret_tax_array[$index]['Value'] += round2($shipping_cost*$item_tax['rate']/(100+$tax_rate), $dec);
                                            $ret_tax_array[$index]['Net'] += $shipping_net;
                                          } else {
--                                              $ret_tax_array[$index]['Value'] += ($shipping_cost * $item_tax['rate'] / 100);
++                                              $ret_tax_array[$index]['Value'] += round2($shipping_cost * $item_tax['rate'] / 100, $dec);
                                            $ret_tax_array[$index]['Net'] += $shipping_cost;
                                          }
                                }
                        }
                }
        }
-       
 -      //print_r($ret_tax_array);
++
 +      if ($tax_algorithm == TCA_TOTALS ) {
 +              // update taxes with 
 +              foreach($ret_tax_array as $index => $item_tax) {
 +                      $ret_tax_array[$index]['Value'] = round2($item_tax['Net'] * $item_tax['rate'] / 100, $dec);
 +              }
 +      }
  
        return $ret_tax_array;
  }
diff --combined update.html
index 6cdf420bb6dcc273b64be4f1c4eeb2a1290077ca,efa23202a2922c5b4f36d5178d4587457272e342..3af13a0ed2c90e66fd6986353990c285d0cd2036
  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
 -<html><head>\r
 -      <meta http-equiv="CONTENT-TYPE" content="text/html; charset=iso-8859-2">\r
 -      \r
 -      <title>FrontAccounting Update</title><meta name="GENERATOR" content="OpenOffice.org 2.4  (Linux)">\r
 -      <meta name="CREATED" content="0;0">\r
 -      <meta name="CHANGED" content="20100902;19041400"></head>\r
 -<body dir="ltr" lang="en-US">\r
 -<p style="margin-bottom: 0cm;"><strong><font color="#cc6600"><font style="font-size: 20pt;" size="5"><i>Front</i></font></font></strong><strong><font style="font-size: 20pt;" size="5">Accounting\r
 -Update</font></strong></p>\r
 -<h2>Important Notes for release 2.3.5.</h2>Change in the behaviour of <span style="font-weight: bold; font-style: italic;">Recurrent Invoices</span>.<br><ul><li>Now\r
 -the Last Sent day is stamped with the former Last Sent (or Begin date\r
 -the first time) + months + days. Before the Last Sent day was stamped\r
 -with tthe creation date (today). The Invoice date is still todays date.\r
 -</li><li>If you for some reason want to make a pause in the recurrent\r
 -invoices, you can now edit the Last Sent day in the Management section\r
 -of Sales tab.</li><li>Before the days value, together with a month\r
 -value, decided which day in the month the invoice was due.. &nbsp;This\r
 -does not&nbsp;work now. You can&nbsp;change the day in the month you\r
 -want the recurrency to happen by setting the Last Sent day with the new\r
 -day in the Management section.&nbsp;</li><li>If you create a new Recurrent Invoice the Beginning date can be set to the day in the month you want the recurrencies to be due.</li></ul>\r
 -<h2>Important Notes</h2>\r
 -<p>Upgrade process can be done only by administrator of the first\r
 -company created during FrontAccounting installation. This person is\r
 -considered as a site admin who have granted access to potentially\r
 -dangerous setup options, like Setup/Software Upgrade.</p>\r
 -<p>In the following description sections related to older FA versions are\r
 -prefixed with <span style="background: rgb(235, 97, 61) none repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial;">[color tags]</span><span style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial;">\r
 -. Y</span>ou can skip tagged fragment safely if currently FA\r
 -application is newer than the version in tag.</p>\r
 -<p>Upgrade process consists of up to four stages, some of them are\r
 -optional:</p>\r
 -<ol>\r
 -      <li><p>Application source files update \r
 -      </p>\r
 -      </li><li><p>Database upgrade &#8211; this step is needed only during\r
 -      upgrade which involves change in major application version number\r
 -      (e.g. from 2.2.x to 2.3.x), and sometimes during upgrade from beta\r
 -      release to stable version. Otherwise this step can be skipped.</p>\r
 -      </li><li><p>Final cleanup &#8211; is needed when some old source files,\r
 -      obsoleted by new release should be removed.</p>\r
 -      </li><li><p>New features configuration &#8211; this is optional step\r
 -      needed for most major releases and some minor ones. \r
 -      </p>\r
 -</li></ol>\r
 -<p style="margin-bottom: 0cm;">Before starting upgrade ensure nobody\r
 -is using the application and make database backup for all companies.\r
 -To be on safe side backup also old source files, especially those\r
 -locally customized (if any).</p>\r
 -<p>Log into admin account of first company.<strong> </strong><strong><span style="">If\r
 -you use a theme other than the standard 3 (aqua, cool or default),\r
 -switch to one of these before going further.</span></strong></p>\r
 -<h2><strong><b>1. Application files update</b></strong></h2>\r
 -<p style="margin-top: 0.42cm; page-break-after: avoid;"><font face="Liberation Sans, sans-serif"><font size="4"><strong><span style="">a. Source\r
 -files update</span></strong></font></font></p>\r
 -<p><strong><span style="">Extract distribution\r
 -zip/tar.gz file in empty directory, and copy all the files to your\r
 -FrontAccounting directory overwriting old files. If it is major\r
 -release upgrade you can skip next step and go directly to cleanup.</span></strong></p>\r
 -<p style="margin-top: 0.42cm; page-break-after: avoid;"><strong><font face="Liberation Sans, sans-serif"><font size="4"><span style="">b. Configuration\r
 -files update</span></font></font></strong></p>\r
 -<p><strong><span style="">Compare new\r
 -</span></strong><strong><i><b>config.default.php</b></i></strong><strong>\r
 -</strong><strong><span style="">file with the old\r
 -</span></strong><strong><i><b>config.php </b></i></strong><strong><span style="font-style: normal;"><span style="">and\r
 -add all n</span></span></strong><strong><span style="">ew\r
 -settings (if any). </span></strong>\r
 -</p>\r
 -<p><strong><span style=""><span style="background: rgb(235, 97, 61) none repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial;">[&lt;FA\r
 -2.2beta]</span></span></strong></p>\r
 -<p><strong> <span style="">$show_users_online = 0;</span></strong></p>\r
 -<p><strong> <span style="">$def_print_destination\r
 -= 0;</span></strong></p>\r
 -<p><strong><span style="">$dflt_date_fmt=0;</span></strong></p>\r
 -<p><strong><span style="">$dflt_date_sep=0;</span></strong></p>\r
 -<p><strong><span style="">$table_style,table_style2\r
 -changed</span></strong></p>\r
 -<p><strong><span style=""><span style="background: rgb(235, 97, 61) none repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial;">[&lt;FA\r
 -2.3beta]</span></span></strong></p>\r
 -<p><strong> <span style="">$alternative_tax_include_on_doc=0;</span></strong></p>\r
 -<p><strong><span style="">$suppress_tax_rates = 0;</span></strong></p>\r
 -<p><strong><span style=""><span style="background: rgb(235, 97, 61) none repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial;">[&lt;FA\r
 -2.3RC1]</span></span></strong><strong> </strong>\r
 -</p>\r
 -<p><strong><span style="">Application version\r
 -information and a couple of other private FA variables are stored in\r
 -</span></strong><strong><i><b>version.php</b></i></strong><strong>\r
 -</strong><strong><span style="">file. The\r
 -application version displayed in footer is defined in $version\r
 -variable unless this is set in config.php file. If you want current\r
 -release version to be displayed on every FA update just remove or\r
 -comment out $version variable in </span></strong><strong><span style="font-style: normal;"><span style="">config.php</span></span></strong><strong><span style="">.</span></strong></p>\r
 -<p><strong><span style=""><span style="background: rgb(235, 97, 61) none repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial;">[&lt;FA\r
 -2.3RC2]</span></span></strong></p>\r
 -<p><strong> <span style="">$save_report_selections &nbsp;= 0; &nbsp;// A value &gt; 0 means days to save the report selections.</span></strong></p><p><strong><span style=""><span style="background: rgb(235, 97, 61) none repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial;">[&lt;FA\r
 -2.3]</span></span></strong></p><p><strong> <span style="">$save_po_item_codes &nbsp;= 0; &nbsp;//&nbsp; show item codes on purchase order&nbsp;</span></strong></p><p><strong><span style="">$def_print_destination = 0; // &nbsp;default print destination. 0 = PDF/Printer, 1 = Excel</span></strong></p><p><strong><span style="">$alternative_tax_include_on_docs = 0; // &nbsp;1 = print Subtotal tax excluded, tax and Total tax included</span></strong></p><p><strong><span style="">$suppress_tax_rates = 0; // &nbsp;suppress tax rates on documents. 0 = no, 1 = yes.</span></strong></p><strong><span style=""><span style="background: rgb(235, 97, 61) none repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial;"></span></span></strong>\r
 -\r
 -<strong><span style=""><span style="background: rgb(235, 97, 61) none repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial;"></span></span></strong><h2><strong><b>2. Database upgrade</b></strong></h2>\r
 -<p><strong><span style="">This step can be skipped\r
 -for small version updates i.e. when you have already installed\r
 -FrontAccounting version 2.3.1 or later. Before database upgrade is\r
 -done on all company databases backup file is created automatically to\r
 -enable database restore after failure.</span></strong></p>\r
 -<p><strong><span style="">After major version\r
 -upgrade overwriting files in first step makes the system unaccessible\r
 -for all users but site admin, who have to run upgrade procedures to\r
 -update all company databases to the new version provided with the\r
 -release. After logging to administrator account of first installed\r
 -company go directly to Setup/Software Upgrade screen, mark all\r
 -subsequent 'Install' checkboxes and press 'Upgrade System'.</span></strong></p>\r
 -<p style="">If something goes wrong during\r
 -upgrade, you can eventually try forced upgrade option. Forced upgrade\r
 -ignores some smaller errors which can arise during upgrade due to\r
 -some exotic database configuration. This is depreciated option, so\r
 -first read error messages if any, try to fix signalized problems,\r
 -restore databases from backup and retry normal installation. To run\r
 -upgrade in forced mode check box 'Force Upgrade', and press 'Upgrade\r
 -System' again.</p>\r
 -<h2>3. Final cleanup</h2>\r
 -<p>Remove or rename install folder in main FrontAccounting directory.\r
 -</p>\r
 -<p>After upgrade is installed you can remove files obsoleted by new\r
 -FrontAccounting version. Also old, unused settings <span style="font-style: normal;"><span style="">can\r
 -be removed from  </span></span><i><b>config.php</b></i><span style="font-style: normal;"><span style="">\r
 -file.</span></span></p>\r
 -<p style="margin-top: 0.42cm; page-break-after: avoid;"><font face="Liberation Sans, sans-serif"><font size="4">a.\r
 -Source files cleanup</font></font></p>\r
 -<p><strong><span style=""><span style="background: rgb(235, 97, 61) none repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial;">[&lt;FA\r
 -2.2beta]</span></span></strong></p>\r
 -<p><strong><span style=""><span style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial;">/includes/reserved.inc\r
 -&#8211; removed.</span></span></strong></p>\r
 -<p><strong><span style=""><span style="background: rgb(235, 97, 61) none repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial;">[&lt;FA\r
 -2.1]</span></span></strong><strong> </strong>\r
 -</p>\r
 -<p><strong><span style="">/admin/db/v_banktrans.inc\r
 -- removed</span></strong></p>\r
 -<p style="margin-top: 0.42cm; page-break-after: avoid;"><font face="Liberation Sans, sans-serif"><font size="4"><span style="font-style: normal;"><span style="">b.\r
 -Config.php cleanup </span></span></font></font>\r
 -</p>\r
 -<p><strong><span style=""><span style="background: rgb(235, 97, 61) none repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial;">[&lt;FA\r
 -2.2RC1]</span></span></strong><strong> </strong>\r
 -</p>\r
 -<p><strong><span style="">$security_headings,\r
 -$security_groups arrays &#8211; moved to database (see Access Setup) \r
 -</span></strong>\r
 -</p>\r
 -<p><strong><span style="">$def_app &#8211; moved\r
 -to user configuration in database.</span></strong></p>\r
 -<p><strong><span style="font-style: normal;"><span style="">$version\r
 -&#8211; moved to </span></span></strong><strong><i><b>version.php</b></i></strong><strong><span style="font-style: normal;"><span style="">\r
 -file. Remove</span></span></strong></p>\r
 -<h2>4. New features configuration</h2>\r
 -<p>During upgrade process new features are initialized to default\r
 -status, and sometimes old settings are also changed to conform with\r
 -new security policy. This automatic process is designed to be as\r
 -neutral for end users as possible, however sometimes site or company\r
 -admin intervention can be necessary to set thing after changes to\r
 -their best state. Below you will find description of new settings\r
 -available after upgrade.</p>\r
 -<p><br><br>\r
 -</p>\r
 -<p>----------------------</p>\r
 -<ul></ul>\r
 +<html><head>
 +      <meta http-equiv="CONTENT-TYPE" content="text/html; charset=iso-8859-2">
 +      
 +      <title>FrontAccounting Update</title><meta name="GENERATOR" content="OpenOffice.org 2.4  (Linux)">
 +      <meta name="CREATED" content="0;0">
 +      <meta name="CHANGED" content="20100902;19041400"></head>
 +<body dir="ltr" lang="en-US">
 +<p style="margin-bottom: 0cm;"><strong><font color="#cc6600"><font style="font-size: 20pt;" size="5"><i>Front</i></font></font></strong><strong><font style="font-size: 20pt;" size="5">Accounting
 +Update</font></strong></p>
++<h2>Important Notes for release 2.3.5.</h2>Change in the behaviour of <span style="font-weight: bold; font-style: italic;">Recurrent Invoices</span>.<br><ul><li>Now
++the Last Sent day is stamped with the former Last Sent (or Begin date
++the first time) + months + days. Before the Last Sent day was stamped
++with tthe creation date (today). The Invoice date is still todays date.
++</li><li>If you for some reason want to make a pause in the recurrent
++invoices, you can now edit the Last Sent day in the Management section
++of Sales tab.</li><li>Before the days value, together with a month
++value, decided which day in the month the invoice was due.. &nbsp;This
++does not&nbsp;work now. You can&nbsp;change the day in the month you
++want the recurrency to happen by setting the Last Sent day with the new
++day in the Management section.&nbsp;</li><li>If you create a new Recurrent Invoice the Beginning date can be set to the day in the month you want the recurrencies to be due.</li></ul>
 +<h2>Important Notes</h2>
 +<p>Upgrade process can be done only by administrator of the first
 +company created during FrontAccounting installation. This person is
 +considered as a site admin who have granted access to potentially
 +dangerous setup options, like Setup/Software Upgrade.</p>
 +<p>In the following description sections related to older FA versions are
 +prefixed with <span style="background: rgb(235, 97, 61) none repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial;">[color tags]</span><span style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial;">
 +. Y</span>ou can skip tagged fragment safely if currently FA
 +application is newer than the version in tag.</p>
 +<p>Upgrade process consists of up to four stages, some of them are
 +optional:</p>
 +<ol>
 +      <li><p>Application source files update 
 +      </p>
 +      </li><li><p>Database upgrade &#8211; this step is needed only during
 +      upgrade which involves change in major application version number
 +      (e.g. from 2.2.x to 2.3.x), and sometimes during upgrade from beta
 +      release to stable version. Otherwise this step can be skipped.</p>
 +      </li><li><p>Final cleanup &#8211; is needed when some old source files,
 +      obsoleted by new release should be removed.</p>
 +      </li><li><p>New features configuration &#8211; this is optional step
 +      needed for most major releases and some minor ones. 
 +      </p>
 +</li></ol>
 +<p style="margin-bottom: 0cm;">Before starting upgrade ensure nobody
 +is using the application and make database backup for all companies.
 +To be on safe side backup also old source files, especially those
 +locally customized (if any).</p>
 +<p>Log into admin account of first company.<strong> </strong><strong><span style="">If
 +you use a theme other than the standard 3 (aqua, cool or default),
 +switch to one of these before going further.</span></strong></p>
 +<h2><strong><b>1. Application files update</b></strong></h2>
 +<p style="margin-top: 0.42cm; page-break-after: avoid;"><font face="Liberation Sans, sans-serif"><font size="4"><strong><span style="">a. Source
 +files update</span></strong></font></font></p>
 +<p><strong><span style="">Extract distribution
 +zip/tar.gz file in empty directory, and copy all the files to your
 +FrontAccounting directory overwriting old files. If it is major
 +release upgrade you can skip next step and go directly to cleanup.</span></strong></p>
 +<p style="margin-top: 0.42cm; page-break-after: avoid;"><strong><font face="Liberation Sans, sans-serif"><font size="4"><span style="">b. Configuration
 +files update</span></font></font></strong></p>
 +<p><strong><span style="">Compare new
 +</span></strong><strong><i><b>config.default.php</b></i></strong><strong>
 +</strong><strong><span style="">file with the old
 +</span></strong><strong><i><b>config.php </b></i></strong><strong><span style="font-style: normal;"><span style="">and
 +add all n</span></span></strong><strong><span style="">ew
 +settings (if any). </span></strong>
 +</p>
 +<p><strong><span style=""><span style="background: rgb(235, 97, 61) none repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial;">[&lt;FA
 +2.2beta]</span></span></strong></p>
 +<p><strong> <span style="">$show_users_online = 0;</span></strong></p>
 +<p><strong> <span style="">$def_print_destination
 += 0;</span></strong></p>
 +<p><strong><span style="">$dflt_date_fmt=0;</span></strong></p>
 +<p><strong><span style="">$dflt_date_sep=0;</span></strong></p>
 +<p><strong><span style="">$table_style,table_style2
 +changed</span></strong></p>
 +<p><strong><span style=""><span style="background: rgb(235, 97, 61) none repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial;">[&lt;FA
 +2.3beta]</span></span></strong></p>
 +<p><strong> <span style="">$alternative_tax_include_on_doc=0;</span></strong></p>
 +<p><strong><span style="">$suppress_tax_rates = 0;</span></strong></p>
 +<p><strong><span style=""><span style="background: rgb(235, 97, 61) none repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial;">[&lt;FA
 +2.3RC1]</span></span></strong><strong> </strong>
 +</p>
 +<p><strong><span style="">Application version
 +information and a couple of other private FA variables are stored in
 +</span></strong><strong><i><b>version.php</b></i></strong><strong>
 +</strong><strong><span style="">file. The
 +application version displayed in footer is defined in $version
 +variable unless this is set in config.php file. If you want current
 +release version to be displayed on every FA update just remove or
 +comment out $version variable in </span></strong><strong><span style="font-style: normal;"><span style="">config.php</span></span></strong><strong><span style="">.</span></strong></p>
 +<p><strong><span style=""><span style="background: rgb(235, 97, 61) none repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial;">[&lt;FA
 +2.3RC2]</span></span></strong></p>
- <p><strong> <span style="">$save_report_selections &nbsp;= 0; &nbsp;// A value &gt; 0 means days to save the report selections</span></strong></p>
++<p><strong> <span style="">$save_report_selections &nbsp;= 0; &nbsp;// A value &gt; 0 means days to save the report selections.</span></strong></p><p><strong><span style=""><span style="background: rgb(235, 97, 61) none repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial;">[&lt;FA
++2.3]</span></span></strong></p><p><strong> <span style="">$save_po_item_codes &nbsp;= 0; &nbsp;//&nbsp; show item codes on purchase order&nbsp;</span></strong></p><p><strong><span style="">$def_print_destination = 0; // &nbsp;default print destination. 0 = PDF/Printer, 1 = Excel</span></strong></p><p><strong><span style="">$alternative_tax_include_on_docs = 0; // &nbsp;1 = print Subtotal tax excluded, tax and Total tax included</span></strong></p><p><strong><span style="">$suppress_tax_rates = 0; // &nbsp;suppress tax rates on documents. 0 = no, 1 = yes.</span></strong></p><strong><span style=""><span style="background: rgb(235, 97, 61) none repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial;"></span></span></strong>
 +
 +<strong><span style=""><span style="background: rgb(235, 97, 61) none repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial;"></span></span></strong><h2><strong><b>2. Database upgrade</b></strong></h2>
 +<p><strong><span style="">This step can be skipped
 +for small version updates i.e. when you have already installed
 +FrontAccounting version 2.3.1 or later. Before database upgrade is
 +done on all company databases backup file is created automatically to
 +enable database restore after failure.</span></strong></p>
 +<p><strong><span style="">After major version
 +upgrade overwriting files in first step makes the system unaccessible
 +for all users but site admin, who have to run upgrade procedures to
 +update all company databases to the new version provided with the
 +release. After logging to administrator account of first installed
 +company go directly to Setup/Software Upgrade screen, mark all
 +subsequent 'Install' checkboxes and press 'Upgrade System'.</span></strong></p>
 +<p style="">If something goes wrong during
 +upgrade, you can eventually try forced upgrade option. Forced upgrade
 +ignores some smaller errors which can arise during upgrade due to
 +some exotic database configuration. This is depreciated option, so
 +first read error messages if any, try to fix signalized problems,
 +restore databases from backup and retry normal installation. To run
 +upgrade in forced mode check box 'Force Upgrade', and press 'Upgrade
 +System' again.</p>
 +<h2>3. Final cleanup</h2>
 +<p>Remove or rename install folder in main FrontAccounting directory.
 +</p>
 +<p>After upgrade is installed you can remove files obsoleted by new
 +FrontAccounting version. Also old, unused settings <span style="font-style: normal;"><span style="">can
 +be removed from  </span></span><i><b>config.php</b></i><span style="font-style: normal;"><span style="">
 +file.</span></span></p>
 +<p style="margin-top: 0.42cm; page-break-after: avoid;"><font face="Liberation Sans, sans-serif"><font size="4">a.
 +Source files cleanup</font></font></p>
 +<p><strong><span style=""><span style="background: rgb(235, 97, 61) none repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial;">[&lt;FA
 +2.2beta]</span></span></strong></p>
 +<p><strong><span style=""><span style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial;">/includes/reserved.inc
 +&#8211; removed.</span></span></strong></p>
 +<p><strong><span style=""><span style="background: rgb(235, 97, 61) none repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial;">[&lt;FA
 +2.1]</span></span></strong><strong> </strong>
 +</p>
 +<p><strong><span style="">/admin/db/v_banktrans.inc
 +- removed</span></strong></p>
 +<p style="margin-top: 0.42cm; page-break-after: avoid;"><font face="Liberation Sans, sans-serif"><font size="4"><span style="font-style: normal;"><span style="">b.
 +Config.php cleanup </span></span></font></font>
 +</p>
 +<p><strong><span style=""><span style="background: rgb(235, 97, 61) none repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial;">[&lt;FA
 +2.2RC1]</span></span></strong><strong> </strong>
 +</p>
 +<p><strong><span style="">$security_headings,
 +$security_groups arrays &#8211; moved to database (see Access Setup) 
 +</span></strong>
 +</p>
 +<p><strong><span style="">$def_app &#8211; moved
 +to user configuration in database.</span></strong></p>
 +<p><strong><span style="font-style: normal;"><span style="">$version
 +&#8211; moved to </span></span></strong><strong><i><b>version.php</b></i></strong><strong><span style="font-style: normal;"><span style="">
 +file. Remove</span></span></strong></p>
 +<h2>4. New features configuration</h2>
 +<p>During upgrade process new features are initialized to default
 +status, and sometimes old settings are also changed to conform with
 +new security policy. This automatic process is designed to be as
 +neutral for end users as possible, however sometimes site or company
 +admin intervention can be necessary to set thing after changes to
 +their best state. Below you will find description of new settings
 +available after upgrade.</p>
 +<p><br><br>
 +</p>
 +<p>----------------------</p>
 +<ul></ul>
  </body></html>
diff --combined version.php
index 807ff4dcc740cc8da56bfbbae3917883400b463f,8c86a3cc72780e7d05882498df33f9a0e2a4e930..1b3db02e8fdeb9893cfaaaeaad54a738f401149a
@@@ -9,7 -9,7 +9,7 @@@ $db_version = "2.3rc"
  
  // application version - can be overriden in config.php
  if (!isset($version))
-       $version                = "2.4 CVS 1";
 -      $version                = "2.3.10";
++      $version                = "2.4 alpha";
  
  //======================================================================
  // Extension packages repository settings