Ejemplo n.º 1
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
Ejemplo n.º 2
0
    def barkeeper_days(self, cr, uid, dt, context=None):
        range_start = util.getFirstOfMonth(dt)
        range_end = util.getFirstOfNextMonth(dt)
        cr.execute(
            "SELECT to_char(start_at, 'YYYY-MM-DD') FROM pos_session WHERE start_at >= %s AND start_at < %s GROUP BY 1 ORDER BY 1 DESC",
            (range_start, range_end))
        data = []
        f = format.LangFormat(cr, uid, context=context)
        for str_date, in cr.fetchall():
            week = util.getWeek(str_date)
            data.append({
                "name":
                "%s, %s" % (f.formatLang(str_date, date=True),
                            f.getDayShortName(str_date, context=context)),
                "date":
                str_date,
                "group":
                _("Week %s") % week,
                "mode":
                "day"
            })

        return {
            "title": "%s %s" % (helper.getMonth(cr, uid, dt, context), dt[:4]),
            "data": data,
            "group": True
        }
Ejemplo n.º 3
0
 def _discount_calc_get(self, cr, uid, ids, field_name, arg, context=None):
   res = dict.fromkeys(ids)
   
   f_price = format.LangFormat(cr, uid, context=context, obj=self, f="discount_price")
   f_discount = format.LangFormat(cr, uid, context=context, obj=self, f="discount")
   
   for obj in self.browse(cr, uid, ids, context):
     val = []
     if obj.discount_action:
       val.append("!")
     if obj.discount_price:
       if obj.discount_unit:
         val.append("*%s" % f_price.formatLang(obj.discount_price))
       else:
         val.append("=%s" % f_price.formatLang(obj.discount_price))
     elif obj.discount:
       val.append("%s%%" % f_discount.formatLang(obj.discount))
     res[obj.id] = "".join(val) or None
     
   return res
Ejemplo n.º 4
0
    def _prepare_order_line_procurement(self,
                                        cr,
                                        uid,
                                        order,
                                        line,
                                        group_id=False,
                                        context=None):
        vals = super(sale_order,
                     self)._prepare_order_line_procurement(cr,
                                                           uid,
                                                           order,
                                                           line,
                                                           group_id=group_id,
                                                           context=context)
        if order.dynbom_location_id:
            product = line.product_id
            if product:
                if product.dynbom:
                    f = format.LangFormat(cr,
                                          uid,
                                          context=context,
                                          dp="Product UoS")
                    name = vals.get("name") or ""
                    line_names = []
                    for mat_line in order.order_line:
                        if mat_line.id != line.id:
                            uom = mat_line.product_uos or mat_line.product_uom
                            line_names.append(
                                "%s x %s %s" %
                                (f.formatLang(mat_line.product_uos_qty),
                                 uom.name, mat_line.name))

                    if line_names:
                        name = "%s\n\n%s\n\n" % (name, "\n\n".join(line_names))
                        vals["name"] = name

                else:
                    vals["location_id"] = order.dynbom_location_id.id
                    parent_loc = order.dynbom_location_id.location_id
                    partner = parent_loc.partner_id
                    if not partner:
                        partner = parent_loc.company_id.partner_id
                    vals["partner_dest_id"] = partner.id

        return vals
Ejemplo n.º 5
0
    def barkeeper_months(self, cr, uid, dt, context=None):
        range_start = util.getFirstOfYear(dt)
        range_end = util.getFirstOfNextYear(dt)
        cr.execute(
            "SELECT to_char(start_at, 'YYYY-MM') FROM pos_session WHERE start_at >= %s AND start_at < %s GROUP BY 1 ORDER BY 1 DESC",
            (range_start, range_end))
        data = []
        f = format.LangFormat(cr, uid, context=context)
        for m, in cr.fetchall():
            str_date = "%s-01" % m
            data.append({
                "name": f.getMonthName(str_date, context),
                "date": str_date,
                "mode": "month",
                "next": "barkeeper_days",
                "nextTitle": _("Day")
            })

        return {"title": dt[:4], "data": data}
Ejemplo n.º 6
0
    def _prepare_cost_invoice(self, cr, uid, partner, company_id, currency_id, analytic_lines, context=None):
        res = super(account_analytic_line, self)._prepare_cost_invoice(cr, uid, partner, company_id, currency_id, analytic_lines, context=context)
        
        line_ids = [l.id for l in analytic_lines]
        account = analytic_lines[0].account_id
        f = format.LangFormat(cr, uid, context)
         
        cr.execute("SELECT MIN(line.date), MAX(line.date) " \
                    "FROM account_analytic_line as line " \
                    "WHERE account_id = %s " \
                        "AND id IN %s AND to_invoice IS NOT NULL", (account.id, tuple(line_ids)))

        invoice_name = None
        for date_from, date_to in cr.fetchall():
            if date_from and date_to:
                invoice_name = "%s %s - %s" % ( account.name or "",f.formatLang(date_from,date=True), f.formatLang(date_to,date=True))

        if not invoice_name:
            invoice_name = "%s %s" % (account.name or "",f.formatLang(util.currentDate(),date=True))

        res["name"] = invoice_name
        return res
    def action_create(self, cr, uid, ids, context=None):
        wizard = self.browse(cr, uid, ids[0], context)

        report_ctx = context and dict(context) or {}
        report_ctx["date_start"] = wizard.date_start
        report_ctx["date_end"] = wizard.date_end

        if wizard.unit == "semester":
            if wizard.sem_start_id.id == wizard.sem_end_id.id:
                report_ctx["duration_title"] = wizard.sem_start_id.name_get(
                )[0][1]
            else:
                report_ctx["duration_title"] = "%s - %s" % (
                    wizard.sem_start_id.name_get()[0][1],
                    wizard.sem_end_id.name_get()[0][1])
        elif wizard.unit == "period":
            if wizard.period_start_id.id == wizard.period_end_id.id:
                report_ctx["duration_title"] = wizard.period_start_id.name_get(
                )[0][1]
            else:
                report_ctx["duration_title"] = "%s - %s" % (
                    wizard.period_start_id.name_get()[0][1],
                    wizard.period_end_id.name_get()[0][1])
        else:
            f = format.LangFormat(cr, uid, context)
            report_ctx["duration_title"] = "%s - %s" % (f.formatLang(
                wizard.date_start,
                date=True), f.formatLang(wizard.date_end, date=True))

        datas = {
            "ids": util.active_ids(context, "academy.trainer"),
            "model": "academy.trainer"
        }
        return {
            "type": "ir.actions.report.xml",
            "report_name": "trainer.reg",
            "datas": datas,
            "context": report_ctx
        }
Ejemplo n.º 8
0
    def registration_post(self, stage=1, **kwargs):
        cr, uid, context = request.cr, request.uid, request.context

        public_user = request.registry["res.users"].browse(
            request.cr, request.uid, request.uid, context=request.context)
        company = public_user.company_id
        hidden_user = company.academy_webuser_id or public_user
        hidden_uid = hidden_user.id

        courses = []

        # used obj
        academy_product_obj = request.registry["academy.course.product"]
        uom_obj = request.registry["product.uom"]
        location_obj = request.registry["academy.location"]
        student_obj = request.registry["academy.student"]
        partner_obj = request.registry["res.partner"]
        city_obj = request.registry["res.city"]
        reg_obj = request.registry["academy.registration"]

        # build selection
        is_student_of_loc = False
        parent_address = True
        invoice_address = False
        extra_info = None
        read_school_rules = None
        invoice_monthly = False
        invoice_per_mail = False

        for key, value in kwargs.items():
            if key == "is_student_of_loc":
                is_student_of_loc = True
            elif key == "has_legal_age":
                parent_address = False
            elif key == "has_invoice_address":
                invoice_address = True
            elif key == "textinput_extra_info":
                extra_info = value
            elif key == "read_school_rules":
                read_school_rules = True
            elif key == "invoice_monthly":
                invoice_monthly = True
            elif key == "invoice_mail":
                invoice_per_mail = value == "mail"
            else:
                m = PATTERN_PRODUCT.match(key)
                if m:
                    uom_id = util.getId(value)
                    if uom_id:
                        course_prod = academy_product_obj.browse(
                            cr,
                            hidden_uid,
                            util.getId(m.group(1)),
                            context=context)
                        uom = uom_obj.browse(cr,
                                             hidden_uid,
                                             uom_id,
                                             context=context)
                        courses.append((course_prod, uom))

        # location
        location_id = util.getId(kwargs.get("location_id"))
        location = location_id and location_obj.browse(
            cr, hidden_uid, location_id, context=context) or None
        address = location and location.address_id
        location_lines = []
        if address:
            location_lines.append(address.name)
            if address.street:
                location_lines.append(address.street)
            if address.street2:
                location_lines.append(address.street2)
            if address.zip:
                if address.city:
                    location_lines.append("%s %s" %
                                          (address.zip, address.city))
                else:
                    location_lines.append(address.zip)

        # registration
        registration = kwargs.get("registration")
        lock_hash = None
        try:
            if registration:
                # lock
                lock_hash = hash("academy_registration_%s" % registration)
                cr.execute("SELECT pg_advisory_lock(%s)" % lock_hash)
                cr.commit()
                # search registration
                reg_id = reg_obj.search_id(cr,
                                           hidden_uid,
                                           [("name", "=", registration)],
                                           context=context)
                if reg_id:
                    values = {
                        "message_title":
                        _("Registration already finished!"),
                        "message_text":
                        _("<p>Registration %s was done</p>") % registration
                    }
                    return request.website.render("website_academy.message",
                                                  values,
                                                  context=context)

            # handle stage
            if stage == 2:
                # finish registration
                warnings = []
                messages = []

                #
                def create_address(obj, fields, data, name):
                    """ get address or create new
                        :return (id,Name)
                    """
                    # search address
                    address_id = obj.search_id(
                        cr, hidden_uid, [("name", "=", data.get("name")),
                                         ("email", "=", data.get("email"))])
                    if address_id:
                        cur_data = obj.read(cr,
                                            hidden_uid,
                                            address_id,
                                            fields,
                                            context=context)
                        changes = []
                        fields = obj.fields_get(cr,
                                                hidden_uid,
                                                allfields=fields,
                                                context=context)
                        for key, value in cur_data.items():
                            if key == "id":
                                continue
                            value1 = value or ""
                            value2 = data.get(key) or ""

                            # get name if it is a many2one field
                            if isinstance(value1, tuple):
                                value1 = value1[1]
                            if isinstance(value2, tuple):
                                value2 = value2[1]
                            if value1 != value2:
                                changes.append(
                                    _("Value of field '%s' is '%s' but customer typed '%s'"
                                      ) %
                                    (fields[key]["string"], value1, value2))
                        if changes:
                            warnings.append("<p><b>%s</b></p>" % name)
                            for change in changes:
                                warnings.append("<p>%s</p>" % change)
                            warnings.append("<p></p>")
                    else:
                        # convert tuple to id
                        for key, value in data.items():
                            if isinstance(value, tuple):
                                data[key] = value[0]

                        # create new address
                        address_id = obj.create(cr,
                                                hidden_uid,
                                                data,
                                                context=context)

                    if address_id:
                        return obj.name_get(cr,
                                            hidden_uid, [address_id],
                                            context=context)[0]
                    return None

                def get_address(prefix):
                    """ parse address data """

                    # simple get
                    def get(name):
                        arg = kwargs.get("%s_%s" % (prefix, name))
                        return arg and arg.strip() or ""

                    firstname = get("firstname")
                    lastname = get("lastname")
                    email = get("email")

                    if not firstname or not lastname or not email:
                        return None

                    name = "%s %s" % (lastname, firstname)
                    city = get("city")
                    zip_code = get("zip")
                    res = {
                        "name": name,
                        "email": email,
                        "street": get("street"),
                        "zip": zip_code,
                        "city": city
                    }

                    nationality = get("nationality")
                    if nationality:
                        res["nationality"] = nationality

                    birthday_dt, birthday = util.tryParseDate(get("birthday"))
                    if birthday_dt:
                        res["birthday"] = util.dateToStr(birthday_dt)

                    phone = get("phone")
                    if phone:
                        res["phone"] = phone

                    city_values = city_obj.search_read(cr,
                                                       hidden_uid,
                                                       [("code", "=", zip)],
                                                       ["name", "state_id"],
                                                       context=context)
                    for city_val in city_values:
                        if re.sub("[^A-Za-z]", "",
                                  city) == re.sub("[^A-Za-z]", "",
                                                  city_val["name"]):
                            res["state_id"] = city_val["state_id"]
                            res["city"] = city_val["name"]
                            break

                    return res

                if not courses:
                    raise osv.except_osv(_("Error"), _("No courses selected"))

                student_values = get_address("form_student")
                if not student_values:
                    raise osv.except_osv(_("Error"),
                                         _("No student address passed"))

                if parent_address:
                    parent_values = get_address("form_parent")
                    if not parent_values:
                        raise osv.except_osv(_("Error"),
                                             _("No parent address passed"))
                    student_values["parent_id"] = create_address(
                        partner_obj, [
                            "name", "email", "street", "zip", "city", "phone",
                            "birthday"
                        ], parent_values, _("Parent"))
                invoice_address_id = None
                if invoice_address:
                    invoice_values = get_address("form_invoice")
                    if not invoice_values:
                        raise osv.except_osv(_("Error"),
                                             _("No invoice address passed"))
                    invoice_address_id = create_address(
                        partner_obj,
                        ["name", "email", "street", "zip", "city", "phone"],
                        invoice_values, _("Invoice Address"))[0]

                # create student address
                student = create_address(student_obj, [
                    "name", "email", "street", "zip", "city", "phone",
                    "nationality", "birthday", "parent_id"
                ], student_values, _("Student"))

                # create courses
                for course in courses:

                    values = {
                        "course_prod_id": course[0].id,
                        "uom_id": course[1].id,
                        "student_id": student[0],
                        "location_id": location_id,
                        "student_of_loc": is_student_of_loc,
                        "note": extra_info,
                        "read_school_rules": read_school_rules,
                        "invoice_monthly": invoice_monthly,
                        "invoice_per_mail": invoice_per_mail
                    }

                    # set invoice address id
                    if invoice_address_id:
                        values["invoice_address_id"] = invoice_address_id

                    # set registration number
                    if registration:
                        values["name"] = registration
                        registration = None

                    # create, register and commit
                    reg_id = reg_obj.create(cr,
                                            hidden_uid,
                                            values,
                                            context=context)
                    reg_name = reg_obj.read(cr,
                                            hidden_uid,
                                            reg_id, ["name"],
                                            context=context)["name"]
                    reg_obj.do_register(cr,
                                        hidden_uid, [reg_id],
                                        context=context,
                                        check=True)
                    cr.commit()

                    # create status message
                    messages.append(
                        _("<p>Registration %s was created.</p>") % reg_name)

                    # add info if something is to add
                    if warnings:
                        warnings = "\n".join(warnings)
                        reg_obj.message_post(cr,
                                             hidden_uid,
                                             reg_id,
                                             body=warnings,
                                             context=context)

                values = {
                    "message_title": _("Registration finished!"),
                    "message_text": "\n".join(messages)
                }
                return request.website.render("website_academy.message",
                                              values,
                                              context=context)
            else:
                # check for fee
                f = format.LangFormat(cr, uid, context=context)
                mail_fee_option = ""
                fee_obj = request.registry["academy.fee"]
                fee_values = fee_obj.search_read(cr,
                                                 SUPERUSER_ID,
                                                 [("per_mail", "=", True)],
                                                 ["list_price"],
                                                 context=context)
                if fee_values:
                    price = fee_values[0]["list_price"]
                    mail_fee_option = _(
                        "Invoice per mail with additional fee of %s %s") % (
                            f.formatLang(price), company.currency_id.symbol)

                # begin registration
                values = {
                    "courses": courses,
                    "location": location,
                    "location_lines": location_lines,
                    "is_student_of_loc": is_student_of_loc,
                    "invoice_per_mail": invoice_per_mail,
                    "location_id": location_id,
                    "mail_fee_option": mail_fee_option,
                    "registration":
                    reg_obj._next_sequence(cr, hidden_uid, context)
                }
                return request.website.render("website_academy.registration",
                                              values)
        finally:
            # unlock
            if lock_hash:
                cr.execute("SELECT pg_advisory_unlock(%s)" % lock_hash)
Ejemplo n.º 9
0
    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
Ejemplo n.º 10
0
    def _prepare_cost_invoice_line(self, cr, uid, invoice_id, product_id, uom, user_id,
                factor_id, account, analytic_lines, journal_type, data, context=None):
        product_obj = self.pool['product.product']
        
        f = format.LangFormat(cr, uid, context)
        uom_context = dict(context or {}, uom=uom)
         
        total_price = sum(l.amount for l in analytic_lines)
        total_qty = sum(l.unit_amount for l in analytic_lines)

        if data.get('product'):
            # force product, use its public price
            if isinstance(data['product'], (tuple, list)):
                product_id = data['product'][0]
            else:
                product_id = data['product']
            unit_price = self._get_invoice_price(cr, uid, account, product_id, user_id, total_qty, uom_context)
        elif journal_type == 'general' and product_id:
            # timesheets, use sale price
            unit_price = self._get_invoice_price(cr, uid, account, product_id, user_id, total_qty, uom_context)
        else:
            # expenses, using price from amount field
            unit_price = total_price*-1.0 / total_qty

        factor = self.pool['hr_timesheet_invoice.factor'].browse(cr, uid, factor_id, context=uom_context)
        factor_name = factor.customer_name or ''
        curr_invoice_line = {
            'price_unit': unit_price,
            'quantity': total_qty,
            'product_id': product_id,
            'discount': factor.factor,
            'invoice_id': invoice_id,
            'name': factor_name,
            'uos_id': uom,
            'account_analytic_id': account.id,
        }

        if product_id:
            product = product_obj.browse(cr, uid, product_id, context=uom_context)
            factor_name = product_obj.name_get(cr, uid, [product_id], context=uom_context)[0][1]
            if factor.customer_name:
                factor_name += ' - ' + factor.customer_name

                general_account = product.property_account_income or product.categ_id.property_account_income_categ
                if not general_account:
                    raise osv.except_osv(_('Error!'), _("Configuration Error!") + '\n' + _("Please define income account for product '%s'.") % product.name)
                taxes = product.taxes_id or general_account.tax_ids
                tax = self.pool['account.fiscal.position'].map_tax(cr, uid, account.partner_id.property_account_position, taxes)
                curr_invoice_line.update({
                    'invoice_line_tax_id': [(6, 0, tax)],
                    'name': factor_name,
                    'invoice_line_tax_id': [(6, 0, tax)],
                    'account_id': general_account.id,
                })

            note = []
            for line in analytic_lines:
                # set invoice_line_note
                details = []
                if data.get('date', False):
                    details.append(f.formatLang(line['date'],date=True))
                if data.get('time', False):
                    line_time = f.formatLang(line.unit_amount,float_time=True)
                    if line['product_uom_id']:
                        details.append("%s %s" % (line_time, line.product_uom_id.name))
                    else:
                        details.append("%s" % (line_time, ))
                if data.get('name', False):
                    details.append(line['name'])
                if details:
                    note.append(u' - '.join(map(lambda x: unicode(x) or '', details)))
            if note:
                curr_invoice_line['name'] += "\n" + ("\n".join(map(lambda x: unicode(x) or '', note)))
        return curr_invoice_line
Ejemplo n.º 11
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"])
            }]
        }
Ejemplo n.º 12
0
    def fpos_ga_order_create(self,
                             cr,
                             uid,
                             partner_id,
                             order_ids,
                             defaults=None,
                             context=None):
        jdoc_obj = self.pool["jdoc.jdoc"]
        order_obj = self.pool["pos.order"]
        fpos_line_obj = self.pool["fpos.order.line"]
        fpos_order_obj = self.pool["fpos.order"]

        data_obj = self.pool["ir.model.data"]
        product_balance_id = data_obj.xmlid_to_res_id(
            cr, uid, "fpos.product_fpos_balance", raise_if_not_found=True)

        f = format.LangFormat(cr, uid, context=context)

        lines = []
        filtered_order_ids = []
        partner_id = None
        first = True

        order_ids = order_obj.search(cr,
                                     uid, [("id", "in", order_ids)],
                                     context=context)
        for order in order_obj.browse(cr,
                                      SUPERUSER_ID,
                                      order_ids,
                                      context=context):
            fpos_order = order.fpos_order_id
            if not fpos_order:
                continue

            if fpos_order.partner_id:
                partner_id = fpos_order.partner_id.id

            if partner_id != partner_id:
                continue

            filtered_order_ids.append(order.id)
            lines.append({
                "name":
                " ".join([
                    f.formatLang(fpos_order.date, date_time=True), order.name
                ]),
                "notice":
                order.pos_reference,
                "qty":
                1,
                "price":
                fpos_order.amount_total,
                "subtotal_incl":
                fpos_order.amount_total,
                "subtotal":
                fpos_order.amount_total,
                "tag":
                "s",
                "flags":
                first and "1b" or "1bl"  # main section
            })

            first = False

            line_values = None
            for fpos_line in fpos_order.line_ids:
                if fpos_line.tag and not fpos_line.tag in ("i", "o"):
                    continue
                line_values = fpos_line_obj.copy_data(cr,
                                                      uid,
                                                      fpos_line.id,
                                                      context=context)

                # replace product with none
                line_values["product_id"] = product_balance_id

                # sub section and payment
                flags = line_values.get("flags") or ""
                if flags.find("2") < 0:
                    flags += "2"
                if flags.find("x") < 0:
                    flags += "x"

                # correct negative
                idx_minus = flags.find("-")
                if idx_minus < 0 and fpos_line.subtotal_incl < 0:
                    flags += "-"
                elif idx_minus >= 0 and fpos_line.subtotal_incl > 0:
                    flags = flags.replace("-", "")

                # set flags
                line_values["flags"] = flags

                # add
                lines.append(line_values)

        # set values for order
        order_values = defaults and dict(defaults) or {}
        order_values["line_ids"] = [(0, 0, l) for l in lines]
        order_values["fpos_user_id"] = uid
        if not "user_id" in order_values:
            order_values["user_id"] = uid
        if not "date" in order_values:
            order_values["date"] = util.currentDateTime()
        if not "ref" in order_values:
            order_values["ref"] = _("Group Invoice")
        if partner_id and not "partner_id" in order_values:
            order_values["partner_id"] = partner_id

        # create order
        fpos_ga_order_id = fpos_order_obj.create(cr,
                                                 uid,
                                                 order_values,
                                                 context=context)
        # update order group
        order_obj.write(cr,
                        uid,
                        filtered_order_ids,
                        {"fpos_group_id": fpos_ga_order_id},
                        context=context)

        res = jdoc_obj.jdoc_by_id(cr,
                                  uid,
                                  "fpos.order",
                                  fpos_ga_order_id,
                                  options={"empty_values": False},
                                  context=context)
        return res
Ejemplo n.º 13
0
 def _prepare_order_line_invoice_line(self, cr, uid, line, account_id=False, context=None):
     # if contract, no invoice
     if line.is_contract:
       return False
   
     res = super(sale_order_line, self)._prepare_order_line_invoice_line(cr, uid, line, account_id, context)
             
     product = line.product_id
     if product and product.type == "service" and product.billed_at_cost:
         task_obj = self.pool["project.task"]
         task_ids = task_obj.search(cr, SUPERUSER_ID, [("sale_line_id","=",line.id)])
         f = format.LangFormat(cr, uid, context=context)
         
         task_set = set()  
         work_info = []        
         effective_hours = 0.0
         
         # add task and childs
         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
                 
         
         # build task set
         for task in task_obj.browse(cr, SUPERUSER_ID, task_ids, context=context):
             effective_hours += add_task(task)
             
         # get quantity
         res["quantity"] = effective_hours
         # set new work info
         if work_info:
             res["name"] = "%s\n%s" % (res["name"], "\n".join(work_info))
         
     return res