passing modules in GPL-3
[odoo/odoo.git] / addons / subscription / subscription.py
1 # -*- encoding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution   
5 #    Copyright (C) 2004-2008 Tiny SPRL (<http://tiny.be>). All Rights Reserved
6 #    $Id$
7 #
8 #    This program is free software: you can redistribute it and/or modify
9 #    it under the terms of the GNU General Public License as published by
10 #    the Free Software Foundation, either version 3 of the License, or
11 #    (at your option) any later version.
12 #
13 #    This program is distributed in the hope that it will be useful,
14 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 #    GNU General Public License for more details.
17 #
18 #    You should have received a copy of the GNU General Public License
19 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 #
21 ##############################################################################
22
23 # TODO:
24 #   Error treatment: exception, request, ... -> send request to user_id
25
26 from mx import DateTime
27 import time
28 from osv import fields,osv
29 from tools.translate import _
30
31 class subscription_document(osv.osv):
32     _name = "subscription.document"
33     _description = "Subscription document"
34     _columns = {
35         'name': fields.char('Name', size=60, required=True),
36         'active': fields.boolean('Active'),
37         'model': fields.many2one('ir.model', 'Object', required=True),
38         'field_ids': fields.one2many('subscription.document.fields', 'document_id', 'Fields')
39     }
40     _defaults = {
41         'active' : lambda *a: True,
42     }
43 subscription_document()
44
45 class subscription_document_fields(osv.osv):
46     _name = "subscription.document.fields"
47     _description = "Subscription document fields"
48     _rec_name = 'field'
49     _columns = {
50         'field': fields.many2one('ir.model.fields', 'Field', domain="[('model_id', '=', parent.model)]", required=True),
51         'value': fields.selection([('false','False'),('date','Current Date')], 'Default Value', size=40),
52         'document_id': fields.many2one('subscription.document', 'Subscription Document', ondelete='cascade'),
53     }
54     _defaults = {}
55 subscription_document_fields()
56
57 def _get_document_types(self, cr, uid, context={}):
58     cr.execute('select m.model, s.name from subscription_document s, ir_model m WHERE s.model = m.id order by s.name')
59     return cr.fetchall()
60
61 class subscription_subscription(osv.osv):
62     _name = "subscription.subscription"
63     _description = "Subscription"
64     _columns = {
65         'name': fields.char('Name', size=60, required=True),
66         'active': fields.boolean('Active'),
67         'partner_id': fields.many2one('res.partner', 'Partner'),
68         'notes': fields.text('Notes'),
69         'user_id': fields.many2one('res.users', 'User', required=True),
70         'interval_number': fields.integer('Interval Qty'),
71         'interval_type': fields.selection([('days', 'Days'), ('weeks', 'Weeks'), ('months', 'Months')], 'Interval Unit'),
72         'exec_init': fields.integer('Number of documents'),
73         'date_init': fields.datetime('First Date'),
74         'state': fields.selection([('draft','Draft'),('running','Running'),('done','Done')], 'Status'),
75         'doc_source': fields.reference('Source Document', required=True, selection=_get_document_types, size=128),
76         'doc_lines': fields.one2many('subscription.subscription.history', 'subscription_id', 'Documents created', readonly=True),
77         'cron_id': fields.many2one('ir.cron', 'Cron Job')
78     }
79     _defaults = {
80         'date_init': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
81         'user_id': lambda obj,cr,uid,context: uid,
82         'active': lambda *a: True,
83         'interval_number': lambda *a: 1,
84         'interval_type': lambda *a: 'months',
85         'doc_source': lambda *a: False,
86         'state': lambda *a: 'draft'
87     }
88
89     def set_process(self, cr, uid, ids, context={}):
90         for row in self.read(cr, uid, ids):
91             mapping = {'name':'name','interval_number':'interval_number','interval_type':'interval_type','exec_init':'numbercall','date_init':'nextcall'}
92             res = {'model':'subscription.subscription', 'args': repr([[row['id']]]), 'function':'model_copy', 'priority':6, 'user_id':row['user_id'] and row['user_id'][0]}
93             for key,value in mapping.items():
94                 res[value] = row[key]
95             id = self.pool.get('ir.cron').create(cr, uid, res)
96             self.write(cr, uid, [row['id']], {'cron_id':id, 'state':'running'})
97         return True
98
99     def model_copy(self, cr, uid, ids, context={}):
100         for row in self.read(cr, uid, ids):
101             cron_ids = [row['cron_id'][0]]
102             remaining = self.pool.get('ir.cron').read(cr, uid, cron_ids, ['numbercall'])[0]['numbercall']
103             try:
104                 (model_name, id) = row['doc_source'].split(',')
105                 id = int(id)
106                 model = self.pool.get(model_name)
107             except:
108                 raise osv.except_osv(_('Wrong Source Document !'), _('Please provide another source document.\nThis one does not exist !'))
109
110             default = {'state':'draft'}
111             doc_obj = self.pool.get('subscription.document')
112             document_ids = doc_obj.search(cr, uid, [('model.model','=',model_name)])
113             doc = doc_obj.browse(cr, uid, document_ids)[0]
114             for f in doc.field_ids:
115                 if f.value=='date':
116                     value = time.strftime('%Y-%m-%d')
117                 else:
118                     value = False
119                 default[f.field.name] = value
120
121             state = 'running'
122
123             # if there was only one remaining document to generate
124             # the subscription is over and we mark it as being done
125             if remaining == 1:
126                 state = 'done'
127             id = self.pool.get(model_name).copy(cr, uid, id, default, context)
128             self.pool.get('subscription.subscription.history').create(cr, uid, {'subscription_id': row['id'], 'date':time.strftime('%Y-%m-%d %H:%M:%S'), 'document_id': model_name+','+str(id)})
129             self.write(cr, uid, [row['id']], {'state':state})
130         return True
131
132     def set_done(self, cr, uid, ids, context={}):
133         res = self.read(cr,uid, ids, ['cron_id'])
134         ids2 = [x['cron_id'][0] for x in res if x['id']]
135         self.pool.get('ir.cron').write(cr, uid, ids2, {'active':False})
136         self.write(cr, uid, ids, {'state':'done'})
137         return True
138
139     def set_draft(self, cr, uid, ids, context={}):
140         self.write(cr, uid, ids, {'state':'draft'})
141         return True
142 subscription_subscription()
143
144 class subscription_subscription_history(osv.osv):
145     _name = "subscription.subscription.history"
146     _description = "Subscription history"
147     _rec_name = 'date'
148     _columns = {
149         'date': fields.datetime('Date'),
150         'subscription_id': fields.many2one('subscription.subscription', 'Subscription', ondelete='cascade'),
151         'document_id': fields.reference('Source Document', required=True, selection=[('account.invoice','Invoice'),('sale.order','Sale Order')], size=128),
152     }
153 subscription_subscription_history()
154
155
156 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
157