Beispiel #1
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
Beispiel #2
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)
Beispiel #3
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
Beispiel #4
0
    def product_id_change(self, cr, uid, ids, pricelist, product, uom=False,
                          product_uom_qty=0, partner_id=False, guarantee_limit=False, context=None):
        """ On change of product it sets product quantity, tax account, name,
        uom of product, unit price and price subtotal.
        @param pricelist: Pricelist of current record.
        @param product: Changed id of product.
        @param uom: UoM of current record.
        @param product_uom_qty: Quantity of current record.
        @param partner_id: Partner of current record.
        @param guarantee_limit: Guarantee limit of current record.
        @return: Dictionary of values and warning message.
        """
        result = {}
        warning = {}
        ctx = context and context.copy() or {}
        ctx['uom'] = uom

        if not product_uom_qty:
            product_uom_qty = 1
        result['product_uom_qty'] = product_uom_qty

        if product:
            product_obj = self.pool.get('product.product').browse(cr, uid, product, context=ctx)
            if partner_id:
                partner = self.pool.get('res.partner').browse(cr, uid, partner_id)
                result['tax_id'] = self.pool.get('account.fiscal.position').map_tax(cr, uid, partner.property_account_position_id, product_obj.taxes_id, context=ctx)

            result['name'] = product_obj.display_name
            result['product_uom'] = product_obj.uom_id and product_obj.uom_id.id or False
            if not pricelist:
                warning = {
                    'title': _('No Pricelist!'),
                    'message':
                        _('You have to select a pricelist in the Repair form !\n'
                        'Please set one before choosing a product.')
                }
            else:
                price = self.pool.get('product.pricelist').price_get(cr, uid, [pricelist],
                            product, product_uom_qty, partner_id, context=ctx)[pricelist]

                if price is False:
                    warning = {
                        'title': _('No valid pricelist line found !'),
                        'message':
                            _("Couldn't find a pricelist line matching this product and quantity.\n"
                            "You have to change either the product, the quantity or the pricelist.")
                     }
                else:
                    result.update({'price_unit': price, 'price_subtotal': price * product_uom_qty})

        return {'value': result, 'warning': warning}
Beispiel #5
0
    def do_change_standard_price(self, cr, uid, ids, new_price, context=None):
        """ Changes the Standard Price of Product and creates an account move accordingly."""
        location_obj = self.pool.get('stock.location')
        move_obj = self.pool.get('account.move')
        if context is None:
            context = {}
        user_company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id
        loc_ids = location_obj.search(cr, uid, [('usage', '=', 'internal'), ('company_id', '=', user_company_id)])
        for rec_id in ids:
            datas = self.get_product_accounts(cr, uid, rec_id, context=context)
            for location in location_obj.browse(cr, uid, loc_ids, context=context):
                c = context.copy()
                c.update({'location': location.id, 'compute_child': False})
                product = self.browse(cr, uid, rec_id, context=c)

                diff = product.standard_price - new_price
                if not diff:
                    raise UserError(_("No difference between standard price and new price!"))
                for prod_variant in product.product_variant_ids:
                    qty = prod_variant.qty_available
                    if qty:
                        # Accounting Entries
                        amount_diff = abs(diff * qty)
                        if diff * qty > 0:
                            debit_account_id = datas['expense'].id
                            credit_account_id = datas['stock_valuation'].id
                        else:
                            debit_account_id = datas['stock_valuation'].id
                            credit_account_id = datas['expense'].id

                        lines = [(0, 0, {'name': _('Standard Price changed'),
                                        'account_id': debit_account_id,
                                        'debit': amount_diff,
                                        'credit': 0,
                                        }),
                                 (0, 0, {
                                        'name': _('Standard Price changed'),
                                        'account_id': credit_account_id,
                                        'debit': 0,
                                        'credit': amount_diff,
                                        })]
                        move_vals = {
                            'journal_id': datas['stock_journal'].id,
                            'company_id': location.company_id.id,
                            'line_ids': lines,
                        }
                        move_id = move_obj.create(cr, uid, move_vals, context=context)
                        move_obj.post(cr, uid, [move_id], context=context)
            self.write(cr, uid, rec_id, {'standard_price': new_price})
        return True
Beispiel #6
0
    def check_operation(self, cr, uid, vals):
        """ Finds which operation is called ie. start, pause, done, cancel.
        @param vals: Dictionary of values.
        @return: True or False
        """
        code_ids = self.pool.get('mrp_operations.operation.code').search(
            cr, uid, [('id', '=', vals['code_id'])])
        code = self.pool.get('mrp_operations.operation.code').browse(
            cr, uid, code_ids)[0]
        code_lst = []
        oper_ids = self.search(cr, uid,
                               [('production_id', '=', vals['production_id']),
                                ('workcenter_id', '=', vals['workcenter_id'])])
        oper_objs = self.browse(cr, uid, oper_ids)

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

            if code.start_stop == 'done':
                if code_lst[len(code_lst) - 1] != 'start' and code_lst[
                        len(code_lst) - 1] != 'resume':
                    raise UserError(
                        _('In order to Finish the operation, it must be in the Start or Resume state!'
                          ))
                    return False
                if 'cancel' in code_lst:
                    raise UserError(_('Operation is Already Cancelled!'))
                    return False
            if code.start_stop == 'cancel':
                if not 'start' in code_lst:
                    raise UserError(_('No operation to cancel.'))
                    return False
                if 'done' in code_lst:
                    raise UserError(_('Operation is already finished!'))
                    return False
        return True
Beispiel #7
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
Beispiel #8
0
 def _check_for_publication(self, cr, uid, ids, vals, context=None):
     if vals.get('website_published'):
         base_url = self.pool['ir.config_parameter'].get_param(cr, uid, 'web.base.url')
         for post in self.browse(cr, uid, ids, context=context):
             post.blog_id.message_post(
                 body='<p>%(post_publication)s <a href="%(base_url)s/blog/%(blog_slug)s/post/%(post_slug)s">%(post_link)s</a></p>' % {
                     'post_publication': _('A new post %s has been published on the %s blog.') % (post.name, post.blog_id.name),
                     'post_link': _('Click here to access the post.'),
                     'base_url': base_url,
                     'blog_slug': slug(post.blog_id),
                     'post_slug': slug(post),
                 },
                 subtype='website_blog.mt_blog_blog_published')
         return True
     return False
Beispiel #9
0
 def onchange_costing_method(self):
     if self.group_costing_method == 0:
         return {
             'warning': {
                 'title':
                 _('Warning!'),
                 'message':
                 _('Disabling the costing methods will prevent you to use the landed costs feature.'
                   ),
             },
             'value': {
                 'group_costing_method': 1
             }
         }
     return {}
Beispiel #10
0
 def attachment_tree_view(self, cr, uid, ids, context):
     domain = [
         '&', ('res_model', '=', 'hr.employee'), ('res_id', 'in', ids)
     ]
     res_id = ids and ids[0] or False
     return {
         'name':
         _('Attachments'),
         'domain':
         domain,
         'res_model':
         'ir.attachment',
         'type':
         'ir.actions.act_window',
         'view_id':
         False,
         'view_mode':
         'kanban,tree,form',
         'view_type':
         'form',
         'limit':
         80,
         'context':
         "{'default_res_model': '%s','default_res_id': %d}" %
         (self._name, res_id)
     }
Beispiel #11
0
    def write(self, cr, uid, ids, vals, context=None):
        """Overwrite the write method to update the last_update field to today

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

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

                if goal.challenge_id and goal.challenge_id.report_message_frequency == 'onchange':
                    self.pool.get('gamification.challenge').report_progress(
                        cr,
                        SUPERUSER_ID,
                        goal.challenge_id,
                        users=[goal.user_id],
                        context=context)
        return result
Beispiel #12
0
    def onchange_partner_id(self, cr, uid, ids, partner_id=None, context=None):
        if not partner_id:
            return {}
        partner = self.pool.get('res.partner').browse(cr,
                                                      uid,
                                                      partner_id,
                                                      context=context)
        warning = {}
        title = False
        message = False

        # If partner has no warning, check its company
        if partner.picking_warn == 'no-message' and partner.parent_id:
            partner = partner.parent_id

        if partner.picking_warn != 'no-message':
            # Block if partner only has warning but parent company is blocked
            if partner.picking_warn != 'block' and partner.parent_id and partner.parent_id.picking_warn == 'block':
                partner = partner.parent_id
            title = _("Warning for %s") % partner.name
            message = partner.picking_warn_msg
            warning = {'title': title, 'message': message}
            if partner.picking_warn == 'block':
                return {'value': {'partner_id': False}, 'warning': warning}

        result = {'value': {}}

        if warning:
            result['warning'] = warning
        return result
Beispiel #13
0
 def create_returns(self, cr, uid, ids, context=None):
     """
      Creates return picking and returns act_window to new picking
     """
     new_picking_id, pick_type_id = self._create_returns(cr,
                                                         uid,
                                                         ids,
                                                         context=context)
     # Override the context to disable all the potential filters that could have been set previously
     ctx = context.copy()
     ctx.update({
         'search_default_picking_type_id': pick_type_id,
         'search_default_draft': False,
         'search_default_assigned': False,
         'search_default_confirmed': False,
         'search_default_ready': False,
         'search_default_late': False,
         'search_default_available': False,
     })
     return {
         'name': _('Returned Picking'),
         'view_type': 'form',
         'view_mode': 'form,tree,calendar',
         'res_model': 'stock.picking',
         'res_id': new_picking_id,
         'type': 'ir.actions.act_window',
         'context': ctx,
     }
Beispiel #14
0
 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
Beispiel #15
0
    def _truncate_node(node, position, simplify_whitespaces=True):
        """ Truncate a node text at a given position. This algorithm will shorten
        at the end of the word whose ending character exceeds position.

            :param bool simplify_whitespaces: whether to try to count all successive
                                              whitespaces as one character. This
                                              option should not be True when trying
                                              to keep 'pre' consistency.
        """
        if node.text is None:
            node.text = ''

        truncate_idx = -1
        if simplify_whitespaces:
            cur_char_nbr = 0
            word = None
            node_words = node.text.strip(' \t\r\n').split()
            for word in node_words:
                cur_char_nbr += len(word)
                if cur_char_nbr >= position:
                    break
            if word:
                truncate_idx = node.text.find(word) + len(word)
        else:
            truncate_idx = position
        if truncate_idx == -1 or truncate_idx > len(node.text):
            truncate_idx = len(node.text)

        # compose new text bits
        innertext = node.text[0:truncate_idx]
        outertext = node.text[truncate_idx:]
        node.text = innertext

        # create <span> ... <a href="#">read more</a></span> node
        read_more_node = _create_node(
            expand_options.get('oe_expand_container_tag', 'span'),
            expand_options.get('oe_expand_container_content', ' ... '), None, {
                'class':
                expand_options.get('oe_expand_container_class',
                                   'oe_mail_expand')
            })
        if expand_options.get('oe_expand_separator_node'):
            read_more_separator_node = _create_node(
                expand_options.get('oe_expand_separator_node'), '', None, {})
            read_more_node.append(read_more_separator_node)
        read_more_link_node = _create_node(
            'a', expand_options.get('oe_expand_a_content', _('read more')),
            None, {
                'href': expand_options.get('oe_expand_a_href', '#'),
                'class': expand_options.get('oe_expand_a_class',
                                            'oe_mail_expand'),
            })
        read_more_node.append(read_more_link_node)
        # create outertext node
        overtext_node = _create_node('span', outertext)
        # tag node
        overtext_node.set('in_overlength', '1')
        # add newly created nodes in dom
        node.append(read_more_node)
        node.append(overtext_node)
    def open_timesheet(self, cr, uid, ids, context=None):
        ts = self.pool.get('hr_timesheet_sheet.sheet')
        if context is None:
            context = {}
        view_type = 'form,tree'

        ids = ts.search(cr,
                        uid, [('user_id', '=', uid),
                              ('state', 'in', ('draft', 'new')),
                              ('date_from', '<=', time.strftime('%Y-%m-%d')),
                              ('date_to', '>=', time.strftime('%Y-%m-%d'))],
                        context=context)

        if len(ids) > 1:
            view_type = 'tree,form'
            domain = "[('id','in',[" + ','.join(map(
                str, ids)) + "]),('user_id', '=', uid)]"
        elif len(ids) == 1:
            domain = "[('user_id', '=', uid)]"
        else:
            domain = "[('user_id', '=', uid)]"
        value = {
            'domain': domain,
            'name': _('Open Timesheet'),
            'view_type': 'form',
            'view_mode': view_type,
            'res_model': 'hr_timesheet_sheet.sheet',
            'view_id': False,
            'type': 'ir.actions.act_window'
        }
        if len(ids) == 1:
            value['res_id'] = ids[0]
        return value
Beispiel #17
0
    def onchange_partner_id_warning(self):
        if not self.partner_id:
            return
        warning = {}
        title = False
        message = False
        partner = self.partner_id

        # If partner has no warning, check its company
        if partner.sale_warn == 'no-message' and partner.parent_id:
            partner = partner.parent_id

        if partner.sale_warn != 'no-message':
            # Block if partner only has warning but parent company is blocked
            if partner.sale_warn != 'block' and partner.parent_id and partner.parent_id.sale_warn == 'block':
                partner = partner.parent_id
            title = _("Warning for %s") % partner.name
            message = partner.sale_warn_msg
            warning = {
                'title': title,
                'message': message,
            }
            if self.partner_id.sale_warn == 'block':
                self.update({
                    'partner_id': False,
                    'partner_invoice_id': False,
                    'partner_shipping_id': False,
                    'pricelist_id': False
                })
                return {'warning': warning}

        if warning:
            return {'warning': warning}
def get_pre_auth_code(suite_id, suite_access_token):
    category_url = "https://qyapi.weixin.qq.com/cgi-bin/service/get_pre_auth_code?suite_access_token=" + suite_access_token
    category_data = {
        "suite_id": suite_id
    }
    req = urllib2.Request(category_url, json.dumps(category_data, ensure_ascii=False).encode('utf8'))
    req.add_header("Content-Type", "application/json")
    response = urllib2.urlopen(req)
    html = response.read().decode("utf-8")
    logger.debug('html:' + html)
    tokeninfo = json.loads(html)
    print tokeninfo
    if tokeninfo["errcode"] == 0:
        return tokeninfo['pre_auth_code']
    else:
        raise osv.except_osv(_('Error!'), _('获取pre_auth_code出错'))
Beispiel #19
0
    def onchange_partner_id_warning(self):
        if not self.partner_id:
            return
        result = {}
        warning = {}
        title = False
        message = False

        partner = self.partner_id

        # If partner has no warning, check its company
        if partner.purchase_warn == 'no-message' and partner.parent_id:
            partner = partner.parent_id

        if partner.purchase_warn != 'no-message':
            # Block if partner only has warning but parent company is blocked
            if partner.purchase_warn != 'block' and partner.parent_id and partner.parent_id.purchase_warn == 'block':
                partner = partner.parent_id
            title = _("Warning for %s") % partner.name
            message = partner.purchase_warn_msg
            warning = {'title': title, 'message': message}
            if partner.purchase_warn == 'block':
                self.update({'partner_id': False})
                return {'warning': warning}

        if warning:
            result['warning'] = warning
        return result
Beispiel #20
0
    def get_google_drive_url(self,
                             cr,
                             uid,
                             config_id,
                             res_id,
                             template_id,
                             context=None):
        config = self.browse(cr, SUPERUSER_ID, config_id, context=context)
        model = config.model_id
        filter_name = config.filter_id and config.filter_id.name or False
        record = self.pool.get(model.model).read(cr,
                                                 uid, [res_id],
                                                 context=context)[0]
        record.update({'model': model.name, 'filter': filter_name})
        name_gdocs = config.name_template
        try:
            name_gdocs = name_gdocs % record
        except:
            raise UserError(
                _("At least one key cannot be found in your Google Drive name pattern"
                  ))

        attach_pool = self.pool.get("ir.attachment")
        attach_ids = attach_pool.search(cr, uid,
                                        [('res_model', '=', model.model),
                                         ('name', '=', name_gdocs),
                                         ('res_id', '=', res_id)])
        url = False
        if attach_ids:
            attachment = attach_pool.browse(cr, uid, attach_ids[0], context)
            url = attachment.url
        else:
            url = self.copy_doc(cr, uid, res_id, template_id, name_gdocs,
                                model.model, context).get('url')
        return url
Beispiel #21
0
    def change_price(self, cr, uid, ids, context=None):
        """ Changes the Standard Price of Product.
            And creates an account move accordingly.
        @param self: The object pointer.
        @param cr: A database cursor
        @param uid: ID of the user currently logged in
        @param ids: List of IDs selected
        @param context: A standard dictionary
        @return:
        """
        if context is None:
            context = {}
        rec_id = context.get('active_id', False)
        assert rec_id, _('Active ID is not set in Context.')
        if context.get("active_model") == 'product.product':
            prod_obj = self.pool.get('product.product')
            rec_id = prod_obj.browse(cr, uid, rec_id,
                                     context=context).product_tmpl_id.id
        prod_obj = self.pool.get('product.template')

        res = self.browse(cr, uid, ids, context=context)

        prod_obj.do_change_standard_price(cr, uid, [rec_id], res[0].new_price,
                                          context)
        return {'type': 'ir.actions.act_window_close'}
Beispiel #22
0
    def _create_accounting_entries(self,
                                   cr,
                                   uid,
                                   line,
                                   move_id,
                                   qty_out,
                                   context=None):
        product_obj = self.pool.get('product.template')
        cost_product = line.cost_line_id and line.cost_line_id.product_id
        if not cost_product:
            return False
        accounts = product_obj.browse(cr,
                                      uid,
                                      line.product_id.product_tmpl_id.id,
                                      context=context).get_product_accounts()
        debit_account_id = accounts.get(
            'stock_valuation',
            False) and accounts['stock_valuation'].id or False
        already_out_account_id = accounts['stock_output'].id
        credit_account_id = line.cost_line_id.account_id.id or cost_product.property_account_expense_id.id or cost_product.categ_id.property_account_expense_categ_id.id

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

        return self._create_account_move_line(cr,
                                              uid,
                                              line,
                                              move_id,
                                              credit_account_id,
                                              debit_account_id,
                                              qty_out,
                                              already_out_account_id,
                                              context=context)
Beispiel #23
0
 def _signup_with_values(self, token, values):
     db, login, password = request.registry['res.users'].signup(
         request.cr, yuancloud.SUPERUSER_ID, values, token)
     request.cr.commit(
     )  # as authenticate will use its own cursor we need to commit the current transaction
     uid = request.session.authenticate(db, login, password)
     if not uid:
         raise SignupError(_('Authentication Failed.'))
     oauth_provider_entity_values = {}
     oauth_provider_entity_values.update({
         "res_user_id":
         uid,
         "oauth_provider_id":
         values.get("oauth_provider_id", ""),
         "oauth_uid":
         values.get("oauth_uid", ""),
         "oauth_access_token":
         values.get("oauth_access_token", "")
     })
     try:
         oauth_provider_entity_id = request.registry[
             'oauth_provider_entity_extend'].create(
                 request.cr, yuancloud.SUPERUSER_ID,
                 oauth_provider_entity_values)
         print oauth_provider_entity_id
     except Exception as e:
         _logger.error("创建登录方式出错:" + str(e))
     request.cr.commit()
Beispiel #24
0
    def _onchange_partner_id(self):
        result = super(account_invoice, self)._onchange_partner_id()
        partner = self.partner_id
        res = {}
        if not partner:
            self.account_id = False
            self.payment_term_id = False
            return result

        # If partner has no warning, check its company
        if partner.invoice_warn == 'no-message' and partner.parent_id:
            partner = partner.parent_id

        if partner.invoice_warn != 'no-message':
            # Block if partner only has warning but parent company is blocked
            if partner.invoice_warn != 'block' and partner.parent_id and partner.parent_id.invoice_warn == 'block':
                partner = partner.parent_id
            res['warning'] = {
                'title': _("Warning for %s") % partner.name,
                'message': partner.invoice_warn_msg
            }

            if partner.invoice_warn == 'block':
                self.partner_id = False

            return res
        return result
Beispiel #25
0
    def action_grant_badge(self, cr, uid, ids, context=None):
        """Wizard action for sending a badge to a chosen user"""

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

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

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

        return result
Beispiel #26
0
 def _company_warning(self, cr, uid, translated_msg, context=None):
     """ Raise a error with custom message, asking user to configure company settings """
     xmlid_mod = self.pool['ir.model.data']
     action_id = xmlid_mod.xmlid_to_res_id(cr, uid,
                                           'base.action_res_company_form')
     raise exceptions.RedirectWarning(
         translated_msg, action_id, _('Go to company configuration screen'))
Beispiel #27
0
    def _refresh_google_token_json(self, cr, uid, refresh_token, service, context=None):  # exchange_AUTHORIZATION vs Token (service = calendar)
        res = False
        client_id = self.get_client_id(cr, uid, service, context)
        client_secret = self.get_client_secret(cr, uid, service, context)

        params = {
            'refresh_token': refresh_token,
            'client_id': client_id,
            'client_secret': client_secret,
            'grant_type': 'refresh_token',
        }

        headers = {"content-type": "application/x-www-form-urlencoded"}

        try:
            uri = self.get_uri_oauth(a='token')

            data = werkzeug.url_encode(params)
            st, res, ask_time = self._do_request(cr, uid, uri, params=data, headers=headers, type='POST', preuri='', context=context)
        except urllib2.HTTPError, e:
            if e.code == 400:  # invalid grant
                registry = yuancloud.modules.registry.RegistryManager.get(request.session.db)
                with registry.cursor() as cur:
                    self.pool['res.users'].write(cur, uid, [uid], {'google_%s_rtoken' % service: False}, context=context)
            error_key = json.loads(e.read()).get("error", "nc")
            _logger.exception("Bad google request : %s !" % error_key)
            error_msg = "Something went wrong during your token generation. Maybe your Authorization Code is invalid or already expired [%s]" % error_key
            raise self.pool.get('res.config.settings').get_config_warning(cr, _(error_msg), context=context)
Beispiel #28
0
    def get_valuation_lines(self,
                            cr,
                            uid,
                            ids,
                            picking_ids=None,
                            context=None):
        picking_obj = self.pool.get('stock.picking')
        lines = []
        if not picking_ids:
            return lines

        for picking in picking_obj.browse(cr, uid, picking_ids):
            for move in picking.move_lines:
                #it doesn't make sense to make a landed cost for a product that isn't set as being valuated in real time at real cost
                if move.product_id.valuation != 'real_time' or move.product_id.cost_method != 'real':
                    continue
                total_cost = 0.0
                weight = move.product_id and move.product_id.weight * move.product_qty
                volume = move.product_id and move.product_id.volume * move.product_qty
                for quant in move.quant_ids:
                    total_cost += quant.cost * quant.qty
                vals = dict(product_id=move.product_id.id,
                            move_id=move.id,
                            quantity=move.product_uom_qty,
                            former_cost=total_cost,
                            weight=weight,
                            volume=volume)
                lines.append(vals)
        if not lines:
            raise UserError(
                _('The selected picking does not contain any move that would be impacted by landed costs. Landed costs are only possible for products configured in real time valuation with real price costing method. Please make sure it is the case, or you selected the correct picking'
                  ))
        return lines
Beispiel #29
0
    def _get_google_token_json(self, cr, uid, authorize_code, service, context=None):
        res = False
        base_url = self.get_base_url(cr, uid, context)
        client_id = self.get_client_id(cr, uid, service, context)
        client_secret = self.get_client_secret(cr, uid, service, context)

        params = {
            'code': authorize_code,
            'client_id': client_id,
            'client_secret': client_secret,
            'grant_type': 'authorization_code',
            'redirect_uri': base_url + '/google_account/authentication'
        }

        headers = {"content-type": "application/x-www-form-urlencoded"}

        try:
            uri = self.get_uri_oauth(a='token')
            data = werkzeug.url_encode(params)

            st, res, ask_time = self._do_request(cr, uid, uri, params=data, headers=headers, type='POST', preuri='', context=context)
        except urllib2.HTTPError:
            error_msg = "Something went wrong during your token generation. Maybe your Authorization Code is invalid"
            raise self.pool.get('res.config.settings').get_config_warning(cr, _(error_msg), context=context)
        return res
def get_login_info(auth_code, access_token):
    category_url = "https://qyapi.weixin.qq.com/cgi-bin/service/get_login_info?access_token=" + access_token
    category_data = {
        "auth_code": auth_code
    }
    req = urllib2.Request(category_url, json.dumps(category_data, ensure_ascii=False).encode('utf8'))
    req.add_header("Content-Type", "application/json")
    response = urllib2.urlopen(req)
    html = response.read().decode("utf-8")
    logger.debug('html:' + html)
    tokeninfo = json.loads(html)
    print tokeninfo
    if 'errcode' not in tokeninfo:
        return tokeninfo
    else:
        raise osv.except_osv(_('Error!'), _('获取企业号登录用户信息出错'))