Exemple #1
0
 def action_create_normalBom(self, cr, uid, ids, context=None):
     """
         Create a new Normal Bom if doesn't exist (action callable from views)
     """
     selectdIds = context.get('active_ids', [])
     objType = context.get('active_model', '')
     if objType != 'product.product':
         raise UserError(_("The creation of the normalBom works only on product_product object"))
     if not selectdIds:
         raise UserError(_("Select a product before to continue"))
     objType = context.get('active_model', False)
     product_product_type_object = self.pool.get(objType)
     collectableProduct = []
     for productBrowse in product_product_type_object.browse(cr, uid, selectdIds, context):
         idTemplate = productBrowse.product_tmpl_id.id
         objBoms = self.pool.get('mrp.bom').search(cr, uid, [('product_tmpl_id', '=', idTemplate),
                                                             ('type', '=', 'normal')])
         if objBoms:
             raise UserError(_("Normal BoM for Part %r already exists." % (objBoms)))
         product_product_type_object.create_bom_from_ebom(cr, uid, productBrowse, 'normal', context)
         collectableProduct.append(productBrowse.id)
     if collectableProduct:
         return {'name': _('Bill of Materials'),
                 'view_type': 'form',
                 "view_mode": 'tree,form',
                 'res_model': 'mrp.bom',
                 'type': 'ir.actions.act_window',
                 'domain': "[('product_id','in', [" + ','.join(map(str, collectableProduct)) + "])]",
                 }
     else:
         raise UserError(_("Unable to create the normall Bom"))
Exemple #2
0
    def create_membership_invoice(self,
                                  cr,
                                  uid,
                                  ids,
                                  product_id=None,
                                  datas=None,
                                  context=None):
        """ Create Customer Invoice of Membership for partners.
        @param datas: datas has dictionary value which consist Id of Membership product and Cost Amount of Membership.
                      datas = {'membership_product_id': None, 'amount': None}
        """
        invoice_obj = self.pool.get('account.invoice')
        invoice_line_obj = self.pool.get('account.invoice.line')
        product_id = product_id or datas.get('membership_product_id', False)
        amount = datas.get('amount', 0.0)
        invoice_list = []
        if type(ids) in (
                int,
                long,
        ):
            ids = [ids]
        for partner in self.browse(cr, uid, ids, context=context):
            account_id = partner.property_account_receivable_id and partner.property_account_receivable_id.id or False
            fpos_id = partner.property_account_position_id and partner.property_account_position_id.id or False
            addr = self.address_get(cr, uid, [partner.id], ['invoice'])
            if partner.free_member:
                raise UserError(_("Partner is a free Member."))
            if not addr.get('invoice', False):
                raise UserError(
                    _("Partner doesn't have an address to make the invoice."))
            invoice_values = {
                'partner_id': partner.id,
                'account_id': account_id,
                'fiscal_position_id': fpos_id or False
            }
            invoice_id = invoice_obj.create(cr,
                                            uid,
                                            invoice_values,
                                            context=context)
            line_values = {
                'product_id': product_id,
                'price_unit': amount,
                'invoice_id': invoice_id,
            }
            # create a record in cache, apply onchange then revert back to a dictionnary
            invoice_line = invoice_line_obj.new(cr,
                                                uid,
                                                line_values,
                                                context=context)
            invoice_line._onchange_product_id()
            line_values = invoice_line._convert_to_write(invoice_line._cache)
            line_values['price_unit'] = amount
            invoice_obj.write(cr,
                              uid, [invoice_id],
                              {'invoice_line_ids': [(0, 0, line_values)]},
                              context=context)
            invoice_list.append(invoice_id)
            invoice_obj.compute_taxes(cr, uid, [invoice_id])

        return invoice_list
Exemple #3
0
    def create(self, cr, uid, vals, context=None):
        if context is None:
            context = {}

        sheet_id = context.get('sheet_id') or self._get_current_sheet(
            cr,
            uid,
            vals.get('employee_id'),
            vals.get('name'),
            context=context)
        if sheet_id:
            att_tz_date_str = self._get_attendance_employee_tz(
                cr,
                uid,
                vals.get('employee_id'),
                date=vals.get('name'),
                context=context)
            ts = self.pool.get('hr_timesheet_sheet.sheet').browse(
                cr, uid, sheet_id, context=context)
            if ts.state not in ('draft', 'new'):
                raise UserError(
                    _('You can not enter an attendance in a submitted timesheet. Ask your manager to reset it before adding attendance.'
                      ))
            elif ts.date_from > att_tz_date_str or ts.date_to < att_tz_date_str:
                raise UserError(
                    _('You can not enter an attendance date outside the current timesheet dates.'
                      ))
        return super(hr_attendance, self).create(cr,
                                                 uid,
                                                 vals,
                                                 context=context)
Exemple #4
0
    def action_grant_badge(self, cr, uid, ids, context=None):
        """Wizard action for sending a badge to a chosen employee"""
        if context is None:
            context = {}

        badge_user_obj = self.pool.get('gamification.badge.user')

        for wiz in self.browse(cr, uid, ids, context=context):
            if not wiz.user_id:
                raise UserError(
                    _('You can send badges only to employees linked to a user.'
                      ))

            if uid == wiz.user_id.id:
                raise UserError(_('You can not send a badge to yourself'))

            values = {
                'user_id': wiz.user_id.id,
                'sender_id': uid,
                'badge_id': wiz.badge_id.id,
                'employee_id': wiz.employee_id.id,
                'comment': wiz.comment,
            }

            badge_user = badge_user_obj.create(cr,
                                               uid,
                                               values,
                                               context=context)
            result = badge_user_obj._send_badge(cr,
                                                uid, [badge_user],
                                                context=context)
        return result
Exemple #5
0
    def unlink(self, cr, uid, ids, context=None):
        sheets = self.read(cr,
                           uid,
                           ids, ['state', 'total_attendance'],
                           context=context)
        for sheet in sheets:
            if sheet['state'] in ('confirm', 'done'):
                raise UserError(
                    _('You cannot delete a timesheet which is already confirmed.'
                      ))
            elif sheet['total_attendance'] <> 0.00:
                raise UserError(
                    _('You cannot delete a timesheet which have attendance entries.'
                      ))

        toremove = []
        analytic_timesheet = self.pool.get('account.analytic.line')
        for sheet in self.browse(cr, uid, ids, context=context):
            for timesheet in sheet.timesheet_ids:
                toremove.append(timesheet.id)
        analytic_timesheet.unlink(cr, uid, toremove, context=context)

        return super(hr_timesheet_sheet, self).unlink(cr,
                                                      uid,
                                                      ids,
                                                      context=context)
Exemple #6
0
 def do_issue(self):
     value = {}
     if self.check_max_issue(self.student_id.id, self.library_card_id.id):
         if self.book_unit_id.state and \
                 self.book_unit_id.state == 'available':
             book_movement_create = {
                 'book_id': self.book_id.id,
                 'book_unit_id': self.book_unit_id.id,
                 'type': self.type,
                 'student_id': self.student_id.id or False,
                 'faculty_id': self.faculty_id.id or False,
                 'library_card_id': self.library_card_id.id,
                 'issued_date': self.issued_date,
                 'return_date': self.return_date,
                 'state': 'issue',
             }
             self.env['op.book.movement'].create(book_movement_create)
             self.book_unit_id.state = 'issue'
             value = {'type': 'ir.actions.act_window_close'}
         else:
             raise UserError(
                 _("Book Unit can not be issued because it's state is : %s")
                 %
                 (dict(book_unit.unit_states).get(self.book_unit_id.state)))
     else:
         raise UserError(
             _('Maximum Number of book allowed for %s is : %s') %
             (self.student_id.name,
              self.library_card_id.library_card_type_id.allow_book))
     return value
Exemple #7
0
 def create_bom_from_ebom(self,
                          cr,
                          uid,
                          objProductProductBrw,
                          newBomType,
                          context={}):
     """
         create a new bom starting from ebom
     """
     if newBomType not in ['normal', 'spbom']:
         raise UserError(
             _("Could not convert source bom to %r" % newBomType))
     product_template_id = objProductProductBrw.product_tmpl_id.id
     bomType = self.pool.get('mrp.bom')
     bomLType = self.pool.get('mrp.bom.line')
     bomIds = bomType.search(cr, uid,
                             [('product_tmpl_id', '=', product_template_id),
                              ('type', '=', newBomType)])
     if bomIds:
         for bom_line in bomType.browse(cr, uid, bomIds[0],
                                        context=context).bom_line_ids:
             self.create_bom_from_ebom(cr, uid, bom_line.product_id,
                                       newBomType, context)
     else:
         idNewTypeBoms = bomType.search(
             cr, uid, [('product_tmpl_id', '=', product_template_id),
                       ('type', '=', 'ebom')])
         if not idNewTypeBoms:
             UserError(_("No Enginnering bom provided"))
         for newBomId in idNewTypeBoms:
             newidBom = bomType.copy(cr, uid, newBomId, {}, context)
             bomType.write(cr,
                           uid, [newidBom], {
                               'name': objProductProductBrw.name,
                               'product_tmpl_id': product_template_id,
                               'type': newBomType
                           },
                           check=False,
                           context=None)
             oidBom = bomType.browse(cr, uid, newidBom, context=context)
             ok_rows = self._summarizeBom(cr, uid, oidBom.bom_line_ids)
             # remove not summarised lines
             for bom_line in list(set(oidBom.bom_line_ids) ^ set(ok_rows)):
                 bomLType.unlink(cr, uid, [bom_line.id], context=None)
             # update the quantity with the summarised values
             for bom_line in ok_rows:
                 bomLType.write(cr,
                                uid, [bom_line.id], {
                                    'type': newBomType,
                                    'source_id': False,
                                    'product_qty': bom_line.product_qty,
                                },
                                context=None)
                 self.create_bom_from_ebom(cr, uid, bom_line.product_id,
                                           newBomType, context)
             self.wf_message_post(cr,
                                  uid, [objProductProductBrw.id],
                                  body=_('Created %r' % newBomType))
             break
Exemple #8
0
    def action_create_new_revision_by_server(self):
        def stateAllows(brwsObj, objType):
            if brwsObj.state != 'released':
                logging.error(
                    '[action_create_new_revision_by_server:stateAllows] Cannot revise obj %s, Id: %r because state is %r'
                    % (objType, brwsObj.id, brwsObj.state))
                raise UserError(
                    _("%s cannot be revised because the state isn't released!"
                      % (objType)))
            return True

        product_id = self.env.context.get('default_product_id', False)
        if not product_id:
            logging.error(
                '[action_create_new_revision_by_server] Cannot revise because product_id is %r'
                % (product_id))
            raise UserError(_('Current component cannot be revised!'))
        prodProdEnv = self.env['product.product']
        prodBrws = prodProdEnv.browse(product_id)
        if stateAllows(prodBrws, 'Component'):
            revRes = prodBrws.NewRevision()
            newID, newIndex = revRes
            newIndex
            if not newID:
                logging.error(
                    '[action_create_new_revision_by_server] newID: %r' %
                    (newID))
                raise UserError(
                    _('Something wrong happens during new component revision process.'
                      ))
            createdDocIds = []
            for docBrws in prodBrws.linkeddocuments:
                if stateAllows(docBrws, 'Document'):
                    resDoc = docBrws.NewRevision()
                    newDocID, newDocIndex = resDoc
                    newDocIndex
                    if not newDocID:
                        logging.error(
                            '[action_create_new_revision_by_server] newDocID: %r'
                            % (newDocID))
                        raise UserError(
                            _('Something wrong happens during new document revision process.'
                              ))
                    createdDocIds.append(newDocID)
            prodProdEnv.browse(newID).linkeddocuments = createdDocIds
            return {
                'name': _('Revised Product'),
                'view_type': 'tree,form',
                "view_mode": 'form',
                'res_model': 'product.product',
                'res_id': newID,
                'type': 'ir.actions.act_window'
            }
    def create_invoices(self):
        sale_orders = self.env['sale.order'].browse(
            self._context.get('active_ids', []))

        if self.advance_payment_method == 'delivered':
            sale_orders.action_invoice_create()
        elif self.advance_payment_method == 'all':
            sale_orders.action_invoice_create(final=True)
        else:
            # Create deposit product if necessary
            if not self.product_id:
                vals = self._prepare_deposit_product()
                self.product_id = self.env['product.product'].create(vals)
                self.env['ir.values'].set_default(
                    'sale.config.settings', 'deposit_product_id_setting',
                    self.product_id.id)

            sale_line_obj = self.env['sale.order.line']
            for order in sale_orders:
                if self.advance_payment_method == 'percentage':
                    amount = order.amount_untaxed * self.amount / 100
                else:
                    amount = self.amount
                if self.product_id.invoice_policy != 'order':
                    raise UserError(
                        _('The product used to invoice a down payment should have an invoice policy set to "Ordered quantities". Please update your deposit product to be able to create a deposit invoice.'
                          ))
                if self.product_id.type != 'service':
                    raise UserError(
                        _("The product used to invoice a down payment should be of type 'Service'. Please use another product or update this product."
                          ))
                so_line = sale_line_obj.create({
                    'name':
                    _('Advance: %s') % (time.strftime('%m %Y'), ),
                    'price_unit':
                    amount,
                    'product_uom_qty':
                    0.0,
                    'order_id':
                    order.id,
                    'discount':
                    0.0,
                    'product_uom':
                    self.product_id.uom_id.id,
                    'product_id':
                    self.product_id.id,
                    'tax_id': [(6, 0, self.product_id.taxes_id.ids)],
                })
                self._create_invoice(order, so_line, amount)
        if self._context.get('open_invoices', False):
            return sale_orders.action_view_invoice()
        return {'type': 'ir.actions.act_window_close'}
Exemple #10
0
    def get_access_token(self, cr, uid, scope=None, context=None):
        ir_config = self.pool['ir.config_parameter']
        google_drive_refresh_token = ir_config.get_param(
            cr, SUPERUSER_ID, 'google_drive_refresh_token')
        if not google_drive_refresh_token:
            if self.pool['res.users']._is_admin(cr, uid, [uid]):
                model, action_id = self.pool[
                    'ir.model.data'].get_object_reference(
                        cr, uid, 'base_setup', 'action_general_configuration')
                msg = _(
                    "You haven't configured 'Authorization Code' generated from google, Please generate and configure it ."
                )
                raise yuancloud.exceptions.RedirectWarning(
                    msg, action_id, _('Go to the configuration panel'))
            else:
                raise UserError(
                    _("Google Drive is not yet configured. Please contact your administrator."
                      ))
        google_drive_client_id = ir_config.get_param(cr, SUPERUSER_ID,
                                                     'google_drive_client_id')
        google_drive_client_secret = ir_config.get_param(
            cr, SUPERUSER_ID, 'google_drive_client_secret')
        #For Getting New Access Token With help of old Refresh Token

        data = werkzeug.url_encode(
            dict(client_id=google_drive_client_id,
                 refresh_token=google_drive_refresh_token,
                 client_secret=google_drive_client_secret,
                 grant_type="refresh_token",
                 scope=scope or 'https://www.googleapis.com/auth/drive'))
        headers = {"Content-type": "application/x-www-form-urlencoded"}
        try:
            req = urllib2.Request('https://accounts.google.com/o/oauth2/token',
                                  data, headers)
            content = urllib2.urlopen(req, timeout=TIMEOUT).read()
        except urllib2.HTTPError:
            if user_is_admin:
                model, action_id = self.pool[
                    'ir.model.data'].get_object_reference(
                        cr, uid, 'base_setup', 'action_general_configuration')
                msg = _(
                    "Something went wrong during the token generation. Please request again an authorization code ."
                )
                raise yuancloud.exceptions.RedirectWarning(
                    msg, action_id, _('Go to the configuration panel'))
            else:
                raise UserError(
                    _("Google Drive is not yet configured. Please contact your administrator."
                      ))
        content = json.loads(content)
        return content.get('access_token')
Exemple #11
0
    def button_validate(self, cr, uid, ids, context=None):
        quant_obj = self.pool.get('stock.quant')

        for cost in self.browse(cr, uid, ids, context=context):
            if cost.state != 'draft':
                raise UserError(_('Only draft landed costs can be validated'))
            if not cost.valuation_adjustment_lines or not self._check_sum(
                    cr, uid, cost, context=context):
                raise UserError(
                    _('You cannot validate a landed cost which has no valid valuation adjustments lines. Did you click on Compute?'
                      ))
            move_id = self._create_account_move(cr, uid, cost, context=context)
            for line in cost.valuation_adjustment_lines:
                if not line.move_id:
                    continue
                per_unit = line.final_cost / line.quantity
                diff = per_unit - line.former_cost_per_unit
                quants = [quant for quant in line.move_id.quant_ids]
                quant_dict = {}
                for quant in quants:
                    if quant.id not in quant_dict:
                        quant_dict[quant.id] = quant.cost + diff
                    else:
                        quant_dict[quant.id] += diff
                for key, value in quant_dict.items():
                    quant_obj.write(cr,
                                    SUPERUSER_ID,
                                    key, {'cost': value},
                                    context=context)
                qty_out = 0
                for quant in line.move_id.quant_ids:
                    if quant.location_id.usage != 'internal':
                        qty_out += quant.qty
                self._create_accounting_entries(cr,
                                                uid,
                                                line,
                                                move_id,
                                                qty_out,
                                                context=context)
            self.write(cr,
                       uid,
                       cost.id, {
                           'state': 'done',
                           'account_move_id': move_id
                       },
                       context=context)
            self.pool.get('account.move').post(cr,
                                               uid, [move_id],
                                               context=context)
        return True
Exemple #12
0
    def check_operation(self, cr, uid, vals):
        """ Finds which operation is called ie. start, pause, done, cancel.
        @param vals: Dictionary of values.
        @return: True or False
        """
        code_ids = self.pool.get('mrp_operations.operation.code').search(
            cr, uid, [('id', '=', vals['code_id'])])
        code = self.pool.get('mrp_operations.operation.code').browse(
            cr, uid, code_ids)[0]
        code_lst = []
        oper_ids = self.search(cr, uid,
                               [('production_id', '=', vals['production_id']),
                                ('workcenter_id', '=', vals['workcenter_id'])])
        oper_objs = self.browse(cr, uid, oper_ids)

        if not oper_objs:
            if code.start_stop != 'start':
                raise UserError(_('Operation is not started yet!'))
                return False
        else:
            for oper in oper_objs:
                code_lst.append(oper.code_id.start_stop)
            if code.start_stop == 'start':
                if 'start' in code_lst:
                    raise UserError(
                        _('Operation has already started! You can either Pause/Finish/Cancel the operation.'
                          ))
                    return False
            if code.start_stop == 'pause':
                if code_lst[len(code_lst) - 1] != 'resume' and code_lst[
                        len(code_lst) - 1] != 'start':
                    raise UserError(
                        _('In order to Pause the operation, it must be in the Start or Resume state!'
                          ))
                    return False
            if code.start_stop == 'resume':
                if code_lst[len(code_lst) - 1] != 'pause':
                    raise UserError(
                        _('In order to Resume the operation, it must be in the Pause state!'
                          ))
                    return False

            if code.start_stop == 'done':
                if code_lst[len(code_lst) - 1] != 'start' and code_lst[
                        len(code_lst) - 1] != 'resume':
                    raise UserError(
                        _('In order to Finish the operation, it must be in the Start or Resume state!'
                          ))
                    return False
                if 'cancel' in code_lst:
                    raise UserError(_('Operation is Already Cancelled!'))
                    return False
            if code.start_stop == 'cancel':
                if not 'start' in code_lst:
                    raise UserError(_('No operation to cancel.'))
                    return False
                if 'done' in code_lst:
                    raise UserError(_('Operation is already finished!'))
                    return False
        return True
Exemple #13
0
    def get_google_drive_url(self,
                             cr,
                             uid,
                             config_id,
                             res_id,
                             template_id,
                             context=None):
        config = self.browse(cr, SUPERUSER_ID, config_id, context=context)
        model = config.model_id
        filter_name = config.filter_id and config.filter_id.name or False
        record = self.pool.get(model.model).read(cr,
                                                 uid, [res_id],
                                                 context=context)[0]
        record.update({'model': model.name, 'filter': filter_name})
        name_gdocs = config.name_template
        try:
            name_gdocs = name_gdocs % record
        except:
            raise UserError(
                _("At least one key cannot be found in your Google Drive name pattern"
                  ))

        attach_pool = self.pool.get("ir.attachment")
        attach_ids = attach_pool.search(cr, uid,
                                        [('res_model', '=', model.model),
                                         ('name', '=', name_gdocs),
                                         ('res_id', '=', res_id)])
        url = False
        if attach_ids:
            attachment = attach_pool.browse(cr, uid, attach_ids[0], context)
            url = attachment.url
        else:
            url = self.copy_doc(cr, uid, res_id, template_id, name_gdocs,
                                model.model, context).get('url')
        return url
Exemple #14
0
 def write(self, cr, uid, ids, vals, context=None):
     if 'uom_id' in vals:
         new_uom = self.pool.get('product.uom').browse(cr,
                                                       uid,
                                                       vals['uom_id'],
                                                       context=context)
         for product in self.browse(cr, uid, ids, context=context):
             old_uom = product.uom_id
             if old_uom != new_uom:
                 if self.pool.get('stock.move').search(
                         cr,
                         uid,
                     [('product_id', 'in',
                       [x.id for x in product.product_variant_ids]),
                      ('state', '=', 'done')],
                         limit=1,
                         context=context):
                     raise UserError(
                         _("You can not change the unit of measure of a product that has already been used in a done stock move. If you need to change the unit of measure, you may deactivate this product."
                           ))
     return super(product_template, self).write(cr,
                                                uid,
                                                ids,
                                                vals,
                                                context=context)
Exemple #15
0
    def _get_sale_order_line_vals(self):
        order = self.env['sale.order'].search([('project_id', '=', self.account_id.id)], limit=1)
        if not order:
            return False
        if order.state != 'sale':
            raise UserError(_('The Sale Order %s linked to the Analytic Account must be validated before registering expenses.' % order.name))

        last_so_line = self.env['sale.order.line'].search([('order_id', '=', order.id)], order='sequence desc', limit=1)
        last_sequence = last_so_line.sequence + 1 if last_so_line else 100

        fpos = order.fiscal_position_id or order.partner_id.property_account_position_id
        taxes = fpos.map_tax(self.product_id.taxes_id)
        price = self._get_invoice_price(order)

        return {
            'order_id': order.id,
            'name': self.name,
            'sequence': last_sequence,
            'price_unit': price,
            'tax_id': [x.id for x in taxes],
            'discount': 0.0,
            'product_id': self.product_id.id,
            'product_uom': self.product_uom_id.id,
            'product_uom_qty': 0.0,
            'qty_delivered': self.unit_amount,
        }
Exemple #16
0
    def get_action(self, cr, uid, ids, report_name, data=None, context=None):
        """Return an action of type ir.actions.report.xml.

        :param ids: Ids of the records to print (if not used, pass an empty list)
        :param report_name: Name of the template to generate an action for
        """
        if ids:
            if not isinstance(ids, list):
                ids = [ids]
            context = dict(context or {}, active_ids=ids)

        report_obj = self.pool['ir.actions.report.xml']
        idreport = report_obj.search(cr, uid, [('report_name', '=', report_name)], context=context)
        try:
            report = report_obj.browse(cr, uid, idreport[0], context=context)
        except IndexError:
            raise UserError(_("Bad Report Reference") + _("This report is not loaded into the database: %s.") % report_name)

        return {
            'context': context,
            'data': data,
            'type': 'ir.actions.report.xml',
            'report_name': report.report_name,
            'report_type': report.report_type,
            'report_file': report.report_file,
            'context': context,
        }
Exemple #17
0
    def get_valuation_lines(self,
                            cr,
                            uid,
                            ids,
                            picking_ids=None,
                            context=None):
        picking_obj = self.pool.get('stock.picking')
        lines = []
        if not picking_ids:
            return lines

        for picking in picking_obj.browse(cr, uid, picking_ids):
            for move in picking.move_lines:
                #it doesn't make sense to make a landed cost for a product that isn't set as being valuated in real time at real cost
                if move.product_id.valuation != 'real_time' or move.product_id.cost_method != 'real':
                    continue
                total_cost = 0.0
                weight = move.product_id and move.product_id.weight * move.product_qty
                volume = move.product_id and move.product_id.volume * move.product_qty
                for quant in move.quant_ids:
                    total_cost += quant.cost * quant.qty
                vals = dict(product_id=move.product_id.id,
                            move_id=move.id,
                            quantity=move.product_uom_qty,
                            former_cost=total_cost,
                            weight=weight,
                            volume=volume)
                lines.append(vals)
        if not lines:
            raise UserError(
                _('The selected picking does not contain any move that would be impacted by landed costs. Landed costs are only possible for products configured in real time valuation with real price costing method. Please make sure it is the case, or you selected the correct picking'
                  ))
        return lines
Exemple #18
0
    def _create_accounting_entries(self,
                                   cr,
                                   uid,
                                   line,
                                   move_id,
                                   qty_out,
                                   context=None):
        product_obj = self.pool.get('product.template')
        cost_product = line.cost_line_id and line.cost_line_id.product_id
        if not cost_product:
            return False
        accounts = product_obj.browse(cr,
                                      uid,
                                      line.product_id.product_tmpl_id.id,
                                      context=context).get_product_accounts()
        debit_account_id = accounts.get(
            'stock_valuation',
            False) and accounts['stock_valuation'].id or False
        already_out_account_id = accounts['stock_output'].id
        credit_account_id = line.cost_line_id.account_id.id or cost_product.property_account_expense_id.id or cost_product.categ_id.property_account_expense_categ_id.id

        if not credit_account_id:
            raise UserError(
                _('Please configure Stock Expense Account for product: %s.') %
                (cost_product.name))

        return self._create_account_move_line(cr,
                                              uid,
                                              line,
                                              move_id,
                                              credit_account_id,
                                              debit_account_id,
                                              qty_out,
                                              already_out_account_id,
                                              context=context)
Exemple #19
0
    def _get_manufacture_pull_rule(self, cr, uid, warehouse, context=None):
        route_obj = self.pool.get('stock.location.route')
        data_obj = self.pool.get('ir.model.data')
        try:
            manufacture_route_id = data_obj.get_object_reference(
                cr, uid, 'mrp', 'route_warehouse0_manufacture')[1]
        except:
            manufacture_route_id = route_obj.search(
                cr, uid, [('name', 'like', _('Manufacture'))], context=context)
            manufacture_route_id = manufacture_route_id and manufacture_route_id[
                0] or False
        if not manufacture_route_id:
            raise UserError(_('Can\'t find any generic Manufacture route.'))

        return {
            'name':
            self._format_routename(cr,
                                   uid,
                                   warehouse,
                                   _(' Manufacture'),
                                   context=context),
            'location_id':
            warehouse.lot_stock_id.id,
            'route_id':
            manufacture_route_id,
            'action':
            'manufacture',
            'picking_type_id':
            warehouse.int_type_id.id,
            'propagate':
            False,
            'warehouse_id':
            warehouse.id,
        }
Exemple #20
0
 def create(self, cr, uid, ids, datas, context=None):
     self.pool = pooler.get_pool(cr.dbname)
     docRepository = self.pool.get('plm.document')._get_filestore(cr)
     componentType = self.pool.get('product.product')
     user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
     msg = "Printed by " + \
         str(user.name) + " : " + str(time.strftime("%d/%m/%Y %H:%M:%S"))
     output = BookCollector(jumpFirst=False,
                            customTest=(False, msg),
                            bottomHeight=10)
     children = []
     documents = []
     components = componentType.browse(cr, uid, ids, context=context)
     for component in components:
         documents.extend(component.linkeddocuments)
         idcs = componentType._getChildrenBom(cr,
                                              uid,
                                              component,
                                              0,
                                              1,
                                              context=context)
         children = componentType.browse(cr, uid, idcs, context=context)
         for child in children:
             documents.extend(child.linkeddocuments)
     if len(documents):
         return packDocuments(docRepository, list(set(documents)), output)
     if context.get("raise_report_warning", True):
         raise UserError(_("No Document found"))
    def preview(self, cr, uid, ids, context=None):
        res = {}
        wi_obj = self.browse(cr, uid, ids[0], context=context)
        if wi_obj.activity_id.type == 'email':
            view_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'mail', 'email_template_preview_form')
            res = {
                'name': _('Email Preview'),
                'view_type': 'form',
                'view_mode': 'form,tree',
                'res_model': 'email_template.preview',
                'view_id': False,
                'context': context,
                'views': [(view_id and view_id[1] or 0, 'form')],
                'type': 'ir.actions.act_window',
                'target': 'new',
                'context': "{'template_id':%d,'default_res_id':%d}"%
                                (wi_obj.activity_id.email_template_id.id,
                                 wi_obj.res_id)
            }

        elif wi_obj.activity_id.type == 'report':
            datas = {
                'ids': [wi_obj.res_id],
                'model': wi_obj.object_id.model
            }
            res = {
                'type' : 'ir.actions.report.xml',
                'report_name': wi_obj.activity_id.report_id.report_name,
                'datas' : datas,
            }
        else:
            raise UserError(_('The current step for this item has no email or report to preview.'))
        return res
Exemple #22
0
    def write(self, cr, uid, ids, vals, context=None):
        """Overwrite the write method to update the last_update field to today

        If the current value is changed and the report frequency is set to On
        change, a report is generated
        """
        if context is None:
            context = {}
        vals['last_update'] = fields.date.today()
        result = super(gamification_goal, self).write(cr,
                                                      uid,
                                                      ids,
                                                      vals,
                                                      context=context)
        for goal in self.browse(cr, uid, ids, context=context):
            if goal.state != "draft" and ('definition_id' in vals
                                          or 'user_id' in vals):
                # avoid drag&drop in kanban view
                raise UserError(
                    _('Can not modify the configuration of a started goal'))

            if vals.get('current'):
                if 'no_remind_goal' in context:
                    # new goals should not be reported
                    continue

                if goal.challenge_id and goal.challenge_id.report_message_frequency == 'onchange':
                    self.pool.get('gamification.challenge').report_progress(
                        cr,
                        SUPERUSER_ID,
                        goal.challenge_id,
                        users=[goal.user_id],
                        context=context)
        return result
Exemple #23
0
    def cancel_repair(self, cr, uid, ids, context=None):
        """ Cancels the repair
        @param self: The object pointer.
        @param cr: A database cursor
        @param uid: ID of the user currently logged in
        @param ids: List of IDs selected
        @param context: A standard dictionary
        @return:
        """
        if context is None:
            context = {}
        record_id = context and context.get('active_id', False) or False
        assert record_id, _('Active ID not Found')
        repair_order_obj = self.pool.get('mrp.repair')
        repair_line_obj = self.pool.get('mrp.repair.line')
        repair_order = repair_order_obj.browse(cr,
                                               uid,
                                               record_id,
                                               context=context)

        if repair_order.invoiced or repair_order.invoice_method == 'none':
            repair_order_obj.action_cancel(cr,
                                           uid, [record_id],
                                           context=context)
        else:
            raise UserError(_('Repair order is not invoiced.'))

        return {'type': 'ir.actions.act_window_close'}
Exemple #24
0
 def random_pick(self):
     """
     To pick a random product from the selected suppliers, and create an order with this one
     """
     self.ensure_one()
     if self.is_max_budget:
         products_obj = self.env['lunch.product'].search([
             ('supplier', "in", self.supplier_ids.ids),
             ('price', '<=', self.max_budget)
         ])
     else:
         products_obj = self.env['lunch.product'].search([
             ('supplier', "in", self.supplier_ids.ids)
         ])
     if len(products_obj) != 0:
         random_product_obj = self.env['lunch.product'].browse(
             [random.choice(products_obj.ids)])
         order_line = self.env['lunch.order.line'].create({
             'product_id':
             random_product_obj.id,
             'order_id':
             self._context['active_id']
         })
     else:
         raise UserError(
             _('No product is matching your request. Now you will starve to death.'
               ))
Exemple #25
0
    def create_employee_from_applicant(self):
        """ Create an hr.employee from the hr.applicants """
        employee = False
        for applicant in self:
            address_id = contact_name = False
            if applicant.partner_id:
                address_id = applicant.partner_id.address_get(['contact'])['contact']
                contact_name = applicant.partner_id.name_get()[0][1]
            if applicant.job_id and (applicant.partner_name or contact_name):
                applicant.job_id.write({'no_of_hired_employee': applicant.job_id.no_of_hired_employee + 1})
                employee = self.env['hr.employee'].create({'name': applicant.partner_name or contact_name,
                                               'job_id': applicant.job_id.id,
                                               'address_home_id': address_id,
                                               'department_id': applicant.department_id.id or False,
                                               'address_id': applicant.company_id and applicant.company_id.partner_id and applicant.company_id.partner_id.id or False,
                                               'work_email': applicant.department_id and applicant.department_id.company_id and applicant.department_id.company_id.email or False,
                                               'work_phone': applicant.department_id and applicant.department_id.company_id and applicant.department_id.company_id.phone or False})
                applicant.write({'emp_id': employee.id})
                applicant.job_id.message_post(
                    body=_('New Employee %s Hired') % applicant.partner_name if applicant.partner_name else applicant.name,
                    subtype="hr_recruitment.mt_job_applicant_hired")
                employee._broadcast_welcome()
            else:
                raise UserError(_('You must define an Applied Job and a Contact Name for this applicant.'))

        employee_action = self.env.ref('hr.open_view_employee_list')
        dict_act_window = employee_action.read([])[0]
        if employee:
            dict_act_window['res_id'] = employee.id
        dict_act_window['view_mode'] = 'form,tree'
        return dict_act_window
Exemple #26
0
 def _prepare_invoice(self):
     """
     Prepare the dict of values to create the new invoice for a sales order. This method may be
     overridden to implement custom invoice generation (making sure to call super() to establish
     a clean extension chain).
     """
     self.ensure_one()
     journal_id = self.env['account.invoice'].default_get(['journal_id'])['journal_id']
     if not journal_id:
         raise UserError(_('Please define an accounting sale journal for this company.'))
     invoice_vals = {
         'name': self.client_order_ref or '',
         'origin': self.name,
         'type': 'out_invoice',
         'reference': self.client_order_ref or self.name,
         'account_id': self.partner_invoice_id.property_account_receivable_id.id,
         'partner_id': self.partner_invoice_id.id,
         'journal_id': journal_id,
         'currency_id': self.pricelist_id.currency_id.id,
         'comment': self.note,
         'payment_term_id': self.payment_term_id.id,
         'fiscal_position_id': self.fiscal_position_id.id or self.partner_invoice_id.property_account_position_id.id,
         'company_id': self.company_id.id,
         'user_id': self.user_id and self.user_id.id,
         'team_id': self.team_id.id
     }
     return invoice_vals
Exemple #27
0
    def action_grant_badge(self, cr, uid, ids, context=None):
        """Wizard action for sending a badge to a chosen user"""

        badge_user_obj = self.pool.get('gamification.badge.user')

        for wiz in self.browse(cr, uid, ids, context=context):
            if uid == wiz.user_id.id:
                raise UserError(_('You can not grant a badge to yourself'))

            #create the badge
            values = {
                'user_id': wiz.user_id.id,
                'sender_id': uid,
                'badge_id': wiz.badge_id.id,
                'comment': wiz.comment,
            }
            badge_user = badge_user_obj.create(cr,
                                               uid,
                                               values,
                                               context=context)
            result = badge_user_obj._send_badge(cr,
                                                uid,
                                                badge_user,
                                                context=context)

        return result
Exemple #28
0
    def get_lib(self, cursor, uid):
        """Return the lib wkhtml path"""
        proxy = self.pool['ir.config_parameter']
        webkit_path = proxy.get_param(cursor, SUPERUSER_ID, 'webkit_path')

        if not webkit_path:
            try:
                defpath = os.environ.get('PATH', os.defpath).split(os.pathsep)
                if hasattr(sys, 'frozen'):
                    defpath.append(os.getcwd())
                    if tools.config['root_path']:
                        defpath.append(
                            os.path.dirname(tools.config['root_path']))
                webkit_path = tools.which('wkhtmltopdf',
                                          path=os.pathsep.join(defpath))
            except IOError:
                webkit_path = None

        if webkit_path:
            return webkit_path

        raise UserError(
            _('Wkhtmltopdf library path is not set') + ' ' +
            _('Please install executable on your system'
              ' (sudo apt-get install wkhtmltopdf) or download it from here:'
              ' http://code.google.com/p/wkhtmltopdf/downloads/list and set the'
              ' path in the ir.config_parameter with the webkit_path key.'
              'Minimal version is 0.9.9'))
Exemple #29
0
    def _prepare_invoice_line(self, qty):
        """
        Prepare the dict of values to create the new invoice line for a sales order line.

        :param qty: float quantity to invoice
        """
        self.ensure_one()
        res = {}
        account = self.product_id.property_account_income_id or self.product_id.categ_id.property_account_income_categ_id
        if not account:
            raise UserError(_('Please define income account for this product: "%s" (id:%d) - or for its category: "%s".') % \
                            (self.product_id.name, self.product_id.id, self.product_id.categ_id.name))

        fpos = self.order_id.fiscal_position_id or self.order_id.partner_id.property_account_position_id
        if fpos:
            account = fpos.map_account(account)

        res = {
            'name': self.name,
            'sequence': self.sequence,
            'origin': self.order_id.name,
            'account_id': account.id,
            'price_unit': self.price_unit,
            'quantity': qty,
            'discount': self.discount,
            'uom_id': self.product_uom.id,
            'product_id': self.product_id.id or False,
            'invoice_line_tax_ids': [(6, 0, self.tax_id.ids)],
            'account_analytic_id': self.order_id.project_id.id,
        }
        return res
Exemple #30
0
    def _get_buy_pull_rule(self, cr, uid, warehouse, context=None):
        route_obj = self.pool.get('stock.location.route')
        data_obj = self.pool.get('ir.model.data')
        try:
            buy_route_id = data_obj.get_object_reference(
                cr, uid, 'purchase', 'route_warehouse0_buy')[1]
        except:
            buy_route_id = route_obj.search(cr,
                                            uid, [('name', 'like', _('Buy'))],
                                            context=context)
            buy_route_id = buy_route_id and buy_route_id[0] or False
        if not buy_route_id:
            raise UserError(_('Can\'t find any generic Buy route.'))

        return {
            'name':
            self._format_routename(cr,
                                   uid,
                                   warehouse,
                                   _(' Buy'),
                                   context=context),
            'location_id':
            warehouse.in_type_id.default_location_dest_id.id,
            'route_id':
            buy_route_id,
            'action':
            'buy',
            'picking_type_id':
            warehouse.in_type_id.id,
            'warehouse_id':
            warehouse.id,
            'group_propagation_option':
            'none',
        }