Switch to new access levels system
[fa-stable.git] / purchasing / supplier_invoice.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_SUPPLIERINVOICE';
13 $path_to_root = "..";
14
15 include_once($path_to_root . "/purchasing/includes/purchasing_db.inc");
16
17 include_once($path_to_root . "/includes/session.inc");
18
19 include_once($path_to_root . "/includes/banking.inc");
20 include_once($path_to_root . "/includes/data_checks.inc");
21
22 include_once($path_to_root . "/purchasing/includes/purchasing_ui.inc");
23 $js = "";
24 if ($use_popup_windows)
25         $js .= get_js_open_window(900, 500);
26 if ($use_date_picker)
27         $js .= get_js_date_picker();
28 page(_("Enter Supplier Invoice"), false, false, "", $js);
29
30 //----------------------------------------------------------------------------------------
31
32 check_db_has_suppliers(_("There are no suppliers defined in the system."));
33
34 //---------------------------------------------------------------------------------------------------------------
35
36 if (isset($_GET['AddedID'])) 
37 {
38         $invoice_no = $_GET['AddedID'];
39         $trans_type = 20;
40
41
42     echo "<center>";
43     display_notification_centered(_("Supplier invoice has been processed."));
44     display_note(get_trans_view_str($trans_type, $invoice_no, _("View this Invoice")));
45
46         display_note(get_gl_view_str($trans_type, $invoice_no, _("View the GL Journal Entries for this Invoice")), 1);
47
48         hyperlink_no_params("$path_to_root/purchasing/supplier_payment.php", _("Entry supplier &payment for this invoice"));
49
50         hyperlink_params($_SERVER['PHP_SELF'], _("Enter Another Invoice"), "New=1");
51
52         hyperlink_params("$path_to_root/admin/attachments.php", _("Add an Attachment"), "filterType=$trans_type&trans_no=$invoice_no");
53         
54         display_footer_exit();
55 }
56
57 //--------------------------------------------------------------------------------------------------
58
59 if (isset($_GET['New']))
60 {
61         if (isset( $_SESSION['supp_trans']))
62         {
63                 unset ($_SESSION['supp_trans']->grn_items);
64                 unset ($_SESSION['supp_trans']->gl_codes);
65                 unset ($_SESSION['supp_trans']);
66         }
67
68         //session_register("SuppInv");
69         session_register("supp_trans");
70         $_SESSION['supp_trans'] = new supp_trans;
71         $_SESSION['supp_trans']->is_invoice = true;
72 }
73
74 //--------------------------------------------------------------------------------------------------
75 function clear_fields()
76 {
77         global $Ajax;
78         
79         unset($_POST['gl_code']);
80         unset($_POST['dimension_id']);
81         unset($_POST['dimension2_id']);
82         unset($_POST['amount']);
83         unset($_POST['memo_']);
84         unset($_POST['AddGLCodeToTrans']);
85         $Ajax->activate('gl_items');
86         set_focus('gl_code');
87 }
88 //------------------------------------------------------------------------------------------------
89 //      GL postings are often entered in the same form to two accounts
90 //  so fileds are cleared only on user demand.
91 //
92 if (isset($_POST['ClearFields']))
93 {
94         clear_fields();
95 }
96
97 if (isset($_POST['AddGLCodeToTrans'])){
98
99         $Ajax->activate('gl_items');
100         $input_error = false;
101
102         $sql = "SELECT account_code, account_name FROM ".TB_PREF."chart_master WHERE account_code='" . $_POST['gl_code'] . "'";
103         $result = db_query($sql,"get account information");
104         if (db_num_rows($result) == 0)
105         {
106                 display_error(_("The account code entered is not a valid code, this line cannot be added to the transaction."));
107                 set_focus('gl_code');
108                 $input_error = true;
109         }
110         else
111         {
112                 $myrow = db_fetch_row($result);
113                 $gl_act_name = $myrow[1];
114                 if (!check_num('amount'))
115                 {
116                         display_error(_("The amount entered is not numeric. This line cannot be added to the transaction."));
117                         set_focus('amount');
118                         $input_error = true;
119                 }
120         }
121
122         if (!is_tax_gl_unique(get_post('gl_code'))) {
123                 display_error(_("Cannot post to GL account used by more than one tax type."));
124                 set_focus('gl_code');
125                 $input_error = true;
126         }
127
128         if ($input_error == false)
129         {
130                 $_SESSION['supp_trans']->add_gl_codes_to_trans($_POST['gl_code'], $gl_act_name,
131                         $_POST['dimension_id'], $_POST['dimension2_id'], 
132                         input_num('amount'), $_POST['memo_']);
133                 set_focus('gl_code');
134         }
135 }
136
137 //------------------------------------------------------------------------------------------------
138
139 function check_data()
140 {
141         If (!$_SESSION['supp_trans']->is_valid_trans_to_post())
142         {
143                 display_error(_("The invoice cannot be processed because the there are no items or values on the invoice.  Invoices are expected to have a charge."));
144                 return false;
145         }
146
147         if (!references::is_valid($_SESSION['supp_trans']->reference)) 
148         {
149                 display_error(_("You must enter an invoice reference."));
150                 set_focus('reference');
151                 return false;
152         }
153
154         if (!is_new_reference($_SESSION['supp_trans']->reference, 20)) 
155         {
156                 display_error(_("The entered reference is already in use."));
157                 set_focus('reference');
158                 return false;
159         }
160
161         if (!references::is_valid($_SESSION['supp_trans']->supp_reference)) 
162         {
163                 display_error(_("You must enter a supplier's invoice reference."));
164                 set_focus('supp_reference');
165                 return false;
166         }
167
168         if (!is_date( $_SESSION['supp_trans']->tran_date))
169         {
170                 display_error(_("The invoice as entered cannot be processed because the invoice date is in an incorrect format."));
171                 set_focus('trans_date');
172                 return false;
173         } 
174         elseif (!is_date_in_fiscalyear($_SESSION['supp_trans']->tran_date)) 
175         {
176                 display_error(_("The entered date is not in fiscal year."));
177                 set_focus('trans_date');
178                 return false;
179         }
180         if (!is_date( $_SESSION['supp_trans']->due_date))
181         {
182                 display_error(_("The invoice as entered cannot be processed because the due date is in an incorrect format."));
183                 set_focus('due_date');
184                 return false;
185         }
186
187         $sql = "SELECT Count(*) FROM ".TB_PREF."supp_trans WHERE supplier_id='" 
188                 . $_SESSION['supp_trans']->supplier_id . "' AND supp_reference='" 
189                 . $_POST['supp_reference'] 
190                 . "' AND ov_amount!=0"; // ignore voided invoice references
191
192         $result=db_query($sql,"The sql to check for the previous entry of the same invoice failed");
193
194         $myrow = db_fetch_row($result);
195         if ($myrow[0] == 1)
196         {       /*Transaction reference already entered */
197                 display_error(_("This invoice number has already been entered. It cannot be entered again." . " (" . $_POST['supp_reference'] . ")"));
198                 return false;
199         }
200
201         return true;
202 }
203
204 //--------------------------------------------------------------------------------------------------
205
206 function handle_commit_invoice()
207 {
208         copy_to_trans($_SESSION['supp_trans']);
209
210         if (!check_data())
211                 return;
212
213         $invoice_no = add_supp_invoice($_SESSION['supp_trans']);
214
215     $_SESSION['supp_trans']->clear_items();
216     unset($_SESSION['supp_trans']);
217
218         meta_forward($_SERVER['PHP_SELF'], "AddedID=$invoice_no");
219 }
220
221 //--------------------------------------------------------------------------------------------------
222
223 if (isset($_POST['PostInvoice']))
224 {
225         handle_commit_invoice();
226 }
227
228 function check_item_data($n)
229 {
230         global $check_price_charged_vs_order_price,
231                 $check_qty_charged_vs_del_qty;
232         if (!check_num('this_quantity_inv'.$n, 0) || input_num('this_quantity_inv'.$n)==0)
233         {
234                 display_error( _("The quantity to invoice must be numeric and greater than zero."));
235                 set_focus('this_quantity_inv'.$n);
236                 return false;
237         }
238
239         if (!check_num('ChgPrice'.$n))
240         {
241                 display_error( _("The price is not numeric."));
242                 set_focus('ChgPrice'.$n);
243                 return false;
244         }
245
246         if ($check_price_charged_vs_order_price == True)
247         {
248                 if ($_POST['order_price'.$n]!=input_num('ChgPrice'.$n)) {
249                      if ($_POST['order_price'.$n]==0 ||
250                                 input_num('ChgPrice'.$n)/$_POST['order_price'.$n] >
251                             (1 + (sys_prefs::over_charge_allowance() / 100)))
252                     {
253                         display_error(_("The price being invoiced is more than the purchase order price by more than the allowed over-charge percentage. The system is set up to prohibit this. See the system administrator to modify the set up parameters if necessary.") .
254                         _("The over-charge percentage allowance is :") . sys_prefs::over_charge_allowance() . "%");
255                         set_focus('ChgPrice'.$n);
256                         return false;
257                     }
258                 }
259         }
260
261         if ($check_qty_charged_vs_del_qty == True)
262         {
263                 if (input_num('this_quantity_inv'.$n) / ($_POST['qty_recd'.$n] - $_POST['prev_quantity_inv'.$n]) >
264                         (1+ (sys_prefs::over_charge_allowance() / 100)))
265                 {
266                         display_error( _("The quantity being invoiced is more than the outstanding quantity by more than the allowed over-charge percentage. The system is set up to prohibit this. See the system administrator to modify the set up parameters if necessary.")
267                         . _("The over-charge percentage allowance is :") . sys_prefs::over_charge_allowance() . "%");
268                         set_focus('this_quantity_inv'.$n);
269                         return false;
270                 }
271         }
272
273         return true;
274 }
275
276 function commit_item_data($n)
277 {
278         if (check_item_data($n))
279         {
280         if (input_num('this_quantity_inv'.$n) >= ($_POST['qty_recd'.$n] - $_POST['prev_quantity_inv'.$n]))
281         {
282                 $complete = true;
283         }
284         else
285         {
286                 $complete = false;
287         }
288
289                 $_SESSION['supp_trans']->add_grn_to_trans($n, $_POST['po_detail_item'.$n],
290                         $_POST['item_code'.$n], $_POST['item_description'.$n], $_POST['qty_recd'.$n],
291                         $_POST['prev_quantity_inv'.$n], input_num('this_quantity_inv'.$n),
292                         $_POST['order_price'.$n], input_num('ChgPrice'.$n), $complete,
293                         $_POST['std_cost_unit'.$n], "");
294         }
295 }
296
297 //-----------------------------------------------------------------------------------------
298
299 $id = find_submit('grn_item_id');
300 if ($id != -1)
301 {
302         commit_item_data($id);
303 }
304
305 if (isset($_POST['InvGRNAll']))
306 {
307         foreach($_POST as $postkey=>$postval )
308     {
309                 if (strpos($postkey, "qty_recd") === 0)
310                 {
311                         $id = substr($postkey, strlen("qty_recd"));
312                         $id = (int)$id;
313                         commit_item_data($id);
314                 }
315     }
316 }       
317
318 //--------------------------------------------------------------------------------------------------
319 $id3 = find_submit('Delete');
320 if ($id3 != -1)
321 {
322         $_SESSION['supp_trans']->remove_grn_from_trans($id3);
323         $Ajax->activate('grn_items');
324         $Ajax->activate('inv_tot');
325 }
326
327 $id4 = find_submit('Delete2');
328 if ($id4 != -1)
329 {
330         $_SESSION['supp_trans']->remove_gl_codes_from_trans($id4);
331         clear_fields();
332         $Ajax->activate('gl_items');
333         $Ajax->activate('inv_tot');
334 }
335
336 $id2 = -1;
337 if ($_SESSION["wa_current_user"]->access == 2)
338 {
339         $id2 = find_submit('void_item_id');
340         if ($id2 != -1) 
341         {
342                 begin_transaction();
343                 
344                 $myrow = get_grn_item_detail($id2);
345
346                 $grn = get_grn_batch($myrow['grn_batch_id']);
347
348             $sql = "UPDATE ".TB_PREF."purch_order_details
349                         SET quantity_received = qty_invoiced, quantity_ordered = qty_invoiced WHERE po_detail_item = ".$myrow["po_detail_item"];
350             db_query($sql, "The quantity invoiced of the purchase order line could not be updated");
351
352             $sql = "UPDATE ".TB_PREF."grn_items
353                 SET qty_recd = quantity_inv WHERE id = ".$myrow["id"];
354                 db_query($sql, "The quantity invoiced off the items received record could not be updated");
355         
356                 update_average_material_cost($grn["supplier_id"], $myrow["item_code"],
357                         $myrow["unit_price"], -$myrow["QtyOstdg"], Today());
358
359                 add_stock_move(25, $myrow["item_code"], $myrow['grn_batch_id'], $grn['loc_code'], sql2date($grn["delivery_date"]), "",
360                         -$myrow["QtyOstdg"], $myrow['std_cost_unit'], $grn["supplier_id"], 1, $myrow['unit_price']);
361                         
362                 commit_transaction();
363                 display_notification(sprintf(_('All yet non-invoiced items on delivery line # %d has been removed.'), $id2));
364
365         }               
366 }
367
368 if (isset($_POST['go']))
369 {
370         $Ajax->activate('gl_items');
371         display_quick_entries($_SESSION['supp_trans'], $_POST['qid'], input_num('totamount'), QE_SUPPINV);
372         $_POST['totamount'] = price_format(0); $Ajax->activate('totamount');
373         $Ajax->activate('inv_tot');
374 }
375
376 start_form();
377
378 invoice_header($_SESSION['supp_trans']);
379
380 if ($_POST['supplier_id']=='') 
381         display_error('No supplier found for entered search text');
382 else {
383         start_outer_table("$table_style2 width=98%", 5);
384
385         display_grn_items($_SESSION['supp_trans'], 1);
386
387         display_gl_items($_SESSION['supp_trans'], 1);
388
389         div_start('inv_tot');
390         invoice_totals($_SESSION['supp_trans']);
391         div_end();
392
393         end_outer_table(0, false);
394 }
395
396 //-----------------------------------------------------------------------------------------
397
398 if ($id != -1 || $id2 != -1)
399 {
400         $Ajax->activate('grn_items');
401         $Ajax->activate('inv_tot');
402 }
403
404 if (get_post('AddGLCodeToTrans'))
405         $Ajax->activate('inv_tot');
406
407 br();
408 submit_center('PostInvoice', _("Enter Invoice"), true, '', 'default');
409 br();
410
411 end_form();
412
413 //--------------------------------------------------------------------------------------------------
414
415 end_page();
416 ?>