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