def emp_create_xml(cr, id, som, eom, emp):
    # Computing the attendence by analytical account
    cr.execute(
        "select line.date, (unit_amount / unit.factor) as amount "\
        "from account_analytic_line as line, hr_analytic_timesheet as hr, "\
        "product_uom as unit "\
        "where hr.line_id=line.id "\
        "and product_uom_id = unit.id "\
        "and line.user_id=%s and line.date >= %s and line.date < %s "
        "order by line.date",
        (id, som.strftime('%Y-%m-%d'), eom.strftime('%Y-%m-%d')))

    # Sum by day
    month = {}
    for presence in cr.dictfetchall():
        day = int(presence['date'][-2:])
        month[day] = month.get(day, 0.0) + presence['amount']

    xml = '''
    <time-element date="%s">
        <amount>%.2f</amount>
    </time-element>
    '''
    time_xml = ([xml % (day, amount) for day, amount in month.iteritems()])

    # Computing the xml
    xml = '''
    <employee id="%d" name="%s">
    %s
    </employee>
    ''' % (id, toxml(emp), '\n'.join(time_xml))
    return xml
Beispiel #2
0
def emp_create_xml(cr, id, som, eom, emp):
    # Computing the attendence by analytical account
    cr.execute(
        "select line.date, (unit_amount / unit.factor) as amount "\
        "from account_analytic_line as line, hr_analytic_timesheet as hr, "\
        "product_uom as unit "\
        "where hr.line_id=line.id "\
        "and product_uom_id = unit.id "\
        "and line.user_id=%s and line.date >= %s and line.date < %s "
        "order by line.date",
        (id, som.strftime('%Y-%m-%d'), eom.strftime('%Y-%m-%d')))

    # Sum by day
    month = {}
    for presence in cr.dictfetchall():
        day = int(presence['date'][-2:])
        month[day] = month.get(day, 0.0) + presence['amount']

    xml = '''
    <time-element date="%s">
        <amount>%.2f</amount>
    </time-element>
    '''
    time_xml = ([xml % (day, amount) for day, amount in month.iteritems()])

    # Computing the xml
    xml = '''
    <employee id="%d" name="%s">
    %s
    </employee>
    ''' % (id, toxml(emp), '\n'.join(time_xml))
    return xml
def emp_create_xml(self, cr, uid, dept, row_id, empid, name, som, eom):
    start_date = str(som).split()[0]
    end_date = str(eom).split()[0]
    difference_date = eom - som
    display={}
    if dept==0:
        count=0
        registry = openerp.registry(cr.dbname)
        attendance_ids = registry['hr_attendance.record.report'].search(cr, uid, [('employee_id','in',[empid,False]),('name','>=',start_date),('name','<=',end_date)],order='name ASC')
        ids_date_attendance = registry['hr_attendance.record.report'].read(cr, uid, attendance_ids, ['name','sign_in'])
        public_holidays = registry['company.public.holidays'].search(cr, uid, [('record_year','=',str(som.year))])
        employee_leaves =  registry['hr.holidays'].search(cr,uid,[('employee_id','in',[empid,False]), ('type', '=', 'remove')])
        ids_date_leaves = registry['hr.holidays'].read(cr, uid, employee_leaves, ['date_from','date_to','state'])

        for index in range(1,difference_date.days +2 ):
            diff=index-1
            current=som+datetime.timedelta(diff)
            display[index] = ''
            #### Checking Present
            for item in ids_date_attendance:
                if str(current).split()[0] == item['name']:
                    display[index]=5
                    count=count +1
                    if display[index] != '':
                        break
            ### Checking Public Holidays
            if display[index] == '':
                for pholiday in registry['company.public.holidays'].browse(cr,uid,public_holidays):
                    if pholiday.holiday_day == str(current).split()[0]:
                        display[index]=4
                        if display[index] != '':
                            break
            ### Checking Leave Request
            if display[index] == '':
                for item in ids_date_leaves:
                    date_from = datetime.datetime.strptime(item['date_from'].split()[0], '%Y-%m-%d')
                    date_to = datetime.datetime.strptime(item['date_to'].split()[0], '%Y-%m-%d')
                    current_update = current.strftime("%Y-%m-%d %H:%M:%S")
                    datetime_current = datetime.datetime.strptime(current_update.split()[0], '%Y-%m-%d')
                    if datetime_current >= date_from and datetime_current <= date_to:
                        display[index]= 1
                        if display[index] != '':
                            break

            ### Cheking Absent
            if display[index] == '':
                if current.strftime('%a') not in ['Sat','Sun']:
                    display[index] = 2
             
    data_xml=['<info id="%d" number="%d" val="%s" />' % (row_id,x,display[x]) for x in range(1,len(display)+1) ]
    
    # Computing the xml
    xml = '''
    %s
    <employee row="%d" id="%d" name="%s" sum="%s">
    </employee>
    ''' % (data_xml,row_id,dept, ustr(toxml(name)),count)

    return xml
    def create_xml(self, cr, uid, ids, data, context):

        # Computing the dates (start of month: som, and end of month: eom)
        som = datetime.date(data["form"]["year"], data["form"]["month"], 1)
        eom = som + datetime.timedelta(lengthmonth(som.year, som.month))
        date_xml = [
            '<date month="%s" year="%d" />' % (self.get_month_name(cr, uid, som.month, context=context), som.year),
            "<days>",
        ]
        date_xml += [
            '<day number="%d" name="%s" weekday="%d" />'
            % (
                x,
                self.get_weekday_name(cr, uid, som.replace(day=x).weekday() + 1, context=context),
                som.replace(day=x).weekday() + 1,
            )
            for x in range(1, lengthmonth(som.year, som.month) + 1)
        ]
        date_xml.append("</days>")
        date_xml.append("<cols>2.5cm%s,2cm</cols>\n" % (",0.7cm" * lengthmonth(som.year, som.month)))

        emp_xml = ""
        emp_obj = pooler.get_pool(cr.dbname).get("hr.employee")
        for id in data["form"]["employee_ids"]:
            user = emp_obj.browse(cr, uid, id).user_id.id
            empl_name = emp_obj.browse(cr, uid, id).name
            if user:
                emp_xml += emp_create_xml(cr, user, som, eom, empl_name)
        # Computing the xml
        # Without this, report don't show non-ascii characters (TO CHECK)
        date_xml = "\n".join(date_xml)
        rpt_obj = pooler.get_pool(cr.dbname).get("hr.employee")
        rml_obj = report_sxw.rml_parse(cr, uid, rpt_obj._name, context)
        header_xml = """
        <header>
        <date>%s</date>
        <company>%s</company>
        </header>
        """ % (
            str(rml_obj.formatLang(time.strftime("%Y-%m-%d"), date=True)) + " " + str(time.strftime("%H:%M")),
            toxml(pooler.get_pool(cr.dbname).get("res.users").browse(cr, uid, uid).company_id.name),
        )

        xml = """<?xml version="1.0" encoding="UTF-8" ?>
        <report>
        %s
        %s
        %s
        </report>
        """ % (
            header_xml,
            date_xml,
            ustr(emp_xml),
        )
        return xml
    def create_xml(self, cr, uid, ids, data, context):
        registry = openerp.registry(cr.dbname)

        # Computing the dates (start of month: som, and end of month: eom)
        som = datetime.date(data['form']['year'], data['form']['month'], 1)
        eom = som + datetime.timedelta(lengthmonth(som.year, som.month))
        date_xml = [
            '<date month="%s" year="%d" />' % (self.get_month_name(
                cr, uid, som.month, context=context), som.year), '<days>'
        ]
        date_xml += [
            '<day number="%d" name="%s" weekday="%d" />' %
            (x,
             self.get_weekday_name(
                 cr, uid, som.replace(day=x).weekday() + 1,
                 context=context), som.replace(day=x).weekday() + 1)
            for x in range(1,
                           lengthmonth(som.year, som.month) + 1)
        ]
        date_xml.append('</days>')
        date_xml.append('<cols>2.5cm%s,2cm</cols>\n' %
                        (',0.7cm' * lengthmonth(som.year, som.month)))

        emp_xml = ''
        emp_obj = registry['hr.employee']
        for id in data['form']['employee_ids']:
            user = emp_obj.browse(cr, uid, id).user_id.id
            empl_name = emp_obj.browse(cr, uid, id).name
            if user:
                emp_xml += emp_create_xml(cr, user, som, eom, empl_name)
        # Computing the xml
        #Without this, report don't show non-ascii characters (TO CHECK)
        date_xml = '\n'.join(date_xml)
        rpt_obj = emp_obj
        rml_obj = report_sxw.rml_parse(cr, uid, rpt_obj._name, context)
        header_xml = '''
        <header>
        <date>%s</date>
        <company>%s</company>
        </header>
        ''' % (str(rml_obj.formatLang(time.strftime("%Y-%m-%d"), date=True)) +
               ' ' + str(time.strftime("%H:%M")),
               toxml(registry['res.users'].browse(cr, uid,
                                                  uid).company_id.name))

        xml = '''<?xml version="1.0" encoding="UTF-8" ?>
        <report>
        %s
        %s
        %s
        </report>
        ''' % (header_xml, date_xml, ustr(emp_xml))
        return xml
Beispiel #6
0
def emp_create_xml(self, cr, uid, dept, holiday_type, row_id, empid, name, som,
                   eom):
    display = {}
    if dept == 0:
        count = 0
        registry = openerp.registry(cr.dbname)
        holidays_ids = registry['hr.holidays'].search(
            cr, uid, [('employee_id', 'in', [empid, False]),
                      ('type', '=', 'remove')])
        ids_date = registry['hr.holidays'].read(
            cr, uid, holidays_ids,
            ['date_from', 'date_to', 'holiday_status_id', 'state'])

        for index in range(1, 61):
            diff = index - 1
            current = som + datetime.timedelta(diff)

            for item in ids_date:
                if current >= strToDate(
                        item['date_from']) and current <= strToDate(
                            item['date_to']):
                    if item['state'] in holiday_type:
                        display[index] = item['holiday_status_id'][0]
                        count = count + 1
                    else:
                        display[index] = ' '
                    break
                else:
                    display[index] = ' '
    else:
        for index in range(1, 61):
            display[index] = ' '
            count = ''

    data_xml = [
        '<info id="%d" number="%d" val="%s" />' % (row_id, x, display[x])
        for x in range(1,
                       len(display) + 1)
    ]

    # Computing the xml
    xml = '''
    %s
    <employee row="%d" id="%d" name="%s" sum="%s">
    </employee>
    ''' % (data_xml, row_id, dept, ustr(toxml(name)), count)

    return xml
def emp_create_xml(self, cr, uid, dept, holiday_type, row_id, empid, name, som, eom):
    display={}
    if dept==0:
        count=0
        registry = openerp.registry(cr.dbname)
        p_id = registry['hr.holidays'].search(cr, uid, [('employee_id','in',[empid,False]), ('type', '=', 'remove')])
        ids_date = registry['hr.holidays'].read(cr, uid, p_id, ['date_from','date_to','holiday_status_id','state'])

        for index in range(1,61):
            diff=index-1
            current=som+datetime.timedelta(diff)

            for item in ids_date:
                if current >= strToDate(item['date_from']) and current <= strToDate(item['date_to']):
                    if item['state'] in holiday_type:
                        display[index]=item['holiday_status_id'][0]
                        count=count +1
                    else:
                        display[index]=' '
                    break
                else:
                    display[index]=' '
    else:
         for index in range(1,61):
              display[index]=' '
              count=''
              
    data_xml=['<info id="%d" number="%d" val="%s" />' % (row_id,x,display[x]) for x in range(1,len(display)+1) ]
    
    # Computing the xml
    xml = '''
    %s
    <employee row="%d" id="%d" name="%s" sum="%s">
    </employee>
    ''' % (data_xml,row_id,dept, ustr(toxml(name)),count)

    return xml
    def create_xml(self, cr, uid, ids, data, context):
        registry = openerp.registry(cr.dbname)

        # Computing the dates (start of month: som, and end of month: eom)
        som = datetime.date(data['form']['year'], data['form']['month'], 1)
        eom = som + datetime.timedelta(lengthmonth(som.year, som.month))
        date_xml = ['<date month="%s" year="%d" />' % (self.get_month_name(cr, uid, som.month, context=context), som.year), '<days>']
        date_xml += ['<day number="%d" name="%s" weekday="%d" />' % (x, self.get_weekday_name(cr, uid, som.replace(day=x).weekday()+1, context=context), som.replace(day=x).weekday()+1) for x in range(1, lengthmonth(som.year, som.month)+1)]
        date_xml.append('</days>')
        date_xml.append('<cols>2.5cm%s,2cm</cols>\n' % (',0.7cm' * lengthmonth(som.year, som.month)))

        emp_xml=''
        emp_obj = registry['hr.employee']
        for id in data['form']['employee_ids']:
            user = emp_obj.browse(cr, uid, id).user_id.id
            empl_name = emp_obj.browse(cr, uid, id).name
            if user:
                emp_xml += emp_create_xml(cr, user, som, eom, empl_name)
        # Computing the xml
        #Without this, report don't show non-ascii characters (TO CHECK)
        date_xml = '\n'.join(date_xml)
        rpt_obj = emp_obj
        rml_obj=report_sxw.rml_parse(cr, uid, rpt_obj._name,context)
        header_xml = '''
        <header>
        <date>%s</date>
        <company>%s</company>
        </header>
        '''  % (str(rml_obj.formatLang(time.strftime("%Y-%m-%d"),date=True))+' ' + str(time.strftime("%H:%M")),toxml(registry['res.users'].browse(cr,uid,uid).company_id.name))

        xml='''<?xml version="1.0" encoding="UTF-8" ?>
        <report>
        %s
        %s
        %s
        </report>
        ''' % (header_xml,date_xml, ustr(emp_xml))
        return xml
    def create_xml(self, cr, uid, ids, data, context):
        registry = openerp.registry(cr.dbname)

        # Get the user id from the selected employee record
        emp_id = data['form']['employee_id']
        emp_obj = registry['hr.employee']
        user_id = emp_obj.browse(cr, uid, emp_id).user_id.id
        empl_name = emp_obj.browse(cr, uid, emp_id).name

        # Computing the dates (start of month: som, and end of month: eom)
        som = datetime.date(data['form']['year'], data['form']['month'], 1)
        eom = som + datetime.timedelta(lengthmonth(som.year, som.month))

        date_xml = [
            '<date month="%s" year="%d" />' % (self.get_month_name(
                cr, uid, som.month, context=context), som.year), '<days>'
        ]
        date_xml += [
            '<day number="%d" name="%s" weekday="%d" />' %
            (x,
             self.get_weekday_name(
                 cr, uid, som.replace(day=x).weekday() + 1,
                 context=context), som.replace(day=x).weekday() + 1)
            for x in range(1,
                           lengthmonth(som.year, som.month) + 1)
        ]

        date_xml.append('</days>')
        date_xml.append('<cols>2.5cm%s,2cm</cols>\n' %
                        (',0.7cm' * lengthmonth(som.year, som.month)))

        # Sum attendence by account, then by day
        accounts = {}
        header_xml = ''
        if user_id:
            # Computing the attendence by analytical account
            cr.execute(
                "select line.date, (unit_amount / unit.factor) as amount, account_id, account.name "\
                "from account_analytic_line as line, hr_analytic_timesheet as hr, "\
                "account_analytic_account as account, product_uom as unit "\
                "where hr.line_id=line.id and line.account_id=account.id "\
                "and product_uom_id = unit.id "\
                "and line.user_id=%s and line.date >= %s and line.date < %s "
                "order by line.date",
                (user_id, som.strftime('%Y-%m-%d'), eom.strftime('%Y-%m-%d')))

            for presence in cr.dictfetchall():
                day = int(presence['date'][-2:])
                account = accounts.setdefault(
                    (presence['account_id'], presence['name']), {})
                account[day] = account.get(day, 0.0) + presence['amount']

        xml = '''
        <time-element date="%s">
            <amount>%.2f</amount>
        </time-element>
        '''
        rpt_obj = registry['hr.employee']
        rml_obj = report_sxw.rml_parse(cr, uid, rpt_obj._name, context)
        if user_id:
            header_xml = '''
            <header>
            <date>%s</date>
            <company>%s</company>
            </header>
            ''' % (
                str(rml_obj.formatLang(time.strftime("%Y-%m-%d"), date=True)) +
                ' ' + str(time.strftime("%H:%M")),
                to_xml(registry['res.users'].browse(cr, uid,
                                                    user_id).company_id.name))

        account_xml = []
        for account, telems in accounts.iteritems():
            aid, aname = account
            aname = registry['account.analytic.account'].name_get(
                cr, uid, [aid], context)
            aname = aname[0][1]

            account_xml.append('<account id="%d" name="%s">' %
                               (aid, toxml(aname)))
            account_xml.append('\n'.join(
                [xml % (day, amount) for day, amount in telems.iteritems()]))
            account_xml.append('</account>')

        # Computing the xml
        xml = '''<?xml version="1.0" encoding="UTF-8" ?>
        <report>
        %s
        <employee>%s</employee>
        %s
        </report>
        ''' % (header_xml, ustr(
            toxml(empl_name)), '\n'.join(date_xml) + '\n'.join(account_xml))
        return xml
    def create_xml(self, cr, uid, ids, datas, context=None):
        obj_student = pooler.get_pool(cr.dbname).get('student.student')
        attendance_sheet_obj = pooler.get_pool
        (cr.dbname).get('attendance.sheet')
        if context is None:
            context = {}
        month = datetime(datas['form']['year'], datas['form']['month'], 1)
        #        stu_ids = context.get('active_ids', [])
        stu_ids = datas['form']['stud_ids']
        user_xml = [
            '<month>%s</month>' % month2name[month.month],
            '<year>%s</year>' % month.year
        ]
        if stu_ids:
            for student in obj_student.read(cr, uid, stu_ids,
                                            ['name', 'standard_id']):
                days_xml = False, []
                user_repr = '''
                <user>
                  <name>%s</name>
                  %%s
                </user>
                ''' % (ustr(toxml(student['name'])))
                today, tomor = month, month + one_day
                while today.month == month.month:
                    day = today.day
                    attendance_sheet_domain = [('standard_id', '=',
                                                student['standard_id'][0]),
                                               ('month_id', '=', today.month)]
                    attendance_sheet_search_ids =\
                        attendance_sheet_obj.search(cr, uid,
                                                    attendance_sheet_domain,
                                                    context=context)
                    if not attendance_sheet_search_ids:
                        var = 'A'
                    else:

                        for attendance_sheet_data in \
                                attendance_sheet_obj. \
                                browse(cr, uid,
                                       attendance_sheet_search_ids,
                                       context=context):
                            for line in attendance_sheet_data.attendance_ids:
                                if line.name == student['name']:
                                    if day == 1:
                                        att = line.one
                                    elif day == 2:
                                        att = line.two
                                    elif day == 3:
                                        att = line.three
                                    elif day == 4:
                                        att = line.four
                                    elif day == 5:
                                        att = line.five
                                    elif day == 6:
                                        att = line.six
                                    elif day == 7:
                                        att = line.seven
                                    elif day == 8:
                                        att = line.eight
                                    elif day == 9:
                                        att = line.nine
                                    elif day == 10:
                                        att = line.ten
                                    elif day == 11:
                                        att = line.one_1
                                    elif day == 12:
                                        att = line.one_2
                                    elif day == 13:
                                        att = line.one_3
                                    elif day == 14:
                                        att = line.one_4
                                    elif day == 15:
                                        att = line.one_5
                                    elif day == 16:
                                        att = line.one_6
                                    elif day == 17:
                                        att = line.one_7
                                    elif day == 18:
                                        att = line.one_8
                                    elif day == 19:
                                        att = line.one_9
                                    elif day == 20:
                                        att = line.one_0
                                    elif day == 21:
                                        att = line.two_1
                                    elif day == 22:
                                        att = line.two_2
                                    elif day == 23:
                                        att = line.two_3
                                    elif day == 24:
                                        att = line.two_4
                                    elif day == 25:
                                        att = line.two_5
                                    elif day == 26:
                                        att = line.two_6
                                    elif day == 27:
                                        att = line.two_7
                                    elif day == 28:
                                        att = line.two_8
                                    elif day == 29:
                                        att = line.two_9
                                    elif day == 30:
                                        att = line.two_0
                                    else:
                                        att = line.three_1

                                    if att is True:
                                        var = 'P'
                                    else:
                                        var = 'A'
                    # Week xml representation


#                    wh = hour2str(wh)
                    today_xml = '<day num="%s"><wh>%s</wh></day>' %\
                        ((today - month).days + 1, var)
                    dy = (today - month).days + 1
                    days_xml.append(today_xml)
                    today, tomor = tomor, tomor + one_day
                user_xml.append(user_repr % '\n'.join(days_xml))
        rpt_obj = pooler.get_pool(cr.dbname).get('student.student')
        rml_obj = report_sxw.rml_parse(cr, uid, rpt_obj._name, context)
        header_xml = '''
        <header>
        <date>%s</date>
        <company>%s</company>
        </header>
        ''' % (str(rml_obj.formatLang(time.strftime("%Y-%m-%d"), date=True)) +
               ' ' + str(time.strftime("%H:%M")), pooler.get_pool(
                   cr.dbname).get('res.users').browse(cr, uid,
                                                      uid).company_id.name)

        first_date = str(month)
        som = datetime.strptime(first_date, '%Y-%m-%d %H:%M:%S')
        eom = som + timedelta(int(dy) - 1)
        day_diff = eom - som
        date_xml = []
        #         cell = 1
        date_xml.append('<days>')
        if day_diff.days >= 30:
            date_xml += [
                '<dayy number="%d" name="%s" cell="%d"/>' %
                (x, som.replace(day=x).strftime('%a'), x - som.day + 1)
                for x in range(som.day,
                               lengthmonth(som.year, som.month) + 1)
            ]
        else:
            if day_diff.days >= (lengthmonth(som.year, som.month) - som.day):
                date_xml += [
                    '<dayy number="%d" name="%s" cell="%d"/>' %
                    (x, som.replace(day=x).strftime('%a'), x - som.day + 1)
                    for x in range(som.day,
                                   lengthmonth(som.year, som.month) + 1)
                ]
            else:
                date_xml += [
                    '<dayy number="%d" name="%s" cell="%d"/>' %
                    (x, som.replace(day=x).strftime('%a'), x - som.day + 1)
                    for x in range(som.day, eom.day + 1)
                ]
        cell = x - som.day + 1
        day_diff1 = day_diff.days - cell + 1
        width_dict = {}
        month_dict = {}
        i = 1
        j = 1
        year = som.year
        month = som.month
        month_dict[j] = som.strftime('%B')
        width_dict[j] = cell

        while day_diff1 > 0:
            if month + i <= 12:
                if day_diff1 > lengthmonth(year, i + month):
                    # Not on 30 else you have problems when entering 01-01-2009
                    #  for example
                    som1 = datetime.date(year, month + i, 1)
                    date_xml += [
                        '<dayy number="%d" name="%s" cell="%d"/>' %
                        (x, som1.replace(day=x).strftime('%a'), cell + x)
                        for x in range(1,
                                       lengthmonth(year, i + month) + 1)
                    ]
                    i = i + 1
                    j = j + 1
                    month_dict[j] = som1.strftime('%B')
                    cell = cell + x
                    width_dict[j] = x
                else:
                    som1 = datetime.date(year, month + i, 1)
                    date_xml += [
                        '<dayy number="%d" name="%s" cell="%d"/>' %
                        (x, som1.replace(day=x).strftime('%a'), cell + x)
                        for x in range(1, eom.day + 1)
                    ]
                    i = i + 1
                    j = j + 1
                    month_dict[j] = som1.strftime('%B')
                    cell = cell + x
                    width_dict[j] = x
                day_diff1 = day_diff1 - x
            else:
                years = year + 1
                year = years
                month = 0
                i = 1
                if day_diff1 >= 30:
                    som1 = datetime.date(years, i, 1)
                    date_xml += [
                        '<dayy number="%d" name="%s" cell="%d"/>' %
                        (x, som1.replace(day=x).strftime('%a'), cell + x)
                        for x in range(1,
                                       lengthmonth(years, i) + 1)
                    ]
                    i = i + 1
                    j = j + 1
                    month_dict[j] = som1.strftime('%B')
                    cell = cell + x
                    width_dict[j] = x
                else:
                    som1 = datetime.date(years, i, 1)
                    i = i + 1
                    j = j + 1
                    month_dict[j] = som1.strftime('%B')
                    date_xml += [
                        '<dayy number="%d" name="%s" cell="%d"/>' %
                        (x, som1.replace(day=x).strftime('%a'), cell + x)
                        for x in range(1, eom.day + 1)
                    ]
                    cell = cell + x
                    width_dict[j] = x
                day_diff1 = day_diff1 - x
        date_xml.append('</days>')
        date_xml.append('<cols>3.5cm%s</cols>\n' % (',0.74cm' * (int(dy))))
        xml = '''<?xml version="1.0" encoding="UTF-8" ?>
        <report>
        %s
        %s
        %s
        </report>
        ''' % (header_xml, '\n'.join(user_xml), date_xml)
        return xml
Beispiel #11
0
    def create_xml(self, cr, uid, ids, datas, context=None):
        obj_emp = pooler.get_pool(cr.dbname).get('hr.employee')
        if context is None:
            context = {}
        month = datetime(datas['form']['year'], datas['form']['month'], 1)
        emp_ids = datas['active_ids']
        user_xml = [
            '<month>%s</month>' % _(month2name[month.month]),
            '<year>%s</year>' % month.year
        ]
        if emp_ids:
            for emp in obj_emp.read(cr, uid, emp_ids, ['name']):
                stop, days_xml = False, []
                total_wh = 0.0
                user_repr = '''
                <user>
                  <name>%s</name>
                  %%s
                </user>
                ''' % (ustr(toxml(emp['name'])))
                today, tomor = month, month + one_day
                while today.month == month.month:
                    #### Work hour calculation
                    sql = '''
                    select action, att.name
                    from hr_employee as emp inner join hr_attendance as att
                         on emp.id = att.employee_id
                    where att.name between %s and %s and emp.id = %s
                    order by att.name
                    '''
                    cr.execute(
                        sql, (today.strftime('%Y-%m-%d %H:%M:%S'),
                              tomor.strftime('%Y-%m-%d %H:%M:%S'), emp['id']))
                    attendences = cr.dictfetchall()
                    wh = 0.0
                    # Fake sign ins/outs at week ends, to take attendances across week ends into account
                    if attendences and attendences[0]['action'] == 'sign_out':
                        attendences.insert(
                            0, {
                                'name': today.strftime('%Y-%m-%d %H:%M:%S'),
                                'action': 'sign_in'
                            })
                    if attendences and attendences[-1]['action'] == 'sign_in':
                        attendences.append({
                            'name':
                            tomor.strftime('%Y-%m-%d %H:%M:%S'),
                            'action':
                            'sign_out'
                        })
                    # sum up the attendances' durations
                    ldt = None
                    for att in attendences:
                        dt = datetime.strptime(att['name'],
                                               '%Y-%m-%d %H:%M:%S')
                        if ldt and att['action'] == 'sign_out':
                            if dt.date() > ldt.date():
                                dt = ldt
                            wh += (float((dt - ldt).seconds) / 60 / 60)
                        else:
                            ldt = dt
                    # Week xml representation
                    total_wh += wh
                    wh = hour2str(wh)
                    today_xml = '<day num="%s"><wh>%s</wh></day>' % (
                        (today - month).days + 1, (wh))
                    dy = (today - month).days + 1
                    days_xml.append(today_xml)
                    today, tomor = tomor, tomor + one_day
                total_wh = hour2str(total_wh)
                today_xml = '<day num="Total"><wh>%s</wh></day>' % (total_wh)
                days_xml.append(today_xml)
                user_xml.append(user_repr % '\n'.join(days_xml))

        rpt_obj = pooler.get_pool(cr.dbname).get('hr.employee')
        rml_obj = report_sxw.rml_parse(cr, uid, rpt_obj._name, context)
        header_xml = '''
        <header>
        <date>%s</date>
        <company>%s</company>
        </header>
        ''' % (str(rml_obj.formatLang(time.strftime("%Y-%m-%d"), date=True)) +
               ' ' + str(time.strftime("%H:%M")),
               to_xml(
                   pooler.get_pool(cr.dbname).get('res.users').browse(
                       cr, uid, uid).company_id.name))

        first_date = str(month)
        som = datetime.strptime(first_date, '%Y-%m-%d %H:%M:%S')
        eom = som + timedelta(int(dy) - 1)
        day_diff = eom - som
        date_xml = []
        cell = 1
        date_xml.append('<days>')
        if day_diff.days >= 30:
            date_xml += [
                '<dayy number="%d" name="%s" cell="%d"/>' %
                (x, _(som.replace(day=x).strftime('%a')), x - som.day + 1)
                for x in range(som.day,
                               lengthmonth(som.year, som.month) + 1)
            ]
        else:
            if day_diff.days >= (lengthmonth(som.year, som.month) - som.day):
                date_xml += [
                    '<dayy number="%d" name="%s" cell="%d"/>' %
                    (x, _(som.replace(day=x).strftime('%a')), x - som.day + 1)
                    for x in range(som.day,
                                   lengthmonth(som.year, som.month) + 1)
                ]
            else:
                date_xml += [
                    '<dayy number="%d" name="%s" cell="%d"/>' %
                    (x, _(som.replace(day=x).strftime('%a')), x - som.day + 1)
                    for x in range(som.day, eom.day + 1)
                ]
        cell = x - som.day + 1
        day_diff1 = day_diff.days - cell + 1
        width_dict = {}
        month_dict = {}
        i = 1
        j = 1
        year = som.year
        month = som.month
        month_dict[j] = som.strftime('%B')
        width_dict[j] = cell

        while day_diff1 > 0:
            if month + i <= 12:
                if day_diff1 > lengthmonth(
                        year, i + month
                ):  # Not on 30 else you have problems when entering 01-01-2009 for example
                    som1 = datetime.date(year, month + i, 1)
                    date_xml += [
                        '<dayy number="%d" name="%s" cell="%d"/>' %
                        (x, _(som1.replace(day=x).strftime('%a')), cell + x)
                        for x in range(1,
                                       lengthmonth(year, i + month) + 1)
                    ]
                    i = i + 1
                    j = j + 1
                    month_dict[j] = som1.strftime('%B')
                    cell = cell + x
                    width_dict[j] = x
                else:
                    som1 = datetime.date(year, month + i, 1)
                    date_xml += [
                        '<dayy number="%d" name="%s" cell="%d"/>' %
                        (x, _(som1.replace(day=x).strftime('%a')), cell + x)
                        for x in range(1, eom.day + 1)
                    ]
                    i = i + 1
                    j = j + 1
                    month_dict[j] = som1.strftime('%B')
                    cell = cell + x
                    width_dict[j] = x
                day_diff1 = day_diff1 - x
            else:
                years = year + 1
                year = years
                month = 0
                i = 1
                if day_diff1 >= 30:
                    som1 = datetime.date(years, i, 1)
                    date_xml += [
                        '<dayy number="%d" name="%s" cell="%d"/>' %
                        (x, _(som1.replace(day=x).strftime('%a')), cell + x)
                        for x in range(1,
                                       lengthmonth(years, i) + 1)
                    ]
                    i = i + 1
                    j = j + 1
                    month_dict[j] = som1.strftime('%B')
                    cell = cell + x
                    width_dict[j] = x
                else:
                    som1 = datetime.date(years, i, 1)
                    i = i + 1
                    j = j + 1
                    month_dict[j] = som1.strftime('%B')
                    date_xml += [
                        '<dayy number="%d" name="%s" cell="%d"/>' %
                        (x, _(som1.replace(day=x).strftime('%a')), cell + x)
                        for x in range(1, eom.day + 1)
                    ]
                    cell = cell + x
                    width_dict[j] = x
                day_diff1 = day_diff1 - x
        date_xml += ['<dayy name="Total" cell="Total"/>']
        date_xml.append('</days>')
        date_xml.append('<cols>3.5cm%s,1.2cm</cols>\n' % (',0.74cm' *
                                                          (int(dy))))
        xml = '''<?xml version="1.0" encoding="UTF-8" ?>
        <report>
        %s
        <title>%s</title>
        %s
        %s
        </report>
        ''' % (header_xml, _('Attendances by Month'), '\n'.join(user_xml),
               date_xml)
        return xml
Beispiel #12
0
    def create_xml(self, cr, uid, ids, datas, context=None):
        obj_emp = pooler.get_pool(cr.dbname).get('hr.employee')

        emp_ids = datas['active_ids']
        start_date = datetime.strptime(datas['form']['init_date'], '%Y-%m-%d')
        end_date = datetime.strptime(datas['form']['end_date'], '%Y-%m-%d')
        first_monday = start_date - relativedelta(
            days=start_date.date().weekday())
        last_monday = end_date + relativedelta(days=7 -
                                               end_date.date().weekday())

        if last_monday < first_monday:
            first_monday, last_monday = last_monday, first_monday

        rpt_obj = pooler.get_pool(cr.dbname).get('hr.employee')
        rml_obj = report_sxw.rml_parse(cr, uid, rpt_obj._name, context)
        header_xml = '''
        <header>
        <date>%s</date>
        <company>%s</company>
        </header>
        ''' % (str(rml_obj.formatLang(time.strftime("%Y-%m-%d"), date=True)) +
               ' ' + str(time.strftime("%H:%M")), pooler.get_pool(
                   cr.dbname).get('res.users').browse(cr, uid,
                                                      uid).company_id.name)
        user_xml = []
        for employee_id in emp_ids:
            emp = obj_emp.read(cr, uid, [employee_id], ['id', 'name'])[0]
            monday, n_monday = first_monday, first_monday + one_week
            stop, week_xml = False, []
            user_repr = '''
            <user>
              <name>%s</name>
              %%s
            </user>
            ''' % tools.ustr(toxml(emp['name']))
            while monday != last_monday:
                #### Work hour calculation
                sql = '''
                select action, att.name
                from hr_employee as emp inner join hr_attendance as att
                     on emp.id = att.employee_id
                where att.name between %s and %s and emp.id = %s
                order by att.name
                '''
                for idx in range(7):
                    cr.execute(sql,
                               (monday.strftime('%Y-%m-%d %H:%M:%S'),
                                (monday + relativedelta(days=idx + 1)
                                 ).strftime('%Y-%m-%d %H:%M:%S'), employee_id))
                    attendances = cr.dictfetchall()
                    week_wh = {}
                    # Fake sign ins/outs at week ends, to take attendances across week ends into account
                    # XXX this is wrong for the first sign-in ever and the last sign out to this date
                    if attendances and attendances[0]['action'] == 'sign_out':
                        attendances.insert(
                            0, {
                                'name': monday.strftime('%Y-%m-%d %H:%M:%S'),
                                'action': 'sign_in'
                            })
                    if attendances and attendances[-1]['action'] == 'sign_in':
                        attendances.append({
                            'name':
                            n_monday.strftime('%Y-%m-%d %H:%M:%S'),
                            'action':
                            'sign_out'
                        })
                    # sum up the attendances' durations
                    ldt = None
                    for att in attendances:
                        dt = datetime.strptime(att['name'],
                                               '%Y-%m-%d %H:%M:%S')
                        if ldt and att['action'] == 'sign_out':
                            week_wh[ldt.date().weekday()] = week_wh.get(
                                ldt.date().weekday(), 0) + (float(
                                    (dt - ldt).seconds) / 3600)
                        else:
                            ldt = dt

                # Week xml representation
                week_repr = [
                    '<week>',
                    '<weekstart>%s</weekstart>' % monday.strftime('%Y-%m-%d'),
                    '<weekend>%s</weekend>' %
                    (n_monday - relativedelta(days=1)).strftime('%Y-%m-%d')
                ]
                for idx in range(7):
                    week_repr.append('<%s>' % num2day[idx])
                    if idx in week_wh:
                        week_repr.append('<workhours>%sh%02d</workhours>' %
                                         to_hour(week_wh[idx]))
                    week_repr.append('</%s>' % num2day[idx])
                week_repr.append('<total>')
                week_repr.append(
                    '<worked>%sh%02d</worked>' %
                    to_hour(reduce(lambda x, y: x + y, week_wh.values(), 0)))
                week_repr.append('</total>')
                week_repr.append('</week>')
                week_xml.append('\n'.join(week_repr))

                monday, n_monday = n_monday, n_monday + one_week
            user_xml.append(user_repr % '\n'.join(week_xml))
        xml = '''<?xml version="1.0" encoding="UTF-8" ?>
        <report>
        %s
        <title>%s</title>
        %s
        </report>
        ''' % (header_xml, _('Attendances by Week'), '\n'.join(user_xml))
        xml = tools.ustr(xml).encode('utf8')
        return self.post_process_xml_data(cr, uid, xml, context)
Beispiel #13
0
    def create_xml(self, cr, uid, ids, datas, context=None):
        registry = openerp.registry(cr.dbname)
        obj_emp = registry['hr.employee']

        emp_ids = datas['active_ids']
        start_date = datetime.strptime(datas['form']['init_date'], '%Y-%m-%d')
        end_date = datetime.strptime(datas['form']['end_date'], '%Y-%m-%d')
        first_monday = start_date - relativedelta(days=start_date.date().weekday())
        last_monday = end_date + relativedelta(days=7 - end_date.date().weekday())

        if last_monday < first_monday:
            first_monday, last_monday = last_monday, first_monday

        rpt_obj = obj_emp
        rml_obj=report_sxw.rml_parse(cr, uid, rpt_obj._name,context)
        header_xml = '''
        <header>
        <date>%s</date>
        <company>%s</company>
        </header>
        ''' % (str(rml_obj.formatLang(time.strftime("%Y-%m-%d"),date=True))+' ' + str(time.strftime("%H:%M")),registry['res.users'].browse(cr,uid,uid).company_id.name)
        user_xml = []
        for employee_id in emp_ids:
            emp = obj_emp.read(cr, uid, [employee_id], ['id', 'name'])[0]
            monday, n_monday = first_monday, first_monday + one_week
            stop, week_xml = False, []
            user_repr = '''
            <user>
              <name>%s</name>
              %%s
            </user>
            ''' % tools.ustr(toxml(emp['name']))
            while monday != last_monday:
                #### Work hour calculation
                sql = '''
                select action, att.name
                from hr_employee as emp inner join hr_attendance as att
                     on emp.id = att.employee_id
                where att.name between %s and %s and emp.id = %s
                order by att.name
                '''
                for idx in range(7):
                    cr.execute(sql, (monday.strftime('%Y-%m-%d %H:%M:%S'), (monday + relativedelta(days=idx+1)).strftime('%Y-%m-%d %H:%M:%S'), employee_id))
                    attendances = cr.dictfetchall()
                    week_wh = {}
                    # Fake sign ins/outs at week ends, to take attendances across week ends into account
                    # XXX this is wrong for the first sign-in ever and the last sign out to this date
                    if attendances and attendances[0]['action'] == 'sign_out':
                        attendances.insert(0, {'name': monday.strftime('%Y-%m-%d %H:%M:%S'), 'action': 'sign_in'})
                    if attendances and attendances[-1]['action'] == 'sign_in':
                        attendances.append({'name': n_monday.strftime('%Y-%m-%d %H:%M:%S'), 'action': 'sign_out'})
                    # sum up the attendances' durations
                    ldt = None
                    for att in attendances:
                        dt = datetime.strptime(att['name'], '%Y-%m-%d %H:%M:%S')
                        if ldt and att['action'] == 'sign_out':
                            week_wh[ldt.date().weekday()] = week_wh.get(ldt.date().weekday(), 0) + (float((dt - ldt).seconds)/3600)
                        else:
                            ldt = dt

                # Week xml representation
                week_repr = ['<week>', '<weekstart>%s</weekstart>' % monday.strftime('%Y-%m-%d'), '<weekend>%s</weekend>' % (n_monday - relativedelta(days=1)).strftime('%Y-%m-%d')]
                for idx in range(7):
                    week_repr.append('<%s>' % num2day[idx])
                    if idx in week_wh:
                        week_repr.append('<workhours>%sh%02d</workhours>' % to_hour(week_wh[idx]))
                    week_repr.append('</%s>' % num2day[idx])
                week_repr.append('<total>')
                week_repr.append('<worked>%sh%02d</worked>' % to_hour(reduce(lambda x,y:x+y, week_wh.values(), 0)))
                week_repr.append('</total>')
                week_repr.append('</week>')
                week_xml.append('\n'.join(week_repr))

                monday, n_monday = n_monday, n_monday + one_week
            user_xml.append(user_repr % '\n'.join(week_xml))
        xml = '''<?xml version="1.0" encoding="UTF-8" ?>
        <report>
        %s
        <title>%s</title>
        %s
        </report>
        ''' % (header_xml,_('Attendances by Week'),'\n'.join(user_xml))
        xml = tools.ustr(xml).encode('utf8')
        return self.post_process_xml_data(cr, uid, xml, context)
Beispiel #14
0
def emp_create_xml(self, cr, uid, dept, row_id, empid, name, som, eom):
    start_date = str(som).split()[0]
    end_date = str(eom).split()[0]
    difference_date = eom - som
    display = {}
    if dept == 0:
        count = 0
        registry = openerp.registry(cr.dbname)
        attendance_ids = registry['hr_attendance.record.report'].search(
            cr,
            uid, [('employee_id', 'in', [empid, False]),
                  ('name', '>=', start_date), ('name', '<=', end_date)],
            order='name ASC')
        ids_date_attendance = registry['hr_attendance.record.report'].read(
            cr, uid, attendance_ids, ['name', 'sign_in'])
        public_holidays = registry['company.public.holidays'].search(
            cr, uid, [('record_year', '=', str(som.year))])
        employee_leaves = registry['hr.holidays'].search(
            cr, uid, [('employee_id', 'in', [empid, False]),
                      ('type', '=', 'remove')])
        ids_date_leaves = registry['hr.holidays'].read(
            cr, uid, employee_leaves, ['date_from', 'date_to', 'state'])

        for index in range(1, difference_date.days + 2):
            diff = index - 1
            current = som + datetime.timedelta(diff)
            display[index] = ''
            #### Checking Present
            for item in ids_date_attendance:
                if str(current).split()[0] == item['name']:
                    display[index] = 5
                    count = count + 1
                    if display[index] != '':
                        break
            ### Checking Public Holidays
            if display[index] == '':
                for pholiday in registry['company.public.holidays'].browse(
                        cr, uid, public_holidays):
                    if pholiday.holiday_day == str(current).split()[0]:
                        display[index] = 4
                        if display[index] != '':
                            break
            ### Checking Leave Request
            if display[index] == '':
                for item in ids_date_leaves:
                    date_from = datetime.datetime.strptime(
                        item['date_from'].split()[0], '%Y-%m-%d')
                    date_to = datetime.datetime.strptime(
                        item['date_to'].split()[0], '%Y-%m-%d')
                    current_update = current.strftime("%Y-%m-%d %H:%M:%S")
                    datetime_current = datetime.datetime.strptime(
                        current_update.split()[0], '%Y-%m-%d')
                    if datetime_current >= date_from and datetime_current <= date_to:
                        display[index] = 1
                        if display[index] != '':
                            break

            ### Cheking Absent
            if display[index] == '':
                if current.strftime('%a') not in ['Sat', 'Sun']:
                    display[index] = 2

    data_xml = [
        '<info id="%d" number="%d" val="%s" />' % (row_id, x, display[x])
        for x in range(1,
                       len(display) + 1)
    ]

    # Computing the xml
    xml = '''
    %s
    <employee row="%d" id="%d" name="%s" sum="%s">
    </employee>
    ''' % (data_xml, row_id, dept, ustr(toxml(name)), count)

    return xml
    def create_xml(self, cr, uid, ids, datas, context=None):
        obj_emp = pooler.get_pool(cr.dbname).get('hr.employee')
        if context is None:
            context = {}
        month = datetime(datas['form']['year'], datas['form']['month'], 1)
        emp_ids = datas['active_ids']
        user_xml = ['<month>%s</month>' % _(month2name[month.month]), '<year>%s</year>' % month.year]
        if emp_ids:
            for emp in obj_emp.read(cr, uid, emp_ids, ['name']):
                stop, days_xml = False, []
                total_wh = 0.0
                user_repr = '''
                <user>
                  <name>%s</name>
                  %%s
                </user>
                ''' % (ustr(toxml(emp['name'])))
                today, tomor = month, month + one_day
                while today.month == month.month:
                    #### Work hour calculation
                    sql = '''
                    select action, att.name
                    from hr_employee as emp inner join hr_attendance as att
                         on emp.id = att.employee_id
                    where att.name between %s and %s and emp.id = %s
                    order by att.name
                    '''
                    cr.execute(sql, (today.strftime('%Y-%m-%d %H:%M:%S'), tomor.strftime('%Y-%m-%d %H:%M:%S'), emp['id']))
                    attendences = cr.dictfetchall()
                    wh = 0.0
                    # Fake sign ins/outs at week ends, to take attendances across week ends into account
                    if attendences and attendences[0]['action'] == 'sign_out':
                        attendences.insert(0, {'name': today.strftime('%Y-%m-%d %H:%M:%S'), 'action':'sign_in'})
                    if attendences and attendences[-1]['action'] == 'sign_in':
                        attendences.append({'name': tomor.strftime('%Y-%m-%d %H:%M:%S'), 'action':'sign_out'})
                    # sum up the attendances' durations
                    ldt = None
                    for att in attendences:
                        dt = datetime.strptime(att['name'], '%Y-%m-%d %H:%M:%S')
                        if ldt and att['action'] == 'sign_out':
                            if dt.date() > ldt.date():
                                dt = ldt
                            wh += (float((dt - ldt).seconds)/60/60)
                        else:
                            ldt = dt
                    # Week xml representation
                    total_wh += wh
                    wh = hour2str(wh)
                    today_xml = '<day num="%s"><wh>%s</wh></day>' % ((today - month).days+1, (wh))
                    dy=(today - month).days+1
                    days_xml.append(today_xml)
                    today, tomor = tomor, tomor + one_day
                total_wh = hour2str(total_wh)
                today_xml = '<day num="Total"><wh>%s</wh></day>' % (total_wh)
                days_xml.append(today_xml)
                user_xml.append(user_repr % '\n'.join(days_xml))

        rpt_obj = pooler.get_pool(cr.dbname).get('hr.employee')
        rml_obj=report_sxw.rml_parse(cr, uid, rpt_obj._name,context)
        header_xml = '''
        <header>
        <date>%s</date>
        <company>%s</company>
        </header>
        ''' % (str(rml_obj.formatLang(time.strftime("%Y-%m-%d"),date=True))+' ' + str(time.strftime("%H:%M")),to_xml(pooler.get_pool(cr.dbname).get('res.users').browse(cr,uid,uid).company_id.name))

        first_date = str(month)
        som = datetime.strptime(first_date, '%Y-%m-%d %H:%M:%S')
        eom = som + timedelta(int(dy)-1)
        day_diff=eom-som
        date_xml=[]
        cell=1
        date_xml.append('<days>')
        if day_diff.days>=30:
            date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som.replace(day=x).strftime('%a')),x-som.day+1) for x in range(som.day, lengthmonth(som.year, som.month)+1)]
        else:
            if day_diff.days>=(lengthmonth(som.year, som.month)-som.day):
                date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som.replace(day=x).strftime('%a')),x-som.day+1) for x in range(som.day, lengthmonth(som.year, som.month)+1)]
            else:
                date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som.replace(day=x).strftime('%a')),x-som.day+1) for x in range(som.day, eom.day+1)]
        cell=x-som.day+1
        day_diff1=day_diff.days-cell+1
        width_dict={}
        month_dict={}
        i=1
        j=1
        year=som.year
        month=som.month
        month_dict[j]=som.strftime('%B')
        width_dict[j]=cell

        while day_diff1>0:
            if month+i<=12:
                if day_diff1 > lengthmonth(year,i+month): # Not on 30 else you have problems when entering 01-01-2009 for example
                    som1=datetime.date(year,month+i,1)
                    date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som1.replace(day=x).strftime('%a')),cell+x) for x in range(1, lengthmonth(year,i+month)+1)]
                    i=i+1
                    j=j+1
                    month_dict[j]=som1.strftime('%B')
                    cell=cell+x
                    width_dict[j]=x
                else:
                    som1=datetime.date(year,month+i,1)
                    date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som1.replace(day=x).strftime('%a')),cell+x) for x in range(1, eom.day+1)]
                    i=i+1
                    j=j+1
                    month_dict[j]=som1.strftime('%B')
                    cell=cell+x
                    width_dict[j]=x
                day_diff1=day_diff1-x
            else:
                years=year+1
                year=years
                month=0
                i=1
                if day_diff1>=30:
                    som1=datetime.date(years,i,1)
                    date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som1.replace(day=x).strftime('%a')),cell+x) for x in range(1, lengthmonth(years,i)+1)]
                    i=i+1
                    j=j+1
                    month_dict[j]=som1.strftime('%B')
                    cell=cell+x
                    width_dict[j]=x
                else:
                    som1=datetime.date(years,i,1)
                    i=i+1
                    j=j+1
                    month_dict[j]=som1.strftime('%B')
                    date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som1.replace(day=x).strftime('%a')),cell+x) for x in range(1, eom.day+1)]
                    cell=cell+x
                    width_dict[j]=x
                day_diff1=day_diff1-x
        date_xml += ['<dayy name="Total" cell="Total"/>']
        date_xml.append('</days>')
        date_xml.append('<cols>3.5cm%s,1.2cm</cols>\n' % (',0.74cm' * (int(dy))))
        xml = '''<?xml version="1.0" encoding="UTF-8" ?>
        <report>
        %s
        <title>%s</title>
        %s
        %s
        </report>
        ''' % (header_xml,_('Attendances by Month'),'\n'.join(user_xml),date_xml)
        return xml
    def create_xml(self, cr, uid, ids, datas, context=None):
        obj_student = pooler.get_pool(cr.dbname).get('student.student')
        attendance_sheet_obj = pooler.get_pool
        (cr.dbname).get('attendance.sheet')
        if context is None:
            context = {}
        month = datetime(datas['form']['year'], datas['form']['month'], 1)
#        stu_ids = context.get('active_ids', [])
        stu_ids = datas['form']['stud_ids']
        user_xml = ['<month>%s</month>' % month2name[month.month],
                    '<year>%s</year>' % month.year]
        if stu_ids:
            for student in obj_student.read(cr, uid, stu_ids,
                                            ['name', 'standard_id']):
                days_xml = False, []
                user_repr = '''
                <user>
                  <name>%s</name>
                  %%s
                </user>
                ''' % (ustr(toxml(student['name'])))
                today, tomor = month, month + one_day
                while today.month == month.month:
                    day = today.day
                    attendance_sheet_domain = [('standard_id', '=',
                                                student['standard_id'][0]),
                                               ('month_id', '=', today.month)]
                    attendance_sheet_search_ids =\
                        attendance_sheet_obj.search(cr, uid,
                                                    attendance_sheet_domain,
                                                    context=context)
                    if not attendance_sheet_search_ids:
                        var = 'A'
                    else:

                        for attendance_sheet_data in \
                                attendance_sheet_obj. \
                                browse(cr, uid,
                                       attendance_sheet_search_ids,
                                       context=context):
                            for line in attendance_sheet_data.attendance_ids:
                                if line.name == student['name']:
                                    if day == 1:
                                        att = line.one
                                    elif day == 2:
                                        att = line.two
                                    elif day == 3:
                                        att = line.three
                                    elif day == 4:
                                        att = line.four
                                    elif day == 5:
                                        att = line.five
                                    elif day == 6:
                                        att = line.six
                                    elif day == 7:
                                        att = line.seven
                                    elif day == 8:
                                        att = line.eight
                                    elif day == 9:
                                        att = line.nine
                                    elif day == 10:
                                        att = line.ten
                                    elif day == 11:
                                        att = line.one_1
                                    elif day == 12:
                                        att = line.one_2
                                    elif day == 13:
                                        att = line.one_3
                                    elif day == 14:
                                        att = line.one_4
                                    elif day == 15:
                                        att = line.one_5
                                    elif day == 16:
                                        att = line.one_6
                                    elif day == 17:
                                        att = line.one_7
                                    elif day == 18:
                                        att = line.one_8
                                    elif day == 19:
                                        att = line.one_9
                                    elif day == 20:
                                        att = line.one_0
                                    elif day == 21:
                                        att = line.two_1
                                    elif day == 22:
                                        att = line.two_2
                                    elif day == 23:
                                        att = line.two_3
                                    elif day == 24:
                                        att = line.two_4
                                    elif day == 25:
                                        att = line.two_5
                                    elif day == 26:
                                        att = line.two_6
                                    elif day == 27:
                                        att = line.two_7
                                    elif day == 28:
                                        att = line.two_8
                                    elif day == 29:
                                        att = line.two_9
                                    elif day == 30:
                                        att = line.two_0
                                    else:
                                        att = line.three_1

                                    if att is True:
                                        var = 'P'
                                    else:
                                        var = 'A'
                    # Week xml representation
#                    wh = hour2str(wh)
                    today_xml = '<day num="%s"><wh>%s</wh></day>' %\
                        ((today - month).days + 1, var)
                    dy = (today - month).days + 1
                    days_xml.append(today_xml)
                    today, tomor = tomor, tomor + one_day
                user_xml.append(user_repr % '\n'.join(days_xml))
        rpt_obj = pooler.get_pool(cr.dbname).get('student.student')
        rml_obj = report_sxw.rml_parse(cr, uid,
                                       rpt_obj._name,
                                       context)
        header_xml = '''
        <header>
        <date>%s</date>
        <company>%s</company>
        </header>
        ''' % (str(rml_obj.formatLang(time.strftime("%Y-%m-%d"), date=True)) +
               ' ' + str(time.strftime("%H:%M")), pooler.get_pool(cr.dbname)
               .get('res.users').browse(cr, uid, uid).company_id.name)

        first_date = str(month)
        som = datetime.strptime(first_date, '%Y-%m-%d %H:%M:%S')
        eom = som + timedelta(int(dy) - 1)
        day_diff = eom - som
        date_xml = []
        #         cell = 1
        date_xml.append('<days>')
        if day_diff.days >= 30:
            date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' %
                         (x, som.replace(day=x).strftime('%a'),
                          x - som.day + 1) for x in range(som.day,
                                                          lengthmonth
                                                          (som.year,
                                                           som.month) + 1)]
        else:
            if day_diff.days >= (lengthmonth(som.year, som.month) - som.day):
                date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' %
                             (x, som.replace(day=x).strftime('%a'),
                              x - som.day + 1) for x in range(som.day,
                                                              lengthmonth
                                                              (som.year,
                                                               som.month) + 1)]
            else:
                date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' %
                             (x, som.replace(day=x).strftime('%a'),
                              x - som.day + 1) for x in range
                             (som.day, eom.day + 1)]
        cell = x - som.day + 1
        day_diff1 = day_diff.days - cell + 1
        width_dict = {}
        month_dict = {}
        i = 1
        j = 1
        year = som.year
        month = som.month
        month_dict[j] = som.strftime('%B')
        width_dict[j] = cell

        while day_diff1 > 0:
            if month + i <= 12:
                if day_diff1 > lengthmonth(year, i + month):
                    # Not on 30 else you have problems when entering 01-01-2009
                    #  for example
                    som1 = datetime.date(year, month + i, 1)
                    date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' %
                                 (x, som1.replace(day=x).strftime('%a'),
                                  cell + x) for x in range
                                 (1, lengthmonth(year, i + month) + 1)]
                    i = i + 1
                    j = j + 1
                    month_dict[j] = som1.strftime('%B')
                    cell = cell + x
                    width_dict[j] = x
                else:
                    som1 = datetime.date(year, month + i, 1)
                    date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' %
                                 (x, som1.replace(day=x).strftime('%a'),
                                  cell + x) for x in range(1, eom.day + 1)]
                    i = i + 1
                    j = j + 1
                    month_dict[j] = som1.strftime('%B')
                    cell = cell + x
                    width_dict[j] = x
                day_diff1 = day_diff1 - x
            else:
                years = year + 1
                year = years
                month = 0
                i = 1
                if day_diff1 >= 30:
                    som1 = datetime.date(years, i, 1)
                    date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' %
                                 (x, som1.replace(day=x).strftime('%a'),
                                  cell + x) for x in range(1,
                                                           lengthmonth(years,
                                                                       i) + 1)]
                    i = i + 1
                    j = j + 1
                    month_dict[j] = som1.strftime('%B')
                    cell = cell + x
                    width_dict[j] = x
                else:
                    som1 = datetime.date(years, i, 1)
                    i = i + 1
                    j = j + 1
                    month_dict[j] = som1.strftime('%B')
                    date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' %
                                 (x, som1.replace(day=x).strftime('%a'),
                                  cell + x) for x in range(1,
                                                           eom.day + 1)]
                    cell = cell + x
                    width_dict[j] = x
                day_diff1 = day_diff1 - x
        date_xml.append('</days>')
        date_xml.append('<cols>3.5cm%s</cols>\n' % (',0.74cm' * (int(dy))))
        xml = '''<?xml version="1.0" encoding="UTF-8" ?>
        <report>
        %s
        %s
        %s
        </report>
        ''' % (header_xml, '\n'.join(user_xml), date_xml)
        return xml
Beispiel #17
0
    def create_xml(self, cr, uid, ids, data, context):

        # Get the user id from the selected employee record
        emp_id = data['form']['employee_id']
        emp_obj = pooler.get_pool(cr.dbname).get('hr.employee')
        user_id = emp_obj.browse(cr, uid, emp_id).user_id.id
        empl_name = emp_obj.browse(cr, uid, emp_id).name

        # Computing the dates (start of month: som, and end of month: eom)
        som = datetime.date(data['form']['year'], data['form']['month'], 1)
        eom = som + datetime.timedelta(lengthmonth(som.year, som.month))

        date_xml = ['<date month="%s" year="%d" />' % (self.get_month_name(cr, uid, som.month, context=context), som.year), '<days>']
        date_xml += ['<day number="%d" name="%s" weekday="%d" />' % (x, self.get_weekday_name(cr, uid, som.replace(day=x).weekday()+1, context=context), som.replace(day=x).weekday()+1) for x in range(1, lengthmonth(som.year, som.month)+1)]

        date_xml.append('</days>')
        date_xml.append('<cols>2.5cm%s,2cm</cols>\n' % (',0.7cm' * lengthmonth(som.year, som.month)))

        # Sum attendence by account, then by day
        accounts = {}
        header_xml = ''
        if user_id:
            # Computing the attendence by analytical account
            cr.execute(
                "select line.date, (unit_amount / unit.factor) as amount, account_id, account.name "\
                "from account_analytic_line as line, hr_analytic_timesheet as hr, "\
                "account_analytic_account as account, product_uom as unit "\
                "where hr.line_id=line.id and line.account_id=account.id "\
                "and product_uom_id = unit.id "\
                "and line.user_id=%s and line.date >= %s and line.date < %s "
                "order by line.date",
                (user_id, som.strftime('%Y-%m-%d'), eom.strftime('%Y-%m-%d')))

            for presence in cr.dictfetchall():
                day = int(presence['date'][-2:])
                account = accounts.setdefault((presence['account_id'], presence['name']), {})
                account[day] = account.get(day, 0.0) + presence['amount']

        xml = '''
        <time-element date="%s">
            <amount>%.2f</amount>
        </time-element>
        '''
        rpt_obj = pooler.get_pool(cr.dbname).get('hr.employee')
        rml_obj = report_sxw.rml_parse(cr, uid, rpt_obj._name,context)
        if user_id:
            header_xml = '''
            <header>
            <date>%s</date>
            <company>%s</company>
            </header>
            ''' % (str(rml_obj.formatLang(time.strftime("%Y-%m-%d"),date=True))+' ' + str(time.strftime("%H:%M")),to_xml(pooler.get_pool(cr.dbname).get('res.users').browse(cr,uid,user_id).company_id.name))

        account_xml = []
        for account, telems in accounts.iteritems():
            aid, aname = account
            aname = pooler.get_pool(cr.dbname).get('account.analytic.account').name_get(cr, uid, [aid], context)
            aname = aname[0][1]

            account_xml.append('<account id="%d" name="%s">' % (aid, toxml(aname)))
            account_xml.append('\n'.join([xml % (day, amount) for day, amount in telems.iteritems()]))
            account_xml.append('</account>')

        # Computing the xml
        xml = '''<?xml version="1.0" encoding="UTF-8" ?>
        <report>
        %s
        <employee>%s</employee>
        %s
        </report>
        ''' % (header_xml, ustr(toxml(empl_name)), '\n'.join(date_xml) + '\n'.join(account_xml))
        return xml