Exemplo n.º 1
0
    def prepare_account_move(self, analytic_lines_ids,notupdatestate):
        """ Creates analytics related financial move lines """
        acc_analytic_line = self.env['account.analytic.line']
        done_analytic_line = self.env['account.analytic.line']
        account_move = self.env['account.move']
        fields_grouped = [
            'id',
            'partner_id',
            'operating_unit_id',
            'wip_month_id',
            'company_id',
        ]
        grouped_by = [
            'partner_id',
            'operating_unit_id',
            'wip_month_id',
            'company_id',
        ]
        result = acc_analytic_line.read_group(
            [('id','in', analytic_lines_ids)],
            fields_grouped,
            grouped_by,
            offset=0,
            limit=None,
            orderby=False,
            lazy=False
        )
        narration = self.description if self.wip else ''
        try:
            if len(result) > 0:
                wip_journal = self.env.ref('magnus_timesheet.wip_journal')
                if not wip_journal.sequence_id:
                    raise UserError(_('Please define sequence on the type WIP journal.'))
                for item in result:
                    if item['partner_id'] == False:
                        raise UserError(_('Please define partner.'))
                    partner_id = item['partner_id'][0]
                    if item['operating_unit_id'] == False:
                        raise UserError(_('Please define operating_unit_id.'))
                    operating_unit_id = item['operating_unit_id'][0]
                    if item['wip_month_id'] == False:
                        raise UserError(_('Please define WIP Month.'))
                    month_id = item['wip_month_id'][0]
                    if item['company_id'] == False:
                        raise UserError(_('Please define Company.'))
                    company_id = item['company_id'][0]

                    date_end = self.env['date.range'].browse(month_id).date_end

                    partner = self.env['res.partner'].browse(partner_id)
                    if not partner.property_account_receivable_id:
                        raise UserError(_('Please define receivable account for partner %s.') % (partner.name))

                    aml = []
                    analytic_line_obj = acc_analytic_line.search([('id', 'in', analytic_lines_ids),('partner_id', '=', partner_id),('operating_unit_id', '=', operating_unit_id), ('wip_month_id', '=', month_id)])
                    analytic_line_obj -= done_analytic_line
                    # if self.wip_percentage > 0.0:
                        #Skip wip move creation when percantage is 0
                    #creates wip moves for all percentages
                    for aal in analytic_line_obj:
                        if not aal.product_id.property_account_wip_id:
                            raise UserError(_('Please define WIP account for product %s.') % (aal.product_id.name))
                        for ml in self._prepare_move_line(aal):
                            aml.append(ml)

                    line = [(0, 0, l) for l in aml]

                    move_vals = {
                        'type':'receivable',
                        'ref': narration,
                        'line_ids': line,
                        'journal_id': wip_journal.id,
                        'date': date_end,
                        'narration': 'WIP move',
                        'to_be_reversed': True,
                    }

                    ctx = dict(self._context, lang=partner.lang)
                    ctx['company_id'] = company_id
                    ctx_nolang = ctx.copy()
                    ctx_nolang.pop('lang', None)
                    move = account_move.with_context(ctx_nolang).create(move_vals)
                    move.is_wip_move=True
                    move.wip_percentage=self.wip_percentage
                    for line in move.line_ids:
                        line.wip_percentage=self.wip_percentage
                    if move:
                        move._post_validate()
                        move.post()

                    account_move |= move
                    cond = '='
                    rec = analytic_line_obj.ids[0]
                    if len(analytic_line_obj) > 1:
                        cond = 'IN'
                        rec = tuple(analytic_line_obj.ids)

                    first_of_next_month_date = (datetime.strptime(date_end, "%Y-%m-%d") + timedelta(days=1)).strftime("%Y-%m-%d")
                    wip_month_id = analytic_line_obj[0].find_daterange_month(first_of_next_month_date)

                    line_query = ("""
                                    UPDATE
                                       account_analytic_line
                                    SET date_of_last_wip = {0}, date_of_next_reconfirmation = {1}, month_of_last_wip = {2}, wip_month_id = {2}
                                    WHERE id {3} {4}
                                    """.format(
                                    "'%s'" % date_end,
                                    "'%s'" % first_of_next_month_date,
                                    wip_month_id.id or False,
                                    cond,
                                    rec))
                    self.env.cr.execute(line_query)
                    done_analytic_line |= analytic_line_obj

        except Exception (e):
            # update the analytic line record into there previous state when job get failed in delay
            for id, state in notupdatestate.iteritems():
                self.env.cr.execute("""
                                UPDATE account_analytic_line SET state = '%s' WHERE id=%s
                                """ % (state,id))
                self.env.cr.commit()
                self.env.cache.invalidate()
            raise FailedJobError(
                _("The details of the error:'%s'") % (unicode(e)))
        vals = [account_move.id]
        # if self.wip_percentage > 0.0 or True:
            # Skip wip reversal creation when percantage is 0
        # creates wip reversal moves for all percentages
        reverse_move=self.wip_reversal(account_move)
        if reverse_move:
            vals.append(reverse_move.id)
        # Adding moves to each record
        self.env['account.analytic.line'].add_move_line(analytic_lines_ids, vals)

        return "WIP moves and Reversals successfully created. \n "
Exemplo n.º 2
0
    def use_quota_if_avaiable(self, request_name, backend_id):
        # TODO: finish the method to control the quota of the methods
        assert request_name
        control = self.search([('request_name', '=', request_name)])
        try:
            assert control
        except AssertionError:
            raise FailedJobError(
                "The action %s doesn't exist on the quota control module (MWS)"
                % request_name)

        last_requests = self.env['amazon.control.date.request'].search(
            [('backend_id', '=', backend_id), ('request_id', '=', control.id)],
            order='request_date desc',
            limit=control.max_quota - ceil(control.max_quota / 3))
        time_now = datetime.now()
        if last_requests and len(last_requests) >= control.max_quota - ceil(
                control.max_quota / 3):
            first_date_request = datetime.strptime(
                last_requests[len(last_requests) - 1].request_date,
                '%Y-%m-%d %H:%M:%S')
            if (time_now - first_date_request).seconds < control.restore_rate:
                raise RetryableJobError(
                    "The quota of %s is empty (MWS)" % request_name,
                    seconds=ceil(control.restore_rate * 1.2),
                    ignore_retry=True)

        if control.max_request_quota_time > 0:
            last_requests = self.env['amazon.control.date.request'].search(
                [('backend_id', '=', backend_id),
                 ('request_id', '=', control.id)],
                order='request_date desc',
                limit=control.max_request_quota_time)

            max_request_factor = 1
            if control.units_of_mesaure_quota == 'min':
                max_request_factor = 60
            if control.units_of_mesaure_quota == 'hor':
                max_request_factor = 60 * 60
            if control.units_of_mesaure_quota == 'day':
                max_request_factor = 60 * 60 * 24

            if last_requests and len(
                    last_requests) >= control.max_request_quota_time:
                first_date_request = datetime.strptime(
                    last_requests[len(last_requests) - 1].request_date,
                    '%Y-%m-%d %H:%M:%S')
                if (time_now - first_date_request).seconds < (
                        control.max_request_quota_units * max_request_factor):
                    raise RetryableJobError(
                        "The quota of %s is empty (MWS)" % request_name,
                        seconds=ceil(control.restore_rate * 1.2),
                        ignore_retry=True)

        self.env['amazon.control.date.request'].create({
            'backend_id':
            backend_id,
            'request_id':
            control.id,
            'request_date':
            time_now.isoformat()
        })