1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
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.
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.
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/>.
20 ##############################################################################
26 from osv import fields, osv
27 from tools.translate import _
29 class account_followup_print(osv.osv_memory):
30 _name = 'account.followup.print'
31 _description = 'Print Follow-up & Send Mail to Customers'
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),
37 def _get_followup(self, cr, uid, context=None):
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
46 def do_continue(self, cr, uid, ids, context=None):
47 mod_obj = self.pool.get('ir.model.data')
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})
56 'name': _('Select Partners'),
59 'view_mode': 'tree,form',
60 'res_model': 'account.followup.print.all',
61 'views': [(resource_id,'form')],
62 'type': 'ir.actions.act_window',
67 'date': lambda *a: time.strftime('%Y-%m-%d'),
68 'followup_id': _get_followup,
70 account_followup_print()
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'
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),
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.
96 create or replace view account_followup_stat_by_partner as (
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
108 LEFT JOIN account_account a ON (l.account_id = a.id)
111 a.type = 'receivable' AND
112 l.reconcile_id is NULL AND
113 l.partner_id IS NOT NULL
115 l.partner_id, l.company_id
117 account_followup_stat_by_partner()
119 class account_followup_print_all(osv.osv_memory):
120 _name = 'account.followup.print.all'
121 _description = 'Print Follow-up & Send Mail to Customers'
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.')
131 def _get_summary(self, cr, uid, context=None):
134 return context.get('summary', '')
136 def _get_partners(self, cr, uid, context=None):
137 return self._get_partners_followp(cr, uid, [], context=context)['partner_ids']
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
143 'email_body': _get_msg,
144 'email_subject': _('Invoices Reminder'),
145 'partner_lang': True,
146 'partner_ids': _get_partners,
147 'summary': _get_summary,
150 def _get_partners_followp(self, cr, uid, ids, context=None):
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
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) "\
168 "AND (l.debit > 0) "\
169 "AND (l.company_id = %s) "\
170 "ORDER BY l.date", (company_id,))
171 move_lines = cr.fetchall()
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
177 current_date = datetime.date(*time.strptime(date,
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)
191 fups[old] = (datetime.date(datetime.MAXYEAR, 12, 31), old)
195 for partner_id, followup_line_id, date_maturity,date, id in move_lines:
198 if followup_line_id not in fups:
200 stat_line_id = partner_id * 10000 + company_id
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}
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')
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']
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)
234 for line in data_lines:
235 total_amt += line.debit - line.credit
238 if partner.type=='contact':
240 dest = [partner.email]
241 if (not dest) and partner.type=='default':
243 dest = [partner.email]
244 src = tools.config.options['email_from']
245 if not data.partner_lang:
246 body = data.email_body
249 cxt['lang'] = partner.lang
250 body = user_obj.browse(cr, uid, uid, context=cxt).company_id.follow_up_msg
254 subtotal_maturity = 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
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
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,
277 'date':time.strftime('%Y-%m-%d'),
280 sub = tools.ustr(data.email_subject)
284 mail_message.schedule_with_attach(cr, uid, src, dest, sub, body, context=context)
285 msg_sent += partner.name + '\n'
287 raise osv.except_osv('Error !', e )
289 msg += partner.name + '\n'
292 summary = _("All Emails have been successfully sent to Partners:.\n\n%s") % msg_sent
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})
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.'})
303 'name': _('Followup Summary'),
306 'view_mode': 'tree,form',
307 'res_model': 'account.followup.print.all',
308 'views': [(resource_id,'form')],
309 'type': 'ir.actions.act_window',
314 def do_print(self, cr, uid, ids, context=None):
317 data = self.read(cr, uid, ids, [], context=context)[0]
318 res = self._get_partners_followp(cr, uid, ids, context)['to_update']
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']:
326 "UPDATE account_move_line "\
327 "SET followup_line_id=%s, followup_date=%s "\
329 (to_update[id]['level'],
331 data.update({'date': context['date']})
334 'model': 'account_followup.followup',
338 'type': 'ir.actions.report.xml',
339 'report_name': 'account_followup.followup.print',
343 account_followup_print_all()
345 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: