Перейти к содержимому
Odoo Меню
  • Войти
  • Попробовать бесплатно
  • Модули
    Финансы
    • Бухгалтерия
    • Выставление счетов
    • Расходы
    • Таблицы
    • Документооборот
    • Подпись
    Продажи
    • CRM
    • Продажи
    • POS Магазин
    • POS Ресторан
    • Подписки
    • Аренда
    Вебсайты
    • Конструктор вебсайтов
    • eCommerce
    • Блог
    • Форум
    • Онлайн-чат
    • Электронное обучение
    Логистика
    • Склад
    • Производство
    • PLM
    • Закупки
    • Обслуживание
    • Качество
    Отдел кадров
    • Сотрудники
    • Подбор персонала
    • Отпуска
    • Оценка персонала
    • Реферальная программа
    • Автопарк
    Маркетинг
    • SMM
    • E-mail рассылки
    • СМС рассылки
    • Мероприятия
    • Автоматизация маркетинга
    • Опросы
    Услуги
    • Проекты
    • Табели
    • Выездной сервис
    • Поддержка
    • Планирование
    • Встречи
    Продуктивность
    • Обсуждения
    • Согласование
    • IoT
    • VoIP-телефония
    • Knowledge
    • WhatsApp
    Сторонние приложения Модуль Студия Odoo Платформа Odoo Cloud
  • Индустрии
    Розничная торговля
    • Книжный магазин
    • Магазин одежды
    • Мебельный магазин
    • Продуктовый магазин
    • Строительный магазин
    • Магазин игрушек
    Гостинично-ресторанный бизнес
    • Бар и паб
    • Ресторан
    • Фастфуд
    • Гостевой дом
    • Дистрибьютор напитков
    • Отель
    Недвижимость
    • Агентство недвижимости
    • Архитектурное бюро
    • Строительство
    • Управление недвижимостью
    • Ландшафтный дизайн
    • Товарищество собственников жилья
    Консалтинг
    • Бухгалтерская фирма
    • Партнер Odoo
    • Маркетинговое агентство
    • Юридическая фирма
    • Подбор персонала
    • Аудиторское бюро
    Производство
    • Текстиль
    • Металл
    • Мебель
    • Продукты питания
    • Пивоварня
    • Корпоративные сувениры
    Здоровье и фитнес
    • Спортивный комплекс
    • Магазин оптики
    • Фитнес-клуб
    • Велнес-центр
    • Аптека
    • Салон красоты
    Услуги
    • Специалист по бытовым услугам
    • Продажа и обслуживание IT-оборудования
    • Солнечные энергосистемы
    • Производство обуви
    • Клининг
    • Системы ОВКВ
    Прочее
    • Некоммерческая организация
    • Консалтинг в сфере устойчивого развития
    • Аренда рекламных щитов
    • Бизнес по фотосъемке
    • Прокат велосипедов
    • Реселлер программного обеспечения
    Все индустрии
  • Community
    Обучение
    • Видео уроки
    • Документация
    • Сертификация
    • Тренинг
    • Блог
    • Подкаст
    Образование и развитие
    • Образовательная программа
    • Деловая игра Scale Up!
    • Экскурсия в офис Odoo
    ПО
    • Скачать
    • Сравнить версии
    • Релизы
    Сотрудничество
    • Github
    • Форум
    • Мероприятия
    • Перевод
    • Стать партнером
    • Услуги для партнеров
    • Зарегистрировать бухгалтерскую фирму
    Услуги
    • Найти партнера
    • Найти бухгалтера
    • Встреча с экспертом
    • Услуги по внедрению
    • Отзывы клиентов
    • Поддержка
    • Обновления
    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
Чтобы взаимодействовать с сообществом, необходимо зарегистрироваться.
Все посты Люди Значки
Теги (Смотреть все)
odoo accounting v14 pos v15
Об этом форуме
Чтобы взаимодействовать с сообществом, необходимо зарегистрироваться.
Все посты Люди Значки
Теги (Смотреть все)
odoo accounting v14 pos v15
Об этом форуме
Помощь

How to add fields from res.partner model as dependencies in product.template model for calculation purposes in Odoo v18 Enterprise?

Подписаться

Получайте уведомления о появлении активности в этом посте

Этот вопрос был отмечен
productmodelsinventorycustomizationodoo
2 Ответы
5308 Представления
Аватар
Zuhair

Hello everyone,

I am working on an Odoo v18 Enterprise implementation and have created several custom fields in the res.partner model, including:

  • x_container_fee (type: monetary)
  • x_customs_duty (type: float)
  • x_handling_charge (type: monetary)
  • x_vendor_type (type: selection)


Additionally, I have created a custom field x_total_cost (type: monetary) in the product.template model.


For calculation purposes, I would like to reference the fields I created in the res.partner model when computing values in the product.template model.


Is it possible to include fields from res.partner as dependencies in product.template? If so, How can this be achieved?

Thank you in advance!

0
Аватар
Отменить
Аватар
Zuhair
Автор Лучший ответ

Hello,

I need to calculate the total cost of products based on certain charges related to international vendors. These charges include:

  1. Container Fee (for the space the product occupies in a shipping container),
  2. Customs Duty (a percentage charge on the base price of the product),
  3. Handling Charge (additional fees for handling the product).

I created those fields on the res.partner model for international suppliers. I want to use these values in the product.template model to compute the total cost of the product (without profit margin).

In the res.partner model I have created those fields:

  1. x_container_fee (Type: Monetary): This field stores the container fee per square meter (or unit of space) that an international vendor charges (vary depending on country).
  2. x_customs_duty (Type: Float): This field represents the customs duty rate (as a percentage) that is applied to products from this international vendor.
  3. x_handling_charge (Type: Monetary): This field stores any additional handling charge imposed by the vendor.
  4. x_vendor_type (Type: Selection): This field indicates whether the vendor is local or international. Only for international vendors do the additional charges (customs, container fee, and handling charge) apply.

In the product.template model:

  1. x_container_space (Type: Float): This field represents the space (in square meters) the product occupies in the shipping container.
  2. x_total_cost (Type: Monetary): This field stores the final total cost of the product, which includes the base price and the additional charges from the international vendor (without the profit margin).

Calculation Process:

For each product, I want to compute the total cost as follows:

  1. Base Price: Start with the product's base price (either list price or cost price).
  2. International Supplier Charges: If the vendor is marked as international, I want to apply:
    • Customs Duty: Calculate the customs duty as a percentage.
    • Container Fee: I will insert on the each product base on the area it will occupy in the container.
    • Handling Charge: Add any fixed handling charges from the vendor.
  3. Final Total Cost: Sum up these values to get the total cost of the product without including the profit margin.

Code I have use:

from odoo import api, fields, models

class ProductTemplate(models.Model):
    _inherit = "product.template"

    # Link to the vendor (res.partner) model
    vendor_id = fields.Many2one('res.partner', string='Vendor', help="Reference to the vendor from res.partner.")

    # Related fields from the vendor
    x_container_fee = fields.Monetary(related='vendor_id.x_container_fee', string='Container Fee', readonly=True)
    x_customs_duty = fields.Float(related='vendor_id.x_customs_duty', string='Customs Duty', readonly=True)
    x_handling_charge = fields.Monetary(related='vendor_id.x_handling_charge', string='Handling Charge', readonly=True)

    # Space occupied by the product in the container (in square meters or units)
    x_container_space = fields.Float(string='Container Space (m²)', help="Space occupied by the product in square meters.")

    # Field to store the calculated total cost
    x_total_cost = fields.Monetary(string='Total Cost', compute='_compute_total_cost', store=True, help="Total cost of the product without profit margin.")

    @api.depends('list_price', 'x_container_fee', 'x_customs_duty', 'x_handling_charge', 'x_container_space')
    def _compute_total_cost(self):
        for product in self:
            # Base price paid to the vendor (list_price or cost price)
            base_price = product.list_price

            # Initialize additional charges
            total_customs_duty = 0
            total_container_fee = 0
            total_handling_charge = 0

            # Check if the vendor is assigned and marked as international
            if product.vendor_id and product.vendor_id.x_vendor_type == 'international':
                # Calculate customs duty (percentage of the base price)
                customs_duty_rate = product.x_customs_duty or 0
                total_customs_duty = base_price * customs_duty_rate / 100

                # Calculate container fee based on the space occupied
                container_fee_per_sqft = product.x_container_fee or 0
                space_occupied = product.x_container_space or 1  # Default to 1 if not specified
                total_container_fee = container_fee_per_sqft * space_occupied

                # Add container handling charge
                total_handling_charge = product.x_handling_charge or 0

            # Calculate total cost (without profit margin)
            product.x_total_cost = base_price + total_customs_duty + total_container_fee + total_handling_charge


 When I created the total cost and put the  ​Python code I need to put the ​Dependencies to which I am having the error:
Unknown field “x_container_fee” in dependency “x_container_fee”


0
Аватар
Отменить
Аватар
Niyas Raphy (Walnut Software Solutions)
Лучший ответ

Hi,
First you need a relation between res.partner table and product.template model and you have to finalize on this one. You will introduce a new field to partner inside the product or will you use the seller_ids field ? Could you give some clarity on this.

Thanks

0
Аватар
Отменить
Не оставайтесь в стороне – присоединяйтесь к обсуждению!

Создайте аккаунт сегодня, чтобы получить доступ к эксклюзивным функциям и стать частью нашего замечательного сообщества!

Регистрация
Похожие посты Ответы Просмотры Активность
what is ordered quantities and deliverd quantities in product type. Решено
product inventory odoo
Аватар
Аватар
Аватар
Аватар
3
апр. 24
5636
update quantity on hand Решено
product inventory quantity odoo
Аватар
Аватар
Аватар
4
мая 25
26833
Product on hand quantity is not equal with product move calculation odoo12
stock product inventory odoo
Аватар
0
сент. 21
3027
i need to know how to change the location of a product which was stored in RM to FG stock or vice versa in odoo v8
product inventory odoo odooV8
Аватар
Аватар
1
июл. 21
4057
Maintenance/Repair - External
product inventory maintenance odoo v17
Аватар
Аватар
1
авг. 24
2995
Сообщество
  • Видео уроки
  • Документация
  • Форум
Открытый исходный код
  • Скачать
  • Github
  • Runbot
  • Перевод
Услуги
  • Хостинг Odoo.sh
  • Поддержка
  • Обновление
  • Индивидуальные решения по доработке
  • Образование
  • Найти бухгалтера
  • Найти партнера
  • Стать партнером
О нас
  • Наша компания
  • Активы бренда
  • Cвяжитесь с нами
  • Вакансии
  • Мероприятия
  • Подкаст
  • Блог
  • Клиенты
  • Правовые документы • Конфиденциальность
  • Безопасность
الْعَرَبيّة 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, E-commerce, Бухгалтерия, Склад, POS, управление проектами и др.

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