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