Customer Payments, Payments to Supplier: improved readbility and multiply cleanups...
[fa-stable.git] / sales / includes / db / custalloc_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 add_cust_allocation($amount, $trans_type_from, $trans_no_from,
15         $trans_type_to, $trans_no_to)
16 {
17         $sql = "INSERT INTO ".TB_PREF."cust_allocations (
18                 amt, date_alloc,
19                 trans_type_from, trans_no_from, trans_no_to, trans_type_to)
20                 VALUES ($amount, Now(), ".db_escape($trans_type_from).", ".db_escape($trans_no_from).", ".db_escape($trans_no_to)
21                 .", ".db_escape($trans_type_to).")";
22
23         db_query($sql, "A customer allocation could not be added to the database");
24 }
25
26 //----------------------------------------------------------------------------------------
27
28
29 function delete_cust_allocation($trans_id)
30 {
31         $sql = "DELETE FROM ".TB_PREF."cust_allocations WHERE id = ".db_escape($trans_id);
32         return db_query($sql, "The existing allocation $trans_id could not be deleted");
33 }
34
35 //----------------------------------------------------------------------------------------
36 //      Update debtor trans alloc field according to current status of cust_allocations
37 //
38 function update_debtor_trans_allocation($trans_type, $trans_no)
39 {
40         $sql = "UPDATE `".TB_PREF."debtor_trans` trans,
41                         (SELECT sum(amt) amt from ".TB_PREF."cust_allocations
42                                 WHERE (trans_type_to=".db_escape($trans_type)." AND trans_no_to=".db_escape($trans_no).")
43                                 OR (trans_type_from=".db_escape($trans_type)." AND trans_no_from=".db_escape($trans_no).")) allocated
44                 SET 
45                         trans.alloc=IFNULL(allocated.amt,0)
46                 WHERE trans.type=".db_escape($trans_type)." AND trans_no=".db_escape($trans_no);
47
48         db_query($sql, "The debtor transaction record could not be modified for the allocation against it");
49 }
50
51 //-------------------------------------------------------------------------------------------------------------
52
53 function void_cust_allocations($type, $type_no, $date="")
54 {
55         return clear_cust_alloctions($type, $type_no, $date);
56 }
57
58 //-------------------------------------------------------------------------------------------------------------
59
60 function clear_cust_alloctions($type, $type_no, $date="")
61 {
62         // clear any allocations for this transaction
63         $sql = "SELECT * FROM ".TB_PREF."cust_allocations
64                 WHERE (trans_type_from=".db_escape($type)." AND trans_no_from=".db_escape($type_no).")
65                 OR (trans_type_to=".db_escape($type)." AND trans_no_to=".db_escape($type_no).")";
66         $result = db_query($sql, "could not void debtor transactions for type=$type and trans_no=$type_no");
67
68         while ($row = db_fetch($result))
69         {
70                 $sql = "UPDATE ".TB_PREF."debtor_trans SET alloc=alloc - " . $row['amt'] . "
71                         WHERE (type= " . $row['trans_type_from'] . " AND trans_no=" . $row['trans_no_from'] . ")
72                         OR (type=" . $row['trans_type_to'] . " AND trans_no=" . $row['trans_no_to'] . ")";
73                 db_query($sql, "could not clear allocation");
74                 // 2008-09-20 Joe Hunt
75                 if ($date != "")
76                         exchange_variation($type, $type_no, $row['trans_type_to'], $row['trans_no_to'], $date,
77                                 $row['amt'], PT_CUSTOMER, true);
78                 //////////////////////
79         }
80
81
82         // remove any allocations for this transaction
83         $sql = "DELETE FROM ".TB_PREF."cust_allocations
84                 WHERE (trans_type_from=".db_escape($type)." AND trans_no_from=".db_escape($type_no).")
85                 OR (trans_type_to=".db_escape($type)." AND trans_no_to=".db_escape($type_no).")";
86
87         db_query($sql, "could not void debtor transactions for type=$type and trans_no=$type_no");
88 }
89 //----------------------------------------------------------------------------------------
90
91 function get_alloc_trans_sql($extra_fields=null, $extra_conditions=null, $extra_tables=null)
92 {
93         $sql = "SELECT
94                 trans.type,
95                 trans.trans_no,
96                 trans.reference,
97                 trans.tran_date,
98                 debtor.name AS DebtorName, 
99                 debtor.curr_code, 
100                 ov_amount+ov_gst+ov_freight+ov_freight_tax+ov_discount AS Total,
101                 trans.alloc,
102                 trans.due_date,
103                 debtor.address,
104                 trans.version,
105                 trans.debtor_no ";
106
107         if ($extra_fields)
108                 $sql .= ", $extra_fields ";
109
110         $sql .= " FROM ".TB_PREF."debtor_trans as trans, "
111                                 .TB_PREF."debtors_master as debtor";
112         if ($extra_tables)
113                 $sql .= ",$extra_tables ";
114
115         $sql .= " WHERE trans.debtor_no=debtor.debtor_no";
116
117         if ($extra_conditions)
118                 $sql .= " AND $extra_conditions ";
119
120         return $sql;
121 }
122
123
124 //-------------------------------------------------------------------------------------------------------------
125
126 function get_allocatable_from_cust_sql($customer_id, $settled)
127 {
128         $settled_sql = "";
129         if (!$settled)
130         {
131                 $settled_sql = " AND (round(ov_amount+ov_gst+ov_freight+ov_freight_tax-ov_discount-alloc,6) > 0)";
132         }
133         $cust_sql = "";
134         if ($customer_id != null)
135                 $cust_sql = " AND trans.debtor_no = ".db_escape($customer_id);
136
137         $sql = get_alloc_trans_sql("round(ov_amount+ov_gst+ov_freight+ov_freight_tax+ov_discount-alloc,6) <= 0 AS settled",
138                 "(type=".ST_CUSTPAYMENT." OR type=".ST_CUSTCREDIT." OR type=".ST_BANKDEPOSIT.") AND (trans.ov_amount > 0) " . $settled_sql . $cust_sql);
139
140         return $sql;
141 }
142
143 //-------------------------------------------------------------------------------------------------------------
144
145 function get_allocatable_to_cust_transactions($customer_id, $trans_no=null, $type=null)
146 {
147         if ($trans_no != null and $type != null)
148         {
149                 $sql = get_alloc_trans_sql("amt", "trans.trans_no = alloc.trans_no_to
150                         AND trans.type = alloc.trans_type_to
151                         AND alloc.trans_no_from=".db_escape($trans_no)."
152                         AND alloc.trans_type_from=".db_escape($type)."
153                         AND trans.debtor_no=".db_escape($customer_id),
154                         "".TB_PREF."cust_allocations as alloc");
155         }
156         else
157         {
158                 $sql = get_alloc_trans_sql(null, "round(ov_amount+ov_gst+ov_freight+ov_freight_tax+ov_discount-alloc,6) > 0
159                         AND trans.type <> " . ST_CUSTPAYMENT . "
160                         AND trans.type <> " . ST_BANKDEPOSIT . "
161                         AND trans.type <> " . ST_CUSTCREDIT . "
162                         AND trans.type <> " . ST_CUSTDELIVERY . "
163                         AND trans.debtor_no=".db_escape($customer_id));
164         }
165
166         return db_query($sql." ORDER BY trans_no", "Cannot retreive alloc to transactions");
167 }
168
169 //-------------------------------------------------------------------------------------------------------------
170
171 function get_allocatable_from_cust_transactions($customer_id, $trans_no=null, $type=null)
172 {
173         if ($trans_no != null and $type != null)
174         {
175                 $sql = get_alloc_trans_sql("amt", "trans.trans_no = alloc.trans_no_from
176                         AND trans.type = alloc.trans_type_from
177                         AND alloc.trans_no_to=".db_escape($trans_no)."
178                         AND alloc.trans_type_to=".db_escape($type)."
179                         AND trans.debtor_no=".db_escape($customer_id),
180                         "".TB_PREF."cust_allocations as alloc");
181         }
182         else
183         {
184                 $sql = get_alloc_trans_sql(null, "round(ov_amount+ov_gst+ov_freight+ov_freight_tax+ov_discount-alloc,6) > 0
185                         AND trans.type <> " . ST_CUSTPAYMENT . "
186                         AND trans.type <> " . ST_BANKDEPOSIT . "
187                         AND trans.type <> " . ST_CUSTCREDIT . "
188                         AND trans.type <> " . ST_CUSTDELIVERY . "
189                         AND trans.debtor_no=".db_escape($customer_id));
190         }
191
192         return db_query($sql." ORDER BY trans_no", "Cannot retreive alloc to transactions");
193 }
194
195 function get_sql_for_customer_allocation_inquiry($from, $to, $customer, $filterType, $settled)
196 {
197         $data_after = date2sql($from);
198         $date_to = date2sql($to);
199
200         $sql = "SELECT 
201                 trans.type,
202                 trans.trans_no,
203                 trans.reference,
204                 trans.order_,
205                 trans.tran_date,
206                 trans.due_date,
207                 debtor.name,
208                 debtor.curr_code,
209         (trans.ov_amount + trans.ov_gst + trans.ov_freight 
210                         + trans.ov_freight_tax + trans.ov_discount)     AS TotalAmount,
211                 trans.alloc AS Allocated,
212                 ((trans.type = ".ST_SALESINVOICE.")
213                         AND trans.due_date < '" . date2sql(Today()) . "') AS OverDue,
214                 trans.debtor_no
215         FROM "
216                         .TB_PREF."debtor_trans as trans, "
217                         .TB_PREF."debtors_master as debtor
218         WHERE debtor.debtor_no = trans.debtor_no
219                         AND (trans.ov_amount + trans.ov_gst + trans.ov_freight 
220                                 + trans.ov_freight_tax + trans.ov_discount != 0)
221                 AND trans.tran_date >= '$data_after'
222                 AND trans.tran_date <= '$date_to'";
223
224         if ($customer != ALL_TEXT)
225                 $sql .= " AND trans.debtor_no = ".db_escape($customer);
226
227         if (isset($filterType) && $filterType != ALL_TEXT)
228         {
229                 if ($filterType == '1' || $filterType == '2')
230                 {
231                         $sql .= " AND trans.type = ".ST_SALESINVOICE." ";
232                 }
233                 elseif ($filterType == '3')
234                 {
235                         $sql .= " AND trans.type = " . ST_CUSTPAYMENT;
236                 }
237                 elseif ($filterType == '4')
238                 {
239                         $sql .= " AND trans.type = ".ST_CUSTCREDIT." ";
240                 }
241
242         if ($filterType == '2')
243         {
244                 $today =  date2sql(Today());
245                 $sql .= " AND trans.due_date < '$today'
246                                 AND (round(abs(trans.ov_amount + "
247                                 ."trans.ov_gst + trans.ov_freight + "
248                                 ."trans.ov_freight_tax + trans.ov_discount) - trans.alloc,6) > 0) ";
249         }
250         }
251         else
252         {
253             $sql .= " AND trans.type <> ".ST_CUSTDELIVERY." ";
254         }
255
256
257         if (!$settled)
258         {
259                 $sql .= " AND (round(abs(trans.ov_amount + trans.ov_gst + "
260                 ."trans.ov_freight + trans.ov_freight_tax + "
261                 ."trans.ov_discount) - trans.alloc,6) != 0) ";
262         }
263
264         return $sql;
265 }
266
267 function credit_sales_invoice_allocate($invoice_no, $credit_no, $amount, $date)
268 {
269
270         $sql = "SELECT ov_freight+ov_gst+ov_amount+ov_freight_tax as total, alloc FROM ".TB_PREF."debtor_trans
271                 WHERE (`type`=".ST_SALESINVOICE." AND trans_no=".db_escape($invoice_no).")";
272         $result = db_query($sql, "can't retrieve invoice totals");
273         $invoice = db_fetch($result);
274         $free = $invoice['total'] - $invoice['alloc'];
275         
276         if ($free < $amount) {
277          // if there is not enough unallocated amount - remove some payment allocations
278                 $sql = "SELECT * FROM ".TB_PREF."cust_allocations
279                         WHERE (trans_type_to=".ST_SALESINVOICE." AND trans_no_to=".db_escape($invoice_no).")
280                         AND trans_type_from <> ".ST_CUSTCREDIT;
281                 $result = db_query($sql, "can't retrieve invoice allocations");
282
283                 while(($free < $amount) && ($alloc = db_fetch($result))) {
284                         $unalloc = min($alloc['amt'], $amount-$free);
285                         update_debtor_trans_allocation($alloc['trans_type_to'], $alloc['trans_no_to'], 
286                                 -$unalloc);
287                         update_debtor_trans_allocation($alloc['trans_type_from'], $alloc['trans_no_from'], 
288                                 -$unalloc);
289
290                         delete_cust_allocation($alloc['id']);
291                         if ($unalloc < $alloc['amt'])
292                                 add_cust_allocation($alloc['amt']-$unalloc, $alloc['trans_type_from'],
293                                         $alloc['trans_no_from'], ST_SALESINVOICE, $invoice_no);
294
295                         $free += $unalloc;
296                 }
297         }
298         if (floatcmp($free, $amount)<0) {
299                 // this should never happen unless sparse credit notices were allocated to 
300                 // the invoice, or summarized freight costs on credit notes is more than those on invoice.
301                 display_error(_("Unsuspected overallocation happened due to sparse credit notes exists for this invoice.
302  Check all credit notes allocated to this invoice for summarized freight charges."));
303                 return false;
304         }
305         update_debtor_trans_allocation(ST_SALESINVOICE, $invoice_no, $amount);
306         update_debtor_trans_allocation(ST_CUSTCREDIT, $credit_no, $amount);
307         add_cust_allocation($amount, ST_CUSTCREDIT, $credit_no, ST_SALESINVOICE, $invoice_no);
308
309         exchange_variation(ST_CUSTCREDIT, $credit_no, ST_SALESINVOICE, $invoice_no, $date,
310                 $amount, PT_CUSTOMER);
311         return true;
312 }
313
314 ?>