예제 #1
0
 def onchange_range(self, dtrange, date_from, date_till, resetRange=False):
     value = {}
     res = {
         "value" : value
     }
     
     if not date_from or resetRange:
         if dtrange == "month":
             date_from = util.getFirstOfLastMonth()
         elif dtrange == "week":
             day = util.strToDate(util.currentDate())
             day = day - relativedelta(days=(7+day.weekday()))
             date_from = util.dateToStr(day)
         else:
             day = util.strToDate(util.currentDate())
             day = day - relativedelta(days=1)
             date_from = util.dateToStr(day)
   
     if dtrange == "month":
         dt_date_from = util.strToDate(date_from)
         date_till = util.dateToStr(dt_date_from + relativedelta(months=1,days=-1))
     elif dtrange == "week":
         dt_date_from = util.strToDate(date_from)
         weekday = dt_date_from.weekday()
         date_till = util.dateToStr(dt_date_from + relativedelta(days=weekday+(6-weekday)))
     else:
         date_till = date_from
         
         
     value["date_from"] = date_from
     value["date_till"] = date_till
     return res
예제 #2
0
 def _compute_chicken_age(self):
     logbook = self.logbook_id
     dt_start = util.strToDate(logbook.date_start)
     dt_cur = util.strToDate(self.day)
     diff = dt_cur - dt_start
     self.chicken_age = logbook.chicken_age + diff.days
     self.chicken_age_weeks = self.chicken_age / 7.0
예제 #3
0
    def _update_pos_rate(self, cr, uid, start_date=None, history_months=1, nofilter=False, context=None):
        
        ranges = []
        if not nofilter:
            
            if not start_date:
                cr.execute("SELECT MAX(date_order) FROM pos_order")
                res = cr.fetchone()
                start_date = res and res[0] and util.strToDate(res[0]) or datetime.now()
                start_date = start_date - relativedelta(months=history_months)
                start_date = util.dateToStr(start_date)
            
            ranges.append("o.date_order >= '%s'" % start_date)
            
            if history_months:
                history_start_dt = util.strToDate(start_date) - relativedelta(years=1)
                history_delta = relativedelta(weeks=(history_months*2))
                history_start = util.dateToStr(history_start_dt - history_delta)
                history_end =  util.dateToStr(history_start_dt + history_delta)
                ranges.append("(o.date_order >= '%s' AND o.date_order <= '%s')" % (history_start, history_end))
            
        rangeStr = ranges and "AND (%s)" % " OR ".join(ranges) or ""
        query = ("SELECT p.id, COUNT(l) FROM product_product p  "
                   " INNER JOIN product_template pt ON pt.id = p.product_tmpl_id " 
                   " LEFT JOIN pos_order_line l ON l.product_id = p.id "  
                   " LEFT JOIN pos_order o ON o.id = l.order_id "
                   " WHERE pt.available_in_pos %s " 
                   " GROUP BY 1 " % rangeStr)
        cr.execute(query)
        
        res = cr.fetchall()
        total = 0.0        
        
        for product_id, usage in res:
            if usage:
                total += usage
                
        if total:
            for product_id, usage in res:
                if usage:
                    rate = (usage / total)*100.0
                    self.write(cr, uid, [product_id], {"pos_rate" : rate}, context=context)
                else:
                    self.write(cr, uid, [product_id], {"pos_rate" : 0.0}, context=context)

        # reset non used
        cr.execute("UPDATE product_product SET pos_rate = 0 WHERE product_tmpl_id IN "
                   " (SELECT pt.id FROM product_template pt WHERE NOT pt.available_in_pos) ")
        
        # update templates
        cr.execute("UPDATE product_template SET tmpl_pos_rate = 0")
        cr.execute("UPDATE product_template "
                   " SET tmpl_pos_rate = t.pos_rate " 
                   " FROM ( "                   
                   "  SELECT product_tmpl_id, SUM(p.pos_rate) AS pos_rate "
                   "  FROM product_product p " 
                   "  GROUP BY 1 "
                   " ) t "
                   " WHERE t.product_tmpl_id = id AND t.pos_rate IS NOT NULL")
예제 #4
0
 def _semester_weeks(self, cr, uid, ids, field_name, arg, context=None):
     res = dict.fromkeys(ids)
     for semester in self.browse(cr, uid, ids, context=context):
         sem_start_dt = util.strToDate(semester.date_start)
         sem_end_dt = util.strToDate(semester.date_end)
         sem_duration = sem_end_dt - sem_start_dt
         sem_weeks = round(sem_duration.days / 7.0)
         res[semester.id] = sem_weeks - semester.holiday_weeks
     return res
예제 #5
0
 def _amount(self):
     if ( self.product_id and self.date_from and self.date_to and self.date_to >= self.date_from ):
         dt_from = util.strToDate(self.date_from)
         dt_to = util.strToDate(self.date_to)
         dt_diff = dt_to - dt_from
         self.days = dt_diff.days + 1
         self.amount = self.days * self.product_id.kw * 24
     else:
         self.amount = 0.0
         self.days = 0.0
예제 #6
0
    def logbook_weeks(self):
        weeks = []

        f = format.LangFormat(self._cr, self._uid, self._context)
        week_start = util.getFirstOfWeek(self.date_start)
        date_end = self.date_end or util.getPrevDayDate(
            util.getFirstOfNextWeek(util.currentDate()))

        while week_start <= date_end:
            week_str = datetime.strftime(util.strToDate(week_start),
                                         _("CW %W"))
            week_first = week_start
            week_start = util.getFirstOfNextWeek(week_start)
            week_end = util.getPrevDayDate(week_start)

            weeks.append({
                "name": week_str,
                "date_start": week_first,
                "group": week_first[:7],
                "start": f.formatLang(week_first, date=True),
                "end": f.formatLang(week_end, date=True)
            })

        weeks.sort(key=lambda v: v["date_start"], reverse=True)
        return weeks
예제 #7
0
파일: timesheet.py 프로젝트: suningwz/fdoo
    def get_leaves(self, cr, uid, sid, context=None):
        res = {}
        sheet = self.browse(cr, uid, sid, context)
        employee_obj = self.pool.get("hr.employee")
        contract = employee_obj._get_contract(cr,
                                              uid,
                                              sheet.employee_id.id,
                                              date_from=sheet.date_from,
                                              date_to=sheet.date_to,
                                              context=context)
        if contract:
            cr.execute(
                "SELECT id, name, date_from, date_to FROM resource_calendar_leaves "
                " WHERE resource_id = %s OR resource_id IS NULL "
                "  AND  (    (date_from >= %s AND date_from <= %s) "
                " OR (date_to >= %s AND date_to <= %s ) "
                " OR (date_from <= %s AND date_to >= %s ) )",
                (sheet.employee_id.resource_id.id, sheet.date_from,
                 sheet.date_to, sheet.date_from, sheet.date_to,
                 sheet.date_from, sheet.date_to))

            for oid, name, leave_date_from, leave_date_to in cr.fetchall():

                date_from = util.timeToDateStr(leave_date_from)
                if date_from < sheet.date_from:
                    date_from = sheet.date_from

                date_to = util.timeToDateStr(leave_date_to)
                if date_to > sheet.date_to:
                    date_to = sheet.date_to

                d_datefrom = util.strToDate(date_from)
                d_dateto = util.strToDate(date_to)
                d_cur = d_datefrom
                d_delta = relativedelta(days=1)

                while d_cur <= d_dateto:
                    cur_date = util.dateToStr(d_cur)
                    leaves = res.get(cur_date)
                    if not leaves:
                        leaves = []
                        res[cur_date] = leaves

                    leaves.append((oid, name))
                    d_cur += d_delta

        return res
예제 #8
0
파일: fpos.py 프로젝트: funkring/fdoo-extra
    def _cashreport_range(self, start_date=None, offset=0):
        if not start_date:
            start_date = util.currentDate()

        cashreport_name = _("Cashreport")
        date_from = start_date
        date_till = start_date
        f = format.LangFormat(self._cr, self._uid, self._context)

        # calc month
        if self.range == "month":
            dt_date_from = util.strToDate(util.getFirstOfMonth(start_date))
            if offset:
                dt_date_from += relativedelta(months=offset)

            date_from = util.dateToStr(dt_date_from)
            date_till = util.getEndOfMonth(dt_date_from)

            month_name = helper.getMonthName(self._cr, self._uid, dt_date_from.month, context=self._context)
            cashreport_name = "%s - %s %s" % (cashreport_name, month_name, dt_date_from.year)

        # calc week
        elif self.range == "week":
            dt_date_from = util.strToDate(start_date)
            if offset:
                dt_date_from += relativedelta(weeks=offset)

            weekday = dt_date_from.weekday()
            dt_date_from = dt_date_from + relativedelta(days=-weekday)
            kw = dt_date_from.isocalendar()[1]
            date_from = util.dateToStr(dt_date_from)
            date_till = util.dateToStr(dt_date_from + relativedelta(days=weekday + (6 - weekday)))
            cashreport_name = _("%s - CW %s %s") % (cashreport_name, kw, dt_date_from.year)

        # calc date
        else:
            if offset:
                dt_date_from = util.strToDate(start_date)
                dt_date_from += relativedelta(days=offset)
                date_from = util.dateToStr(dt_date_from)
                date_till = date_from

            cashreport_name = _("%s - %s") % (cashreport_name, f.formatLang(date_from, date=True))

        return (date_from, date_till, cashreport_name)
예제 #9
0
파일: timesheet.py 프로젝트: suningwz/fdoo
 def _total_target(self, cr, uid, ids, name, arg, context=None):
     res = dict.fromkeys(ids, 0.0)
     working_hour_obj = self.pool.get("resource.calendar")
     employee_obj = self.pool.get("hr.employee")
     for sheet in self.browse(cr, uid, ids, context):
         contract = employee_obj._get_contract(cr,
                                               uid,
                                               sheet.employee_id.id,
                                               date_from=sheet.date_from,
                                               date_to=sheet.date_to,
                                               context=context)
         if contract:
             res[sheet.id] = working_hour_obj.interval_hours_without_leaves(
                 cr, uid, contract["working_hours"].id,
                 util.strToDate(contract["date_from"]),
                 util.strToDate(contract["date_to"]),
                 sheet.employee_id.resource_id.id)
     return res
예제 #10
0
    def _check_birthday(self, cr, uid):
        dt_current = util.strToDate(util.currentDate())
        date_search = "%%-%02d-%02d" % (dt_current.month,dt_current.day)
        template_xmlid = "partner_birthday_mail.email_partner_birthday"

        partner_ids = self.search(cr, uid, [("birthday","ilike",date_search)])
        template_obj = self.pool["email.template"]
        template_id = self.pool["ir.model.data"].xmlid_to_res_id(cr, uid, template_xmlid)
        if template_id:
            for partner in self.browse(cr, uid, partner_ids):
                template_obj.send_mail(cr, uid, template_id, partner.id, force_send=True)
예제 #11
0
 def _get_date_from(self, cr, uid, str_date, context=None):
     d_date = util.strToDate(str_date)
     user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
     r = user.company_id and user.company_id.timesheet_range or 'month'
     if r == 'month':
         return d_date.strftime('%Y-%m-01')
     elif r == 'week':
         return (d_date +
                 relativedelta(weekday=0, weeks=-1)).strftime('%Y-%m-%d')
     elif r == 'year':
         return d_date.strftime('%Y-01-01')
     return d_date.strftime('%Y-%m-%d')
예제 #12
0
파일: timesheet.py 프로젝트: suningwz/fdoo
 def _total_target(self, cr, uid, ids, field_name, arg, context=None):
     res = dict.fromkeys(ids, 0.0)
     working_hour_obj = self.pool.get("resource.calendar")
     employee_obj = self.pool.get("hr.employee")
     for daily_sheet in self.browse(cr, uid, ids, context):
         sheet = daily_sheet.sheet_id
         date_from = daily_sheet.name
         date_to = util.dateToStr(
             util.getLastTimeOfDay(util.strToDate(date_from)))
         contract = employee_obj._get_contract(cr,
                                               uid,
                                               sheet.employee_id.id,
                                               date_from=date_from,
                                               date_to=date_to,
                                               context=context)
         if contract:
             res[sheet.id] = working_hour_obj.interval_hours_without_leaves(
                 cr, uid, contract["working_hours"].id,
                 util.strToDate(contract["date_from"]),
                 util.strToDate(contract["date_to"]),
                 sheet.employee_id.resource_id.id)
     return res
예제 #13
0
 def line_next(self,cr,uid,profile,profile_line,date_current,date_due):
     if not date_due:
         return None
     date_current = util.strToDate(date_current)
     date_due = util.strToDate(date_due)        
     #check if profile 
     if profile_line and profile_line.profile_id.id != profile.id:
         profile_line=None            
     #calc next line
     delta = date_current-date_due        
     line_next = None
     #
     if ( delta.days > 0 ):            
         profile_line_obj = self.pool.get("account.dunning_profile_line")
         lines = profile_line_obj.browse(cr,uid,profile_line_obj.search(cr,uid,[("profile_id","=",profile.id)],order="sequence asc"))
         for line in lines:
             remind_date = date_due+relativedelta(days=line.delay)
             if remind_date <= date_current:
                 line_next = line
                 if not profile_line or line_next.sequence > profile_line.sequence:
                     break            
     return line_next
예제 #14
0
 def holidays_validate(self, cr, uid, ids, context=None):
     """ Add Resource Leaves """
     if super(hr_holidays, self).holidays_validate(cr,
                                                   uid,
                                                   ids,
                                                   context=context):
         data_holiday = self.browse(cr, uid, ids, context=context)
         employee_obj = self.pool.get("hr.employee")
         obj_res_leave = self.pool.get('resource.calendar.leaves')
         for record in data_holiday:
             # only holidays from employees
             if record.holiday_type == 'employee' and record.type == 'remove':
                 # get holiday date
                 date_from = helper.strToLocalDateStr(
                     cr, uid, record.date_from, context)
                 date_to = util.dateToStr(
                     util.getLastTimeOfDay(
                         util.strToDate(
                             helper.strToLocalDateStr(
                                 cr, uid, record.date_to, context))))
                 # get contract
                 contract = employee_obj._get_contract(
                     cr,
                     uid,
                     record.employee_id.id,
                     date_from=date_from,
                     date_to=date_to,
                     context=context)
                 if contract:
                     vals = {
                         'name': record.name,
                         'calendar_id': contract["working_hours"].id,
                         'resource_id': record.employee_id.resource_id.id,
                         'date_from': date_from,
                         'date_to': date_to,
                         'holiday_id': record.id
                     }
                     leave_id = obj_res_leave.create(cr, uid, vals)
                     self.write(cr, uid, ids, {'leave_id': leave_id})
         return True
     return False
예제 #15
0
파일: timesheet.py 프로젝트: suningwz/fdoo
 def get_timesheet_data(self, cr, uid, id, context=None):
     days = super(hr_timesheet_sheet,
                  self).get_timesheet_data(cr, uid, id, context=context)
     working_hour_obj = self.pool.get("resource.calendar")
     employee_obj = self.pool.get("hr.employee")
     sheet = self.browse(cr, uid, id, context)
     for key, value in days.items():
         contract = employee_obj._get_contract(cr,
                                               uid,
                                               sheet.employee_id.id,
                                               date_from=key,
                                               date_to=key,
                                               context=context)
         if contract:
             dt = util.strToDate(key)
             value[
                 "total_target"] = working_hour_obj.interval_hours_without_leaves(
                     cr, uid, contract["working_hours"].id, dt, dt,
                     sheet.employee_id.resource_id.id) or 0.0
             value["total_saldo"] = (value.get("total_attendance_day")
                                     or 0.0) - value["total_target"]
     return days
예제 #16
0
파일: timesheet.py 프로젝트: suningwz/fdoo
    def _total_current_target(self,
                              cr,
                              uid,
                              ids,
                              field_name,
                              arg,
                              context=None):
        res = dict.fromkeys(ids, 0.0)
        working_hour_obj = self.pool.get("resource.calendar")
        employee_obj = self.pool.get("hr.employee")
        for sheet in self.browse(cr, uid, ids, context):
            contract = employee_obj._get_contract(cr,
                                                  uid,
                                                  sheet.employee_id.id,
                                                  date_from=sheet.date_from,
                                                  date_to=sheet.date_to,
                                                  context=context)
            if contract:
                sheet_now = datetime.now()
                sheet_from = util.strToDate(sheet.date_from)
                sheet_to = util.strToDate(sheet.date_to)

                if sheet_to.date() < sheet_now.date(
                ) or not sheet_from.date() < sheet_now.date():
                    res[sheet.
                        id] = working_hour_obj.interval_hours_without_leaves(
                            cr, uid, contract["working_hours"].id,
                            util.strToDate(contract["date_from"]),
                            util.strToDate(contract["date_to"]),
                            sheet.employee_id.resource_id.id)
                else:
                    res[sheet.
                        id] = working_hour_obj.interval_hours_without_leaves(
                            cr, uid, contract["working_hours"].id,
                            util.strToDate(contract["date_from"]),
                            util.strToDate(contract["date_to"]),
                            sheet.employee_id.resource_id.id)
        return res
예제 #17
0
파일: company.py 프로젝트: suningwz/fdoo
 def nonworking_day_count(self,cr,uid,company,start_date,end_date,context=None):        
     if company.calendar_id:            
         cal_obj = self.pool.get("resource.calendar")
         return cal_obj.nonworking_day_count(cr,uid,company.calendar_id,util.strToDate(start_date),util.strToDate(end_date))
     else:
         return 0
예제 #18
0
    def get_timesheet_data(self, cr, uid, oid, context=None):
        #inner function for get lines
        def _get_attendances(in_days, in_day):
            data = in_days.get(in_day, None)
            if data == None:
                data = {}
                in_days[in_day] = data

            attendance = data.get("attendances", None)
            if attendance == None:
                attendance = []
                in_days[in_day]["attendances"] = attendance

            return attendance

        timesheet = self.browse(cr, uid, oid, context)
        attendance_obj = self.pool.get("hr.attendance")
        attendance_ids = attendance_obj.search(
            cr, uid, [("sheet_id", "=", timesheet.id)], order="name asc")

        next_range = {"day": None, "from": None, "to": None}

        days = {}
        for att in attendance_obj.browse(cr, uid, attendance_ids, context):
            cur_day = util.timeToDateStr(att.name)
            if att.action == "sign_in":
                next_range = {
                    "day": cur_day,
                    "from": helper.strToLocalTimeStr(cr, uid, att.name,
                                                     context),
                    "to": None
                }
                _get_attendances(days, cur_day).append(next_range)
            elif att.action == "sign_out":
                if next_range["day"] != cur_day:
                    next_range = {
                        "day": cur_day,
                        "from": None,
                        "to": helper.strToLocalTimeStr(cr, uid, att.name,
                                                       context)
                    }
                    _get_attendances(days, cur_day).append(next_range)
                else:
                    next_range["to"] = helper.strToLocalTimeStr(
                        cr, uid, att.name, context)

        leaves = self.get_leaves(cr, uid, oid, context)
        date_from = util.strToDate(timesheet.date_from)
        date_to = util.strToDate(timesheet.date_to)
        date_cur = date_from
        delta_day = relativedelta(days=1)
        range_open = False

        while date_cur <= date_to:
            date_cur_str = util.dateToStr(date_cur)
            attendances = _get_attendances(days, date_cur_str)

            days[date_cur_str]['total_attendance_day'] = 0.0
            days[date_cur_str]['total_timesheet_day'] = 0.0
            days[date_cur_str]['total_difference_day'] = 0.0

            leaves_for_day = leaves.get(date_cur_str)
            if leaves_for_day:
                days[date_cur_str]["leaves"] = leaves_for_day

            if not attendances and range_open:
                attendances.append({
                    "day": date_cur_str,
                    "from": date_cur_str + " 00:00:00",
                    "to": date_cur_str + " 24:00:00"
                })
            elif attendances:
                if range_open:
                    attendances[0]["from"] = date_cur_str + " 00:00:00"
                    range_open = False
                last_range = attendances[-1]
                if not last_range.get("to"):
                    range_open = True
                    last_range["to"] = util.timeToStr(date_cur + delta_day)
            date_cur += delta_day

        #get total days
        cr.execute(
            'SELECT day.name, day.total_attendance, day.total_timesheet, day.total_difference\
                FROM hr_timesheet_sheet_sheet AS sheet \
                LEFT JOIN hr_timesheet_sheet_sheet_day AS day \
                    ON (sheet.id = day.sheet_id \
                        AND day.name IN %s) \
                WHERE sheet.id = %s', (tuple(days.keys()), oid))

        for total_day in cr.fetchall():
            if total_day[0]:
                days[total_day[0]]['total_attendance_day'] = total_day[1]
                days[total_day[0]]['total_timesheet_day'] = total_day[2]
                days[total_day[0]]['total_difference_day'] = total_day[3]

        #get analytic lines
        line_obj = self.pool.get("hr.analytic.timesheet")
        for key, value in days.items():
            value["lines"] = line_obj.search(cr,
                                             uid,
                                             [("date", "=", key),
                                              ("sheet_id", "=", timesheet.id)],
                                             order="id asc")

        return days
예제 #19
0
            def exportInvoice(invoice):
                company = invoice.company_id
                account_payable = invoice.partner_id.property_account_payable
                account_receivable = invoice.partner_id.property_account_receivable
                country = invoice.partner_id.country_id
                country_code = country and country.code or ""
                foreigner = country_code and "AT" != country.code
                european_union = False
                if foreigner and invoice.partner_id.vat:
                    european_union = True

                area = "I"
                if foreigner:
                    if european_union:
                        area = "EU"
                    elif invoice.type in ["out_invoice", "out_refund"]:
                        area = "A"
                    else:
                        area = "D"

                bmd_text = [invoice.number]
                if invoice.name:
                    bmd_text.append(invoice.name)

                # check/trim period
                period = invoice.period_id
                bookingdate = invoice.date_invoice
                if bookingdate < period.date_start or bookingdate > period.date_stop:
                    bookingdate = period.date_stop

                bmd_line = {
                    "bereich":
                    area,
                    "satzart":
                    "0",
                    "invoice_id":
                    invoice.id,
                    "partner_id":
                    invoice.partner_id.id,
                    "buchdat":
                    bookingdate,
                    "belegdat":
                    invoice.date_invoice,
                    "belegnr":
                    self.belegnr_get(invoice.number),
                    "bucod":
                    "1",
                    "zziel":
                    "0",
                    "text":
                    ":".join(bmd_text),
                    "gegenbuchkz":
                    "E",
                    "verbuchkz":
                    "A",
                    "symbol": (invoice.journal_id and invoice.journal_id.code)
                    or ""
                }

                sign = 1.0
                if invoice.type == "out_refund":
                    sign = -1.0

                if invoice.type in ("in_refund", "in_invoice"):
                    if (invoice.type == "in_invoice"):
                        sign = -1
                    bmd_line["bucod"] = "2"
                    bmd_line["ebkennz"] = "1"
                    bmd_line[
                        "konto"] = account_payable and account_payable.code or ""
                else:
                    bmd_line[
                        "konto"] = account_receivable and account_receivable.code or ""

                if invoice.date_due and invoice.date_invoice:
                    bmd_line["zziel"] = (
                        util.strToDate(invoice.date_due) -
                        util.strToDate(invoice.date_invoice)).days

                accounts = {}
                for line in invoice.invoice_line:
                    account = line.account_id
                    taxes = line.invoice_line_tax_id
                    product = line.product_id
                    steucod = ""

                    # Eingangs- bzw. Lieferanten Rechnungen
                    if invoice.type in ["in_invoice", "in_refund"]:
                        # Für Produkt Eingang/Import werden die lokalen Steuern des Produkt/Mapping verwendet
                        if foreigner:
                            if product:
                                taxes = line.product_tax_ids
                            # Wenn kein Produkt angegeben wurde, wird ein reverse mapping der Steuer versucht
                            # falls ein Steuermapping verwendet wird
                            elif invoice.fiscal_position:
                                try:
                                    taxes = fpos_obj.unmap_tax(
                                        cr, uid, invoice.fiscal_position,
                                        taxes)
                                except Exception as e:
                                    raise osv.except_osv(
                                        "Fehler",
                                        "Steuerumschlüsselungsfehler bei Rechnung %s"
                                        % invoice.number)

                        if european_union:
                            steucod = "09"  #Einkauf innergem. Erwerb, wenn VSt-Abzug besteht

                        if product:
                            if european_union and product.type == "service":
                                steucod = "19"  #Reverse Charge mit Vorsteuer"
                    # Ausgangs- bzw. Rechnungen an Kunden
                    elif invoice.type in ["out_invoice", "out_refund"]:
                        if european_union:
                            steucod = "07"  #Innergemeinschaftliche Lieferung

                    tax = taxes and int(taxes[0].amount * 100) or 0
                    account_key = (account.code, tax, steucod)
                    account_data = accounts.get(account_key)
                    if not account_data:
                        account_data = BmdAccountData(account.code, tax,
                                                      steucod)
                        accounts[account_key] = account_data

                    line_total = tax_obj.compute_all(
                        cr,
                        uid,
                        taxes,
                        line.price_unit * (1 - (line.discount or 0.0) / 100.0),
                        line.quantity,
                        product=line.product_id.id,
                        partner=line.invoice_id.partner_id.id)

                    line_sum = line.price_subtotal_taxed
                    line_tax = line_total["total_included"] - line_total[
                        "total"]

                    account_data.amount += line_sum
                    account_data.amount_tax += line_tax

                def addExportLine(account_data):
                    bmd_line_copy = bmd_line.copy()
                    bmd_line_copy["gkto"] = account_data.code
                    bmd_line_copy["betrag"] = account_data.amount * sign
                    bmd_line_copy["mwst"] = account_data.tax
                    bmd_line_copy["steuer"] = round(
                        (-1.0 * sign) * account_data.amount_tax, 2)

                    if account_data.steucod:
                        bmd_line_copy["steucod"] = account_data.steucod

                    if receipt_primary:
                        if bmd_line_copy["bucod"] == "1":
                            bmd_line_copy["bucod"] = "2"
                        if bmd_line_copy["bucod"] == "2":
                            bmd_line_copy["bucod"] = "1"
                        tmp = bmd_line_copy["konto"]
                        bmd_line_copy["konto"] = bmd_line_copy["gkto"]
                        bmd_line_copy["gkto"] = tmp
                        bmd_line_copy[
                            "betrag"] = bmd_line_copy["betrag"] * -1.0
                        bmd_line_copy[
                            "steuer"] = bmd_line_copy["steuer"] * -1.0

                    # Steuern auf Null setzen wenn Drittland
                    if area == "D":
                        bmd_line_copy["mwst"] = 0
                        bmd_line_copy["steuer"] = 0.0

                    #
                    bmd_line_copy["account_id"] = account_obj.search_id(
                        cr, uid, [("company_id", "=", company.id),
                                  ("code", "=", bmd_line_copy["konto"])])
                    bmd_line_copy["account_contra_id"] = account_obj.search_id(
                        cr, uid, [("company_id", "=", company.id),
                                  ("code", "=", bmd_line_copy["gkto"])])
                    export_lines.append((0, 0, bmd_line_copy))

                for account_data in accounts.values():
                    addExportLine(account_data)
 def _start_date(self, reg_data):
     start_date = util.strToDate(reg_data["start_date"])
     return datetime.strftime(start_date, self.localcontext["start_date_format"])
예제 #21
0
    def logbook_week(self, date_start=None):
        if not date_start:
            date_start = util.currentDate()

        f = format.LangFormat(self._cr, self._uid, self._context)

        week_start = util.getFirstOfWeek(date_start)
        week_next = util.getFirstOfNextWeek(date_start)
        week_str = datetime.strftime(util.strToDate(week_start), _("CW %W"))

        week_day = week_start
        week_end = week_day

        days = []
        log_obj = self.env["farm.chicken.log"]

        sum_loss = 0

        first_weight = 0.0

        valid_count = 0
        fill_count = 0
        day_count = 0

        chicken_count = 0

        avg_data = {}

        def getAvg(name, calc=True):
            data = avg_data.get(name, None)
            if data is None:
                data = {"val": [], "avg": 0.0}
                avg_data[name] = data

            if calc:
                val = data["val"][:7]
                val_len = len(val)
                if val_len:
                    data["avg"] = sum(val) / val_len

            return data

        def addAvg(name, val):
            if val:
                data = getAvg(name, calc=False)
                data["val"].insert(0, val)
            return val

        # get 14 logs for average calc
        logByDay = {}
        logs = log_obj.search([("logbook_id", "=", self.id),
                               ("day", "<", week_next)],
                              limit=14,
                              order="day desc")
        if logs:
            # set new start
            week_day_avg = logs[-1].day
            if week_day_avg < week_day:
                week_day = week_day_avg
            # assign log
            for log in logs:
                logByDay[log.day] = log

        chicken_age_weeks = 0

        while week_day < week_next:
            week_end = week_day

            loss = 0
            loss_fix = False
            loss_fix_amount = 0
            loss_amount = 0
            eggs_performance = 0.0
            weight = 0

            eggs_total = 0
            eggs_broken = 0
            eggs_dirty = 0
            eggs_weight = 0
            eggs_machine = 0
            chicken_age = 0

            feed = 0
            water = 0

            valid = False
            filled = False
            note = ""

            log = logByDay.get(week_day)
            if log:
                loss = log.loss
                loss_amount = log.loss_amount or 0
                loss_fix = log.loss_fix
                loss_fix_amount = log.loss_fix_amount

                eggs_total = addAvg("eggs_total", log.eggs_total)
                eggs_broken = addAvg("eggs_broken", log.eggs_broken)
                eggs_dirty = addAvg("eggs_dirty", log.eggs_dirty)
                eggs_weight = addAvg("eggs_weight", log.eggs_weight)
                eggs_machine = addAvg("eggs_machine", log.eggs_machine)
                eggs_performance = addAvg("eggs_performance",
                                          log.eggs_performance)

                feed = addAvg("feed", log.feed)
                water = addAvg("water", log.water)

                weight = log.weight
                if weight and not first_weight:
                    first_weight = weight

                chicken_count = log.chicken_count

                note = log.note or note
                chicken_age_weeks = log.chicken_age_weeks
                chicken_age = log.chicken_age
                valid = log.state != "draft"
                filled = True

            if filled:
                day_count += 1
                sum_loss += loss_amount

            # add day only if within week
            if week_day >= week_start:
                if filled:
                    fill_count += 1
                if valid:
                    valid_count += 1

                days.append({
                    "name":
                    format_date(util.strToDate(week_day),
                                "E d.M.y",
                                locale=self._context.get("lang")
                                or tools.config.defaultLang),
                    "day":
                    week_day,
                    "loss":
                    loss,
                    "loss_fix":
                    loss_fix,
                    "loss_fix_amount":
                    loss_fix_amount,
                    "eggs_total":
                    eggs_total,
                    "eggs_broken":
                    eggs_broken,
                    "eggs_dirty":
                    eggs_dirty,
                    "eggs_weight":
                    eggs_weight,
                    "eggs_machine":
                    eggs_machine,
                    "weight":
                    weight,
                    "note":
                    note,
                    "valid":
                    valid,
                    "filled":
                    filled,
                    "chicken_age_weeks":
                    chicken_age_weeks,
                    "overview": [{
                        "name": _("Eggs Total"),
                        "value": "%s" % eggs_total
                    }, {
                        "name": _("Eggs Machine"),
                        "value": "%s" % eggs_machine
                    }, {
                        "name": _("Broken Eggs"),
                        "value": "%s" % eggs_broken
                    }, {
                        "name": _("Dirty Eggs"),
                        "value": "%s" % eggs_dirty
                    }, {
                        "name": _("Eggs Weight"),
                        "value": "%s g" % f.formatLang(eggs_weight)
                    }, {
                        "name":
                        _("Egg Performance"),
                        "value":
                        "%s %%" % f.formatLang(eggs_performance)
                    }, {
                        "name": _("Loss"),
                        "value": "%s" % loss_amount
                    }, {
                        "name": _("Chicken Count"),
                        "value": "%s" % chicken_count
                    }, {
                        "name": _("Chicken Weight"),
                        "value": "%s kg" % f.formatLang(weight)
                    }, {
                        "name": _("Day Age"),
                        "value": "%s" % chicken_age
                    }, {
                        "name":
                        _("Feed"),
                        "value":
                        "%s kg" % f.formatLang(feed, digits=0)
                    }, {
                        "name": _("Water"),
                        "value": "%s l" % f.formatLang(water)
                    }]
                })

            week_day = util.getNextDayDate(week_day)

        days_len = len(days)
        return {
            "name":
            "%s %s" % (self.name, week_str),
            "week":
            week_str,
            "date":
            week_start,
            "start":
            f.formatLang(week_start, date=True),
            "end":
            f.formatLang(week_end, date=True),
            "filled":
            days_len == fill_count,
            "validated":
            days_len == valid_count,
            "days":
            days,
            "overview": [{
                "name":
                _("Eggs"),
                "value":
                "%s" % f.formatLang(getAvg("eggs_total")["avg"])
            }, {
                "name":
                _("Eggs Machine"),
                "value":
                "%s" % f.formatLang(getAvg("eggs_machine")["avg"])
            }, {
                "name":
                _("Broken Eggs"),
                "value":
                "%s" % f.formatLang(getAvg("eggs_broken")["avg"])
            }, {
                "name":
                _("Dirty Eggs"),
                "value":
                "%s" % f.formatLang(getAvg("eggs_dirty")["avg"])
            }, {
                "name":
                _("Eggs Weight"),
                "value":
                "%s g" % f.formatLang(getAvg("eggs_weight")["avg"])
            }, {
                "name":
                _("Egg Performance"),
                "value":
                "%s %%" % f.formatLang(getAvg("eggs_performance")["avg"])
            }, {
                "name": _("Loss"),
                "value": "%s" % sum_loss,
            }, {
                "name": _("Chicken Count"),
                "value": "%s" % chicken_count
            }, {
                "name": _("Chicken Weight"),
                "value": "%s kg" % f.formatLang(first_weight)
            }, {
                "name": _("Week Age"),
                "value": "%s" % chicken_age_weeks
            }, {
                "name":
                _("Feed"),
                "value":
                "%s kg" % f.formatLang(getAvg("feed")["avg"], digits=0)
            }, {
                "name": _("Water"),
                "value": "%s l" % f.formatLang(getAvg("water")["avg"])
            }]
        }
예제 #22
0
    def action_invoice(self, cr, uid, ids, context=None):
        invoice_obj = self.pool["account.invoice"]
        invoice_line_obj = self.pool["account.invoice.line"]
        reg_obj = self.pool["academy.registration"]
        reg_inv_obj = self.pool["academy.registration.invoice"]
        fee_obj = self.pool["academy.fee"]

        wizard = self.browse(cr, uid, ids[0], context=context)
        semester = wizard.semester_id

        # registration query filter
        reg_query = []
        sel_reg_ids = util.active_ids(context, "academy.registration")
        if sel_reg_ids:
            reg_query.append(("id", "in", sel_reg_ids))

        # state filter
        reg_query.append("!")
        reg_query.append(("state", "in", ["draft", "cancel", "check"]))

        # search valid registration ids
        reg_ids = reg_obj.search(cr, uid, reg_query)

        # get semester weeks
        sem_weeks = semester.semester_weeks
        sem_start_dt = util.strToDate(semester.date_start)
        sem_end_dt = util.strToDate(semester.date_end)

        # group registrations
        for reg in reg_obj.browse(cr, uid, reg_ids, context=context):
            # check if invoice for registration exist
            reg_inv_id = reg_inv_obj.search_id(
                cr,
                uid, [("registration_id", "=", reg.id),
                      ("semester_id", "=", semester.id),
                      ("invoice_id.state", "!=", "cancel")],
                context=context)
            if reg_inv_id:
                continue

            # get invoice address
            student = reg.student_id
            partner = reg.use_invoice_address_id

            # invoice context
            inv_context = context and dict(context) or {}
            inv_context["type"] = "out_invoice"

            # get invoice or create new
            invoice_id = invoice_obj.search_id(
                cr, uid, [("state", "=", "draft"),
                          ("partner_id", "=", partner.id)])
            if not invoice_id:
                # invoice values
                inv_values = {
                    "partner_id": partner.id,
                    "name": wizard.customer_ref
                }

                inv_values.update(
                    invoice_obj.onchange_partner_id(cr,
                                                    uid, [],
                                                    "out_invoice",
                                                    partner.id,
                                                    context=context)["value"])
                invoice_id = invoice_obj.create(cr,
                                                uid,
                                                inv_values,
                                                context=context)

            # get new invoice
            invoice = invoice_obj.browse(cr, uid, invoice_id, context=context)
            # get fees
            fees = fee_obj.browse(cr,
                                  uid,
                                  fee_obj.search(cr, uid, []),
                                  context=context)

            # create line

            # add product function
            def addProduct(product,
                           uos_id=None,
                           discount=0.0,
                           discount_reason=None):
                line = {
                    "invoice_id": invoice_id,
                    "product_id": product.id,
                    "quantity": 1.0,
                    "uos_id": uos_id or product.uos_id.id
                }

                if discount:
                    line["discount"] = discount

                line.update(
                    invoice_line_obj.product_id_change(
                        cr,
                        uid, [],
                        line["product_id"],
                        line["uos_id"],
                        qty=line["quantity"],
                        type=invoice.type,
                        partner_id=invoice.partner_id.id,
                        fposition_id=invoice.fiscal_position.id,
                        company_id=invoice.company_id.id,
                        currency_id=invoice.currency_id.id,
                        context=inv_context)["value"])

                tax_ids = line.get("invoice_line_tax_id")
                if tax_ids:
                    line["invoice_line_tax_id"] = [(6, 0, tax_ids)]

                # discount reason
                if discount_reason:
                    line["name"] = _("%s - %s\n%s\n%s") % (
                        reg.name, line["name"], reg.student_id.name,
                        discount_reason)
                # or default
                else:
                    line["name"] = _("%s - %s\n%s") % (reg.name, line["name"],
                                                       reg.student_id.name)

                return invoice_line_obj.create(cr, uid, line, context=context)

            # create line

            # calc discount
            discount = 0.0
            discount_reason = None
            if reg.intership_date:
                intership_dt = util.strToDate(reg.intership_date)
                if intership_dt > sem_start_dt and intership_dt < sem_end_dt:
                    missed_duration = intership_dt - sem_start_dt
                    missed_weeks = int(missed_duration.days / 7.0)
                    if missed_weeks:
                        discount = (100.0 / sem_weeks) * missed_weeks
                        #discount_reason = _("Intership discount for %s missed weeks") % missed_weeks

            addProduct(reg.course_prod_id.product_id,
                       reg.uom_id.id,
                       discount=discount,
                       discount_reason=discount_reason)

            # add fees

            category_set = set([c.id for c in reg.location_id.category_id])

            for fee in fees:
                # check if uom is used and match
                if fee.apply_uom_id and fee.uom_id.id != reg.uom_id.id:
                    continue

                # check fee per mail
                if fee.per_mail and not reg.invoice_per_mail:
                    continue

                # check monthly invoice
                if fee.monthly and not reg.invoice_monthly:
                    continue

                # check if categories match
                if fee.location_category_ids:
                    has_category = False
                    for category in fee.location_category_ids:
                        if category.id in category_set:
                            has_category = True
                            break
                    if not has_category:
                        continue

                # check fee already paid this year
                if fee.per_year:
                    cr.execute(
                        " SELECT COUNT(l.id) FROM account_invoice_line l "
                        " INNER JOIN account_invoice inv ON inv.id = l.invoice_id AND inv.state != 'cancel' "
                        " INNER JOIN academy_registration_invoice rinv ON rinv.invoice_id = inv.id "
                        " INNER JOIN academy_semester sem ON sem.id = rinv.semester_id AND sem.year_id = %s "
                        " INNER JOIN academy_registration r ON r.id = rinv.registration_id AND r.student_id = %s "
                        " WHERE l.product_id = %s ",
                        (semester.year_id.id, student.id, fee.product_id.id))

                    rows = cr.fetchone()
                    # check if alfready invoiced this year
                    if rows and rows[0]:
                        continue

                # check for discount
                discount = 0.0
                if fee.sibling_discount:
                    parent = student.partner_id.parent_id

                    fee_query = (
                        " SELECT COUNT(l.id) FROM account_invoice_line l "
                        " INNER JOIN account_invoice inv ON inv.id = l.invoice_id AND inv.state != 'cancel' "
                        " INNER JOIN academy_registration_invoice rinv ON rinv.invoice_id = inv.id AND rinv.semester_id = %s "
                        " INNER JOIN academy_registration r ON r.id = rinv.registration_id "
                        " INNER JOIN academy_student s ON s.id = r.student_id "
                        " INNER JOIN res_partner p ON p.id = s.partner_id "
                        " WHERE l.product_id = %s "
                        "   AND l.quantity > 0 AND l.discount < 100 "
                        "   AND %s " %
                        (semester.id, fee.product_id.id, parent and
                         ("(p.parent_id = %s OR p.id = %s) " %
                          (parent.id, student.partner_id.id)) or
                         ("p.id = %s " % student.partner_id.id)))
                    cr.execute(fee_query)
                    rows = cr.fetchone()
                    # already invoiced ?
                    if rows and rows[0]:
                        discount = fee.sibling_discount

                # add fee
                addProduct(fee.product_id, discount=discount)

            # create invoice link
            reg_inv_obj.create(
                cr, uid, {
                    "registration_id": reg.id,
                    "semester_id": semester.id,
                    "invoice_id": invoice_id
                })

            # write origin
            origin = reg.name
            if invoice.origin and origin:
                origin = "%s:%s" % (invoice.origin, origin)

            # check invoice per mail
            inv_values = {"origin": origin}
            if reg.invoice_per_mail and not invoice.invoice_per_mail:
                inv_values["invoice_per_mail"] = True

            invoice_obj.write(cr, uid, invoice_id, inv_values, context=context)

            # validate invoice
            invoice_obj.button_compute(cr, uid, [invoice_id], context=context)

        return {"type": "ir.actions.act_window_close"}
예제 #23
0
파일: timesheet.py 프로젝트: suningwz/fdoo
    def _build_sheet(self,
                     cr,
                     uid,
                     date_from=None,
                     date_to=None,
                     months=None,
                     employee=None,
                     sheets=None,
                     context=None):
        # check context date
        if not context is None:
            if not date_from:
                date_from = context.get("date_from")
            if not date_to:
                date_to = context.get("date_to")

        # check months
        if date_from and months:
            date_to = util.getNextDayOfMonth(date_from, inMonth=months)

        # if employ was passed
        if employee:
            date_cur = util.currentDate()
            if not date_from:
                date_from = util.getFirstOfMonth(date_cur)
            if not date_to:
                date_to = util.getEndOfMonth(date_cur)

            cr.execute(
                "SELECT s.id FROM hr_timesheet_sheet_sheet s "
                " WHERE (( s.date_from <= %s AND s.date_to >= %s) "
                "  OR  ( s.date_from <= %s AND s.date_to >= %s) "
                "  OR  ( s.date_from >= %s AND s.date_to <= %s)) "
                " AND s.employee_id = %s "
                " ORDER BY s.date_from ",
                (date_from, date_from, date_to, date_to, date_from, date_to,
                 employee.id))

            sheet_ids = [r[0] for r in cr.fetchall()]
            sheets = self.browse(cr, uid, sheet_ids, context=context)

        # if sheets was passed
        elif sheets:
            if not date_from:
                date_from = sheets[0].date_from
            if not date_to:
                date_to = sheets[-1].date_to

        # return if no sheet
        if not sheets or not date_from or not date_to:
            return None

        cr.execute(
            "SELECT s.id FROM hr_timesheet_sheet_sheet s "
            " WHERE s.date_to = ( SELECT MAX(s2.date_to) FROM hr_timesheet_sheet_sheet s2 "
            " WHERE s2.date_to < %s AND s2.employee_id = s.employee_id )"
            " AND s.employee_id = %s "
            " ORDER BY s.date_from ",
            (sheets[0].date_from, sheets[0].employee_id.id))

        query_res = cr.fetchall()
        sheet_before = None
        if query_res:
            sheet_before = self.browse(cr,
                                       uid,
                                       query_res[0][0],
                                       context=context)

        days = []
        res = {
            "date_from": date_from,
            "date_to": date_to,
            "days": days,
            "employee": sheets[0].employee_id
        }

        dt_to = util.strToDate(date_to)
        dt_from = util.strToDate(date_from)

        total_timesheet = 0.0
        total_target = 0.0
        total = 0.0
        total_saldo = 0.0
        current_saldo = 0.0
        leaves_taken = 0.0
        sick_leaves = 0.0
        last_saldo = 0.0

        remaining_leaves = sheets[0].remaining_leaves
        max_leaves = sheets[0].remaining_leaves

        if sheet_before:
            current_saldo = sheet_before.current_saldo
            last_saldo = current_saldo

        leave_obj = self.pool.get("resource.calendar.leaves")
        timesheet_line_obj = self.pool.get("hr.analytic.timesheet")
        for sheet in sheets:
            timesheet_data = self.get_timesheet_data(cr,
                                                     sheet.user_id.id,
                                                     sheet.id,
                                                     context=context)

            sheet_dt_from = util.strToDate(sheet.date_from)
            sheet_dt_cur = sheet_dt_from
            sheet_dt_to = util.strToDate(sheet.date_to)

            delta_day = relativedelta(days=1)

            while sheet_dt_cur <= sheet_dt_to and sheet_dt_cur <= dt_to:
                date_day = util.dateToStr(sheet_dt_cur)
                timesheet_day = timesheet_data.get(date_day)
                if timesheet_day:
                    # vars
                    day_saldo = timesheet_day.get("total_saldo") or 0.0

                    # increment saldo
                    current_saldo += day_saldo

                    # check if date is in date from
                    if sheet_dt_cur >= dt_from:
                        # get vars
                        day_total_timesheet = timesheet_day.get(
                            "total_timesheet_day") or 0.0
                        day_target = timesheet_day.get("total_target") or 0.0
                        day_attendance = timesheet_day.get(
                            "total_attendance_day") or 0.0

                        # get attendance
                        attendance = []
                        attendance_text = []
                        attendance_lines = timesheet_day.get(
                            "attendances", None)
                        if attendance_lines:
                            for attendance_line in attendance_lines:
                                timestamp_to = attendance_line["to"]
                                time_only = timestamp_to and timestamp_to.split(
                                    " ")[1] or None
                                if time_only != "24:00:00":
                                    time_from = util.timeToStrHours(
                                        attendance_line["from"])
                                    time_to = util.timeToStrHours(timestamp_to)
                                    attendance_text.append(
                                        "%s - %s" % (time_from, time_to))
                                    attendance.append({
                                        "time_from": time_from,
                                        "time_to": time_to
                                    })

                        # get work
                        work = timesheet_line_obj.browse(cr,
                                                         uid,
                                                         timesheet_day.get(
                                                             "lines", []),
                                                         context=context)

                        # process leaves
                        leaves = timesheet_day.get("leaves", [])
                        leave_names = []
                        for leave in leave_obj.browse(cr,
                                                      uid,
                                                      [l[0] for l in leaves],
                                                      context=context):
                            leave_names.append(leave.name)
                            if leave.name:
                                attendance_text.append(leave.name)
                            holiday = leave.holiday_id
                            holiday_status = holiday.holiday_status_id
                            if holiday_status:
                                holiday_categ = holiday_status.categ_id
                                if holiday_categ:
                                    if holiday_categ.leave_type == "holiday":
                                        leaves_taken += 1
                                    if holiday_categ.leave_type == "sickness":
                                        sick_leaves += 1
                            # ONLY ONE LEAVE per DAY
                            break

                        # increment counters
                        total_timesheet += day_total_timesheet
                        total_target += day_target
                        total += day_attendance
                        total_saldo += day_saldo
                        day = {
                            "day": date_day,
                            "total_timesheet": day_total_timesheet,
                            "total": day_attendance,
                            "total_saldo": day_saldo,
                            "total_target": day_target,
                            "current_saldo": current_saldo,
                            "attendance": attendance,
                            "attendance_text": "\n".join(attendance_text),
                            "work": work,
                            "leaves": leave_names,
                            "leaves_taken": leaves_taken,
                            "remaining_leaves": remaining_leaves,
                            "sick_leaves": sick_leaves,
                            "sheet": sheet
                        }
                        days.append(day)

                    elif sheet_dt_cur < dt_from:
                        last_saldo = current_saldo

                # next day
                sheet_dt_cur += delta_day

        res["max_leaves"] = max_leaves
        res["last_saldo"] = last_saldo
        res["current_saldo"] = current_saldo
        res["leaves_taken"] = leaves_taken
        res["remaining_leaves"] = remaining_leaves
        res["total_timesheet"] = total_timesheet
        res["total_target"] = total_target
        res["sick_leaves"] = sick_leaves
        res["total"] = total
        res["total_saldo"] = total_saldo
        return res
예제 #24
0
    def create_calendar_entries(self,
                                cr,
                                uid,
                                ids,
                                fiscalyear_id,
                                company_id=None,
                                calendar_id=None,
                                resource_id=None,
                                context=None):
        leave_obj = self.pool.get("resource.calendar.leaves")
        event_obj = self.pool.get("calendar.event")
        account_fiscalyear_obj = self.pool.get("account.fiscalyear")
        fiscal_year_date = util.strToDate(
            account_fiscalyear_obj.browse(cr, uid, fiscalyear_id,
                                          context).date_start)
        easter_sunday_date = util.dateEasterSunday(fiscal_year_date.year)

        for holiday in self.browse(cr, uid, ids, context):
            holiday_date = util.strToDate(holiday.date)
            if holiday.calc_type == "none":
                holiday_date = holiday_date.replace(year=fiscal_year_date.year)
            elif holiday.calc_type == "easter":
                holiday_easter_sunday_date = util.dateEasterSunday(
                    holiday_date.year)
                easter_delta = holiday_easter_sunday_date - easter_sunday_date
                holiday_date = holiday_date + abs(easter_delta)
            leave_ids = leave_obj.search(
                cr, uid, [("official_holiday_id", "=", holiday.id),
                          ("calendar_id", "=", calendar_id),
                          ("date_from", "=", util.timeToStr(holiday_date))])
            if not leave_ids:
                leave_values = {
                    "name": holiday.name,
                    "date_from": util.timeToStr(holiday_date),
                    "date_to":
                    util.timeToStr(util.getLastTimeOfDay(holiday_date)),
                    "resource_id": resource_id,
                    "company_id": company_id,
                    "calendar_id": calendar_id,
                    "official_holiday_id": holiday.id
                }
                leave_obj.create(cr, uid, leave_values, context=context)
            event_ids = event_obj.search(
                cr, uid, [("official_holiday_id", "=", holiday.id)])
            if not event_ids:
                event_values_start = event_obj.onchange_dates(
                    cr,
                    uid, [],
                    fromtype="start",
                    start=util.timeToDateStr(holiday_date),
                    checkallday=True,
                    allday=True,
                    context=context)
                event_values_end = event_obj.onchange_dates(
                    cr,
                    uid, [],
                    fromtype="stop",
                    end=util.timeToDateStr(
                        util.getLastTimeOfDay(holiday_date)),
                    checkallday=True,
                    allday=True,
                    context=context)
                if event_values_start and event_values_end:
                    event_values = event_values_start["value"]
                    event_values.update(event_values_end["value"])
                    event_values["name"] = holiday.name
                    event_values["class"] = "public"
                    event_values["user_id"] = None
                    event_values["show_as"] = "busy"
                    event_values["official_holiday_id"] = holiday.id
                    event_values["partner_ids"] = None
                    event_obj.create(cr, uid, event_values, context=context)
예제 #25
0
파일: analytic.py 프로젝트: suningwz/fdoo
    def _prepare_invoice_data(self, cr, uid, contract, context=None):
        invoice = super(account_analytic_account, self)._prepare_invoice_data(cr, uid, contract, context=context)
        
        # invoice name to contract name
        invoice["name"] = contract.name
        
        # determine user
        user_id = contract.manager_id or contract.user_id
        if user_id:
            invoice["user_id"] = user_id.id
        
        # determine shop
        if contract.shop_id:
            invoice["shop_id"] = contract.shop_id.id
        else:
            # shop from template
            template = contract.template_id
            if template and template.shop_id:
                invoice["shop_id"] = template.shop_id.id
            else:
                parent = contract.parent_id
                if parent:
                    # get shop from parent
                    if parent.shop_id:
                        invoice["shop_id"] = parent.shop_id.id
                    else:
                        # shop from autocreate
                        shop_obj = self.pool["sale.shop"]
                        shop_ids = shop_obj.search(cr, uid, [("autocreate_order_parent_id","=",parent.id)], limit=2)
                        if not shop_ids:
                            shop_ids = shop_obj.search(cr, uid, [("project_id","=",parent.id)], limit=2)
                        # check if only one shop is assinged
                        if len(shop_ids) == 1:
                            invoice["shop_id"] = shop_ids[0]
                        
        # performance period
        if contract.recurring_invoices:
            
            # get next date function            
            def getNextDate(cur_date,sign=1):
                interval = contract.recurring_interval*sign
                if contract.recurring_rule_type == 'daily':
                    return cur_date+relativedelta(days=+interval)
                elif contract.recurring_rule_type == 'weekly':
                    return cur_date+relativedelta(weeks=+interval)
                elif contract.recurring_rule_type == 'monthly':
                    return cur_date+relativedelta(months=+interval)
                else:
                    return cur_date+relativedelta(years=+interval)
            
            
            cur_date = util.strToDate(contract.recurring_next_date or util.currentDate())
            if contract.recurring_prepaid:
                invoice["perf_enabled"] = True
                invoice["perf_start"] = cur_date
                invoice["perf_end"] = getNextDate(cur_date)
            else:
                invoice["perf_enabled"] = True
                invoice["perf_start"] = getNextDate(cur_date,-1)
                invoice["perf_end"] = cur_date
                
            # first of month and last of month
            if contract.recurring_rule_type == 'monthly':
                invoice["perf_end"] = util.strToDate(util.getEndOfMonth(invoice["perf_end"]))
                if contract.recurring_interval > 0:
                    interval = -(contract.recurring_interval-1)
                    invoice["perf_start"] = util.strToDate(util.getFirstOfMonth(invoice["perf_end"]))+relativedelta(months=interval)
                
            # convert dt to str
            invoice["perf_start"] = util.dateToStr(invoice["perf_start"])
            invoice["perf_end"] = util.dateToStr(invoice["perf_end"])

        return invoice
예제 #26
0
    def _students(self, cr, uid, ids, date_from, date_to, context=None):
        res = []
        reg_obj = self.pool["academy.registration"]

        dt_from = util.strToDate(date_from)
        dt_to = util.strToDate(date_to)

        for trainer in self.browse(cr, uid, ids, context=context):
            # get week end
            dt_we = dt_from + relativedelta(days=(6 - dt_from.weekday()))
            # get week start
            dt_ws = dt_from

            # registry per trainer
            regs = {}
            trainer_data = {"trainer": trainer, "regs": regs}
            res.append(trainer_data)

            # start loop
            while dt_ws <= dt_to:  # until to date
                # convert to str
                we = util.dateToStr(dt_we)
                ws = util.dateToStr(dt_ws)

                # query students
                cr.execute(
                    "SELECT ts.reg_id, ts.day FROM academy_trainer_student ts "
                    "INNER JOIN academy_registration r ON r.id = ts.reg_id "
                    "       AND r.state = 'assigned' "
                    "LEFT  JOIN academy_semester sb ON sb.id = r.semester_id "
                    "LEFT  JOIN academy_semester se ON se.id = r.unreg_semester_id "
                    "WHERE  ts.trainer_id = %s "
                    "  AND  sb.date_start <= %s"
                    "  AND  ( se.date_end IS NULL OR se.date_end >= %s )"
                    "  AND  ( r.abort_date IS NULL OR r.abort_date > %s )"
                    "  AND  ts.day = ( SELECT MAX(ts2.day) FROM academy_trainer_student ts2 "
                    " WHERE ts2.reg_id = ts.reg_id "
                    "   AND ts2.day < %s "
                    ") "
                    " GROUP BY 1,2 ",
                    (
                        trainer.id,  # trainer
                        ws,  # check semester start
                        ws,  # check semester end
                        we,  # check abort
                        we  # check trainer assignment
                    ))

                # process registers
                rows = cr.fetchall()
                if rows:
                    for reg_id, start_date in rows:
                        reg_data = regs.get(reg_id, None)
                        if reg_data is None:
                            reg_data = {
                                "reg":
                                reg_obj.browse(cr,
                                               uid,
                                               reg_id,
                                               context=context),
                                "start_date":
                                start_date,
                                "hours":
                                0.0
                            }

                        reg = reg_data["reg"]

                        # check if day is in the other month
                        dt_reg_start = util.strToDate(start_date)
                        dt_course_date = dt_ws - relativedelta(
                            days=dt_ws.weekday()) + relativedelta(
                                days=dt_reg_start.weekday())
                        if dt_to < dt_course_date or dt_from > dt_course_date:
                            continue

                        # increment hours
                        reg_data["hours"] = reg_data["hours"] + (
                            int(round(reg.hours * 60.0)) / 60.0)
                        regs[reg_id] = reg_data

                # increment
                # .. next week start
                dt_ws = dt_we + relativedelta(days=1)
                # .. next week end
                dt_we += relativedelta(weeks=1)

        return res
예제 #27
0
    def default_get(self, cr, uid, fields_list, context=None):
        res = super(invoice_merge_wizard,
                    self).default_get(cr, uid, fields_list, context)
        if not context or context.get("active_model") != "account.invoice":
            return res

        invoice_ids = context.get("active_ids") or []
        invoice_obj = self.pool.get("account.invoice")
        invoice_merge = {}

        for invoice in invoice_obj.browse(cr, uid, invoice_ids, context):
            invoice_key = (invoice.partner_id, invoice.type)
            data = invoice_merge.get(invoice_key)
            if not data:
                data = {
                    "name":
                    _("Collective Invoice"),
                    "partner_id":
                    invoice.partner_id.id,
                    "type":
                    invoice.type,
                    "info": [],
                    "invoice_ids": [],
                    "comment": [],
                    "payment_term":
                    invoice.payment_term and invoice.payment_term.id or None,
                    "fiscal_position":
                    invoice.fiscal_position and invoice.fiscal_position.id
                    or None,
                    "company_id":
                    invoice.company_id.id,
                    "account_id":
                    invoice.account_id.id,
                    "journal_id":
                    invoice.journal_id.id,
                    "currency_id":
                    invoice.currency_id.id,
                    "user_id":
                    uid,
                }
                invoice_merge[invoice_key] = data

            data_state = data.get("state") or 0
            data_num = data.get("num_of_invoices") or 0
            data_amount = data.get("amount") or 0.0
            data_info = data["info"]
            data_invoice_ids = data["invoice_ids"]
            data_comment = data["comment"]
            dt_invoice = invoice.date_invoice and util.strToDate(
                invoice.date_invoice) or None
            dt_from_date = data.get("from_date") or None
            dt_to_date = data.get("to_date") or None

            def addInfo(infoState, infoText):
                data_info.append(infoText)
                return max(data_state, infoState)

            if invoice.state == "draft":
                data_invoice_ids.append(invoice.id)
                data_amount += invoice.amount_total

                if invoice.comment:
                    data_comment.append(invoice.comment)

                if dt_invoice:
                    dt_from_date = (dt_from_date and min(
                        dt_from_date, dt_invoice)) or dt_invoice
                    dt_to_date = (dt_to_date and max(dt_to_date,
                                                     dt_invoice)) or dt_invoice

                data_num += 1
            else:
                data_state = addInfo(
                    1,
                    _("%s is no draft Invoice, Ignored!") % (invoice.name, ))

            data["amount"] = data_amount
            data["state"] = data_state
            data["num_of_invoices"] = data_num
            data["from_date"] = dt_from_date
            data["to_date"] = dt_to_date

        def mergeLines(key):
            textLines = data[key]
            if not textLines:
                del data[key]
            else:
                data[key] = "\n".join(textLines)

        def toStrDate(key):
            dtValue = data[key]
            if dtValue:
                dtValue = util.dateToStr(dtValue)
                data[key] = dtValue
            return dtValue

        res_merge_ids = []
        for data in invoice_merge.values():
            mergeLines("info")
            mergeLines("comment")
            str_range = helper.getMonthYearRange(cr, uid,
                                                 toStrDate("from_date"),
                                                 toStrDate("to_date"), context)
            if str_range:
                data["name"] = _("Collective Invoice %s") % (str_range, )
            data["invoice_ids"] = [(6, 0, data["invoice_ids"])]
            res_merge_ids.append(data)

        res["merge_ids"] = res_merge_ids
        return res
예제 #28
0
파일: analytic.py 프로젝트: suningwz/fdoo
    def _recurring_task_create(self, cr, uid, ids, automatic=False, context=None):
        if context is None:
          context = {}
          
        task_ids = []
        
        current_date =  util.currentDate()
        if ids:
            contract_ids = ids
        else:
            contract_ids = self.search(cr, uid, [("use_tasks","=",True), ("recurring_task_next","<=", current_date), ("state","=", "open"), ("recurring_task","=", True), ("type", "=", "contract")])
        if contract_ids:
            
            task_obj = self.pool["project.task"]
            recurring_task_obj = self.pool["account.analytic.recurring.task"]
            project_obj = self.pool["project.project"]
            f = format.LangFormat(cr, uid, context)
            
            cr.execute("SELECT company_id, array_agg(id) as ids FROM account_analytic_account WHERE id IN %s GROUP BY company_id", (tuple(contract_ids),))
            for company_id, ids in cr.fetchall():
                context_contract = dict(context, company_id=company_id, force_company=company_id)
                for contract in self.browse(cr, uid, ids, context=context_contract):
                    
                    project_ids = project_obj.search(cr, uid, [("analytic_account_id","=",contract.id)], context=context_contract)
                    if not project_ids:
                      raise Warning(_("No Project for generating tasks of contract %s found") % contract.name)
                    
                    project = project_obj.browse(cr, uid, project_ids[0], context=context_contract)
                    
                    try:
                      
                        # get interval
                        interval = contract.recurring_task_interval
                        rule = contract.recurring_rule_type      
                        next_date = contract.recurring_task_next or current_date                
                        if contract.recurring_task_rule == "daily":
                          # daily
                          dt_interval = relativedelta(days=interval)
                          interval_name = f.formatLang(next_date, date=True)
                        elif contract.recurring_task_rule == "weekly":
                          # weekly
                          dt_interval = relativedelta(weeks=interval)
                          interval_name = _("%s WE%s") % (util.getYearStr(next_date), util.getWeek(next_date))
                        elif contract.recurring_task_rule == "monthly":
                          # monthly
                          dt_interval = relativedelta(months=interval)
                          interval_name = helper.getMonthYear(cr, uid, next_date, context=context)
                        else:
                          # yearly
                          interval_name = util.getYearStr(next_date)
                          dt_interval = relativedelta(years=interval)
                        
                        # next date
                        next_date = util.dateToStr(util.strToDate(next_date) + dt_interval)
                        
                        # execute task
                        processed_tasks = 0
                        finished_tasks = 0
                        for recurring_task in contract.recurring_task_ids:
                          
                          task_values = self._recurring_task_prepare(cr, uid, project, recurring_task, interval_name, next_date, context=context_contract)
                          if task_values:
                            
                            processed_tasks += 1
                            
                            # execute task if it is not finished
                            task_count = recurring_task.count
                            if not recurring_task.repeat or task_count < recurring_task.repeat:
                              task_count = recurring_task.count + 1                          
                              task_ids.append(task_obj.create(cr, uid, task_values, context=context_contract))
                              recurring_task_obj.write(cr, uid, [recurring_task.id], {"count": task_count}, context=context_contract)
                              
                            # check if task is finished
                            if recurring_task.repeat and task_count >= recurring_task.repeat:
                              finished_tasks += 1                      
                          
                        # check if all tasks are finished  
                        if finished_tasks and finished_tasks == processed_tasks:
                          values["recurring_task"] = False

                        # update contract
                        values = {"recurring_task_next": next_date}
                        self.write(cr, uid, [contract.id], values, context=context)
                        
                        # commit if automatic 
                        if automatic:
                            cr.commit()
                            
                    except Exception:
                        # log error if automatic
                        if automatic:
                            cr.rollback()
                            _logger.exception("Fail to create recurring task for contract %s [%s]", (contract.name, contract.code))
                        else:
                            raise
                          
        return task_ids
예제 #29
0
    def action_report(self):
        session_obj = self.pool["pos.session"]
        for wizard in self:
            # get ids
            config_ids = [p.id for p in wizard.pos_ids]            
            session_ids = session_obj.search(self._cr, self._uid, [("start_at",">=",wizard.date_from),("start_at","<=",wizard.date_till),("config_id","in",config_ids),("state","=","closed")], context=self._context)
            if not session_ids:
                return True
            
            datas = {
                 "ids": session_ids,
                 "model": "pos.session"
            }        
           
            # get context
            report_ctx = self._context and dict(self._context) or {}
            
            # format
            f = format.LangFormat(self._cr, self._uid, self._context)
            if wizard.range == "month":
                dt = util.strToDate(wizard.date_from)
                dt_till = util.strToDate(wizard.date_till)
                report_name = _("%s - %s / %s %s") % (f.formatLang(wizard.date_from, date=True), 
                                                                        f.formatLang(wizard.date_till, date=True),
                                                                        helper.getMonthName(self._cr, self._uid, dt.month, context=self._context),
                                                                        dt.year)
                
                if dt_till.year != dt.year or dt_till.month != dt.month:
                    report_name = _("%s - %s %s") % (report_name, 
                                                     helper.getMonthName(self._cr, self._uid, dt_till.month, context=self._context),
                                                     dt_till.year)
                
            elif wizard.range == "week":
                dt = util.strToDate(wizard.date_from)
                dt_till = util.strToDate(wizard.date_till)
                kw = dt.isocalendar()[1]
                kw_till = dt_till.isocalendar()[1]
                
                report_name = _("%s - %s / CW %s %s") % (f.formatLang(wizard.date_from, date=True), 
                                                                        f.formatLang(wizard.date_till, date=True),
                                                                        kw, 
                                                                        dt.year)
                 
                if dt_till.year != dt.year or kw != kw_till:
                    report_name = _("%s - CW %s %s") % (report_name, kw_till, dt_till.year)
                    
            else:
                if wizard.date_from == wizard.date_till:
                    report_name = f.formatLang(wizard.date_from, date=True)
                else:
                    report_name = "%s - %s" %  (f.formatLang(wizard.date_from, date=True), 
                                                f.formatLang(wizard.date_till, date=True))
                
                
            # report name
            report_ctx["cashreport_name"] = report_name  
          
            # check options
            if wizard.detail:
                report_ctx["print_detail"] = True            
            if wizard.separate:
                report_ctx["no_group"] = True
            if wizard.product:
                report_ctx["print_product"] = True

            # add report info                
            report_ctx["pos_report_info"] = {
                "name" : report_name,
                "from" : wizard.date_from,
                "till" : wizard.date_till,
                "config_ids" : config_ids
            }
                
            # return
            return  {
                "type": "ir.actions.report.xml",
                "report_name": "point_of_sale.report_sessionsummary",
                "datas": datas,
                "context" : report_ctx
            }