예제 #1
0
    def create_xml_cols(self,
                        cr,
                        uid,
                        ids,
                        col_value,
                        flag,
                        planed_amount,
                        context=None):
        content = ''
        col_type = 'total'
        vals = ''
        extra = flag == 1 and 'للصنف ' or 'الكلي'
        fiscalyear_obj = self.pool.get('account.fiscalyear')
        result = 0.0
        temp = 0.0
        for year in fiscalyear_obj.browse(cr,
                                          uid,
                                          col_value['fiscalyear_ids'],
                                          context=context):
            temp += planed_amount['next_planned_amount'][year.name]
        result = temp != 0.0 and (planed_amount['planned_amount'] -
                                  temp) * 100 / temp

        vals += ''' <cols note="False" type="%s"> <val> %s </val></cols> ''' % (
            col_type, self.rml_obj.formatLang(result))
        vals += ''' <cols note="False" type="%s"> <val> %s </val></cols> ''' % (
            col_type, self.rml_obj.formatLang(result))
        vals += ''' <cols note="False" type="%s"> <val> %s </val></cols> ''' % (
            col_type, self.rml_obj.formatLang(planed_amount['planned_amount']))
        if col_value['num_year'] != 0:
            for year in fiscalyear_obj.browse(cr,
                                              uid,
                                              col_value['fiscalyear_ids'],
                                              context=context):
                temp = planed_amount['next_planned_amount'][year.name]
                result = 0.0
                result = temp != 0.0 and (
                    planed_amount['balance'] /
                    planed_amount['next_planned_amount'][year.name]) * 100

                vals += ''' <cols note="False" type="%s"> <val> %s </val></cols> ''' % (
                    col_type, self.rml_obj.formatLang(result))
                vals += ''' <cols note="False" type="%s"> <val> %s </val></cols> ''' % (
                    col_type, self.rml_obj.formatLang(
                        planed_amount['balance']))
                vals += ''' <cols note="False" type="%s"> <val> %s </val></cols> ''' % (
                    col_type,
                    self.rml_obj.formatLang(
                        planed_amount['next_planned_amount'][year.name]))
        if flag == 1:
            tempural = "الإجمالي " + extra
            class_name = u'' + tempural.decode(
                'utf-8') + u'' + col_value['name']
            vals += ''' <cols note="False" type="%s"> <val> %s </val></cols> ''' % (
                col_type, ustr(toxml(class_name)))
        else:
            vals += ''' <cols note="False" type="%s"> <val> %s </val></cols> ''' % (
                col_type, ustr(toxml('الإجمالي')))
        content += vals
        return content
예제 #2
0
    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), 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), 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)))
        
        # 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",
            (data['form']['user_id'], som.strftime('%Y-%m-%d'), eom.strftime('%Y-%m-%d')))

        # Sum attendence by account, then by day
        accounts = {}
        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>
        '''
        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 employee
        cr.execute("select name from res_users where id=%s", (data['form']['user_id'],))
        emp = cr.fetchone()[0]

        # Computing the xml
        xml = '''<?xml version="1.0" encoding="UTF-8" ?>
        <report>
        <employee>%s</employee>
        %s
        </report>
        ''' % (toxml(emp), '\n'.join(date_xml) + '\n'.join(account_xml))
        return xml
예제 #3
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 period_compare_budget_xml(self, cr, uid, ids, datas, header_xml, analytic_acc=False, context={}):
        period_obj = self.pool.get('account.period')
        fiscal_year_obj = self.pool.get('account.fiscalyear')
        form = datas.get('form', {})
        dept_xml = '''<datas>'''
        fiscalyear = fiscal_year_obj.browse(cr, uid, form.get('fiscalyear_id', []), context=context)
        period_objs = fiscalyear and fiscalyear.period_ids
        period_objs.reverse()
        period_from = form.get('period_from', False)
        period_to = form.get('period_to', False)
	
        period_from_start = period_from and period_obj.browse(cr, uid, period_from, context=context).date_start or ''
        period_stop = period_to and period_obj.browse(cr, uid, period_to, context=context).date_stop or ''

        periods = not (period_from or period_to) and period_objs or []
        if not periods:
            for period in period_objs:
                if datetime.strptime(period.date_start, '%Y-%m-%d').date() >= datetime.strptime(period_from_start, '%Y-%m-%d').date() and datetime.strptime(period.date_stop, '%Y-%m-%d').date() <= datetime.strptime(period_stop, '%Y-%m-%d').date():
                    periods.append(period)
        length = 1
        for period in periods:
            if not period.special:
                dept_xml += ''' <header name="%s"/> ''' % (ustr(toxml(period.name)))
                length += 1
        dept_xml += '''</datas>'''
        dept_xml += '''<cols>%s120,60</cols>''' % ((str((800*self.columns-180) / length) + ',') * int(length))
        content = ''
        result = []
        for period in periods:
            if not period.special:
                budget_report = account_report_budget.account_budget(cr, uid, "", context=context)
                budget_report.set_context([], datas, ids)
                form.update({'period_from':period.id, 'period_to':period.id})
                if form.get('type_selection', 'detail') == 'detail':
                    result.append(budget_report._get_company_detail(form, analytic_acc))
                else:
                    result.append(budget_report._get_company_detail_total(form, analytic_acc))
        if result:
            for i in range(len(result[0])):
                content += ''' <row> '''
                total = 0
                vals = ''
                for j in range(len(result)):
                    total += result[j][i]['planned_amount'] / self.accuracy
                    row_type = result[j][i].get('code', '*') == '*' and 'total' or 'detail'
                    vals += ''' <cols type="%s">  <val> ''' % (row_type)
                    vals += ''' %s ''' % (self.rml_obj.formatLang(result[j][i]['planned_amount'] / self.accuracy))
                    vals += ''' </val> </cols> '''
                code = result[0][i].get('code', '*') == '*' and ' ' or result[0][i].get('code', '*')
                content += ''' <cols type="%s"> <val> %s </val></cols> '''% (row_type,self.rml_obj.formatLang(total))
                content += vals + ''' <cols type="%s"> <val> %s </val> </cols> <cols type="%s"> <val> %s </val> </cols>'''% (row_type,ustr(toxml(result[0][i]['name'])),row_type,ustr(toxml(code)))
                content += ''' </row> '''
        xml = '''
        <page size='%s' type='%s'>
        %s
        %s
        %s
        </page>
        ''' % (self.size, self.type, header_xml, dept_xml, content)
        return xml
예제 #5
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
예제 #6
0
def emp_create_xml(self, cr, uid, dept, holiday_type, row_id, empid, name, som, eom):
    display = {}
    if dept == 0:
        count = 0
        p_id = (
            pooler.get_pool(cr.dbname)
            .get("hr.holidays")
            .search(cr, uid, [("employee_id", "in", [empid, False]), ("type", "=", "remove")])
        )
        ids_date = (
            pooler.get_pool(cr.dbname)
            .get("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 = ""

    xml = """
        <time-element index="%d">
            <value>%s</value>
        </time-element>
        """
    time_xml = [xml % (index, value) for index, value in display.iteritems()]
    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">
    %s
    </employee>
    """ % (
        data_xml,
        row_id,
        dept,
        toxml(name),
        count,
        "\n".join(time_xml),
    )

    return xml
예제 #7
0
    def create_xml(self, cr, uid, ids, datas, context):
        service = netsvc.LocalService('object_proxy')

        month = DateTime.DateTime(datas['form']['year'], datas['form']['month'], 1)
        
        user_xml = ['<month>%s</month>' % month2name[month.month], '<year>%s</year>' % month.year]
        
        for employee_id in ids:
            emp = service.execute(cr.dbname, uid, 'hr.employee', 'read', [employee_id])[0]
            stop, days_xml = False, []
            user_repr = '''
            <user>
              <name>%s</name>
              %%s
            </user>
            ''' % (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'), employee_id))
                attendences = cr.dictfetchall()
                wh = 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
                for att in attendences:
                    dt = DateTime.strptime(att['name'], '%Y-%m-%d %H:%M:%S')
                    if att['action'] == 'sign_out':
                        wh += (dt - ldt).hours
                    ldt = dt
                
                # Week xml representation
                wh = hour2str(wh)
                today_xml = '<day num="%s"><wh>%s</wh></day>' % ((today - month).days+1, wh)
                days_xml.append(today_xml)
                today, tomor = tomor, tomor + one_day
                
            user_xml.append(user_repr % '\n'.join(days_xml))
        
        xml = '''<?xml version="1.0" encoding="UTF-8" ?>
        <report>
        %s
        </report>
        ''' % '\n'.join(user_xml)

        return xml
예제 #8
0
def emp_create_xml(self, cr, uid, dept, row_id, empid, name, som, eom):

    dayDiff = eom - som
    display = {}
    if dept == 0:
        p_id = pooler.get_pool(cr.dbname).get('hr.holidays').search(
            cr, uid, [('employee_id', '=', empid)])

        ids_date = pooler.get_pool(cr.dbname).get('hr.holidays').read(
            cr, uid, p_id, ['date_from', 'date_to', 'holiday_status', 'state'])

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

            for item in ids_date:
                #            print current,"from",item['date_from'],"to",item['date_to']
                if current >= strToDate(
                        item['date_from']) and current <= strToDate(
                            item['date_to']):
                    if item['state'] == 'confirm' or item[
                            'state'] == 'validate':
                        display[index] = item['holiday_status'][0]
                    else:
                        display[index] = ' '
                    break
                else:
                    display[index] = ' '

    else:

        for index in range(1, dayDiff.days + 2):
            display[index] = ' '

    xml = '''
        <time-element index="%d">
            <value>%s</value>
        </time-element>
        '''
    time_xml = ([xml % (index, value) for index, value in display.iteritems()])
    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">
    %s
    </employee>
    ''' % (data_xml, row_id, dept, toxml(name), '\n'.join(time_xml))

    return xml
def emp_create_xml(self, cr, uid, dept, holiday_type, row_id, empid, name, som,
                   eom):
    display = {}
    if dept == 0:
        count = 0
        p_id = pooler.get_pool(cr.dbname).get('hr.holidays').search(
            cr, uid, [('employee_id', 'in', [empid, False]),
                      ('type', '=', 'remove')])
        ids_date = pooler.get_pool(cr.dbname).get('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 = ''

    xml = '''
        <time-element index="%d">
            <value>%s</value>
        </time-element>
        '''
    time_xml = ([xml % (index, value) for index, value in display.iteritems()])
    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">
    %s
    </employee>
    ''' % (data_xml, row_id, dept, toxml(name), count, '\n'.join(time_xml))

    return xml
def emp_create_xml(self,cr,uid,dept,row_id,empid,name,som,eom):

    dayDiff=eom-som
    display={}
    if dept==0:
        p_id=pooler.get_pool(cr.dbname).get('hr.holidays').search(cr,uid,[('employee_id','=',empid)])

        ids_date = pooler.get_pool(cr.dbname).get('hr.holidays').read(cr,uid,p_id,['date_from','date_to','holiday_status','state'])

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

            for item in ids_date:
    #            print current,"from",item['date_from'],"to",item['date_to']
                if current >= strToDate(item['date_from']) and current <= strToDate(item['date_to']):
                    if item['state']=='confirm' or item['state']=='validate':
                        display[index]=item['holiday_status'][0]
                    else:
                        display[index]=' '
                    break
                else:
                    display[index]=' '

    else:

         for index in range(1,dayDiff.days+2):
              display[index]=' '

    xml = '''
        <time-element index="%d">
            <value>%s</value>
        </time-element>
        '''
    time_xml = ([xml % (index, value) for index,value in display.iteritems()])
    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">
    %s
    </employee>
    ''' % (data_xml,row_id,dept, toxml(name), '\n'.join(time_xml))

    return xml
예제 #11
0
def emp_create_xml(self,cr,uid,dept,holiday_type,row_id,empid,name,som,eom):

    display={}

    if dept==0:
        count=0
        p_id=pooler.get_pool(cr.dbname).get('hr.holidays').search(cr,uid,[('employee_id','in',[empid,False])])
        ids_date = pooler.get_pool(cr.dbname).get('hr.holidays').read(cr,uid,p_id,['date_from','date_to','holiday_status','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'][0]
                        count=count +1
                    else:
                        display[index]=' '
                    break
                else:
                    display[index]=' '
    else:
         for index in range(1,61):
              display[index]=' '
              count=''

    xml = '''
        <time-element index="%d">
            <value>%s</value>
        </time-element>
        '''
    time_xml = ([xml % (index, value) for index,value in display.iteritems()])
    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">
    %s
    </employee>
    ''' % (data_xml,row_id,dept, toxml(name),count, '\n'.join(time_xml))

    return xml
    def dept_compare_period_budget_xml(self, cr, uid, ids, datas, header_xml, context=None):
        analytic_account_obj = self.pool.get('account.analytic.account')
        dept_xml = '''<datas>'''
        main_dept = analytic_account_obj.search(cr, uid, [('main_dept', '=', True)], context=context, order='code desc')
        analytic_accounts = analytic_account_obj.browse(cr, uid, main_dept, context=context)
        for analytic in analytic_accounts:
            dept_xml += ''' <header name="%s"/> ''' % (ustr(toxml(analytic.name)))
        dept_xml += '''</datas>'''
        length = len(main_dept) + 1
        dept_xml += '''<cols>%s120,60</cols>''' % ((str((800*self.columns-180) / length) + ',') * int(length))
        content = ''
        result = []
        for analytic in analytic_accounts:
            budget_report = account_report_budget.account_budget(cr, uid, "", context=context)
            budget_report.set_context([], datas, ids)
            if datas.get('form', {}).get('type_selection', 'detail') == 'detail':
                result.append(budget_report._get_company_detail(datas.get('form', {}), analytic.id))
            else:
                result.append(budget_report._get_company_detail_total(datas.get('form', {}), analytic.id))
        if result:
            for i in range(len(result[0])):
                content += ''' <row> '''
                total = 0
                vals = ''
                for j in range(len(result)):
                    total += result[j][i]['planned_amount'] / self.accuracy
                    row_type = result[j][i].get('code', '*') == '*' and 'total' or 'detail'
                    vals += ''' <cols type="%s">  <val> ''' % (row_type)
                    vals += ''' %s ''' % (self.rml_obj.formatLang(result[j][i]['planned_amount'] / self.accuracy))
                    vals += ''' </val> </cols> '''
                code = result[0][i].get('code', '*') == '*' and ' ' or result[0][i].get('code', '*')
                content += ''' <cols type="%s"> <val> %s </val></cols> '''% (row_type,self.rml_obj.formatLang(total))
                content += vals + ''' <cols type="%s"> <val> %s </val> </cols> <cols type="%s"> <val> %s </val> </cols>'''% (row_type,ustr(toxml(result[0][i]['name'])),row_type,ustr(toxml(code)))
                content += ''' </row> '''

        xml = '''<?xml version="1.0" encoding="UTF-8" ?>
        <report><page size='%s' type='%s'>
        %s
        %s
        %s
        </page></report>
        ''' % (self.size, self.type, header_xml, dept_xml, content)
        return xml
    def dept_compare_fiscalyear_budget_xml(self, cr, uid, ids, datas, header_xml, context=None):
        analytic_account_obj = self.pool.get('account.analytic.account')
        dept_xml = '''<datas>'''
        main_dept = analytic_account_obj.search(cr, uid, [('main_dept', '=', True),('company_id', '=', datas['form']['company_id'])], context=context, order='code desc')
        analytic_accounts = analytic_account_obj.browse(cr, uid, main_dept, context=context)
        if not analytic_accounts:
            raise orm.except_orm(_('Error!'), _('There is no Data to Display ' )) 
        for analytic in analytic_accounts:
            dept_xml += ''' <header name="%s"/> ''' % (ustr(toxml(analytic.name)))
        dept_xml += '''</datas>'''
        length = len(main_dept) + 1
        dept_xml += '''<cols>%s120,60</cols>''' % ((str((800*self.columns-180) / length) + ',') * int(length))
        content = ''
        result = []
        for analytic in analytic_accounts:
            if datas.get('form', {}).get('type_selection', 'detail') == 'detail':
                result.append(self._get_fiscalyear_company_detail(cr, uid, ids, datas, analytic.id, context=context))
            else:
                result.append(self._get_fiscalyear_company_detail_total(cr, uid, ids, datas, analytic.id, context=context))
        if result:
            for i in range(len(result[0])):
                content += ''' <row> '''
                total = 0
                vals = ''
                for j in range(len(result)):
                    total += i < len(result[j]) and result[j][i]['planned_amount'] / self.accuracy or 0.0
                    row_type = i < len(result[j]) and result[j][i].get('code', '*') == '*' and 'total' or 'detail'
                    vals += ''' <cols type="%s">  <val> ''' % (row_type)
                    vals += ''' %s ''' % (self.rml_obj.formatLang(i< len(result[j]) and result[j][i]['planned_amount'] / self.accuracy or 0.0))
                    vals += ''' </val> </cols> '''
                code = i < len(result[j]) and (result[0][i].get('code', '*') == '*' and ' ' or result[0][i].get('code', '*')) or ' ' 
                content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (row_type,self.rml_obj.formatLang(total))
                content += vals + ''' <cols type="%s"> <val> %s </val> </cols> <cols type="%s"> <val> %s </val> </cols>''' % (row_type,ustr(toxml(result[0][i]['name'])),row_type,ustr(toxml(code)))
                content += ''' </row> '''

        xml = '''<?xml version="1.0" encoding="UTF-8" ?>
        <report><page size='%s' type='%s'>
        %s
        %s
        %s
        </page></report>
        ''' % (self.size, self.type, header_xml, dept_xml, content)
        return xml
예제 #14
0
def emp_create_xml(cr, uid, som, eom, emp):
    user = pooler.get_pool(cr.dbname).get("res.users").browse(cr, uid, uid)
    max_work_hours = user.company_id.timesheet_max_difference

    # 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""",
        (uid, 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"]
        if month[day] > max_work_hours:
            month[day] = max_work_hours

    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>
    """ % (
        uid,
        toxml(emp),
        "\n".join(time_xml),
    )
    return xml
예제 #15
0
def emp_create_xml(cr, uid, som, eom, emp):
    user = pooler.get_pool(cr.dbname).get('res.users').browse(cr, uid, uid)
    max_work_hours = user.company_id.timesheet_max_difference

    # 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""",
        (uid, 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']
        if month[day] > max_work_hours:
            month[day] = max_work_hours

    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>
    ''' % (uid, toxml(emp), '\n'.join(time_xml))
    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, []
                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':
                            wh += (float((dt - ldt).seconds)/60/60)
                        else:
                            ldt = dt
                    # Week xml representation
                    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
                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")),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
        <title>%s</title>
        %s
        %s
        </report>
        ''' % (header_xml,_('Attendances By Month'),'\n'.join(user_xml),date_xml)
        return xml
예제 #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")),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
예제 #18
0
    def compare_budget(self, cr, uid, ids, datas, header_xml, context=None):
        period_pool = self.pool.get('account.period')
        account_pool = self.pool.get('account.account')
        budget_line_pool = self.pool.get('account.budget.lines')
        fisc_budget_line_pool = self.pool.get(
            'account.fiscalyear.budget.lines')
        fiscalyear_obj = self.pool.get('account.fiscalyear')
        classification_obj = self.pool.get('account.budget.classification')
        account_chart = datas.get('form', {}).get('chart_account_id', [])
        analytic_chart = datas.get('form', {}).get('chart_analytic_account_id',
                                                   [])
        period_from = datas.get('form', {}).get('period_from', False)
        period_to = datas.get('form', {}).get('period_to', False)
        classification_ids = datas.get('form', {}).get('classification_ids',
                                                       False)
        num_year = datas.get('form', {}).get('num_year', False)
        fiscalyear_id = datas.get('form', {}).get('first_fiscalyear', False)
        fiscalyear_ids = fiscalyear_obj.search(
            cr,
            uid, [('id', '!=', fiscalyear_id),
                  ('date_stop', '<',
                   fiscalyear_obj.browse(
                       cr, uid, fiscalyear_id, context=context).date_start)],
            limit=num_year,
            order='date_start desc',
            context=context)
        period_from_start = period_from and period_pool.browse(
            cr, uid, period_from, context=context).date_start or ''
        period_stop = period_to and period_pool.browse(
            cr, uid, period_to, context=context).date_stop or ''
        current_periods = period_pool.search(
            cr, uid, [('fiscalyear_id', '=', fiscalyear_id)], context=context)
        analytic_child_ids = self._get_children_and_consol(
            cr, uid, analytic_chart, 'account.analytic.account', context)
        account_child_ids = self._get_children_and_consol(
            cr, uid, account_chart, 'account.account', context)
        general_account = self._sort_filter(cr,
                                            uid,
                                            account_child_ids,
                                            context=context)
        budget_class = {'id': False, 'name': '', 'class': ''}
        years_planned_amount = {
            'planned_amount': 0.0,
            'next_planned_amount': {},
            'balance': 0.0
        }
        class_planed_amount = {
            'planned_amount': 0.0,
            'next_planned_amount': {},
            'balance': 0.0
        }
        next_fiscalyear_ids = []
        account_budget = {
            'code': '',
            'name': '',
            'planned_amount': 0.0,
            'next_planned_amount': {},
            'balance': 0.0
        }
        count = 0
        flag = False
        temp = ''
        classenametemp = classification_obj.browse(cr,
                                                   uid,
                                                   classification_ids[0],
                                                   context=context).name
        class_name = (u' الصنف %s' % (classification_obj.browse(
            cr, uid, classification_ids[0], context=context).name))
        content = ''' <row name="%s" count="1" class="True" item="False"> ''' % (
            ustr(toxml(class_name)))
        dept_xml = '''<datas>'''
        dept_xml += ''' <header name="%s" split="False"/> ''' % (ustr(
            toxml('التوصيات')))
        dept_xml += ''' <header name="%s" split="False"/> ''' % (ustr(
            toxml('نسبة التغيير')))
        note = ''
        vals = ''
        xml = ''
        if fiscalyear_ids == []:
            num_year = 0
        if classification_ids == []:
            xml += self.generate_empty(cr,
                                       uid,
                                       ids,
                                       datas,
                                       header_xml,
                                       context=context)
            return xml
        for classification in classification_obj.browse(cr,
                                                        uid,
                                                        classification_ids,
                                                        context=context):
            for account in classification.account_ids:
                vals = ''
                if count == 0:
                    dept_xml += ''' <header name="%s" split="False"/> ''' % (
                        ustr(
                            toxml("المصدق الحالي " + str(
                                fiscalyear_obj.browse(
                                    cr, uid, fiscalyear_id,
                                    context=context).name))))
                    if num_year != 0:
                        dept_xml += ''' <header2 name=" " split="False"/> '''
                for year in fiscalyear_obj.browse(cr,
                                                  uid,
                                                  fiscalyear_ids,
                                                  context=context):
                    account_budget['next_planned_amount'][year.name] = 0.0
                    if count == 0:
                        flag = True
                        years_planned_amount['next_planned_amount'][
                            year.name] = 0.0
                        class_planed_amount['next_planned_amount'][
                            year.name] = 0.0
                        if num_year != 0:
                            dept_xml += ''' <header name="%s" split="True"/> ''' % (
                                ustr(toxml("المقترح للعام " + str(year.name))))
                            dept_xml += ''' <header2 name=" " split="True"/> '''
                if count == 0:
                    dept_xml += ''' <header name="%s" split="False"/> ''' % (
                        ustr(toxml('بند الخصم')))
                    if num_year != 0:
                        dept_xml += ''' <header2 name=" " split="False"/> '''
                    else:
                        dept_xml += ''' <header2 name=" " split="True"/> '''
                    dept_xml += '''</datas>'''
                    length = len(fiscalyear_ids)
                    if length == 0: length = 1
                    factor = num_year
                    page_size = 0
                    if self.size == 'A3_landscape':
                        page_size = 1572
                    else:
                        page_size = 786
                    if num_year == 0 or fiscalyear_ids == []:
                        row_width = page_size / 4
                        dept_xml += '''<cols>160,70,80,90</cols>'''
                        dept_xml += '''<splitcols>160,70,80,90</splitcols>'''
                        dept_xml += '''<extracols>400</extracols>'''
                        dept_xml += '''<cols2>%s%s</cols2>''' % (((str(
                            (page_size) / (4)) + ',') * int(3)), row_width)
                        dept_xml += '''<headercols>%s%s</headercols>''' % ((
                            (str(
                                (page_size) / (4)) + ',') * int(3)), row_width)
                        factor = 1
                    elif num_year <= length:
                        row_width = page_size / (4 + (num_year * 3))
                        dept_xml += '''<cols>160,70,80,%s90</cols>''' % (
                            (str((3 * 70 * num_year) / num_year) + ',') *
                            int(num_year))
                        dept_xml += '''<splitcols>160,70,80,%s90</splitcols>''' % (
                            (str((3 * 70 * num_year) /
                                 (num_year * 3)) + ',') * int(num_year * 3))
                        dept_xml += '''<extracols>310,%s90</extracols>''' % (
                            (str((3 * 70 * num_year) /
                                 (num_year * 3)) + ',') * int(num_year * 3))
                        dept_xml += '''<cols2>%s%s%s</cols2>''' % ((
                            (str(round(((page_size) /
                                        (4 + (num_year * 3))), 2)) + ',') *
                            int(3)), ((str(
                                round(((page_size) / (4 + (num_year * 3))) *
                                      (3))) + ',') * int(num_year)), row_width)
                        dept_xml += '''<headercols>%s,%s%s</headercols>''' % (
                            (row_width * 3),
                            ((str(round(
                                (page_size) / (4 + (num_year * 3)))) + ',') *
                             int(num_year * 3)), row_width)
                    else:
                        row_width = page_size / (4 + (length * 3))
                        dept_xml += '''<cols>160,70,80,%s90</cols>''' % ((str(
                            (3 * 70 * length) / length) + ',') * int(length))
                        dept_xml += '''<splitcols>160,70,80,%s90</splitcols>''' % (
                            (str((3 * 70 * length) /
                                 (length * 3)) + ',') * int(length * 3))
                        dept_xml += '''<extracols>310,%s90</extracols>''' % (
                            (str((3 * 70 * length) /
                                 (length * 3)) + ',') * int(length * 3))
                        dept_xml += '''<cols2>%s%s%s</cols2>''' % (
                            ((str(round(
                                ((page_size) /
                                 (4 + (length * 3))), 2)) + ',') * int(3)),
                            ((str(
                                round(((page_size) / (4 + (length * 3))) *
                                      (3))) + ',') * int(length)), row_width)
                        dept_xml += '''<headercols>%s,%s%s</headercols>''' % (
                            (row_width * 3),
                            ((str(round(
                                (page_size) / (4 + (length * 3)))) + ',') *
                             int(length * 3)), row_width)
                        factor = length
                if count > 0 and budget_class[
                        'id'] != classification.id and budget_class[
                            'id'] != False:
                    content += ''' <row name="None" count="2" class="False" item="False"> '''
                elif count > 0 and budget_class['id'] != classification.id:
                    content += ''' <row name="None" count="2" class="False" item="False"> '''
                elif count > 0:
                    content += ''' <row name="None" count="2" class="False" item="True"> '''
                if budget_class['id'] != classification.id:
                    class_name = (u' الصنف %s' % (classification.name))
                    if budget_class['id'] != False:
                        temp = {
                            'name': budget_class['name'],
                            'fiscalyear_ids': fiscalyear_ids,
                            'num_year': num_year,
                        }
                        vals += self.create_xml_cols(
                            cr,
                            uid,
                            ids,
                            temp,
                            1,
                            class_planed_amount,
                            context=context) + '''  <val>  </val></row> '''
                        vals += '''<row name="%s" count="2" class="True" item="False"> ''' % (
                            ustr(toxml(class_name)))
                        vals += ''' <val> %s </val> ''' % (ustr(toxml(note)))
                        note = ''
                        if num_year != 0:
                            for year in fiscalyear_obj.browse(cr,
                                                              uid,
                                                              fiscalyear_ids,
                                                              context=context):
                                class_planed_amount['next_planned_amount'][
                                    year.name] = 0.0
                        class_planed_amount['planned_amount'] = 0.0
                        class_planed_amount['balance'] = 0.0
                    if num_year == 0 or fiscalyear_ids == []:
                        for i in range(1, 5):
                            if i == 1:
                                vals += ''' <cols note="True" type="%s"> <val> %s </val></cols> ''' % (
                                    'total', ustr(toxml(" ")))
                            elif i == 4:
                                vals += ''' <cols note="False" type="%s"> <val> %s </val></cols> ''' % (
                                    'total', ustr(toxml(class_name)))
                            else:
                                vals += ''' <cols note="False" type="%s"> <val> %s </val></cols> ''' % (
                                    'total', ustr(toxml(" ")))
                    else:
                        for i in range(1, (factor * 3) + 5):
                            if i == 1:
                                vals += ''' <cols note="True" type="%s"> <val> %s </val></cols> ''' % (
                                    'total', ustr(toxml(" ")))
                            elif i == ((factor * 3) + 4):
                                vals += ''' <cols note="False" type="%s"> <val> %s </val></cols> ''' % (
                                    'total', ustr(toxml(class_name)))
                            else:
                                vals += ''' <cols note="False" type="%s"> <val> %s </val></cols> ''' % (
                                    'total', ustr(toxml(" ")))
                    vals += '''  <val>  </val></row> <row name="None" count="2" class="False" item="True"> '''
                    budget_class['id'] = classification.id
                account_budget = {
                    'code': account.code,
                    'name': account.name,
                    'planned_amount': 0.0,
                    'next_planned_amount': {},
                    'balance': 0.0
                }
                if num_year != 0:
                    for year in fiscalyear_obj.browse(cr,
                                                      uid,
                                                      fiscalyear_ids,
                                                      context=context):
                        account_budget['next_planned_amount'][year.name] = 0.0
                current_lines = budget_line_pool.search(
                    cr,
                    uid, [('period_id', 'in', current_periods),
                          ('analytic_account_id', 'in', analytic_child_ids),
                          ('general_account_id', '=', account.id)],
                    context=context)
                current_lines2 = fisc_budget_line_pool.search(
                    cr,
                    uid, [('fiscalyear_id', '=', fiscalyear_id),
                          ('analytic_account_id', 'in', analytic_child_ids),
                          ('general_account_id', '=', account.id)],
                    context=context)
                next_lines = []
                if num_year != 0:
                    next_lines = fisc_budget_line_pool.search(
                        cr,
                        uid,
                        [('fiscalyear_id', 'in', fiscalyear_ids),
                         ('analytic_account_id', 'in', analytic_child_ids),
                         ('general_account_id', '=', account.id)],
                        context=context)
                period_ids = period_pool.search(
                    cr,
                    uid, [('fiscalyear_id', 'in', fiscalyear_ids)],
                    context=context)
                bal_lines = budget_line_pool.search(
                    cr,
                    uid, [('period_id', 'in', period_ids),
                          ('analytic_account_id', 'in', analytic_child_ids),
                          ('general_account_id', '=', account.id)],
                    context=context)
                if current_lines:
                    for line in budget_line_pool.browse(cr,
                                                        uid,
                                                        current_lines,
                                                        context=context):
                        account_budget['planned_amount'] += line.planned_amount
                        class_planed_amount[
                            'planned_amount'] += line.planned_amount
                        years_planned_amount[
                            'planned_amount'] += line.planned_amount
                        flag = True

                    for line in fisc_budget_line_pool.browse(cr,
                                                             uid,
                                                             current_lines2,
                                                             context=context):
                        if line.note != False:
                            note += "\n" + line.note + " -"

                if bal_lines:
                    for line in budget_line_pool.browse(cr,
                                                        uid,
                                                        bal_lines,
                                                        context=context):
                        account_budget['balance'] += line.balance
                        class_planed_amount['balance'] += line.balance
                        years_planned_amount['balance'] += line.balance
                temp = 0.0
                if next_lines:
                    for line in fisc_budget_line_pool.browse(cr,
                                                             uid,
                                                             next_lines,
                                                             context=context):
                        account_budget['next_planned_amount'][
                            line.fiscalyear_id.name] += line.planned_amount
                        class_planed_amount['next_planned_amount'][
                            line.fiscalyear_id.name] += line.planned_amount
                        years_planned_amount['next_planned_amount'][
                            line.fiscalyear_id.name] += line.planned_amount
                    for year in fiscalyear_obj.browse(cr,
                                                      uid,
                                                      fiscalyear_ids,
                                                      context=context):
                        temp += account_budget['next_planned_amount'][
                            year.name]
                    flag = True
                vals += ''' <cols note="True" type="%s"> <val> %s </val></cols> ''' % (
                    'detail', ustr(toxml(note)))
                result = 0.0
                result = temp != 0 and (account_budget['planned_amount'] -
                                        temp) * 100 / temp
                vals += ''' <cols note="False" type="%s"> <val> %s </val></cols> ''' % (
                    'detail', self.rml_obj.formatLang(result))
                result = 0.0
                if current_lines:
                    vals += ''' <cols note="False" type="%s"> <val> %s </val></cols> ''' % (
                        'detail',
                        self.rml_obj.formatLang(
                            account_budget['planned_amount']))
                else:
                    vals += ''' <cols note="False" type="%s"> <val> %s </val></cols> ''' % (
                        'detail', self.rml_obj.formatLang(0.0))
                if next_lines:
                    for year in fiscalyear_obj.browse(cr,
                                                      uid,
                                                      fiscalyear_ids,
                                                      context=context):
                        result = 0.0
                        if account_budget['next_planned_amount'][
                                year.name] != 0.0:
                            result = (account_budget['balance'] /
                                      account_budget['next_planned_amount'][
                                          year.name]) * 100
                        vals += ''' <cols note="False" type="%s"> <val> %s </val></cols> ''' % (
                            'detail', self.rml_obj.formatLang(result))
                        vals += ''' <cols note="False" type="%s"> <val> %s </val></cols> ''' % (
                            'detail',
                            self.rml_obj.formatLang(account_budget['balance']))
                        vals += ''' <cols note="False" type="%s"> <val> %s </val></cols> ''' % (
                            'detail',
                            self.rml_obj.formatLang(
                                account_budget['next_planned_amount'][
                                    year.name]))
                elif num_year != 0 and num_year <= len(fiscalyear_ids):
                    for i in range(1, num_year + 1):
                        for j in range(1, 4):
                            vals += ''' <cols note="False" type="%s"> <val> %s </val></cols> ''' % (
                                'detail', self.rml_obj.formatLang(0.0))
                elif num_year != 0 and num_year > len(fiscalyear_ids):
                    for i in range(1, len(fiscalyear_ids) + 1):
                        for j in range(1, 4):
                            vals += ''' <cols note="False" type="%s"> <val> %s </val></cols> ''' % (
                                'detail', self.rml_obj.formatLang(0.0))
                vals += ''' <cols note="False" type="%s"> <val> %s </val></cols> ''' % (
                    'detail', ustr(toxml(account.name)))
                budget_class['name'] = classification.name
                budget_class['class'] = classification.code
                count += 1
                content += vals + '''  <val>  </val></row> '''
        temp = {
            'name': budget_class['name'],
            'fiscalyear_ids': fiscalyear_ids,
            'num_year': num_year,
        }
        content += '''<row name="None" count="2" class="None" item="False"> ''' + self.create_xml_cols(
            cr, uid, ids, temp, 1, class_planed_amount, context=context)
        content += '''  <val> %s </val></row> ''' % (ustr(toxml(note)))
        temp = {
            'name': '',
            'fiscalyear_ids': fiscalyear_ids,
            'num_year': num_year,
        }
        content += '''<row name="None" count="2" class="False" item="False"> ''' + self.create_xml_cols(
            cr, uid, ids, temp, 2, years_planned_amount, context=context)
        content += '''  <val> %s </val></row> ''' % (ustr(toxml(note)))
        if flag == False:
            xml += self.generate_empty(cr,
                                       uid,
                                       ids,
                                       datas,
                                       header_xml,
                                       context=context)
        else:
            extra = False
            if num_year != 0: extra = True
            xml += '''<?xml version="1.0" encoding="UTF-8" ?>
            <report><page size='%s' type='%s' extra='%s'>
            %s
            %s
            %s
            </page></report>
            ''' % (self.size, self.type, extra, header_xml, dept_xml, content)
        return xml
예제 #19
0
    def generate_empty(self, cr, uid, ids, datas, header_xml, context=None):
        num_year = datas.get('form', {}).get('num_year', False)
        fiscalyear_obj = self.pool.get('account.fiscalyear')
        fiscalyear_id = datas.get('form', {}).get('first_fiscalyear', False)
        fiscalyear_ids = fiscalyear_obj.search(
            cr,
            uid, [('id', '!=', fiscalyear_id),
                  ('date_stop', '<',
                   fiscalyear_obj.browse(
                       cr, uid, fiscalyear_id, context=context).date_start)],
            limit=num_year,
            order='date_start desc',
            context=context)
        fiscalyear_obj = self.pool.get('account.fiscalyear')
        dept_xml = '''<datas>'''
        dept_xml += ''' <header name="%s" split="False"/> ''' % (ustr(
            toxml('التوصيات')))
        dept_xml += ''' <header name="%s" split="False"/> ''' % (ustr(
            toxml('نسبة التغيير')))
        dept_xml += ''' <header name="%s" split="False"/> ''' % (ustr(
            toxml("المصدق الحالي " + str(
                fiscalyear_obj.browse(cr, uid, fiscalyear_id,
                                      context=context).name))))
        fiscalyear_ids.reverse()
        if num_year != 0 and fiscalyear_ids != []:
            dept_xml += ''' <header2 name=" " split="False"/> '''
            for year in fiscalyear_obj.browse(cr,
                                              uid,
                                              fiscalyear_ids,
                                              context=context):
                dept_xml += ''' <header name="%s" split="True"/> ''' % (ustr(
                    toxml("المقترح للعام " + str(year.name))))
                dept_xml += ''' <header2 name=" " split="True"/> '''
            dept_xml += ''' <header2 name=" " split="False"/> '''
        else:
            dept_xml += ''' <header2 name=" " split="False"/> '''
        dept_xml += ''' <header name="%s" split="False"/> ''' % (ustr(
            toxml('بند الخصم')))
        dept_xml += '''</datas>'''
        length = len(fiscalyear_ids)
        if length == 0: length = 1
        factor = num_year
        page_size = 0
        if self.size == 'A3_landscape':
            page_size = 1572
        else:
            page_size = 786
        if num_year == 0 or fiscalyear_ids == []:
            row_width = page_size / 4
            dept_xml += '''<cols>160,70,80,90</cols>'''
            dept_xml += '''<splitcols>160,70,80,90</splitcols>'''
            dept_xml += '''<extracols>400</extracols>'''
            dept_xml += '''<cols2>%s%s</cols2>''' % (((str(
                (page_size) / (4)) + ',') * int(3)), row_width)
            dept_xml += '''<headercols>%s%s</headercols>''' % (((str(
                (page_size) / (4)) + ',') * int(3)), row_width)
            factor = 1
        elif num_year <= length:
            row_width = page_size / (4 + (num_year * 3))
            dept_xml += '''<cols>160,70,80,%s90</cols>''' % ((str(
                (3 * 70 * num_year) / num_year) + ',') * int(num_year))
            dept_xml += '''<splitcols>160,70,80,%s90</splitcols>''' % ((str(
                (3 * 70 * num_year) /
                (num_year * 3)) + ',') * int(num_year * 3))
            dept_xml += '''<extracols>310,%s90</extracols>''' % ((str(
                (3 * 70 * num_year) /
                (num_year * 3)) + ',') * int(num_year * 3))
            dept_xml += '''<cols2>%s%s%s</cols2>''' % (
                ((str(round(
                    ((page_size) / (4 + (num_year * 3))), 2)) + ',') * int(3)),
                ((str(round(((page_size) / (4 + (num_year * 3))) *
                            (3))) + ',') * int(num_year)), row_width)
            dept_xml += '''<headercols>%s,%s%s</headercols>''' % (
                (row_width * 3),
                ((str(round(
                    (page_size) /
                    (4 +
                     (num_year * 3)))) + ',') * int(num_year * 3)), row_width)
        else:
            row_width = page_size / (4 + (length * 3))
            dept_xml += '''<cols>160,70,80,%s90</cols>''' % ((str(
                (3 * 70 * length) / length) + ',') * int(length))
            dept_xml += '''<splitcols>160,70,80,%s90</splitcols>''' % ((str(
                (3 * 70 * length) / (length * 3)) + ',') * int(length * 3))
            dept_xml += '''<extracols>310,%s90</extracols>''' % ((str(
                (3 * 70 * length) / (length * 3)) + ',') * int(length * 3))
            dept_xml += '''<cols2>%s%s%s</cols2>''' % (
                ((str(round(
                    ((page_size) / (4 + (length * 3))), 2)) + ',') * int(3)),
                ((str(round(((page_size) / (4 + (length * 3))) *
                            (3))) + ',') * int(length)), row_width)
            dept_xml += '''<headercols>%s,%s%s</headercols>''' % (
                (row_width * 3), ((str(round(
                    (page_size) /
                    (4 + (length * 3)))) + ',') * int(length * 3)), row_width)
            factor = length

        content = ''' <row name="%s" count="1" class="True" item="True"> ''' % (
            ustr(toxml("صنف")))
        if num_year == 0 or fiscalyear_ids == []:
            for i in range(1, 5):
                if i == 1:
                    content += ''' <cols note="True" type="%s"> <val> %s </val></cols> ''' % (
                        'total', ustr(toxml(" ")))
                else:
                    content += ''' <cols note="False" type="%s"> <val> %s </val></cols> ''' % (
                        'total', ustr(toxml(" ")))
        else:
            for i in range(1, (factor * 3) + 5):
                if i == 1:
                    content += ''' <cols note="True" type="%s"> <val> %s </val></cols> ''' % (
                        'total', ustr(toxml(" ")))
                else:
                    content += ''' <cols note="False" type="%s"> <val> %s </val></cols> ''' % (
                        'total', ustr(toxml(" ")))
        content += '''  <val>  </val></row> '''
        extra = False
        if num_year != 0: extra = True
        xml = '''<?xml version="1.0" encoding="UTF-8" ?>
        <report><page size='%s' type='%s' extra='%s'>
        %s
        %s
        %s
        </page></report>
        ''' % (self.size, self.type, extra, header_xml, dept_xml, content)
        return xml
예제 #20
0
    def compare_budget(self, cr, uid, ids, datas, header_xml, context=None):
        account_obj = self.pool.get('account.account')
        period_pool = self.pool.get('account.period')
        budget_pool = self.pool.get('account.budget')
        budget_line_pool = self.pool.get('account.budget.lines')
        classification_obj = self.pool.get('account.budget.classification')
        move_line_pool = self.pool.get('account.move.line')
        fiscal_year_obj = self.pool.get('account.fiscalyear')
        account_chart = datas.get('form', {}).get('chart_account_id', [])
        analytic_chart = datas.get('form', {}).get('chart_analytic_account_id',
                                                   [])
        classification_ids = datas.get('form', {}).get('classification_ids',
                                                       False)
        fiscalyear_id = datas.get('form', {}).get('first_fiscalyear', False)
        select_quarter = datas.get('form', {}).get('quarter', False)
        current_periods = period_pool.search(
            cr, uid, [('fiscalyear_id', '=', fiscalyear_id)], context=context)
        analytic_child_ids = self._get_children_and_consol(
            cr, uid, analytic_chart, 'account.analytic.account', context)
        account_child_ids = self._get_children_and_consol(
            cr, uid, account_chart, 'account.account', context)
        general_account = self._sort_filter(cr,
                                            uid,
                                            account_child_ids,
                                            context=context)
        dept_xml = '''<datas>'''
        dept_xml += ''' <header name="%s" split="False"/> ''' % (ustr(
            toxml('المتبقي')))
        dept_xml += ''' <header name="%s" split="False"/> ''' % (ustr(
            toxml('الإجمالي')))
        vals = ''
        xml = ''

        date_start_quar = ''
        date_endss_quar = ''

        date_start_quar1 = ''
        date_endss_quar1 = ''

        date_start_quar2 = ''
        date_endss_quar2 = ''

        date_start_quar3 = ''
        date_endss_quar3 = ''
        diff = 0
        length = 1
        year = fiscal_year_obj.browse(cr, uid, fiscalyear_id,
                                      context=context).name
        flag = True
        if select_quarter == 'first':
            february = monthrange(int(year), 2)[1]
            date_start_quar1 = str(year) + "-" + '1' + "-" + "1"
            date_endss_quar1 = str(year) + "-" + '1' + "-" + "31"

            date_start_quar2 = str(year) + "-" + '2' + "-" + "1"
            date_endss_quar2 = str(year) + "-" + '2' + "-" + str(february)

            date_start_quar3 = str(year) + "-" + '3' + "-" + "1"
            date_endss_quar3 = str(year) + "-" + '3' + "-" + "31"

            dept_xml += ''' <header name="%s"/> ''' % (ustr(toxml('مارس')))
            dept_xml += ''' <header name="%s"/> ''' % (ustr(toxml('فبراير')))
            dept_xml += ''' <header name="%s"/> ''' % (ustr(toxml('يناير')))
            flag = False
            length += 3
        if select_quarter == 'second':
            month_strats = 1
            month_end = 3
            date_start_quar = str(year) + "-" + str(month_strats) + "-" + "1"
            date_endss_quar = str(year) + "-" + str(month_end) + "-" + "31"

            date_start_quar1 = str(year) + "-" + '4' + "-" + "1"
            date_endss_quar1 = str(year) + "-" + '4' + "-" + "30"

            date_start_quar2 = str(year) + "-" + '5' + "-" + "1"
            date_endss_quar2 = str(year) + "-" + '5' + "-" + "31"

            date_start_quar3 = str(year) + "-" + '6' + "-" + "1"
            date_endss_quar3 = str(year) + "-" + '6' + "-" + "30"

            dept_xml += ''' <header name="%s"/> ''' % (ustr(toxml('يونيو')))
            dept_xml += ''' <header name="%s"/> ''' % (ustr(toxml('مايو')))
            dept_xml += ''' <header name="%s"/> ''' % (ustr(toxml('أبريل')))
            dept_xml += ''' <header name="%s"/> ''' % (ustr(
                toxml('الربع الأول')))

            length += 4
        if select_quarter == 'third':
            month_strats = 1
            month_end = 6
            date_start_quar = str(year) + "-" + str(month_strats) + "-" + "1"
            date_endss_quar = str(year) + "-" + str(month_end) + "-" + "30"

            date_start_quar1 = str(year) + "-" + '7' + "-" + "1"
            date_endss_quar1 = str(year) + "-" + '7' + "-" + "31"

            date_start_quar2 = str(year) + "-" + '8' + "-" + "1"
            date_endss_quar2 = str(year) + "-" + '8' + "-" + "31"

            date_start_quar3 = str(year) + "-" + '9' + "-" + "1"
            date_endss_quar3 = str(year) + "-" + '9' + "-" + "30"

            dept_xml += ''' <header name="%s"/> ''' % (ustr(toxml('سبتمبر')))
            dept_xml += ''' <header name="%s"/> ''' % (ustr(toxml('أغسطس')))
            dept_xml += ''' <header name="%s"/> ''' % (ustr(toxml('يوليو')))
            dept_xml += ''' <header name="%s"/> ''' % (ustr(
                toxml('الربع الثاني')))

            length += 4
        if select_quarter == 'fourth':
            month_strats = 1
            month_end = 9
            date_start_quar = str(year) + "-" + str(month_strats) + "-" + "1"
            date_endss_quar = str(year) + "-" + str(month_end) + "-" + "30"

            date_start_quar1 = str(year) + "-" + '10' + "-" + "1"
            date_endss_quar1 = str(year) + "-" + '10' + "-" + "31"

            date_start_quar2 = str(year) + "-" + '11' + "-" + "1"
            date_endss_quar2 = str(year) + "-" + '11' + "-" + "30"

            date_start_quar3 = str(year) + "-" + '12' + "-" + "1"
            date_endss_quar3 = str(year) + "-" + '12' + "-" + "31"

            dept_xml += ''' <header name="%s"/> ''' % (ustr(toxml('ديسمبر')))
            dept_xml += ''' <header name="%s"/> ''' % (ustr(toxml('نوفمبر')))
            dept_xml += ''' <header name="%s"/> ''' % (ustr(toxml('أكتوبر')))
            dept_xml += ''' <header name="%s"/> ''' % (ustr(
                toxml('الربع الثالث')))

            length += 4
        dept_xml += ''' <header name="%s" split="False"/> ''' % (ustr(
            toxml("الإعتماد")))
        dept_xml += ''' <header name="%s" split="False"/> ''' % (ustr(
            toxml('البند')))
        dept_xml += ''' <header name="%s" split="False"/> ''' % (ustr(
            toxml('الرمز')))
        dept_xml += '''</datas>'''
        col = ((str((80 * length) / length) + ',') * int(length - 1))
        dept_xml += '''<cols>80,80,%s80,100,80</cols>''' % (str(col))
        result = []
        total = 0
        total_final = 0
        total_quarter = 0
        total_quarter1 = 0
        total_quarter2 = 0
        total_quarter3 = 0
        total_of_total_final = 0
        total_residual_final = 0
        content = ''
        for classification in classification_obj.browse(cr,
                                                        uid,
                                                        classification_ids,
                                                        context=context):
            class_name = (u' %s' % (classification.name))
            account_total = 0
            account_balance = 0
            account_balance1 = 0
            account_balance2 = 0
            account_balance3 = 0
            total_of_total = 0
            total_residual = 0
            if self.type_selection == 'detail':
                content += ''' <row item="False"> '''
                for i in range(1, 5 + length):
                    if i == length + 3:
                        content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
                            'total', ustr(toxml(class_name)))
                    elif i == length + 4:
                        content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
                            'total', ustr(toxml(classification.code)))
                    else:
                        content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
                            'total', ustr(toxml(" ")))
                content += ''' </row> '''
            #For order account by code
            account_ids = [
                account.id for account in classification.account_ids
            ]
            account_ids = account_obj.search(cr,
                                             uid, [('id', 'in', account_ids)],
                                             order='code')
            aggregate_budget = []
            for account in account_obj.browse(cr, uid, account_ids, context):
                #for account in classification.account_ids:
                total_class = 0
                residual = 0
                balance = 0
                balance1 = 0
                balance2 = 0
                balance3 = 0
                current_quarter_lines = budget_line_pool.search(
                    cr, uid,
                    [('period_id', 'in', current_periods),
                     ('analytic_account_id', 'in', analytic_child_ids),
                     ('general_account_id', '=', account.id)])
                if current_quarter_lines:
                    quarter_amount = 0
                    for line in budget_line_pool.browse(cr,
                                                        uid,
                                                        current_quarter_lines,
                                                        context=context):
                        bl = 0
                        bl1 = 0
                        bl2 = 0
                        bl3 = 0
                        planed = line.planned_amount
                        sign = line.general_account_id.user_type.report_type in (
                            'income', 'liability') and -1 or 1
                        if flag:
                            move = move_line_pool.search(
                                cr,
                                uid, [('analytic_account_id', 'in',
                                       analytic_child_ids),
                                      ('date', '>=', date_start_quar),
                                      ('date', '<=', date_endss_quar),
                                      ('account_id', '=',
                                       line.general_account_id.id),
                                      ('state', '=', 'valid')],
                                context=context)
                            for moves in move_line_pool.browse(
                                    cr, uid, move, context=context):
                                bl += moves.debit - moves.credit
                            balance = sign * bl

                        move1 = move_line_pool.search(
                            cr,
                            uid,
                            [('analytic_account_id', 'in', analytic_child_ids),
                             ('date', '>=', date_start_quar1),
                             ('date', '<=', date_endss_quar1),
                             ('account_id', '=', line.general_account_id.id),
                             ('state', '=', 'valid')],
                            context=context)
                        move2 = move_line_pool.search(
                            cr,
                            uid,
                            [('analytic_account_id', 'in', analytic_child_ids),
                             ('date', '>=', date_start_quar2),
                             ('date', '<=', date_endss_quar2),
                             ('account_id', '=', line.general_account_id.id),
                             ('state', '=', 'valid')],
                            context=context)
                        move3 = move_line_pool.search(
                            cr,
                            uid,
                            [('analytic_account_id', 'in', analytic_child_ids),
                             ('date', '>=', date_start_quar3),
                             ('date', '<=', date_endss_quar3),
                             ('account_id', '=', line.general_account_id.id),
                             ('state', '=', 'valid')],
                            context=context)
                        for moves1 in move_line_pool.browse(cr,
                                                            uid,
                                                            move1,
                                                            context=context):
                            bl1 += moves1.debit - moves1.credit

                        for moves2 in move_line_pool.browse(cr,
                                                            uid,
                                                            move2,
                                                            context=context):
                            bl2 += moves2.debit - moves2.credit

                        for moves3 in move_line_pool.browse(cr,
                                                            uid,
                                                            move3,
                                                            context=context):
                            bl3 += moves3.debit - moves3.credit

                        balance1 = sign * bl1
                        balance2 = sign * bl2
                        balance3 = sign * bl3
                        total_class += round(planed, 2)
                total = balance + balance1 + balance2 + balance3
                residual = total_class - total
                if self.type_selection == 'detail':
                    content += ''' <row item="False"> '''
                    content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
                        'detail', ustr(toxml('{:,.2f}'.format(residual))))
                    content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
                        'detail', ustr(toxml('{:,.2f}'.format(total))))
                    content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
                        'detail', ustr(toxml('{:,.2f}'.format(balance3))))
                    content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
                        'detail', ustr(toxml('{:,.2f}'.format(balance2))))
                    content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
                        'detail', ustr(toxml('{:,.2f}'.format(balance1))))
                    if flag:
                        content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
                            'detail', ustr(toxml('{:,.2f}'.format(balance))))
                    content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
                        'detail', ustr(toxml('{:,.2f}'.format(total_class))))
                    content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
                        'detail', ustr(toxml(account.name)))
                    content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
                        'detail', ustr(toxml(account.code)))
                    content += ''' </row> '''
                else:
                    aggregate_budget.append({
                        'parent_code': account.parent_id.code,
                        'parent_name': account.parent_id.name,
                        'total_class': total_class,
                        'balance': balance,
                        'balance1': balance1,
                        'balance2': balance2,
                        'balance3': balance3,
                        'total': total,
                        'residual': residual,
                    })
                #Total Classification
                account_total += total_class
                account_balance += balance
                account_balance1 += balance1
                account_balance2 += balance2
                account_balance3 += balance3
                total_of_total += total
                total_residual += residual
            if self.type_selection == 'total':
                aggregate_budget.sort(key=itemgetter("parent_code"))
                aggregate_budget_temp = []
                aggregate_budget_final = []
                for key, group in itertools.groupby(
                        aggregate_budget, lambda item: item["parent_code"]):
                    aggregate_budget_temp.append([item for item in group])
                for record in aggregate_budget_temp:
                    aggregate_budget_final.append({
                        'parent_name':
                        record[0]['parent_name'],
                        'parent_code':
                        record[0]['parent_code'],
                        'total_class':
                        sum([item["total_class"] for item in record]),
                        'balance':
                        sum([item["balance"] for item in record]),
                        'balance1':
                        sum([item["balance1"] for item in record]),
                        'balance2':
                        sum([item["balance2"] for item in record]),
                        'balance3':
                        sum([item["balance3"] for item in record]),
                        'total':
                        sum([item["total"] for item in record]),
                        'residual':
                        sum([item["residual"] for item in record]),
                    })

                for record in aggregate_budget_final:
                    content += ''' <row item="False"> '''
                    content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
                        'detail',
                        ustr(toxml('{:,.2f}'.format(record['residual']))))
                    content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
                        'detail', ustr(toxml('{:,.2f}'.format(
                            record['total']))))
                    content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
                        'detail',
                        ustr(toxml('{:,.2f}'.format(record['balance3']))))
                    content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
                        'detail',
                        ustr(toxml('{:,.2f}'.format(record['balance2']))))
                    content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
                        'detail',
                        ustr(toxml('{:,.2f}'.format(record['balance1']))))
                    if flag:
                        content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
                            'detail',
                            ustr(toxml('{:,.2f}'.format(record['balance']))))
                    content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
                        'detail',
                        ustr(toxml('{:,.2f}'.format(record['total_class']))))
                    content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
                        'detail', ustr(toxml(record['parent_name'])))
                    content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
                        'detail', ustr(toxml(record['parent_code'])))
                    content += ''' </row> '''

            #Totals Final
            total_final += account_total
            total_quarter += account_balance
            total_quarter1 += account_balance1
            total_quarter2 += account_balance2
            total_quarter3 += account_balance3
            total_of_total_final += total_of_total
            total_residual_final += total_residual
            extra = ' '
            tempural = "إجمالي " + extra
            classes = u'' + tempural.decode(
                'utf-8') + u'' + classification.name
            content += ''' <row> '''
            content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
                'total', ustr(toxml('{:,.2f}'.format(total_residual))))
            content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
                'total', ustr(toxml('{:,.2f}'.format(total_of_total))))
            content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
                'total', ustr(toxml('{:,.2f}'.format(account_balance3))))
            content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
                'total', ustr(toxml('{:,.2f}'.format(account_balance2))))
            content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
                'total', ustr(toxml('{:,.2f}'.format(account_balance1))))
            if flag:
                content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
                    'total', ustr(toxml('{:,.2f}'.format(account_balance))))
            content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
                'total', ustr(toxml('{:,.2f}'.format(account_total))))
            content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
                "total", ustr(toxml(classes)))
            content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
                "total", ustr(toxml('')))
            content += ''' </row> '''
        extra = 'الكلي'
        tempural = "الإجمالي " + extra
        classes_totals = u'' + tempural.decode('utf-8') + u''
        content += ''' <row> '''
        content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
            'total', ustr(toxml('{:,.2f}'.format(total_residual_final))))
        content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
            'total', ustr(toxml('{:,.2f}'.format(total_of_total_final))))
        content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
            'total', ustr(toxml('{:,.2f}'.format(total_quarter3))))
        content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
            'total', ustr(toxml('{:,.2f}'.format(total_quarter2))))
        content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
            'total', ustr(toxml('{:,.2f}'.format(total_quarter1))))
        if flag:
            content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
                'total', ustr(toxml('{:,.2f}'.format(total_quarter))))
        content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
            'total', ustr(toxml('{:,.2f}'.format(total_final))))
        content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
            "total", ustr(toxml(classes_totals)))
        content += ''' <cols type="%s"> <val> %s </val></cols> ''' % (
            "total", ustr(toxml('')))
        content += ''' </row> '''

        xml += '''<?xml version="1.0" encoding="UTF-8" ?>
        <report><page size='%s' type='%s'>
        %s
        %s
        %s
        </page></report>
        ''' % (self.size, self.type, header_xml, dept_xml, content)
        return xml
예제 #21
0
    def create_xml(self, cr, uid, ids, datas, context):
        service = netsvc.LocalService('object_proxy')

        month = DateTime.DateTime(datas['form']['year'],
                                  datas['form']['month'], 1)

        user_xml = [
            '<month>%s</month>' % month2name[month.month],
            '<year>%s</year>' % month.year
        ]

        for employee_id in ids:
            emp = service.execute(cr.dbname, uid, 'hr.employee', 'read',
                                  [employee_id])[0]
            stop, days_xml = False, []
            user_repr = '''
            <user>
              <name>%s</name>
              %%s
            </user>
            ''' % (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'), employee_id))
                attendences = cr.dictfetchall()
                wh = 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
                for att in attendences:
                    dt = DateTime.strptime(att['name'], '%Y-%m-%d %H:%M:%S')
                    if att['action'] == 'sign_out':
                        wh += (dt - ldt).hours
                    ldt = dt

                # Week xml representation
                wh = hour2str(wh)
                today_xml = '<day num="%s"><wh>%s</wh></day>' % (
                    (today - month).days + 1, wh)
                days_xml.append(today_xml)
                today, tomor = tomor, tomor + one_day

            user_xml.append(user_repr % '\n'.join(days_xml))

        xml = '''<?xml version="1.0" encoding="UTF-8" ?>
        <report>
        %s
        </report>
        ''' % '\n'.join(user_xml)

        return xml
예제 #22
0
    def create_xml(self, cr, uid, ids, datas, context=None):
        obj_emp = pooler.get_pool(cr.dbname).get('hr.employee')

        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

        user_xml = []

        for employee_id in 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>
            ''' % 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) + (
                                    (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.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>')
                if len(week_repr) > 21:  # 21 = minimal length of week_repr
                    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
        </report>
        ''' % '\n'.join(user_xml)
        return self.post_process_xml_data(cr, uid, xml, context)
예제 #23
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")), 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
예제 #24
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 = context.get('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, []
                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':
                            wh += (dt - ldt).seconds / 60 / 60
                        else:
                            ldt = dt
                    # Week xml representation


#                    wh = hour2str(wh)
                    today_xml = '<day num="%s"><wh>%s</wh></day>' % (
                        (today - month).days + 1, round(wh, 2))
                    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('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)

        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
    def create_xml(self, cr, uid, ids, datas, context=None):
        obj_emp = pooler.get_pool(cr.dbname).get('hr.employee')
        
        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

        user_xml = []

        for employee_id in 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>
            ''' % 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) + ((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.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>')
                if len(week_repr) > 21: # 21 = minimal length of week_repr
                    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
        </report>
        ''' % '\n'.join(user_xml)
        return self.post_process_xml_data(cr, uid, xml, context)