Cost handling in purchasing module fixed.
[fa-stable.git] / purchasing / includes / db / po_db.inc
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 // ------------------------------------------------------------------------------
13
14 function get_supplier_details_to_order(&$order, $supplier_id)
15 {
16         $sql = "SELECT curr_code, supp_name, tax_group_id, supp.tax_included, dimension_id, dimension2_id,
17                         supp.credit_limit - Sum((ov_amount + ov_gst + ov_discount)) as cur_credit,
18                                 terms.terms, terms.days_before_due, terms.day_in_following_month, tg.tax_area
19                 FROM ".TB_PREF."suppliers supp
20                          LEFT JOIN ".TB_PREF."supp_trans trans ON supp.supplier_id = trans.supplier_id
21                          LEFT JOIN ".TB_PREF."payment_terms terms ON supp.payment_terms=terms.terms_indicator
22                          LEFT JOIN ".TB_PREF."tax_groups tg ON supp.tax_group_id=tg.id
23                 WHERE supp.supplier_id = ".db_escape($supplier_id)."
24                 GROUP BY
25                           supp.supp_name";
26
27         $result = db_query($sql, "The supplier details could not be retreived");
28         $myrow = db_fetch($result);
29
30         $order->credit = $myrow["cur_credit"];
31         $order->terms = array( 
32                 'description' => $myrow['terms'],
33                 'days_before_due' => $myrow['days_before_due'], 
34                 'day_in_following_month' => $myrow['day_in_following_month'] );
35
36         $_POST['supplier_id'] = $supplier_id;
37         $_POST['supplier_name'] = $myrow["supp_name"];
38         $_POST['curr_code'] = $myrow["curr_code"];
39         $_POST['dimension'] = $myrow["dimension_id"];
40         $_POST['dimension2'] = $myrow["dimension2_id"];
41
42         $order->set_supplier($supplier_id, $myrow["supp_name"], $myrow["curr_code"], 
43                 $myrow["tax_group_id"], $myrow["tax_included"], $myrow["tax_area"]);
44 }
45
46 //----------------------------------------------------------------------------------------
47
48 function delete_po($po)
49 {
50         global $Refs;
51
52         begin_transaction();
53         hook_db_prevoid($po, ST_PURCHORDER);
54         $sql = "DELETE FROM ".TB_PREF."purch_orders WHERE order_no=".db_escape($po);
55         db_query($sql, "The order header could not be deleted");
56
57         $sql = "DELETE FROM ".TB_PREF."purch_order_details WHERE order_no =".db_escape($po);
58         db_query($sql, "The order detail lines could not be deleted");
59
60         $Refs->restore_last(ST_PURCHORDER, $po);
61         commit_transaction();
62 }
63
64 //----------------------------------------------------------------------------------------
65
66 function add_po(&$po_obj)
67 {
68         global $Refs;
69
70         begin_transaction();
71         hook_db_prewrite($po_obj, ST_PURCHORDER);
72
73      /*Insert to purchase order header record */
74      $sql = "INSERT INTO ".TB_PREF."purch_orders (supplier_id, Comments, ord_date, reference, 
75         supp_reference, into_stock_location, delivery_address, total, tax_included, prep_amount) VALUES(";
76      $sql .= db_escape($po_obj->supplier_id) . "," .
77          db_escape($po_obj->Comments) . ",'" .
78          date2sql($po_obj->tran_date) . "', " .
79                  db_escape($po_obj->reference) . ", " .
80          db_escape($po_obj->supp_ref) . ", " .
81          db_escape($po_obj->Location) . ", " .
82          db_escape($po_obj->delivery_address) . ", " .
83          db_escape($po_obj->get_trans_total()). ", " .
84          db_escape($po_obj->tax_included). ", " .
85          db_escape($po_obj->prep_amount). ")";
86
87         db_query($sql, "The purchase order header record could not be inserted");
88
89      /*Get the auto increment value of the order number created from the sql above */
90      $po_obj->order_no = db_insert_id();
91
92      /*Insert the purchase order detail records */
93      foreach ($po_obj->line_items as $line_no => $po_line)
94      {
95                 $sql = "INSERT INTO ".TB_PREF."purch_order_details (order_no, item_code, description, delivery_date,    unit_price,     quantity_ordered) VALUES (";
96                 $sql .= $po_obj->order_no . ", " . db_escape($po_line->stock_id). "," .
97                 db_escape($po_line->item_description). ",'" .
98                 date2sql($po_line->req_del_date) . "'," .
99                 db_escape($po_line->price) . ", " .
100                 db_escape($po_line->quantity). ")";
101                 db_query($sql, "One of the purchase order detail records could not be inserted");
102                 $po_obj->line_items[$line_no]->po_item_id = db_insert_id();
103      }
104
105         $Refs->save(ST_PURCHORDER, $po_obj->order_no, $po_obj->reference);
106
107         add_audit_trail(ST_PURCHORDER, $po_obj->order_no, $po_obj->tran_date);
108         hook_db_postwrite($po_obj, ST_PURCHORDER);
109         commit_transaction();
110
111         return $po_obj->order_no;
112 }
113
114 //----------------------------------------------------------------------------------------
115
116 function update_po(&$po_obj)
117 {
118         begin_transaction();
119         hook_db_prewrite($po_obj, ST_PURCHORDER);
120
121     /*Update the purchase order header with any changes */
122     $sql = "UPDATE ".TB_PREF."purch_orders SET Comments=" . db_escape($po_obj->Comments) . ",
123                 supp_reference= ". db_escape( $po_obj->supp_ref). ",
124                 into_stock_location=" . db_escape($po_obj->Location). ",
125                 ord_date='" . date2sql($po_obj->tran_date) . "',
126                 delivery_address=" . db_escape($po_obj->delivery_address).",
127                 total=". db_escape($po_obj->get_trans_total()).",
128                 prep_amount=". db_escape($po_obj->prep_amount).",
129                 tax_included=". db_escape($po_obj->tax_included);
130     $sql .= " WHERE order_no = " . $po_obj->order_no;
131         db_query($sql, "The purchase order could not be updated");
132
133         $sql = "DELETE FROM ".TB_PREF."purch_order_details WHERE order_no="
134                 .db_escape($po_obj->order_no);
135         db_query($sql, "could not delete old purch order details");
136
137     /*Now Update the purchase order detail records */
138     foreach ($po_obj->line_items as $po_line)
139     {
140         $sql = "INSERT INTO ".TB_PREF."purch_order_details (po_detail_item, order_no, item_code, 
141                 description, delivery_date, unit_price, quantity_ordered, quantity_received) VALUES ("
142                         .db_escape($po_line->po_item_id ? $po_line->po_item_id : 0). ","
143                         .$po_obj->order_no . ","
144                         .db_escape($po_line->stock_id). ","
145                         .db_escape($po_line->item_description). ",'"
146                         .date2sql($po_line->req_del_date) . "',"
147                         .db_escape($po_line->price) . ", "
148                         .db_escape($po_line->quantity) . ", "
149                         .db_escape($po_line->qty_received) . ")";
150                 db_query($sql, "One of the purchase order detail records could not be updated");
151     }
152
153         reallocate_payments($po_obj->order_no, ST_PURCHORDER, $po_obj->tran_date, $po_obj->get_trans_total(), $po_obj->prepayments, $po_obj->supplier_id);
154
155         add_audit_trail($po_obj->trans_type, $po_obj->order_no, Today(), _("Updated."));
156         hook_db_postwrite($po_obj, ST_PURCHORDER);
157         commit_transaction();
158
159         return $po_obj->order_no;
160 }
161
162 //----------------------------------------------------------------------------------------
163
164 function read_po_header($order_no, &$order)
165 {
166         $sql = "SELECT po.*, tg.tax_area, supplier.*, loc.location_name 
167                 FROM ".TB_PREF."purch_orders po,"
168                         .TB_PREF."suppliers supplier
169                         LEFT JOIN ".TB_PREF."tax_groups tg ON supplier.tax_group_id=tg.id,"
170                         .TB_PREF."locations loc
171                 WHERE po.supplier_id = supplier.supplier_id
172                 AND loc.loc_code = into_stock_location
173                 AND po.order_no = ".db_escape($order_no);
174
175         $result = db_query($sql, "The order cannot be retrieved");
176
177         if (db_num_rows($result) == 1)
178         {
179
180         $myrow = db_fetch($result);
181
182         $order->trans_type = ST_PURCHORDER;
183         $order->order_no = $order_no;
184
185         $order->set_supplier($myrow["supplier_id"], $myrow["supp_name"], $myrow["curr_code"],
186                 $myrow['tax_group_id'], $myrow["tax_included"], $myrow["tax_area"]);
187
188                 $order->credit = get_current_supp_credit($order->supplier_id);
189
190         $order->tran_date = sql2date($myrow["ord_date"]);
191         $order->Comments = $myrow["comments"];
192         $order->Location = $myrow["into_stock_location"];
193         $order->supp_ref = $myrow["supp_reference"];
194         $order->reference = $myrow["reference"];
195         $order->delivery_address = $myrow["delivery_address"];
196         $order->alloc = $myrow["alloc"];
197         $order->prep_amount = $myrow["prep_amount"];
198         $order->prepayments = get_payments_for($order_no, ST_PURCHORDER, $myrow["supplier_id"]);
199
200         return true;
201         }
202
203         display_db_error("FATAL : duplicate purchase order found", "", true);
204         return false;
205 }
206
207 //----------------------------------------------------------------------------------------
208
209 function read_po_items($order_no, &$order, $open_items_only=false)
210 {
211         /*now populate the line po array with the purchase order details records */
212
213         $sql = "SELECT poline.*, units
214                 FROM ".TB_PREF."purch_order_details poline
215                         LEFT JOIN ".TB_PREF."stock_master item  ON poline.item_code=item.stock_id
216                 WHERE order_no =".db_escape($order_no)
217                         ." AND poline.quantity_ordered!=0";
218
219     if ($open_items_only)
220                 $sql .= " AND (poline.quantity_ordered > poline.quantity_received) ";
221
222         $sql .= " ORDER BY po_detail_item";
223
224         $result = db_query($sql, "The lines on the purchase order cannot be retrieved");
225
226     if (db_num_rows($result) > 0)
227     {
228                 while ($myrow = db_fetch($result))
229         {
230                 $data = get_purchase_data($order->supplier_id, $myrow['item_code']);
231                 if ($data !== false)
232                 {
233                         if ($data['supplier_description'] != "")
234                                 $myrow['description'] = $data['supplier_description'];
235                 }               
236
237                 $order->add_to_order($myrow["item_code"],
238                         $myrow["quantity_ordered"],$myrow["description"],
239                 $myrow["unit_price"], sql2date($myrow["delivery_date"]),
240                         $myrow["qty_invoiced"], $myrow["quantity_received"],
241                         $myrow["quantity_ordered"], 0, $myrow["po_detail_item"], $myrow["std_cost_unit"]);
242         } /* line po from purchase order details */
243     } //end of checks on returned data set
244 }
245
246 //----------------------------------------------------------------------------------------
247
248 function read_po($order_no, &$order, $open_items_only=false)
249 {
250         $result = read_po_header($order_no, $order);
251
252         if ($result)
253                 read_po_items($order_no, $order, $open_items_only);
254 }
255
256 //----------------------------------------------------------------------------------------
257
258 function get_po_items($order_no)
259 {
260         $sql = "SELECT item_code, quantity_ordered, quantity_received, qty_invoiced
261                 FROM ".TB_PREF."purch_order_details
262                 WHERE order_no=".db_escape($order_no)
263                 ." ORDER BY po_detail_item";
264
265         $result = db_query($sql, "could not query purch order details");
266     check_db_error("Could not check that the details of the purchase order had not been changed by another user ", $sql);
267     return $result;
268 }
269 //----------------------------------------------------------------------------------------
270
271 function get_short_info($stock_id)
272 {
273         $sql = "SELECT description, units, mb_flag
274                 FROM ".TB_PREF."stock_master WHERE stock_id = ".db_escape($stock_id);
275
276         return db_query($sql,"The stock details for " . $stock_id . " could not be retrieved");
277 }
278
279 function get_sql_for_po_search_completed($from, $to, $supplier_id=ALL_TEXT, $location=ALL_TEXT,
280         $order_number = '', $stock_id = '', $also_closed=false)
281 {
282         $sql = "SELECT 
283                 porder.order_no, 
284                 porder.reference, 
285                 supplier.supp_name, 
286                 location.location_name,
287                 porder.supp_reference, 
288                 porder.ord_date, 
289                 supplier.curr_code, 
290                 Sum(line.unit_price*line.quantity_ordered) AS OrderValue,
291                 Sum(line.delivery_date < '". date2sql(Today()) ."'
292                 AND (line.quantity_ordered > line.quantity_received)) As OverDue,
293                 porder.into_stock_location,
294                 chk.isopen
295                 FROM ".TB_PREF."purch_orders as porder
296                                 LEFT JOIN (
297                                         SELECT order_no, SUM(quantity_ordered-quantity_received + quantity_ordered-qty_invoiced) isopen
298                                         FROM ".TB_PREF."purch_order_details
299                                         GROUP BY order_no
300                                 ) chk ON chk.order_no=porder.order_no,"
301                         .TB_PREF."purch_order_details as line, "
302                         .TB_PREF."suppliers as supplier, "
303                         .TB_PREF."locations as location
304                 WHERE porder.order_no = line.order_no
305                 AND porder.supplier_id = supplier.supplier_id
306                 AND location.loc_code = porder.into_stock_location ";
307
308         if ($supplier_id != ALL_TEXT)
309                 $sql .= "AND supplier.supplier_id=".$supplier_id." ";
310         if ($order_number != "")
311         {
312                 $sql .= "AND porder.reference LIKE ".db_escape('%'. $order_number . '%');
313         }
314         else
315         {
316
317                 $data_after = date2sql($from);
318                 $date_before = date2sql($to);
319
320                 $sql .= " AND porder.ord_date >= '$data_after'";
321                 $sql .= " AND porder.ord_date <= '$date_before'";
322
323                 if ($location != ALL_TEXT)
324                 {
325                         $sql .= " AND porder.into_stock_location = ".db_escape($location);
326                 }
327                 if ($stock_id !== '')
328                 {
329                         $sql .= " AND line.item_code=".db_escape($stock_id);
330                 }
331                 if ($supplier_id != ALL_TEXT)
332                         $sql .= " AND supplier.supplier_id=".db_escape($supplier_id);
333
334         }
335
336         if (!$also_closed)
337                 $sql .= " AND isopen";
338         $sql .= " GROUP BY porder.order_no";
339         return $sql;
340 }
341
342 function get_sql_for_po_search($from, $to, $supplier_id=ALL_TEXT, $location=ALL_TEXT, $order_number='', $stock_id='')
343 {
344         $sql = "SELECT 
345                 porder.order_no, 
346                 porder.reference,
347                 supplier.supp_name, 
348                 location.location_name,
349                 porder.supp_reference, 
350                 porder.ord_date,
351                 supplier.curr_code,
352                 Sum(line.unit_price*line.quantity_ordered) AS OrderValue,
353                 Sum(line.delivery_date < '". date2sql(Today()) ."'
354                 AND (line.quantity_ordered > line.quantity_received)) As OverDue
355                 FROM ".TB_PREF."purch_orders as porder,"
356                         .TB_PREF."purch_order_details as line, "
357                         .TB_PREF."suppliers as supplier, "
358                         .TB_PREF."locations as location
359                 WHERE porder.order_no = line.order_no
360                 AND porder.supplier_id = supplier.supplier_id
361                 AND location.loc_code = porder.into_stock_location
362                 AND (line.quantity_ordered > line.quantity_received) ";
363
364         if ($order_number != "")
365         {
366                 $sql .= "AND porder.reference LIKE ".db_escape('%'. $order_number . '%');
367         }
368         else
369         {
370                 $data_after = date2sql($from);
371                 $data_before = date2sql($to);
372
373                 $sql .= "  AND porder.ord_date >= '$data_after'";
374                 $sql .= "  AND porder.ord_date <= '$data_before'";
375
376                 if ($location != ALL_TEXT)
377                 {
378                         $sql .= " AND porder.into_stock_location = ".db_escape($location);
379                 }
380
381                 if ($stock_id != '')
382                 {
383                         $sql .= " AND line.item_code=".db_escape($stock_id);
384                 }
385                 if ($supplier_id != ALL_TEXT)
386                         $sql .= " AND supplier.supplier_id=".db_escape($supplier_id);
387         } //end not order number selected
388
389         $sql .= " GROUP BY porder.order_no";
390         return $sql;
391 }
392