コード例 #1
0
 def _get_archive_groups(self, model, domain=None, fields=None,
                         groupby="create_date", order="create_date desc"):
     if not model:
         return []
     if domain is None:
         domain = []
     if fields is None:
         fields = ['name', 'create_date']
     groups = []
     for group in request.env[model].sudo().read_group(
             domain, fields=fields, groupby=groupby, orderby=order):
         label = group[groupby]
         date_begin = date_end = None
         for leaf in group["__domain"]:
             if leaf[0] == groupby:
                 if leaf[1] == ">=":
                     date_begin = leaf[2]
                 elif leaf[1] == "<":
                     date_end = leaf[2]
         groups.append({
             'date_begin': Date.to_string(Date.from_string(date_begin)),
             'date_end': Date.to_string(Date.from_string(date_end)),
             'name': label,
             'item_count': group[groupby + '_count']
         })
     return groups
コード例 #2
0
 def _inverse_age(self):
     self._check_release_date()
     for perizia in self.filtered('giorni_consegna'):
         d = fDate.from_string(
             perizia.inizio_operazioni) + td(days=perizia.giorni_consegna)
         # delta = fDate.from_string(perizia.inizio_operazioni) + perizia.giorni_consegna
         perizia.fine_operazioni = fDate.to_string(d)
コード例 #3
0
ファイル: main.py プロジェクト: ruben-algios/event
    def days_with_events(self, start, end):
        """Let visitors know when are there going to be any events.

        :param start string:
            Search events from that date.

        :param end string:
            Search events until that date.
        """
        events = request.env["event.event"].search([
            "|",
            ("date_begin", "<=", end),
            ("date_end", ">=", start),
        ])
        days = set()
        one_day = timedelta(days=1)
        start = Date.from_string(start)
        end = Date.from_string(end)
        for event in events:
            now = max(Date.from_string(event.date_begin), start)
            event_end = min(Date.from_string(event.date_end), end)
            while now <= event_end:
                days.add(now)
                now += one_day
        return [Date.to_string(day) for day in days]
コード例 #4
0
 def _get_archive_groups(self, model, domain=None, fields=None,
                         groupby="create_date", order="create_date desc"):
     if not model:
         return []
     if domain is None:
         domain = []
     if fields is None:
         fields = ['name', 'create_date']
     groups = []
     for group in request.env[model].read_group(
             domain, fields=fields, groupby=groupby, orderby=order):
         label = group[groupby]
         date_begin = date_end = None
         for leaf in group["__domain"]:
             if leaf[0] == groupby:
                 if leaf[1] == ">=":
                     date_begin = leaf[2]
                 elif leaf[1] == "<":
                     date_end = leaf[2]
         groups.append({
             'date_begin': Date.to_string(Date.from_string(date_begin)),
             'date_end': Date.to_string(Date.from_string(date_end)),
             'name': label,
             'item_count': group[groupby + '_count']
         })
     return groups
コード例 #5
0
 def _compute_age(self):
     today = fDate.from_string(fDate.today())
     self._check_release_date()
     for perizia in self.filtered('fine_operazioni'):
         delta = fDate.from_string(
             perizia.fine_operazioni) - fDate.from_string(
                 perizia.inizio_operazioni)
         # delta = fDate.from_string(days)
         perizia.giorni_consegna = delta.days
コード例 #6
0
 def setUp(self):
     super(TestBarcodeNoConsuSingleAttr, self).setUp()
     self.product = self.env['product.product'].create({
         'name':
         'bbc_stock_bom_product',
         'type':
         'consu',
         'default_code':
         'product_barcode'
     })
     self.attr = self.env['product.attribute'].create({
         'name':
         'Attribute1',
         'value_ids': [(0, 0, {
             'name': 'Attr1 - Val1'
         })],
     })
     self.picking = self.PickingObj.create({
         'partner_id':
         self.partner_delta_id,
         'picking_type_id':
         self.picking_type_in
     })
     self.MoveObj.create({
         'name': self.product.name,
         'product_id': self.product.id,
         'product_uom_qty': 1,
         'product_uom': self.product.uom_id.id,
         'picking_id': self.picking.id,
         'location_id': self.supplier_location,
         'location_dest_id': self.stock_location,
         'date_expected': Date.context_today(self.env.user),
     })
     self.picking.action_confirm()
コード例 #7
0
ファイル: controllers.py プロジェクト: DudhatShivam/bestja
    def projects_list(self):
        user_bank_id = None
        if not http.request.env.user.sudo(http.request.env.user). \
                user_has_groups(
                    'bestja_project_hierarchy.managers_level0,bestja_project_hierarchy.managers_level1'
                ):
            user_organization = http.request.env['organization'].sudo().search(
                [
                    ('level', '=', 2),
                    '|',  # noqa
                    ('coordinator', '=', http.request.env.user.id),
                    ('projects.manager', '=', http.request.env.user.id)
                ])
            if not user_organization:
                return exceptions.Forbidden()
            user_bank_id = user_organization.parent.id

        projects = http.request.env['bestja.project'].sudo().search(
            [
                ('organization_level', '=', 0),
                ('use_detailed_reports', '=', True),
                ('date_start', '<=', Date.today()),
            ],
            order='date_start desc')

        return http.request.render('bestja_detailed_reports.projects_list', {
            'projects': projects,
            'user_bank_id': user_bank_id,
        })
コード例 #8
0
ファイル: controllers.py プロジェクト: EE/bestja
    def projects_list(self):
        user_bank_id = None
        if not http.request.env.user.sudo(http.request.env.user). \
                user_has_groups(
                    'bestja_project_hierarchy.managers_level0,bestja_project_hierarchy.managers_level1'
                ):
            user_organization = http.request.env['organization'].sudo().search([
                ('level', '=', 2),
                '|',  # noqa
                    ('coordinator', '=', http.request.env.user.id),
                    ('projects.manager', '=', http.request.env.user.id)
            ])
            if not user_organization:
                return exceptions.Forbidden()
            user_bank_id = user_organization.parent.id

        projects = http.request.env['bestja.project'].sudo().search([
            ('organization_level', '=', 0),
            ('use_detailed_reports', '=', True),
            ('date_start', '<=', Date.today()),
        ], order='date_start desc')

        return http.request.render('bestja_detailed_reports.projects_list', {
            'projects': projects,
            'user_bank_id': user_bank_id,
        })
コード例 #9
0
ファイル: main.py プロジェクト: ruben-algios/event
    def events_for_day(self, day=None, limit=None):
        """List events for a given day.

        :param day string:
            Date in a string. If ``None``, we'll search for upcoming events
            from today up to specified limit.

        :param limit int:
            How many results to return.
        """
        ref = day or Date.to_string(date.today())
        domain = [
            ("date_end", ">=", ref),
        ]
        if day:
            domain.append(("date_begin", "<=", ref))
        return request.env["event.event"].search_read(
            domain=domain,
            limit=limit,
            fields=[
                "date_begin",
                "name",
                "event_type_id",
                "website_published",
                "website_url",
            ],
        )
コード例 #10
0
    def get_absent_on(self, date=None):
        self.ensure_one()
        if not date:
            return None

        querying_day = date
        if isinstance(date, datetime.date):
            querying_day = Date.to_string(date)

        absent_type = self.env.ref("hr_sf.absent_holidays_status")
        absent_type_id = absent_type.id

        for holiday in self.holidays_ids:
            if not holiday.date_from or not holiday.date_to:
                continue
            if holiday.holiday_status_id.id != absent_type_id:
                continue

            if not all((holiday.morning_start_work_time,
                        holiday.morning_end_work_time,
                        holiday.afternoon_start_work_time,
                        holiday.afternoon_end_work_time)):
                return None

            dt_the_day_morning_start_work_time = datetime.datetime.strptime(
                    "%s %s" % (querying_day, holiday.morning_start_work_time), DEFAULT_SERVER_DATETIME_FORMAT)
            dt_the_day_morning_end_work_time = datetime.datetime.strptime(
                    "%s %s" % (querying_day, holiday.morning_end_work_time), DEFAULT_SERVER_DATETIME_FORMAT)
            dt_the_day_afternoon_start_work_time = datetime.datetime.strptime(
                    "%s %s" % (querying_day, holiday.afternoon_start_work_time), DEFAULT_SERVER_DATETIME_FORMAT)
            dt_the_day_afternoon_end_work_time = datetime.datetime.strptime(
                    "%s %s" % (querying_day, holiday.afternoon_end_work_time), DEFAULT_SERVER_DATETIME_FORMAT)

            dt_holiday_from = Datetime.from_string(holiday.date_from) + datetime.timedelta(hours=8)
            dt_holiday_to = Datetime.from_string(holiday.date_to) + datetime.timedelta(hours=8)

            # deal with morning first
            dt_cal_start = max(dt_the_day_morning_start_work_time, dt_holiday_from)
            dt_cal_start = min(dt_cal_start, dt_the_day_morning_end_work_time)

            dt_cal_end = min(dt_the_day_morning_end_work_time, dt_holiday_to)
            dt_cal_end = max(dt_cal_end, dt_the_day_morning_start_work_time)

            if dt_cal_end > dt_cal_start:
                return absent_type.name

            # then deal with afternoon first
            dt_cal_start = max(dt_the_day_afternoon_start_work_time, dt_holiday_from)
            dt_cal_start = min(dt_cal_start, dt_the_day_afternoon_end_work_time)

            dt_cal_end = min(dt_the_day_afternoon_end_work_time, dt_holiday_to)
            dt_cal_end = max(dt_cal_end, dt_the_day_afternoon_start_work_time)

            if dt_cal_end > dt_cal_start:
                return absent_type.name
コード例 #11
0
    def test_02_max_date(self):
        next_year_apr = '%s-04-01' % (int(self.today[:4]) + 1)
        delay = Date.to_string(
            Date.from_string(self.today) + timedelta(days=self.seller_delay))

        """ Test if max_incoming_stock_date is the date today plus delay
        in case there is no stock of the product. """
        self.assertEqual(self.product.max_incoming_stock_date, delay)
        self.assertEqual(self.bom_product.max_incoming_stock_date, delay)

        picking_in = self.PickingObj.create({
            'partner_id': self.partner_delta_id,
            'picking_type_id': self.picking_type_in})
        self.MoveObj.create({
            'name': self.product.name,
            'product_id': self.product.id,
            'product_uom_qty': 1,
            'product_uom': self.product.uom_id.id,
            'picking_id': picking_in.id,
            'location_id': self.supplier_location,
            'location_dest_id': self.stock_location,
            'date_expected': next_year_apr,
        })

        """ Test if date_expected is the max_incoming_stock_date
        in case there are incoming products. """
        picking_in.action_confirm()
        self.product.refresh()
        self.assertEqual(self.product.max_incoming_stock_date, next_year_apr)
        self.assertEqual(
            self.bom_product.max_incoming_stock_date, next_year_apr)

        """ Test if the max_incoming_stock_date is the date today plus
        delay in case there is stock of the product. """
        picking_in.action_done()
        self.product.refresh()
        self.assertEqual(self.product.max_incoming_stock_date, delay)
        self.assertEqual(
            self.bom_product.max_incoming_stock_date, delay)
コード例 #12
0
	def write(self,cr,uid,ids,vals,context=None):
        	return_value = super(sale_order, self).write(cr, uid, ids, vals, context)
		if 'state' in vals.keys():
			if vals['state'] in ['progress','manual']:
				# stage_id = self.pool.get('crm.case.stage').search(cr,uid,[('name','=','Won - Order placed')])
				stage_id = self.pool.get('crm.case.stage').search(cr,uid,[('sequence','=',110)])
				if stage_id:
					for order_id in ids:
						order = self.pool.get('sale.order').browse(cr,uid,order_id)
						opportunity_id = order.opportunity_id.id
						if opportunity_id:
							vals_opp = {
								'stage_id': stage_id[0]
								}
							return_id = self.pool.get('crm.lead').write(cr,uid,opportunity_id,vals_opp)
		if 'order_line' in vals.keys():
			lines = vals['order_line']
			for order_line in lines:
				if not order_line[2]:
					continue
				if 'order_id' not in order_line[2].keys():
					continue
				order_id = order_line[2]['order_id']
				order = self.pool.get('sale.order').browse(cr,uid,order_id)
				product_id = order_line[2]['product_id']
				product = self.pool.get('product.product').browse(cr,uid,product_id)
				if not product.supplier_id:
					return return_value
				partner = self.pool.get('res.partner').browse(cr,uid,product.supplier_id.id)
				if partner.country_id.holidays_ids:
					for holiday in partner.country_id.holidays_ids:
					#if holiday.date > vals['date_order'][:10]:
                                	        _logger.debug('Checking holiday %s %s against %s', holiday.date, type(holiday.date), order.date_order)
                                        	order_date =  order.date_order
	                                        holiday_date = newdate.from_string(holiday.date)
						if type(order_date) == str:
							 order_date = datetime.strptime(order.date_order, '%Y-%m-%d %H:%M:%S').date()
                        	                if holiday_date > order_date:
							holiday_id = self.pool.get('sale.order.holidays').search(cr,uid,\
								[('order_id','=',order_id),('name','=',holiday.holiday_name),\
								 ('country_id','=',partner.country_id.id),\
								 ('date','=', holiday.date)])
							if not holiday_id:
								vals_holiday = {
									'order_id': order_id,
									'country_id': partner.country_id.id,
									'name': holiday.holiday_name,
									'date': holiday.date,
									}
								return_holiday = self.pool.get('sale.order.holidays').create(cr,uid,vals_holiday)
		return return_value
コード例 #13
0
    def setUp(self):
        super(TestSalesPrice, self).setUp()
        attribute = self.env['product.attribute'].create({
            'name':
            'sales_price_attribute',
        })
        self.red = self.env['product.attribute.value'].create({
            'name':
            'red',
            'attribute_id':
            attribute.id,
        })
        self.blue = self.env['product.attribute.value'].create({
            'name':
            'blue',
            'attribute_id':
            attribute.id,
        })

        # Product is created with a list price of 75.95
        self.template = self.env['product.template'].create({
            'name':
            'bbc_stock_bom_product',
            'type':
            'product',
            'list_price':
            75.95,
            'attribute_line_ids': [(0, 0, {
                'attribute_id':
                attribute.id,
                'value_ids': [(6, 0, attribute.value_ids.ids)],
            })],
        })
        self.env['product.attribute.price'].create({
            'product_tmpl_id':
            self.template.id,
            'value_id':
            self.blue.id,
            'price_extra':
            -20,
        })
        self.today = Date.context_today(self.env.user)
        self.pricelist_version = self.env['product.pricelist.version'].search(
            [
                '|', ('date_start', '=', False),
                ('date_start', '<=', self.today), '|',
                ('date_end', '=', False), ('date_end', '>=', self.today),
                ('pricelist_id.type', '=', 'sale')
            ],
            limit=1)
        self.pricelist = self.pricelist_version.pricelist_id
コード例 #14
0
 def create_order(self, partner, shipping):
     return self.env['sale.order'].create({
         'partner_id':
         partner.id,
         'partner_invoice_id':
         partner.id,
         'partner_shipping_id':
         shipping.id,
         'user_id':
         self.env.user.id,
         'pricelist_id':
         partner.property_product_pricelist.id,
         'date_order':
         Date.context_today(self.env.user),
     })
コード例 #15
0
	def create(self,cr,uid,vals,context=None):
        	return_value = super(sale_order, self).create(cr, uid, vals, context)
		if 'partner_id' in vals.keys():
			partner = self.pool.get('res.partner').browse(cr,uid,vals['partner_id'])
			if partner.country_id.holidays_ids and 'date_order' in vals.keys():
				for holiday in partner.country_id.holidays_ids:
				#if holiday.date > vals['date_order'][:10]:
                                        _logger.debug('Checking holiday %s %s against %s', holiday.date, type(holiday.date), vals['date_order'])
                                        order_date = vals['date_order']
                                        holiday_date = newdate.from_string(holiday.date)
					if type(order_date) == str:
						 order_date = datetime.strptime(vals['date_order'], '%Y-%m-%d %H:%M:%S').date()
                                        if holiday_date > order_date:
						vals_holiday = {
							'order_id': return_value,
							'country_id': partner.country_id.id,
							'name': holiday.holiday_name,
							'date': holiday.date,
							}
						return_holiday = self.pool.get('sale.order.holidays').create(cr,uid,vals_holiday)
		return return_value
コード例 #16
0
 def setUp(self):
     super(TestMaxDate, self).setUp()
     self.product = self.env['product.product'].create({
         'name': 'test max date',
         'type': 'product',
     })
     self.seller_delay = 5
     self.env['product.supplierinfo'].create({
         'name': self.partner_delta_id,
         'delay': self.seller_delay,
         'product_tmpl_id': self.product.product_tmpl_id.id,
     })
     self.bom_product = self.env['product.product'].create({
         'name': 'test max date bom',
         'type': 'consu',
     })
     self.env['mrp.bom'].create({
         'product_id': self.bom_product.id,
         'product_tmpl_id': self.bom_product.product_tmpl_id.id,
         'bom_line_ids': [(0, 0, {
             'product_id': self.product.id})],
     })
     self.today = Date.context_today(self.env.user)
コード例 #17
0
class Lectures(Model):
    _name = 'academy.lectures'
    _order = 'date ASC'

    name = Char(required=True, string="Name")
    date = Date(required=True, string="Date")
コード例 #18
0
 def _inverse_age(self):
     today = fDate.from_string(fDate.today())
     for book in self.filtered('date_release'):
         d = td(days=book.age_days) - today
         book.date_release = fDate.to_string(d)
コード例 #19
0
    def genera_grafica(self, start,stop):
        """ Genera imagen de la grafica de los sensores """

        f_start = Date.from_string(start)
        f_stop  = Date.from_string(stop)
        delta   = f_stop-f_start
        if delta.days <=30:
            return False

        obj_company = self.env['res.company'].sudo()
        company_ids = self._get_companys()
        company_matriz = obj_company.search([('id', 'not in', company_ids.split(','))], limit=1)
        atrace = []
        annotations = []

        for company_id in company_ids.split(","):
            name_company = obj_company.browse([int(company_id)]).name

            xy = []
            regist = self._get_punt_company_mes(start,stop,int(company_id))
            valores = []
            mes_x = []
            puntua_y = []
            i = 0
            for row in regist:
                mes_x.append(row['mes'])
                puntua_y.append(round(row['puntua'], 2))
                valores.append([(row['mes']), round(row['puntua'], 2)])


            if len(valores) != 0:
                max_idx = np.argmax(puntua_y)
                max_valy = puntua_y[max_idx]
                max_valx = mes_x[max_idx]
                min_idx = np.argmin(puntua_y)
                min_valy = puntua_y[min_idx]
                min_valx = mes_x[min_idx]

                media_y = round(np.average(puntua_y), 2)
                amedia_y = np.empty(len(mes_x))
                amedia_y.fill(media_y)

                atrace.append(go.Scatter(
                    x=mes_x,
                    y=amedia_y,
                    line=dict(width=0.5),
                    name=" Media %s " % name_company,
                    ))

                atrace.append(go.Scatter(
                    x=mes_x,
                    y=puntua_y,
                    name=name_company,
                    ))

                annotations.append(dict(x=min_valx, y=min_valy,
                                        xanchor='right', yanchor='middle',
                                        text='Min {}'.format(min_valy),
                                        font=dict(family='Arial',
                                                  size=16,
                                                  color='rgb(182,128, 64)', ),
                                        showarrow=True, ))
                annotations.append(dict(x=max_valx, y=max_valy,
                                        xanchor='right', yanchor='middle',
                                        text='Max {}'.format(max_valy),
                                        font=dict(family='Arial',
                                                  size=16,
                                                  color='rgb(182,128, 64)', ),
                                        showarrow=True, ))

                annotations.append(dict(xref='paper', x=max_valx, y=media_y,
                                        xanchor='right', yanchor='middle',
                                        text='Media {}'.format(media_y) ,
                                        font=dict(family='Arial',
                                                  size=16,
                                                  color='rgb(182,128, 64)', ),
                                        showarrow=True, ))


            else:
                maxpunt = 0
                minpunt = 0

        annotations.append(dict(xref='paper', yref='paper', x=20, y=30,
                                xanchor='center', yanchor='center',
                                text="%s" % company_matriz.name,
                                font=dict(family='Arial',
                                          size=12,
                                          color='rgb(37,37,37)'),
                                showarrow=False, ))

        xaxis = dict(
            title='Meses',
            showline=True,
            showgrid=True,
            showticklabels=True,
            nticks=24,
            linecolor='rgb(204, 204, 204)',
            linewidth=2,
            autotick=True,
            ticks='outside',
            tickcolor='rgb(204, 204, 204)',
            tickwidth=2,
            ticklen=5,
            tickfont=dict(
                family='Arial',
                size=12,
                color='rgb(82, 82, 82)',
                ), )

        layout = dict(title='EVALUACIONES COMPRENDIDAS DESDE  %s HASTA %s ' % (start,stop),
                      yaxis=dict(title='Puntos'),
                      xaxis=xaxis, width=1600, height=1000
        )
        layout['annotations'] = annotations
        normalizaname = company_matriz.name.replace(" ","_")
        fig = go.Figure(data=atrace, layout=layout)
        py.sign_in('jdarknet', 'jjy1dua07v')
        image_save = get_module_path("appcc") + ("/static/img/%s.png" % normalizaname)
        image_path = get_module_resource('appcc', 'static/img','%s.png' % normalizaname)
        py.image.save_as(fig, image_save)
        i=0
        while i < 10:
            time.sleep(1)
            try:
                archivo = open(image_path, 'rb').read().encode('base64')
            except IOError:
                i=i+1
            else:
                i=i+1

        return archivo
コード例 #20
0
    def test_tax_balance(self):
        tax_account_id = self.env['account.account'].search(
            [('name', '=', 'Tax Paid')], limit=1).id
        tax = self.env['account.tax'].create({
            'name': 'Tax 10.0%',
            'amount': 10.0,
            'amount_type': 'percent',
            'account_id': tax_account_id,
        })
        invoice_account_id = self.env['account.account'].search(
            [('user_type_id', '=',
              self.env.ref('account.data_account_type_receivable').id)],
            limit=1).id
        invoice_line_account_id = self.env['account.account'].search(
            [('user_type_id', '=',
              self.env.ref('account.data_account_type_expenses').id)],
            limit=1).id
        invoice = self.env['account.invoice'].create({
            'partner_id':
            self.env.ref('base.res_partner_2').id,
            'account_id':
            invoice_account_id,
            'type':
            'out_invoice',
        })

        self.env['account.invoice.line'].create({
            'product_id':
            self.env.ref('product.product_product_4').id,
            'quantity':
            1.0,
            'price_unit':
            100.0,
            'invoice_id':
            invoice.id,
            'name':
            'product that cost 100',
            'account_id':
            invoice_line_account_id,
            'invoice_line_tax_ids': [(6, 0, [tax.id])],
        })
        invoice._onchange_invoice_line_ids()
        invoice._convert_to_write(invoice._cache)
        self.assertEqual(invoice.state, 'draft')

        # change the state of invoice to open by clicking Validate button
        invoice.action_invoice_open()

        self.assertEquals(tax.base_balance, 100.)
        self.assertEquals(tax.balance, 10.)
        self.assertEquals(tax.base_balance_regular, 100.)
        self.assertEquals(tax.balance_regular, 10.)
        self.assertEquals(tax.base_balance_refund, 0.)
        self.assertEquals(tax.balance_refund, 0.)

        # testing wizard
        current_range = self.range.search([
            ('date_start', '=',
             '%s-%s-01' % (self.current_year, self.current_month))
        ])
        wizard = self.env['wizard.open.tax.balances'].new({})
        self.assertFalse(wizard.from_date)
        self.assertFalse(wizard.to_date)
        wizard = self.env['wizard.open.tax.balances'].new({
            'date_range_id':
            current_range[0].id,
        })
        wizard.onchange_date_range_id()
        wizard._convert_to_write(wizard._cache)
        action = wizard.open_taxes()
        self.assertEqual(action['context']['from_date'],
                         current_range[0].date_start)
        self.assertEqual(action['context']['to_date'],
                         current_range[0].date_end)
        self.assertEqual(action['xml_id'],
                         'account_tax_balance.action_tax_balances_tree')

        # exercise search has_moves = True
        taxes = self.env['account.tax'].search([('has_moves', '=', True)])
        self.assertEqual(len(taxes), 1)
        self.assertEqual(taxes[0].name, u"Tax 10.0%")

        # testing buttons
        tax_action = tax.view_tax_lines()
        base_action = tax.view_base_lines()
        tax_action_move_lines = self.env['account.move.line'].\
            search(tax_action['domain'])
        self.assertTrue(invoice.move_id.line_ids & tax_action_move_lines)
        self.assertEqual(tax_action['xml_id'],
                         'account.action_account_moves_all_tree')
        base_action_move_lines = self.env['account.move.line'].\
            search(base_action['domain'])
        self.assertTrue(invoice.move_id.line_ids & base_action_move_lines)
        self.assertEqual(base_action['xml_id'],
                         'account.action_account_moves_all_tree')

        # test specific method
        state_list = tax.get_target_state_list(target_move='all')
        self.assertEqual(state_list, ['posted', 'draft'])
        state_list = tax.get_target_state_list(target_move='whatever')
        self.assertEqual(state_list, [])

        refund = self.env['account.invoice'].create({
            'partner_id':
            self.env.ref('base.res_partner_2').id,
            'account_id':
            invoice_account_id,
            'type':
            'out_refund',
        })

        self.env['account.invoice.line'].create({
            'product_id':
            self.env.ref('product.product_product_2').id,
            'quantity':
            1.0,
            'price_unit':
            25.0,
            'invoice_id':
            refund.id,
            'name':
            'returned product that cost 25',
            'account_id':
            invoice_line_account_id,
            'invoice_line_tax_ids': [(6, 0, [tax.id])],
        })
        refund._onchange_invoice_line_ids()
        refund._convert_to_write(invoice._cache)
        self.assertEqual(refund.state, 'draft')

        # change the state of refund to open by clicking Validate button
        refund.action_invoice_open()

        self.assertEquals(tax.base_balance, 75.)
        self.assertEquals(tax.balance, 7.5)
        self.assertEquals(tax.base_balance_regular, 100.)
        self.assertEquals(tax.balance_regular, 10.)
        self.assertEquals(tax.base_balance_refund, -25.)
        self.assertEquals(tax.balance_refund, -2.5)

        # Taxes on liquidity type moves are included
        liquidity_account_id = self.env['account.account'].search(
            [('internal_type', '=', 'liquidity')], limit=1).id
        self.env['account.move'].create({
            'date':
            Date.context_today(self.env.user),
            'journal_id':
            self.env['account.journal'].search([('type', '=', 'bank')],
                                               limit=1).id,
            'name':
            'Test move',
            'line_ids': [(0, 0, {
                'account_id': liquidity_account_id,
                'debit': 110,
                'credit': 0,
                'name': 'Bank Fees',
            }),
                         (0, 0, {
                             'account_id': invoice_line_account_id,
                             'debit': 0,
                             'credit': 100,
                             'name': 'Bank Fees',
                             'tax_ids': [(4, tax.id)]
                         }),
                         (0, 0, {
                             'account_id': tax.account_id.id,
                             'debit': 0,
                             'credit': 10,
                             'name': 'Bank Fees',
                             'tax_line_id': tax.id,
                         })],
        }).post()
        tax.refresh()
        self.assertEquals(tax.base_balance, 175.)
        self.assertEquals(tax.balance, 17.5)
コード例 #21
0
ファイル: person.py プロジェクト: MostlyOpen/odoo_addons
 def _inverse_age_days(self):
     today = fDate.from_string(fDate.today())
     for person in self.filtered('birthday'):
         d = td(days=person.age_days)
         person.birthday = fDate.to_string(today - d)
コード例 #22
0
    def attendance_per_location(self, date=None, location=None):
        if not date:
            date = Date.today()

        dt_from = datetime.datetime.strptime("%s 00:00:00" % date, DEFAULT_SERVER_DATETIME_FORMAT) - datetime.timedelta(
                hours=8)
        dt_to = datetime.datetime.strptime("%s 23:59:59" % date, DEFAULT_SERVER_DATETIME_FORMAT) - datetime.timedelta(
                hours=8)

        if not location:
            location = "1"

        Attendance = request.env["hr.attendance"].sudo()
        Employee = request.env["hr.employee"].sudo()
        values = {}

        domain = []
        if date:
            domain.append(("name", ">=", Datetime.to_string(dt_from)))
            domain.append(("name", "<=", Datetime.to_string(dt_to)))

        # if location:
        #     domain.append(("location", "=", location))

        all_employees = Employee.search([])

        emp_attendances_values = []
        for emp in all_employees:
            attendance = dict()
            attendance["name"] = emp.name
            attendance["dep"] = emp.department_id.name

            records = Attendance.search(domain + [("employee_id", "=", emp.id)],
                                        order="name")
            if records and records[-1].location:
                latest_rec = records[-1]
                attendance["state"] = "打卡"

                dt = UTC_Datetime_To_TW_TZ(latest_rec.name)
                date_part = dt.strftime(DEFAULT_SERVER_DATE_FORMAT)
                time_part = dt.strftime(DEFAULT_SERVER_TIME_FORMAT)
                attendance["date"] = date_part
                attendance["time"] = time_part
                attendance["location"] = latest_rec.location
            else:
                attendance["state"] = "未打卡"
                attendance["date"] = None
                attendance["time"] = None
                attendance["location"] = None

            leave_time = emp.get_holiday_on(date)
            attendance["leave"] = string.join(leave_time.keys(), ",") if leave_time else None

            emp_attendances_values.append(attendance)

        # attendance_grouped_by_location = itertools.groupby(emp_attendances_values, key=lambda a: a["location"])
        attendances = defaultdict(lambda: list())
        for attendance in emp_attendances_values:
            attendances[attendance["location"]].append(attendance)  # or _("not attended")

        print_time = UTC_Datetime_To_TW_TZ(Datetime.now())
        values["print_time"] = Datetime.to_string(print_time)

        values["date"] = date
        values["location"] = location
        values["emp_attendances"] = attendances
        keys = sorted(attendances.keys())
        if None in keys:
            keys.remove(None)
            keys.append(None)
        values["attendance_keys"] = keys
        values["action_count"] = len(filter(lambda a: a.get("date", None), emp_attendances_values))
        values["un_action_count"] = len(filter(lambda a: not a.get("date", None), emp_attendances_values))

        return request.render("hr_sf.attendance_per_location", values)
コード例 #23
0
 def _inverse_age(self):
     today = fDate.from_string(fDate.today())
     for book in self.filtered('date_release'):
         d = td(days=book.age_days) - today
         book.date_release = fDate.to_string(d)
コード例 #24
0
    def get_value(self, cr, uid, formula_id, base_date=False, context=None):
        class BrowsableObject(object):
            def __init__(self, pool, cr, uid, formula_id, context, dict):
                self.pool = pool
                self.cr = cr
                self.uid = uid
                self.formula_id = formula_id
                self.formula = self.pool.get('contracts_pro.formula').browse(
                    cr, uid, formula_id) or False
                self.dict = dict
                self.context = context

            def __getattr__(self, attr):
                return attr in self.dict and self.dict.__getitem__(attr) or 0.0

        class Metrics(BrowsableObject):
            """a class that will be used into the python code, mainly for usability purposes"""

            # Service functions

            # Last value for a metric in a period
            def get_last_metric_value(self,
                                      metric_code,
                                      period,
                                      base_date=False):
                values = self.get_metric_values(metric_code, period, base_date)
                return values and values[-1]['value']

            # Average of values for a metric in a period
            def get_avg_metric_value(self,
                                     metric_code,
                                     period,
                                     base_date=False):
                values = self.get_metric_values(metric_code, period, base_date)
                value_sum = values and sum([elem['value']
                                            for elem in values]) or 0
                value_cnt = len(values)
                return value_cnt and value_sum / value_cnt or 0

            # First value for a metric in a period
            def get_first_metric_value(self,
                                       metric_code,
                                       period,
                                       base_date=False):
                values = self.get_metric_values(metric_code, period, base_date)
                return values and values[0]['value']

            # Variation value for a metric in a period
            def get_metric_value_variation(self,
                                           metric_code,
                                           period,
                                           base_date=False):
                result = 0
                values = self.get_metric_values(metric_code, period, base_date)
                if values:
                    first_date = values[0]['date']
                    res = self.get_previous_metric_value(
                        metric_code, first_date)
                    if not res:
                        raise osv.except_osv(
                            _('Error!'),
                            _('Evaluating metric: ') + metric_code +
                            _(', no previous value for defined period'))
                    first = res['value']
                    last = values[-1]['value']
                    result = last - first
                return result

            # Variation factor between 0 and 1 for a metric in a period
            def get_metric_value_variation_prc(self,
                                               metric_code,
                                               period,
                                               base_date=False):
                result = 0
                values = self.get_metric_values(metric_code, period, base_date)
                if values:
                    first_date = values[0]['date']
                    res = self.get_previous_metric_value(
                        metric_code, first_date)
                    if not res:
                        raise osv.except_osv(
                            _('Error!'),
                            _('Evaluating metric: ') + metric_code +
                            _(', no previous value for defined period'))
                    first = res['value']
                    last = values[-1]['value']
                    result = first and (last - first) / first
                return result or 0

            # Minimum value for a metric in a period
            def get_min_metric_value(self,
                                     metric_code,
                                     period,
                                     base_date=False):
                values = self.get_metric_values(metric_code, period, base_date)
                min_value = values and min([elem['value']
                                            for elem in values]) or 0
                return min_value

            # Maximum value for a metric in a period
            def get_max_metric_value(self,
                                     metric_code,
                                     period,
                                     base_date=False):
                values = self.get_metric_values(metric_code, period, base_date)
                max_value = values and max([elem['value']
                                            for elem in values]) or 0
                return max_value

            # Returns an ascending ordered by date list of dictionaries with 'value' and 'date' elements, inside a period for a specific metric
            def get_metric_values(self,
                                  metric_code,
                                  period_code,
                                  base_date=False):

                # Check period and metric codes
                period_obj = self.pool.get('contracts_pro.period')
                period_id = period_obj.search(self.cr,
                                              self.uid,
                                              [('code', '=', period_code)],
                                              context=self.context)
                if not period_id:
                    raise osv.except_osv(_('Error!'),
                                         _('Period code not found'))
                metric_obj = self.pool.get('contracts_pro.metric')
                metric_id = metric_obj.search(self.cr,
                                              self.uid,
                                              [('code', '=', metric_code)],
                                              context=self.context)
                if not metric_id:
                    raise osv.except_osv(_('Error!'),
                                         _('Metric code not found'))

                # Get period limits
                base_date = base_date or datetime.now().date()
                period = period_obj.browse(self.cr,
                                           self.uid,
                                           period_id,
                                           context=self.context)
                start_period, end_period = period_obj.get_period_limits_from_date(
                    self.cr, self.uid, [period.id], base_date)

                # Get historic values for period
                values_obj = self.pool.get(
                    'contracts_pro.metric_history_value')
                values_ids = values_obj.search(
                    self.cr,
                    self.uid, [('date', '>=', start_period),
                               ('date', '<=', end_period),
                               ('metric_id', '=', metric_id[0])],
                    order='date',
                    context=self.context)
                values = [{
                    'value': elem.value,
                    'date': elem.date
                } for elem in values_obj.browse(
                    self.cr, self.uid, values_ids, context=self.context)]

                return values

            # Returns previous value to a reference date
            def get_previous_metric_value(self, metric_code, reference_date):

                metric_obj = self.pool.get('contracts_pro.metric')
                metric_id = metric_obj.search(self.cr,
                                              self.uid,
                                              [('code', '=', metric_code)],
                                              context=self.context)
                if not metric_id:
                    raise osv.except_osv(_('Error!'),
                                         _('Metric code not found'))

                # Get previous value
                values_obj = self.pool.get(
                    'contracts_pro.metric_history_value')
                filter = reference_date and [
                    ('date', '<', reference_date),
                    ('metric_id', '=', metric_id[0])
                ] or [('metric_id', '=', metric_id[0])]
                values_ids = values_obj.search(self.cr,
                                               self.uid,
                                               filter,
                                               order='date desc',
                                               limit=1,
                                               context=self.context)
                if values_ids:
                    elem = values_obj.browse(self.cr,
                                             self.uid,
                                             values_ids,
                                             context=self.context)
                    return {'value': elem.value, 'date': elem.date}
                return False

        # Base date or today
        base_date = base_date or datetime.now().date().strftime('%Y-%m-%d')

        # Get related metrics
        formula = self.browse(cr, uid, formula_id, context=context)
        metrics = formula.metric_ids
        metrics_dict = self.pool.get('contracts_pro.metric').read(
            cr, uid, [el.id for el in metrics], context=context)

        # Check last updates for related metrics and max age tolerance
        if formula.metric_age_tolerance:
            for item in metrics_dict:
                if not item['last_update']:
                    raise osv.except_osv(
                        _('Error!'),
                        _('La variable no tiene fecha de actualización alguna definida'
                          ))
                dt_last_update = datetime.strptime(item['last_update'],
                                                   '%Y-%m-%d').date()
                dt_evaluation_date = datetime.strptime(base_date,
                                                       '%Y-%m-%d').date()
                # If older than tolerance, return error
                if (dt_evaluation_date -
                        dt_last_update).days > formula.metric_age_tolerance:
                    raise osv.except_osv(
                        _('Error!'),
                        _('Last value older than tolerance for metric: ' +
                          item['name']))

        # Create object to browse in formula code
        metrics_obj = Metrics(self.pool, cr, uid, formula.id, context,
                              metrics_dict)

        # Put objects in dictionary to be used by rules
        baselocaldict = {'metrics': metrics_obj}
        localdict = dict(baselocaldict,
                         formula=formula,
                         base_date=base_date,
                         metric_objects=metrics,
                         context=context)

        for var in localdict['metric_objects']:
            base_date_formatted = Date.from_string(base_date)
            if not var.value_history_ids.filtered(
                    lambda x: Date.from_string(x.date) == base_date_formatted):
                raise ValidationError(
                    _("La variable %s no tiene valores definidos para la fecha %s y está siendo usada en la fórmula!"
                      ) % (var.name, base_date_formatted))
        # Evaluate formula and get result
        try:
            eval(formula.formula, localdict, mode='exec', nocopy=True)
            if 'result' in localdict:
                value = localdict['result']
            else:
                value = {}
        except Exception:
            raise osv.except_osv(_('Error!'),
                                 _('Evaluation formula code: ' + formula.name))

        return value
コード例 #25
0
    def get_attendance_detail_line(self, dt_date):
        self.ensure_one()
        if not isinstance(dt_date, datetime.date):
            return None

        OfficialHoliday = self.env["hr.official_holiday"]

        dt_str = Date.to_string(dt_date)

        overtime_durations = self.get_overtime_hours_on(date_from=dt_str,
                                                        date_to=dt_str)
        if dt_date.weekday() in (5, 6) and not overtime_durations:
            return None

        line = dict()
        line['name'] = self.name
        line['emp_dep'] = self.department_id.name
        line['emp_code'] = self.internal_code
        line['date'] = dt_date.strftime(
            DEFAULT_SERVER_DATE_FORMAT)  # + " %A" Date.to_string(dt)

        start_work_time = self.get_start_work_time_on(dt_str)
        line["start_work_time"] = start_work_time.strftime(DEFAULT_SERVER_TIME_FORMAT) \
            if start_work_time else None

        end_work_time = self.get_end_work_time_on(dt_str)
        line["end_work_time"] = end_work_time.strftime(DEFAULT_SERVER_TIME_FORMAT) \
            if end_work_time else None

        late_minutes = self.get_late_minutes_on(dt_str)
        line["late_minutes"] = round(late_minutes, 2) if late_minutes else None

        early_minutes = self.get_early_minutes_on(dt_str)
        line["early_minutes"] = round(early_minutes,
                                      2) if early_minutes else None

        work_duration = self.get_work_duration_on(dt_str)
        line["work_duration"] = round(work_duration,
                                      2) if work_duration else None

        # overtime_durations = self.get_overtime_hours_on(date_from=dt_str, date_to=dt_str)

        if overtime_durations:
            line["overtime_stage1"] = overtime_durations.get("stage1", None)
            line["overtime_stage2"] = overtime_durations.get("stage2", None)
            line["overtime_stage3"] = overtime_durations.get("stage3", None)

        # line["overtime_hours"] = round(overtime_hours, 2)

        leaves = self.get_holiday_on(dt_str)
        line["holiday_detail"] = leaves

        all_leaves = list()
        if leaves:
            for l in leaves.values():
                all_leaves.extend(l)
        holiday_total = round(sum(l[2].seconds / 3600.0 for l in all_leaves),
                              2)
        line["holiday_total"] = holiday_total

        official_holiday = OfficialHoliday.get_official_holiday_on(dt_str)
        line["official_holiday"] = official_holiday

        absent = self.get_absent_on(dt_str)

        if leaves:
            line["summary"] = string.join(
                set(leaves.keys() + ([absent] if absent else []) +
                    ([official_holiday] if official_holiday else [])), ",")
        else:
            line["summary"] = None

        if not official_holiday and holiday_total < 8.0:
            line["forget_card"] = self.get_forget_card_on(dt_str)
        else:
            line["forget_card"] = None
        return line
コード例 #26
0
 def _check_date_release(self):
     for r in self:
         if r.date_release > dt.today():
             raise models.ValidationError('Release date cannot be in future.')
コード例 #27
0
ファイル: hr_employee.py プロジェクト: likaiyuan/hr_sf
    def get_holiday_on(self, date=None):
        self.ensure_one()
        if not date:
            return None

        querying_day = date
        if isinstance(date, datetime.date):
            querying_day = Date.to_string(date)

        leaves = defaultdict(lambda: list(
        ))  # [None, None, datetime.timedelta()] _time = datetime.timedelta()

        absent_type_id = self.env.ref("hr_sf.absent_holidays_status").id

        for holiday in self.holidays_ids:
            if not holiday.date_from or not holiday.date_to:
                continue
            if holiday.holiday_status_id.id == absent_type_id:
                continue

            if not all((holiday.morning_start_work_time,
                        holiday.morning_end_work_time,
                        holiday.afternoon_start_work_time,
                        holiday.afternoon_end_work_time)):
                return None

            dt_the_day_morning_start_work_time = datetime.datetime.strptime(
                "%s %s" % (querying_day, holiday.morning_start_work_time),
                DEFAULT_SERVER_DATETIME_FORMAT)
            dt_the_day_morning_end_work_time = datetime.datetime.strptime(
                "%s %s" % (querying_day, holiday.morning_end_work_time),
                DEFAULT_SERVER_DATETIME_FORMAT)
            dt_the_day_afternoon_start_work_time = datetime.datetime.strptime(
                "%s %s" % (querying_day, holiday.afternoon_start_work_time),
                DEFAULT_SERVER_DATETIME_FORMAT)
            dt_the_day_afternoon_end_work_time = datetime.datetime.strptime(
                "%s %s" % (querying_day, holiday.afternoon_end_work_time),
                DEFAULT_SERVER_DATETIME_FORMAT)

            dt_holiday_from = Datetime.from_string(
                holiday.date_from) + datetime.timedelta(hours=8)
            dt_holiday_to = Datetime.from_string(
                holiday.date_to) + datetime.timedelta(hours=8)
            # deal with morning first
            dt_cal_start = max(dt_the_day_morning_start_work_time,
                               dt_holiday_from)
            dt_cal_start = min(dt_cal_start, dt_the_day_morning_end_work_time)

            dt_cal_end = min(dt_the_day_morning_end_work_time, dt_holiday_to)
            dt_cal_end = max(dt_cal_end, dt_the_day_morning_start_work_time)

            if dt_cal_end > dt_cal_start:
                leaves[holiday.holiday_status_id.name].append(
                    (dt_cal_start, dt_cal_end, dt_cal_end - dt_cal_start))
                # leaves[holiday.holiday_status_id.name][0] = dt_cal_start
                # leaves[holiday.holiday_status_id.name][1] = dt_cal_end
                # leaves[holiday.holiday_status_id.name][2] += dt_cal_end - dt_cal_start

            # then deal with afternoon first
            dt_cal_start = max(dt_the_day_afternoon_start_work_time,
                               dt_holiday_from)
            dt_cal_start = min(dt_cal_start,
                               dt_the_day_afternoon_end_work_time)

            dt_cal_end = min(dt_the_day_afternoon_end_work_time, dt_holiday_to)
            dt_cal_end = max(dt_cal_end, dt_the_day_afternoon_start_work_time)

            if dt_cal_end > dt_cal_start:
                leaves[holiday.holiday_status_id.name].append(
                    (dt_cal_start, dt_cal_end, dt_cal_end - dt_cal_start))
                # leaves[holiday.holiday_status_id.name][0] = dt_cal_start
                # leaves[holiday.holiday_status_id.name][1] = dt_cal_end
                # leaves[holiday.holiday_status_id.name][2] += dt_cal_end - dt_cal_start

        return leaves
コード例 #28
0
 def generate_key_from_date(self, date_str=None):
     if date_str:
         date = Date.from_string(date_str)
         key = "%04d%02d%02d" % (date.year, date.month, date.day)
         return key
コード例 #29
0
 def _compute_age(self):
     today = fDate.from_string(fDate.today())
     for book in self.filtered('date_release'):
         delta = (fDate.from_string(book.date_release) - today)
         book.age_days = delta.days
コード例 #30
0
    def get_attendance_statistics(self,
                                  date_from=None,
                                  date_to=None,
                                  filter_by=None,
                                  employee_ids=None,
                                  department_ids=None):
        CAL_START_TIME = datetime.datetime.now()
        print "开始计算出勤统计表:", CAL_START_TIME
        if any((date_from, date_to)) and not all((date_from, date_to)):
            return "miss date_from or date_to"

        if not date_from and not date_to:
            now = datetime.datetime.now()
            date_from = datetime.datetime(now.year, now.month, 1)
            date_to = datetime.datetime(date_from.year, date_from.month + 1, 1)
        elif date_from and date_to:
            date_from = Date.from_string(date_from)
            date_to = Date.from_string(date_to)

        Employee = self.env["hr.employee"].sudo()

        employee_search_domain = []
        if filter_by == "employee" and employee_ids:
            employee_search_domain.append(("id", "in", employee_ids))
        if filter_by == "department" and department_ids:
            employee_search_domain.append(
                ("department_id", "in", department_ids))
        all_employees = Employee.search(employee_search_domain)
        all_employees = sorted(all_employees,
                               key=lambda e:
                               (e.department_id.name
                                if e.department_id else "", e.internal_code))

        emp_attendances_values = []
        for emp in all_employees:
            dt = date_from
            emp_lines = list()
            days = 0
            while dt <= date_to:
                line = emp.get_attendance_detail_line(dt)
                if line:
                    emp_lines.append(line)
                days += 1
                dt += datetime.timedelta(days=1)

            if emp_lines:
                emp_total_line = dict()
                emp_total_line["name"] = emp.name
                emp_total_line[
                    'emp_dep'] = emp.department_id.name if emp.department_id else ""
                emp_total_line['emp_code'] = emp.internal_code
                # emp_total_line['date'] = '小计'
                # emp_total_line['end_work_time'] = None
                # emp_total_line['start_work_time'] = None
                # emp_total_line['late_minutes'] = sum(l["late_minutes"] or 0 for l in emp_lines)
                # emp_total_line['early_minutes'] = sum(l["early_minutes"] or 0 for l in emp_lines)
                emp_total_line["work_duration"] = round(
                    sum(l.get("work_duration", None) or 0
                        for l in emp_lines) / 8.0, 2)
                # emp_total_line["late_minutes"] = sum(l["late_minutes"] or 0 for l in emp_lines)

                emp_total_line["overtime_stage1"] = sum(
                    l.get("overtime_stage1", None) or 0 for l in emp_lines)
                emp_total_line["overtime_stage2"] = sum(
                    l.get("overtime_stage2", None) or 0 for l in emp_lines)
                emp_total_line["overtime_stage3"] = sum(
                    l.get("overtime_stage3", None) or 0 for l in emp_lines)

                holiday_detail = defaultdict(lambda: 0)
                for line in emp_lines:
                    if line.get("holiday_detail", None):
                        for holiday in line["holiday_detail"]:
                            holiday_detail[holiday] += round(
                                sum(h[2].seconds / 3600.0
                                    for h in line["holiday_detail"][holiday]),
                                2)

                emp_total_line["holiday_detail"] = holiday_detail

                emp_total_line["holiday_total"] = sum(l["holiday_total"] or 0
                                                      for l in emp_lines)

                # emp_total_line["summary"] = string.join(set(l["summary"] for l in emp_lines))
                emp_total_line["forget_card"] = sum(l["forget_card"] or 0
                                                    for l in emp_lines)
                #
                emp_attendances_values.append(emp_total_line)

        CAL_END_TIME = datetime.datetime.now()
        print "结束时间:", CAL_END_TIME
        print "耗时:", CAL_END_TIME - CAL_START_TIME
        return emp_attendances_values
コード例 #31
0
ファイル: calendar.py プロジェクト: sc4you/online
class hr_timesheet_sheet_sheet_day_cat_detail(osv.osv):
    _name = "hr_timesheet_sheet.sheet.day_cat_detail"
    _description = "Category by Days in Period"
    _auto = False
    _order = 'name'

    # Fields:
    name = Date(string='Date', readonly='True')
    timesheet_id = Many2one(comodel_name='hr_timesheet_sheet.sheet', string='Timesheet')
    employee_id = Many2one(comodel_name='hr.employee', string='Employee')

    ga = Float(string="GA", readonly='True')
    ga_e = Float(string="GA Expense", readonly='True')
    ga_a = Float(string="GA Abroad", readonly='True')
    ga_ae = Float(string="GA Abroad Expense", readonly='True')

    cm = Float(string="CM", readonly='True')
    cm_e = Float(string="CM Expense", readonly='True')
    cm_a = Float(string="CM Abroad", readonly='True')
    cm_ae = Float(string="CM Abroad Expense", readonly='True')

    t = Float(string="T", readonly='True')
    t_e = Float(string="T Expense", readonly='True')
    t_a = Float(string="T Abroad", readonly='True')
    t_ae = Float(string="T Abroad Expense", readonly='True')

    os = Float(string="OS", readonly='True')
    os_e = Float(string="OS Expense", readonly='True')
    os_a = Float(string="OS Abroad", readonly='True')
    os_ae = Float(string="OS Abroad Expense", readonly='True')

    sum_e = Float(string="Expense", readonly='True')
    sum_a = Float(string="Abroad", readonly='True')
    sum_ae = Float(string="Abroad Expense", readonly='True')

    # Sum of the events categories per day
    def init(self, cr):
        tools.drop_view_if_exists(cr, 'hr_timesheet_sheet_sheet_day_cat_detail')
        cr.execute(""" CREATE OR REPLACE VIEW hr_timesheet_sheet_sheet_day_cat_detail as (
            select
                 ts.id * 100000 + ((period.day::date - ts.date_from::timestamp::date) + 1) AS id
                ,ts.id timesheet_id
                ,ts.employee_id
                ,ts.user_id
                ,period.day as name
                ,count(distinct e.id)
                ,sum(case when cc.name = 'GENERAL ACTIVITY' then e.duration else 0 end) ga
                ,sum(case when cc.name = 'GENERAL ACTIVITY > Expense Entitled' then e.duration else 0 end) ga_e
                ,sum(case when cc.name = 'GENERAL ACTIVITY > Abroad' then e.duration else 0 end) ga_a
                ,sum(case when cc.name = 'GENERAL ACTIVITY > Abroad > Expense Entitled' then e.duration else 0 end) ga_ae
                ,sum(case when cc.name = 'CUSTOMER MEETING' then e.duration else 0 end) cm
                ,sum(case when cc.name = 'CUSTOMER MEETING > Expense Entitled' then e.duration else 0 end) cm_e
                ,sum(case when cc.name = 'CUSTOMER MEETING > Abroad' then e.duration else 0 end) cm_a
                ,sum(case when cc.name = 'CUSTOMER MEETING > Abroad > Expense Entitled' then e.duration else 0 end) cm_ae
                ,sum(case when cc.name = 'TRIP' then e.duration else 0 end) t
                ,sum(case when cc.name = 'TRIP > Expense Entitled' then e.duration else 0 end) t_e
                ,sum(case when cc.name = 'TRIP > Abroad' then e.duration else 0 end) t_a
                ,sum(case when cc.name = 'TRIP > Abroad > Expense Entitled' then e.duration else 0 end) t_ae
                ,sum(case when cc.name = 'OVERNIGHT STAY > Expense Entitled' then e.duration else 0 end) os_e
                ,sum(case when cc.name = 'OVERNIGHT STAY > Abroad' then e.duration else 0 end) os_a
                ,sum(case when cc.name = 'OVERNIGHT STAY > Abroad > Expense Entitled' then e.duration else 0 end) os_ae
                ,sum(case when cc.name = 'OVERNIGHT STAY' then e.duration else 0 end) os
                -- ,sum(case when cc.name like '%Expense%' then e.duration else 0 end) sum_exp
                -- ,sum(case when cc.name like '%Abroad%' then e.duration else 0 end) sum_abr
                ,sum(case when cc.name in ( 'GENERAL ACTIVITY > Expense Entitled'
                                           ,'CUSTOMER MEETING > Expense Entitled'
                                           ,'TRIP > Expense Entitled'
                                            ) then e.duration else 0 end) sum_e
                ,sum(case when cc.name in ( 'GENERAL ACTIVITY > Abroad'
                                           ,'CUSTOMER MEETING > Abroad'
                                           ,'TRIP > Abroad'
                                            ) then e.duration else 0 end) sum_a
                ,sum(case when cc.name in ( 'GENERAL ACTIVITY > Abroad > Expense Entitled'
                                           ,'CUSTOMER MEETING > Abroad > Expense Entitled'
                                           ,'TRIP > Abroad > Expense Entitled'
                                            ) then e.duration else 0 end) sum_ae
                ,p.name partner_name
            from   hr_timesheet_sheet_sheet ts
            inner join res_users u
                on u.id = ts.user_id
            inner join res_partner p
                on p.id = u.partner_id
            cross join generate_series(ts.date_from::timestamp without time zone, ts.date_to::timestamp without time zone, '1 day'::interval) period(day)
            left join calendar_event e
                on e.user_id = ts.user_id
                   and e.start_datetime::timestamp::date = period.day::timestamp::date
                   and e.category_id in (select id from calendar_event_category where name in
                                                        ('GENERAL ACTIVITY'
                                                        ,'GENERAL ACTIVITY > Expense Entitled'
                                                        ,'GENERAL ACTIVITY > Abroad'
                                                        ,'GENERAL ACTIVITY > Abroad > Expense Entitled'
                                                        ,'CUSTOMER MEETING'
                                                        ,'CUSTOMER MEETING > Expense Entitled'
                                                        ,'CUSTOMER MEETING > Abroad'
                                                        ,'CUSTOMER MEETING > Abroad > Expense Entitled'
                                                        ,'TRIP'
                                                        ,'TRIP > Expense Entitled'
                                                        ,'TRIP > Abroad'
                                                        ,'TRIP > Abroad > Expense Entitled'
                                                        ,'OVERNIGHT STAY > Expense Entitled'
                                                        ,'OVERNIGHT STAY > Abroad'
                                                        ,'OVERNIGHT STAY > Abroad > Expense Entitled'
                                                        ,'OVERNIGHT STAY'))

            left join calendar_event_category cc
                on cc.id = e.category_id
            group by
                 ts.id
                ,ts.employee_id
                ,ts.user_id
                ,period.day
                ,p.name
            order by ts.id, period.day
            )""")
コード例 #32
0
    def get_attendance_detail(self,
                              date_from=None,
                              date_to=None,
                              filter_by_employee=None,
                              employee_ids=None):
        CAL_START_TIME = datetime.datetime.now()
        print "开始计算出勤明细表:", CAL_START_TIME
        if any((date_from, date_to)) and not all((date_from, date_to)):
            return "miss date_from or date_to"

        if not date_from and not date_to:
            now = datetime.datetime.now()
            date_from = datetime.datetime(now.year, now.month, 1)
            date_to = datetime.datetime(date_from.year, date_from.month + 1, 1)
        elif date_from and date_to:
            date_from = Date.from_string(date_from)
            date_to = Date.from_string(date_to)

        Employee = self.env["hr.employee"].sudo()

        emp_attendances_values = []

        employee_search_domain = []
        if filter_by_employee and employee_ids:
            employee_search_domain.append(("id", "in", employee_ids))
        all_employees = Employee.search(employee_search_domain)

        for emp in all_employees:
            dt = date_from
            emp_lines = list()
            while dt <= date_to:
                dt_str = Date.to_string(dt)

                overtime_hours = emp.get_overtime_hours_on(date_from=dt_str,
                                                           date_to=dt_str)
                if dt.weekday() in (5, 6) and (emp.responsibility
                                               or not overtime_hours):
                    dt += datetime.timedelta(days=1)
                    continue

                line = dict()
                line['name'] = emp.name
                line['emp_dep'] = emp.department_id.name
                line['emp_code'] = emp.internal_code
                line['date'] = dt.strftime(
                    DEFAULT_SERVER_DATE_FORMAT)  # + " %A" Date.to_string(dt)

                start_work_time = emp.get_start_work_time_on(dt_str)
                line["start_work_time"] = start_work_time.strftime(DEFAULT_SERVER_TIME_FORMAT) \
                    if start_work_time else None

                end_work_time = emp.get_end_work_time_on(dt_str)
                line["end_work_time"] = end_work_time.strftime(DEFAULT_SERVER_TIME_FORMAT) \
                    if end_work_time else None

                late_minutes = emp.get_late_minutes_on(dt_str)
                line["late_minutes"] = round(late_minutes,
                                             2) if late_minutes else None

                early_minutes = emp.get_early_minutes_on(dt_str)
                line["early_minutes"] = round(early_minutes,
                                              2) if early_minutes else None

                work_duration = emp.get_work_duration_on(dt_str)
                line["work_duration"] = round(work_duration,
                                              2) if work_duration else None

                line["overtime_hours"] = round(overtime_hours, 2)

                leaves = emp.get_holiday_on(dt_str)
                all_leaves = list()
                for l in leaves.values():
                    all_leaves.extend(l)
                line["holiday_total"] = round(
                    sum(l[2].seconds / 3600.0 for l in all_leaves), 2)

                absent_for_summary = []
                absent = emp.get_absent_on(dt_str)
                if absent:
                    absent_for_summary.append(_("absent"))
                line["summary"] = string.join(
                    set(leaves.keys() + absent_for_summary), ",")
                line["forget_card"] = emp.get_forget_card_on(dt_str)

                emp_attendances_values.append(line)
                emp_lines.append(line)
                dt += datetime.timedelta(days=1)

            if emp_lines:
                emp_total_line = dict()
                emp_total_line["name"] = None
                emp_total_line['emp_dep'] = None
                emp_total_line['emp_code'] = None
                emp_total_line['date'] = '小计'
                emp_total_line['end_work_time'] = None
                emp_total_line['start_work_time'] = None
                emp_total_line['late_minutes'] = sum(l["late_minutes"] or 0
                                                     for l in emp_lines)
                emp_total_line['early_minutes'] = sum(l["early_minutes"] or 0
                                                      for l in emp_lines)
                emp_total_line["work_duration"] = sum(l["work_duration"] or 0
                                                      for l in emp_lines)
                emp_total_line["late_minutes"] = sum(l["late_minutes"] or 0
                                                     for l in emp_lines)

                emp_total_line["overtime_hours"] = sum(l["overtime_hours"] or 0
                                                       for l in emp_lines)
                emp_total_line["holiday_total"] = sum(l["holiday_total"] or 0
                                                      for l in emp_lines)
                emp_total_line["summary"] = string.join(
                    set(l["summary"] for l in emp_lines))
                emp_total_line["forget_card"] = sum(l["forget_card"] or 0
                                                    for l in emp_lines)
                emp_attendances_values.append(emp_total_line)

        CAL_END_TIME = datetime.datetime.now()
        print "结束时间:", CAL_END_TIME
        print "耗时:", CAL_END_TIME - CAL_START_TIME
        return emp_attendances_values
コード例 #33
0
ファイル: hr_employee.py プロジェクト: likaiyuan/hr_sf
    def get_absent_on(self, date=None):
        self.ensure_one()
        if not date:
            return None

        querying_day = date
        if isinstance(date, datetime.date):
            querying_day = Date.to_string(date)

        absent_type_id = self.env.ref("hr_sf.absent_holidays_status").id

        for holiday in self.holidays_ids:
            if not holiday.date_from or not holiday.date_to:
                continue
            if holiday.holiday_status_id.id != absent_type_id:
                continue

            if not all((holiday.morning_start_work_time,
                        holiday.morning_end_work_time,
                        holiday.afternoon_start_work_time,
                        holiday.afternoon_end_work_time)):
                return None

            dt_the_day_morning_start_work_time = datetime.datetime.strptime(
                "%s %s" % (querying_day, holiday.morning_start_work_time),
                DEFAULT_SERVER_DATETIME_FORMAT)
            dt_the_day_morning_end_work_time = datetime.datetime.strptime(
                "%s %s" % (querying_day, holiday.morning_end_work_time),
                DEFAULT_SERVER_DATETIME_FORMAT)
            dt_the_day_afternoon_start_work_time = datetime.datetime.strptime(
                "%s %s" % (querying_day, holiday.afternoon_start_work_time),
                DEFAULT_SERVER_DATETIME_FORMAT)
            dt_the_day_afternoon_end_work_time = datetime.datetime.strptime(
                "%s %s" % (querying_day, holiday.afternoon_end_work_time),
                DEFAULT_SERVER_DATETIME_FORMAT)

            dt_holiday_from = Datetime.from_string(
                holiday.date_from) + datetime.timedelta(hours=8)
            dt_holiday_to = Datetime.from_string(
                holiday.date_to) + datetime.timedelta(hours=8)

            # deal with morning first
            dt_cal_start = max(dt_the_day_morning_start_work_time,
                               dt_holiday_from)
            dt_cal_start = min(dt_cal_start, dt_the_day_morning_end_work_time)

            dt_cal_end = min(dt_the_day_morning_end_work_time, dt_holiday_to)
            dt_cal_end = max(dt_cal_end, dt_the_day_morning_start_work_time)

            if dt_cal_end > dt_cal_start:
                return 1

            # then deal with afternoon first
            dt_cal_start = max(dt_the_day_afternoon_start_work_time,
                               dt_holiday_from)
            dt_cal_start = min(dt_cal_start,
                               dt_the_day_afternoon_end_work_time)

            dt_cal_end = min(dt_the_day_afternoon_end_work_time, dt_holiday_to)
            dt_cal_end = max(dt_cal_end, dt_the_day_afternoon_start_work_time)

            if dt_cal_end > dt_cal_start:
                return 1
コード例 #34
0
    def get_attendance_detail_line(self, dt_date):
        self.ensure_one()
        if not isinstance(dt_date, datetime.date):
            return None

        OfficialHoliday = self.env["hr.official_holiday"]

        dt_str = Date.to_string(dt_date)

        overtime_durations = self.get_overtime_hours_on(date_from=dt_str, date_to=dt_str)
        if dt_date.weekday() in (5, 6) and not overtime_durations:
            return None

        line = dict()
        line['name'] = self.name
        line['emp_dep'] = self.department_id.name
        line['emp_code'] = self.internal_code
        line['date'] = dt_date.strftime(DEFAULT_SERVER_DATE_FORMAT)  # + " %A" Date.to_string(dt)

        start_work_time = self.get_start_work_time_on(dt_str)
        line["start_work_time"] = start_work_time.strftime(DEFAULT_SERVER_TIME_FORMAT) \
            if start_work_time else None

        end_work_time = self.get_end_work_time_on(dt_str)
        line["end_work_time"] = end_work_time.strftime(DEFAULT_SERVER_TIME_FORMAT) \
            if end_work_time else None

        late_minutes = self.get_late_minutes_on(dt_str)
        line["late_minutes"] = round(late_minutes, 2) if late_minutes else None

        early_minutes = self.get_early_minutes_on(dt_str)
        line["early_minutes"] = round(early_minutes, 2) if early_minutes else None

        work_duration = self.get_work_duration_on(dt_str)
        line["work_duration"] = round(work_duration, 2) if work_duration else None

        # overtime_durations = self.get_overtime_hours_on(date_from=dt_str, date_to=dt_str)

        if overtime_durations:
            line["overtime_stage1"] = overtime_durations.get("stage1", None)
            line["overtime_stage2"] = overtime_durations.get("stage2", None)
            line["overtime_stage3"] = overtime_durations.get("stage3", None)

        # line["overtime_hours"] = round(overtime_hours, 2)

        leaves = self.get_holiday_on(dt_str)
        line["holiday_detail"] = leaves

        all_leaves = list()
        if leaves:
            for l in leaves.values():
                all_leaves.extend(l)
        holiday_total = round(sum(l[2].seconds / 3600.0 for l in all_leaves), 2)
        line["holiday_total"] = holiday_total

        official_holiday = OfficialHoliday.get_official_holiday_on(dt_str)
        line["official_holiday"] = official_holiday

        absent = self.get_absent_on(dt_str)

        if leaves:
            line["summary"] = string.join(
                    set(leaves.keys() + ([absent] if absent else []) + ([official_holiday] if official_holiday else [])),
                    ",")
        else:
            line["summary"] = None

        if not official_holiday and holiday_total < 8.0:
            line["forget_card"] = self.get_forget_card_on(dt_str)
        else:
            line["forget_card"] = None
        return line
コード例 #35
0
    def get_attendance_detail(self, date_from=None, date_to=None, filter_by=None, employee_ids=None,
                              department_ids=None):
        CAL_START_TIME = datetime.datetime.now()
        print "开始计算出勤明细表:", CAL_START_TIME
        if any((date_from, date_to)) and not all((date_from, date_to)):
            return "miss date_from or date_to"

        if not date_from and not date_to:
            now = datetime.datetime.now()
            date_from = datetime.datetime(now.year, now.month, 1)
            date_to = datetime.datetime(date_from.year, date_from.month + 1, 1)
        elif date_from and date_to:
            date_from = Date.from_string(date_from)
            date_to = Date.from_string(date_to)

        Employee = self.env["hr.employee"].sudo()

        emp_attendances_values = []

        employee_search_domain = []
        if filter_by == "employee" and employee_ids:
            employee_search_domain.append(("id", "in", employee_ids))
        if filter_by == "department" and department_ids:
            employee_search_domain.append(("department_id", "in", department_ids))
        all_employees = Employee.search(employee_search_domain)
        all_employees = sorted(all_employees,
                               key=lambda e: (e.department_id.name if e.department_id else "", e.internal_code))

        for emp in all_employees:
            dt = date_from
            emp_lines = list()
            while dt <= date_to:
                # dt_str = Date.to_string(dt)
                #
                # overtime_durations = emp.get_overtime_hours_on(date_from=dt_str, date_to=dt_str)
                # if dt.weekday() in (5, 6) and (emp.responsibility or not overtime_durations):
                #     dt += datetime.timedelta(days=1)
                #     continue
                #
                # line = dict()
                # line['name'] = emp.name
                # line['emp_dep'] = emp.department_id.name
                # line['emp_code'] = emp.internal_code
                # line['date'] = dt.strftime(DEFAULT_SERVER_DATE_FORMAT)  # + " %A" Date.to_string(dt)
                #
                # start_work_time = emp.get_start_work_time_on(dt_str)
                # line["start_work_time"] = start_work_time.strftime(DEFAULT_SERVER_TIME_FORMAT) \
                #     if start_work_time else None
                #
                # end_work_time = emp.get_end_work_time_on(dt_str)
                # line["end_work_time"] = end_work_time.strftime(DEFAULT_SERVER_TIME_FORMAT) \
                #     if end_work_time else None
                #
                # late_minutes = emp.get_late_minutes_on(dt_str)
                # line["late_minutes"] = round(late_minutes, 2) if late_minutes else None
                #
                # early_minutes = emp.get_early_minutes_on(dt_str)
                # line["early_minutes"] = round(early_minutes, 2) if early_minutes else None
                #
                # work_duration = emp.get_work_duration_on(dt_str)
                # line["work_duration"] = round(work_duration, 2) if work_duration else None
                #
                # if overtime_durations:
                #     line["overtime_stage1"] = overtime_durations.get("stage1", None)
                #     line["overtime_stage2"] = overtime_durations.get("stage2", None)
                #     line["overtime_stage3"] = overtime_durations.get("stage3", None)
                #
                # # line["overtime_hours"] = round(overtime_hours, 2)
                #
                # leaves = emp.get_holiday_on(dt_str)
                # all_leaves = list()
                # for l in leaves.values():
                #     all_leaves.extend(l)
                # line["holiday_total"] = round(sum(l[2].seconds / 3600.0 for l in all_leaves), 2)
                #
                # absent_for_summary = []
                # absent = emp.get_absent_on(dt_str)
                # if absent:
                #     absent_for_summary.append(_("absent"))
                # line["summary"] = string.join(set(leaves.keys() + absent_for_summary), ",")
                # line["forget_card"] = emp.get_forget_card_on(dt_str)

                line = emp.get_attendance_detail_line(dt)
                if line:
                    emp_attendances_values.append(line)
                    emp_lines.append(line)
                dt += datetime.timedelta(days=1)

            if emp_lines:
                emp_total_line = dict()
                emp_total_line["name"] = None
                emp_total_line['emp_dep'] = None
                emp_total_line['emp_code'] = None
                emp_total_line['date'] = '小计'
                emp_total_line['end_work_time'] = None
                emp_total_line['start_work_time'] = None
                emp_total_line['late_minutes'] = sum(l["late_minutes"] or 0 for l in emp_lines)
                emp_total_line['early_minutes'] = sum(l["early_minutes"] or 0 for l in emp_lines)
                emp_total_line["work_duration"] = sum(l["work_duration"] or 0 for l in emp_lines)
                # emp_total_line["late_minutes"] = sum(l["late_minutes"] or 0 for l in emp_lines)
                # line["overtime_stage1"]
                emp_total_line["overtime_stage1"] = sum(l.get("overtime_stage1", None) or 0 for l in emp_lines)
                emp_total_line["overtime_stage2"] = sum(l.get("overtime_stage2", None) or 0 for l in emp_lines)
                emp_total_line["overtime_stage3"] = sum(l.get("overtime_stage3", None) or 0 for l in emp_lines)
                emp_total_line["holiday_total"] = sum(l["holiday_total"] or 0 for l in emp_lines)
                holiday_names = []
                for l in emp_lines:
                    if l["holiday_detail"]:
                        names = l["holiday_detail"].keys()
                        if names:
                            holiday_names.extend(names)

                emp_total_line["summary"] = string.join(set(holiday_names),',')
                emp_total_line["forget_card"] = sum(l["forget_card"] or 0 for l in emp_lines)
                emp_attendances_values.append(emp_total_line)

        CAL_END_TIME = datetime.datetime.now()
        print "结束时间:", CAL_END_TIME
        print "耗时:", CAL_END_TIME - CAL_START_TIME
        return emp_attendances_values
コード例 #36
0
    def get_attendance_detail(self,
                              date_from=None,
                              date_to=None,
                              filter_by=None,
                              employee_ids=None,
                              department_ids=None):
        CAL_START_TIME = datetime.datetime.now()
        print "开始计算出勤明细表:", CAL_START_TIME
        if any((date_from, date_to)) and not all((date_from, date_to)):
            return "miss date_from or date_to"

        if not date_from and not date_to:
            now = datetime.datetime.now()
            date_from = datetime.datetime(now.year, now.month, 1)
            date_to = datetime.datetime(date_from.year, date_from.month + 1, 1)
        elif date_from and date_to:
            date_from = Date.from_string(date_from)
            date_to = Date.from_string(date_to)

        Employee = self.env["hr.employee"].sudo()

        emp_attendances_values = []

        employee_search_domain = []
        if filter_by == "employee" and employee_ids:
            employee_search_domain.append(("id", "in", employee_ids))
        if filter_by == "department" and department_ids:
            employee_search_domain.append(
                ("department_id", "in", department_ids))
        all_employees = Employee.search(employee_search_domain)
        all_employees = sorted(all_employees,
                               key=lambda e:
                               (e.department_id.name
                                if e.department_id else "", e.internal_code))

        for emp in all_employees:
            dt = date_from
            emp_lines = list()
            while dt <= date_to:
                # dt_str = Date.to_string(dt)
                #
                # overtime_durations = emp.get_overtime_hours_on(date_from=dt_str, date_to=dt_str)
                # if dt.weekday() in (5, 6) and (emp.responsibility or not overtime_durations):
                #     dt += datetime.timedelta(days=1)
                #     continue
                #
                # line = dict()
                # line['name'] = emp.name
                # line['emp_dep'] = emp.department_id.name
                # line['emp_code'] = emp.internal_code
                # line['date'] = dt.strftime(DEFAULT_SERVER_DATE_FORMAT)  # + " %A" Date.to_string(dt)
                #
                # start_work_time = emp.get_start_work_time_on(dt_str)
                # line["start_work_time"] = start_work_time.strftime(DEFAULT_SERVER_TIME_FORMAT) \
                #     if start_work_time else None
                #
                # end_work_time = emp.get_end_work_time_on(dt_str)
                # line["end_work_time"] = end_work_time.strftime(DEFAULT_SERVER_TIME_FORMAT) \
                #     if end_work_time else None
                #
                # late_minutes = emp.get_late_minutes_on(dt_str)
                # line["late_minutes"] = round(late_minutes, 2) if late_minutes else None
                #
                # early_minutes = emp.get_early_minutes_on(dt_str)
                # line["early_minutes"] = round(early_minutes, 2) if early_minutes else None
                #
                # work_duration = emp.get_work_duration_on(dt_str)
                # line["work_duration"] = round(work_duration, 2) if work_duration else None
                #
                # if overtime_durations:
                #     line["overtime_stage1"] = overtime_durations.get("stage1", None)
                #     line["overtime_stage2"] = overtime_durations.get("stage2", None)
                #     line["overtime_stage3"] = overtime_durations.get("stage3", None)
                #
                # # line["overtime_hours"] = round(overtime_hours, 2)
                #
                # leaves = emp.get_holiday_on(dt_str)
                # all_leaves = list()
                # for l in leaves.values():
                #     all_leaves.extend(l)
                # line["holiday_total"] = round(sum(l[2].seconds / 3600.0 for l in all_leaves), 2)
                #
                # absent_for_summary = []
                # absent = emp.get_absent_on(dt_str)
                # if absent:
                #     absent_for_summary.append(_("absent"))
                # line["summary"] = string.join(set(leaves.keys() + absent_for_summary), ",")
                # line["forget_card"] = emp.get_forget_card_on(dt_str)

                line = emp.get_attendance_detail_line(dt)
                if line:
                    emp_attendances_values.append(line)
                    emp_lines.append(line)
                dt += datetime.timedelta(days=1)

            if emp_lines:
                emp_total_line = dict()
                emp_total_line["name"] = None
                emp_total_line['emp_dep'] = None
                emp_total_line['emp_code'] = None
                emp_total_line['date'] = '小计'
                emp_total_line['end_work_time'] = None
                emp_total_line['start_work_time'] = None
                emp_total_line['late_minutes'] = sum(l["late_minutes"] or 0
                                                     for l in emp_lines)
                emp_total_line['early_minutes'] = sum(l["early_minutes"] or 0
                                                      for l in emp_lines)
                emp_total_line["work_duration"] = sum(l["work_duration"] or 0
                                                      for l in emp_lines)
                # emp_total_line["late_minutes"] = sum(l["late_minutes"] or 0 for l in emp_lines)
                # line["overtime_stage1"]
                emp_total_line["overtime_stage1"] = sum(
                    l.get("overtime_stage1", None) or 0 for l in emp_lines)
                emp_total_line["overtime_stage2"] = sum(
                    l.get("overtime_stage2", None) or 0 for l in emp_lines)
                emp_total_line["overtime_stage3"] = sum(
                    l.get("overtime_stage3", None) or 0 for l in emp_lines)
                emp_total_line["holiday_total"] = sum(l["holiday_total"] or 0
                                                      for l in emp_lines)
                holiday_names = []
                for l in emp_lines:
                    if l["holiday_detail"]:
                        names = l["holiday_detail"].keys()
                        if names:
                            holiday_names.extend(names)

                emp_total_line["summary"] = string.join(
                    set(holiday_names), ',')
                emp_total_line["forget_card"] = sum(l["forget_card"] or 0
                                                    for l in emp_lines)
                emp_attendances_values.append(emp_total_line)

        CAL_END_TIME = datetime.datetime.now()
        print "结束时间:", CAL_END_TIME
        print "耗时:", CAL_END_TIME - CAL_START_TIME
        return emp_attendances_values
コード例 #37
0
ファイル: hr_employee.py プロジェクト: likaiyuan/hr_sf
    def get_holiday_on(self, date=None):
        self.ensure_one()
        if not date:
            return None

        querying_day = date
        if isinstance(date, datetime.date):
            querying_day = Date.to_string(date)

        leaves = defaultdict(lambda: list())  # [None, None, datetime.timedelta()] _time = datetime.timedelta()

        absent_type_id = self.env.ref("hr_sf.absent_holidays_status").id

        for holiday in self.holidays_ids:
            if not holiday.date_from or not holiday.date_to:
                continue
            if holiday.holiday_status_id.id == absent_type_id:
                continue

            if not all((holiday.morning_start_work_time,
                        holiday.morning_end_work_time,
                        holiday.afternoon_start_work_time,
                        holiday.afternoon_end_work_time)):
                return None

            dt_the_day_morning_start_work_time = datetime.datetime.strptime(
                    "%s %s" % (querying_day, holiday.morning_start_work_time), DEFAULT_SERVER_DATETIME_FORMAT)
            dt_the_day_morning_end_work_time = datetime.datetime.strptime(
                    "%s %s" % (querying_day, holiday.morning_end_work_time), DEFAULT_SERVER_DATETIME_FORMAT)
            dt_the_day_afternoon_start_work_time = datetime.datetime.strptime(
                    "%s %s" % (querying_day, holiday.afternoon_start_work_time), DEFAULT_SERVER_DATETIME_FORMAT)
            dt_the_day_afternoon_end_work_time = datetime.datetime.strptime(
                    "%s %s" % (querying_day, holiday.afternoon_end_work_time), DEFAULT_SERVER_DATETIME_FORMAT)

            dt_holiday_from = Datetime.from_string(holiday.date_from) + datetime.timedelta(hours=8)
            dt_holiday_to = Datetime.from_string(holiday.date_to) + datetime.timedelta(hours=8)
            # deal with morning first
            dt_cal_start = max(dt_the_day_morning_start_work_time, dt_holiday_from)
            dt_cal_start = min(dt_cal_start, dt_the_day_morning_end_work_time)

            dt_cal_end = min(dt_the_day_morning_end_work_time, dt_holiday_to)
            dt_cal_end = max(dt_cal_end, dt_the_day_morning_start_work_time)

            if dt_cal_end > dt_cal_start:
                leaves[holiday.holiday_status_id.name].append((dt_cal_start, dt_cal_end, dt_cal_end - dt_cal_start))
                # leaves[holiday.holiday_status_id.name][0] = dt_cal_start
                # leaves[holiday.holiday_status_id.name][1] = dt_cal_end
                # leaves[holiday.holiday_status_id.name][2] += dt_cal_end - dt_cal_start

            # then deal with afternoon first
            dt_cal_start = max(dt_the_day_afternoon_start_work_time, dt_holiday_from)
            dt_cal_start = min(dt_cal_start, dt_the_day_afternoon_end_work_time)

            dt_cal_end = min(dt_the_day_afternoon_end_work_time, dt_holiday_to)
            dt_cal_end = max(dt_cal_end, dt_the_day_afternoon_start_work_time)

            if dt_cal_end > dt_cal_start:
                leaves[holiday.holiday_status_id.name].append((dt_cal_start, dt_cal_end, dt_cal_end - dt_cal_start))
                # leaves[holiday.holiday_status_id.name][0] = dt_cal_start
                # leaves[holiday.holiday_status_id.name][1] = dt_cal_end
                # leaves[holiday.holiday_status_id.name][2] += dt_cal_end - dt_cal_start

        return leaves
コード例 #38
0
		compute_sudo=False,
		)

	publisher_city = fields.Char(
		'Publisher City',
		related='publisher_id.city')


	_sql_constraints = [
		('name_uniq',
		'UNIQUE (name)',
		'Book title must be unique.')
		]

def _inverse_age(self): today =
	fDate.from_string(fDate.today())
	for book in self.filtered('date_release'):
	d = td(days=book.age_days) - today
	book.date_release = fDate.to_string(d)

def _search_age(self, operator, value):
	today = fDate.from_string(fDate.today())
	value_days = td(days=value)
	value_date = fDate.to_string(today - value_days)
	return [('date_release', operator, value_date)]


@api.model
	def _referencable_models(self):
	models = self.env['res.request.link'].search([])
	return [(x.object, x.name) for x in models]
コード例 #39
0
 def _compute_age(self):
     today = fDate.from_string(fDate.today())
     for book in self.filtered('date_release'):
         delta = (fDate.from_string(book.date_release) - today)
         book.age_days = delta.days
コード例 #40
0
    def get_attendance_statistics(self, date_from=None, date_to=None, filter_by=None, employee_ids=None,
                                  department_ids=None):
        CAL_START_TIME = datetime.datetime.now()
        print "开始计算出勤统计表:", CAL_START_TIME
        if any((date_from, date_to)) and not all((date_from, date_to)):
            return "miss date_from or date_to"

        if not date_from and not date_to:
            now = datetime.datetime.now()
            date_from = datetime.datetime(now.year, now.month, 1)
            date_to = datetime.datetime(date_from.year, date_from.month + 1, 1)
        elif date_from and date_to:
            date_from = Date.from_string(date_from)
            date_to = Date.from_string(date_to)

        Employee = self.env["hr.employee"].sudo()

        employee_search_domain = []
        if filter_by == "employee" and employee_ids:
            employee_search_domain.append(("id", "in", employee_ids))
        if filter_by == "department" and department_ids:
            employee_search_domain.append(("department_id", "in", department_ids))
        all_employees = Employee.search(employee_search_domain)
        all_employees = sorted(all_employees,
                               key=lambda e: (e.department_id.name if e.department_id else "", e.internal_code))

        emp_attendances_values = []
        for emp in all_employees:
            dt = date_from
            emp_lines = list()
            days = 0
            while dt <= date_to:
                line = emp.get_attendance_detail_line(dt)
                if line:
                    emp_lines.append(line)
                days += 1
                dt += datetime.timedelta(days=1)

            if emp_lines:
                emp_total_line = dict()
                emp_total_line["name"] = emp.name
                emp_total_line['emp_dep'] = emp.department_id.name if emp.department_id else ""
                emp_total_line['emp_code'] = emp.internal_code
                # emp_total_line['date'] = '小计'
                # emp_total_line['end_work_time'] = None
                # emp_total_line['start_work_time'] = None
                # emp_total_line['late_minutes'] = sum(l["late_minutes"] or 0 for l in emp_lines)
                # emp_total_line['early_minutes'] = sum(l["early_minutes"] or 0 for l in emp_lines)
                emp_total_line["work_duration"] = round(sum(l.get("work_duration", None) or 0 for l in emp_lines) / 8.0,
                                                        2)
                # emp_total_line["late_minutes"] = sum(l["late_minutes"] or 0 for l in emp_lines)

                emp_total_line["overtime_stage1"] = sum(l.get("overtime_stage1", None) or 0 for l in emp_lines)
                emp_total_line["overtime_stage2"] = sum(l.get("overtime_stage2", None) or 0 for l in emp_lines)
                emp_total_line["overtime_stage3"] = sum(l.get("overtime_stage3", None) or 0 for l in emp_lines)

                holiday_detail = defaultdict(lambda: 0)
                for line in emp_lines:
                    if line.get("holiday_detail", None):
                        for holiday in line["holiday_detail"]:
                            holiday_detail[holiday] += round(
                                    sum(h[2].seconds / 3600.0 for h in line["holiday_detail"][holiday]), 2)

                emp_total_line["holiday_detail"] = holiday_detail

                emp_total_line["holiday_total"] = sum(l["holiday_total"] or 0 for l in emp_lines)

                # emp_total_line["summary"] = string.join(set(l["summary"] for l in emp_lines))
                emp_total_line["forget_card"] = sum(l["forget_card"] or 0 for l in emp_lines)
                #
                emp_attendances_values.append(emp_total_line)

        CAL_END_TIME = datetime.datetime.now()
        print "结束时间:", CAL_END_TIME
        print "耗时:", CAL_END_TIME - CAL_START_TIME
        return emp_attendances_values
コード例 #41
0
 def _search_age(operator, value):
     today = fDate.from_string(fDate.today())
     value_days = td(days=value)
     value_date = fDate.to_string(today - value_days)
     return [('date_release', operator, value_date)]
コード例 #42
0
    def get_attendance_detail(self, date_from=None, date_to=None, filter_by_employee=None, employee_ids=None):
        CAL_START_TIME = datetime.datetime.now()
        print "开始计算出勤明细表:", CAL_START_TIME
        if any((date_from, date_to)) and not all((date_from, date_to)):
            return "miss date_from or date_to"

        if not date_from and not date_to:
            now = datetime.datetime.now()
            date_from = datetime.datetime(now.year, now.month, 1)
            date_to = datetime.datetime(date_from.year, date_from.month + 1, 1)
        elif date_from and date_to:
            date_from = Date.from_string(date_from)
            date_to = Date.from_string(date_to)

        Employee = self.env["hr.employee"].sudo()

        emp_attendances_values = []

        employee_search_domain = []
        if filter_by_employee and employee_ids:
            employee_search_domain.append(("id", "in", employee_ids))
        all_employees = Employee.search(employee_search_domain)

        for emp in all_employees:
            dt = date_from
            emp_lines = list()
            while dt <= date_to:
                dt_str = Date.to_string(dt)

                overtime_hours = emp.get_overtime_hours_on(date_from=dt_str, date_to=dt_str)
                if dt.weekday() in (5, 6) and (emp.responsibility or not overtime_hours):
                    dt += datetime.timedelta(days=1)
                    continue

                line = dict()
                line['name'] = emp.name
                line['emp_dep'] = emp.department_id.name
                line['emp_code'] = emp.internal_code
                line['date'] = dt.strftime(DEFAULT_SERVER_DATE_FORMAT)  # + " %A" Date.to_string(dt)

                start_work_time = emp.get_start_work_time_on(dt_str)
                line["start_work_time"] = start_work_time.strftime(DEFAULT_SERVER_TIME_FORMAT) \
                    if start_work_time else None

                end_work_time = emp.get_end_work_time_on(dt_str)
                line["end_work_time"] = end_work_time.strftime(DEFAULT_SERVER_TIME_FORMAT) \
                    if end_work_time else None

                late_minutes = emp.get_late_minutes_on(dt_str)
                line["late_minutes"] = round(late_minutes, 2) if late_minutes else None

                early_minutes = emp.get_early_minutes_on(dt_str)
                line["early_minutes"] = round(early_minutes, 2) if early_minutes else None

                work_duration = emp.get_work_duration_on(dt_str)
                line["work_duration"] = round(work_duration, 2) if work_duration else None

                line["overtime_hours"] = round(overtime_hours, 2)

                leaves = emp.get_holiday_on(dt_str)
                all_leaves = list()
                for l in leaves.values():
                    all_leaves.extend(l)
                line["holiday_total"] = round(sum(l[2].seconds / 3600.0 for l in all_leaves),2)

                absent_for_summary = []
                absent = emp.get_absent_on(dt_str)
                if absent:
                    absent_for_summary.append(_("absent"))
                line["summary"] = string.join(set(leaves.keys() + absent_for_summary), ",")
                line["forget_card"] = emp.get_forget_card_on(dt_str)

                emp_attendances_values.append(line)
                emp_lines.append(line)
                dt += datetime.timedelta(days=1)

            if emp_lines:
                emp_total_line = dict()
                emp_total_line["name"] = None
                emp_total_line['emp_dep'] = None
                emp_total_line['emp_code'] = None
                emp_total_line['date'] = '小计'
                emp_total_line['end_work_time'] = None
                emp_total_line['start_work_time'] = None
                emp_total_line['late_minutes'] = sum(l["late_minutes"] or 0 for l in emp_lines)
                emp_total_line['early_minutes'] = sum(l["early_minutes"] or 0 for l in emp_lines)
                emp_total_line["work_duration"] = sum(l["work_duration"] or 0 for l in emp_lines)
                emp_total_line["late_minutes"] = sum(l["late_minutes"] or 0 for l in emp_lines)

                emp_total_line["overtime_hours"] = sum(l["overtime_hours"] or 0 for l in emp_lines)
                emp_total_line["holiday_total"] = sum(l["holiday_total"] or 0 for l in emp_lines)
                emp_total_line["summary"] = string.join(set(l["summary"] for l in emp_lines))
                emp_total_line["forget_card"] = sum(l["forget_card"] or 0 for l in emp_lines)
                emp_attendances_values.append(emp_total_line)

        CAL_END_TIME = datetime.datetime.now()
        print "结束时间:", CAL_END_TIME
        print "耗时:", CAL_END_TIME - CAL_START_TIME
        return emp_attendances_values
コード例 #43
0
ファイル: person.py プロジェクト: MostlyOpen/odoo_addons
 def _compute_age_days(self):
     today = fDate.from_string(fDate.today())
     for person in self.filtered('birthday'):
         delta = (today - fDate.from_string(person.birthday))
         person.age_days = delta.days
コード例 #44
0
    def test_01_max_date(self):
        next_year = '%s-01-01' % (int(self.today[:4]) + 1)
        next_year_feb = '%s-02-01' % (int(self.today[:4]) + 1)
        next_year_feb6 = '%s-02-06' % (int(self.today[:4]) + 1)

        delay = Date.to_string(
            Date.from_string(self.today) + timedelta(days=self.seller_delay))
        self.assertEqual(
            self.product.max_incoming_stock_date, delay)
        self.product.max_incoming_stock_date_override = True
        self.product.max_incoming_stock_date_override_value = next_year
        self.assertEqual(
            self.product.max_incoming_stock_date, next_year)
        self.assertEqual(
            self.bom_product.max_incoming_stock_date, next_year)
        self.product.max_incoming_stock_date_override = False
        picking_in = self.PickingObj.create({
            'partner_id': self.partner_delta_id,
            'picking_type_id': self.picking_type_in})
        self.MoveObj.create({
            'name': self.product.name,
            'product_id': self.product.id,
            'product_uom_qty': 1,
            'product_uom': self.product.uom_id.id,
            'picking_id': picking_in.id,
            'location_id': self.supplier_location,
            'location_dest_id': self.stock_location,
            'date_expected': next_year_feb,
        })
        picking_in.action_confirm()
        self.assertEqual(self.product.max_incoming_stock_date, next_year_feb)
        self.assertEqual(
            self.bom_product.max_incoming_stock_date, next_year_feb)
        self.product.max_incoming_stock_date_override = True
        self.product.max_incoming_stock_date_override_value = self.today
        self.assertEqual(self.product.max_incoming_stock_date, self.today)
        self.env['product.product'].reset_max_incoming_date_override()
        self.assertEqual(self.product.max_incoming_stock_date, next_year_feb)

        # When a product has to be ordered, add supplier lead time to max date
        # expected of running orders
        picking_out = self.PickingObj.create({
            'partner_id': self.partner_delta_id,
            'picking_type_id': self.picking_type_out})
        move = self.MoveObj.create({
            'name': self.product.name,
            'product_id': self.product.id,
            'product_uom_qty': 1,
            'product_uom': self.product.uom_id.id,
            'picking_id': picking_out.id,
            'location_dest_id': self.customer_location,
            'location_id': self.stock_location,
            'date_expected': next_year,
        })
        picking_out.action_confirm()
        self.product.refresh()
        self.assertEqual(self.product.max_incoming_stock_date, next_year_feb)

        # Test that we can modify the picking's max_date (#2800)
        # Call _register_hook manually because tests run before Odoo does
        self.env['stock.picking']._register_hook()
        picking_out.write({'max_date': next_year_feb6})
        self.assertEqual(move.date_expected, next_year_feb6 + ' 00:00:00')
        self.assertEqual(picking_out.max_date, next_year_feb6 + ' 00:00:00')
コード例 #45
0
ファイル: person.py プロジェクト: MostlyOpen/odoo_addons
 def _search_age_days(self, operator, value):
     today = fDate.from_string(fDate.today())
     value_days = td(days=value)
     value_date = fDate.to_string(today - value_days)
     print '>>>>>>>>>', [('birthday', operator, value_date)]
     return [('birthday', operator, value_date)]
コード例 #46
0
 def _search_age(self, operator, value):
     today = fDate.from_string(fDate.today())
     value_days = td(days=value)
     value_date = fDate.to_string(today - value_days)
     return [('date_release', operator, value_date)]