Skip to Content
Odoo मेन्यू
  • Sign in
  • मुफ़्त में आज़माएं
  • ऐप्लिकेशन
    फ़ाइनेंस
    • अकाउंटिंग
    • इनवॉइसिंग
    • एक्सपेंस
    • स्प्रेडशीट (बीआई)
    • डॉक्यूमेंट्स
    • साइन
    सेल्स
    • सीआरएम
    • सेल्स
    • पीओएस शॉप
    • पीओएस रेस्टोरेंट
    • सब्सक्रिप्शन
    • रेंटल
    वेबसाइट
    • वेबसाइट बिल्डर
    • ई-कॉमर्स
    • ब्लॉग
    • फ़ोरम
    • लाइव चैट
    • ई-लर्निंग
    सप्लाई चेन
    • इन्वेंट्री
    • मैन्युफ़ैक्चरिंग
    • पीएलएम
    • परचेज़
    • मेंटेनेंस
    • क्वालिटी
    मानव संसाधन
    • कर्मचारी
    • रिक्रूटमेंट
    • टाइम ऑफ़
    • अप्रेज़ल
    • रेफ़रल
    • फ़्लीट
    मार्केटिंग
    • सोशल मार्केटिंग
    • ईमेल मार्केटिंग
    • एसएमएस मार्केटिंग
    • इवेंट
    • मार्केटिंग ऑटोमेशन
    • सर्वे
    सेवाएं
    • प्रोजेक्ट
    • टाइमशीट
    • फ़ील्ड सर्विस
    • हेल्पडेस्क
    • प्लानिंग
    • अपॉइंटमेंट
    प्रॉडक्टिविटी
    • डिस्कस
    • अप्रूवल
    • आईओटी
    • वीओआईपी
    • नॉलेज
    • WhatsApp
    तीसरे पक्ष के ऐप्लिकेशन Odoo स्टूडियो Odoo क्लाउड प्लेटफ़ॉर्म
  • इंडस्ट्री
    रीटेल
    • बुक स्टोर
    • क्लोदिंग स्टोर
    • फ़र्नीचर स्टोर
    • ग्रॉसरी स्टोर
    • हार्डवेयर स्टोर
    • टॉय स्टोर
    Food & Hospitality
    • बार और पब
    • रेस्टोरेंट
    • फ़ास्ट फ़ूड
    • Guest House
    • बेवरिज डिस्ट्रीब्यूटर
    • होटल
    रियल एस्टेट
    • Real Estate Agency
    • आर्किटेक्चर फ़र्म
    • कंसट्रक्शन
    • एस्टेट मैनेजमेंट
    • गार्ड्निंग
    • प्रॉपर्टी ओनर असोसिएशन
    कंसल्टिंग
    • अकाउंटिंग फ़र्म
    • Odoo पार्टनर
    • मार्केटिंग एजेंसी
    • लॉ फ़र्म
    • टैलेंट ऐक्विज़िशन
    • ऑडिट & सर्टिफ़िकेशन
    मैन्युफ़ैक्चरिंग
    • टेक्सटाइल
    • Metal
    • फ़र्नीचर
    • फ़ूड
    • Brewery
    • कॉर्पोरेट गिफ़्ट
    हेल्थ & फिटनेस
    • स्पोर्ट्स क्लब
    • आईवियर स्टोर
    • फिटनेस सेंटर
    • वेलनेस प्रैक्टिशनर
    • फॉर्मेसी
    • हेयर सैलून
    Trades
    • Handyman
    • आईटी हॉर्डवेयर और सपोर्ट
    • Solar Energy Systems
    • Shoe Maker
    • Cleaning Services
    • HVAC Services
    अन्य
    • Nonprofit Organization
    • एन्वायरमेंटल एजेंसी
    • बिलबोर्ड रेंटल
    • फ़ोटोग्राफी
    • बाइक लीजिंग
    • सॉफ़्टवेयर रीसेलर
    Browse all Industries
  • कम्यूनिटी
    सीखें
    • ट्यूटोरियल्स
    • दस्तावेज़
    • सर्टिफ़िकेशन
    • ट्रेनिंग
    • ब्लॉग
    • पॉडकास्ट
    शिक्षा को बढ़ावा दें
    • एजुकेशन प्रोग्राम
    • स्केल अप! बिजनेस गेम
    • 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:

  • सीआरएम
  • e-Commerce
  • लेखांकन
  • इन्वेंटरी
  • PoS
  • प्रोजेक्ट
  • MRP
All apps
You need to be registered to interact with the community.
All Posts People Badges
टैग (View all)
odoo accounting v14 pos v15
About this forum
You need to be registered to interact with the community.
All Posts People Badges
टैग (View all)
odoo accounting v14 pos v15
About this forum
Help

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

Subscribe

Get notified when there's activity on this post

This question has been flagged
integrationcustomposissuePOS
742 Views
Avatar
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
Avatar
Discard
Enjoying the discussion? Don't just read, join in!

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

Sign up
Related Posts Replies Views Activity
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
Avatar
0
अक्तू॰ 25
2321
Is it possible to integrate Webflow into Odoo? If yes, is there any documentation on this?
integration
Avatar
Avatar
1
नव॰ 25
7138
Can concepts be predefined for Cash In/Out?
POS
Avatar
Avatar
2
सित॰ 25
751
is the odoo API integration available for odoo cloud edition? Solved
integration
Avatar
Avatar
Avatar
Avatar
3
अग॰ 25
5410
Self hosting Odoo custom Solved
custom
Avatar
1
अग॰ 24
2789
कम्यूनिटी
  • ट्यूटोरियल्स
  • दस्तावेज़
  • फ़ोरम
ओपन सोर्स
  • डाउनलोड
  • Github
  • रनबॉट
  • अनुवाद
सेवाएं
  • Odoo.sh Hosting
  • सहायता
  • अपग्रेड
  • कस्टम डेवलपमेंट्स
  • शिक्षा
  • अकाउंटेंट खोजें
  • पार्टनर ढूंढें
  • पार्टनर बनें
हमारे बारे में
  • हमारी कंपनी
  • ब्रांड ऐसेट
  • संपर्क करें
  • नौकरियां
  • इवेंट
  • पॉडकास्ट
  • ब्लॉग
  • ग्राहक
  • लीगल • गोपनीयता
  • सुरक्षा
الْعَرَبيّة 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, बिज़नेस से जुड़े ऐप्लिकेशन का एक कलेक्शन है जो ओपन सोर्स पर आधारित है. इसमें आपकी कंपनी की हर ज़रूरत के लिए ऐप्लिकेशन हैं. जैसे, सीआरएम, ई-कॉमर्स, अकाउंटिंग, इन्वेंट्री, पॉइंट ऑफ़ सेल, प्रोजेक्ट मैनेजमेंट वगैरह.

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