예제 #1
0
파일: sale.py 프로젝트: yuancloud/yuancloud
    def automatic_payment(self, amount=None):
        """ Create the payment entries to pay a sale order, respecting
        the payment terms.
        If no amount is defined, it will pay the residual amount of the sale
        order.
        """
        self.ensure_one()
        method = self.payment_method_id
        if not method:
            raise exceptions.Warning(
                _("An automatic payment can not be created for the sale "
                  "order %s because it has no payment method.") % self.name)

        if not method.journal_id:
            raise exceptions.Warning(
                _("An automatic payment should be created for the sale order"
                  " %s but the payment method '%s' has no journal defined.") %
                (self.name, method.name))

        journal = method.journal_id
        date = self.date_order[:10]
        if amount is None:
            amount = self.residual
        if self.payment_term:
            amounts = self.payment_term.compute(amount, date_ref=date)[0]
        else:
            amounts = [(date, amount)]

        # reversed is cosmetic, compute returns terms in the 'wrong' order
        for date, amount in reversed(amounts):
            self._add_payment(journal, amount, date)
        return True
예제 #2
0
    def write(self, vals):
        '''
        功能:员工代号不能重复
        :param vals:
        :return:
        '''
        try:
            for employee in self:
                code = vals.get('code', False)
                if code:
                    exis_emps = self.env['hr.employee'].search([
                        ('code', '=', code), ('id', '!=', employee.id)
                    ])
                    if len(exis_emps) > 0:
                        exis_emp_names = ''
                        for exis_emp in exis_emps:
                            exis_emp_names = exis_emp_names + exis_emp.name + ','
                        msg = '员工代号%s重复(具有该员工代号的员工有%s)!' % (
                            code, exis_emp_names[0:-1])
                        raise except_osv(_('错误'), _(msg))
                return super(hr_employee, employee).write(vals)

        except Exception as e:
            _logger.error(e)
            raise e
예제 #3
0
 def post_notification(self):
     base_url = self.env['ir.config_parameter'].get_param('web.base.url')
     for post in self:
         if post.state == 'active' and post.parent_id:
             body = _(
                 '<p>A new answer for <i>%s</i> has been posted. <a href="%s/forum/%s/question/%s">Click here to access the post.</a></p>' %
                 (post.parent_id.name, base_url, slug(post.parent_id.forum_id), slug(post.parent_id))
             )
             post.parent_id.message_post(subject=_('Re: %s') % post.parent_id.name, body=body, subtype='website_forum.mt_answer_new')
         elif post.state == 'active' and not post.parent_id:
             body = _(
                 '<p>A new question <i>%s</i> has been asked on %s. <a href="%s/forum/%s/question/%s">Click here to access the question.</a></p>' %
                 (post.name, post.forum_id.name, base_url, slug(post.forum_id), slug(post))
             )
             post.message_post(subject=post.name, body=body, subtype='website_forum.mt_question_new')
         elif post.state == 'pending' and not post.parent_id:
             # TDE FIXME: in master, you should probably use a subtype;
             # however here we remove subtype but set partner_ids
             partners = post.sudo().message_partner_ids.filtered(lambda partner: partner.user_ids and partner.user_ids.karma >= post.forum_id.karma_moderate)
             note_subtype = self.sudo().env.ref('mail.mt_note')
             body = _(
                 '<p>A new question <i>%s</i> has been asked on %s and require your validation. <a href="%s/forum/%s/question/%s">Click here to access the question.</a></p>' %
                 (post.name, post.forum_id.name, base_url, slug(post.forum_id), slug(post))
             )
             post.message_post(subject=post.name, body=body, subtype_id=note_subtype.id, partner_ids=partners.ids)
     return True
예제 #4
0
    def write(self, vals):
        if 'content' in vals:
            vals['content'] = self._update_content(vals['content'], self.forum_id.id)
        if 'state' in vals:
            if vals['state'] in ['active', 'close'] and any(not post.can_close for post in self):
                raise KarmaError('Not enough karma to close or reopen a post.')
        if 'active' in vals:
            if any(not post.can_unlink for post in self):
                raise KarmaError('Not enough karma to delete or reactivate a post')
        if 'is_correct' in vals:
            if any(not post.can_accept for post in self):
                raise KarmaError('Not enough karma to accept or refuse an answer')
            # update karma except for self-acceptance
            mult = 1 if vals['is_correct'] else -1
            for post in self:
                if vals['is_correct'] != post.is_correct and post.create_uid.id != self._uid:
                    post.create_uid.sudo().add_karma(post.forum_id.karma_gen_answer_accepted * mult)
                    self.env.user.sudo().add_karma(post.forum_id.karma_gen_answer_accept * mult)
        if any(key not in ['state', 'active', 'is_correct', 'closed_uid', 'closed_date', 'closed_reason_id'] for key in vals.keys()) and any(not post.can_edit for post in self):
            raise KarmaError('Not enough karma to edit a post.')

        res = super(Post, self).write(vals)
        # if post content modify, notify followers
        if 'content' in vals or 'name' in vals:
            for post in self:
                if post.parent_id:
                    body, subtype = _('Answer Edited'), 'website_forum.mt_answer_edit'
                    obj_id = post.parent_id
                else:
                    body, subtype = _('Question Edited'), 'website_forum.mt_question_edit'
                    obj_id = post
                obj_id.message_post(body=body, subtype=subtype)
        return res
예제 #5
0
 def _get_recursive_parts(self, cr, uid, ids, excludeStatuses,
                          includeStatuses):
     """
        Get all ids related to current one as children
     """
     errors = []
     tobeReleasedIDs = []
     if not isinstance(ids, (list, tuple)):
         ids = [ids]
     tobeReleasedIDs.extend(ids)
     children = []
     for oic in self.browse(cr, uid, ids, context=None):
         children = self.browse(cr, uid,
                                self._getChildrenBom(cr, uid, oic, 1))
         for child in children:
             if (child.state
                     not in excludeStatuses) and (child.state
                                                  not in includeStatuses):
                 errors.append(
                     _("Product code: %r revision %r ")
                     & (child.engineering_code, child.engineering_revision))
                 continue
             if child.state in includeStatuses:
                 if child.id not in tobeReleasedIDs:
                     tobeReleasedIDs.append(child.id)
     msg = ''
     if errors:
         msg = _("Unable to perform workFlow action due")
         for subMsg in errors:
             msg = "\n" + subMsg
     return (msg, list(set(tobeReleasedIDs)))
예제 #6
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"))
예제 #7
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
예제 #8
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
예제 #9
0
    def create(self,vals):
        '''
        功能:重写create
        :param vals:
        :return:
        '''
        try :
            #检查门店编码是否符合规定(四位且首字母大写)
            code=vals['code']
            re_str='[A-Z]{1}[A-Z0-9]{3}'
            if len(code)!=4 or not re.match(re_str,code):
                msg='门店编码:%s,不满足门店编码规范:必须为"大写字母与数字组合的四位字符串"且"首字母大写"!' % vals['code']
                raise  except_osv(_('错误'), _(msg))

            #检查是否创建销售团队
            if (vals['store_owner'] or len(vals['users'])>0) and not vals['sale_team']:
                #创建销售团队
                sale_team=self.env['crm.team']
                sale_team_values={}
                sale_team_values['name']=vals['name']+'-销售团队'
                sale_team_values['code']=vals['code']
                #团队成员
                user_ids=[]
                if vals['store_owner']:
                    sale_team_values['user_id']=vals['store_owner']
                for userinfo in vals['users']:
                    user_ids.append(userinfo[2]['user_id'])
                member_ids=[[6, False, user_ids]]
                sale_team_values['member_ids']=member_ids
                sale_team_id=sale_team.create(sale_team_values)
                vals['sale_team']=sale_team_id.id

            #检查是否创建POS
            virtual_location=vals.get('virtual_location',False)
            company_id=vals.get('company_id',False)
            if not virtual_location and not company_id:
                if len(vals['pos_ids'])==0:
                    #创建POS
                    pos_instance=self.env['pos.config']
                    pos_value={}
                    pos_value['name']=vals['code']+'-POS'
                    pos_value['stock_location_id']=vals['virtual_location']
                    pos_value['company_id']=vals['company_id']
                    if vals['company_id']:
                        journals=self.env['account.journal'].search([('company_id','=',vals['company_id']),('journal_user','=','1')])
                        journal_ids=[]
                        for journal in journals:
                            journal_ids.append(journal.id)
                        pos_value['journal_ids']=[[6, False, journal_ids]]
                    pos_id=pos_instance.create(pos_value)
                    pos_ids=[[6, False, [pos_id.id]]]
                    vals['pos_ids']=pos_ids

            return  super(o2o_store, self).create(vals)
        except Exception as e:
            _logger.error(e)
            raise e
예제 #10
0
class plm_component(models.Model):
    _name       = 'product.product'
    _inherit    = 'product.product'

    @api.multi
    def _father_part_compute(self, name='', arg={}):
        """ Gets father bom.
        @param self: The object pointer
        @param cr: The current row, from the database cursor,
        @param uid: The current user ID for security checks
        @param ids: List of selected IDs
        @param name: Name of the field
        @param arg: User defined argument
        @param context: A standard dictionary for contextual values
        @return:  Dictionary of values
        """
        bom_line_objType = self.env['mrp.bom.line']
        prod_objs = self.browse(self.ids)
        for prod_obj in prod_objs:
            prod_ids=[]
            bom_line_objs = bom_line_objType.search([('product_id','=',prod_obj.id)])
            for bom_line_obj in bom_line_objs:                
                prod_ids.extend([bom_line_obj.bom_id.product_id.id])
            prod_obj.father_part_ids = self.env['product.product'].browse(list(set(prod_ids)))
    
    linkeddocuments = fields.Many2many  ('plm.document', 'plm_component_document_rel','component_id','document_id', _('Linked Docs'))  
    tmp_material    = fields.Many2one   ('plm.material',_('Raw Material'), required=False, change_default=True, help=_("Select raw material for current product"))
    #tmp_treatment   = fields.Many2one('plm.treatment',_('Thermal Treatment'), required=False, change_default=True, help=_("Select thermal treatment for current product"))
    tmp_surface     = fields.Many2one   ('plm.finishing',_('Surface Finishing'), required=False, change_default=True, help=_("Select surface finishing for current product"))
    father_part_ids = fields.Many2many  ('product.product', compute = _father_part_compute, string=_("BoM Hierarchy"), store =False)

    def on_change_tmpmater(self, cr, uid, ids, tmp_material=False):
        values = {'engineering_material': ''}
        if tmp_material:
            thisMaterial = self.pool.get('plm.material')
            thisObject = thisMaterial.browse(cr, uid, tmp_material)
            if thisObject.name:
                values['engineering_material'] = unicode(thisObject.name)
        return {'value': values}

    def on_change_tmptreatment(self, cr, uid, ids, tmp_treatment=False):
        values = {'engineering_treatment': ''}
        if tmp_treatment:
            thisTreatment = self.pool.get('plm.treatment')
            thisObject = thisTreatment.browse(cr, uid, tmp_treatment)
            if thisObject.name:
                values['engineering_treatment'] = unicode(thisObject.name)
        return {'value': values}

    def on_change_tmpsurface(self, cr, uid, ids, tmp_surface=False):
        values = {'engineering_surface': ''}
        if tmp_surface:
            thisSurface = self.pool.get('plm.finishing')
            thisObject = thisSurface.browse(cr, uid, tmp_surface)
            if thisObject.name:
                values['engineering_surface'] = unicode(thisObject.name)
        return {'value': values}
예제 #11
0
 def create_custom_menu(self):
     print self
     code = self.code
     officalaccount = self.officalaccount.id
     if code:
         print code
         print officalaccount
         if self.menuid:
             raise except_osv(_('Error!'), _(u"已经创建微信个性化菜单,不能再次创建"))
         custom_menu = self.pool.get(
             'wx.officialaccount_menu').get_custom_menu(
                 self._cr, self._uid, self._context, code, officalaccount)
         print custom_menu
         matchrule = {}
         if self.sex:
             matchrule.update({"sex": self.sex})
         # if self.group_id:
         #     matchrule.update({
         #         "group_id":self.group_id['groupid']
         #     })
         if self.client_platform_type:
             matchrule.update(
                 {"client_platform_type": self.client_platform_type})
         if self.country:
             matchrule.update({"country": self.country})
         if self.province:
             matchrule.update({"province": self.province})
         if self.city:
             matchrule.update({"city": self.city})
         menudata = "{" + custom_menu + "," + "\"matchrule\":" + json.dumps(
             matchrule, ensure_ascii=False) + "}"
         print menudata
         if self.officalaccount.is_auth_officialaccount:
             auth_access_token = public_sdk.get_authorizer_access_token(
                 self.officalaccount.wx_appid,
                 self.officalaccount.auth_component.auth_component_appid,
                 self.officalaccount.auth_component.
                 auth_component_appsecret,
                 self.officalaccount.authorizer_refresh_token)
             menuresult = menu_manager.create_addconditional_menu_access_token(
                 menudata, auth_access_token)
             pass
         else:
             menuManager = menu_manager.menu_manager(
                 self.officalaccount.wx_appid,
                 self.officalaccount.wx_appsecret)
             menuresult = menuManager.create_addconditional_menu(menudata)
         if 'errcode' in menuresult:
             result = "创建个性化菜单失败:" + str(
                 menuresult['errcode']) + "," + menuresult['errmsg']
             raise except_osv(_('Error!'), _(result))
             pass
         else:
             menuid = menuresult['menuid']
             self.menuid = menuid
         print menuresult
예제 #12
0
class report_plm_document_wall(models.Model):
    _name = "report.plm_document.wall"
    _description = "Users that did not inserted documents since one month"
    _auto = False

    name = fields.Date(_('Month'), readonly=True)
    user_id = fields.Many2one('res.users', _('Owner'), readonly=True)
    user = fields.Char(_('User'), size=64, readonly=True)
    month = fields.Char(_('Month'), size=24, readonly=True)
    last = fields.Datetime(_('Last Posted Time'), readonly=True)
예제 #13
0
def geo_find(addr):
    url = 'http://apis.map.qq.com/ws/geocoder/v1/?key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77&'
    url += urllib.quote(addr.encode('utf8'))

    try:
        result = json.load(urllib.urlopen(url))
    except Exception, e:
        raise osv.except_osv(_('Network error'),
                             _(
                                 'Cannot contact geolocation servers. Please make sure that your internet connection is up and running (%s).') % e)
예제 #14
0
class plm_config_settings(models.Model):
    _name = 'plm.config.settings'
    _inherit = 'res.config.settings'

    plm_service_id  =   fields.Char(_('Register PLM module, insert your Service ID.'),  size=128,  help=_("Insert the Service ID and register your PLM module. Ask it to OmniaSolutions."))
    activated_id    =   fields.Char(_('Activated PLM client'),                          size=128,  help=_("Listed activated Client."))
    active_editor   =   fields.Char(_('Client Editor Name'),                            size=128,  help=_("Used Editor Name"))
    active_node     =   fields.Char(_('OS machine name'),                               size=128,  help=_("Editor Machine name"))
    active_os       =   fields.Char(_('OS name'),                                       size=128,  help=_("Editor OS name"))
    active_os_rel   =   fields.Char(_('OS release'),                                    size=128,  help=_("Editor OS release"))
    active_os_ver   =   fields.Char(_('OS version'),                                    size=128,  help=_("Editor OS version"))
    active_os_arch  =   fields.Char(_('OS architecture'),                               size=128,  help=_("Editor OS architecture"))
    node_id         =   fields.Char(_('Registered PLM client'),                         size=128,  help=_("Listed registered Client."))

    def GetServiceIds(self, cr, uid, oids, default=None, context=None):
        """
            Get all Service Ids registered.
        """
        ids = []
        partIds = self.search(cr, uid, [('activated_id', '=', False)], context=context)
        for part in self.browse(cr, uid, partIds):
            ids.append(part.plm_service_id)
        return list(set(ids))

    def RegisterActiveId(self, cr, uid, vals, default=None, context=None):
        """
            Get all Service Ids registered.  [serviceID, activation, activeEditor, (system, node, release, version, machine, processor) ]
        """
        defaults = {}
        serviceID, activation, activeEditor, platformData, nodeId = vals
        if activation:
            defaults['plm_service_id'] = serviceID
            defaults['activated_id'] = activation
            defaults['active_editor'] = activeEditor
            defaults['active_os'] = platformData[0]
            defaults['active_node'] = platformData[1]
            defaults['active_os_rel'] = platformData[2]
            defaults['active_os_ver'] = platformData[3]
            defaults['active_os_arch'] = platformData[4]
            defaults['node_id'] = nodeId
            partIds = self.search(cr, uid, [('plm_service_id', '=', serviceID), ('activated_id', '=', activation)], context=context)
            if partIds:
                for partId  in partIds:
                    self.write(cr, uid, [partId], defaults, context=context)
                    return False
            self.create(cr, uid, defaults, context=context)
        return False

    def GetActiveServiceId(self, cr, uid, vals, default=None, context=None):
        """
            Get all Service Ids registered.  [serviceID, activation, activeEditor, (system, node, release, version, machine, processor) ]
        """
        results = []
        nodeId, activation, activeEditor, platformData = vals
        activeEditor = activeEditor
        platformData = platformData
        partIds = self.search(cr, uid, [('node_id', '=', nodeId), ('activated_id', '=', activation)], context=context)
        for partId  in self.browse(cr, uid, partIds):
            results.append(partId.plm_service_id)
        return results
예제 #15
0
 def on_change_url(self):
     self.ensure_one()
     if self.url:
         res = self._parse_document_url(self.url)
         if res.get('error'):
             raise Warning(_('Could not fetch data from url. Document or access right not available:\n%s') % res['error'])
         values = res['values']
         if not values.get('document_id'):
             raise Warning(_('Please enter valid Youtube or Google Doc URL'))
         for key, value in values.iteritems():
             setattr(self, key, value)
예제 #16
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'}
예제 #18
0
 def action_release(self, cr, uid, ids, context=None):
     """
        action to be executed for Released state
     """
     tmpl_ids = []
     full_ids = []
     defaults = {}
     prodTmplType = self.pool.get('product.template')
     excludeStatuses = ['released', 'undermodify', 'obsoleted']
     includeStatuses = ['confirmed']
     errors, allIDs = self._get_recursive_parts(cr, uid, ids,
                                                excludeStatuses,
                                                includeStatuses)
     if len(allIDs) < 1 or len(errors) > 0:
         raise UserError(errors)
     allProdObjs = self.browse(cr, uid, allIDs, context=context)
     for oldObject in allProdObjs:
         last_id = self._getbyrevision(cr, uid, oldObject.engineering_code,
                                       oldObject.engineering_revision - 1)
         if last_id != None:
             defaults['engineering_writable'] = False
             defaults['state'] = 'obsoleted'
             prodObj = self.browse(cr, uid, [last_id], context=context)
             prodTmplType.write(cr,
                                uid, [prodObj.product_tmpl_id.id],
                                defaults,
                                context=context)
             self.wf_message_post(
                 cr,
                 uid, [last_id],
                 body=_('Status moved to: %s.' %
                        (USEDIC_STATES[defaults['state']])))
         defaults['engineering_writable'] = False
         defaults['state'] = 'released'
     self._action_ondocuments(cr, uid, allIDs, 'release')
     for currId in allProdObjs:
         if not (currId.id in ids):
             tmpl_ids.append(currId.product_tmpl_id.id)
         full_ids.append(currId.product_tmpl_id.id)
     self.signal_workflow(cr, uid, tmpl_ids, 'release')
     objId = self.pool.get('product.template').write(cr,
                                                     uid,
                                                     full_ids,
                                                     defaults,
                                                     context=context)
     if (objId):
         self.wf_message_post(cr,
                              uid,
                              allIDs,
                              body=_('Status moved to: %s.' %
                                     (USEDIC_STATES[defaults['state']])))
     return objId
예제 #19
0
 def _get_new_menu_pages(self):
     todo = [(_('Introduction'), 'website_event.template_intro'),
             (_('Location'), 'website_event.template_location')]
     result = []
     for name, path in todo:
         complete_name = name + ' ' + self.name
         newpath = self.env['website'].new_page(complete_name,
                                                path,
                                                ispage=False)
         url = "/event/" + slug(self) + "/page/" + newpath
         result.append((name, url))
     result.append((_('Register'), '/event/%s/register' % slug(self)))
     return result
예제 #20
0
class plm_description(models.Model):
    _inherit = "plm.description"

    bom_tmpl = fields.Many2one(
        'mrp.bom',
        _('Choose a BoM'),
        required=False,
        change_default=True,
        help=_("Select a  BoM as template to drive building Spare BoM."))

    _defaults = {
        'bom_tmpl': lambda *a: False,
    }
예제 #21
0
 def _onchange_product_uom_qty(self):
     if self.state == 'sale' and self.product_id.type in [
             'product', 'consu'
     ] and self.product_uom_qty < self._origin.product_uom_qty:
         warning_mess = {
             'title':
             _('Ordered quantity decreased!'),
             'message':
             _('You are decreasing the ordered quantity! Do not forget to manually update the delivery order if needed.'
               ),
         }
         return {'warning': warning_mess}
     return {}
예제 #22
0
 def NewRevision(self, cr, uid, ids, context=None):
     """
         create a new revision of current component
     """
     newID = None
     newIndex = 0
     for tmpObject in self.browse(cr, uid, ids, context=context):
         latestIDs = self.GetLatestIds(
             cr,
             uid, [(tmpObject.engineering_code,
                    tmpObject.engineering_revision, False)],
             context=context)
         for oldObject in self.browse(cr, uid, latestIDs, context=context):
             newIndex = int(oldObject.engineering_revision) + 1
             defaults = {}
             defaults['engineering_writable'] = False
             defaults['state'] = 'undermodify'
             self.write(cr,
                        uid, [oldObject.id],
                        defaults,
                        context=context,
                        check=False)
             self.wf_message_post(
                 cr,
                 uid, [oldObject.id],
                 body=_('Status moved to: %s.' %
                        (USEDIC_STATES[defaults['state']])))
             # store updated infos in "revision" object
             defaults[
                 'name'] = oldObject.name  # copy function needs an explicit name value
             defaults['engineering_revision'] = newIndex
             defaults['engineering_writable'] = True
             defaults['state'] = 'draft'
             defaults['linkeddocuments'] = [
             ]  # Clean attached documents for new revision object
             newID = self.copy(cr,
                               uid,
                               oldObject.id,
                               defaults,
                               context=context)
             self.wf_message_post(cr,
                                  uid, [oldObject.id],
                                  body=_('Created : New Revision.'))
             self.write(cr,
                        uid, [newID], {'name': oldObject.name},
                        check=False,
                        context=None)
             # create a new "old revision" object
             break
         break
     return (newID, newIndex)
예제 #23
0
class plm_finishing(models.Model):
    _name = "plm.finishing"
    _description = "Surface Finishing"

    name            =   fields.Char(_('Specification'), size=128, required=True)
    description     =   fields.Char(_('Description'), size=128)
    sequence        =   fields.Integer(_('Sequence'), help=_("Gives the sequence order when displaying a list of product categories."))

#    _defaults = {
#        'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'plm.finishing'),
#    }
    _sql_constraints = [
        ('name_uniq', 'unique(name)', _('Raw Material has to be unique !')),
    ]
예제 #24
0
 def saveChild(name,  partID, sourceID, bomID=None, kindBom=None, args=None):
     """
         Saves the relation ( child side in mrp.bom.line )
     """
     try:
         res={}
         if bomID!=None:
             res['bom_id']=bomID
         if kindBom!=None:
             res['type']=kindBom
         else:
             res['type']='ebom'
         res['product_id']=partID
         res['source_id']=sourceID
         res['name']=name
         if args!=None:
             for arg in args:
                 res[str(arg)]=args[str(arg)]
         if ('product_qty' in res):
             if(type(res['product_qty'])!=types.FloatType) or (res['product_qty']<1e-6):
                 res['product_qty']=1.0
         return self.pool.get('mrp.bom.line').create(cr, uid, res)
     except:
         logging.error("saveChild :  unable to create a relation for part (%s) with source (%d) : %s." %(name,sourceID,str(args)))
         raise AttributeError(_("saveChild :  unable to create a relation for part (%s) with source (%d) : %s." %(name,sourceID,str(sys.exc_info()))))
예제 #25
0
 def saveParent(name,  partID, sourceID, kindBom=None, args=None):
     """
         Saves the relation ( parent side in mrp.bom )
     """
     try:
         res={}
         if kindBom!=None:
             res['type']=kindBom
         else:
             res['type']='ebom'
         
         objPart=self.pool.get('product.product').browse(cr,uid,partID,context=None)
         res['product_tmpl_id']=objPart.product_tmpl_id.id
         res['product_id']=partID
         res['source_id']=sourceID
         res['name']=name
         if args!=None:
             for arg in args:
                 res[str(arg)]=args[str(arg)]
         if ('product_qty' in res):
             if(type(res['product_qty'])!=types.FloatType) or (res['product_qty']<1e-6):
                 res['product_qty']=1.0
         return self.create(cr, uid, res)
     except:
         logging.error("saveParent :  unable to create a relation for part (%s) with source (%d) : %s." %(name,sourceID,str(args)))
         raise AttributeError(_("saveParent :  unable to create a relation for part (%s) with source (%d) : %s." %(name,sourceID,str(sys.exc_info()))))
예제 #26
0
     def toCompute(parentName, relations):
         """
             Processes relations  
         """
         sourceIDParent=None
         sourceID=None
         bomID=False
         subRelations=[(a, b, c, d, e, f) for a, b, c, d, e, f in relations if a == parentName]
         if len(subRelations)<1: # no relation to save 
             return None
         parentName, parentID, tmpChildName, tmpChildID, sourceID, tempRelArgs=subRelations[0]
         ids=self.search(cr,uid,[('product_id','=',parentID),('source_id','=',sourceID)])
         if not ids:
             bomID=saveParent(parentName, parentID, sourceID, kindBom='ebom')
             for rel in subRelations:
                 #print "Save Relation ", rel
                 parentName, parentID, childName, childID, sourceID, relArgs=rel
                 if parentName == childName:
                     logging.error('toCompute : Father (%s) refers to himself' %(str(parentName)))
                     raise Exception(_('saveChild.toCompute : Father "%s" refers to himself' %(str(parentName))))
 
                 tmpBomId=saveChild(childName, childID, sourceID, bomID, kindBom='ebom', args=relArgs)
                 tmpBomId=toCompute(childName, relations)
             self.RebaseProductWeight(cr, uid, bomID, self.RebaseBomWeight(cr, uid, bomID))
         return bomID
예제 #27
0
파일: note.py 프로젝트: yuancloud/yuancloud
 def _notification_get_recipient_groups(self,
                                        cr,
                                        uid,
                                        ids,
                                        message,
                                        recipients,
                                        context=None):
     res = super(note_note,
                 self)._notification_get_recipient_groups(cr,
                                                          uid,
                                                          ids,
                                                          message,
                                                          recipients,
                                                          context=context)
     new_action_id = self.pool['ir.model.data'].xmlid_to_res_id(
         cr, uid, 'note.action_note_note')
     new_action = self._notification_link_helper(cr,
                                                 uid,
                                                 ids,
                                                 'new',
                                                 context=context,
                                                 action_id=new_action_id)
     res['user'] = {
         'actions': [{
             'url': new_action,
             'title': _('New Note')
         }]
     }
     return res
예제 #28
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,
        }
예제 #29
0
 def _parse_document_url(self, url, only_preview_fields=False):
     document_source, document_id = self._find_document_data_from_url(url)
     if document_source and hasattr(self,
                                    '_parse_%s_document' % document_source):
         return getattr(self, '_parse_%s_document' % document_source)(
             document_id, only_preview_fields)
     return {'error': _('Unknown document')}
예제 #30
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"))