示例#1
0
    def action_submit_expenses(self, **kwargs):
        """Send user corrected values to the ocr"""
        res = super(HrExpense, self).action_submit_expenses(**kwargs)

        for expense in self.filtered(
                lambda x: x.extract_state == 'waiting_validation'):
            endpoint = self.env['ir.config_parameter'].sudo().get_param(
                'hr_expense_extract_endpoint', 'https://iap-extract.odoo.com'
            ) + '/iap/expense_extract/validate'

            values = {
                'exp_total': expense.get_validation('exp_total'),
                'exp_date': expense.get_validation('exp_date'),
                'exp_description': expense.get_validation('exp_description'),
                'exp_currency': expense.get_validation('exp_currency'),
                'exp_bill_reference':
                expense.get_validation('exp_bill_reference')
            }
            params = {
                'document_id': expense.extract_remote_id,
                'version': CLIENT_OCR_VERSION,
                'values': values
            }
            try:
                iap_tools.iap_jsonrpc(endpoint, params=params)
                expense.extract_state = 'done'
            except AccessError:
                pass
        return res
示例#2
0
    def test_amazon_connection(self):
        """
        Create Seller account in ERP if not created before.
        If auth_token and merchant_id found in ERP then raise UserError.
        If Amazon Seller Account is registered in IAP raise UserError.
        IF Amazon Seller Account is not registered in IAP then create it.
        This function will load Marketplaces automatically based on seller region.
        :return:
        """
        amazon_seller_obj = self.env['amazon.seller.ept']
        iap_account_obj = self.env['iap.account']
        seller_exist = amazon_seller_obj.search([
            ('auth_token', '=', self.auth_token),
            ('merchant_id', '=', self.merchant_id)
        ])

        if seller_exist:
            raise UserError(_('Seller already exist with given Credential.'))

        account = iap_account_obj.search([('service_name', '=', 'amazon_ept')])
        if account:
            kwargs = self.prepare_marketplace_kwargs(account)
            response = iap_tools.iap_jsonrpc(DEFAULT_ENDPOINT + '/verify_iap',
                                             params=kwargs)
        else:
            account = iap_account_obj.create({'service_name': 'amazon_ept'})
            account._cr.commit()
            kwargs = self.prepare_marketplace_kwargs(account)
            response = iap_tools.iap_jsonrpc(DEFAULT_ENDPOINT +
                                             '/register_iap',
                                             params=kwargs)

        if response.get('error', {}):
            raise UserError(_(response.get('error')))

        flag = response.get('result', {})
        if flag:
            company_id = self.company_id or self.env.user.company_id or False
            vals = self.prepare_amazon_seller_vals(company_id)
            if self.country_id.code in ['AE', 'DE', 'EG', 'ES', 'FR', 'GB', 'IN', 'IT', 'SA', \
                                        'TR', 'NL']:
                vals.update({'is_european_region': True})
            else:
                vals.update({'is_european_region': False})
            try:
                seller = amazon_seller_obj.create(vals)
                seller.load_marketplace()
                self.create_transaction_type(seller)

            except Exception as e:
                raise UserError(
                    _('Exception during instance creation.\n %s' % (str(e))))
            action = self.env.ref('amazon_ept.action_amazon_configuration',
                                  False)
            result = action.read()[0] if action else {}
            result.update({'seller_id': seller.id})
            if seller.amazon_selling in ['FBA', 'Both']:
                self.update_reimbursement_details(seller)
        return True
 def decode_amazon_encrypted_vcs_attachments_data(self, attachment_id, job):
     """
     Added method to decode the encrypted VCS attachments data.
     """
     dbuuid = self.env['ir.config_parameter'].sudo().get_param(
         'database.uuid')
     req = {
         'dbuuid': dbuuid,
         'report_id': self.report_id,
         'datas': attachment_id.datas.decode(),
         'amz_report_type': 'vcs_tax_report'
     }
     response = iap_tools.iap_jsonrpc(DEFAULT_ENDPOINT + '/decode_data',
                                      params=req,
                                      timeout=1000)
     if response.get('result'):
         imp_file = StringIO(
             base64.b64decode(response.get('result')).decode('ISO-8859-1'))
     elif self._context.get('is_auto_process', False):
         job.log_lines.create({
             'message':
             'Error found in Decryption of Data %s' %
             response.get('error', '')
         })
         return True
     else:
         raise Warning(response.get('error'))
     return imp_file
    def get_report_request_list(self):
        """
        Get Report Requests List from Amazon, Check Status of Process.
        @author: Keyur Kanani
        :return: Boolean
        """
        self.ensure_one()
        if not self.seller_id:
            raise UserError(_('Please select Seller'))
        if not self.report_request_id:
            return True
        kwargs = self.prepare_amazon_request_report_kwargs(self.seller_id)
        kwargs.update({
            'emipro_api': 'get_report_request_list_v13',
            'request_ids': (self.report_request_id, )
        })

        response = iap_tools.iap_jsonrpc(DEFAULT_ENDPOINT + '/iap_request',
                                         params=kwargs)
        if not response.get('reason'):
            list_of_wrapper = response.get('result')
        else:
            raise UserError(_(response.get('reason')))
        for result in list_of_wrapper:
            self.update_report_history(result)
        return True
示例#5
0
 def get_report(self):
     """
     This Method relocates get stock report as an attachment in stock reports form view.
     :return: This Method return boolean(True/False).
     """
     self.ensure_one()
     common_log_book_obj = self.env['common.log.book.ept']
     shipping_report_obj = self.env['shipping.report.request.history']
     result = {}
     seller = self.seller_id
     if not seller:
         raise UserError(_('Please select Seller'))
     if not self.report_id:
         return True
     kwargs = shipping_report_obj.prepare_amazon_request_report_kwargs(
         self.seller_id)
     kwargs.update({
         'emipro_api': 'get_report_v13',
         'report_id': self.report_id
     })
     response = iap_tools.iap_jsonrpc(DEFAULT_ENDPOINT + '/iap_request',
                                      params=kwargs,
                                      timeout=1000)
     if response.get('reason'):
         if self._context.get('is_auto_process'):
             common_log_book_obj.create({
                 'type':
                 'import',
                 'module':
                 'amazon_ept',
                 'active':
                 True,
                 'log_lines': [(0, 0, {
                     'message':
                     'Stock adjustment Report Process ' +
                     response.get('reason')
                 })]
             })
         else:
             raise UserError(_(response.get('reason')))
     else:
         result = response.get('result')
     if result:
         result = result.encode()
         result = base64.b64encode(result)
         file_name = "Stock_adjusments_report_" + time.strftime(
             "%Y_%m_%d_%H%M%S") + '.csv'
         attachment = self.env['ir.attachment'].create({
             'name': file_name,
             'datas': result,
             'res_model': 'mail.compose.message',
             'type': 'binary'
         })
         self.message_post(
             body=_("<b>Stock adjustment Report Downloaded</b>"),
             attachment_ids=attachment.ids)
         self.write({'attachment_id': attachment.id})
         seller.write(
             {'stock_adjustment_report_last_sync_on': datetime.now()})
     return True
示例#6
0
    def retry_ocr(self):
        """Retry to contact iap to submit the first attachment in the chatter"""
        if not self.env.company.expense_extract_show_ocr_option_selection or self.env.company.expense_extract_show_ocr_option_selection == 'no_send':
            return False
        attachments = self.message_main_attachment_id
        if attachments and attachments.exists() and self.extract_state in [
                'no_extract_requested', 'not_enough_credit', 'error_status',
                'module_not_up_to_date'
        ]:
            account_token = self.env['iap.account'].get('invoice_ocr')
            endpoint = self.env['ir.config_parameter'].sudo().get_param(
                'hr_expense_extract_endpoint',
                'https://iap-extract.odoo.com') + '/iap/expense_extract/parse'

            user_infos = {
                'user_company_VAT': self.company_id.vat,
                'user_company_name': self.company_id.name,
                'user_company_country_code': self.company_id.country_id.code,
                'user_lang': self.env.user.lang,
                'user_email': self.env.user.email,
            }
            params = {
                'account_token':
                account_token.account_token,
                'version':
                CLIENT_OCR_VERSION,
                'dbuuid':
                self.env['ir.config_parameter'].sudo().get_param(
                    'database.uuid'),
                'documents': [x.datas.decode('utf-8') for x in attachments],
                'file_names': [x.name for x in attachments],
                'user_infos':
                user_infos,
            }
            try:
                result = iap_tools.iap_jsonrpc(endpoint, params=params)
                self.extract_status_code = result['status_code']
                if result['status_code'] == SUCCESS:
                    self.extract_state = 'waiting_extraction'
                    self.extract_remote_id = result['document_id']
                    if 'isMobile' in self.env.context and self.env.context[
                            'isMobile']:
                        for record in self:
                            timer = 0
                            while record.extract_state != 'waiting_validation' and timer < 10:
                                timer += 1
                                time.sleep(1)
                                record._check_status()

                elif result['status_code'] == ERROR_NOT_ENOUGH_CREDIT:
                    self.extract_state = 'not_enough_credit'
                else:
                    self.extract_state = 'error_status'
                    _logger.warning(
                        'There was an issue while doing the OCR operation on this file. Error: -1'
                    )

            except AccessError:
                self.extract_state = 'error_status'
                self.extract_status_code = ERROR_NO_CONNECTION
 def get_fcm_project_id(self):
     ir_params_sudo = self.env['ir.config_parameter'].sudo()
     if not ir_params_sudo.get_param('mail_mobile.enable_ocn'):
         return
     project_id = ir_params_sudo.get_param('odoo_ocn.project_id')
     if not project_id:
         params = {
             'ocnuuid': self._get_ocn_uuid(),
             'server_version': odoo.release.version,
             'db': self.env.cr.dbname,
             'company_name': self.env.company.name,
             'url': ir_params_sudo.get_param('web.base.url')
         }
         try:
             # Register instance to ocn service. Unique with ocn.uuid
             project_id = iap_tools.iap_jsonrpc(self._get_endpoint() +
                                                '/iap/ocn/enable_service',
                                                params=params)
             # Storing project id for generate token
             ir_params_sudo.set_param('odoo_ocn.project_id', project_id)
         except Exception as e:
             _logger.error(
                 'An error occured while contacting the ocn server: %s',
                 e.args[0])
     return project_id
 def _perform_reveal_service(self, server_payload):
     result = False
     account_token = self.env['iap.account'].get('reveal')
     endpoint = self.env['ir.config_parameter'].sudo().get_param(
         'reveal.endpoint', DEFAULT_ENDPOINT) + '/iap/clearbit/1/reveal'
     params = {
         'account_token': account_token.account_token,
         'data': server_payload
     }
     result = iap_tools.iap_jsonrpc(endpoint, params=params, timeout=300)
     for res in result.get('reveal_data', []):
         if not res.get('not_found'):
             lead = self._create_lead_from_response(res)
             self.env['crm.reveal.view'].search([('reveal_ip', '=',
                                                  res['ip'])]).unlink()
         else:
             self.env['crm.reveal.view'].search([
                 ('reveal_ip', '=', res['ip'])
             ]).write({'reveal_state': 'not_found'})
     if result.get('credit_error'):
         self.env['crm.iap.lead.helpers'].notify_no_more_credit(
             'reveal', self._name, 'reveal.already_notified')
         return False
     else:
         self.env['ir.config_parameter'].sudo().set_param(
             'reveal.already_notified', False)
     return True
示例#9
0
    def update_images(self, instance):
        """
        This Method relocates prepare image envelope for amazon.
        :param instance: This arguments relocates instance of amazon.
        :return: This Method return boolean(True/False).
        """
        message_id = 1
        merchant_string = "<MerchantIdentifier>%s</MerchantIdentifier>" % (instance.merchant_id)
        message_information = ''
        for amazon_product in self:
            if not amazon_product.exported_to_amazon:
                continue
            for image_obj in amazon_product.product_id.ept_image_ids:
                message_information = self.create_image_dict(amazon_product, image_obj,
                                                             message_information, message_id)
                message_id += 1
        if message_information:
            data = """<?xml version="1.0" encoding="utf-8"?>
            <AmazonEnvelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
            xsi:noNamespaceSchemaLocation="amzn-envelope.xsd"><Header><DocumentVersion>1.01
            </DocumentVersion>""" + merchant_string + """</Header><MessageType>
            ProductImage</MessageType>""" + message_information + """</AmazonEnvelope>"""
            kwargs = self.get_amazon_product_request_data_ept(instance, data, 'update_images_v13')
            kwargs.update({'marketplaceids': [instance.market_place_id]})

            response = iap_tools.iap_jsonrpc(DEFAULT_ENDPOINT + '/iap_request', params=kwargs)
            if response.get('reason'):
                raise UserError(_(response.get('reason')))
            results = response.get('result')
            self.process_amazon_update_image_result(instance, results, data)

        return True
    def get_report_request_list(self):
        """
        This method will request for get report request list based on report_request_id
        and process response and update report history in odoo.
        """
        self.ensure_one()
        if not self.seller_id:
            raise UserError(_('Please select Seller'))
        if not self.report_request_id:
            return True

        kwargs = self.prepare_amazon_request_report_kwargs(self.seller_id)
        kwargs.update({
            'emipro_api': 'get_report_request_list_v13',
            'request_ids': (self.report_request_id)
        })

        response = iap_tools.iap_jsonrpc(DEFAULT_ENDPOINT + '/iap_request',
                                         params=kwargs)
        if not response.get('reason'):
            list_of_wrapper = response.get('result')
        else:
            raise UserError(_(response.get('reason')))
        for result in list_of_wrapper:
            self.update_report_history(result)
        return True
示例#11
0
    def request_report(self):
        """
        This method request in Amazon for unshipped Sales Orders.
        :return:True
        """
        seller = self.seller_id
        report_type = self.report_type
        instances = seller.instance_ids
        marketplace_ids = tuple(map(lambda x: x.market_place_id, instances))

        if not seller:
            raise UserError(_('Please select Seller'))

        kwargs = self.prepare_fbm_unshipped_data_request_ept('request_report_fbm_v13')
        kwargs.update({'report_type': report_type,
                       'marketplace_ids': marketplace_ids,
                       'ReportOptions': "ShowSalesChannel=true"})

        response = iap_tools.iap_jsonrpc(DEFAULT_ENDPOINT + '/iap_request',
                                         params=kwargs, timeout=1000)
        if response.get('reason'):
            raise UserError(_(response.get('reason')))
        result = response.get('result')
        self.update_report_history(result)
        return True
示例#12
0
    def get_report_request_list(self):
        """
        This Method relocates get report list from amazon.
        :return: This Method return boolean(True/False).
        """
        self.ensure_one()
        common_log_book_obj = self.env['common.log.book.ept']
        shipping_report_obj = self.env['shipping.report.request.history']
        list_of_wrapper = []
        if not self.seller_id:
            raise UserError(_('Please select Seller'))
        if not self.report_request_id:
            return True
        kwargs = shipping_report_obj.prepare_amazon_request_report_kwargs(self.seller_id)
        kwargs.update( \
            {'emipro_api': 'get_report_request_list_v13', 'request_ids': (self.report_request_id,)})
        response = iap_tools.iap_jsonrpc(DEFAULT_ENDPOINT + '/iap_request', params=kwargs)
        if response.get('reason'):
            if self._context.get('is_auto_process'):
                common_log_book_obj.create({
                    'type': 'import',
                    'module': 'amazon_ept',
                    'active': True,
                    'log_lines': [
                        (0, 0, {'message': 'Rating Report Process ' + response.get('reason')})]
                })
            else:
                raise UserError(_(response.get('reason')))
        else:
            list_of_wrapper = response.get('result')

        for result in list_of_wrapper:
            self.update_report_history(result)
        return True
示例#13
0
 def get_inbound_import_shipment(self, instance, warehouse_id, ship_ids):
     """
     Import already created Inbound Shipment from shipment id and
     it will be created for given warehouse id.
     :param instance: amazon.instance.ept()
     :param warehouse_id: stock.warehouse()
     :param ship_ids: []
     :return:
     @author: Keyur Kanani
     """
     amz_inbound_shipment_obj = self.env['amazon.inbound.shipment.ept']
     shipment_ids = ship_ids.split(',')
     # No Need to Import Duplicate Inbound Shipment
     inbound_shipment = amz_inbound_shipment_obj.search([('shipment_id', 'in', shipment_ids)])
     if inbound_shipment:
         shipments = ", ".join(str(shipment.shipment_id) for shipment in inbound_shipment)
         raise UserError(_("Shipments %s already exists" % shipments))
     for shipment_id in shipment_ids:
         kwargs = self.amz_prepare_inbound_kwargs_vals(instance)
         kwargs.update({'emipro_api': 'check_status_v13', 'shipment_ids': [shipment_id]})
         response = iap_tools.iap_jsonrpc(DEFAULT_ENDPOINT + '/iap_request', params=kwargs)
         if response.get('reason'):
             raise UserError(_(response.get('reason')))
         amazon_shipments = response.get('amazon_shipments')
         inbound_shipment = self.create_amazon_inbound_shipment(amazon_shipments, instance.id,
                                                                warehouse_id.id)
         self.get_list_inbound_shipment_items(shipment_id, instance, inbound_shipment.id)
         inbound_shipment.create_shipment_picking()
示例#14
0
 def _perform_request(self):
     """
     This will perform the request and create the corresponding leads.
     The user will be notified if he hasn't enough credits.
     """
     server_payload = self._prepare_iap_payload()
     reveal_account = self.env['iap.account'].get('reveal')
     dbuuid = self.env['ir.config_parameter'].sudo().get_param(
         'database.uuid')
     endpoint = self.env['ir.config_parameter'].sudo().get_param(
         'reveal.endpoint',
         DEFAULT_ENDPOINT) + '/iap/clearbit/1/lead_mining_request'
     params = {
         'account_token': reveal_account.account_token,
         'dbuuid': dbuuid,
         'data': server_payload
     }
     try:
         response = iap_tools.iap_jsonrpc(endpoint,
                                          params=params,
                                          timeout=300)
         return response['data']
     except iap_tools.InsufficientCreditError as e:
         self.error = 'Insufficient credits. Recharge your account and retry.'
         self.state = 'error'
         self._cr.commit()
         raise e
示例#15
0
 def _contact_iap(self, local_endpoint, params):
     account = self.env['iap.account'].get('sms')
     params['account_token'] = account.account_token
     endpoint = self.env['ir.config_parameter'].sudo().get_param(
         'sms.endpoint', DEFAULT_ENDPOINT)
     # TODO PRO, the default timeout is 15, do we have to increase it ?
     return iap_tools.iap_jsonrpc(endpoint + local_endpoint, params=params)
示例#16
0
 def send_cerex_request(self):
     user_token = self.env['iap.account'].get('live_cur_ex_rate')
     service_endpoint = self.env['ir.config_parameter'].sudo().get_param(
         'live_cur_ex_rate.endpoint', self._default_live_cur_ex_rate)
     for move in self:
         if move.company_currency_id == move.currency_id:
             raise UserError(
                 _('Invoice currency and compnay currency is same, this doucment do not require exchange rates.'
                   ))
         params = {
             'user_token': user_token.account_token,
             'request_res_id': '%s,%s' % (move._name, move.id),
             'from_cur': move.company_currency_id.name,
             'to_cur': move.currency_id.name,
         }
         endpoint = self.env['ir.config_parameter'].sudo().get_param(
             'live_cur_ex_rate.endpoint', self._default_live_cur_ex_rate)
         response = iap_tools.iap_jsonrpc(service_endpoint +
                                          '/curex/v1/request',
                                          params=params)
         response_data = json.loads(response)
         move.write({
             'iap_curex_request_id':
             response_data.get('cur_ex_request_id'),
             'iap_curex_request_hold_token':
             response_data.get('credit_auth_token'),
         })
         move.message_post(
             body='Exchange rate request has been succesfully sent.')
     return {'type': 'ir.actions.act_window_close'}
    def get_report_request_list(self):
        """
            @author : Harnisha Patel
            @last_updated_on : 3/10/2019
            The below method checks status and gets the report list.
            """
        self.ensure_one()
        seller = self.instance_id.seller_id
        account = self.env['iap.account'].search([('service_name', '=', 'amazon_ept')])
        dbuuid = self.env['ir.config_parameter'].sudo().get_param('database.uuid')
        if not seller:
            raise UserError(_('Please select Seller'))
        if not self.report_request_id:
            return True
        kwargs = {'merchant_id': seller.merchant_id and str(seller.merchant_id) or False,
                  'auth_token': seller.auth_token and str(seller.auth_token) or False,
                  'app_name': 'amazon_ept',
                  'account_token': account.account_token,
                  'emipro_api': 'get_report_request_list_v13',
                  'dbuuid': dbuuid,
                  'amazon_marketplace_code': seller.country_id.amazon_marketplace_code or
                                             seller.country_id.code,
                  'request_ids': (self.report_request_id,),
                  }

        response = iap_tools.iap_jsonrpc(DEFAULT_ENDPOINT + '/iap_request', params=kwargs)
        if response.get('reason'):
            raise UserError(_(response.get('reason')))
        list_of_wrapper = response.get('result')
        for result in list_of_wrapper:
            self.update_report_history(result)
        return True
示例#18
0
    def _perform_request(self):
        """
        This will perform the request and create the corresponding leads.
        The user will be notified if he hasn't enough credits.
        """
        self.error_type = False
        server_payload = self._prepare_iap_payload()
        reveal_account = self.env['iap.account'].get('reveal')
        dbuuid = self.env['ir.config_parameter'].sudo().get_param(
            'database.uuid')
        endpoint = self.env['ir.config_parameter'].sudo().get_param(
            'reveal.endpoint',
            DEFAULT_ENDPOINT) + '/iap/clearbit/1/lead_mining_request'
        params = {
            'account_token': reveal_account.account_token,
            'dbuuid': dbuuid,
            'data': server_payload
        }
        try:
            response = iap_tools.iap_jsonrpc(endpoint,
                                             params=params,
                                             timeout=300)
            if not response.get('data'):
                self.error_type = 'no_result'
                return False

            return response['data']
        except iap_tools.InsufficientCreditError as e:
            self.error_type = 'credits'
            self.state = 'error'
            return False
        except Exception as e:
            raise UserError(_("Your request could not be executed: %s", e))
示例#19
0
    def get_report(self):
        """
        This method get the report and store in one csv file and attached with one attachment.
        :return:True
        """
        seller = self.seller_id
        if not seller:
            raise UserError(_('Please select seller'))
        if not self.report_id:
            return True

        kwargs = self.prepare_fbm_unshipped_data_request_ept('get_report_v13')
        kwargs.update({'report_id': self.report_id,
                       'amz_report_type': 'fbm_report', })

        response = iap_tools.iap_jsonrpc(DEFAULT_ENDPOINT + '/iap_request',
                                         params=kwargs, timeout=1000)
        if response.get('reason'):
            raise UserError(_(response.get('reason')))
        result = response.get('result')
        file_name = "FBM_Sale_Order_" + time.strftime(
            "%Y_%m_%d_%H%M%S") + '.csv'

        attachment = self.env['ir.attachment'].create({
            'name': file_name,
            'datas': result.encode(),
            'res_model': 'mail.compose.message',
            'type': 'binary'
        })
        self.message_post(body=_("<b>FBM Sale Order Report Downloaded</b>"),
                          attachment_ids=attachment.ids)
        self.write({'attachment_id': attachment.id})
        return True
 def request_report(self):
     """
         @author : Harnisha Patel
         @last_updated_on : 3/10/2019
         The below method requests the record of the report.
         """
     seller = self.instance_id.seller_id
     account = self.env['iap.account'].search([('service_name', '=', 'amazon_ept')])
     dbuuid = self.env['ir.config_parameter'].sudo().get_param('database.uuid')
     if not seller:
         raise UserError(_('Please select instance'))
     marketplace_ids = tuple([self.instance_id.market_place_id])
     kwargs = {'merchant_id': seller.merchant_id and str(seller.merchant_id) or False,
               'auth_token': seller.auth_token and str(seller.auth_token) or False,
               'app_name': 'amazon_ept',
               'account_token': account.account_token,
               'emipro_api': 'request_report_v13',
               'dbuuid': dbuuid,
               'amazon_marketplace_code': seller.country_id.amazon_marketplace_code or
                                          seller.country_id.code,
               'report_type': self.report_type or '_GET_MERCHANT_LISTINGS_DATA_',
               'marketplace_ids': marketplace_ids,
               'start_date': None,
               'end_date': None,
               }
     response = iap_tools.iap_jsonrpc(DEFAULT_ENDPOINT + '/iap_request', params=kwargs)
     if response.get('reason'):
         raise UserError(_(response.get('reason')))
     result = response.get('result')
     self.update_report_history(result)
     return True
示例#21
0
 def _contact_iap(self, local_endpoint, params):
     account = self.env['iap.account'].get('reveal')
     dbuuid = self.env['ir.config_parameter'].sudo().get_param('database.uuid')
     params['account_token'] = account.account_token
     params['dbuuid'] = dbuuid
     base_url = self.env['ir.config_parameter'].sudo().get_param('enrich.endpoint', self._DEFAULT_ENDPOINT)
     return iap_tools.iap_jsonrpc(base_url + local_endpoint, params=params, timeout=300)
示例#22
0
 def _rpc_remote_api(self, action, params, timeout=15):
     if self.env.registry.in_test_mode():
         return False, 'Insufficient Credit'
     url = '%s/%s' % (self.get_endpoint(), action)
     account = self.env['iap.account'].get('partner_autocomplete')
     if not account.account_token:
         return False, 'No Account Token'
     params.update({
         'db_uuid':
         self.env['ir.config_parameter'].sudo().get_param('database.uuid'),
         'account_token':
         account.account_token,
         'country_code':
         self.env.company.country_id.code,
         'zip':
         self.env.company.zip,
     })
     try:
         return iap_tools.iap_jsonrpc(url=url,
                                      params=params,
                                      timeout=timeout), False
     except (ConnectionError, HTTPError, exceptions.AccessError,
             exceptions.UserError) as exception:
         _logger.error('Autocomplete API error: %s' % str(exception))
         return False, str(exception)
     except iap_tools.InsufficientCreditError as exception:
         _logger.warning(
             'Insufficient Credits for Autocomplete Service: %s' %
             str(exception))
         return False, 'Insufficient Credit'
示例#23
0
 def _get_twitter_oauth_signature_from_iap(self,
                                           method,
                                           url,
                                           params,
                                           oauth_token_secret=''):
     params['oauth_nonce'] = str(params['oauth_nonce'])
     json_params = {
         'method':
         method,
         'url':
         url,
         'params':
         params,
         'oauth_token_secret':
         oauth_token_secret,
         'db_uuid':
         self.env['ir.config_parameter'].sudo().get_param('database.uuid')
     }
     social_iap_endpoint = self.env['ir.config_parameter'].sudo().get_param(
         'social.social_iap_endpoint',
         self.env['social.media']._DEFAULT_SOCIAL_IAP_ENDPOINT)
     try:
         return iap_tools.iap_jsonrpc(url_join(
             social_iap_endpoint, 'iap/social_twitter/get_signature'),
                                      params=json_params)
     except AccessError:
         return None
示例#24
0
    def fetch_cerex_update(self):
        user_token = self.env['iap.account'].get('live_cur_ex_rate')
        service_endpoint = self.env['ir.config_parameter'].sudo().get_param(
            'live_cur_ex_rate.endpoint', self._default_live_cur_ex_rate)

        for move in self:
            if not move.iap_curex_request_id or not move.iap_curex_request_hold_token:
                raise UserError(
                    _('INvoice request is not genereated yet, please senf requets first'
                      ))
            params = {
                'user_token': user_token.account_token,
                'request_id': move.iap_curex_request_id,
                'credit_auth_token': move.iap_curex_request_hold_token,
            }
            endpoint = self.env['ir.config_parameter'].sudo().get_param(
                'live_cur_ex_rate.endpoint', self._default_live_cur_ex_rate)
            response = iap_tools.iap_jsonrpc(service_endpoint +
                                             '/curex/v1/fetch',
                                             params=params)
            response_data = json.loads(response)
            if response_data.get('error', False):
                raise UserError(response_data.get('error', ''))
            move.write({
                'iap_curex_request_id': False,
                'iap_curex_request_hold_token': False,
                'iap_curex_rate': response_data.get('result'),
                'iap_curex_rate_dt': fields.Datetime.now(),
            })
        return {'type': 'ir.actions.act_window_close'}
示例#25
0
    def auto_delete_customer_pii_details(self):
        """
        Auto Archive Customer's PII Details after 30 days of Import as per Amazon MWS Policies.
        :return:
        """
        if not self.env['amazon.seller.ept'].search([]):
            return True
        account = self.env['iap.account'].search([('service_name', '=',
                                                   'amazon_ept')])
        dbuuid = self.env['ir.config_parameter'].sudo().get_param(
            'database.uuid')
        kwargs = {
            'app_name': 'amazon_ept',
            'account_token': account.account_token,
            'dbuuid': dbuuid,
            'updated_records':
            'Scheduler for delete PII data has been started.'
        }
        iap_tools.iap_jsonrpc(DEFAULT_ENDPOINT + '/delete_pii',
                              params=kwargs,
                              timeout=1000)
        query = """update res_partner set name='Amazon',commercial_company_name='Amazon', 
                    display_name='Amazon', 
                    street=NULL,street2=NULL,email=NULL,city=NULL,state_id=NULL,country_id=NULL,
                    zip=Null,phone=NULL,mobile=NULL
                    from
                    (select r1.id as partner_id,r2.id as partner_invoice_id,r3.id as 
                    partner_shipping_id from sale_order
                    inner join res_partner r1 on r1.id=sale_order.partner_id
                    inner join res_partner r2 on r2.id=sale_order.partner_invoice_id
                    inner join res_partner r3 on r3.id=sale_order.partner_shipping_id
                    where amz_instance_id is not null and sale_order.create_date<=current_date-30)T
                    where res_partner.id in 
                    (T.partner_id,T.partner_invoice_id,T.partner_shipping_id)
                    """
        self.env.cr.execute(query)

        if self.env.cr.rowcount:
            kwargs.update({
                'updated_records':
                'Archived %d customers' % self.env.cr.rowcount
            })
            iap_tools.iap_jsonrpc(DEFAULT_ENDPOINT + '/delete_pii',
                                  params=kwargs,
                                  timeout=1000)
        return True
示例#26
0
    def process_fbm_sale_order_file(self):
        """
        This method process the attached file with record and create Sales orders.
        :return:True
        """
        self.ensure_one()
        ir_cron_obj = self.env['ir.cron']
        common_log_book_obj = self.env['common.log.book.ept']
        common_log_line_obj = self.env['common.log.lines.ept']

        if not self._context.get('is_auto_process', False):
            ir_cron_obj.with_context({'raise_warning': True}).find_running_schedulers( \
                'ir_cron_process_amazon_unshipped_orders_seller_', self.seller_id.id)

        marketplaceids = tuple(map(lambda x: x.market_place_id, self.seller_id.instance_ids))
        if not marketplaceids:
            raise UserError(
                "There is no any instance is configured of seller %s" % (self.seller_id.name))
        if not self.attachment_id:
            raise UserError(_("There is no any report are attached with this record."))

        file_order_list = self.get_unshipped_order()
        unshipped_order_list = []
        business_prime_dict = {}

        kwargs = self.prepare_fbm_unshipped_data_request_ept('get_order_v13')
        kwargs.update({'marketplaceids': marketplaceids})
        model_id = self.env['ir.model']._get('fbm.sale.order.report.ept').id

        log_book = common_log_book_obj.amazon_create_transaction_log('import',
                                                                     model_id,
                                                                     self.id)

        for x in range(0, len(file_order_list), 50):
            sale_orders_list = file_order_list[x:x + 50]
            kwargs.update({'sale_order_list': sale_orders_list})
            # TODO: Max_request_quota = 6, restore_rate = 1req/min
            response = iap_tools.iap_jsonrpc(DEFAULT_ENDPOINT + '/iap_request', params=kwargs,
                                             timeout=1000)
            if response.get('reason'):
                if self._context.get('is_auto_process'):
                    message = 'FBM Sale Order Report Auto Process'
                    common_log_line_obj.amazon_create_order_log_line(message, model_id, self.id,
                                                                     False, False,
                                                                     log_book)
                else:
                    raise UserError(_(response.get('reason')))
            else:
                unshipped_order_list, business_prime_dict = self.process_fbm_shipped_order_response_ept(
                    response, unshipped_order_list, business_prime_dict)

        self.process_prepare_unshipped_order_list_ept(unshipped_order_list, business_prime_dict,
                                                      log_book)
        if not log_book.log_lines:
            log_book.unlink()
        self.write({'state': 'processed'})
        return True
    def get_report(self):
        """
        This method is used to get vcs tax report and create attachments and post the message.
        """
        self.ensure_one()
        common_log_book_obj = self.env['common.log.book.ept']
        result = {}
        seller = self.seller_id
        if not seller:
            raise UserError(_('Please select seller'))
        if not self.report_id:
            return True

        kwargs = self.prepare_amazon_request_report_kwargs(self.seller_id)
        kwargs.update({
            'emipro_api': 'get_report_v13',
            'report_id': self.report_id,
            'amz_report_type': 'vcs_tax_report'
        })
        response = iap_tools.iap_jsonrpc(DEFAULT_ENDPOINT + '/iap_request',
                                         params=kwargs,
                                         timeout=1000)
        if response.get('reason'):
            if self._context.get('is_auto_process'):
                common_log_book_obj.create({
                    'type':
                    'import',
                    'module':
                    'amazon_ept',
                    'active':
                    True,
                    'log_lines': [(0, 0, {
                        'message':
                        'VCS Report Process ' + response.get('reason')
                    })]
                })
            else:
                raise UserError(_(response.get('reason')))
        else:
            result = response.get('result')
        if result:
            file_name = "VCS_Tax_report_" + time.strftime(
                "%Y_%m_%d_%H%M%S") + '.csv'
            attachment = self.env['ir.attachment'].create({
                'name':
                file_name,
                'datas':
                result.encode(),
                'res_model':
                'mail.compose.message',
                'type':
                'binary'
            })
            self.message_post(body=_("<b>VCS Tax Report Downloaded</b>"),
                              attachment_ids=attachment.ids)
            self.write({'attachment_id': attachment.id})
        return True
示例#28
0
 def _send_notification_to_partners(self, pids, message, msg_vals):
     """
     Send the notification to a list of partners
     :param pids: list of partners
     :param message: current mail.message record
     :param msg_vals: dict values for current notification
     """
     if pids:
         receiver_ids = self.env['res.partner'].sudo().search([
             ('id', 'in', list(pids)),
             ('ocn_token', '!=', False)
         ])
         if receiver_ids:
             endpoint = self.env['res.config.settings']._get_endpoint()
             chunks = self._ocn_prepare_payload(receiver_ids, message, msg_vals)
             for chunk in chunks:
                 try:
                     iap_tools.iap_jsonrpc(endpoint + '/iap/ocn/send', params=chunk)
                 except Exception as e:
                     _logger.error('An error occured while contacting the ocn server: %s', e)
示例#29
0
    def _snailmail_print_valid_address(self):
        """
        get response
        {
            'request_code': RESPONSE_OK, # because we receive 200 if good or fail
            'total_cost': total_cost,
            'credit_error': credit_error,
            'request': {
                'documents': documents,
                'options': options
                }
            }
        }
        """
        endpoint = self.env['ir.config_parameter'].sudo().get_param('snailmail.endpoint', DEFAULT_ENDPOINT)
        timeout = int(self.env['ir.config_parameter'].sudo().get_param('snailmail.timeout', DEFAULT_TIMEOUT))
        params = self._snailmail_create('print')
        response = iap_tools.iap_jsonrpc(endpoint + PRINT_ENDPOINT, params=params, timeout=timeout)
        for doc in response['request']['documents']:
            if doc.get('sent') and response['request_code'] == 200:
                self.env['iap.account']._send_iap_bus_notification(
                    service_name='snailmail',
                    title=_("Snail Mails are successfully sent"))
                note = _('The document was correctly sent by post.<br>The tracking id is %s', doc['send_id'])
                letter_data = {'info_msg': note, 'state': 'sent', 'error_code': False}
                notification_data = {
                    'notification_status': 'sent',
                    'failure_type': False,
                    'failure_reason': False,
                }
            else:
                error = doc['error'] if response['request_code'] == 200 else response['reason']

                if error == 'CREDIT_ERROR':
                    self.env['iap.account']._send_iap_bus_notification(
                        service_name='snailmail',
                        title=_("Not enough credits for Snail Mail"),
                        error_type="credit")
                note = _('An error occurred when sending the document by post.<br>Error: %s', self._get_error_message(error))
                letter_data = {
                    'info_msg': note,
                    'state': 'error',
                    'error_code': error if error in ERROR_CODES else 'UNKNOWN_ERROR'
                }
                notification_data = {
                    'notification_status': 'exception',
                    'failure_type': self._get_failure_type(error),
                    'failure_reason': note,
                }

            letter = self.browse(doc['letter_id'])
            letter.write(letter_data)
            letter.notification_ids.sudo().write(notification_data)
        self.message_id._notify_message_notification_update()
示例#30
0
    def _firebase_send_message_from_iap(self, data, visitors):
        social_iap_endpoint = self.env['ir.config_parameter'].sudo().get_param(
            'social.social_iap_endpoint',
            self.env['social.media']._DEFAULT_SOCIAL_IAP_ENDPOINT)
        batch_size = 100

        tokens = visitors.mapped('push_token')
        data.update({
            'db_uuid':
            self.env['ir.config_parameter'].sudo().get_param('database.uuid')
        })
        for tokens_batch in tools.split_every(batch_size,
                                              tokens,
                                              piece_maker=list):
            batch_data = dict(data)
            batch_data['tokens'] = tokens_batch
            iap_tools.iap_jsonrpc(url_join(
                social_iap_endpoint,
                '/iap/social_push_notifications/firebase_send_message'),
                                  params=batch_data)

        return []