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