Перейти к содержимому
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
Об этом форуме
Помощь

Sale Order from Custom Module

Подписаться

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

Этот вопрос был отмечен
actioninvoicecreatecustomSO
10 Ответы
10274 Представления
Аватар
Gregory Gillis

I am making a custom module to track service tickets for a repair shop. I would like to be able to open the custom module tickets and be able to create a SO/Invoice from within the ticket so they are linked. 

ie. Custom brings item in for repair. While technician is working, they can add items required for the repair to the repair ticket and will update the sales order without changing screens. We can then use a button in the top corner to see the attached sales order and invoices. This way we just pull up a service ticket and can see what items are being used, what the customer owes, and what payments that have made on that specific ticket. 


I have tried mimicking code from the sales module as a template, but cannot get the custom module to make a sales order when our ticket is created so that they are linked-the repair ticket shows as source document for SO.

Using Odoo 12 Community, and coding manually without access to the Studio module. 

0
Аватар
Отменить
Sehrish

To implement your changes you just need to know how to customize existing modules, have a look into: https://learnopenerp.tumblr.com/

Аватар
Jake Robinson
Лучший ответ

Hi Gregory, 

The easiest way would be to add three new fields on the ticket model:

A sale order many2one (Hook the create method to create a blank sale order when a ticket is created)

A sale order line many2many related to the sale orders order_line field.

An invoice many2many related to the sale orders invoice_ids field.

With these three fields you can show a link to the sale order and its invoices, as well as show and manipulate the sale orders order lines.

0
Аватар
Отменить
Gregory Gillis
Автор

The three fields you mentioned are easy enough and I can add those in. However, I am lost with "Hook the create method to create a blank sale order when a ticket is created". Any chance you can provide an example of that code? Thanks.

Jake Robinson

In the ticket model (assuming the ticket has a partner field called partner_id and the tickets sale field is call sale_order_id):

def create(self, vals):

res = super(TicketModelClass, self).create(vals)

res.sale_order_id = self.env['sale.order'].create({'partner_id': res.partner_id.id})

return res

Gregory Gillis
Автор

I am now getting this error message when I applied that code. Here is snippet of my models.py:

sale_order_id = fields.Many2one('sale.order')

def create(self, vals):

res = super(TicketModelClass, self).create(vals)

res.sale_order_id = self.env['sale.order'].create({'partner_id': res.customer})

return res

sale_order_line = fields.Many2many(related="sale_order_id.order_line")

invoice_id = fields.Many2many(related="sale_order_id.invoice_ids")

(I am using 'customer' for the customer/partner in the model)

And here is the error I am getting when I refresh Odoo and reload the server:

2018-11-12 16:00:11,799 26612 ERROR coding werkzeug: Error on request:

Traceback (most recent call last):

File "/usr/local/lib/python3.6/site-packages/werkzeug/serving.py", line 205, in run_wsgi

execute(self.server.app)

File "/usr/local/lib/python3.6/site-packages/werkzeug/serving.py", line 193, in execute

application_iter = app(environ, start_response)

File "/mylocation/odoo12/odoo/service/server.py", line 339, in app

return self.app(e, s)

File "/mylocation/odoo12/odoo/service/wsgi_server.py", line 128, in application

return application_unproxied(environ, start_response)

File "/mylocation/odoo12/odoo/service/wsgi_server.py", line 117, in application_unproxied

result = odoo.http.root(environ, start_response)

File "/mylocation/odoo12/odoo/http.py", line 1317, in __call__

return self.dispatch(environ, start_response)

File "/mylocation/odoo12/odoo/http.py", line 1290, in __call__

return self.app(environ, start_wrapped)

File "/usr/local/lib/python3.6/site-packages/werkzeug/wsgi.py", line 599, in __call__

return self.app(environ, start_response)

File "/mylocation/odoo12/odoo/http.py", line 1489, in dispatch

response = self.get_response(httprequest, result, explicit_session)

File "/mylocation/odoo12/odoo/http.py", line 287, in __exit__

elif self.registry:

File "/mylocation/odoo12/odoo/http.py", line 378, in registry

return odoo.registry(self.db)

File "/mylocation/odoo12/odoo/__init__.py", line 78, in registry

return modules.registry.Registry(database_name)

File "/mylocation/odoo12/odoo/modules/registry.py", line 62, in __new__

return cls.new(db_name)

File "/mylocation/odoo12/odoo/modules/registry.py", line 86, in new

odoo.modules.load_modules(registry._db, force_demo, status, update_module)

File "/mylocation/odoo12/odoo/modules/loading.py", line 422, in load_modules

force, status, report, loaded_modules, update_module, models_to_check)

File "/mylocation/odoo12/odoo/modules/loading.py", line 318, in load_marked_modules

perform_checks=perform_checks, models_to_check=models_to_check

File "/mylocation/odoo12/odoo/modules/loading.py", line 196, in load_module_graph

registry.setup_models(cr)

File "/mylocation/odoo12/odoo/modules/registry.py", line 267, in setup_models

model._setup_fields()

File "/mylocation/odoo12/odoo/models.py", line 2596, in _setup_fields

field.setup_full(self)

File "/mylocation/odoo12/odoo/fields.py", line 483, in setup_full

self._setup_related_full(model)

File "/mylocation/odoo12/odoo/fields.py", line 534, in _setup_related_full

raise TypeError("Type of related field %s is inconsistent with %s" % (self, field))

TypeError: Type of related field repaircenter.ticket.sale_order_line is inconsistent with sale.order.order_line - - -

Gregory Gillis
Автор

If I comment out the sale_order_line, Odoo loads, but whenever I create a new ticket, I get the following error:

TypeError: create() missing 1 required positional argument: 'vals'

I have tried changing the customer and partner_id but didn't make a difference.

Jake Robinson

Two issues, the first is that I forgot to add the @api.model on the create method. This just goes on the line above def create...

The second is that the many2many fields need a comodel. In the many2one, the 'sale.order' you have written tells the system that that many2one is for sale orders. You need to do the same for the many2manys. Use comodel_name='sale.order.line' and comodel_name='account.invoice' in their definitions.

Gregory Gillis
Автор

I am now getting this error: TypeError: create() got an unexpected keyword argument 'context'

Here is the updated code:

sale_order_line = fields.Many2many('sale.order.line')

invoices_id = fields.Many2one('account.invoice')

sale_order_id = fields.Many2one('sale.order')

@api.model

def create(self):

res = super(RepairTicket, self).create(vals)

res.sale_order_id = self.env['sale.order'].create({'partner_id': res.partner_id.id})

return res

sale_order_line_id = fields.Many2many('sale.order.line')

invoice_id = fields.Many2many(related="sale_order_id.invoice_ids")

If I change the @api.model to @api.multi, I get this error instead:

NameError: name 'vals' is not defined

Gregory Gillis
Автор

EDIT: I realized I as missing vals from the def create(self, vals). I added it back in and am back to this error:

TypeError: create() missing 1 required positional argument: 'vals'

Аватар
Gregory Gillis
Автор Лучший ответ

After fiddling some more,  I was able to make some headway. I am able to create a new sales order whenever I create a new ticket in my custom module using the following code.

    sale_order_id = fields.Many2one('sale.order')
@api.model
def create(self, vals):
res = super(RepairTicket, self).create(vals)
res.sale_order_id = self.env['sale.order'].create({'partner_id': res.partner_id, 'origin':res.id})
return res
(Note, I had to add a new field: partner_id=fields.Integer(related="customer.id") to get the id number form my customer field. I also added in the ticket number to show as the source document in the order.)
However, I cannot get it to pull in the sale order lines. Whenever I use any of the code above for sale_order_line or sale.order.line it prevents odoo from starting when I reboot. Need to be able to edit/view sale order lines on the same screen if possible. Thanks.

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

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

Регистрация
Похожие посты Ответы Просмотры Активность
Custom invoice template per client
invoice custom template
Аватар
Аватар
Аватар
2
сент. 24
12334
Error Findings
invoice error create
Аватар
0
нояб. 23
2047
Strip string from a field with defined separator in invoice report
invoice custom reports
Аватар
0
мар. 22
2
Error creating an invoice
invoice error create
Аватар
Аватар
1
апр. 20
4260
How to pass custom field value from account.invoice to account.invoice.line on Create() method? Решено
invoice field custom
Аватар
1
нояб. 19
6784
Сообщество
  • Видео уроки
  • Документация
  • Форум
Открытый исходный код
  • Скачать
  • 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