Ejemplo n.º 1
0
    def _dailyEnd(self, session):
        if not session.stop_at:
            return _("Open")

        startDate = util.timeToDateStr(session.start_at)
        stopDate = util.timeToDateStr(session.stop_at)
        stopTime = util.timeToStrHours(session.stop_at)

        if startDate != stopDate:
            return "%s %s" % (self.formatLang(stopDate, date=True), stopTime)

        return stopTime
Ejemplo n.º 2
0
    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
Ejemplo n.º 3
0
     def add_task(task):
         # check if task already processed
         if task.id in task_set:
             return 0.0
         
         hours = 0.0
         
         # check work 
         for work in task.work_ids:
             if work.hours:
                 # round to quarter and add
                 work_minutes = round(work.hours * 60)
                 work_minutes_rest = work_minutes % 15
                 if work_minutes_rest:
                     work_minutes = work_minutes + (15 - work_minutes_rest)
                 
                 task_hours = float(work_minutes) / 60.0                
                 hours+=task_hours
                                         
                 work_line = []
                 
                 # append date
                 if work.date:
                     work_line.append(f.formatLang(util.timeToDateStr(work.date), date=True))
                
                 # append time
                 work_line.append(_("%s Hour(s)") % f.formatLang(task_hours, float_time=True))
                      
                 # append name
                 if work.name:
                     work_line.append(work.name)
                     
                 work_info.append(" - ".join(work_line))
 
         # add childs
         task_set.add(task.id)
         for child_task in task.child_ids:
             hours += add_task(child_task)
         
         return hours
Ejemplo n.º 4
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
Ejemplo n.º 5
0
    def barkeeper_status(self, cr, uid, options, context=None):
        order_obj = self.pool["pos.order"]
        session_obj = self.pool["pos.session"]
        config_obj = self.pool["pos.config"]
        company_obj = self.pool["res.company"]

        company_id = company_obj._company_default_get(cr, uid, context=context)
        company = company_obj.browse(cr, uid, company_id, context=context)
        currency = company.currency_id.symbol

        # result
        stat = {
            "title": _("No Data"),
            "currency": currency,
            "name": "",
            "group": "",
            "range": ""
        }

        # search first order if
        # and build default options
        # if no options are passed
        config_id = None
        config = None
        date = None
        mode = "today"
        if options:
            config_id = options.get("config_id")
            # if mode is today
            # date is none
            mode = options.get("mode")
            if not mode or mode == "today":
                date = None
                options["mode"] = "today"
            else:
                date = options.get("date")

        nodata = False
        if not config_id or not date:
            # get latest order
            order_id = None
            if config_id:
                config = config_obj.browse(cr, uid, config_id, context=context)
                order_id = order_obj.search_id(
                    cr,
                    uid, [
                        '|', ("session_id.config_id", "=", config_id),
                        ('session_id.config_id.parent_user_id', '=',
                         config.user_id.id)
                    ],
                    order="date_order desc",
                    context=None)
            else:
                order_id = order_obj.search_id(cr,
                                               uid,
                                               [("session_id", "!=", False)],
                                               order="date_order desc",
                                               context=None)

            # check if order exist
            if order_id:
                order = order_obj.browse(cr, uid, order_id, context=context)

                # get parent
                config = order.session_id.config_id
                while config.parent_user_id:
                    parent_config_id = config_obj.search_id(
                        cr,
                        uid, [("user_id", "=", config.parent_user_id.id)],
                        context=context)
                    if not parent_config_id or parent_config_id == config.id:
                        break
                    config = config_obj.browse(cr,
                                               uid,
                                               parent_config_id,
                                               context=context)

                config_id = config.id
                options = {
                    "mode": "today",
                    "date": util.timeToDateStr(order.date_order),
                    "config_id": config_id
                }
            else:
                nodata = True

        # set options
        stat["options"] = options

        # if not data return
        if not config_id:
            return stat

        # get current mode
        if not config or config.id != config_id:
            config = config_obj.browse(cr, uid, config_id, context=context)
        config_ids = [config_id]

        # build title and group description
        stat["name"] = config.name
        if config.user_id:
            group = []
            childEntries = config_obj.search_read(
                cr,
                uid, [("parent_user_id", "=", config.user_id.id)],
                ["name", "sign_pid"],
                context=context)
            for childEntry in childEntries:
                group.append(childEntry["sign_pid"] or childEntry["name"])
                config_ids.append(childEntry["id"])
            if group:
                group.insert(0, config.sign_pid or config.name)
            stat["group"] = ", ".join(group)

        # return if no default data
        if nodata:
            return stat

        # find start
        statDate = options.get("date")
        if not statDate:
            options["date"] = statDate = util.currentDate()

        # add amount
        orderDicts = []

        def addAmount(amount, amountStat, sections, count=False):
            for section in sections:

                subsections = None
                sectionStat = None

                if len(section) == 1:
                    key = section[0]
                    sectionStat = amountStat.get(key)
                    if sectionStat is None:
                        sectionStat = {
                            "amount": 0.0,
                            "count": 0,
                            "currency": currency
                        }
                        amountStat[key] = sectionStat

                elif len(section) >= 2:
                    field = section[0]
                    key = section[1]

                    if len(section) >= 3:
                        subsections = section[2]

                    keyStat = amountStat.get(field)
                    if keyStat is None:
                        keyStat = {}
                        amountStat[field] = keyStat
                        orderDicts.append((amountStat, field, keyStat))

                    sectionStat = keyStat.get(key)
                    if sectionStat is None:
                        sectionStat = {
                            "key": key,
                            "amount": 0.0,
                            "count": 0,
                            "currency": currency
                        }
                        keyStat[key] = sectionStat

                sectionStat["amount"] = sectionStat["amount"] + amount
                if count:
                    sectionStat["count"] = sectionStat["count"] + 1

                if subsections:
                    addAmount(amount, sectionStat, subsections, count=count)

        # setup range
        time_keyfunc = lambda date_order: helper.strToLocalDateStr(
            cr, uid, date_order, context=context)
        if mode == "year":
            stat["title"] = _("Year")
            startDate = util.getFirstOfYear(statDate)
            endDate = util.getFirstOfNextYear(statDate)
            dt_delta = relativedelta(years=1)
            time_keyfunc = lambda date_order: helper.strToLocalDateStr(
                cr, uid, date_order, context=context)[:7]
        elif mode == "month":
            stat["title"] = _("Month")
            startDate = util.getFirstOfMonth(statDate)
            endDate = util.getFirstOfNextMonth(statDate)
            dt_delta = relativedelta(months=1)
        elif mode == "week":
            stat["title"] = _("Week")
            startDate = util.getFirstOfWeek(statDate)
            endDate = util.getFirstOfNextWeek(statDate)
            dt_delta = relativedelta(weeks=1)
        else:
            time_keyfunc = lambda date_order: "%s:00" % helper.strToLocalTimeStr(
                cr, uid, date_order, context=context).split(" ")[1][:2]
            stat["title"] = _("Day")
            startDate = statDate
            endDate = util.getNextDayDate(statDate)
            dt_delta = relativedelta(hours=1)

        # query session build range
        session_ids = session_obj.search(cr,
                                         uid,
                                         [("start_at", ">=", startDate),
                                          ("start_at", "<", endDate),
                                          ("config_id", "in", config_ids)],
                                         order="start_at asc",
                                         context=context)
        stat["range"] = helper.getRangeName(cr,
                                            uid,
                                            startDate,
                                            util.getPrevDayDate(endDate),
                                            context=context)

        # query orders
        order_ids = order_obj.search(cr,
                                     uid, [("session_id", "in", session_ids)],
                                     order="date_order asc",
                                     context=context)
        orders = order_obj.browse(cr, uid, order_ids, context=context)

        # build base
        addAmount(0, stat, [("total", )])
        if orders:
            firstOrder = orders[0]
            lastOrder = orders[-1]

            curTime = util.strToTime(firstOrder.date_order)
            timeEnd = util.strToTime(lastOrder.date_order)
            while curTime <= timeEnd:
                time_key = time_keyfunc(util.timeToStr(curTime))
                addAmount(0, stat, [("byTime", time_key)])
                curTime += dt_delta

        # iterate orders
        for order in orders:
            # check if it is relevant
            fpos_order = order.fpos_order_id
            notbalance = fpos_order.tag != "s"
            user = order.user_id

            # add turnover for journal
            for st in order.statement_ids:
                journal = st.journal_id
                amount = notbalance and st.amount or 0.0
                addAmount(
                    amount, stat,
                    [("byJournal", journal.name),
                     ("byUser", user.name, [("byJournal", journal.name)])],
                    True)

            # add to order
            time_key = time_keyfunc(order.date_order)
            amount = notbalance and order.amount_total or 0.0
            addAmount(amount, stat,
                      [("total", ),
                       ("byTime", time_key, [("byUser", user.name)])], True)

        # sort dicts
        for (parent, key, value) in orderDicts:
            parent[key] = value and sorted(value.values(),
                                           key=lambda en: en["key"]) or []

        return stat
Ejemplo n.º 6
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)
Ejemplo n.º 7
0
    def _statistic(self, sessions, daily=False, no_group=False):
        sessions = sorted(sessions,
                          key=lambda session:
                          (session.start_at or "", session.stop_at or ""))

        # check no group
        if no_group:
            res = []
            for session in sessions:
                stat = self._buildStatistic([session])
                if stat:
                    res.append(stat)
            return res

        stat = self._buildStatistic(sessions)
        if not stat:
            return []

        if not daily and self.localcontext.get("daily_overview"):
            sessionsPerDay = stat["days"]
            report_info = self.localcontext.get("pos_report_info")
            report_info["from"], report_info["till"]

            def selectDay(day):
                if not day:
                    return None

                selDay = None

                # get sel day
                if sessionsPerDay:
                    dayEntry = sessionsPerDay[-1]
                    selDay = dayEntry["day"]
                else:
                    selDay = day
                    dayEntry = {"day": selDay, "sessions": []}
                    sessionsPerDay.append(dayEntry)

                # fill gap
                while selDay < day:
                    selDay = util.getNextDayDate(selDay)
                    dayEntry = {"day": selDay, "sessions": []}
                    sessionsPerDay.append(dayEntry)

                # check result
                if selDay == day:
                    return dayEntry

                return None

            selectDay(report_info.get("from"))
            for session in sessions:
                if not session.start_at:
                    continue
                dayEntry = selectDay(util.timeToDateStr(session.start_at))
                if dayEntry:
                    dayEntry["sessions"].append(session)

            selectDay(report_info.get("till"))

        return [stat]