Optimized Inventory Valuation Reports, 301 and 308.
[fa-stable.git] / reporting / rep308.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.3 $
15 // Creator:             boxygen
16 // date_:               2017-05-12
17 // Title:               Costed Inventory Movements
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/ui/ui_input.inc");
24 include_once($path_to_root . "/includes/data_checks.inc");
25 include_once($path_to_root . "/gl/includes/gl_db.inc");
26 include_once($path_to_root . "/sales/includes/db/sales_types_db.inc");
27 include_once($path_to_root . "/inventory/includes/inventory_db.inc");
28
29 //----------------------------------------------------------------------------------------------------
30
31 inventory_movements();
32
33 function get_domestic_price($myrow, $stock_id)
34 {
35     if ($myrow['type'] == ST_SUPPRECEIVE || $myrow['type'] == ST_SUPPCREDIT)
36     {
37         $price = $myrow['price'];
38         if ($myrow['person_id'] > 0)
39         {
40             // Do we have foreign currency?
41             $supp = get_supplier($myrow['person_id']);
42             $currency = $supp['curr_code'];
43             $ex_rate = get_exchange_rate_to_home_currency($currency, sql2date($myrow['tran_date']));
44             $price /= $ex_rate;
45         }
46     }
47     else
48         $price = $myrow['standard_cost']; // Item Adjustments just have the real cost
49     return $price;
50 }
51
52 function fetch_items($category=0)
53 {
54         $sql = "SELECT stock_id, stock.description AS name,
55                 stock.category_id,units,
56                 cat.description
57             FROM ".TB_PREF."stock_master stock LEFT JOIN ".TB_PREF."stock_category cat ON stock.category_id=cat.category_id
58                 WHERE mb_flag <> 'D'";
59         if ($category != 0)
60             $sql .= " AND cat.category_id = ".db_escape($category);
61         $sql .= " ORDER BY stock.category_id, stock_id";
62     return db_query($sql,"No transactions were returned");
63 }
64
65 function trans_qty($stock_id, $location=null, $from_date, $to_date, $inward = true)
66 {
67     if ($from_date == null)
68         $from_date = Today();
69     
70     $from_date = date2sql($from_date);
71     
72     if ($to_date == null)
73         $to_date = Today();
74     
75     $to_date = date2sql($to_date);
76     
77     $sql = "SELECT ".($inward ? '' : '-')."SUM(qty) FROM ".TB_PREF."stock_moves
78         WHERE stock_id=".db_escape($stock_id)."
79         AND tran_date >= '$from_date'
80         AND tran_date <= '$to_date' AND type <> ".ST_LOCTRANSFER;
81     
82     if ($location != '')
83         $sql .= " AND loc_code = ".db_escape($location);
84     
85     if ($inward)
86         $sql .= " AND qty > 0 ";
87     else
88         $sql .= " AND qty < 0 ";
89     
90     $result = db_query($sql, "QOH calculation failed");
91     
92     $myrow = db_fetch_row($result);
93     
94     return $myrow[0];
95 }
96
97 function avg_unit_cost($stock_id, $location=null, $to_date)
98 {
99     if ($to_date == null)
100         $to_date = Today();
101     
102     $to_date = date2sql($to_date);
103     
104     $sql = "SELECT standard_cost, price, tran_date, type, trans_no, qty, person_id  FROM ".TB_PREF."stock_moves
105         WHERE stock_id=".db_escape($stock_id)."
106         AND tran_date < '$to_date' AND standard_cost > 0.001 AND qty <> 0 AND type <> ".ST_LOCTRANSFER;
107     
108     if ($location != '')
109         $sql .= " AND loc_code = ".db_escape($location);
110     $sql .= " ORDER BY tran_date";
111     
112     $result = db_query($sql, "No standard cost transactions were returned");
113     
114     if ($result == false)
115         return 0;
116     
117     $qty = $tot_cost = 0;
118     while ($row=db_fetch($result))
119     {
120         $qty += $row['qty'];
121         $price = get_domestic_price($row, $stock_id);
122         $tran_cost = $price * $row['qty'];
123         $tot_cost += $tran_cost;
124     }
125     if ($qty != 0)
126         return $tot_cost/ $qty;
127     else
128         return 0; //by Faisal
129 }
130
131 //----------------------------------------------------------------------------------------------------
132
133 function trans_qty_unit_cost($stock_id, $location=null, $from_date, $to_date, $inward = true)
134 {
135     if ($from_date == null)
136         $from_date = Today();
137     
138     $from_date = date2sql($from_date);
139     
140     if ($to_date == null)
141         $to_date = Today();
142     
143     $to_date = date2sql($to_date);
144     
145     $sql = "SELECT standard_cost, price, tran_date, type, trans_no, qty, person_id FROM ".TB_PREF."stock_moves
146         WHERE stock_id=".db_escape($stock_id)."
147         AND tran_date <= '$to_date' AND tran_date >= '$from_date' AND standard_cost > 0.001 AND qty <> 0 AND type <> ".ST_LOCTRANSFER;
148     
149     if ($location != '')
150         $sql .= " AND loc_code = ".db_escape($location);
151     
152     if ($inward)
153         $sql .= " AND qty > 0 ";
154     else
155         $sql .= " AND qty < 0 ";
156     $sql .= " ORDER BY tran_date";
157     
158     $result = db_query($sql, "No standard cost transactions were returned");
159     
160     if ($result == false)
161         return 0;
162     
163     $qty = $tot_cost = 0;
164     while ($row=db_fetch($result))
165     {
166         $qty += $row['qty'];
167         $price = get_domestic_price($row, $stock_id); 
168         $tran_cost = $row['qty'] * $price;
169         $tot_cost += $tran_cost;
170     }
171     if ($qty != 0)
172         return $tot_cost/ $qty;
173     else
174         return 0; //by Faisal
175 }
176
177 //----------------------------------------------------------------------------------------------------
178
179 function inventory_movements()
180 {
181     global $path_to_root;
182     
183     $from_date = $_POST['PARAM_0'];
184     $to_date = $_POST['PARAM_1'];
185     $category = $_POST['PARAM_2'];
186     $location = $_POST['PARAM_3'];
187     $comments = $_POST['PARAM_4'];
188     
189     $orientation = $_POST['PARAM_5'];
190     $destination = $_POST['PARAM_6'];
191     if ($destination)
192         include_once($path_to_root . "/reporting/includes/excel_report.inc");
193     else
194         include_once($path_to_root . "/reporting/includes/pdf_report.inc");
195     $orientation = ($orientation ? 'L' : 'P');
196     if ($category == ALL_NUMERIC)
197         $category = 0;
198     if ($category == 0)
199         $cat = _('All');
200     else
201         $cat = get_category_name($category);
202     
203     if ($location == '')
204         $loc = _('All');
205     else
206         $loc = get_location_name($location);
207     
208     $cols = array(0, 60, 130, 160, 185, 215, 250, 275, 305, 340, 365, 395, 430, 455, 485, 520);
209     
210     $headers = array(_('Category'), _('Description'),    _('UOM'), '', '', _('OpeningStock'), '', '',_('StockIn'), '', '', _('Delivery'), '', '', _('ClosingStock'));
211     $headers2 = array("", "", "", _("QTY"), _("Rate"), _("Value"), _("QTY"), _("Rate"), _("Value"), _("QTY"), _("Rate"), _("Value"), _("QTY"), _("Rate"), _("Value"));
212     
213     $aligns = array('left',    'left',    'left', 'right', 'right', 'right', 'right','right' ,'right', 'right', 'right','right', 'right', 'right', 'right');
214     
215     $params =   array(  0 => $comments,
216                         1 => array('text' => _('Period'), 'from' => $from_date, 'to' => $to_date),
217                         2 => array('text' => _('Category'), 'from' => $cat, 'to' => ''),
218                         3 => array('text' => _('Location'), 'from' => $loc, 'to' => ''));
219     
220     $rep = new FrontReport(_('Costed Inventory Movements'), "CostedInventoryMovements", user_pagesize(), 8, $orientation);
221     if ($orientation == 'L')
222         recalculate_cols($cols);
223     
224     $rep->Font();
225     $rep->Info($params, $cols, $headers2, $aligns, $cols, $headers, $aligns);
226     $rep->NewPage();
227     
228     $totval_open = $totval_in = $totval_out = $totval_close = 0;
229     $result = fetch_items($category);
230     
231     $dec = user_price_dec();
232     $catgor = '';
233     while ($myrow=db_fetch($result))
234     {
235         if ($catgor != $myrow['description'])
236         {
237             $rep->NewLine(2);
238             $rep->fontSize += 2;
239             $rep->TextCol(0, 3, $myrow['category_id'] . " - " . $myrow['description']);
240             $catgor = $myrow['description'];
241             $rep->fontSize -= 2;
242             $rep->NewLine();
243         }
244         $qoh_start = get_qoh_on_date($myrow['stock_id'], $location, add_days($from_date, -1));
245         $qoh_end = get_qoh_on_date($myrow['stock_id'], $location, $to_date);
246         
247         $inward = trans_qty($myrow['stock_id'], $location, $from_date, $to_date);
248         $outward = trans_qty($myrow['stock_id'], $location, $from_date, $to_date, false);
249         $openCost = avg_unit_cost($myrow['stock_id'], $location, $from_date);
250         $unitCost = avg_unit_cost($myrow['stock_id'], $location, add_days($to_date, 1));
251         if ($qoh_start == 0 && $inward == 0 && $outward == 0 && $qoh_end == 0)
252             continue;
253         $rep->NewLine();
254         $rep->TextCol(0, 1,    $myrow['stock_id']);
255         $rep->TextCol(1, 2, $myrow['name']);
256         $rep->TextCol(2, 3, $myrow['units']);
257         $rep->AmountCol(3, 4, $qoh_start, get_qty_dec($myrow['stock_id']));
258         $rep->AmountCol(4, 5, $openCost, $dec);
259         $openCost *= $qoh_start;
260         $totval_open += $openCost;
261         $rep->AmountCol(5, 6, $openCost);
262         
263         if($inward>0){
264             $rep->AmountCol(6, 7, $inward, get_qty_dec($myrow['stock_id']));
265             $unitCost_in = trans_qty_unit_cost($myrow['stock_id'], $location, $from_date, $to_date);
266             $rep->AmountCol(7, 8, $unitCost_in,$dec);
267             $unitCost_in *= $inward;
268             $totval_in += $unitCost_in;
269             $rep->AmountCol(8, 9, $unitCost_in);
270         }
271         
272         if($outward>0){
273             $rep->AmountCol(9, 10, $outward, get_qty_dec($myrow['stock_id']));
274             $unitCost_out =    trans_qty_unit_cost($myrow['stock_id'], $location, $from_date, $to_date, false);
275             $rep->AmountCol(10, 11, $unitCost_out,$dec);
276             $unitCost_out *= $outward;
277             $totval_out += $unitCost_out;
278             $rep->AmountCol(11, 12, $unitCost_out);
279         }
280         
281         $rep->AmountCol(12, 13, $qoh_end, get_qty_dec($myrow['stock_id']));
282         $rep->AmountCol(13, 14, $unitCost,$dec);
283         $unitCost *= $qoh_end;
284         $totval_close += $unitCost;
285         $rep->AmountCol(14, 15, $unitCost);
286         
287         $rep->NewLine(0, 1);
288     }
289     $rep->Line($rep->row  - 4);
290     $rep->NewLine(2);
291     $rep->TextCol(0, 1,    _("Total"));
292     $rep->AmountCol(5, 6, $totval_open);
293     $rep->AmountCol(8, 9, $totval_in);
294     $rep->AmountCol(11, 12, $totval_out);
295     $rep->AmountCol(14, 15, $totval_close);
296     $rep->Line($rep->row  - 4);
297     
298     $rep->End();
299 }
300 ?>