~technofluid-team/openobject-addons/technofluid_multiple_installations

« back to all changes in this revision

Viewing changes to hr_timesheet_ical/wizard/wizard_ical.py

  • Committer: pinky
  • Date: 2006-12-07 13:41:40 UTC
  • Revision ID: pinky-dedd7f8a42bd4557112a0513082691b8590ad6cc
New trunk

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
import re
 
2
import urllib2
 
3
import datetime
 
4
from schoolbell.calendar import icalendar
 
5
 
 
6
import wizard
 
7
import pooler
 
8
 
 
9
CALENDAR_URL = 'http://127.0.0.1:7180'
 
10
 
 
11
def _employee_get(self,cr,uid,context={}):
 
12
        ids = self.pool.get('hr.employee').search(cr, uid, [('user_id','=', uid)])
 
13
        if ids:
 
14
                return ids[0]
 
15
        return False
 
16
 
 
17
class RequestHandler(object):
 
18
 
 
19
        def __init__(self):
 
20
                self.auth_handler = urllib2.HTTPBasicAuthHandler()
 
21
                self.opener = urllib2.build_opener(self.auth_handler)
 
22
 
 
23
        def addAuthentication(self, username, password):
 
24
                self.auth_handler.add_password('zope', CALENDAR_URL, username, password)
 
25
 
 
26
def get_url(url, auth_data={}):
 
27
        req = RequestHandler()
 
28
        if auth_data:
 
29
                req.addAuthentication(auth_data['user'], auth_data['pass'])
 
30
        return req.opener.open(url).read()
 
31
 
 
32
def _start_date(uid, y, z):
 
33
        today = datetime.date.today()
 
34
        monday = today - datetime.timedelta(days=today.weekday())
 
35
        return monday.strftime('%Y-%m-%d')
 
36
 
 
37
def _end_date(uid, y, z):
 
38
        today = datetime.date.today()
 
39
        friday = today + datetime.timedelta(days=4-today.weekday())
 
40
        return friday.strftime('%Y-%m-%d')
 
41
 
 
42
ical_form = """<?xml version="1.0" ?>
 
43
<form string="Chose the dates">
 
44
        <field name="startdate" />
 
45
        <field name="enddate" />
 
46
        <field name="user_id" colspan="3"/>
 
47
</form>"""
 
48
 
 
49
ical_fields = {
 
50
        'startdate' : dict(string='Start date', type='date', required=True, default=_start_date),
 
51
        'enddate' : dict(string='End date', type='date', required=True, default=_end_date),
 
52
        'user_id' : dict(string=u'User', type='many2one', relation='res.users', required=True, default=lambda x,y,z:x),
 
53
        }
 
54
 
 
55
success_form = """<?xml version="1.0" ?>
 
56
<form string="Import successful">
 
57
        <separator string="Import successful" />
 
58
</form>"""
 
59
 
 
60
success_fields = {}
 
61
 
 
62
project_re = re.compile(r"^ *\[?(\d{1,4}\.?\d{0,3})\]? *(.*)", re.UNICODE)
 
63
 
 
64
class wizard_import_icalendar(wizard.interface):
 
65
        def import_ical(self, cr, uid, data, context):
 
66
                employee_id = _employee_get(pooler.get_pool(cr.dbname).get('hr.attendance'), cr, data['form']['user_id'])
 
67
                if not employee_id:
 
68
                        raise wizard.except_wizard('No employee found for the user', 'Login ID: %s' % data['form']['user_id'])
 
69
                
 
70
                first, end = [datetime.date(*(map(int, x.split('-')))) for x in [data['form']['startdate'], data['form']['enddate']]]
 
71
                end = min(end, datetime.date.today())
 
72
                try:
 
73
                        user_obj = pooler.get_pool(cr.dbname).get('res.users')
 
74
                        user = user_obj.read(cr, uid, [data['form']['user_id']])
 
75
                        events = icalendar.read_icalendar(get_url('%s/persons/%s/calendar.ics' % (CALENDAR_URL, user[0]['login']), {'user': 'manager', 'pass': 'schoolbell'}))
 
76
                except urllib2.HTTPError, e:
 
77
                        raise wizard.except_wizard('Erreur HTTP', '%s - %s' % (e.code, e.msg))
 
78
                except IndexError:
 
79
                        raise wizard.except_wizard('No user login found', 'Login ID: %s' % data['form']['user_id'])
 
80
                
 
81
                event_obj = pooler.get_pool(cr.dbname).get('res.partner.event')
 
82
                timesheet_line_obj = pooler.get_pool(cr.dbname).get('hr.analytic.timesheet')
 
83
                analytic_account_obj = pooler.get_pool(cr.dbname).get('account.analytic.account')
 
84
                for event in [e for e in events if first <= e.dtstart.date() <= end]:
 
85
                        project_search = project_re.search(event.title)
 
86
                        if not project_search:
 
87
                                continue
 
88
                        else:
 
89
                                project_code, summary = project_search.groups()
 
90
                        
 
91
                        account_id = analytic_account_obj.name_search(cr, uid, project_code)
 
92
                        if account_id:
 
93
                                account_id = account_id[0][0]
 
94
                                timesheet_line_id = timesheet_line_obj.search(cr, uid, [('event_ical_id', '=', event.unique_id)])
 
95
                                if not timesheet_line_id:
 
96
                                        unit_id = timesheet_line_obj.default_get(cr, uid, ['product_uom_id','product_id'], {'user_id' : data['form']['user_id']})
 
97
                                        amount = timesheet_line_obj.on_change_unit_amount(cr, uid, [], unit_id['product_id'], event.duration.seconds / 3600.0, unit_id['product_uom_id'])
 
98
                                        if amount:
 
99
                                                amount = amount['value']['amount']
 
100
                                        timesheet_line_obj.create(cr, uid, {'name' : summary, 'date' : event.dtstart.strftime('%Y-%m-%d'), 'unit_amount' : event.duration.seconds / 3600.0,
 
101
                                                                                                                'user_id' :vdata['form']['user_id'], 'account_id' : account_id, 'amount' : amount,
 
102
                                                                                                                'event_ical_id' : event.unique_id},
 
103
                                                                                          {'user_id' : data['form']['user_id']})
 
104
 
 
105
                                event_id = event_obj.search(cr, uid, [('event_ical_id', '=', event.unique_id)])
 
106
                                if not event_id:
 
107
                                        account = pooler.get_pool(cr.dbname).get('account.analytic.account').read(cr, uid, [account_id], ['partner_id', 'contact_id'])
 
108
                                        if account:
 
109
                                                event_obj.create(cr, uid,
 
110
                                                  {'name' : summary,
 
111
                                                   'description' : event.description,
 
112
                                                   'partner_id' : account[0]['partner_id'][0],
 
113
                                                   'project_id' : account_id,
 
114
                                                   'user_id' : data['form']['user_id'],
 
115
                                                   'date' : event.dtstart.strftime('%Y-%m-%d %H:%M'),
 
116
                                                   'event_ical_id' : event.unique_id})
 
117
                return {}
 
118
        
 
119
        states = {
 
120
                'init' : {
 
121
                        'actions' : [],
 
122
                        'result' : {'type' : 'form', 'arch' : ical_form, 'fields' : ical_fields, 'state' : (('import', 'Import'), ('end', 'Cancel'))}
 
123
                        },
 
124
                'import' : {
 
125
                        'actions' : [import_ical],
 
126
                        'result' : {'type' : 'form', 'arch' : success_form, 'fields' : success_fields, 'state' : (('end', 'Quit'),)}
 
127
                        },
 
128
                }
 
129
 
 
130
wizard_import_icalendar('hr.ical_import')