예제 #1
0
    def _adyen_form_get_tx_from_data(self, cr, uid, data, context=None):
        reference, pspReference = data.get('merchantReference'), data.get('pspReference')
        if not reference or not pspReference:
            error_msg = _('Adyen: received data with missing reference (%s) or missing pspReference (%s)') % (reference, pspReference)
            _logger.info(error_msg)
            raise ValidationError(error_msg)

        # find tx -> @TDENOTE use pspReference ?
        tx_ids = self.pool['payment.transaction'].search(cr, uid, [('reference', '=', reference)], context=context)
        if not tx_ids or len(tx_ids) > 1:
            error_msg = _('Adyen: received data for reference %s') % (reference)
            if not tx_ids:
                error_msg += _('; no order found')
            else:
                error_msg += _('; multiple order found')
            _logger.info(error_msg)
            raise ValidationError(error_msg)
        tx = self.pool['payment.transaction'].browse(cr, uid, tx_ids[0], context=context)

        # verify shasign
        shasign_check = self.pool['payment.acquirer']._adyen_generate_merchant_sig(tx.acquirer_id, 'out', data)
        if shasign_check != data.get('merchantSig'):
            error_msg = _('Adyen: invalid merchantSig, received %s, computed %s') % (data.get('merchantSig'), shasign_check)
            _logger.warning(error_msg)
            raise ValidationError(error_msg)

        return tx
예제 #2
0
    def _cart_update(self, cr, uid, ids, product_id=None, line_id=None, add_qty=0, set_qty=0, context=None, **kwargs):
        """ Add or set product quantity, add_qty can be negative """
        value = super(sale_order, self)._cart_update(cr, uid, ids, product_id, line_id, add_qty, set_qty, context=context, **kwargs)

        sol = self.pool.get('sale.order.line')
        line = sol.browse(cr, SUPERUSER_ID, value.get('line_id'), context=context)

        # link a product to the sale order
        if kwargs.get('linked_line_id'):
            linked_line_id = sol.browse(cr, SUPERUSER_ID, kwargs['linked_line_id'], context=context)
            line.write({
                    "name": _("%s\nOption for: %s") % (line.name, linked_line_id.product_id.name_get()[0][1]),
                    "linked_line_id": linked_line_id.id
                })

        value['option_ids'] = set()
        for so in self.browse(cr, uid, ids, context=context):
            # select all optional products linked to the updated line
            option_line_ids = [l for l in so.order_line if l.linked_line_id.id == line.id]

            # update line
            for option_line_id in option_line_ids:
                super(sale_order, self)._cart_update(cr, uid, ids, option_line_id.product_id.id, option_line_id.id, add_qty, set_qty, context=context, **kwargs)
                option_line_id.write({"name": _("%s\nOption for: %s") % (option_line_id.name, option_line_id.linked_line_id.product_id.name_get()[0][1])})
                value['option_ids'].add(option_line_id.id)

        value['option_ids'] = list(value['option_ids'])

        return value
예제 #3
0
 def compute_rule(self, cr, uid, rule_id, localdict, context=None):
     """
     :param rule_id: id of rule to compute
     :param localdict: dictionary containing the environement in which to compute the rule
     :return: returns a tuple build as the base/amount computed, the quantity and the rate
     :rtype: (float, float, float)
     """
     rule = self.browse(cr, uid, rule_id, context=context)
     if rule.amount_select == 'fix':
         try:
             return rule.amount_fix, float(eval(rule.quantity, localdict)), 100.0
         except:
             raise UserError(_('Wrong quantity defined for salary rule %s (%s).') % (rule.name, rule.code))
     elif rule.amount_select == 'percentage':
         try:
             return (float(eval(rule.amount_percentage_base, localdict)),
                     float(eval(rule.quantity, localdict)),
                     rule.amount_percentage)
         except:
             raise UserError(_('Wrong percentage base or quantity defined for salary rule %s (%s).') % (rule.name, rule.code))
     else:
         try:
             eval(rule.amount_python_compute, localdict, mode='exec', nocopy=True)
             return float(localdict['result']), 'result_qty' in localdict and localdict['result_qty'] or 1.0, 'result_rate' in localdict and localdict['result_rate'] or 100.0
         except:
             raise UserError(_('Wrong python code defined for salary rule %s (%s).') % (rule.name, rule.code))
예제 #4
0
    def state_update(self, newstate, states_to_update, level=100):
        if level < 1:
            raise UserError(_('Recursion error in modules dependencies !'))

        # whether some modules are installed with demo data
        demo = False

        for module in self:
            # determine dependency modules to update/others
            update_mods, ready_mods = self.browse(), self.browse()
            for dep in module.dependencies_id:
                if dep.state == 'unknown':
                    raise UserError(_("You try to install module '%s' that depends on module '%s'.\nBut the latter module is not available in your system.") % (module.name, dep.name,))
                if dep.depend_id.state == newstate:
                    ready_mods += dep.depend_id
                else:
                    update_mods += dep.depend_id

            # update dependency modules that require it, and determine demo for module
            update_demo = update_mods.state_update(newstate, states_to_update, level=level-1)
            module_demo = module.demo or update_demo or any(mod.demo for mod in ready_mods)
            demo = demo or module_demo

            # check dependencies and update module itself
            self.check_external_dependencies(module.name, newstate)
            if module.state in states_to_update:
                module.write({'state': newstate, 'demo': module_demo})

        return demo
예제 #5
0
    def _buckaroo_form_get_tx_from_data(self, cr, uid, data, context=None):
        """ Given a data dict coming from buckaroo, verify it and find the related
        transaction record. """
        reference, pay_id, shasign = data.get('BRQ_INVOICENUMBER'), data.get('BRQ_PAYMENT'), data.get('BRQ_SIGNATURE')
        if not reference or not pay_id or not shasign:
            error_msg = _('Buckaroo: received data with missing reference (%s) or pay_id (%s) or shasign (%s)') % (reference, pay_id, shasign)
            _logger.info(error_msg)
            raise ValidationError(error_msg)

        tx_ids = self.search(cr, uid, [('reference', '=', reference)], context=context)
        if not tx_ids or len(tx_ids) > 1:
            error_msg = _('Buckaroo: received data for reference %s') % (reference)
            if not tx_ids:
                error_msg += _('; no order found')
            else:
                error_msg += _('; multiple order found')
            _logger.info(error_msg)
            raise ValidationError(error_msg)
        tx = self.pool['payment.transaction'].browse(cr, uid, tx_ids[0], context=context)

        #verify shasign
        shasign_check = self.pool['payment.acquirer']._buckaroo_generate_digital_sign(tx.acquirer_id, 'out' ,data)
        if shasign_check.upper() != shasign.upper():
            error_msg = _('Buckaroo: invalid shasign, received %s, computed %s, for data %s') % (shasign, shasign_check, data)
            _logger.info(error_msg)
            raise ValidationError(error_msg)

        return tx 
예제 #6
0
    def import_zipfile(self, cr, uid, module_file, force=False, context=None):
        if not module_file:
            raise Exception("No file sent.")
        if not zipfile.is_zipfile(module_file):
            raise UserError(_('File is not a zip file!'))

        success = []
        errors = dict()
        module_names = []
        with zipfile.ZipFile(module_file, "r") as z:
            for zf in z.filelist:
                if zf.file_size > MAX_FILE_SIZE:
                    msg = _("File '%s' exceed maximum allowed file size")
                    raise UserError(msg % zf.filename)

            with ecore.tools.osutil.tempdir() as module_dir:
                z.extractall(module_dir)
                dirs = [d for d in os.listdir(module_dir) if os.path.isdir(opj(module_dir, d))]
                for mod_name in dirs:
                    module_names.append(mod_name)
                    try:
                        # assert mod_name.startswith('theme_')
                        path = opj(module_dir, mod_name)
                        self.import_module(cr, uid, mod_name, path, force=force, context=context)
                        success.append(mod_name)
                    except Exception, e:
                        _logger.exception('Error while importing module')
                        errors[mod_name] = exception_to_unicode(e)
예제 #7
0
    def page_search_dependencies(self, cr, uid, view_id, context=None):
        dep = super(Website, self).page_search_dependencies(cr,
                                                            uid,
                                                            view_id,
                                                            context=context)

        post_obj = self.pool.get('blog.post')

        view = self.pool.get('ir.ui.view').browse(cr,
                                                  uid,
                                                  view_id,
                                                  context=context)
        name = view.key.replace("website.", "")
        fullname = "website.%s" % name

        dom = [
            '|', ('content', 'ilike', '/page/%s' % name),
            ('content', 'ilike', '/page/%s' % fullname)
        ]
        posts = post_obj.search(cr, uid, dom, context=context)
        if posts:
            page_key = _('Blog Post')
            dep[page_key] = []
        for p in post_obj.browse(cr, uid, posts, context=context):
            dep[page_key].append({
                'text':
                _('Blog Post <b>%s</b> seems to have a link to this page !' %
                  p.name),
                'link':
                p.website_url
            })

        return dep
예제 #8
0
    def _format_transfer_data(self, cr, uid, context=None):
        company_id = self.pool['res.users'].browse(
            cr, uid, uid, context=context).company_id.id
        # filter only bank accounts marked as visible
        journal_ids = self.pool['account.journal'].search(
            cr,
            uid, [('type', '=', 'bank'), ('display_on_footer', '=', True),
                  ('company_id', '=', company_id)],
            context=context)
        accounts = self.pool['account.journal'].browse(
            cr, uid, journal_ids,
            context=context).mapped('bank_account_id').name_get()
        bank_title = _('Bank Accounts') if len(accounts) > 1 else _(
            'Bank Account')
        bank_accounts = ''.join(
            ['<ul>'] + ['<li>%s</li>' % name
                        for id, name in accounts] + ['</ul>'])
        post_msg = '''<div>
<h3>Please use the following transfer details</h3>
<h4>%(bank_title)s</h4>
%(bank_accounts)s
<h4>Communication</h4>
<p>Please use the order name as communication reference.</p>
</div>''' % {
            'bank_title': bank_title,
            'bank_accounts': bank_accounts,
        }
        return post_msg
예제 #9
0
 def get_tweets(self, limit=20):
     key = request.website.twitter_api_key
     secret = request.website.twitter_api_secret
     screen_name = request.website.twitter_screen_name
     cr, uid = request.cr, request.uid
     debug = request.registry['res.users'].has_group(cr, uid, 'base.group_website_publisher')
     if not key or not secret:
         if debug:
             return {"error": _("Please set the Twitter API Key and Secret in the Website Settings.")}
         return []
     if not screen_name:
         if debug:
             return {"error": _("Please set a Twitter screen name to load favorites from, "
                                "in the Website Settings (it does not have to be yours)")}
         return []
     twitter_tweets = request.registry['website.twitter.tweet']
     tweets = twitter_tweets.search_read(
             cr, uid,
             [('website_id','=', request.website.id),
              ('screen_name','=', screen_name)],
             ['tweet'], limit=int(limit), order="tweet_id desc", context=request.context)
     if len(tweets) < 12:
         if debug:
             return {"error": _("Twitter user @%(username)s has less than 12 favorite tweets. "
                                "Please add more or choose a different screen name.") % \
                                   {'username': screen_name}}
         else:
             return []
     return [json.loads(tweet['tweet']) for tweet in tweets]
예제 #10
0
파일: res_partner.py 프로젝트: LiberTang0/5
    def onchange_parent_id(self, cr, uid, ids, parent_id, context=None):
        def value_or_id(val):
            """ return val or val.id if val is a browse record """
            return val if isinstance(val, (bool, int, long, float,
                                           basestring)) else val.id

        if not parent_id or not ids:
            return {'value': {}}
        if parent_id:
            result = {}
            partner = self.browse(cr, uid, ids[0], context=context)
            if partner.parent_id and partner.parent_id.id != parent_id:
                result['warning'] = {
                    'title':
                    _('Warning'),
                    'message':
                    _('Changing the company of a contact should only be done if it '
                      'was never correctly set. If an existing contact starts working for a new '
                      'company then a new contact should be created under that new '
                      'company. You can use the "Discard" button to abandon this change.'
                      )
                }
            # for contacts: copy the parent address, if set (aka, at least
            # one value is set in the address: otherwise, keep the one from
            # the contact)
            if partner.type == 'contact':
                parent = self.browse(cr, uid, parent_id, context=context)
                address_fields = self._address_fields(cr, uid, context=context)
                if any(parent[key] for key in address_fields):
                    result['value'] = dict((key, value_or_id(parent[key]))
                                           for key in address_fields)
        return result
예제 #11
0
    def get_error_messages(self, cr, uid, ids, context=None):
        res_users = self.pool.get('res.users')
        emails = []
        error_empty = []
        error_emails = []
        error_user = []
        ctx = dict(context or {}, active_test=False)
        for wizard_user in self.browse(cr, SUPERUSER_ID, ids, context):
            if wizard_user.in_portal and not wizard_user.user_id:
                email = extract_email(wizard_user.email)
                if not email:
                    error_empty.append(wizard_user.partner_id)
                elif email in emails and email not in error_emails:
                    error_emails.append(wizard_user.partner_id)
                user = res_users.search(cr, SUPERUSER_ID, [('login', '=', email)], context=ctx)
                if user:
                    error_user.append(wizard_user.partner_id)
                emails.append(email)

        error_msg = []
        if error_empty:
            error_msg.append("%s\n- %s" % (_("Some contacts don't have a valid email: "),
                                '\n- '.join(['%s' % (p.display_name,) for p in error_empty])))
        if error_emails:
            error_msg.append("%s\n- %s" % (_("Several contacts have the same email: "),
                                '\n- '.join([p.email for p in error_emails])))
        if error_user:
            error_msg.append("%s\n- %s" % (_("Some contacts have the same email as an existing portal user:"******"To resolve this error, you can: \n"
                "- Correct the emails of the relevant contacts\n"
                "- Grant access only to contacts with unique emails"))
        return error_msg
예제 #12
0
 def gengo_authentication(self, cr, uid, context=None):
     '''
     This method tries to open a connection with Gengo. For that, it uses the Public and Private
     keys that are linked to the company (given by Gengo on subscription). It returns a tuple with
      * as first element: a boolean depicting if the authentication was a success or not
      * as second element: the connection, if it was a success, or the error message returned by
         Gengo when the connection failed.
         This error message can either be displayed in the server logs (if the authentication was called
         by the cron) or in a dialog box (if requested by the user), thus it's important to return it
         translated.
     '''
     user = self.pool.get('res.users').browse(cr, 1, uid, context=context)
     if not user.company_id.gengo_public_key or not user.company_id.gengo_private_key:
         return (False, _("Gengo `Public Key` or `Private Key` are missing. Enter your Gengo authentication parameters under `Settings > Companies > Gengo Parameters`."))
     try:
         gengo = Gengo(
             public_key=user.company_id.gengo_public_key.encode('ascii'),
             private_key=user.company_id.gengo_private_key.encode('ascii'),
             sandbox=user.company_id.gengo_sandbox,
         )
         gengo.getAccountStats()
         return (True, gengo)
     except Exception, e:
         _logger.exception('Gengo connection failed')
         return (False, _("Gengo connection failed with this message:\n``%s``") % e)
예제 #13
0
    def act_update(self, cr, uid, ids, context=None):
        '''
        Function called by the wizard.
        '''
        if context is None:
            context = {}

        flag, gengo = self.gengo_authentication(cr, uid, context=context)
        if not flag:
            raise UserError(gengo)
        for wizard in self.browse(cr, uid, ids, context=context):
            supported_langs = self.pool.get('ir.translation')._get_all_supported_languages(cr, uid, context=context)
            language = self.pool.get('ir.translation')._get_gengo_corresponding_language(wizard.lang_id.code)
            if language not in supported_langs:
                raise UserError(_('This language is not supported by the Gengo translation services.'))

            ctx = context.copy()
            ctx['gengo_language'] = wizard.lang_id.id
            if wizard.sync_limit > 200 or wizard.sync_limit < 1:
                raise UserError(_('The number of terms to sync should be between 1 to 200 to work with Gengo translation services.'))
            if wizard.sync_type in ['send', 'both']:
                self._sync_request(cr, uid, wizard.sync_limit, context=ctx)
            if wizard.sync_type in ['receive', 'both']:
                self._sync_response(cr, uid, wizard.sync_limit, context=ctx)
        return {'type': 'ir.actions.act_window_close'}
예제 #14
0
 def _get_twitter_exception_message(self, error_code, context=None):
     TWITTER_EXCEPTION = {
         304:
         _('There was no new data to return.'),
         400:
         _('The request was invalid or cannot be otherwise served. Requests without authentication are considered invalid and will yield this response.'
           ),
         401:
         _('Authentication credentials were missing or incorrect. Maybe screen name tweets are protected.'
           ),
         403:
         _('The request is understood, but it has been refused or access is not allowed. Please check your Twitter API Key and Secret.'
           ),
         429:
         _('Request cannot be served due to the applications rate limit having been exhausted for the resource.'
           ),
         500:
         _('Twitter seems broken. Please retry later. You may consider posting an issue on Twitter forums to get help.'
           ),
         502:
         _('Twitter is down or being upgraded.'),
         503:
         _('The Twitter servers are up, but overloaded with requests. Try again later.'
           ),
         504:
         _('The Twitter servers are up, but the request could not be serviced due to some failure within our stack. Try again later.'
           )
     }
     if error_code in TWITTER_EXCEPTION:
         return TWITTER_EXCEPTION[error_code]
     else:
         return _('HTTP Error: Something is misconfigured')
예제 #15
0
    def web_auth_reset_password(self, *args, **kw):
        qcontext = self.get_auth_signup_qcontext()

        if not qcontext.get('token') and not qcontext.get(
                'reset_password_enabled'):
            raise werkzeug.exceptions.NotFound()

        if 'error' not in qcontext and request.httprequest.method == 'POST':
            try:
                if qcontext.get('token'):
                    self.do_signup(qcontext)
                    return super(AuthSignupHome, self).web_login(*args, **kw)
                else:
                    login = qcontext.get('login')
                    assert login, "No login provided."
                    res_users = request.registry.get('res.users')
                    res_users.reset_password(request.cr, ecore.SUPERUSER_ID,
                                             login)
                    qcontext['message'] = _(
                        "An email has been sent with credentials to reset your password"
                    )
            except SignupError:
                qcontext['error'] = _("Could not reset your password")
                _logger.exception('error when resetting password')
            except Exception, e:
                qcontext['error'] = _(e.message)
예제 #16
0
파일: report.py 프로젝트: ecoreos/hz
    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,
        }
예제 #17
0
    def create_slide(self, *args, **post):
        payload = request.httprequest.content_length
        # payload is total request content size so it's not exact size of file.
        # already add client validation this is for double check if client alter.
        if (payload / 1024 / 1024 > 15):
            return {'error': _('File is too big. File size cannot exceed 15MB')}

        values = dict((fname, post[fname]) for fname in [
            'name', 'url', 'tag_ids', 'slide_type', 'channel_id',
            'mime_type', 'datas', 'description', 'image', 'index_content', 'website_published'] if post.get(fname))
        if post.get('category_id'):
            if post['category_id'][0] == 0:
                values['category_id'] = request.env['slide.category'].create({
                    'name': post['category_id'][1]['name'],
                    'channel_id': values.get('channel_id')}).id
            else:
                values['category_id'] = post['category_id'][0]

        # handle exception during creation of slide and sent error notification to the client
        # otherwise client slide create dialog box continue processing even server fail to create a slide.
        try:
            slide_id = request.env['slide.slide'].create(values)
        except (UserError, AccessError) as e:
            _logger.error(e)
            return {'error': e.name}
        except Exception as e:
            _logger.error(e)
            return {'error': _('Internal server error, please try again later or contact administrator.\nHere is the error message: %s' % e.message)}
        return {'url': "/slides/slide/%s" % (slide_id.id)}
예제 #18
0
 def onchange_parent_id(self, cr, uid, ids, parent_id, context=None):
     def value_or_id(val):
         """ return val or val.id if val is a browse record """
         return val if isinstance(val, (bool, int, long, float, basestring)) else val.id
     if not parent_id or not ids:
         return {'value': {}}
     if parent_id:
         result = {}
         partner = self.browse(cr, uid, ids[0], context=context)
         if partner.parent_id and partner.parent_id.id != parent_id:
             result['warning'] = {
                 'title': _('Warning'),
                 'message': _('Changing the company of a contact should only be done if it '
                              'was never correctly set. If an existing contact starts working for a new '
                              'company then a new contact should be created under that new '
                              'company. You can use the "Discard" button to abandon this change.')}
         # for contacts: copy the parent address, if set (aka, at least
         # one value is set in the address: otherwise, keep the one from
         # the contact)
         if partner.type == 'contact':
             parent = self.browse(cr, uid, parent_id, context=context)
             address_fields = self._address_fields(cr, uid, context=context)
             if any(parent[key] for key in address_fields):
                 result['value'] = dict((key, value_or_id(parent[key])) for key in address_fields)
     return result
예제 #19
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',
        }
예제 #20
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,
        }
예제 #21
0
 def button_uninstall(self, cr, uid, ids, context=None):
     if any(m.name == 'base'
            for m in self.browse(cr, uid, ids, context=context)):
         raise UserError(_("The `base` module cannot be uninstalled"))
     dep_ids = self.downstream_dependencies(cr, uid, ids, context=context)
     self.write(cr, uid, ids + dep_ids, {'state': 'to remove'})
     return dict(ACTION_DICT, name=_('Uninstall'))
예제 #22
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
예제 #23
0
    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
예제 #24
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)
예제 #25
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)
예제 #26
0
파일: webkit_report.py 프로젝트: ecoreos/hz
    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'))
예제 #27
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
예제 #28
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
예제 #29
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
예제 #30
0
    def web_login(self, *args, **kw):
        ensure_db()
        if request.httprequest.method == 'GET' and request.session.uid and request.params.get(
                'redirect'):
            # Redirect if already logged in and redirect param is present
            return http.redirect_with_hash(request.params.get('redirect'))
        providers = self.list_providers()

        response = super(OAuthLogin, self).web_login(*args, **kw)
        if response.is_qweb:
            error = request.params.get('oauth_error')
            if error == '1':
                error = _("Sign up is not allowed on this database.")
            elif error == '2':
                error = _("Access Denied")
            elif error == '3':
                error = _(
                    "You do not have access to this database or your invitation has expired. Please ask for an invitation and be sure to follow the link in your invitation email."
                )
            else:
                error = None

            response.qcontext['providers'] = providers
            if error:
                response.qcontext['error'] = error

        return response
예제 #31
0
    def create(self, cr, uid, vals, context=None):
        reference = vals.get('reference', False)
        reference_type = vals.get('reference_type', False)
        if vals.get('type') == 'out_invoice' and not reference_type:
            # fallback on default communication type for partner
            reference_type = self.pool.get('res.partner').browse(cr, uid, vals['partner_id']).out_inv_comm_type
            if reference_type == 'bba':
                reference = self.generate_bbacomm(cr, uid, [], vals['type'], reference_type, vals['partner_id'], '', context={})['value']['reference']
            vals.update({
                'reference_type': reference_type or 'none',
                'reference': reference,
            })

        if reference_type == 'bba':
            if not reference:
                raise UserError(_('Empty BBA Structured Communication!' \
                                    '\nPlease fill in a unique BBA Structured Communication.'))
            if self.check_bbacomm(reference):
                reference = re.sub('\D', '', reference)
                vals['reference'] = '+++' + reference[0:3] + '/' + reference[3:7] + '/' + reference[7:] + '+++'
                same_ids = self.search(cr, uid,
                    [('type', '=', 'out_invoice'), ('reference_type', '=', 'bba'),
                     ('reference', '=', vals['reference'])])
                if same_ids:
                    raise UserError(_('The BBA Structured Communication has already been used!' \
                                        '\nPlease create manually a unique BBA Structured Communication.'))
        return super(account_invoice, self).create(cr, uid, vals, context=context)
예제 #32
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,
        }
예제 #33
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'))
예제 #34
0
    def send_get_mail_body(self, cr, uid, ids, partner=None, context=None):
        """ Short-circuit parent method for mail groups, replace the default
            footer with one appropriate for mailing-lists."""
        # TDE: temporary addition (mail was parameter) due to semi-new-API
        mail = self.browse(cr, uid, ids[0], context=context)

        if mail.model == 'mail.channel' and mail.res_id:
            # no super() call on purpose, no private links that could be quoted!
            channel = self.pool['mail.channel'].browse(cr, uid, mail.res_id, context=context)
            base_url = self.pool['ir.config_parameter'].get_param(cr, uid, 'web.base.url')
            vals = {
                'maillist': _('Mailing-List'),
                'post_to': _('Post to'),
                'unsub': _('Unsubscribe'),
                'mailto': 'mailto:%s@%s' % (channel.alias_name, channel.alias_domain),
                'group_url': '%s/groups/%s' % (base_url, slug(channel)),
                'unsub_url': '%s/groups?unsubscribe' % (base_url,),
            }
            footer = """_______________________________________________
                        %(maillist)s: %(group_url)s
                        %(post_to)s: %(mailto)s
                        %(unsub)s: %(unsub_url)s
                    """ % vals
            body = tools.append_content_to_html(mail.body, footer, container_tag='div')
            return body
        else:
            return super(MailMail, self).send_get_mail_body(cr, uid, ids, partner=partner, context=context)
예제 #35
0
    def onchange_module(self, cr, uid, ids, field_value, module_name, context=None):
        module_pool = self.pool.get('ir.module.module')
        module_ids = module_pool.search(
            cr, SUPERUSER_ID, [('name', '=', module_name.replace("module_", '')),
            ('state','in', ['to install', 'installed', 'to upgrade'])],
            context=context)
        installed_module_ids = module_pool.search(
            cr, SUPERUSER_ID, [('name', '=', module_name.replace("module_", '')),
            ('state', 'in', ['uninstalled'])],
            context=context)

        if module_ids and not field_value:
            dep_ids = module_pool.downstream_dependencies(cr, SUPERUSER_ID, module_ids, context=context)
            dep_name = [x.shortdesc for x  in module_pool.browse(
                cr, SUPERUSER_ID, dep_ids + module_ids, context=context)]
            message = '\n'.join(dep_name)
            return {
                'warning': {
                    'title': _('Warning!'),
                    'message': _('Disabling this option will also uninstall the following modules \n%s') % message,
                }
            }
        if installed_module_ids and field_value:
            dep_ids = module_pool.upstream_dependencies(cr, SUPERUSER_ID, installed_module_ids, context=context)
            dep_name = [x['display_name'] for x in module_pool.search_read(
                cr, SUPERUSER_ID, ['|', ('id', 'in', installed_module_ids), ('id', 'in', dep_ids), ('application', '=', True)], context=context)]
            if dep_name:
                message = ''.join(["- %s \n" % name for name in dep_name])
                return {
                    'warning': {
                        'title': _('Warning!'),
                        'message': _('Enabling this feature will install the following paying application(s) : \n%s') % message,
                    }
                }
        return {}
예제 #36
0
파일: main.py 프로젝트: ecoreos/hz
 def dialog_preview(self, **data):
     Slide = request.env['slide.slide']
     document_type, document_id = Slide._find_document_data_from_url(
         data['url'])
     preview = {}
     if not document_id:
         preview['error'] = _(
             'Please enter valid youtube or google doc url')
         return preview
     existing_slide = Slide.search(
         [('channel_id', '=', int(data['channel_id'])),
          ('document_id', '=', document_id)],
         limit=1)
     if existing_slide:
         preview['error'] = _(
             'This video already exists in this channel <a target="_blank" href="/slides/slide/%s">click here to view it </a>'
             % existing_slide.id)
         return preview
     values = Slide._parse_document_url(data['url'],
                                        only_preview_fields=True)
     if values.get('error'):
         preview['error'] = _(
             'Could not fetch data from url. Document or access right not available.\nHere is the received response: %s'
             % values['error'])
         return preview
     return values
예제 #37
0
    def button_upgrade(self, cr, uid, ids, context=None):
        depobj = self.pool.get('ir.module.module.dependency')
        todo = list(self.browse(cr, uid, ids, context=context))
        self.update_list(cr, uid)

        i = 0
        while i < len(todo):
            mod = todo[i]
            i += 1
            if mod.state not in ('installed', 'to upgrade'):
                raise UserError(_("Can not upgrade module '%s'. It is not installed.") % (mod.name,))
            self.check_external_dependencies(mod.name, 'to upgrade')
            iids = depobj.search(cr, uid, [('name', '=', mod.name)], context=context)
            for dep in depobj.browse(cr, uid, iids, context=context):
                if dep.module_id.state == 'installed' and dep.module_id not in todo:
                    todo.append(dep.module_id)

        ids = map(lambda x: x.id, todo)
        self.write(cr, uid, ids, {'state': 'to upgrade'}, context=context)

        to_install = []
        for mod in todo:
            for dep in mod.dependencies_id:
                if dep.state == 'unknown':
                    raise UserError(_('You try to upgrade a module that depends on the module: %s.\nBut this module is not available in your system.') % (dep.name,))
                if dep.state == 'uninstalled':
                    ids2 = self.search(cr, uid, [('name', '=', dep.name)])
                    to_install.extend(ids2)

        self.button_install(cr, uid, to_install, context=context)
        return dict(ACTION_DICT, name=_('Apply Schedule Upgrade'))
예제 #38
0
 def onchange_uom(self,
                  cr,
                  uid,
                  ids,
                  product_id,
                  product_uom,
                  context=None):
     res = {'value': {}}
     if not product_uom or not product_id:
         return res
     product = self.pool.get('product.product').browse(cr,
                                                       uid,
                                                       product_id,
                                                       context=context)
     uom = self.pool.get('product.uom').browse(cr,
                                               uid,
                                               product_uom,
                                               context=context)
     if uom.category_id.id != product.uom_id.category_id.id:
         res['warning'] = {
             'title':
             _('Warning'),
             'message':
             _('The Product Unit of Measure you chose has a different category than in the product form.'
               )
         }
         res['value'].update({'product_uom': product.uom_id.id})
     return res
예제 #39
0
    def _get_accounting_data_for_valuation(self, cr, uid, move, context=None):
        """
        Return the accounts and journal to use to post Journal Entries for the real-time
        valuation of the quant.

        :param context: context dictionary that can explicitly mention the company to consider via the 'force_company' key
        :returns: journal_id, source account, destination account, valuation account
        :raise: osv.except_osv() is any mandatory account or journal is not defined.
        """
        product_obj = self.pool.get('product.template')
        accounts = product_obj.browse(cr, uid, move.product_id.product_tmpl_id.id, context).get_product_accounts()
        if move.location_id.valuation_out_account_id:
            acc_src = move.location_id.valuation_out_account_id.id
        else:
            acc_src = accounts['stock_input'].id

        if move.location_dest_id.valuation_in_account_id:
            acc_dest = move.location_dest_id.valuation_in_account_id.id
        else:
            acc_dest = accounts['stock_output'].id

        acc_valuation = accounts.get('stock_valuation', False)
        if acc_valuation:
            acc_valuation = acc_valuation.id
        if not accounts.get('stock_journal', False):
            raise UserError(_('You don\'t have any stock journal defined on your product category, check if you have installed a chart of accounts'))
        if not acc_src:
            raise UserError(_('Cannot find a stock input account for the product %s. You must define one on the product category, or on the location, before processing this operation.') % (move.product_id.name))
        if not acc_dest:
            raise UserError(_('Cannot find a stock output account for the product %s. You must define one on the product category, or on the location, before processing this operation.') % (move.product_id.name))
        if not acc_valuation:
            raise UserError(_('You don\'t have any stock valuation account defined on your product category. You must define one before processing this operation.'))
        journal_id = accounts['stock_journal'].id
        return journal_id, acc_src, acc_dest, acc_valuation
예제 #40
0
파일: date_range.py 프로젝트: ecoreos/hz
    def _validate_range(self):
        for this in self:
            start = fields.Date.from_string(this.date_start)
            end = fields.Date.from_string(this.date_end)
            if start >= end:
                raise ValidationError(
                    _("%s is not a valid range (%s >= %s)") %
                    (this.name, this.date_start, this.date_end))
            if this.type_id.allow_overlap:
                continue

            SQL = """
                SELECT
                    id
                FROM
                    date_range dt
                WHERE
                    DATERANGE(dt.date_start, dt.date_end, '[]') &&
                        DATERANGE(%s::date, %s::date, '[]')
                    AND dt.id != %s
                    AND dt.active
                    AND dt.company_id = %s
                    AND dt.type_id=%s;"""
            self.env.cr.execute(SQL,
                                (this.date_start, this.date_end, this.id,
                                 this.company_id.id or None, this.type_id.id))
            res = self.env.cr.fetchall()
            if res:
                dt = self.browse(res[0][0])
                raise ValidationError(
                    _("%s overlaps %s") % (this.name, dt.name))
예제 #41
0
 def _get_errors(self, cr, uid, order, context=None):
     errors = super(SaleOrder, self)._get_errors(cr, uid, order, context=context)
     if not self._get_delivery_methods(cr, uid, order, context=context):
         errors.append(
             (_('Sorry, we are unable to ship your order'),
              _('No shipping method is available for your current order and shipping address. '
                'Please contact us for more information.')))
     return errors
예제 #42
0
파일: res_users.py 프로젝트: LiberTang0/5
 def copy(self, cr, uid, id, default=None, context=None):
     user2copy = self.read(cr, uid, [id], ['login','name'])[0]
     default = dict(default or {})
     if ('name' not in default) and ('partner_id' not in default):
         default['name'] = _("%s (copy)") % user2copy['name']
     if 'login' not in default:
         default['login'] = _("%s (copy)") % user2copy['login']
     return super(res_users, self).copy(cr, uid, id, default, context)
예제 #43
0
    def generate_eu_service(self):
        tax_rate = self.env["l10n_eu_service.service_tax_rate"]
        account_tax = self.env['account.tax']
        fpos = self.env['account.fiscal.position']
        for country in self.todo_country_ids:
            format_params = {'country_name': country.name}
            tax_name = _(
                "VAT for EU Services to %(country_name)s") % format_params
            #create a new tax based on the selected service tax
            data_tax = {
                'name':
                tax_name,
                'amount':
                tax_rate.search([('country_id', '=', country.id)]).rate,
                'account_id':
                self.account_collected_id.id or self.tax_id.account_id.id,
                'refund_account_id':
                self.account_collected_id.id
                or self.tax_id.refund_account_id.id,
                'type_tax_use':
                'sale',
                'description':
                "EU-VAT-%s-S" % country.code,
                'sequence':
                1000,
            }
            tax = account_tax.create(data_tax)
            if self.fiscal_position_id:
                account_ids = [(6, 0, self.fiscal_position_id.account_ids.ids)]
            else:
                account_ids = False
            #create a fiscal position for the country
            fiscal_pos_name = _("Intra-EU B2C in %(country_name)s") % {
                'country_name': country.name
            }
            fiscal_pos_name += " (EU-VAT-%s)" % country.code
            data_fiscal = {
                'name':
                fiscal_pos_name,
                'company_id':
                self.company_id.id,
                'vat_required':
                False,
                'auto_apply':
                True,
                'country_id':
                country.id,
                'account_ids':
                account_ids,
                'tax_ids': [(0, 0, {
                    'tax_src_id': self.tax_id.id,
                    'tax_dest_id': tax.id
                })],
            }
            fpos.create(data_fiscal)

        return {'type': 'ir.actions.act_window_close'}
예제 #44
0
 def on_change_encryption(self, cr, uid, ids, smtp_encryption):
     if smtp_encryption == 'ssl':
         result = {'value': {'smtp_port': 465}}
         if not 'SMTP_SSL' in smtplib.__all__:
             result['warning'] = {'title': _('Warning'),
                                  'message': _('Your server does not seem to support SSL, you may want to try STARTTLS instead')}
     else:
         result = {'value': {'smtp_port': 25}}
     return result
예제 #45
0
    def page_search_dependencies(self, cr, uid, view_id=False, context=None):
        dep = {}
        if not view_id:
            return dep

        # search dependencies just for information.
        # It will not catch 100% of dependencies and False positive is more than possible
        # Each module could add dependences in this dict
        if context is None:
            context = {}
        View = self.pool.get('ir.ui.view')
        Menu = self.pool.get('website.menu')

        view = View.browse(cr, uid, view_id, context=context)
        website_id = context.get('website_id')
        name = view.key.replace("website.", "")
        fullname = "website.%s" % name

        if view.page:
            # search for page with link
            page_search_dom = [
                '|', ('website_id', '=', website_id), ('website_id', '=', False),
                '|', ('arch_db', 'ilike', '/page/%s' % name), ('arch_db', 'ilike', '/page/%s' % fullname)
            ]
            pages = View.search(cr, uid, page_search_dom, context=context)
            if pages:
                page_key = _('Page')
                dep[page_key] = []
            for page in View.browse(cr, uid, pages, context=context):
                if page.page:
                    dep[page_key].append({
                        'text': _('Page <b>%s</b> seems to have a link to this page !' % page.key),
                        'link': '/page/%s' % page.key
                    })
                else:
                    dep[page_key].append({
                        'text': _('Template <b>%s (id:%s)</b> seems to have a link to this page !' % (page.key, page.id)),
                        'link': '#'
                    })

            # search for menu with link
            menu_search_dom = [
                '|', ('website_id', '=', website_id), ('website_id', '=', False),
                '|', ('url', 'ilike', '/page/%s' % name), ('url', 'ilike', '/page/%s' % fullname)
            ]

            menus = Menu.search(cr, uid, menu_search_dom, context=context)
            if menus:
                menu_key = _('Menu')
                dep[menu_key] = []
            for menu in Menu.browse(cr, uid, menus, context=context):
                dep[menu_key].append({
                    'text': _('Menu <b>%s</b> seems to have a link to this page !' % menu.name),
                    'link': False
                })

        return dep
예제 #46
0
    def button_install(self):
        # domain to select auto-installable (but not yet installed) modules
        auto_domain = [('state', '=', 'uninstalled'),
                       ('auto_install', '=', True)]

        # determine whether an auto-install module must be installed:
        #  - all its dependencies are installed or to be installed,
        #  - at least one dependency is 'to install'
        install_states = frozenset(('installed', 'to install', 'to upgrade'))

        def must_install(module):
            states = set(dep.state for dep in module.dependencies_id)
            return states <= install_states and 'to install' in states

        modules = self
        while modules:
            # Mark the given modules and their dependencies to be installed.
            modules.state_update('to install', ['uninstalled'])

            # Determine which auto-installable modules must be installed.
            modules = self.search(auto_domain).filtered(must_install)

        # retrieve the installed (or to be installed) theme modules
        theme_category = self.env.ref('base.module_category_theme')
        theme_modules = self.search([
            ('state', 'in', list(install_states)),
            ('category_id', 'child_of', [theme_category.id]),
        ])

        # determine all theme modules that mods depends on, including mods
        def theme_deps(mods):
            deps = mods.mapped('dependencies_id.depend_id')
            while deps:
                mods |= deps
                deps = deps.mapped('dependencies_id.depend_id')
            return mods & theme_modules

        if any(module.state == 'to install' for module in theme_modules):
            # check: the installation is valid if all installed theme modules
            # correspond to one theme module and all its theme dependencies
            if not any(
                    theme_deps(module) == theme_modules
                    for module in theme_modules):
                state_labels = dict(
                    self.fields_get(['state'])['state']['selection'])
                themes_list = [
                    "- %s (%s)" %
                    (module.shortdesc, state_labels[module.state])
                    for module in theme_modules
                ]
                raise UserError(_(
                    "You are trying to install incompatible themes:\n%s\n\n" \
                    "Please uninstall your current theme before installing another one.\n"
                    "Warning: switching themes may significantly alter the look of your current website pages!"
                ) % ("\n".join(themes_list)))

        return dict(ACTION_DICT, name=_('Install'))
예제 #47
0
 def onchange_tracking(self, cr, uid, ids, tracking, context=None):
     if not tracking or tracking == 'none':
         return {}
     unassigned_quants = self.pool['stock.quant'].search_count(cr, uid, [('product_id','in', ids), ('lot_id','=', False), ('location_id.usage','=', 'internal')], context=context)
     if unassigned_quants:
         return {'warning' : {
                 'title': _('Warning!'),
                 'message' : _("You have products in stock that have no lot number.  You can assign serial numbers by doing an inventory.  ")
         }}
     return {}
예제 #48
0
 def onchange_product_uom(self, cr, uid, ids, product_id, product_uom, context=None):
     res = {'value': {}}
     if not product_uom or not product_id:
         return res
     product = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
     uom = self.pool.get('product.uom').browse(cr, uid, product_uom, context=context)
     if uom.category_id.id != product.uom_id.category_id.id:
         res['warning'] = {'title': _('Warning'), 'message': _('The Product Unit of Measure you chose has a different category than in the product form.')}
         res['value'].update({'product_uom': product.uom_id.id})
     return res
예제 #49
0
 def _get_new_menu_pages(self):
     result = super(event_event, self)._get_new_menu_pages()[0]  # TDE CHECK api.one -> returns a list with one item ?
     if self.show_tracks:
         result.append((_('Talks'), '/event/%s/track' % slug(self)))
         result.append((_('Agenda'), '/event/%s/agenda' % slug(self)))
     if self.blog_id:
         result.append((_('News'), '/blogpost'+slug(self.blog_ig)))
     if self.show_track_proposal:
         result.append((_('Talk Proposals'), '/event/%s/track_proposal' % slug(self)))
     return result
예제 #50
0
    def generate_po(self, cr, uid, ids, context=None):
        """
        Generate all purchase order based on selected lines, should only be called on one tender at a time
        """
        po = self.pool.get('purchase.order')
        poline = self.pool.get('purchase.order.line')
        id_per_supplier = {}
        for tender in self.browse(cr, uid, ids, context=context):
            if tender.state == 'done':
                raise UserError(_('You have already generate the purchase order(s).'))

            confirm = False
            #check that we have at least confirm one line
            for po_line in tender.po_line_ids:
                if po_line.quantity_tendered > 0:
                    confirm = True
                    break
            if not confirm:
                raise UserError(_('You have no line selected for buying.'))

            #check for complete RFQ
            for quotation in tender.purchase_ids:
                if (self.check_valid_quotation(cr, uid, quotation, context=context)):
                    #Set PO state to confirm
                    po.button_confirm(cr, uid, [quotation.id], context=context)

            #get other confirmed lines per supplier
            for po_line in tender.po_line_ids:
                #only take into account confirmed line that does not belong to already confirmed purchase order
                if po_line.quantity_tendered > 0 and po_line.order_id.state in ['draft', 'sent', 'to approve']:
                    if id_per_supplier.get(po_line.partner_id.id):
                        id_per_supplier[po_line.partner_id.id].append(po_line)
                    else:
                        id_per_supplier[po_line.partner_id.id] = [po_line]

            #generate po based on supplier and cancel all previous RFQ
            ctx = dict(context or {}, force_requisition_id=True)
            for supplier, product_line in id_per_supplier.items():
                #copy a quotation for this supplier and change order_line then validate it
                quotation_id = po.search(cr, uid, [('requisition_id', '=', tender.id), ('partner_id', '=', supplier)], limit=1)[0]
                vals = self._prepare_po_from_tender(cr, uid, tender, context=context)
                new_po = po.copy(cr, uid, quotation_id, default=vals, context=context)
                #duplicate po_line and change product_qty if needed and associate them to newly created PO
                for line in product_line:
                    vals = self._prepare_po_line_from_tender(cr, uid, tender, line, new_po, context=context)
                    poline.copy(cr, uid, line.id, default=vals, context=context)
                #use workflow to set new PO state to confirm
                po.button_confirm(cr, uid, [new_po], context=context)

            #cancel other orders
            self.cancel_unconfirmed_quotations(cr, uid, tender, context=context)

            #set tender to state done
            self.signal_workflow(cr, uid, [tender.id], 'done')
        return True
예제 #51
0
    def _merge(self, cr, uid, partner_ids, dst_partner=None, context=None):
        proxy = self.pool.get('res.partner')

        partner_ids = proxy.exists(cr, uid, list(partner_ids), context=context)
        if len(partner_ids) < 2:
            return

        if len(partner_ids) > 3:
            raise UserError(
                _("For safety reasons, you cannot merge more than 3 contacts together. You can re-open the wizard several times if needed."
                  ))

        if ecore.SUPERUSER_ID != uid and len(
                set(partner.email for partner in proxy.browse(
                    cr, uid, partner_ids, context=context))) > 1:
            raise UserError(
                _("All contacts must have the same email. Only the Administrator can merge contacts with different emails."
                  ))

        if dst_partner and dst_partner.id in partner_ids:
            src_partners = proxy.browse(
                cr,
                uid, [id for id in partner_ids if id != dst_partner.id],
                context=context)
        else:
            ordered_partners = self._get_ordered_partner(
                cr, uid, partner_ids, context)
            dst_partner = ordered_partners[-1]
            src_partners = ordered_partners[:-1]
        _logger.info("dst_partner: %s", dst_partner.id)

        if ecore.SUPERUSER_ID != uid and self._model_is_installed(cr, uid, 'account.move.line', context=context) and \
                self.pool.get('account.move.line').search(cr, ecore.SUPERUSER_ID, [('partner_id', 'in', [partner.id for partner in src_partners])], context=context):
            raise UserError(
                _("Only the destination contact may be linked to existing Journal Items. Please ask the Administrator if you need to merge several contacts linked to existing Journal Items."
                  ))

        call_it = lambda function: function(
            cr, uid, src_partners, dst_partner, context=context)

        call_it(self._update_foreign_keys)
        call_it(self._update_reference_fields)
        call_it(self._update_values)

        _logger.info('(uid = %s) merged the partners %r with %s', uid,
                     list(map(operator.attrgetter('id'), src_partners)),
                     dst_partner.id)
        dst_partner.message_post(body='%s %s' %
                                 (_("Merged with the following partners:"),
                                  ", ".join('%s<%s>(ID %s)' %
                                            (p.name, p.email or 'n/a', p.id)
                                            for p in src_partners)))

        for partner in src_partners:
            partner.unlink()
예제 #52
0
 def _get_errors(self, cr, uid, order, context=None):
     errors = super(SaleOrder, self)._get_errors(cr,
                                                 uid,
                                                 order,
                                                 context=context)
     if not self._get_delivery_methods(cr, uid, order, context=context):
         errors.append((
             _('Sorry, we are unable to ship your order'),
             _('No shipping method is available for your current order and shipping address. '
               'Please contact us for more information.')))
     return errors
예제 #53
0
 def _get_new_menu_pages(self):
     result = super(event_event, self)._get_new_menu_pages()[
         0]  # TDE CHECK api.one -> returns a list with one item ?
     if self.show_tracks:
         result.append((_('Talks'), '/event/%s/track' % slug(self)))
         result.append((_('Agenda'), '/event/%s/agenda' % slug(self)))
     if self.blog_id:
         result.append((_('News'), '/blogpost' + slug(self.blog_ig)))
     if self.show_track_proposal:
         result.append(
             (_('Talk Proposals'), '/event/%s/track_proposal' % slug(self)))
     return result
예제 #54
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