[FIX] analytic_contract_hr_expense: fixed amounts in billing table + view inheritancy
[odoo/odoo.git] / addons / event_moodle / event_moodle.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2012 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 from osv import fields, osv
23 import xmlrpclib
24 import string
25 import time
26 import random
27 from random import sample
28 from tools.translate import _
29
30 class event_moodle(osv.osv):
31     _name = 'event.moodle.config.wiz'
32     _columns = {
33         'moodle_username' : fields.char('Moodle Username', 128, help="You can also connect with your username that you define when you create a token"),
34         'moodle_password' : fields.char('Moodle Password', 128),
35         'moodle_token' : fields.char('Moodle Token', 128, help="Put your token that you created in your moodle server"),
36         'server_moodle': fields.char('Moodle Server', 128, required=True,help="URL where you have your moodle server. For exemple: 'http://127.0.0.1' or 'http://localhost'"),
37         'url': fields.char('URL to Moodle Server', size=256, help="The url that will be used for the connection with moodle in xml-rpc"),
38     }
39
40     _order = 'create_date desc'
41
42     _defaults = {
43         'server_moodle': 'http://127.0.0.1',
44     }
45
46     def configure_moodle(self, cr, uid, ids, context=None):
47         url = self.make_url(cr, uid, ids, context=context)
48         self.write(cr, uid, ids, {'url': url})
49         return {'type': 'ir.actions.act_window_close'}
50
51     def find(self, cr, uid, context=None):
52         """
53         Find the config wizard containing the configuration and raise and error if none is available.
54         """
55         moodle_config_wiz_ids = self.search(cr, uid, [], context=context)
56         if not moodle_config_wiz_ids:
57             raise osv.except_osv(('Error!'),("Configure your moodle connexion before"))
58         return moodle_config_wiz_ids[0]
59
60     def make_url(self, cr, uid, ids, context=None):
61         """
62         create the good url with the information of the configuration
63         @return url for moodle connexion
64         """
65         def _encode_password(password):
66             for i in range(len(password)):
67                 x = password[i]
68                 if x not in string.ascii_letters + string.digits:
69                     unicode_car = (hex(ord(x)))
70                     hex_car = '%'+str(unicode_car[2:])
71                     password = password.replace(x,hex_car)
72             return password
73         url=""
74         config_moodle = self.browse(cr, uid, ids[0], context=context)
75         if config_moodle.moodle_username and config_moodle.moodle_password:
76             #connexion with password and username
77             password = _encode_password(config_moodle.moodle_password)
78             url = config_moodle.server_moodle + '/moodle/webservice/xmlrpc/simpleserver.php?wsusername=' + config_moodle.moodle_username + '&wspassword=' + password
79         if config_moodle.moodle_token:
80             #connexion with token
81             url = config_moodle.server_moodle + '/moodle/webservice/xmlrpc/server.php?wstoken=' + config_moodle.moodle_token
82         return url
83
84     def create_moodle_user(self, cr, uid, id, dic_user, context=None):
85         """
86         create a moodle user
87         @param dic_user : is a list of dictonnaries with the moodle information
88         @return a liste of dictonaries with the create user id
89         """
90         #connect to moodle
91         url = self.browse(cr, uid, id, context=context).url
92         sock = xmlrpclib.ServerProxy(url)
93         #add user in moodle and return list of id and username
94         return sock.core_user_create_users(dic_user)
95
96     def create_moodle_courses(self, cr, uid, id, courses, context=None):
97         """
98         create a mmodle course
99         @param courses : is a list of dictionaries with the moodle course information
100         @return a list of dictionaries with the create course id
101         """
102         #connect to moodle
103         url = self.browse(cr, uid, id, context=context).url
104         sock = xmlrpclib.ServerProxy(url)
105         return sock.core_course_create_courses(courses)
106
107     def moodle_enrolled(self, cr, uid, id, enrolled, context=None):
108         """
109         this method is used to match a course with users
110         @param enrolled : list of dictonaries with the course id and the user id
111         """
112         #connect to moodle
113         url = self.browse(cr, uid, id, context=context).url
114         sock = xmlrpclib.ServerProxy(url)
115         #add enrolled in moodle
116         sock.enrol_manual_enrol_users(enrolled)
117
118     def create_password(self):
119         """
120         create a random password
121         """
122         rand = string.ascii_letters + string.digits
123         length = 8
124         passwd = ''.join(sample(rand, length))
125         passwd = passwd + '+'
126         return passwd
127
128     def check_email(self,email):
129     
130         """
131         check if email is correct
132         """
133         if email:
134             if (email.count('@') != 1 and email.count('.') < 1):
135                 raise osv.except_osv(_('Error!'),_("Your email '%s' is wrong") % (email))
136
137     def make_username(self, username, response_courses):
138         """
139         create a moodle username with a random number for the uniqueness
140         @return the moodle username
141         """
142         if username:
143             #remove space in the name
144             username = username.replace(" ","_")
145             #give an user name
146             name_user = username + "%d" % (response_courses,) + "%d" % (random.randint(1,999999),)
147         else:
148             name_user = "moodle_" + "%d" % (response_courses,) + "%d" % (random.randint(1,999999),)
149         return name_user
150
151 event_moodle()
152
153 class event_event(osv.osv):
154     _inherit = "event.event"
155
156     _columns={
157         'moodle_id': fields.integer('Moodle ID', help='The identifier of this event in Moodle'),
158     }
159
160     def check_registration_limits(self, cr, uid, ids, context=None):
161         """
162         create moodle courses ,users and match them when an event is confirmed
163         if the event_registration is not confirmed then it doesn t nothing
164         """
165         res = super(event_event, self).check_registration_limits(cr, uid, ids, context=context)
166         moodle_pool = self.pool.get('event.moodle.config.wiz')
167         moodle_config_wiz_id = moodle_pool.find(cr, uid, context=context)
168         list_users=[]
169         userid = []
170         for event in self.browse(cr, uid, ids, context=context):
171             #moodle use time() to store the date
172             date = time.strptime(event.date_begin, '%Y-%m-%d %H:%M:%S')
173             date = int (time.mktime(date))
174             #create the dict of values to create the course in Moodle
175             dic_courses= [{
176                 'fullname': event.name,
177                 'shortname': '',
178                 'startdate': date,
179                 'summary': event.note,
180                 'categoryid':1, #the category hardcoded is 'Miscellaneous'
181                 }]
182             #create a course in moodle and keep the id
183             response_courses = moodle_pool.create_moodle_courses(cr, uid, moodle_config_wiz_id, dic_courses, context=context)
184             self.write(cr, uid, event.id, {'moodle_id': response_courses[0]['id']})
185
186             moodle_uids = []
187             for registration in event.registration_ids:
188                 if registration.state == 'open':
189                     #enroll the registration in Moodle as it is confirmed
190                     if not registration.moodle_uid:
191                         #create a dictionary for an user
192                         name_user = moodle_pool.make_username(registration.name, response_courses[0]['id'])
193                         moodle_pool.check_email(registration.email)
194                         passwd = moodle_pool.create_password()
195                         dic_users={
196                             'username' : name_user,
197                             'password' : passwd,
198                             'city' : registration.city,
199                             'firstname' : registration.name ,
200                             'lastname': '',
201                             'email': registration.email
202                         }
203                         #create the user in moodle
204                         response_user = moodle_pool.create_moodle_user(cr, uid, moodle_config_wiz_id, [dic_users], context=context)
205                         for user in response_user:
206                             self.pool.get('event.registration').write(cr,uid,[registration.id],{'moodle_uid': user['id'], 'moodle_user_password': passwd, 'moodle_username': name_user})
207                             moodle_uids.append(user['id'])
208                     else:
209                         moodle_uids.append(registration.moodle_uid)
210
211             #link the course with users
212             enrolled = []
213             for moodle_user in moodle_uids:
214                 enrolled.append({
215                 'roleid' :'5', #mark as 'Student'
216                 'userid' : moodle_user,
217                 'courseid' :response_courses[0]['id']
218                 })
219             moodle_pool.moodle_enrolled(cr, uid, moodle_config_wiz_id, enrolled, context=context)
220         return res
221
222 event_event()
223
224 class event_registration(osv.osv):
225
226     _inherit = "event.registration"
227
228     _columns={
229         'moodle_user_password': fields.char('Password for Moodle User', 128),
230         'moodle_username': fields.char('Moodle Username', 128),
231         'moodle_uid': fields.integer('Moodle User ID'),
232     }
233
234     def confirm_registration(self, cr, uid, ids, context=None):
235         """
236         create a user and match to a course if the event is already confirmed
237         """
238         res = super(event_registration, self).confirm_registration(cr, uid, ids, context=context)
239         moodle_pool = self.pool.get('event.moodle.config.wiz')
240         moodle_config_wiz_id = moodle_pool.find(cr, uid, context=context)
241         for register in self.browse(cr, uid, ids, context=context):
242             if register.event_id.state == 'confirm' and register.event_id.moodle_id:
243                 if not register.moodle_uid:
244                     #create the user in moodle
245                     name_user = moodle_pool.make_username(register.name, register.event_id.moodle_id)
246                     moodle_pool.check_email(register.email)
247                     passwd = moodle_pool.create_password()
248                     dic_users = [{
249                         'username': name_user,
250                         'password': passwd,
251                         'city': register.city,
252                         'firstname': register.name,
253                         'lastname': '', #we could make a split of the register.name on ' ' but it would be inaccurate, so it seems better to let it empty as it's not really useful
254                         'email': register.email,
255                     }]
256                     response_user = moodle_pool.create_moodle_user(cr, uid, moodle_config_wiz_id, dic_users, context=context)
257                     #write in database the password and the username
258                     moodle_user_id = response_user[0]['id']
259                     self.pool.get('event.registration').write(cr, uid, ids, {'moodle_uid': moodle_user_id, 'moodle_user_password': passwd, 'moodle_username': name_user})
260                 else:
261                     moodle_user_id = register.moodle_uid
262                 enrolled=[{
263                     'roleid': '5', #mark as student
264                     'userid': moodle_user_id,
265                     'courseid': register.event_id.moodle_id
266                 }]
267                 moodle_pool.moodle_enrolled(cr, uid, moodle_config_wiz_id, enrolled, context=context)
268         return res
269
270     def onchange_moodle_name(self, cr, uid, ids, moodle_username, context=None):
271         """
272         This onchange receive as parameter a username moddle and will fill the moodle_uid and password fields if existing records with this username are found
273             @param moodle_username: the existing moodle username
274         """
275         res = {}
276         reg_ids = self.search(cr, uid, [('moodle_username', '=', moodle_username)], order='create_date desc', context=context)
277         if reg_ids:
278             reg = self.browse(cr, uid, reg_ids[0], context=context)
279             res = {'value' :{
280                     'moodle_uid': reg.moodle_uid,
281                     'name': reg.name,
282                     'email':reg.email,
283                     'phone':reg.phone,
284                     'city': reg.city,
285                     'street': reg.street}}
286         return res
287 event_registration()