Use xml id for attributes groups in menuitem tags
[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.many2one('ir.model', 'Model', required=True),
44                 'field_ids': fields.one2many('subscription.document.fields', 'document_id', 'Fields')
45         }
46         _defaults = {
47                 'active' : lambda *a: True,
48         }
49 subscription_document()
50
51 class subscription_document_fields(osv.osv):
52         _name = "subscription.document.fields"
53         _description = "Subscription document fields"
54         _rec_name = 'field'
55         _columns = {
56                 'field': fields.many2one('ir.model.fields', 'Field', domain="[('model_id', '=', parent.model)]", required=True),
57                 'value': fields.selection([('false','False'),('date','Current Date')], 'Default Value', size=40),
58                 'document_id': fields.many2one('subscription.document', 'Subscription Document', ondelete='cascade'),
59         }
60         _defaults = {}
61 subscription_document_fields()
62
63 def _get_document_types(self, cr, uid, context={}):
64         cr.execute('select m.model, s.name from subscription_document s, ir_model m WHERE s.model = m.id order by s.name')
65         return cr.fetchall()
66
67 class subscription_subscription(osv.osv):
68         _name = "subscription.subscription"
69         _description = "Subscription"
70         _columns = {
71                 'name': fields.char('Name', size=60, required=True),
72                 'active': fields.boolean('Active'),
73                 'partner_id': fields.many2one('res.partner', 'Partner'),
74                 'notes': fields.text('Notes'),
75                 'user_id': fields.many2one('res.users', 'User', required=True),
76                 'interval_number': fields.integer('Interval Qty'),
77                 'interval_type': fields.selection([('days', 'Days'), ('weeks', 'Weeks'), ('months', 'Months')], 'Interval Unit'),
78                 'exec_init': fields.integer('Number of documents'),
79                 'date_init': fields.datetime('First Date'),
80                 'state': fields.selection([('draft','Draft'),('running','Running'),('done','Done')], 'State'),
81                 'doc_source': fields.reference('Source Document', required=True, selection=_get_document_types, size=128),
82                 'doc_lines': fields.one2many('subscription.subscription.history', 'subscription_id', 'Documents created', readonly=True),
83                 'cron_id': fields.many2one('ir.cron', 'Cron Job')
84         }
85         _defaults = {
86                 'date_init': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
87                 'user_id': lambda obj,cr,uid,context: uid,
88                 'active': lambda *a: True,
89                 'interval_number': lambda *a: 1,
90                 'interval_type': lambda *a: 'months',
91                 'doc_source': lambda *a: False,
92                 'state': lambda *a: 'draft'
93         }
94
95         def set_process(self, cr, uid, ids, context={}):
96                 for row in self.read(cr, uid, ids):
97                         mapping = {'name':'name','interval_number':'interval_number','interval_type':'interval_type','exec_init':'numbercall','date_init':'nextcall'}
98                         res = {'model':'subscription.subscription', 'args': repr([[row['id']]]), 'function':'model_copy', 'priority':6, 'user_id':row['user_id'] and row['user_id'][0]}
99                         for key,value in mapping.items():
100                                 res[value] = row[key]
101                         id = self.pool.get('ir.cron').create(cr, uid, res)
102                         self.write(cr, uid, [row['id']], {'cron_id':id, 'state':'running'})
103                 return True
104
105         def model_copy(self, cr, uid, ids, context={}):
106                 for row in self.read(cr, uid, ids):
107                         cron_ids = [row['cron_id'][0]]
108                         remaining = self.pool.get('ir.cron').read(cr, uid, cron_ids, ['numbercall'])[0]['numbercall']
109                         try:
110                                 (model_name, id) = row['doc_source'].split(',')
111                                 id = int(id)
112                                 model = self.pool.get(model_name)
113                         except:
114                                 raise osv.except_osv('Wrong Source Document !', 'Please provide another source document.\nThis one does not exist !')
115
116                         default = {'state':'draft'}
117                         doc_obj = self.pool.get('subscription.document')
118                         document_ids = doc_obj.search(cr, uid, [('model.model','=',model_name)])
119                         doc = doc_obj.browse(cr, uid, document_ids)[0]
120                         for f in doc.field_ids:
121                                 if f.value=='date':
122                                         value = time.strftime('%Y-%m-%d')
123                                 else:
124                                         value = False
125                                 default[f.field.name] = value
126
127                         state = 'running'
128
129                         # if there was only one remaining document to generate
130                         # the subscription is over and we mark it as being done
131                         if remaining == 1:
132                                 state = 'done'
133                         id = self.pool.get(model_name).copy(cr, uid, id, default, context)
134                         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)})
135                         self.write(cr, uid, [row['id']], {'state':state})
136                 return True
137
138         def set_done(self, cr, uid, ids, context={}):
139                 res = self.read(cr,uid, ids, ['cron_id'])
140                 ids2 = [x['cron_id'][0] for x in res if x['id']]
141                 self.pool.get('ir.cron').write(cr, uid, ids2, {'active':False})
142                 self.write(cr, uid, ids, {'state':'done'})
143                 return True
144
145         def set_draft(self, cr, uid, ids, context={}):
146                 self.write(cr, uid, ids, {'state':'draft'})
147                 return True
148 subscription_subscription()
149
150 class subscription_subscription_history(osv.osv):
151         _name = "subscription.subscription.history"
152         _description = "Subscription history"
153         _rec_name = 'date'
154         _columns = {
155                 'date': fields.datetime('Date'),
156                 'subscription_id': fields.many2one('subscription.subscription', 'Subscription', ondelete='cascade'),
157                 'document_id': fields.reference('Source Document', required=True, selection=[('account.invoice','Invoice'),('sale.order','Sale Order')], size=128),
158         }
159 subscription_subscription_history()
160