Exemplo n.º 1
0
    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]
 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
Exemplo n.º 3
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
Exemplo n.º 4
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
Exemplo n.º 5
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)
	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
	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
Exemplo n.º 8
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)
    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
Exemplo n.º 10
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
    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
Exemplo n.º 12
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
 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)]
Exemplo n.º 14
0
 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)
Exemplo n.º 15
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)]
    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
Exemplo n.º 17
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]
 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
Exemplo n.º 19
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
Exemplo n.º 20
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
 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
Exemplo n.º 22
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
Exemplo n.º 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)
Exemplo n.º 24
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
Exemplo n.º 25
0
 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
Exemplo n.º 26
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')
Exemplo n.º 27
0
 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)]
 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)