Incorrect Journal Balance (sales invoice) when many decimals in tax and price.
[fa-stable.git] / reporting / rep301.php
1 <?php
2 /**********************************************************************
3     Copyright (C) FrontAccounting, LLC.
4         Released under the terms of the GNU General Public License, GPL,
5         as published by the Free Software Foundation, either version 3
6         of the License, or (at your option) any later version.
7     This program is distributed in the hope that it will be useful,
8     but WITHOUT ANY WARRANTY; without even the implied warranty of
9     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10     See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
11 ***********************************************************************/
12 $page_security = 'SA_ITEMSVALREP';
13 // ----------------------------------------------------------------
14 // $ Revision:  2.4 $
15 // Creator:             Joe Hunt, boxygen
16 // date_:               2014-05-13
17 // Title:               Inventory Valuation
18 // ----------------------------------------------------------------
19 $path_to_root="..";
20
21 include_once($path_to_root . "/includes/session.inc");
22 include_once($path_to_root . "/includes/date_functions.inc");
23 include_once($path_to_root . "/includes/data_checks.inc");
24 include_once($path_to_root . "/gl/includes/gl_db.inc");
25 include_once($path_to_root . "/inventory/includes/db/items_category_db.inc");
26
27 //----------------------------------------------------------------------------------------------------
28
29 print_inventory_valuation_report();
30
31 function get_domestic_price($myrow, $stock_id)
32 {
33     if ($myrow['type'] == ST_SUPPRECEIVE || $myrow['type'] == ST_SUPPCREDIT)
34      {
35         $price = $myrow['price'];
36         if ($myrow['person_id'] > 0)
37         {
38             // Do we have foreign currency?
39             $supp = get_supplier($myrow['person_id']);
40             $currency = $supp['curr_code'];
41             $ex_rate = $myrow['ex_rate'];
42             $price *= $ex_rate;
43         }
44     }
45     else
46         $price = $myrow['standard_cost']; //pick standard_cost for sales deliveries
47
48     return $price;
49 }
50
51 function getAverageCost($stock_id, $location, $to_date)
52 {
53         if ($to_date == null)
54                 $to_date = Today();
55
56         $to_date = date2sql($to_date);
57
58         $sql = "SELECT move.*, supplier.supplier_id person_id, IF(ISNULL(grn.rate), credit.rate, grn.rate) ex_rate
59                 FROM ".TB_PREF."stock_moves move
60                                 LEFT JOIN ".TB_PREF."supp_trans credit ON credit.trans_no=move.trans_no AND credit.type=move.type
61                                 LEFT JOIN ".TB_PREF."grn_batch grn ON grn.id=move.trans_no AND 25=move.type
62                                 LEFT JOIN ".TB_PREF."suppliers supplier ON IFNULL(grn.supplier_id, credit.supplier_id)=supplier.supplier_id
63                                 LEFT JOIN ".TB_PREF."debtor_trans cust_trans ON cust_trans.trans_no=move.trans_no AND cust_trans.type=move.type
64                                 LEFT JOIN ".TB_PREF."debtors_master debtor ON cust_trans.debtor_no=debtor.debtor_no
65                         WHERE stock_id=".db_escape($stock_id)."
66                         AND move.tran_date <= '$to_date' AND standard_cost > 0.001 AND qty <> 0 AND move.type <> ".ST_LOCTRANSFER;
67
68         if ($location != 'all')
69                 $sql .= " AND move.loc_code = ".db_escape($location);
70
71         $sql .= " ORDER BY tran_date";  
72
73         $result = db_query($sql, "No standard cost transactions were returned");
74     
75     if ($result == false)
76         return 0;
77         $qty = $tot_cost = 0;
78         while ($row=db_fetch($result))
79         {
80                 $qty += $row['qty'];    
81                 $price = get_domestic_price($row, $stock_id);
82         $tran_cost = $row['qty'] * $price;
83         $tot_cost += $tran_cost;
84         }
85         if ($qty == 0)
86                 return 0;
87         return $tot_cost / $qty;
88 }
89
90 function getTransactions($category, $location, $date)
91 {
92         $date = date2sql($date);
93
94         $sql = "SELECT item.category_id,
95                         category.description AS cat_description,
96                         item.stock_id,
97                         item.units,
98                         item.description, item.inactive,
99                         move.loc_code,
100                         units.decimals,
101                         SUM(move.qty) AS QtyOnHand, 
102                         item.material_cost AS UnitCost,
103                         SUM(move.qty) * item.material_cost AS ItemTotal 
104                         FROM "
105                         .TB_PREF."stock_master item,"
106                         .TB_PREF."stock_category category,"
107                         .TB_PREF."stock_moves move,"
108                         .TB_PREF."item_units units
109                 WHERE item.stock_id=move.stock_id
110                 AND item.category_id=category.category_id
111                 AND item.mb_flag<>'D' AND mb_flag <> 'F' 
112                 AND move.tran_date <= '$date'
113                 AND item.units=units.abbr
114                 GROUP BY item.category_id,
115                         category.description, ";
116                 if ($location != 'all')
117                         $sql .= "move.loc_code, ";
118                 $sql .= "item.stock_id,
119                         item.description
120                 HAVING ROUND(SUM(move.qty), units.decimals) != 0";
121                 if ($category != 0)
122                         $sql .= " AND item.category_id = ".db_escape($category);
123                 if ($location != 'all')
124                         $sql .= " AND move.loc_code = ".db_escape($location);
125                 $sql .= " ORDER BY item.category_id,
126                         item.stock_id";
127
128     return db_query($sql,"No transactions were returned");
129 }
130
131 //----------------------------------------------------------------------------------------------------
132
133 function print_inventory_valuation_report()
134 {
135     global $path_to_root, $SysPrefs;
136
137         $date = $_POST['PARAM_0'];
138     $category = $_POST['PARAM_1'];
139     $location = $_POST['PARAM_2'];
140     $detail = $_POST['PARAM_3'];
141     $comments = $_POST['PARAM_4'];
142         $orientation = $_POST['PARAM_5'];
143         $destination = $_POST['PARAM_6'];
144         if ($destination)
145                 include_once($path_to_root . "/reporting/includes/excel_report.inc");
146         else
147                 include_once($path_to_root . "/reporting/includes/pdf_report.inc");
148         $detail = !$detail;
149     $dec = user_price_dec();
150
151         $orientation = ($orientation ? 'L' : 'P');
152         if ($category == ALL_NUMERIC)
153                 $category = 0;
154         if ($category == 0)
155                 $cat = _('All');
156         else
157                 $cat = get_category_name($category);
158
159         if ($location == ALL_TEXT)
160                 $location = 'all';
161         if ($location == 'all')
162                 $loc = _('All');
163         else
164                 $loc = get_location_name($location);
165
166         $cols = array(0, 75, 225, 250, 350, 450,        515);
167
168         $headers = array(_('Category'), '', _('UOM'), _('Quantity'), _('Unit Cost'), _('Value'));
169
170         $aligns = array('left', 'left', 'left', 'right', 'right', 'right');
171
172     $params =   array(  0 => $comments,
173                                         1 => array('text' => _('End Date'), 'from' => $date,            'to' => ''),
174                                     2 => array('text' => _('Category'), 'from' => $cat, 'to' => ''),
175                                     3 => array('text' => _('Location'), 'from' => $loc, 'to' => ''));
176
177     $rep = new FrontReport(_('Inventory Valuation Report'), "InventoryValReport", user_pagesize(), 9, $orientation);
178     if ($orientation == 'L')
179         recalculate_cols($cols);
180     $rep->Font();
181     $rep->Info($params, $cols, $headers, $aligns);
182     $rep->NewPage();
183
184         $res = getTransactions($category, $location, $date);
185         $total = $grandtotal = 0.0;
186         $catt = '';
187         while ($trans=db_fetch($res))
188         {
189                 if ($catt != $trans['cat_description'])
190                 {
191                         if ($catt != '')
192                         {
193                                 if ($detail)
194                                 {
195                                         $rep->NewLine(2, 3);
196                                         $rep->TextCol(0, 4, _('Total'));
197                                 }
198                                 $rep->AmountCol(5, 6, $total, $dec);
199                                 if ($detail)
200                                 {
201                                         $rep->Line($rep->row - 2);
202                                         $rep->NewLine();
203                                 }
204                                 $rep->NewLine();
205                                 $total = 0.0;
206                         }
207                         $rep->TextCol(0, 1, $trans['category_id']);
208                         $rep->TextCol(1, 2, $trans['cat_description']);
209                         $catt = $trans['cat_description'];
210                         if ($detail)
211                                 $rep->NewLine();
212                 }
213                 if (isset($SysPrefs->use_costed_values) && $SysPrefs->use_costed_values==1)
214                 {
215                         $UnitCost = getAverageCost($trans['stock_id'], $location, $date);
216                         $ItemTotal = $trans['QtyOnHand'] * $UnitCost;
217                 }       
218                 else
219                 {
220                         $UnitCost = $trans['UnitCost'];
221                         $ItemTotal = $trans['ItemTotal'];
222                 }       
223                 if ($detail)
224                 {
225                         $rep->NewLine();
226                         $rep->fontSize -= 2;
227                         $rep->TextCol(0, 1, $trans['stock_id']);
228                         $rep->TextCol(1, 2, $trans['description'].($trans['inactive']==1 ? " ("._("Inactive").")" : ""), -1);
229                         $rep->TextCol(2, 3, $trans['units']);
230                         $rep->AmountCol(3, 4, $trans['QtyOnHand'], get_qty_dec($trans['stock_id']));
231                         
232                         $dec2 = 0;
233                         price_decimal_format($UnitCost, $dec2);
234                         $rep->AmountCol(4, 5, $UnitCost, $dec2);
235                         $rep->AmountCol(5, 6, $ItemTotal, $dec);
236                         $rep->fontSize += 2;
237                 }
238                 $total += $ItemTotal;
239                 $grandtotal += $ItemTotal;
240         }
241         if ($detail)
242         {
243                 $rep->NewLine(2, 3);
244                 $rep->TextCol(0, 4, _('Total'));
245         }
246         $rep->Amountcol(5, 6, $total, $dec);
247         if ($detail)
248         {
249                 $rep->Line($rep->row - 2);
250                 $rep->NewLine();
251         }
252         $rep->NewLine(2, 1);
253         $rep->TextCol(0, 4, _('Grand Total'));
254         $rep->AmountCol(5, 6, $grandtotal, $dec);
255         $rep->Line($rep->row  - 4);
256         $rep->NewLine();
257     $rep->End();
258 }
259