[IMP] sale order line invisible type
[odoo/odoo.git] / addons / account_followup / wizard / account_followup_print.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21
22 import datetime
23 import time
24
25 import tools
26 from osv import fields, osv
27 from tools.translate import _
28
29 class account_followup_print(osv.osv_memory):
30     _name = 'account.followup.print'
31     _description = 'Print Follow-up & Send Mail to Customers'
32     _columns = {
33         'date': fields.date('Follow-up Sending Date', required=True, help="This field allow you to select a forecast date to plan your follow-ups"),
34         'followup_id': fields.many2one('account_followup.followup', 'Follow-Up', required=True),
35     }
36
37     def _get_followup(self, cr, uid, context=None):
38         if context is None:
39             context = {}
40         if context.get('active_model', 'ir.ui.menu') == 'account_followup.followup':
41             return context.get('active_id', False)
42         company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id
43         followp_id = self.pool.get('account_followup.followup').search(cr, uid, [('company_id', '=', company_id)], context=context)
44         return followp_id and followp_id[0] or False
45
46     def do_continue(self, cr, uid, ids, context=None):
47         mod_obj = self.pool.get('ir.model.data')
48
49         if context is None:
50             context = {}
51         data = self.browse(cr, uid, ids, context=context)[0]
52         model_data_ids = mod_obj.search(cr, uid, [('model','=','ir.ui.view'),('name','=','view_account_followup_print_all')], context=context)
53         resource_id = mod_obj.read(cr, uid, model_data_ids, fields=['res_id'], context=context)[0]['res_id']
54         context.update({'followup_id': data.followup_id.id, 'date': data.date, 'company_id': data.followup_id.company_id.id})
55         return {
56             'name': _('Select Partners'),
57             'view_type': 'form',
58             'context': context,
59             'view_mode': 'tree,form',
60             'res_model': 'account.followup.print.all',
61             'views': [(resource_id,'form')],
62             'type': 'ir.actions.act_window',
63             'target': 'new',
64     }
65
66     _defaults = {
67          'date': lambda *a: time.strftime('%Y-%m-%d'),
68          'followup_id': _get_followup,
69     }
70 account_followup_print()
71
72 class account_followup_stat_by_partner(osv.osv):
73     _name = "account_followup.stat.by.partner"
74     _description = "Follow-up Statistics by Partner"
75     _rec_name = 'partner_id'
76     _auto = False
77     _columns = {
78         'partner_id': fields.many2one('res.partner', 'Partner', readonly=True),
79         'date_move':fields.date('First move', readonly=True),
80         'date_move_last':fields.date('Last move', readonly=True),
81         'date_followup':fields.date('Latest follow-up', readonly=True),
82         'max_followup_id': fields.many2one('account_followup.followup.line',
83                                     'Max Follow Up Level', readonly=True, ondelete="cascade"),
84         'balance':fields.float('Balance', readonly=True),
85         'company_id': fields.many2one('res.company', 'Company', readonly=True),
86     }
87
88     def init(self, cr):
89         tools.drop_view_if_exists(cr, 'account_followup_stat_by_partner')
90         # Here we don't have other choice but to create a virtual ID based on the concatenation
91         # of the partner_id and the company_id, because if a partner is shared between 2 companies,
92         # we want to see 2 lines for him in this table. It means that both company should be able
93         # to send him follow-ups separately . An assumption that the number of companies will not
94         # reach 10 000 records is made, what should be enough for a time.
95         cr.execute("""
96             create or replace view account_followup_stat_by_partner as (
97                 SELECT
98                     l.partner_id * 10000 + l.company_id as id,
99                     l.partner_id AS partner_id,
100                     min(l.date) AS date_move,
101                     max(l.date) AS date_move_last,
102                     max(l.followup_date) AS date_followup,
103                     max(l.followup_line_id) AS max_followup_id,
104                     sum(l.debit - l.credit) AS balance,
105                     l.company_id as company_id
106                 FROM
107                     account_move_line l
108                     LEFT JOIN account_account a ON (l.account_id = a.id)
109                 WHERE
110                     a.active AND
111                     a.type = 'receivable' AND
112                     l.reconcile_id is NULL AND
113                     l.partner_id IS NOT NULL
114                     GROUP BY
115                     l.partner_id, l.company_id
116             )""")
117 account_followup_stat_by_partner()
118
119 class account_followup_print_all(osv.osv_memory):
120     _name = 'account.followup.print.all'
121     _description = 'Print Follow-up & Send Mail to Customers'
122     _columns = {
123         'partner_ids': fields.many2many('account_followup.stat.by.partner', 'partner_stat_rel', 'osv_memory_id', 'partner_id', 'Partners', required=True),
124         'email_conf': fields.boolean('Send Email Confirmation'),
125         'email_subject': fields.char('Email Subject', size=64),
126         'partner_lang': fields.boolean('Send Email in Partner Language', help='Do not change message text, if you want to send email in partner language, or configure from company'),
127         'email_body': fields.text('Email Body'),
128         'summary': fields.text('Summary', required=True, readonly=True),
129         'test_print': fields.boolean('Test Print', help='Check if you want to print follow-ups without changing follow-ups level.')
130     }
131     def _get_summary(self, cr, uid, context=None):
132         if context is None:
133             context = {}
134         return context.get('summary', '')
135
136     def _get_partners(self, cr, uid, context=None):
137         return self._get_partners_followp(cr, uid, [], context=context)['partner_ids']
138
139     def _get_msg(self, cr, uid, context=None):
140         return self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.follow_up_msg
141
142     _defaults = {
143          'email_body': _get_msg,
144          'email_subject': _('Invoices Reminder'),
145          'partner_lang': True,
146          'partner_ids': _get_partners,
147          'summary': _get_summary,
148     }
149
150     def _get_partners_followp(self, cr, uid, ids, context=None):
151         data = {}
152         if context is None:
153             context = {}
154         if ids:
155             data = self.browse(cr, uid, ids, context=context)[0]
156         company_id = 'company_id' in context and context['company_id'] or data.company_id.id
157
158         cr.execute(
159             "SELECT l.partner_id, l.followup_line_id,l.date_maturity, l.date, l.id "\
160             "FROM account_move_line AS l "\
161                 "LEFT JOIN account_account AS a "\
162                 "ON (l.account_id=a.id) "\
163             "WHERE (l.reconcile_id IS NULL) "\
164                 "AND (a.type='receivable') "\
165                 "AND (l.state<>'draft') "\
166                 "AND (l.partner_id is NOT NULL) "\
167                 "AND (a.active) "\
168                 "AND (l.debit > 0) "\
169                 "AND (l.company_id = %s) "\
170             "ORDER BY l.date", (company_id,))
171         move_lines = cr.fetchall()
172         old = None
173         fups = {}
174         fup_id = 'followup_id' in context and context['followup_id'] or data.followup_id.id
175         date = 'date' in context and context['date'] or data.date
176
177         current_date = datetime.date(*time.strptime(date,
178             '%Y-%m-%d')[:3])
179         cr.execute(
180             "SELECT * "\
181             "FROM account_followup_followup_line "\
182             "WHERE followup_id=%s "\
183             "ORDER BY delay", (fup_id,))
184         for result in cr.dictfetchall():
185             delay = datetime.timedelta(days=result['delay'])
186             fups[old] = (current_date - delay, result['id'])
187             if result['start'] == 'end_of_month':
188                 fups[old][0].replace(day=1)
189             old = result['id']
190
191         fups[old] = (datetime.date(datetime.MAXYEAR, 12, 31), old)
192
193         partner_list = []
194         to_update = {}
195         for partner_id, followup_line_id, date_maturity,date, id in move_lines:
196             if not partner_id:
197                 continue
198             if followup_line_id not in fups:
199                 continue
200             stat_line_id = partner_id * 10000 + company_id
201             if date_maturity:
202                 if date_maturity <= fups[followup_line_id][0].strftime('%Y-%m-%d'):
203                     if stat_line_id not in partner_list:
204                         partner_list.append(stat_line_id)
205                     to_update[str(id)]= {'level': fups[followup_line_id][1], 'partner_id': stat_line_id}
206             elif date and date <= fups[followup_line_id][0].strftime('%Y-%m-%d'):
207                 if stat_line_id not in partner_list:
208                     partner_list.append(stat_line_id)
209                 to_update[str(id)]= {'level': fups[followup_line_id][1], 'partner_id': stat_line_id}
210         return {'partner_ids': partner_list, 'to_update': to_update}
211
212     def do_mail(self ,cr, uid, ids, context=None):
213         mod_obj = self.pool.get('ir.model.data')
214         move_obj = self.pool.get('account.move.line')
215         user_obj = self.pool.get('res.users')
216         line_obj = self.pool.get('account_followup.stat')
217         mail_message = self.pool.get('mail.message')
218
219         if context is None:
220             context = {}
221         data = self.browse(cr, uid, ids, context=context)[0]
222         stat_by_partner_line_ids = [partner_id.id for partner_id in data.partner_ids]
223         partners = [stat_by_partner_line / 10000 for stat_by_partner_line in stat_by_partner_line_ids]
224         model_data_ids = mod_obj.search(cr, uid, [('model','=','ir.ui.view'),('name','=','view_account_followup_print_all_msg')], context=context)
225         resource_id = mod_obj.read(cr, uid, model_data_ids, fields=['res_id'], context=context)[0]['res_id']
226         if data.email_conf:
227             msg_sent = ''
228             msg_unsent = ''
229             data_user = user_obj.browse(cr, uid, uid, context=context)
230             for partner in self.pool.get('res.partner').browse(cr, uid, partners, context=context):
231                 ids_lines = move_obj.search(cr,uid,[('partner_id','=',partner.id),('reconcile_id','=',False),('account_id.type','in',['receivable']),('company_id','=',context.get('company_id', False))])
232                 data_lines = move_obj.browse(cr, uid, ids_lines, context=context)
233                 total_amt = 0.0
234                 for line in data_lines:
235                     total_amt += line.debit - line.credit
236                 dest = False
237                 if partner:
238                     if partner.type=='contact':
239                         if adr.email:
240                             dest = [partner.email]
241                     if (not dest) and partner.type=='default':
242                         if partner.email:
243                             dest = [partner.email]
244                 src = tools.config.options['email_from']
245                 if not data.partner_lang:
246                     body = data.email_body
247                 else:
248                     cxt = context.copy()
249                     cxt['lang'] = partner.lang
250                     body = user_obj.browse(cr, uid, uid, context=cxt).company_id.follow_up_msg
251                 move_line = ''
252                 subtotal_due = 0.0
253                 subtotal_paid = 0.0
254                 subtotal_maturity = 0.0
255                 balance = 0.0
256                 l = '--------------------------------------------------------------------------------------------------------------------------'
257                 head = l+ '\n' + 'Date'.rjust(10) + '\t' + 'Description'.rjust(10) + '\t' + 'Ref'.rjust(10) + '\t' + 'Due date'.rjust(10) + '\t' + 'Due'.rjust(10) + '\t' + 'Paid'.rjust(10) + '\t' + 'Maturity'.rjust(10) + '\t' + 'Litigation'.rjust(10) + '\n' + l
258                 for i in data_lines:
259                     maturity = 0.00
260                     if i.date_maturity < time.strftime('%Y-%m-%d') and (i.debit - i.credit):
261                         maturity = i.debit - i.credit
262                     subtotal_due = subtotal_due + i.debit
263                     subtotal_paid = subtotal_paid + i.credit
264                     subtotal_maturity = subtotal_maturity + int(maturity)
265                     balance = balance + (i.debit - i.credit)
266                     move_line = move_line + (i.date).rjust(10) + '\t'+ (i.name).rjust(10) + '\t'+ (i.ref or '').rjust(10) + '\t' + (i.date_maturity or '').rjust(10) + '\t' + str(i.debit).rjust(10)  + '\t' + str(i.credit).rjust(10)  + '\t' + str(maturity).rjust(10) + '\t' + str(i.blocked).rjust(10) + '\n'
267                 move_line = move_line + l + '\n'+ '\t\t\t' + 'Sub total'.rjust(35) + '\t' + (str(subtotal_due) or '').rjust(10) + '\t' + (str(subtotal_paid) or '').rjust(10) + '\t' + (str(subtotal_maturity) or '').rjust(10)+ '\n'
268                 move_line = move_line + '\t\t\t' + 'Balance'.rjust(33) + '\t' + str(balance).rjust(10) + '\n' + l
269                 val = {
270                     'partner_name':partner.name,
271                     'followup_amount':total_amt,
272                     'user_signature':data_user.name,
273                     'company_name':data_user.company_id.name,
274                     'company_currency':data_user.company_id.currency_id.name,
275                     'line':move_line,
276                     'heading': head,
277                     'date':time.strftime('%Y-%m-%d'),
278                 }
279                 body = body%val
280                 sub = tools.ustr(data.email_subject)
281                 msg = ''
282                 if dest:
283                     try:
284                         mail_message.schedule_with_attach(cr, uid, src, dest, sub, body, context=context)
285                         msg_sent += partner.name + '\n'
286                     except Exception, e:
287                         raise osv.except_osv('Error !', e )
288                 else:
289                     msg += partner.name + '\n'
290                     msg_unsent += msg
291             if not msg_unsent:
292                 summary = _("All Emails have been successfully sent to Partners:.\n\n%s") % msg_sent
293             else:
294                 msg_unsent = _("Email not sent to following Partners, Email not available !\n\n%s") % msg_unsent
295                 msg_sent = msg_sent and _("\n\nEmail sent to following Partners successfully. !\n\n%s") % msg_sent
296                 line = '=========================================================================='
297                 summary = msg_unsent + line + msg_sent
298             context.update({'summary': summary})
299         else:
300             context.update({'summary': '\n\n\nEmail has not been sent to any partner. If you want to send it, please tick send email confirmation on wizard.'})
301
302         return {
303             'name': _('Followup Summary'),
304             'view_type': 'form',
305             'context': context,
306             'view_mode': 'tree,form',
307             'res_model': 'account.followup.print.all',
308             'views': [(resource_id,'form')],
309             'type': 'ir.actions.act_window',
310             'target': 'new',
311             'nodestroy': True
312             }
313
314     def do_print(self, cr, uid, ids, context=None):
315         if context is None:
316             context = {}
317         data = self.read(cr, uid, ids, [], context=context)[0]
318         res = self._get_partners_followp(cr, uid, ids, context)['to_update']
319         to_update = res
320         data['followup_id'] = 'followup_id' in context and context['followup_id'] or False
321         date = 'date' in context and context['date'] or data['date']
322         if not data['test_print']:
323             for id in to_update.keys():
324                 if to_update[id]['partner_id'] in data['partner_ids']:
325                     cr.execute(
326                         "UPDATE account_move_line "\
327                         "SET followup_line_id=%s, followup_date=%s "\
328                         "WHERE id=%s",
329                         (to_update[id]['level'],
330                         date, int(id),))
331         data.update({'date': context['date']})
332         datas = {
333              'ids': [],
334              'model': 'account_followup.followup',
335              'form': data
336         }
337         return {
338             'type': 'ir.actions.report.xml',
339             'report_name': 'account_followup.followup.print',
340             'datas': datas,
341         }
342
343 account_followup_print_all()
344
345 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: