def reset_password(self, **payload): body = request.httprequest.get_data() payload = json.loads(body.decode("utf-8")) email = payload.get('email') user_ids = request.env['res.users'].sudo().search_read( domain=[('login', '=', email)], fields=['id'], offset=None, limit=1, order=None ) try: user_ids.action_reset_password() return simple_response({ "code": 200, "result": "OK" }) except: return simple_response({ "code": 200, "result": "OK" })
def log_in(self, **post): body = request.httprequest.get_data() body_json = json.loads(body.decode("utf-8")) _token = request.env['api.access_token'] db = 'odoo' 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) # 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) 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) # 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": "refreshToken" } }, 200, )
def stock_check(self, **payload): response = { "code": 200, "result": { "item_id": 580, "product_id": 580, "stock_id": 1, "qty": 53, "is_in_stock": True, "is_qty_decimal": False, "show_default_notification_message": False, "use_config_min_qty": True, "min_qty": 0, "use_config_min_sale_qty": 1, "min_sale_qty": 1, "use_config_max_sale_qty": True, "max_sale_qty": 10000, "use_config_backorders": True, "backorders": 0, "use_config_notify_stock_qty": True, "notify_stock_qty": 1, "use_config_qty_increments": True, "qty_increments": 0, "use_config_enable_qty_inc": True, "enable_qty_increments": False, "use_config_manage_stock": True, "manage_stock": True, "low_stock_date": None, "is_decimal_divided": False, "stock_status_changed_auto": 0 } } return simple_response(response)
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 payment_methods(self, **payload): data = { "code":200, "result": [ { "code":"cashondelivery", "title":"Contra reembolso" } ] } return simple_response(data)
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 order(self, **payload): body = request.httprequest.get_data() body_json = json.loads(body.decode("utf-8")) cart_id = int(body_json.get('cart_id')) request.env['sale.order'].sudo().search([ ('id', '=', cart_id) ]).write({ 'confirmation_date': datetime.now(), 'state': 'sale', }) data = { "code": 200, "result": "OK" } return simple_response(data)
def shipping_methods(self, **payload): body = request.httprequest.get_data() body_json = json.loads(body.decode("utf-8")) data = { "code":200, "result": [ { "carrier_code":"flatrate", "method_code":"flatrate", "carrier_title":"Flat Rate", "method_title":"Gratis", "amount":0, "base_amount":0 ,"available":True, "error_message":"", "price_excl_tax":0, "price_incl_tax":0 } ] } return simple_response(data)
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 cart_update(self, **payload): body = request.httprequest.get_data() payload = json.loads(body.decode("utf-8")) # We need: product id # We have: product template id and product_attribute_value_id s # Use received product_tmpl_id to retrieve product ids from product.product received_product_tmpl_id = int(payload.get('cartItem').get('sku')) configurable_item_options = payload.get('cartItem').get('product_option').get('extension_attributes').get('configurable_item_options') desired_options_array = [] for configurable_item_option in configurable_item_options: desired_options_array.append( int(configurable_item_option.get('option_value')) ) product_templates = request.env['product.template'].sudo().search_read( domain=[('id', '=', received_product_tmpl_id)], fields=['name', 'list_price'], offset=None, limit=None, order=None) product_template_name = product_templates[0]["name"] price_unit = product_templates[0]["list_price"] products = request.env['product.product'].sudo().search_read( domain=[('product_tmpl_id', '=', received_product_tmpl_id)], fields=['id', 'attribute_value_ids'], offset=None, limit=None, order=None) desired_product_id = -1 for product in products: actual_options_array = [] value_ids = product['attribute_value_ids'] for value_id in value_ids: actual_options_array.append(value_id) # If product_attribute_value_id s match with the received ones, this product id is the desired one desired = collections.Counter(desired_options_array) == collections.Counter(actual_options_array) if desired: desired_product_id = product['id'] desired_quantity = int(payload.get('cartItem').get('qty')) user_data = request.env['res.users'].sudo().search_read( domain=[('id', '=', request.session.uid)], fields=['partner_id'], offset=None, limit=1, order=None ) order_id = -1 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 ) orders = request.env['sale.order'].sudo().search_read( domain=[('partner_id', '=', user_data[0].get('partner_id')[0])], fields=['id'], offset=None, limit=1, order='create_date DESC' ) order_id = int(orders[0].get('id')) else: order_id = int(payload.get('cartItem').get('quoteId')) data = request.env['sale.order.line'].sudo().search_read( domain=[ ('order_id', '=', order_id), ('product_id', '=', desired_product_id), ], fields=['id'], offset=None, limit=1, order='create_date DESC' ) # If line exists if data: # Update quantity request.env['sale.order.line'].sudo().search([ ('order_id', '=', order_id), ('product_id', '=', desired_product_id), ]).write({ 'product_uom_qty': desired_quantity, }) else: # Create new line order_line = request.env['sale.order.line'].sudo().create({ 'order_id': order_id, 'product_id': desired_product_id, 'product_uom_qty': desired_quantity, 'customer_lead': 0.0, 'name': product_template_name, 'price_unit': price_unit, }) response = { "code": 200, "result": {} } return simple_response( response )
def cart(self, **payload): cart_id = int(payload.get('cartId')) cart_lines = request.env['sale.order.line'].sudo().search_read( domain=[('order_id', '=', cart_id)], fields=[ 'id', 'name', 'invoice_status', 'price_unit', 'price_subtotal', 'price_tax', 'price_total', 'price_reduce', 'price_reduce_taxinc', 'price_reduce_taxexcl', 'discount', 'product_id', 'product_uom_qty', ], offset=None, limit=None, order='id DESC' ) items = [] for line in cart_lines: product_id = line['product_id'][0] # Prepare configurable_item_options product_data = request.env['product.product'].sudo().search_read( domain=[('id', '=', product_id)], fields=['attribute_value_ids'], offset=None, limit=None, order=None) configurable_item_options = [] value_ids = product_data[0]['attribute_value_ids'] for value_id in value_ids: attribute_value = request.env['product.attribute.value'].sudo().search_read( domain=[('id', '=', value_id)], fields=['attribute_id'], offset=None, limit=None, order=None) attribute_id = attribute_value[0]['attribute_id'][0] configurable_item_options.append( self.configurable_item_option_json( str(attribute_id), int(value_id) ) ) items.append(self.cart_item_json( line['name'], product_id, configurable_item_options, payload.get('cartId'), )) return simple_response( { "code": 200, "result": items, "cart_id": int(payload.get('cartId')), } )
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 attributes_json(self, **payload): result = { "took":0, "timed_out": False, "_shards":{ "total":5, "successful":5, "skipped":0, "failed":0 }, "hits":{ "total":4, "max_score":0, "hits":[ { "_index":"vue_storefront_catalog_1552559102", "_type":"attribute", "_id":"145", "_score":0, "_source":{ "is_wysiwyg_enabled": False, "is_html_allowed_on_front": True, "used_for_sort_by": False, "is_filterable": True, "is_filterable_in_search": False, "is_used_in_grid": False, "is_visible_in_grid": False, "is_filterable_in_grid": False, "position":0, "apply_to":[ ], "is_searchable":"0", "is_visible_in_advanced_search":"0", "is_comparable":"0", "is_used_for_promo_rules":"1", "is_visible_on_front":"0", "used_in_product_listing":"0", "is_visible": True, "scope":"global", "attribute_id":145, "attribute_code":"erin_recommends", "frontend_input":"boolean", "entity_type_id":"4", "is_required": False, "options":[ { "label":"Yes", "value":"1" }, { "label":"No", "value":"0" } ], "is_user_defined": True, "default_frontend_label":"Erin Recommends", "frontend_labels": None, "backend_type":"int", "source_model":"Magento\\Eav\\Model\\Entity\\Attribute\\Source\\Boolean", "default_value":"", "is_unique":"0", "validation_rules":[ ], "id":145, "tsk":1551705231251 } }, { "_index":"vue_storefront_catalog_1552559102", "_type":"attribute", "_id":"142", "_score":0, "_source":{ "is_wysiwyg_enabled": False, "is_html_allowed_on_front": True, "used_for_sort_by": False, "is_filterable": True, "is_filterable_in_search": False, "is_used_in_grid": False, "is_visible_in_grid": False, "is_filterable_in_grid": False, "position":0, "apply_to":[ ], "is_searchable":"0", "is_visible_in_advanced_search":"0", "is_comparable":"0", "is_used_for_promo_rules":"1", "is_visible_on_front":"0", "used_in_product_listing":"1", "is_visible": True, "scope":"global", "attribute_id":142, "attribute_code":"size", "frontend_input":"select", "entity_type_id":"4", "is_required": False, "options":[ { "label":" ", "value":"" }, { "label":"55 cm", "value":"91" }, { "label":"XS", "value":"167" }, { "label":"65 cm", "value":"92" }, { "label":"S", "value":"168" }, { "label":"75 cm", "value":"93" }, { "label":"M", "value":"169" }, { "label":"6 foot", "value":"94" }, { "label":"L", "value":"170" }, { "label":"8 foot", "value":"95" }, { "label":"XL", "value":"171" }, { "label":"10 foot", "value":"96" }, { "label":"28", "value":"172" }, { "label":"29", "value":"173" }, { "label":"30", "value":"174" }, { "label":"31", "value":"175" }, { "label":"32", "value":"176" }, { "label":"33", "value":"177" }, { "label":"34", "value":"178" }, { "label":"36", "value":"179" }, { "label":"38", "value":"180" } ], "is_user_defined": True, "default_frontend_label":"Size", "frontend_labels": None, "backend_type":"int", "source_model":"Magento\\Eav\\Model\\Entity\\Attribute\\Source\\Table", "default_value":"91", "is_unique":"0", "validation_rules":[ ], "id":142, "tsk":1551705231251 } }, { "_index":"vue_storefront_catalog_1552559102", "_type":"attribute", "_id":"93", "_score":0, "_source":{ "is_wysiwyg_enabled": False, "is_html_allowed_on_front": True, "used_for_sort_by": False, "is_filterable": True, "is_filterable_in_search": False, "is_used_in_grid": True, "is_visible_in_grid": False, "is_filterable_in_grid": True, "position":0, "apply_to":[ "simple", "virtual", "configurable" ], "is_searchable":"0", "is_visible_in_advanced_search":"0", "is_comparable":"0", "is_used_for_promo_rules":"1", "is_visible_on_front":"0", "used_in_product_listing":"1", "is_visible": True, "scope":"global", "attribute_id":93, "attribute_code":"color", "frontend_input":"select", "entity_type_id":"4", "is_required": False, "options":[ { "label":" ", "value":"" }, { "label":"Black", "value":"49" }, { "label":"Blue", "value":"50" }, { "label":"Brown", "value":"51" }, { "label":"Gray", "value":"52" }, { "label":"Green", "value":"53" }, { "label":"Lavender", "value":"54" }, { "label":"Multi", "value":"55" }, { "label":"Orange", "value":"56" }, { "label":"Purple", "value":"57" }, { "label":"Red", "value":"58" }, { "label":"White", "value":"59" }, { "label":"Yellow", "value":"60" } ], "is_user_defined": True, "default_frontend_label":"Color", "frontend_labels": None, "backend_type":"int", "source_model":"Magento\\Eav\\Model\\Entity\\Attribute\\Source\\Table", "default_value":"49", "is_unique":"0", "validation_rules":[ ], "id":93, "tsk":1551705231251 } }, { "_index":"vue_storefront_catalog_1552559102", "_type":"attribute", "_id":"77", "_score":0, "_source":{ "is_wysiwyg_enabled": False, "is_html_allowed_on_front": False, "used_for_sort_by": True, "is_filterable": True, "is_filterable_in_search": False, "is_used_in_grid": False, "is_visible_in_grid": False, "is_filterable_in_grid": False, "position":0, "apply_to":[ "simple", "virtual", "bundle", "downloadable", "configurable" ], "is_searchable":"1", "is_visible_in_advanced_search":"1", "is_comparable":"0", "is_used_for_promo_rules":"0", "is_visible_on_front":"0", "used_in_product_listing":"1", "is_visible": True, "scope":"global", "attribute_id":77, "attribute_code":"price", "frontend_input":"price", "entity_type_id":"4", "is_required": True, "options":[ ], "is_user_defined": False, "default_frontend_label":"Price", "frontend_labels": None, "backend_type":"decimal", "backend_model":"Magento\\Catalog\\Model\\Product\\Attribute\\Backend\\Price", "is_unique":"0", "validation_rules":[ ], "id":77, "tsk":1551705231251 } } ] } } return simple_response(result) attributes = [] attributes.append(self.attributeJSON("93", "color", "Color")) attributes.append(self.attributeJSON("142", "size", "Size")) return valid_response(attributes)
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 shipping_information(self, **payload): body = request.httprequest.get_data() body_json = json.loads(body.decode("utf-8")) cart_id = int(payload.get('cartId')) order = request.env['sale.order'].sudo().search_read( domain=[ ('id', '=', cart_id), ], fields=[ 'id', 'confirmation_date', 'amount_total', 'amount_tax', 'amount_untaxed', ], offset=None, limit=1, order='create_date DESC' )[0] order_id = int(order.get('id')) confirmation_date = str(order.get('confirmation_date')) amount_total = order.get('amount_total') amount_tax = order.get('amount_tax') amount_untaxed = order.get('amount_untaxed') data = { "code": 200, "result": { "payment_methods": [ { "code": "cashondelivery", "title": "Cash On Delivery" }, { "code": "checkmo", "title": "Check / Money order" } ], "totals": { "grand_total": 45.8, "base_grand_total": amount_total, "subtotal": 48, "base_subtotal": 48, "discount_amount": -8.86, "base_discount_amount": -8.86, "subtotal_with_discount": 39.14, "base_subtotal_with_discount": 39.14, "shipping_amount": 5, "base_shipping_amount": 5, "shipping_discount_amount": 0, "base_shipping_discount_amount": 0, "tax_amount": amount_tax, "base_tax_amount": amount_tax, "weee_tax_applied_amount": None, "shipping_tax_amount": 0, "base_shipping_tax_amount": 0, "subtotal_incl_tax": amount_total, "shipping_incl_tax": 5, "base_shipping_incl_tax": 5, "base_currency_code": "USD", "quote_currency_code": "USD", "items_qty": 2, "items": [], "total_segments": [ { "code": "subtotal", "title": "Subtotal", "value": amount_total }, { "code": "shipping", "title": "Envío", "value": 0 }, { "code": "tax", "title": "I.V.A.", "value": amount_tax, "area": "taxes", "extension_attributes": { "tax_grandtotal_details": [ { "amount": amount_tax, "rates": [ { "percent": "23", "title": "VAT23" } ], "group_id": 1 } ] } }, { "code": "grand_total", "title": "Grand Total", "value": amount_total, "area": "footer" } ] } } } return simple_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 order_history(self, **payload): user_data = request.env['res.users'].sudo().search_read( domain=[('id', '=', request.session.uid)], fields=['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=[ 'name', 'id', 'email', 'phone', 'company_name', 'commercial_company_name', 'vat', 'street', # street 'street2', 'city', # city 'zip', # postcode 'country_id', 'state_id', ], offset=None, limit=1, order=None )[0] split_result = partner_data.get('name').split() name = split_result[0] lastname = " ".join(split_result[1:]) orders = request.env['sale.order'].sudo().search_read( domain=[ ('partner_id', '=', user_data.get('partner_id')[0]), ('state', '=', 'sale'), ], fields=[ 'id', 'confirmation_date', 'amount_total', 'amount_tax', 'amount_untaxed', ], offset=None, limit=None, order='create_date DESC' ) orders_array = [] for order in orders: order_id = int(order.get('id')) confirmation_date = str(order.get('confirmation_date')) amount_total = order.get('amount_total') amount_tax = order.get('amount_tax') amount_untaxed = order.get('amount_untaxed') # Order items cart_lines = request.env['sale.order.line'].sudo().search_read( domain=[('order_id', '=', order_id)], fields=[ 'id', 'name', 'invoice_status', 'price_unit', 'price_subtotal', # row total without tax 'price_tax', # row total of tax 'price_total', # row total with tax 'price_reduce', 'price_reduce_taxexcl', # price unit without tax (also can be price_unit) 'price_reduce_taxinc', # price unit with tax 'discount', 'product_id', 'product_uom_qty', # quantity ], offset=None, limit=None, order='id DESC' ) items_array = [] for line in cart_lines: product_id = line['product_id'][0] name = line['name'] sku = line['product_id'][0] price_unit_without_tax = line['price_reduce_taxexcl'] price_unit_with_tax = line['price_reduce_taxinc'] row_total_tax = line['price_tax'] row_total_without_tax = line['price_subtotal'] row_total_with_tax = line['price_total'] quantity = int(line['product_uom_qty']) items_array.append(JSONTypes.order_item_json( order_id, confirmation_date, name, sku, price_unit_without_tax, quantity, row_total_with_tax, 0, )) orders_array.append(JSONTypes.order_json( order_id, confirmation_date, amount_total, amount_tax, amount_untaxed, 0, 0, items_array, name, lastname, partner_data.get('city'), # city partner_data.get('zip'), # postcode partner_data.get('street'), # street )) return simple_response( { "code": 200, "result": { "items": orders_array, "search_criteria": { "filter_groups": [ { "filters": [ { "field": "customer_email", "value": "*****@*****.**", "condition_type": "eq" } ] } ] }, "total_count": 50 } } )
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, }), )