def wrap(self, *args, **kwargs): """.""" access_token = kwargs.get('token') if not access_token: return invalid_response('access_token_not_found', 'missing access token in request header', 401) access_token_data = request.env['api.access_token'].sudo().search( [('token', '=', access_token)], order='id DESC', limit=1) if access_token_data.find_one_or_create_token(user_id=access_token_data.user_id.id) != access_token: return invalid_response('access_token', 'token seems to have expired or invalid', 401) request.session.uid = access_token_data.user_id.id request.uid = access_token_data.user_id.id return func(self, *args, **kwargs)
def remove_line(self, **payload): # Request payload body = request.httprequest.get_data() body_json = json.loads(body.decode("utf-8")) received_sku = int(body_json.get('cartItem').get('sku')) received_quote_id = int(body_json.get('cartItem').get('quoteId')) guest_partner_id = 4 expected_partner_id = guest_partner_id if request.session.uid: user_data = request.env['res.users'].sudo().search_read( domain=[('id', '=', request.session.uid)], fields=['partner_id'], offset=None, limit=1, order=None )[0] expected_partner_id = user_data.get('partner_id')[0] # Check if order is related to authenticated user order_data = request.env['sale.order'].sudo().search_read( domain=[('id', '=', received_quote_id)], fields=['partner_id'], offset=None, limit=1, order=None )[0] actual_partner_id = order_data.get('partner_id')[0] if actual_partner_id != expected_partner_id: return invalid_response('params', {'errors': ['Unauthorized']}, 400) # Remove sale order line record = request.env['sale.order.line'].sudo().search([ ('order_id', '=', received_quote_id), ('product_id', '=', received_sku), ]) if record: record.unlink() return simple_response( { "code": 200, "result": True } ) else: return invalid_response('missing_line', 'Line with order id %s could not be found.' % received_quote_id, 404)
def sign_up(self, **payload): body = request.httprequest.get_data() payload = json.loads(body.decode("utf-8")) firstname = payload.get('customer').get('firstname') lastname = payload.get('customer').get('lastname') email = payload.get('customer').get('email') password = payload.get('password') resource = request.env['res.users'].sudo().create({ 'name': firstname + " " + lastname, 'parent_name': lastname, 'login': email, 'company_ids': [1], 'company_id': 1, 'new_password': password, 'is_company': False, 'groups_id': [9] }) data = { "code": 200, "result": { "id": resource.id, "group_id": 1, "created_at": "2018-04-03 13:35:13", "updated_at": "2018-04-03 13:35:13", "created_in": "Default Store View", "email": email, "firstname": firstname, "lastname": lastname, "store_id": 1, "website_id": 1, "addresses": [], "disable_auto_group_change": 0 } } request.env.cr.execute( 'INSERT INTO res_company_users_rel(user_id, cid) VALUES(' + str(resource.id) + ', 1)') if resource: return simple_response(data) else: return invalid_response(data)
def get(self, model=None, id=None, **payload): ioc_name = model model = request.env[self._model].sudo().search( [('model', '=', model)], limit=1) if model: domain, fields, offset, limit, order = extract_arguments( payload) data = request.env[model.model].sudo().search_read( domain=domain, fields=['id', 'name', 'description', 'price', 'public_categ_ids'], offset=offset, limit=limit, order=order) if data: return valid_response(data) else: return valid_response(data) return invalid_response('invalid object model', 'The model %s is not available in the registry.' % ioc_name)
def log_out(self, **post): """.""" _token = request.env['api.access_token'] access_token = request.httprequest.headers.get('access_token') access_token = _token.search([('token', '=', access_token)]) if not access_token: info = "No access token was provided in request!" error = 'no_access_token' _logger.error(info) return invalid_response(400, error, info) for token in access_token: token.unlink() # Successful response: return valid_response( 200, {"desc": 'token successfully deleted', "delete": True} )
def categories(self, **payload): # str(json.loads(payload.get('request')).get('_appliedFilters')[0].get('value').get('eq')) # == 2 --> root categories request_json = json.loads(payload.get('request')) # Check if detail of category query_json = json.loads(payload.get('request')).get('query') if query_json: specific_url_key = \ json.loads(payload.get('request')).get('query').get('bool').get('filter').get('bool').get('must')[0].get( 'terms').get('url_key')[0] int_specific_url_key = int(specific_url_key) # Find category categories = request.env['product.public.category'].sudo().search_read( domain=[('id', '=', int_specific_url_key)], fields=['id', 'name', 'display_name', 'parent_id', 'child_id', 'parent_path', 'sequence'], offset=None, limit=None, order=None) # child_id=[] # get_sub_categ = "SELECT parent_path from product_public_category where parent_path LIKE '%/"+str(int_specific_url_key)+"/%'" # for val_get_sub_categ in get_sub_categ: # val_get_sub_categ = val_get_sub_categ.split("/") # while "" in val_get_sub_categ: # val_get_sub_categ.remove("") # if str(val_get_sub_categ[-1]) != str(int_specific_url_key): # categories_sub = request.env['product.public.category'].sudo().search([('public_categ_ids', '=', id)]) # child_id.append() print("LINE 447") print(categories) if categories: parent_id = 2 response = JSONTypes.categories_to_response(categories, 2, parent_id, self.category_offset) return simple_response(response) else: return invalid_response({ "error": 500 }) applied_filters = json.loads(payload.get('request')).get('_appliedFilters') applied_filter = applied_filters[0] # Check if detail of category with slug if applied_filter.get('attribute') == "slug": slug = applied_filter.get('value').get('eq') requested_id = int(slug.split("-")[-1]) - self.category_offset # Find category categories = request.env['product.public.category'].sudo().search_read( domain=[('id', '=', requested_id)], fields=['id', 'name', 'display_name', 'parent_id', 'child_id'], offset=None, limit=None, order=None) if categories: parent_id = 2 response = JSONTypes.categories_to_response(categories, 2, parent_id, self.category_offset) return simple_response(response) else: return invalid_response({ "error": 500 }) if applied_filter.get('attribute') == "url_key" or ( len(applied_filters) == 1 and applied_filter.get('attribute') == "is_active"): parent_id = 2 else: parent_id = applied_filter.get('value').get('eq') if parent_id == 2 or parent_id is None: # Root categories categories = request.env['product.public.category'].sudo().search_read( domain=[('parent_id', '=', False)], fields=['id', 'name', 'display_name', 'parent_id', 'child_id'], offset=None, limit=None, order=None) if categories: response = JSONTypes.categories_to_response(categories, 2, parent_id, self.category_offset) return simple_response(response) else: return invalid_response({ "error": 500 }) else: categories = request.env['product.public.category'].sudo().search_read( domain=[('parent_id', '=', parent_id - self.category_offset)], fields=['id', 'name', 'display_name', 'parent_id', 'child_id'], offset=None, limit=None, order=None) if categories: response = JSONTypes.categories_to_response(categories, 3, parent_id, self.category_offset) return simple_response(response) else: return invalid_response({ "error": 500 })
def cart_create(self, **payload): if request.session.uid: user_data = request.env['res.users'].sudo().search_read( domain=[('id', '=', request.session.uid)], fields=['partner_id'], offset=None, limit=1, order=None ) partner_id = int(user_data[0].get('partner_id')[0]) sale_order = request.env['sale.order'].sudo().create({ 'currency_id': 1, 'date_order': datetime.now(), 'name': 'SO', 'partner_id': partner_id, 'partner_invoice_id': partner_id, 'partner_shipping_id': partner_id, 'picking_policy': 'direct', 'pricelist_id': 1, 'warehouse_id': 1, 'state': 'draft', 'team_id': 2, }) if sale_order: return simple_response( { "code": 200, "result": str(sale_order.id) } ) else: return invalid_response( { "code": 500, } ) else: sale_order = request.env['sale.order'].sudo().create({ 'currency_id': 1, 'date_order': datetime.now(), 'name': 'SO', 'partner_id': 4, 'partner_invoice_id': 4, 'partner_shipping_id': 4, 'picking_policy': 'direct', 'pricelist_id': 1, 'warehouse_id': 1, 'state': 'draft', 'team_id': 2, }) if sale_order: return simple_response( { "code": 200, "result": str(sale_order.id) } ) else: return invalid_response( { "code": 500, } )
def edit_profile(self, **payload): body = request.httprequest.get_data() body_json = json.loads(body.decode("utf-8")) user_data = request.env['res.users'].sudo().search_read( domain=[('id', '=', request.session.uid)], fields=['login', 'partner_id'], offset=None, limit=1, order=None )[0] partner_id = user_data.get('partner_id')[0] partner_data = request.env['res.partner'].sudo().search_read( domain=[('id', '=', partner_id)], fields=[ 'id', 'email', 'name', 'phone', 'company_name', 'commercial_company_name', 'vat', 'street', 'street2', 'city', 'zip', 'country_id', 'state_id', ], offset=None, limit=1, order=None )[0] firstname = body_json.get('customer').get('firstname') lastname = body_json.get('customer').get('lastname') email = body_json.get('customer').get('email') address = body_json.get('customer').get('addresses')[0] if not lastname: lastname = address.get('lastname') city = address.get('city') country_id = address.get('country_id') postcode = address.get('postcode') street = address.get('street')[0] street2 = address.get('street')[1] request.env['res.partner'].sudo().search([('id', '=', partner_id)]).write({ 'name': firstname + ' ' + lastname, 'email': email, 'street': street, 'city': city, 'zip': postcode, 'street2': street2 + ';' + country_id, }) if payload.get('email') != partner_data.get('email'): # Running this will cause to expire the token on web session (web module) request.env['res.users'].sudo().search([('id', '=', request.session.uid)]).write({ 'login': email, }) data = request.env['res.users'].sudo().search_read(domain=[('id', '=', request.session.uid)], fields=['id', 'login'], offset=None, limit=1, order=None) if data: split_result = partner_data.get('name').split() name = split_result[0] lastname = " ".join(split_result[1:]) if partner_data.get('street2'): split_result_street = partner_data.get('street2').split(';') street2 = split_result_street[0] if len(split_result_street) > 1: country_id = split_result_street[1] else: country_id = False else: street2 = '' country_id = False response_data = { "code":200, "result": self.user_json( partner_data.get('id'), # id user_data.get('login'), # email name, # name lastname, # lastname partner_data.get('street'), # street street2, #street2 partner_data.get('city'), # city partner_data.get('zip'), # zip country_id, # country_id ) } return simple_response(response_data, 200) else: return invalid_response(data)
def profile(self, **payload): user_data = request.env['res.users'].sudo().search_read( domain=[('id', '=', request.session.uid)], fields=['login', 'partner_id'], offset=None, limit=1, order=None )[0] partner_data = request.env['res.partner'].sudo().search_read( domain=[('id', '=', user_data.get('partner_id')[0])], fields=[ 'id', 'email', 'name', 'phone', 'company_name', 'commercial_company_name', 'vat', 'street', 'street2', 'city', 'zip', 'country_id', 'state_id', ], offset=None, limit=1, order=None )[0] if partner_data: split_result = partner_data.get('name').split() name = split_result[0] lastname = " ".join(split_result[1:]) if partner_data.get('street2'): split_result_street = partner_data.get('street2').split(';') street2 = split_result_street[0] if len(split_result_street) > 1: country_id = split_result_street[1] else: country_id = False else: street2 = '' country_id = False street = partner_data.get('street') if not street: street = None city = partner_data.get('city') if not city: city = None zip = partner_data.get('zip') if not zip: zip = None response_data = { "code":200, "result": self.user_json( partner_data.get('id'), # id user_data.get('login'), # email name, # name lastname, # lastname street, # street street2, # street2 city, # city zip, # zip country_id, # country_id ) } return simple_response(response_data, 200) else: return invalid_response({})
def categories(self, **payload): #str(json.loads(payload.get('request')).get('_appliedFilters')[0].get('value').get('eq')) # == 2 --> root categories request_json = json.loads(payload.get('request')) # Check if detail of category query_json = json.loads(payload.get('request')).get('query') if query_json: specific_url_key = json.loads(payload.get('request')).get( 'query').get('bool').get('filter').get('bool').get( 'must')[0].get('terms').get('url_key')[0] int_specific_url_key = int(specific_url_key) # Find category categories = request.env['product.public.category'].sudo( ).search_read( domain=[('id', '=', int_specific_url_key)], fields=['id', 'name', 'display_name', 'parent_id', 'child_id'], offset=None, limit=None, order=None) if categories: parent_id = 2 response = JSONTypes.categories_to_response( categories, 2, parent_id, self.category_offset) return simple_response(response) else: return invalid_response({"error": 500}) applied_filters = json.loads( payload.get('request')).get('_appliedFilters') applied_filter = applied_filters[0] # Check if detail of category with slug if applied_filter.get('attribute') == "slug": slug = applied_filter.get('value').get('eq') requested_id = int(slug.split("-")[-1]) - self.category_offset # Find category categories = request.env['product.public.category'].sudo( ).search_read( domain=[('id', '=', requested_id)], fields=['id', 'name', 'display_name', 'parent_id', 'child_id'], offset=None, limit=None, order=None) if categories: parent_id = 2 response = JSONTypes.categories_to_response( categories, 2, parent_id, self.category_offset) return simple_response(response) else: return invalid_response({"error": 500}) if applied_filter.get('attribute') == "url_key" or ( len(applied_filters) == 1 and applied_filter.get('attribute') == "is_active"): parent_id = 2 else: parent_id = applied_filter.get('value').get('eq') if parent_id == 2 or parent_id is None: # Root categories categories = request.env['product.public.category'].sudo( ).search_read( domain=[('parent_id', '=', False)], fields=['id', 'name', 'display_name', 'parent_id', 'child_id'], offset=None, limit=None, order=None) if categories: response = JSONTypes.categories_to_response( categories, 2, parent_id, self.category_offset) return simple_response(response) else: return invalid_response({"error": 500}) else: categories = request.env['product.public.category'].sudo( ).search_read( domain=[('parent_id', '=', parent_id - self.category_offset)], fields=['id', 'name', 'display_name', 'parent_id', 'child_id'], offset=None, limit=None, order=None) if categories: response = JSONTypes.categories_to_response( categories, 3, parent_id, self.category_offset) return simple_response(response) else: return invalid_response({"error": 500})
def categories(self, **payload): #str(json.loads(payload.get('request')).get('_appliedFilters')[0].get('value').get('eq')) # == 2 --> root categories request_json = json.loads(payload.get('request')) # Check if detail of category query_json = json.loads(payload.get('request')).get('query') if query_json: specific_url_key = json.loads(payload.get('request')).get('query').get('bool').get('filter').get('bool').get('must')[0].get('terms').get('url_key')[0] int_specific_url_key = int(specific_url_key) # Find category categories = request.env['product.public.category'].sudo().search_read( domain=[('id', '=', int_specific_url_key)], fields=['id', 'name', 'display_name', 'parent_id', 'child_id'], offset=None, limit=None, order=None) if categories: parent_id = 2 response = self.categories_to_response(categories, 2, parent_id) return simple_response(response) else: return invalid_response({ "error": 500 }) applied_filters = json.loads(payload.get('request')).get('_appliedFilters') applied_filter = applied_filters[0] # Check if detail of category with slug if applied_filter.get('attribute') == "slug": slug = applied_filter.get('value').get('eq') requested_id = int(slug.split("-")[-1]) - self.category_offset # Find category categories = request.env['product.public.category'].sudo().search_read( domain=[('id', '=', requested_id)], fields=['id', 'name', 'display_name', 'parent_id', 'child_id'], offset=None, limit=None, order=None) if categories: parent_id = 2 response = self.categories_to_response(categories, 2, parent_id) return simple_response(response) else: return invalid_response({ "error": 500 }) if applied_filter.get('attribute') == "url_key" or (len(applied_filters) == 1 and applied_filter.get('attribute') == "is_active"): parent_id = 2 else: parent_id = applied_filter.get('value').get('eq') if parent_id == 2: # Root categories categories = request.env['product.public.category'].sudo().search_read( domain=[('parent_id', '=', False)], fields=['id', 'name', 'display_name', 'parent_id', 'child_id'], offset=None, limit=None, order=None) if categories: response = self.categories_to_response(categories, 2, parent_id) return simple_response(response) else: return invalid_response({ "error": 500 }) else: categories = request.env['product.public.category'].sudo().search_read( domain=[('parent_id', '=', parent_id - self.category_offset)], fields=['id', 'name', 'display_name', 'parent_id', 'child_id'], offset=None, limit=None, order=None) if categories: response = self.categories_to_response(categories, 3, parent_id) return simple_response(response) else: return invalid_response({ "error": 500 }) response = { "took":1, "timed_out": False, "_shards":{ "total":5, "successful":5, "skipped":0, "failed":0 }, "hits":{ "total":2, "max_score": None, "hits":[ { "_index":"vue_storefront_catalog_1552559102", "_type":"category", "_id":"21", "_score": None, "_source":{ "path":"1/2/20/21", "is_active": True, "level":3, "product_count":0, "children_count":"4", "parent_id": parent_id, "name":"Tops" + str(json.loads(payload.get('request')).get('_appliedFilters')[0].get('value').get('eq')), "id":21, "url_path":"women/tops-women/tops-21", "url_key":"tops-21", "children_data":[ { "id":23 }, { "id":24 }, { "id":25 }, { "id":26 } ] }, "sort":[ 1 ] }, { "_index":"vue_storefront_catalog_1552559102", "_type":"category", "_id":"22", "_score": None, "_source":{ "path":"1/2/20/22", "is_active": True, "level":3, "product_count":0, "children_count":"2", "parent_id": parent_id, "name":"Bottoms", "id":22, "url_key":"bottoms-22", "children_data":[ { "id":27 }, { "id":28 } ], "url_path":"women/bottoms-women/bottoms-22" }, "sort":[ 2 ] } ] } } return simple_response(response) response = { "items": [ { "id": 27, "parent_id": 2, "name": "Category without childs", "is_active": True, "position": 5, "level": 2, "product_count": 2, "entity_type_id": 3, "attribute_set_id": 3, "children_count": 0, "request_path": "accessories/shoes.html", "children_data": [ ], "created_at": "2017-11-06 12:16:41", "updated_at": "2017-11-06 12:16:42", "path": "1/2/29", "available_sort_by": [ ], "include_in_menu": False, "display_mode": "PAGE", "is_anchor": "0", "url_key": "promotions-29", "url_path": "promotions/promotions-29", "slug": "promotions-29", "tsk": 1551705224325 } ], "total": 3, "start": 1, "perPage": 3, "aggregations": [ ] } return simple_response(response) data = request.env['product.public.category'].sudo().search_read( domain=[('parent_id', '=', False)], fields=['id', 'name', 'display_name', 'parent_id', 'child_id'], offset=None, limit=None, order=None) if data: return valid_response(data) else: return invalid_response(data)
def products(self, **payload): # Detect specific category requested_id = -1 applied_filters = json.loads(payload.get('request')).get('_appliedFilters') for applied_filter in applied_filters: if applied_filter.get('attribute') == "category_ids": ins = applied_filter.get('value').get('in') if len(ins) == 1: slug = applied_filter.get('value').get('in')[0] requested_id = int(slug.split("-")[-1]) - self.category_offset domain = [] if requested_id != -1: domain = [('public_categ_ids', 'in', [requested_id])] data = request.env['product.template'].sudo().search_read( domain=domain, fields=[ 'id', 'name', 'description', 'list_price', 'public_categ_ids', 'default_code', 'attribute_line_ids' ], offset=None, limit=None, order=None) if data: products = [] for element in data: # Preparing data for "configurable_options" variants_array = [] attribute_line_ids = element.get('attribute_line_ids') for attribute_line_id in attribute_line_ids: variant = request.env['product.template.attribute.line'].sudo().search_read( domain=[('id', '=', attribute_line_id)], fields=['id', 'value_ids', 'attribute_id'], offset=None, limit=None, order=None)[0] value_ids = variant['value_ids'] variant['attributes'] = [] for value_id in value_ids: attribute = request.env['product.attribute.value'].sudo().search_read( domain=[('id', '=', value_id)], fields=['name', 'html_color'], offset=None, limit=None, order=None) variant['attributes'].append(attribute) variants_array.append(variant) # Preparing data for "configurable_children" # "product.attribute.value.product.product.rel" relates products with attribute values # find products for current template configurable_childrens = request.env['product.product'].sudo().search_read( domain=[('product_tmpl_id', '=', element.get('id'))], fields=['id', 'attribute_value_ids'], offset=None, limit=None, order=None) configurable_children_array = [] for configurable_children in configurable_childrens: configurable_children['list_price'] = element.get('list_price') configurable_children['attributes'] = [] value_ids = configurable_children['attribute_value_ids'] for value_id in value_ids: attribute = request.env['product.attribute.value'].sudo().search_read( domain=[('id', '=', value_id)], fields=['id', 'name', 'attribute_id'], offset=None, limit=None, order=None) configurable_children['attributes'].append(attribute) configurable_children_array.append( configurable_children ) products.append(self.productJSON( element.get('name'), element.get('id'), element.get('default_code'), element.get('list_price'), element.get('attribute_line_ids'), variants_array, configurable_children_array, )) return valid_response(products) else: return invalid_response(data)
def token2(self, **post): body = request.httprequest.get_data() body_json = json.loads(body.decode("utf-8")) _token = request.env['api.access_token'] db = 'odoo' #params = ['db', 'username', 'password'] #params = {key: post.get(key) for key in params if post.get(key)} #db, username, password = db, post.get('username'), post.get('password') username = body_json.get('username') password = body_json.get('password') if not all([db, username, password]): # Empty 'db' or 'username' or 'password: error_info = { "code": 500, "result": "You did not sign in correctly or your account is temporarily disabled." } return simple_response(error_info, 400) return invalid_response(400, 'missing error', 'either of the following are missing [db, username,password]') # Login in odoo database: try: request.session.authenticate(db, username, password) except Exception as e: # Invalid database: info = "The database name is not valid {}".format((e)) error = 'invalid_database' _logger.error(info) error_info = { "code": 500, "result": "You did not sign in correctly or your account is temporarily disabled." } return simple_response(error_info, 400) return invalid_response(400, error, info) uid = request.session.uid # odoo login failed: if not uid: info = "authentication failed" error = 'authentication failed' _logger.error(info) error_info = { "code": 500, "result": "You did not sign in correctly or your account is temporarily disabled." } return simple_response(error_info, 400) return invalid_response(401, error, info) # Generate tokens access_token = _token.find_one_or_create_token( user_id=uid, create=True) # Successful response: return simple_response( { "code": 200, "result": access_token, "meta": { "refreshToken": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjEzOSJ9.a4HQc2HODmOj5SRMiv-EzWuMZbyIz0CLuVRhPw_MrOM" } }, 200, ) return werkzeug.wrappers.Response( status=200, content_type='application/json; charset=utf-8', headers=[('Cache-Control', 'no-store'), ('Pragma', 'no-cache')], response=json.dumps({ 'uid': uid, 'user_context': request.session.get_context() if uid else {}, 'company_id': request.env.user.company_id.id if uid else None, 'access_token': access_token, 'expires_in': self._expires_in, }), )