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

Odoo POS: Preventing stale card_payment attempts without breaking order cancel/retry flow

Подписаться

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

Этот вопрос был отмечен
integrationcustomposissuePOS
724 Представления
Аватар
boris

Hello,

We are working with Odoo 18 Community using a custom-made pos_payment module.

We implemented logic to mark a card_payment attempt to avoid stale orders being executed again on other requests.

This works for preventing duplicate transactions.

However, we ran into a side effect:

  • When an order is canceled in POS and then retried from the frontend, the retry succeeds without sending a request to the server.
  • This seems to happen because the canceled order is still considered “marked,” so the retry logic bypasses the server call.

Question:

How can we adjust the logic so that:

  1. Stale card_payment attempts are still blocked.
  2. Canceled orders can be retried properly, sending the request to the server again.

python

import logging

import requests

from datetime import timedelta

from odoo import models, fields, api

from requests.exceptions import HTTPError

from odoo.exceptions import UserError


_logger = logging.getLogger(__name__)


class PosOrder(models.Model):

    _inherit = 'pos.order'


    fiscal_printed = fields.Boolean(string="Fiscal Printed", default=False)

    is_fiscalized = fields.Boolean(string="Fiscalized", default=False)

    card_payment_attempted = fields.Boolean(string="Card Payment Attempted", default=False)


    @api.model

    def sync_from_ui(self, orders):

        _logger.info("POSCP → received %s orders", len(orders))

        res = super().sync_from_ui(orders)


        # Ensure keys POS expects (prevents JS crash)

        if isinstance(res, dict):

            res.setdefault('pos.order', [])

            res.setdefault('pos.order.line', [])


        # Collect newly created order IDs

        order_ids = [e['id'] for e in res.get('pos.order', []) if isinstance(e, dict) and e.get('id')]

        _logger.info("POSCP → new order IDs from super(): %s", order_ids)


        if not order_ids:

            return res


        # DEBUG: log state/flags for ALL new orders before filtering

        now = fields.Datetime.now()

        for o in self.env['pos.order'].browse(order_ids):

            age = None

            ref_dt = o.date_order or o.create_date

            if ref_dt:

                age = (now - ref_dt).total_seconds()

            pay_mix = [(p.payment_method_id.journal_id.type, float(p.amount)) for p in o.payment_ids]

            _logger.info(

                "POSCP • Order probe id=%s name=%s state=%s is_fiscalized=%s card_payment_attempted=%s "

                "fiscal_printed=%s amount_total=%.2f age_sec=%s payments=%s",

                o.id, o.name, o.state, o.is_fiscalized, o.card_payment_attempted,

                o.fiscal_printed, float(o.amount_total), age, pay_mix

            )


        # Optional: ignore queued orders older than N minutes (UNCOMMENT to enforce)

        # max_age = timedelta(minutes=3)

        def is_fresh(o):

            # base predicate

            ok = (o.state == 'paid' and not o.is_fiscalized and not o.card_payment_attempted)

            # age gate (optional)

            # if ok and (o.date_order or o.create_date):

            #     ok = (now - (o.date_order or o.create_date)) <= max_age

            return ok


        fresh_orders = self.env['pos.order'].browse(order_ids).filtered(is_fresh)

        _logger.info("POSCP → fresh_orders picked: %s", [o.id for o in fresh_orders])


        for order in fresh_orders:

            pay_cash = order.payment_ids.filtered(lambda p: p.payment_method_id.journal_id.type == 'cash')

            pay_other = order.payment_ids.filtered(lambda p: p.payment_method_id.journal_id.type != 'cash')


            _logger.info(

                "POSCP → handling id=%s name=%s cash=%s other=%s attempted=%s fiscalized=%s",

                order.id, order.name,

                [(p.id, float(p.amount)) for p in pay_cash],

                [(p.id, float(p.amount)) for p in pay_other],

                order.card_payment_attempted, order.is_fiscalized

            )


            if pay_other:

                try:

                    _logger.info("POSCP → _send_card_payment(%s)", order.name)

                    order._send_card_payment()

                except UserError:

                    raise

                except Exception as e:

                    _logger.exception("POSCP ✖ card error for %s: %s", order.name, e)

                    raise UserError(f"Card payment failed: {e}")


            if pay_cash:

                try:

                    _logger.info("POSCP → _send_ecr_receipt(%s)", order.name)

                    order._send_ecr_receipt()

                except Exception as e:

                    _logger.exception("POSCP ✖ cash error for %s: %s", order.name, e)

                    raise UserError(f"Cash receipt printing failed: {e}")


            order.write({'fiscal_printed': True})

            self.env.cr.commit()

            _logger.info("POSCP → marked fiscal_printed on id=%s", order.id)


        return res


    def _send_card_payment(self):

        self.ensure_one()

        if self.card_payment_attempted:

            _logger.warning("POSCP ↻ already attempted card for %s – skipping", self.name)

            return

        self.write({'card_payment_attempted': True})

        self.env.cr.commit()

        _logger.info("POSCP → set card_payment_attempted=True for id=%s", self.id)


        cfg = self.session_id.config_id

        url = cfg.card_api_url

        api_key = cfg.card_api_key

        missing = [a for a in ('card_api_url', 'card_api_key') if not getattr(cfg, a)]

        if missing:

            raise ValueError("Missing POS config fields: %s" % ','.join(missing))


        items = [{

            "text1": ln.product_id.name,

            "text2": ln.product_id.description_sale or "",

            "sign": "+",

            "price": float(ln.price_unit),

            "qty": int(ln.qty),

            "percent": int(ln.discount or 0),

            "netto": 0,

        } for ln in self.lines]


        payload = {

            "unicSaleNum": self._get_unic_sale_num(),

            "items": items,

            "payment": {"method": "P", "amountIn": float(self.amount_total)},

        }


        headers = {"Content-Type": "application/json", "X-API-Key": api_key}

        endpoint = url.rstrip('/') + '/api/cardpayment'

        _logger.info("POSCP → POST %s payload=%s", endpoint, payload)


        try:

            resp = requests.post(endpoint, json=payload, headers=headers, timeout=60)

            resp.raise_for_status()

        except HTTPError as httpe:

            status = getattr(httpe.response, 'status_code', None)

            if status in (400, 402):

                try:

                    reason = httpe.response.json().get('error', 'Card was declined')

                except Exception:

                    reason = 'Card was declined'

                # self.write({'card_payment_attempted': False})

                # self.env.cr.commit()

                raise UserError(f"Payment declined: {reason}")

            raise


        data = resp.json()

        _logger.info("POSCP ← card API response: %s", data)


        if data.get('status') in ('declined', 'error', 'failed'):

            reason = data.get('message') or data.get('error') or 'Card was declined'

            raise UserError(f"Payment declined: {reason}")


        self.write({'is_fiscalized': True})

        self.env.cr.commit()

        _logger.info("POSCP → set is_fiscalized=True for id=%s", self.id)

        return data


    def _send_ecr_receipt(self):

        self.ensure_one()

        cfg = self.session_id.config_id

        url = cfg.card_api_url

        api_key = cfg.card_api_key

        if not url or not api_key:

            raise UserError("Missing receipt configuration on POS '%s'" % cfg.name)


        items = [{

            "text1": ln.product_id.name,

            "text2": ln.product_id.description_sale or "",

            "sign": "+",

            "price": float(ln.price_unit),

            "qty": int(ln.qty),

            "percent": int(ln.discount or 0),

            "netto": 0,

        } for ln in self.lines]


        req = {"unicSaleNum": self._get_unic_sale_num(), "items": items}

        headers = {"Content-Type": "application/json", "X-API-Key": api_key}

        endpoint = url.rstrip('/') + '/api/receipt'

        _logger.info("POSCP → POST %s payload=%s", endpoint, req)


        resp = requests.post(endpoint, json=req, headers=headers, timeout=60)

        resp.raise_for_status()

        data = resp.json()

        _logger.info("POSCP ← receipt API response: %s", data)


        webSrv = data.get("WebSrvCmd") or {}

        if webSrv.get("HasErr", False):

            raise UserError("ECR printing failed")


        self.write({'is_fiscalized': True})

        self.env.cr.commit()

        _logger.info("POSCP → set is_fiscalized=True for id=%s", self.id)

        return data


    def _get_unic_sale_num(self):

        self.ensure_one()

        dt = fields.Datetime.now()

        return f"DY{dt.strftime('%y%m%d')}-OP{str(0).zfill(2)}-{str(self.id or 0).zfill(7)}"


Thanks in advance for any pointers or best practices to handle both cases!

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

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

Регистрация
Похожие посты Ответы Просмотры Активность
How to create a custom registration for different types of user and also during registration how to integrate third party apis (ie Yoti for KYC) to complete the KYC
integration custom registration thirdparty apis
Аватар
0
окт. 25
2311
Is it possible to integrate Webflow into Odoo? If yes, is there any documentation on this?
integration
Аватар
Аватар
1
нояб. 25
7087
Can concepts be predefined for Cash In/Out?
POS
Аватар
Аватар
2
сент. 25
724
is the odoo API integration available for odoo cloud edition? Решено
integration
Аватар
Аватар
Аватар
Аватар
3
авг. 25
5328
Self hosting Odoo custom Решено
custom
Аватар
1
авг. 24
2770
Сообщество
  • Видео уроки
  • Документация
  • Форум
Открытый исходный код
  • Скачать
  • 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