Incorrect Journal Balance (sales invoice) when many decimals in tax and price.
[fa-stable.git] / sales / create_recurrent_invoices.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_SALESINVOICE';
13 $path_to_root = "..";
14 include_once($path_to_root . "/sales/includes/cart_class.inc");
15 include_once($path_to_root . "/includes/session.inc");
16 include_once($path_to_root . "/sales/includes/ui/sales_order_ui.inc");
17 include_once($path_to_root . "/includes/ui.inc");
18 include_once($path_to_root . "/reporting/includes/reporting.inc");
19
20 $js = "";
21 if ($SysPrefs->use_popup_windows)
22         $js .= get_js_open_window(900, 600);
23 if (user_use_date_picker())
24         $js .= get_js_date_picker();
25
26 page(_($help_context = "Create and Print Recurrent Invoices"), false, false, "", $js);
27
28 function create_recurrent_invoices($customer_id, $branch_id, $order_no, $tmpl_no, $date, $from, $to, $memo)
29 {
30         global $Refs, $SysPrefs;
31
32         update_last_sent_recurrent_invoice($tmpl_no, $to);
33
34         $doc = new Cart(ST_SALESORDER, array($order_no));
35         
36         if (!empty($SysPrefs->prefs['dim_on_recurrent_invoice']))
37                 $doc->trans_type = ST_SALESINVOICE;
38         
39         get_customer_details_to_order($doc, $customer_id, $branch_id);
40
41         $doc->trans_type = ST_SALESORDER;
42         $doc->trans_no = 0;
43         $doc->document_date = $date;
44
45         $doc->due_date = get_invoice_duedate($doc->payment, $doc->document_date);
46
47         $doc->reference = $Refs->get_next($doc->trans_type, null, array('customer' => $customer_id, 'branch' => $branch_id,
48                 'date' => $date));
49         if (!empty($doc->Comments))
50                 $memo .= "\n" . $doc->Comments;
51         $doc->Comments = $memo;
52
53         foreach ($doc->line_items as $line_no=>$item) {
54                 $line = &$doc->line_items[$line_no];
55                 $new_price = get_price($line->stock_id, $doc->customer_currency,
56                         $doc->sales_type, $doc->price_factor, $doc->document_date);
57                 if ($new_price != 0)    // use template price if no price is currently set for the item.
58                         $line->price = $new_price;
59         }       
60         $cart = $doc;
61         $cart->trans_type = ST_SALESINVOICE;
62         $cart->reference = $Refs->get_next($cart->trans_type);
63         $cart->payment_terms['cash_sale'] = false; // no way to register cash payment with recurrent invoice at once
64         $invno = $cart->write(1);
65
66         return $invno;
67 }
68
69 function calculate_from($myrow)
70 {
71         if ($myrow["last_sent"] == '0000-00-00')
72                 $from = sql2date($myrow["begin"]);
73         else
74                 $from = sql2date($myrow["last_sent"]);
75         return $from;
76 }
77
78 function calculate_next($myrow)
79 {
80         if ($myrow["last_sent"] == '0000-00-00')
81                 $next = sql2date($myrow["begin"]);
82         else
83                 $next = sql2date($myrow["last_sent"]);
84         $next = add_months($next, $myrow['monthly']);
85         $next = add_days($next, $myrow['days']);
86         return add_days($next,-1);
87 }
88
89 $id = find_submit("confirmed");
90 if ($id != -1 && is_date_closed($_POST['trans_date']))
91 {
92         display_error(_("The entered date is out of fiscal year or is closed for further data entry."));
93         set_focus('trans_date');
94         $_POST['create'.$id] = 1;       //re-display current page
95         $id = -1;
96 }
97
98 if ($id != -1)
99 {
100         /*
101                 whole invoiced time is <begin, end>
102                 invoices are issued _after_ invoiced period is gone, eg:
103                 begin 1.1
104                 end       31.3
105                 period:    invoice ready for issue since:
106                 1.1-31.1 -      1.2
107                 1.2-28.2 -      1.3
108                 1.3-31.3 -      1.4
109                 In example above, when end is set to 1.4 will generate additional invoice on 1.5 !
110         */
111
112         $Ajax->activate('_page_body');
113         $from = get_post('from');
114         $to = get_post('to');
115         $memo = get_post('memo');
116         $date = $_POST['trans_date'];
117         $myrow = get_recurrent_invoice($id);
118
119         $invs = array();
120         if (recurrent_invoice_ready($id, $date))
121         {
122                         begin_transaction();
123
124                         if ($myrow['debtor_no'] == 0)
125                         {
126                                 $cust = get_cust_branches_from_group($myrow['group_no']);
127                                 while ($row = db_fetch($cust))
128                                 {
129                                         $invs[] = create_recurrent_invoices($row['debtor_no'], $row['branch_code'], $myrow['order_no'], $myrow['id'],
130                                                 $date, $from, $to, $memo);
131                                 }
132                         }
133                         else
134                         {
135                                 $invs[] = create_recurrent_invoices($myrow['debtor_no'], $myrow['group_no'], $myrow['order_no'], $myrow['id'],
136                                         $date, $from, $to, $memo);
137                         }
138                         commit_transaction();
139         }
140         if (count($invs) > 0)
141         {
142                 $min = min($invs);
143                 $max = max($invs);
144         }
145         else 
146                 $min = $max = 0;
147         display_notification(sprintf(_("%s recurrent invoice(s) created, # %s - # %s."), count($invs), $min, $max));
148         if (count($invs) > 0)
149         {
150                 $ar = array('PARAM_0' => $min."-".ST_SALESINVOICE,      'PARAM_1' => $max."-".ST_SALESINVOICE, 'PARAM_2' => "",
151                         'PARAM_3' => 0, 'PARAM_4' => 0, 'PARAM_5' => "", 'PARAM_6' => "", 'PARAM_7' => user_def_print_orientation());
152                 display_note(print_link(sprintf(_("&Print Recurrent Invoices # %s - # %s"), $min, $max), 107, $ar), 0, 1);
153                 $ar['PARAM_3'] = 1; // email
154                 display_note(print_link(sprintf(_("&Email Recurrent Invoices # %s - # %s"), $min, $max), 107, $ar), 0, 1);
155         }
156 }
157
158
159 $id = find_submit('create');
160 if ($id != -1)
161 {
162         $Ajax->activate('_page_body');
163         $date = Today();
164         $myrow = get_recurrent_invoice($id);
165         $from = calculate_from($myrow);
166         $to = add_months($from, $myrow['monthly']);
167         $to = add_days($to, $myrow['days']);
168
169         if (!is_date_in_fiscalyear($date))
170                 display_error(_("The entered date is out of fiscal year or is closed for further data entry."));
171         elseif (!date1_greater_date2(add_days(Today(), 1), $to))
172                 display_error(_("Recurrent invoice cannot be generated before last day of covered period."));
173         elseif (check_recurrent_invoice_prices($id))
174                 display_error(_("Recurrent invoices cannot be generated because some items have no price defined in customer currency."));
175         elseif (!check_sales_order_type($myrow['order_no']))
176                 display_error(_("Recurrent invoices cannot be generated because selected sales order template uses prepayment sales terms. Change payment terms and try again."));
177         else {
178                 $count = recurrent_invoice_count($id);
179
180                 $_POST['trans_date'] = $to;
181                 start_form();
182                 start_table(TABLESTYLE, "width=50%");
183                 label_row(_('Description:'), $myrow["description"]);
184                 label_row(_('Template:'), get_customer_trans_view_str(ST_SALESORDER, $myrow["order_no"]));
185                 label_row(_('Number of invoices:'), $count);
186                 date_row(_('Invoice date:'), 'trans_date');
187                 $newto = add_months($to, $myrow['monthly']);
188                 $newto = add_days($newto, $myrow['days']);
189                 text_row(_('Invoice notice:'), 'memo', sprintf(_("Recurrent Invoice covers period %s - %s."), $to,       add_days($newto, -1)), 100, 100);
190                 //text_row(_('Invoice notice:'), 'memo', sprintf(_("Recurrent Invoice covers period %s - %s."), //$from, add_days($to, -1)), 100, 100);
191                 end_table();
192                 hidden('from', $from, true);
193                 hidden('to', $to, true);
194                 br();
195                 submit_center_first('confirmed'.$id, _('Create'), _('Create recurrent invoices'), false, ICON_OK);
196                 submit_center_last('cancel', _('Cancel'), _('Return to recurrent invoices'), false, ICON_ESCAPE);
197                 submit_js_confirm("do_create".$id, sprintf(_("You are about to issue %s invoices.\n Do you want to continue?"), $count));
198                 end_form();
199
200                 display_footer_exit();
201         }
202 }
203 else
204 {
205 $result = get_recurrent_invoices(Today());
206
207 start_form();
208 start_table(TABLESTYLE, "width=70%");
209 $th = array(_("Description"), _("Template No"),_("Customer"),_("Branch")."/"._("Group"),_("Days"),_("Monthly"),_("Begin"),_("End"),_("Next invoice"),"");
210 table_header($th);
211 $k = 0;
212 $due = false;
213 while ($myrow = db_fetch($result)) 
214 {
215         if ($myrow['overdue'])
216         {
217                 start_row("class='overduebg'");
218                 $due = true;
219         }
220         else
221                 alt_table_row_color($k);
222
223         label_cell($myrow["description"]);
224         label_cell(get_customer_trans_view_str(ST_SALESORDER, $myrow["order_no"]), "nowrap align='right'");
225         if ($myrow["debtor_no"] == 0)
226         {
227                 label_cell("");
228
229                 label_cell(get_sales_group_name($myrow["group_no"]));
230         }
231         else
232         {
233                 label_cell(get_customer_name($myrow["debtor_no"]));
234                 label_cell(get_branch_name($myrow['group_no']));
235         }
236         label_cell($myrow["days"]);
237         label_cell($myrow['monthly']);
238         label_cell(sql2date($myrow['begin']),  "align='center'");
239         label_cell(sql2date($myrow['end']),      "align='center'");
240         label_cell(calculate_next($myrow),      "align='center'");
241         if ($myrow['overdue'])
242         {
243                 $count = recurrent_invoice_count($myrow['id']);
244                 if ($count)
245                 {
246                         button_cell("create".$myrow["id"], sprintf(_("Create %s Invoice(s)"), $count), "", ICON_DOC, 'process');
247                 } else {
248                         label_cell('');
249                 }
250         }
251         else
252                 label_cell("");
253         end_row();
254 }
255 end_table();
256 end_form();
257 if ($due)
258         display_note(_("Marked items are due."), 1, 0, "class='overduefg'");
259 else
260         display_note(_("No recurrent invoices are due."), 1, 0);
261
262 br();
263 }
264 end_page();