Резерв истёк, а оплата пришла позже: проверяем товар перед отгрузкой
Детерминированная модель показывает, как учесть позднюю оплату, не отгрузить уже занятый товар, пережить повтор уведомления и создать новый резерв только после фактического появления остатка.

В этой статье
Если подтверждение оплаты пришло после окончания резерва, факт денег нельзя автоматически превращать в право на отгрузку. Сначала сохраните и проверьте платёж, затем отдельно подтвердите действующий резерв. Если резерв уже снят и товар занял другой заказ, безопасное состояние — paid_needs_stock: оплата учтена, отгрузка запрещена, а следующий шаг выбирается по правилам магазина — новый резерв, замена, ожидание или возврат.
Проверяемая модель ниже разводит финансовое и складское состояния. Она не меняет данные 1С-Битрикс и не изображает штатный обработчик конкретной платёжной системы. Её задача уже: показать, что позднее и повторное уведомление не уводят остаток ниже нуля и не создают отгрузку без товара.
Где возникает разрыв
В актуальной документации 1С-Битрикс по резервированию товаров указано: магазин настраивает момент резервирования и число дней до автоматического снятия резерва, если покупатель не выполняет действий по заказу. При включённом резервировании доступное количество уменьшается в момент резерва, а зарезервированный товар списывается при отгрузке.
Отдельная страница настроек модуля Интернет-магазин перечисляет варианты «при оформлении заказа», «при полной оплате», «при частичной оплате», «при разрешении доставки» и «при отгрузке». На странице также отмечено, что эти настройки недоступны в редакциях «Стандарт» и «Старт». Текущие страницы проверены 10 ноября 2026 года; конкретную установленную версию модулей sale и catalog всё равно нужно сверять на проекте.
Тут есть подвох: платёжный сервис и задача снятия резервов живут по разным часам. Уведомление может обрабатываться после того, как резерв уже освобождён и единица досталась следующему заказу. Время оплаты полезно для разбора, но оно не возвращает физически занятый товар.
Например, документация ЮKassa по входящим уведомлениям предупреждает, что подтверждение платежа может занять от нескольких минут до нескольких часов. Получение уведомления подтверждается HTTP 200; при других кодах сервис продолжает доставку в течение 24 часов от события. Там же рекомендовано проверить текущий статус объекта. Эти условия относятся к ЮKassa и не переносятся на другого провайдера без его документации.
Условия безопасной модели
Среда: CPython 3.12.14, только стандартная библиотека.
В начале доступна одна единица одного товара; каждый сценарий создаёт новый объект Store.
Время задано целыми учебными отметками, а не системными часами. Так ветвление воспроизводится без ожидания.
Резерв, платёж, заказ и отгрузка хранятся раздельно. Ключ повтора — пара из внешнего payment_id и терминального статуса succeeded.
Модель работает только в памяти процесса, не использует сеть, файлы, базу, реальный магазин или платёжный API.
Программа ничего не записывает и не удаляет; после запуска очищать нечего.
Полный воспроизводимый пример
Сохраните код в новом пустом каталоге как late_payment_reservation_lab.py. В нём нет секретов, путей к проекту и операций над рабочими данными.
from __future__ import annotations
from dataclasses import dataclass, field
class StateConflict(RuntimeError):
pass
@dataclass
class Reservation:
order_id: str
expires_at: int | None
state: str = "active"
@dataclass
class Order:
order_id: str
state: str = "new"
payment_id: str | None = None
@dataclass
class Store:
available: int = 1
orders: dict[str, Order] = field(default_factory=dict)
reservations: dict[str, Reservation] = field(default_factory=dict)
processed_payments: dict[tuple[str, str], str] = field(default_factory=dict)
shipments: set[str] = field(default_factory=set)
def place_order(self, order_id: str, *, now: int, expires_at: int) -> str:
if expires_at <= now:
raise ValueError("expires_at must be in the future")
if order_id in self.orders:
return "already_placed"
if self.available < 1:
raise StateConflict("stock_unavailable")
self.available -= 1
self.orders[order_id] = Order(order_id, state="awaiting_payment")
self.reservations[order_id] = Reservation(order_id, expires_at)
return "reserved"
def _release_expired_reservation(self, order_id: str, *, now: int) -> bool:
reservation = self.reservations[order_id]
if (
reservation.state == "active"
and reservation.expires_at is not None
and reservation.expires_at <= now
):
reservation.state = "expired"
self.available += 1
return True
return False
def expire_reservations(self, *, now: int) -> int:
return sum(
self._release_expired_reservation(order_id, now=now)
for order_id in list(self.reservations)
)
def apply_payment(
self,
order_id: str,
*,
payment_id: str,
status: str,
now: int,
) -> str:
if status != "succeeded":
raise ValueError("only succeeded payments are accepted by this model")
key = (payment_id, status)
if key in self.processed_payments:
return f"duplicate:{self.processed_payments[key]}"
order = self.orders[order_id]
if order.payment_id not in (None, payment_id):
raise StateConflict("order_linked_to_another_payment")
self._release_expired_reservation(order_id, now=now)
reservation = self.reservations[order_id]
order.payment_id = payment_id
if reservation.state == "active":
order.state = "paid_reserved"
else:
order.state = "paid_needs_stock"
self.processed_payments[key] = order.state
return order.state
def cancel_unpaid_order(self, order_id: str) -> str:
order = self.orders[order_id]
if order.payment_id is not None:
raise StateConflict("paid_order_requires_separate_decision")
reservation = self.reservations[order_id]
if reservation.state == "active":
reservation.state = "released"
self.available += 1
order.state = "canceled"
return "canceled"
def reconcile_paid_order(self, order_id: str) -> str:
order = self.orders[order_id]
if order.state == "paid_reserved":
return "already_reserved"
if order.state != "paid_needs_stock":
raise StateConflict("order_is_not_waiting_for_stock")
if self.available < 1:
return "still_waiting"
self.available -= 1
self.reservations[order_id] = Reservation(
order_id,
expires_at=None,
state="active",
)
order.state = "paid_reserved"
return "reserved_after_payment"
def create_shipment(self, order_id: str) -> str:
order = self.orders[order_id]
reservation = self.reservations[order_id]
if order.state != "paid_reserved" or reservation.state != "active":
raise StateConflict("shipment_requires_active_reservation")
if order_id in self.shipments:
return "already_created"
reservation.state = "consumed"
order.state = "shipment_created"
self.shipments.add(order_id)
return "created"
def scenario_payment_before_expiry() -> None:
store = Store()
store.place_order("order-a", now=0, expires_at=10)
first = store.apply_payment(
"order-a",
payment_id="payment-a",
status="succeeded",
now=5,
)
repeat = store.apply_payment(
"order-a",
payment_id="payment-a",
status="succeeded",
now=6,
)
shipment = store.create_shipment("order-a")
assert first == "paid_reserved"
assert repeat == "duplicate:paid_reserved"
assert shipment == "created"
assert store.available == 0
assert len(store.shipments) == 1
print(
"on_time: first=paid_reserved repeat=duplicate:paid_reserved "
"shipment=created available=0 shipments=1"
)
def scenario_late_payment_after_stock_taken() -> None:
store = Store()
store.place_order("order-late", now=0, expires_at=10)
assert store.expire_reservations(now=10) == 1
store.place_order("order-next", now=11, expires_at=20)
first = store.apply_payment(
"order-late",
payment_id="payment-late",
status="succeeded",
now=12,
)
repeat = store.apply_payment(
"order-late",
payment_id="payment-late",
status="succeeded",
now=13,
)
waiting = store.reconcile_paid_order("order-late")
try:
store.create_shipment("order-late")
except StateConflict as exc:
blocked = str(exc)
else:
raise AssertionError("shipment must be blocked without a reservation")
assert first == "paid_needs_stock"
assert repeat == "duplicate:paid_needs_stock"
assert waiting == "still_waiting"
assert blocked == "shipment_requires_active_reservation"
assert store.available == 0
assert len(store.shipments) == 0
print(
"late: first=paid_needs_stock repeat=duplicate:paid_needs_stock "
"reconcile=still_waiting shipment=blocked available=0 shipments=0"
)
store.cancel_unpaid_order("order-next")
reserved = store.reconcile_paid_order("order-late")
shipment = store.create_shipment("order-late")
assert reserved == "reserved_after_payment"
assert shipment == "created"
assert store.available == 0
assert len(store.shipments) == 1
print(
"recovered: reconcile=reserved_after_payment shipment=created "
"available=0 shipments=1"
)
def scenario_other_payment_id() -> None:
store = Store()
store.place_order("order-conflict", now=0, expires_at=10)
store.apply_payment(
"order-conflict",
payment_id="payment-1",
status="succeeded",
now=5,
)
try:
store.apply_payment(
"order-conflict",
payment_id="payment-2",
status="succeeded",
now=6,
)
except StateConflict as exc:
result = str(exc)
else:
raise AssertionError("a second payment id must require investigation")
assert result == "order_linked_to_another_payment"
assert store.available == 0
assert len(store.shipments) == 0
print(
"conflict: second_payment=order_linked_to_another_payment "
"available=0 shipments=0"
)
def main() -> None:
scenario_payment_before_expiry()
scenario_late_payment_after_stock_taken()
scenario_other_payment_id()
if __name__ == "__main__":
main()
Запустите файл обычным пользователем:
python3 late_payment_reservation_lab.py
Два последовательных запуска завершились с кодом 0 и дали одинаковый вывод:
on_time: first=paid_reserved repeat=duplicate:paid_reserved shipment=created available=0 shipments=1
late: first=paid_needs_stock repeat=duplicate:paid_needs_stock reconcile=still_waiting shipment=blocked available=0 shipments=0
recovered: reconcile=reserved_after_payment shipment=created available=0 shipments=1
conflict: second_payment=order_linked_to_another_payment available=0 shipments=0
SHA-256 проверенного файла: 8da3b15b277374dcc639f4de263277dae82a76072320de65cc3cce88aaead416.
Что подтвердил прогон
Сценарий | Результат | Инвариант |
|---|---|---|
Оплата до истечения | paid_reserved, одна отгрузка | available=0, shipments=1 |
Оплата после истечения | paid_needs_stock, отгрузка заблокирована | available=0, shipments=0 |
Повтор уведомления | duplicate с прежним исходом | складской остаток и число отгрузок не меняются |
Товар снова появился | новый резерв, затем отгрузка | available=0, shipments=1 |
Другой payment_id | конфликт для разбора | вторая оплата не присваивается молча |
В позднем сценарии заказ order-late теряет резерв в момент 10. В момент 11 единственную единицу резервирует order-next. Подтверждение payment-late приходит в момент 12: заказ становится оплаченным, но остаётся без товара. Повтор в момент 13 возвращает прежний исход, а попытка создать отгрузку останавливается. Только после освобождения единицы другим заказом отдельная сверка создаёт новый резерв.
Модель доказывает ветвление и инварианты на заданных данных. Она не измеряет задержки сети, не проверяет модуль оплаты или обмен с 1С и не является внедрением у клиента. В реальном проекте операции со складом должны быть атомарными или защищёнными версией записи; иначе два процесса смогут одновременно увидеть одну свободную единицу.
Почему paid не равно ready_to_ship
Статус оплаты отвечает на финансовый вопрос: подтверждён ли конкретный платёж, сумма, валюта и получатель. Резерв отвечает на складской вопрос: обещана ли конкретному заказу доступная единица товара или торгового предложения. Отгрузка требует обоих подтверждений. Одна зелёная галочка не должна работать за две — интерфейсам такое нравится, складам заметно меньше.
paid_reserved: платёж подтверждён, действующий резерв найден; можно переходить к правилам отгрузки.
paid_needs_stock: платёж подтверждён, действующего резерва нет; автоматическая отгрузка запрещена.
payment_conflict: заказ уже связан с другим внешним платежом; нужна сверка суммы, валюты, возвратов и платёжного документа.
duplicate: тот же подтверждённый результат уже применён; повтор не создаёт резерв или отгрузку заново.
Состояние paid_needs_stock не предписывает универсальный бизнес-ответ. Для одного магазина допустим новый резерв после фактического пополнения складского остатка, для другого — согласованная замена, частичная отгрузка или возврат. Важно не скрывать выбор за автоматической отметкой «оплачено и готово».
Как перенести механизм в интеграцию 1С-Битрикс
Зафиксируйте редакцию продукта, версии модулей sale и catalog, включённые количественный и складской учёты, правило резервирования и срок снятия. Отдельно укажите товар или торговое предложение и склад.
Свяжите заказ, платёжный документ и внешний payment_id. Номер заказа не заменяет идентификатор операции провайдера, особенно при нескольких попытках оплаты.
Проверяйте подлинность и актуальный статус платежа по правилам конкретного провайдера. Только после этого сохраняйте финансовый факт.
В той же согласованной границе прочитайте состояние резерва. Истёкший или уже использованный резерв не восстанавливайте простым уменьшением остатка задним числом.
Если товара нет, сохраните paid_needs_stock, не устанавливайте автоматически признак «Доставка разрешена» и не создавайте отгрузку. Запишите безопасную причину и сделайте заказ видимым оператору.
Если товар появился, создайте новый резерв атомарно и только затем разрешайте следующий этап. Конкурентная попытка должна получить отказ, а не ту же последнюю единицу.
Защитите повтор по устойчивому ключу платежа и терминального статуса. Письмо покупателю, обмен с 1С, чек и отгрузка имеют собственные ключи и точки возобновления.
Проверьте сценарии на копии проекта: оплата до срока, после срока при нулевом остатке, повтор уведомления, другой payment_id, возврат, частичная оплата и торговое предложение с отдельным остатком.
Не исправляйте расхождение прямым изменением поля в базе: можно обойти события модуля, складские документы и связанный платёжный документ. Не включайте массовый сброс резервов ради одного заказа. Официальная документация отдельно предупреждает, что при активных заказах такой сброс способен привести к двойной отмене резерва и неверному количеству.
Граница с соседними материалами
Если деньги у провайдера есть, а заказ вообще не получил подтверждение, сначала нужен разбор маршрута из материала «Оплата прошла, а заказ остался неоплаченным». Здесь подтверждение уже принято; решается более узкий конфликт между поздней оплатой и истёкшим резервом.
Правила владельца физического, доступного и показываемого количества разобраны в материале «Остаток в 1С и на сайте не совпадает». Новый пример не выбирает источник истины за проект: он проверяет одно переходное состояние заказа.
Критерий приёмки
На тестовой среде позднее подтверждение должно сохранить проверенный платёж, но не создать отгрузку без действующего резерва. Повтор того же уведомления не меняет остаток и не запускает действия второй раз. При нулевом остатке заказ остаётся видимым как paid_needs_stock; после появления товара новый резерв создаётся конкурентно безопасно, и только затем разрешается отгрузка. Другой внешний payment_id не присваивается молча. Если хотя бы одно из этих условий не выполняется, интеграция ещё не готова к автоматическому сценарию.
If payment confirmation arrives after the reservation expires, the fact of payment cannot automatically become a right to ship. First, save and verify the payment, then separately confirm the active reservation. If the reservation has already been released and the item is allocated to another order, the safe state is paid_needs_stock: payment recorded, shipping prohibited, and the next step determined by store rules—new reservation, replacement, waiting, or refund.
The model below separates financial and warehouse states. It does not alter 1C-Bitrix data nor depict the standard handler for a specific payment system. Its purpose is to show that late or duplicate notifications do not drive stock below zero or trigger shipping without available goods.
Where the Gap Occurs
The current 1C-Bitrix documentation on product reservation states: the store configures the moment of reservation and the number of days until automatic release if the buyer takes no action on the order. With reservation enabled, the available quantity decreases at the moment of reservation, and reserved items are deducted upon shipment.
A separate settings page for the Online Store module lists options for "at order placement", "upon full payment", "upon partial payment", "upon delivery approval", and "upon shipment". The page also notes that these settings are unavailable in the "Standard" and "Start" editions. The current pages were verified on November 10, 2026; the specific installed version of the sale and catalog modules must still be verified on the project.
Here lies the catch: the payment service and the reservation release task operate on different timelines. A notification may be processed after the reservation is released and the unit assigned to the next order. Payment time is useful for analysis, but it cannot physically return an already allocated item.
For example, the documentation for YKassa regarding incoming notifications warns that payment confirmation may take from several minutes to several hours. Receipt of a notification is confirmed via HTTP 200; for other codes, the service continues delivery for 24 hours from the event. It is also recommended there to check the current status of the object. These conditions apply to YKassa and are not transferred to another provider without its documentation.
Conditions for the Safe Model
Environment: CPython 3.12.14, standard library only.
Initially, one unit of a single product is available; each scenario creates a new Store object.
Time is set using whole academic timestamps, not system clocks. This allows branching to be reproduced without waiting.
Reserve, payment, order, and shipment are stored separately. The repeat key is the pair of external payment_id and terminal status succeeded.
The model operates only in process memory; it does not use the network, files, database, real store, or payment API.
The program writes nothing and deletes nothing; after launch, there is nothing to clean up.
Complete reproducible example
Save the code in a new empty directory as late_payment_reservation_lab.py. It contains no secrets, project paths, or operations on live data.
from __future__ import annotations
from dataclasses import dataclass, field
class StateConflict(RuntimeError):
pass
@dataclass
class Reservation:
order_id: str
expires_at: int | None
state: str = "active"
@dataclass
class Order:
order_id: str
state: str = "new"
payment_id: str | None = None
@dataclass
class Store:
available: int = 1
orders: dict[str, Order] = field(default_factory=dict)
reservations: dict[str, Reservation] = field(default_factory=dict)
processed_payments: dict[tuple[str, str], str] = field(default_factory=dict)
shipments: set[str] = field(default_factory=set)
def place_order(self, order_id: str, *, now: int, expires_at: int) -> str:
if expires_at <= now:
raise ValueError("expires_at must be in the future")
if order_id in self.orders:
return "already_placed"
if self.available < 1:
raise StateConflict("stock_unavailable")
self.available -= 1
self.orders[order_id] = Order(order_id, state="awaiting_payment")
self.reservations[order_id] = Reservation(order_id, expires_at)
return "reserved"
def _release_expired_reservation(self, order_id: str, *, now: int) -> bool:
reservation = self.reservations[order_id]
if (
reservation.state == "active"
and reservation.expires_at is not None
and reservation.expires_at <= now
):
reservation.state = "expired"
self.available += 1
return True
return False
def expire_reservations(self, *, now: int) -> int:
return sum(
self._release_expired_reservation(order_id, now=now)
for order_id in list(self.reservations)
)
def apply_payment(
self,
order_id: str,
*,
payment_id: str,
status: str,
now: int,
) -> str:
if status != "succeeded":
raise ValueError("only succeeded payments are accepted by this model")
key = (payment_id, status)
if key in self.processed_payments:
return f"duplicate:{self.processed_payments[key]}"
order = self.orders[order_id]
if order.payment_id not in (None, payment_id):
raise StateConflict("order_linked_to_another_payment")
self._release_expired_reservation(order_id, now=now)
reservation = self.reservations[order_id]
order.payment_id = payment_id
if reservation.state == "active":
order.state = "paid_reserved"
else:
order.state = "paid_needs_stock"
self.processed_payments[key] = order.state
return order.state
def cancel_unpaid_order(self, order_id: str) -> str:
order = self.orders[order_id]
if order.payment_id is not None:
raise StateConflict("paid_order_requires_separate_decision")
reservation = self.reservations[order_id]
if reservation.state == "active":
reservation.state = "released"
self.available += 1
order.state = "canceled"
return "canceled"
def reconcile_paid_order(self, order_id: str) -> str:
order = self.orders[order_id]
if order.state == "paid_reserved":
return "already_reserved"
if order.state != "paid_needs_stock":
raise StateConflict("order_is_not_waiting_for_stock")
if self.available < 1:
return "still_waiting"
self.available -= 1
self.reservations[order_id] = Reservation(
order_id,
expires_at=None,
state="active",
)
order.state = "paid_reserved"
return "reserved_after_payment"
def create_shipment(self, order_id: str) -> str:
order = self.orders[order_id]
reservation = self.reservations[order_id]
if order.state != "paid_reserved" or reservation.state != "active":
raise StateConflict("shipment_requires_active_reservation")
if order_id in self.shipments:
return "already_created"
reservation.state = "consumed"
order.state = "shipment_created"
self.shipments.add(order_id)
return "created"
def scenario_payment_before_expiry() -> None:
store = Store()
store.place_order("order-a", now=0, expires_at=10)
first = store.apply_payment(
"order-a",
payment_id="payment-a",
status="succeeded",
now=5,
)
repeat = store.apply_payment(
"order-a",
payment_id="payment-a",
status="succeeded",
now=6,
)
shipment = store.create_shipment("order-a")
assert first == "paid_reserved"
assert repeat == "duplicate:paid_reserved"
assert shipment == "created"
assert store.available == 0
assert len(store.shipments) == 1
print(
"on_time: first=paid_reserved repeat=duplicate:paid_reserved "
"shipment=created available=0 shipments=1"
)
def scenario_late_payment_after_stock_taken() -> None:
store = Store()
store.place_order("order-late", now=0, expires_at=10)
assert store.expire_reservations(now=10) == 1
store.place_order("order-next", now=11, expires_at=20)
first = store.apply_payment(
"order-late",
payment_id="payment-late",
status="succeeded",
now=12,
)
repeat = store.apply_payment(
"order-late",
payment_id="payment-late",
status="succeeded",
now=13,
)
waiting = store.reconcile_paid_order("order-late")
try:
store.create_shipment("order-late")
except StateConflict as exc:
blocked = str(exc)
else:
raise AssertionError("shipment must be blocked without a reservation")
assert first == "paid_needs_stock"
assert repeat == "duplicate:paid_needs_stock"
assert waiting == "still_waiting"
assert blocked == "shipment_requires_active_reservation"
assert store.available == 0
assert len(store.shipments) == 0
print(
"late: first=paid_needs_stock repeat=duplicate:paid_needs_stock "
"reconcile=still_waiting shipment=blocked available=0 shipments=0"
)
store.cancel_unpaid_order("order-next")
reserved = store.reconcile_paid_order("order-late")
shipment = store.create_shipment("order-late")
assert reserved == "reserved_after_payment"
assert shipment == "created"
assert store.available == 0
assert len(store.shipments) == 1
print(
"recovered: reconcile=reserved_after_payment shipment=created "
"available=0 shipments=1"
)
def scenario_other_payment_id() -> None:
store = Store()
store.place_order("order-conflict", now=0, expires_at=10)
store.apply_payment(
"order-conflict",
payment_id="payment-1",
status="succeeded",
now=5,
)
try:
store.apply_payment(
"order-conflict",
payment_id="payment-2",
status="succeeded",
now=6,
)
except StateConflict as exc:
result = str(exc)
else:
raise AssertionError("a second payment id must require investigation")
assert result == "order_linked_to_another_payment"
assert store.available == 0
assert len(store.shipments) == 0
print(
"conflict: second_payment=order_linked_to_another_payment "
"available=0 shipments=0"
)
def main() -> None:
scenario_payment_before_expiry()
scenario_late_payment_after_stock_taken()
scenario_other_payment_id()
if __name__ == "__main__":
main()
Run the file as a regular user:
python3 late_payment_reservation_lab.py
Two sequential runs completed with exit code 0 and produced identical output:
on_time: first=paid_reserved repeat=duplicate:paid_reserved shipment=created available=0 shipments=1
late: first=paid_needs_stock repeat=duplicate:paid_needs_stock reconcile=still_waiting shipment=blocked available=0 shipments=0
recovered: reconcile=reserved_after_payment shipment=created available=0 shipments=1
conflict: second_payment=order_linked_to_another_payment available=0 shipments=0
SHA-256 of the verified file: 8da3b15b277374dcc639f4de263277dae82a76072320de65cc3cce88aaead416.
What the run confirmed
Scenario | Result | Invariant |
|---|---|---|
Payment before expiration | paid_reserved, one shipment | available=0, shipments=1 |
Payment after expiration | paid_needs_stock, shipment blocked | available=0, shipments=0 |
Retry notification | duplicate with previous outcome | warehouse balance and shipment count do not change |
Product reappears | new reserve, then shipment | available=0, shipments=1 |
different payment_id | conflict for resolution | a second payment must not be silently assigned |
In the late scenario, order order-late loses its reservation at time 10. At time 11, order-next reserves the single unit. The payment-late confirmation arrives at time 12: the order becomes paid but remains without goods. The retry at time 13 returns the same outcome, and the attempt to create a shipment is blocked. Only after another order releases the unit does a separate reconciliation create a new reservation.
The model demonstrates branching and invariants on the given data. It does not measure network latency, does not test the payment module or integration with 1C, and is not a client deployment. In a real project, warehouse operations must be atomic or protected by optimistic locking; otherwise, two processes could simultaneously see the same free unit.
Why 'paid' does not equal 'ready_to_ship'
The payment status answers a financial question: has a specific payment been confirmed, including amount, currency, and recipient? The reservation answers a warehouse question: has a specific order been promised an available unit of goods or a product variant? Shipping requires both confirmations. A single green checkmark should not serve two purposes; interfaces like this, but warehouses do not.
paid_reserved: payment confirmed, active reserve found; proceed to shipment rules.
paid_needs_stock: payment confirmed, no active reserve; automatic shipment is prohibited.
payment_conflict: order already linked to another external payment; requires reconciliation of amount, currency, refunds, and payment document.
duplicate: the same confirmed result is already applied; a repeat does not create a new reservation or shipment.
The paid_needs_stock state does not prescribe a universal business response. For one store, a new reservation after actual replenishment of warehouse stock is acceptable; for another, it may be an agreed replacement, partial shipment, or return. It is important not to hide this choice behind an automatic "paid and ready" status.
How to port the mechanism to the 1C-Bitrix integration
Record the product edition, the versions of the sale and catalog modules, the enabled quantity and warehouse accounting, the reservation rule, and the expiration time. Specify the product or product variant and the warehouse separately.
Link the order, the payment document, and the external payment_id. The order number does not replace the provider's operation identifier, especially during multiple payment attempts.
Verify the authenticity and current status of the payment according to the specific provider's rules. Only then record the financial fact.
Within the same agreed boundary, read the reservation state. Do not restore an expired or already used reservation by simply reducing the balance retroactively.
If the product is unavailable, set paid_needs_stock, do not automatically set the "Delivery Allowed" flag, and do not create a shipment. Record a safe reason and make the order visible to the operator.
If the product becomes available, create a new reservation atomically and only then allow the next stage. A concurrent attempt must receive a rejection, not the same last unit.
Protect the repeat using a stable payment key and terminal status. The email to the buyer, the exchange with 1C, the receipt, and the shipment each have their own keys and resumption points.
Verify scenarios on a project copy: payment before the deadline, payment after the deadline with a zero balance, repeated notification, different payment_id, refund, partial payment, and a product variant with a separate balance.
Do not fix the discrepancy by directly changing the field in the database: you may bypass module events, warehouse documents, and the linked payment document. Do not enable a mass reset of reservations for a single order. Official documentation separately warns that with active orders, such a reset can lead to a double cancellation of the reservation and an incorrect quantity.
Boundary with adjacent materials
If the provider has funds but the order received no confirmation, first analyze the route described in the material Payment Completed, But Order Remains Unpaid. Here, confirmation is already accepted; the issue is a narrower conflict between late payment and an expired reservation.
The rules for the owner of physical, available, and displayed quantities are explained in the material 1C and Website Balances Do Not Match. This new example does not select a source of truth for the project; it checks a single transitional state of the order.
Acceptance criteria
On the test environment, a late confirmation must preserve the verified payment without creating a shipment without an active reserve. Repeating the same notification must not change the balance or trigger actions a second time. With a zero balance, the order remains visible as paid_needs_stock; once the item appears, a new reserve is created in a concurrently safe manner, and only then is shipment permitted. Another external payment_id must not be silently assigned. If any of these conditions is not met, the integration is not yet ready for an automated scenario.





Обсуждение 0
Делись опытом и задавай вопросы. Комментарии без ссылок появляются после проверки редактором.
Пока никто не написал. Начни обсуждение.