Skip to Content
Odoo Меню
  • Увійти
  • Спробуйте це безкоштовно
  • Додатки
    Фінанси
    • Бухоблік
    • Виставлення рахунку
    • Витрати
    • Електронні таблиці (BI)
    • Документи
    • Підпис
    Продажі
    • CRM
    • Продажі
    • POS Магазин
    • POS Ресторан
    • Підписки
    • Оренда
    Веб-сайти
    • Конструктор веб-сайту
    • Електронна комерція
    • Блог
    • Форум
    • Живий чат
    • Електронне навчання
    Ланцюг поставок
    • Склад
    • Виробництво
    • PLM
    • Купівлі
    • Технічне обслуговування
    • Якість
    Кадри
    • Співробітники
    • Рекрутинг
    • Відпустки
    • Оцінювання
    • Рекомендації
    • Автотранспорт
    Маркетинг
    • Маркетинг соцмереж
    • Email-маркетинг
    • SMS-маркетинг
    • Події
    • Автом. маркетингу
    • Опитування
    Послуги
    • Проект
    • Табелі
    • Виїзне обслуговування
    • Служба підтримки
    • Планування
    • Призначення
    Продуктивність
    • Обговорення
    • Схвалення
    • IoT
    • IP-телефонія
    • База знань
    • WhatsApp
    Сторонні модулі Odoo Studio Платформа Odoo Cloud
  • Сфери
    Роздрібна торгівля
    • Книжковий магазин
    • Магазин одягу
    • Магазин меблів
    • Продуктовий магазин
    • Магазин будівельних матеріалів
    • Магазин іграшок
    Food & Hospitality
    • Бар та паб
    • Ресторан
    • Фастфуд
    • Guest House
    • Дистриб'ютор напоїв
    • Hotel
    Нерухомість
    • Real Estate Agency
    • Архітектурна фірма
    • Будівництво
    • Управління нерухомістю
    • Садівництво
    • Асоціація власників нерухомості
    Консалтинг
    • Бухгалтерська компанія
    • Партнер Odoo
    • Агенція маркетингу
    • Юридична фірма
    • Придбання Талантів
    • Аудит та сертифікація
    Виробництво
    • Textile
    • Metal
    • Меблі
    • Їжа
    • Brewery
    • Корпоративні подарунки
    Здоров'я & Фітнес
    • Спортивний клуб
    • Оптика
    • Фітнес-центр
    • Практики здоров'я
    • Аптека
    • Салон краси
    Trades
    • Ремонтник
    • IT-обладнання та Підтримка
    • Системи сонячної енергії
    • Shoe Maker
    • Cleaning Services
    • HVAC Services
    Інші
    • Nonprofit Organization
    • Екологічна агенція
    • Оренда білбордів
    • Фотографія
    • Лізинг велосипедів
    • Реселлер програмного забезпечення
    Browse all Industries
  • Спільнота
    Навчання
    • Навчальний посібник
    • Документація
    • Сертифікації
    • Тренування
    • Блог
    • Подкаст
    Сприяйте Освіті
    • Програма навчання
    • Бізнес гра Scale Up!
    • Відвідайте Odoo
    Отримайте програмне забезпечення
    • Завантаження
    • Порівняйте версії
    • Релізи
    Співпрацюйте
    • Github
    • Форум
    • Події
    • Переклади
    • Стати партнером
    • Services for Partners
    • Зареєструйте вашу бухгалтерську фірму
    Отримайте послуги
    • Знайдіть партнера
    • Знайдіть бухгалтера
    • Зустріньтеся з консультантом
    • Послуги з впровадження
    • Референси клієнтів
    • Підтримка
    • Оновлення
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Отримати демо
  • Ціни
  • Допомога

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Бухоблік
  • Склад
  • PoS
  • Проект
  • MRP
All apps
Вам необхідно зареєструватися, щоб взаємодіяти зі спільнотою.
All Posts Люди Значки
Мітки (View all)
odoo accounting v14 pos v15
Про цей форум
Вам необхідно зареєструватися, щоб взаємодіяти зі спільнотою.
All Posts Люди Значки
Мітки (View all)
odoo accounting v14 pos v15
Про цей форум
Допомога

Programmatically add products to a cart – Odoo 13

Підписатися

Отримуйте сповіщення про активність щодо цієї публікації

Це запитання позначене
javascriptsalesale.orderecommercewebsite
1 Відповісти
9672 Переглядів
Аватар
Marcus

I have a custom module with a form. Based on the answers inside this form I’m generating order line. After user sends this form I’m creating sale order with all products from the generated order line.

So from JavaScript I’m sending an JSON with products to buy:

order_data = [{product_id: 1, amount: 10, …},{product_id: 2, …}, …];

note = ‘’;

this._rpc({

        route: '/api/create_order',

        params: { order_products: order_data, note: note }

    }).then((data) => {

        window.location = '/contactus-thank-you';

    }).catch((error) => {

        console.error(error);

    });

 

And then inside Python I’m creating sale order based on the JSON:

@http.route('/api/create_order', type='json', auth='user', website=True)

def create_order(self, **kw):

    uid = http.request.env.context.get('uid')

    partner_id = http.request.env['res.users'].search([('id','=',uid)]).partner_id.id

    

    order_products = kw.get('order_products', [])

    note = kw.get('note', '')

    order_line = []

 

    for product in order_products:

 

        amount = 0

        if 'custom_amount' in product:

            amount = product['custom_amount']

        else:

            amount = product['amount']

 

        if amount > 0:

            order_line.append(

                (0, 0, {

                    'product_id': product['product_id'],

                    'product_uom_qty': amount,

                }))

 

    order_data = {

        'name': http.request.env['ir.sequence'].with_user(SUPERUSER_ID).next_by_code('sale.order') or _('New'),

        'partner_id': partner_id,

        'order_line': order_line,

        'note': note,

    }

 

    result_insert_record = http.request.env['sale.order'].with_user(SUPERUSER_ID).create(order_data)

    return result_insert_record.id

 

But instead of generating sale order directly I need to use workflow from Odoo’s eCommerce addon. That way user can edit for example delivery address, choose payment etc. So I think I just need to put all the product inside a cart programmatically and then rest will be taken care of by Odoo built-in functionality.

But how? I’ve tried to find something inside Odoo’s source code but it is quite hard to grasp anything.

1
Аватар
Відмінити
Аватар
Paresh Wagh
Найкраща відповідь

Hi Andrzej:

The eCommerce module leverages the same models that are used by the regular Sales app i.e. sale.order, sale.order.line, etc. It creates a Quotation in the backend (with the Website tagged onto the Order) as soon as the user gets into checkout mode.

TIP: You can check this out by adding items to the shopping cart, getting into checkout mode and then checking the list of Quotations/Orders in the backend by removing the default filter criteria.

0
Аватар
Відмінити
Marcus
Автор

I tried setting 'website_id' in the sale order but user does not see anything inside their cart. It must be something more to it.

Paresh Wagh

You're right. This needs more research. I think what you are attempting to do is to get into the workflow before the quotation is created.

Mike Cordero

Hi, Was this ever solved?

Marcus
Автор

Hi Mike, yes I did finally solve this. Check my thread on stackoverflow

https://stackoverflow.com/questions/63034005/programmatically-add-products-to-a-cart-odoo-13/63244596#63244596

Mike Cordero

Great find.

Since I couldn't add a follow-up comment in stackoverflow, I'm placing it here:

I'm having a hard time trying to put all the pieces together to establish the following:

I've modified the website_sale.products_item template to display just the products and replaced product_price with a One2many field that I've added to the product_template model (inherited) which displays the allowed quantity available for each product.

Looking for a way to then take those quantities per product, pass them to a javascript that will determine if the selected quantities for each product exist in an allowed combination table.

My ultimate goal is to have the client select the allowed amount per product(all on the same page), click a button that will add the items to the cart (and correct quantities) in one step and take them to the cart, then finish off with the regular process.

I'm not too keen on the process of executing the javascript part from within a button in xml, and stitching the /api/create_order controller route to the sale_get_order() script above..

Any guidance in the right direction is truly appreciated.

Marcus
Автор

It is a little bit hard to tell without any code sample.

But I would avoid using JavaScript for handling logic if possible. Especially if those limits must be enforced (customer can easily modify JS).

I would write a custom controller that you would call from JavaScript (when button is clicked) - similar to a script from my original question.

Controller then would take care of the logic and checking if given values are correct. Next it would call sale_get_order() to get or create new order. Then you could add order lines to the order generated by sale_get_order. Lastly controller can redirect customer to a cart webpage.

Enjoying the discussion? Don't just read, join in!

Create an account today to enjoy exclusive features and engage with our awesome community!

Реєстрація
Related Posts Відповіді Переглядів Дія
Javascript error Odoo 13 e-commerce/website
javascript ecommerce website 13
Аватар
Аватар
1
лист. 19
5401
Website Information
sale ecommerce website v9
Аватар
0
лют. 17
3756
create a Button on the home page of website
javascript ecommerce website website_sale OWL
Аватар
0
серп. 24
2210
Pass data between controller and js
javascript ecommerce controller website eCommerce
Аватар
Аватар
1
лют. 22
3638
How to submit an element of an radio list in website? Javascript event problem.
javascript ecommerce website website_sale odoo12
Аватар
0
лют. 21
3286
Спільнота
  • Навчальний посібник
  • Документація
  • Форум
Open Source
  • Завантаження
  • Github
  • Runbot
  • Переклади
Послуги
  • Хостинг Odoo.sh
  • Підтримка
  • Оновлення
  • Кастомні доробки
  • Навчання
  • Знайдіть бухгалтера
  • Знайдіть партнера
  • Стати партнером
Про нас
  • Наша компанія
  • Торгові активи
  • Зв'яжіться з нами
  • Вакансії
  • Події
  • Подкаст
  • Блог
  • Клієнти
  • Юридичні документи • Конфіденційність
  • Безпека
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo - це набір програм для роботи з відкритим кодом, які охоплюють всі ваші потреби компанії: CRM, електронна комерція, бухгалтерський облік, склад, точка продажу, управління проектами тощо.

Унікальна пропозиція Odoo - це одночасно дуже проста у використанні та повністю інтегрована.

Website made with

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now