[0005223] Fixed Asset Purchase, Direct Supplier Invoice: fixed invalid cost handling...
[fa-stable.git] / purchasing / includes / purchasing_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 include_once($path_to_root . "/purchasing/includes/supp_trans_class.inc");
13
14 include_once($path_to_root . "/includes/banking.inc");
15 include_once($path_to_root . "/includes/inventory.inc");
16
17 include_once($path_to_root . "/includes/date_functions.inc");
18
19 include_once($path_to_root . "/includes/db/allocations_db.inc");
20
21 include_once($path_to_root . "/purchasing/includes/db/supp_trans_db.inc");
22 include_once($path_to_root . "/purchasing/includes/db/po_db.inc");
23 include_once($path_to_root . "/purchasing/includes/db/grn_db.inc");
24 include_once($path_to_root . "/purchasing/includes/db/invoice_db.inc");
25 include_once($path_to_root . "/purchasing/includes/db/suppalloc_db.inc");
26 include_once($path_to_root . "/purchasing/includes/db/supp_payment_db.inc");
27 include_once($path_to_root . "/purchasing/includes/db/suppliers_db.inc");
28
29 //-------------------------------------------------------------------------------------------------------------
30
31 // add a supplier-related gl transaction
32 // $date_ is display date (non-sql)
33 // $amount is in SUPPLIERS'S currency
34
35 function add_gl_trans_supplier($type, $type_no, $date_, $account, $dimension, $dimension2,  
36         $amount, $supplier_id, $err_msg="", $rate=0, $memo="")
37 {
38         if ($err_msg == "")
39                 $err_msg = "The supplier GL transaction could not be inserted"; 
40                 
41         return add_gl_trans($type, $type_no, $date_, $account, $dimension, $dimension2, $memo, 
42                 $amount, get_supplier_currency($supplier_id), 
43                 PT_SUPPLIER, $supplier_id, $err_msg, $rate);
44 }
45
46 //----------------------------------------------------------------------------------------
47
48 function get_purchase_price($supplier_id, $stock_id)
49 {
50         $sql = "SELECT price, conversion_factor FROM ".TB_PREF."purch_data 
51                 WHERE supplier_id = ".db_escape($supplier_id) . " 
52                 AND stock_id = ".db_escape($stock_id);
53         $result = db_query($sql, "The supplier pricing details for " . $stock_id . " could not be retrieved");    
54
55         if (db_num_rows($result) == 1)
56         {
57                 $myrow = db_fetch($result);
58                 return $myrow["price"] / $myrow['conversion_factor'];
59         } 
60         else 
61         {
62                 return 0;
63         }       
64 }
65
66 function get_purchase_conversion_factor($supplier_id, $stock_id)
67 {
68         $sql = "SELECT conversion_factor FROM ".TB_PREF."purch_data 
69                 WHERE supplier_id = ".db_escape($supplier_id)." 
70                 AND stock_id = ".db_escape($stock_id);
71         $result = db_query($sql, "The supplier pricing details for " . $stock_id . " could not be retrieved");    
72
73         if (db_num_rows($result) == 1)
74         {
75                 $myrow = db_fetch($result);
76                 return $myrow['conversion_factor'];
77         } 
78         else 
79         {
80                 return 1;
81         }       
82 }
83 //----------------------------------------------------------------------------------------
84
85 function get_purchase_data($supplier_id, $stock_id)
86 {
87         $sql = "SELECT * FROM ".TB_PREF."purch_data 
88                 WHERE supplier_id = ".db_escape($supplier_id) . "
89                 AND stock_id = ".db_escape($stock_id);
90         $result = db_query($sql, "The supplier pricing details for " . $stock_id . " could not be retrieved");    
91
92         return db_fetch($result);
93 }
94
95 function add_or_update_purchase_data($supplier_id, $stock_id, $price, $description="", $uom="")
96 {
97         $data = get_purchase_data($supplier_id, $stock_id);
98
99         $description = substr($description, 0, 50); // FIXME: temporary constraint to avoid db errors on long descriptions, see [0005170]
100         if ($data === false)
101         {
102                 $sql = "INSERT INTO ".TB_PREF."purch_data (supplier_id, stock_id, price, suppliers_uom,
103                         conversion_factor, supplier_description) VALUES (".db_escape($supplier_id)
104                         .", ".db_escape($stock_id).", ".db_escape($price).", "
105                         .db_escape($uom).", 1, ".db_escape($description).")";
106                 db_query($sql,"The supplier purchasing details could not be added");
107                 return;
108         }       
109         $price = round($price * $data['conversion_factor'], user_price_dec());
110         $sql = "UPDATE ".TB_PREF."purch_data SET price=".db_escape($price);
111         if ($uom != "")
112                 $sql .= ",suppliers_uom=".db_escape($uom);
113         if ($description != "") 
114                 $sql .= ",supplier_description=".db_escape($description);
115         $sql .= " WHERE stock_id=".db_escape($stock_id)." AND supplier_id=".db_escape($supplier_id);
116         db_query($sql,"The supplier purchasing details could not be updated");
117         return true;
118 }
119
120 function get_po_prepayments($supp_trans)
121 {
122         // collect purchase order line ids
123         $allocations = array();
124         $line_ids = array();
125         foreach($supp_trans->grn_items as $item)
126                 if ($item->po_detail_item)
127                         $line_ids[] = $item->po_detail_item;
128
129         if (!count($line_ids))
130                 return $allocations;
131
132         $sql = "SELECT DISTINCT allocs.*
133                 FROM ".TB_PREF."supp_allocations allocs 
134                         LEFT JOIN ".TB_PREF."purch_order_details line ON line.order_no=allocs.trans_no_to AND trans_type_to=".ST_PURCHORDER."
135                 WHERE line.po_detail_item IN(".implode(',', array_values($line_ids)).")";
136
137         $result = db_query($sql, "Cannot retrieve po prepayments");
138
139         while($dat = db_fetch($result))
140         {
141                 $allocations[] = $dat;
142         }
143
144         return $allocations;
145 }
146
147 //---------------------------------------------------------------------------------------------------
148 //
149 //      Add Purchase Order, GRN or Purchase Invoice with parent auto documents (if any)
150 //
151 function add_direct_supp_trans($cart)
152 {
153         global $Refs, $type_shortcuts;
154
155         if ($cart->trans_type != ST_PURCHORDER) {
156                 // for direct grn/invoice set same dates for lines as for whole document
157                 foreach ($cart->line_items as $line_no =>$line)
158                         $cart->line_items[$line_no]->req_del_date = $cart->orig_order_date;
159         }
160
161         $ref = $cart->reference;
162         if ($cart->trans_type != ST_PURCHORDER) {
163                 $cart->reference = 'auto';
164                 begin_transaction();    // all db changes as single transaction for direct document
165         }
166         $order_no = add_po($cart);
167         $cart->order_no = $order_no;
168
169         if ($cart->trans_type == ST_PURCHORDER)
170                 return $order_no;
171
172         //Direct GRN
173         if ($cart->trans_type == ST_SUPPRECEIVE)
174                 $cart->reference = $ref;
175         if ($cart->trans_type != ST_SUPPINVOICE)
176                 $cart->Comments = $cart->reference; //grn does not hold supp_ref
177         foreach($cart->line_items as $key => $line)
178                 $cart->line_items[$key]->receive_qty = $line->quantity;
179         $grn_no = add_grn($cart);
180         if ($cart->trans_type == ST_SUPPRECEIVE) {
181                 commit_transaction(); // save PO+GRN
182                 return $grn_no;
183         }
184         //      Direct Purchase Invoice
185         $inv = new supp_trans(ST_SUPPINVOICE);
186         $inv->Comments = $cart->Comments;
187         $inv->supplier_id = $cart->supplier_id;
188         $inv->tran_date = $cart->orig_order_date;
189         $inv->due_date = $cart->due_date;
190         $inv->dimension = $cart->dimension;
191         $inv->dimension2 = $cart->dimension2;
192         $inv->reference = $ref;
193         $inv->supp_reference = $cart->supp_ref;
194         $inv->tax_included = $cart->tax_included;
195         $supp = get_supplier($cart->supplier_id);
196         $inv->tax_group_id = $supp['tax_group_id'];
197         $inv->ov_amount = $inv->ov_gst = $inv->ov_discount = 0;
198         $total = 0;
199                 foreach($cart->line_items as $key => $line) {
200                 $inv->add_grn_to_trans($line->grn_item_id, $line->po_detail_rec, $line->stock_id,
201                         $line->item_description, $line->receive_qty, 0, $line->receive_qty,
202                         $line->price, $line->price, true, get_unit_cost($line->stock_id), '');
203                 $total += round2(($line->receive_qty * $line->price), user_price_dec());
204         }
205         $inv->tax_overrides = $cart->tax_overrides;
206         if (!$inv->tax_included) {
207                 $taxes = $inv->get_taxes($inv->tax_group_id, 0, false);
208                 foreach( $taxes as $taxitem) {
209                         $total += isset($taxitem['Override']) ? $taxitem['Override'] : $taxitem['Value'];
210                 }
211         }
212         $inv->currency = $cart->curr_code;
213         $inv->ex_rate = $cart->ex_rate;
214
215         $inv_no = add_supp_invoice($inv);
216
217         if ($cart->cash_account) {
218                 $pmt_no = write_supp_payment(0, $inv->supplier_id, $cart->cash_account, $inv->tran_date, $Refs->get_next(ST_SUPPAYMENT, null, $inv->tran_date), 
219                         $total, 0, _('Payment for:').$inv->supp_reference .' ('.$type_shortcuts[ST_SUPPINVOICE].$inv_no.')' . ' ' . $cart->Comments, $cart->dimension, $cart->dimension2);
220                 add_supp_allocation($total, ST_SUPPAYMENT, $pmt_no, ST_SUPPINVOICE, $inv_no, $inv->supplier_id, $inv->tran_date);
221                 update_supp_trans_allocation(ST_SUPPINVOICE, $inv_no, $inv->supplier_id);
222                 update_supp_trans_allocation(ST_SUPPAYMENT, $pmt_no, $inv->supplier_id);
223         }
224         commit_transaction(); // save PO+GRN+PI(+SP)
225         return $inv_no;
226 }
227