A negotiated cart paid through Stripe's user_cart_complete_checkout
already fired _finalize_auction_offer_state(cart, request) — which
flips linked offers to PAID and linked auctions to SETTLED. But the
PayPal complete-checkout (cart.py:paypal_complete_checkout) and the
Adyen complete-checkout (cart.py:adyen_complete_checkout) paths
never called it.
Symptom: buyer pays a negotiated offer through PayPal or Adyen,
invoice is written, sale email fires — but offer.state stays at
ACCEPTED. The offer detail page keeps rendering the Pay $X / Cancel
buttons because `{% if is_accepted and not is_paid %}` is still True.
Even worse, the buyer could click Cancel after the payment had
processed (the cancel endpoint guarded on `state != ACCEPTED`, which
also still permitted it).
Fix: add the _finalize_auction_offer_state(cart, request) call to
both paypal_complete_checkout and adyen_complete_checkout, right
when successful_invoices is populated — before the cart line items
get drained. Each takes (cart, request) which both sites have in
scope. With the offer now in PAID:
- is_paid=True flips the offer.j2 gate, hiding Pay/Cancel.
- /o/{id}/cancel raises OfferRejected ("only accepted offers can
be cancelled by buyer").
- _user_party / shop_offers / buyer dashboards all read the right
terminal state.
Note: this only patches the cart.py callsites. Webhook fallbacks
(views/webhooks.py) and the crypto-watcher finalize path
(lib/crypto_watcher/__init__.py) still don't call mark_paid because
they only have `invoice`, not `cart`. Follow-up will route those
through a `_finalize_invoice_negotiation(invoice, session)` helper
once that's needed; the cart.py paths cover the common case.
Two coupled fixes the rendered sale email exposed:
<img src="None/<shop_id>/<product_id>/thumbnail1?ts=...">
1. ShopContextRequestWrapper (lib/crypto_watcher/__init__.py:1243)
wraps env_request for email-rendering inside the watcher loop. It
overrode domain / host_url / app and proxied everything else via
__getattr__. send_purchase_email + send_sale_email read
`request.shop_cdn_endpoint` — but that's a reified Pyramid request
method, not a static attr on env_request. __getattr__'s default
returned None, and the email's <img src> became `None/.../...`.
Fix: add explicit `shop_cdn_endpoint` (and `shop`) properties on
the wrapper, derived from the wrapper's `_shop`. Order:
- BYOB shop with primary_s3_cdn_endpoint set → that
- else `app["bucket.secure_uploads.get_endpoint"]` (MPS default)
- else None
The BYOB branch also defends against an enabled-but-blank
primary_s3_cdn_endpoint — drops to the default rather than
returning None.
2. Offer + auction-outbid emails carried no product thumbnail at
all — bummer, since the recipient can't visually identify which
item the negotiation is about. New _product_thumbnail_html(request,
product) helper renders a 184px-max <img> identical to the
purchase/sale shape (or empty string if the product has no
thumbnail1 extension / no CDN endpoint).
Wired into:
- send_offer_received_email
- send_offer_accepted_email
- send_offer_countered_email
- send_offer_declined_email
- send_offer_withdrawn_email
- send_offer_buyer_cancelled_email
- send_auction_outbid_email
Templates in lib/mail_messages.py gained a `{thumbnail}` slot
between the headline and the click-through link. Text variants are
unchanged (no inline images in text email).
Both fixes target the same surface: every transactional email now
renders the right image, regardless of whether it's sent from a
view (Pyramid request) or the crypto watcher loop (wrapped env_req).
The withdraw form on /o/<id> was nested inside the buyer's
`can_act` (your-turn) block, so a buyer who'd just opened an offer
or whose counter was awaiting the seller's response saw the
"Waiting on the other party" panel with no way to back out — they
either had to wait for auto-expiry or message the seller.
Add a symmetric withdraw form inside the `is_open` waiting block,
gated on actor_party == 0 (viewer is the buyer). The lib already
permits withdraw at any non-terminal pre-accept state
(lib/offer.py withdraw_offer); only the UI was the bottleneck.
Sellers don't get a symmetric "pull out" here — they decline
instead, which lives in their can_act block.
Regression test test_buyer_sees_withdraw_button_while_waiting_on_seller
asserts the form action and "Withdraw offer" copy render on a
PENDING offer from the buyer's view.
CI on commit 5f735ee broke two double-spend-protection unit tests:
TypeError: unsupported format string passed to MagicMock.__format__
The new notify_purchase_and_sale() call inside the crypto-watcher
finalization path runs `f"${invoice.total:.2f}"` to compose the
notification body. The double-spend tests pass a MagicMock as the
invoice — its .total is a MagicMock too — and the format-spec call
fails before _safe_add even runs.
Fix: wrap every public notify_* helper in a top-level
try/except-and-log. A notification persist failure must not
propagate up the payment-finalization stack (it didn't matter in
prod because real invoices format fine, but the unit-test mocks
exposed the contract gap).
All five helpers updated: notify_purchase_and_sale,
notify_auction_outbid, notify_auction_won,
notify_auction_ended_no_winner, notify_offer_expired. Inner
functions hold the actual logic; the outer wrapper is just the
swallow-and-log shield.
This also stops a transient DB or attribute error inside the
helper from rolling back the payment txn — same defense the
_safe_email wrapper provides for mail sends.
Two cleanups:
1. The orphaned blue "Waiting on the other party to respond" stripe
(alert-info-bg) appeared between the offer header and the
"Waiting on the other party · They have in X to respond" well
below — identical copy, twice. Same pattern as the previously
removed green "Offer accepted" banner. Dropping both the can_act
("It's your turn — accept, counter, or decline below") and
is_open branches of the state-notice. The "Your turn" section
heading and the waiting well right below already carry the
message, with the live countdown that the alert lacked.
Kept: DECLINED, WITHDRAWN, EXPIRED, PAID — those have no
follow-on action block, so the alert is the only signal.
2. DEFAULT_OFFER_EXPIRATION_HOURS 48 → 72 (3 days). Fox: 48h still
too tight for sellers checking shop mail intermittently. 7 days
was too generous, 48 hours was on the strict side. 72 hours
covers a long weekend.
Per-shop overrides are unchanged — operators tweak
offer_expiration_hours via offer-settings on /s/<shop>/settings.
Ported remarkbox's pattern over to MPS. views/version.py now tries
sources in order:
1. /opt/make_post_sell/commit-hash.txt (CI deploy artifact)
2. /opt/make_post_sell/env/commit-hash.txt (alt salt layout)
3. <package>/../commit-hash.txt (relative)
4. <package>/GIT_HASH (setup.py legacy)
5. git rev-parse --short HEAD (dev environment)
6. "unknown" (last resort)
MPS CI's build stage already writes commit-hash.txt to the artifact
tarball (.gitlab-ci.yml:38 `echo $CI_COMMIT_SHA >> commit-hash.txt`);
salt deploys it. setup.py's GIT_HASH rewrite still runs at install
time as a redundant fallback, so any environment that hasn't migrated
to commit-hash.txt yet keeps working.
Dev environments fall through to git rev-parse, which is faster and
more accurate than the previous setup.py-rewrites-source pattern that
required the file to be in the package at runtime. With this change,
/version returns the actual deployed commit hash everywhere — no
stale GIT_HASH file in git history (the file is .gitignored as of
c383c41).
Plug the remaining state-machine gaps the previous notification
batch left dark. With auction_tick and offer_tick running on cron,
buyers and sellers now learn about every passive transition:
- auction_tick ACTIVE → ENDED (with winner) drops
notify_auction_won for the winner — they see the pay CTA + 48h
payment_deadline before it lapses. Previously only the email
fired (and only if SMTP succeeded); now the in-app row also
exists with breadcrumbs Shop → Product → Auction.
- auction_tick ACTIVE → ENDED (without winner / reserve not met)
drops notify_auction_ended_no_winner for shop owners so they
can decide to relist.
- offer_tick PENDING/COUNTERED → EXPIRED and ACCEPTED → EXPIRED
both drop notify_offer_expired for buyer + shop owners. The
buyer was the most-affected silent case: they made an offer,
the seller never responded, the offer auto-expired, the buyer
never knew.
Four new notification kinds in models/notification.py:
auction_won, auction_ended_no_winner, auction_cancelled
(reserved — no call site yet), offer_expired.
lib/notifications.py orchestrator refactored: _resolve_session()
accepts either a Pyramid request or a SQLAlchemy session so the
same helpers work in views AND tick jobs.
Integration tests in TestAuctionTickIntegration and
TestOfferTickIntegration assert the right row exists with the
right kind + FK after each tick.
Three remaining notification surfaces wired:
1. Purchase (buyer) + sale (every shop owner) notifications drop on
every cart-completion site. Coverage:
- views/cart.py x3 (Stripe / PayPal-create / Adyen) — alongside the
existing send_purchase_email + send_sale_email pair
- views/webhooks.py x4 (PayPal capture / approved / Stripe / Adyen)
- lib/crypto_watcher/__init__.py x3 (Monero / Dogecoin / confirmed
duplicate-path) — gated on the existing sales_email_sent flag so
a rescan can't write duplicate rows
Each notification carries invoice_id, so MpsNotification.breadcrumbs
walks Shop → Product (first line item) → Invoice (/i/<id>).
2. Auction outbid: when a new bid lands and the prior bidder is
bumped, alongside send_auction_outbid_email the prior bidder gets
a row with auction_id set — breadcrumbs walk Shop → Product →
Auction (/a/<id>).
3. Read rows stay visible. Fox's clarification: mark-read must not
delete; just fade. The row stays in the list (still clickable,
breadcrumb still works); only the unread accent class and the
opacity differ. Tokens: .notification-row has opacity 0.65;
.notification-row-unread overrides to 1 + alert-info-bg +
left accent border. test_read_notifications_remain_visible_but_faded
asserts the row count stays the same in DB and the rendered
subject is still in the HTML after dismiss.
Shared orchestration in new lib/notifications.py — notify_purchase_and_sale
and notify_auction_outbid keep the call sites to one line each.
3 new functional tests, 108/108 in the offer/auction/cart sweep.
Every transactional email on the offer state machine now also drops a
row in a new mps_notification table — the user has a permanent in-app
inbox even if they never opened the email.
Schema (mps_notification, migration 5d01b163b805):
- user_id recipient
- shop_id which shop this is about (nullable)
- kind discriminator (offer_received, offer_accepted,
offer_countered, offer_declined, offer_withdrawn,
offer_buyer_cancelled, purchase, sale,
auction_outbid)
- subject, body denormalized text so deleting the source entity
doesn't blank the row
- link_url primary click-through (/o/<id>, /a/<id>, /i/<id>)
- offer_id, auction_id, invoice_id
optional FKs for breadcrumb rendering
- created/updated_timestamp
- read bool, drives the unread badge
- read_timestamp
Composite index on (user_id, read, created_timestamp) for cheap
unread-count queries.
Surfaces:
- request.unread_notification_count (reified) drives a navbar badge
next to the profile name and a duplicate badge on the /u/settings
"Notifications" button.
- /u/notifications lists rows newest-first with the kind label, time
delta (ago.human), subject/body, and a breadcrumb chain back to
source entities. MpsNotification.breadcrumbs walks shop → product
→ offer/auction/invoice for any combination of attached FKs.
- /u/notifications/{id}/read marks a single row read; bulk
"Mark all read" on the list page hits /u/notifications/read-all.
Wired into every offer state transition (open, counter, accept,
decline, withdraw, buyer-cancel) alongside the existing email sends.
_safe_email and notification persist are now decoupled — SMTP outages
no longer block notification creation. (This was the regression the
new TestNotifications suite caught: pre-fix, a refused SMTP swallowed
the notification persist call too.)
Tokenized CSS for the badge (.notification-badge pill, danger color)
and the list rows (.notification-row, .notification-row-unread with
left accent border, .notification-row-breadcrumbs trail). Grid only,
no flex, no inline styles.
Tests TestNotifications.test_offer_open_drops_received_notification_for_seller
and test_badge_count_and_mark_read drive the full flow: buyer opens
offer → seller's row exists with breadcrumbs (Shop → Product → Offer)
→ /u/settings badge renders → /u/notifications/read-all clears.
Previously the only emails on the offer state machine were:
- PENDING → seller (offer received)
- auto-accept / seller-accept → buyer (offer accepted)
- cart paid → buyer + seller (purchase / sale)
Every other transition was silent — buyer countered, seller
countered, seller manually declined, buyer withdrew before accept,
buyer cancelled after accept. The buyer-cancelled-after-accept case
stung most: the seller had accepted and was awaiting payment that
was never coming, with no notice except by polling /s/<shop>/offers.
Five gap-plugs:
1. Buyer counters back → seller(s) emailed (all shop owners).
2. Seller counters → buyer emailed.
3. Seller manually declines → buyer emailed. (auto-decline stays
silent — the submit flash already conveys it inline.)
4. Buyer withdraws (pre-accept) → seller(s) emailed.
5. Buyer cancels (post-accept) → seller(s) emailed with explicit
"buyer cancelled accepted offer" copy so the seller stops
expecting payment.
Templates: OFFER_COUNTERED_{TEXT,HTML}, OFFER_DECLINED_{TEXT,HTML},
OFFER_WITHDRAWN_{TEXT,HTML}, OFFER_BUYER_CANCELLED_{TEXT,HTML} in
lib/mail_messages.py.
Helpers: send_offer_countered_email, send_offer_declined_email,
send_offer_withdrawn_email, send_offer_buyer_cancelled_email in
lib/mail.py — same pattern as send_offer_received_email +
send_offer_accepted_email.
Each handler in views/offer.py snapshots the pre-action state, runs
the action, and only emails on the actual transition (so a retried
POST against an already-terminal offer doesn't re-fire the email).
All sends go through _safe_email which logs + swallows exceptions:
mail failure cannot 500 an offer-state HTTP response.
Crypto status-poll endpoints flashed "Payment received! Waiting for
confirmations…" on every refresh while a quote was in the
received-but-not-confirmed state. The flash queue is a list, so
identical alerts piled up — fox's screenshot showed the same line
repeated 18+ times stacked down the page.
Two-layer fix:
1. Render-level dedupe in templates/snippets/flash-alerts.j2.
Pop the queue once, walk it, render each unique (message, level)
pair only the first time it's seen. Safe regardless of how the
queue was populated — covers any other view that might flash
duplicates without the helper.
2. New request.flash_once(message, level) helper (request_methods.py)
that peeks the queue and skips the append if (message, level) is
already there. Switch the two crypto status-poll handlers
(views/crypto.py — Monero block ~820, Dogecoin block ~910) to use
it. Both endpoints are hit on every poll, so the queue-level
dedupe matters even with render-level dedupe (other consumers of
the queue would still see duplicates, and the queue would balloon).
The flash queue itself stays a list (order-preserving) — set would
lose insertion order, which matters when multiple distinct alerts
need to render top-to-bottom. The peek-then-skip pattern keeps the
list semantics while preventing dup growth.
CRITICAL financial defect. Cart UI showed the negotiated $21 total
for an accepted offer (list was $42), but EVERY payment pipeline —
Stripe (cart.py:848), PayPal (cart.py:1164), Monero quote
(crypto.py:269), Dogecoin quote (crypto.py:538) — pulled
invoice.total_in_cents, which summed line items and ignored the
cart_offer / cart_auction override entirely. Buyer's DOGE quote
asked for ~373 DOGE (≈$42 USD) for an offer they negotiated to $21.
Seller would have eaten $21 per accepted offer.
Fix:
- New column mps_invoice.negotiation_override_in_cents (nullable
BigInteger). Migration 27bc1bfc33dc adds it idempotently.
- Invoice.total_in_cents short-circuits to the override + handling
when the column is set. Coupons / discount math is bypassed (the
buyer already negotiated; we don't stack on top).
- Invoice.apply_cart_negotiation(cart) helper copies the cart's
override onto the invoice in one call. Idempotent. No-op for
non-negotiated carts.
- Wired into every invoice-from-cart construction site (7 total):
- views/crypto.py:161 (Monero quote)
- views/crypto.py:454 (Dogecoin quote — fox's screenshot)
- views/cart.py:827 (Stripe checkout)
- views/cart.py:974 (PayPal create-order)
- views/cart.py:1153 (Adyen sessions)
- views/cart.py:1258 (PayPal complete-checkout)
- views/cart.py:1388 (post-PayPal-approval finalize)
Two integration tests cover the model:
- test_negotiation_override_short_circuits_total walks the
invoice-from-negotiated-cart flow, asserts $42 → $21 transition
after apply_cart_negotiation, and confirms handling still adds
on top.
- test_apply_cart_negotiation_noop_when_not_negotiated proves the
helper is safe to call on plain carts (no negotiation_override
set, line items sum normally).
Legacy invoices already in the DB have NULL on the new column —
they keep their line-item-summed totals, untouched.
Three UI fixes batched (all touched adjacent templates):
1. /u/offers, /u/bids, and /s/{shop}/offers tables were cramped on
desktop: max-width was the .one-column 600px constraint, so the
Product column word-wrapped and timestamps wrapped onto multiple
lines. Widen .shop-offers-page to 1100px on desktop, give
Product the auto-flow column and tag the rest with .col-narrow
(nowrap) / .col-action (right-aligned). Replace strftime UTC
strings with ago.human() relative deltas ("2 hours ago",
"5 minutes ago") in the three views that feed those tables.
Mobile (<720px) collapses each row to a block list — the dense
table layout is desktop-only.
2. /u/cart/{id}/checkout had a visible gap between the
"Pay with Credit Card — Add Card" CTA and the PayPal button —
a redundant <br/> at the top of the PayPal block. Drop it; the
buttons' own margins now space them naturally.
3. Buyer's accepted-offer pay panel had Pay and Cancel stacked
vertically with Cancel rendered as a faint text link. Per fox:
put them on the same line, Cancel on the left. New
.offer-pay-cta-actions grid (auto 1fr) renders Cancel as a
neutral mps-button at start, Pay as the green primary at end.
Stacks on viewports under 600px.
All token-driven CSS, Grid only (no flexbox), no inline styles.
CI on commit 5272988 (drop orphaned green "Offer accepted" banner)
broke one stray assertion in TestOfferRoutes that still searched for
the removed string. Update the test to assert on the surfaces that
DO carry the state now:
- the offer-state-badge with class offer-state-1 (visible "Accepted")
- the Pay $96.00 now CTA (the actual call to action)
- the /o/{id}/checkout form action
Same intent, current markup.
The server-side guards on /cart/add and /cart/{id}/quantity stop the
exploit, but the buyer still saw an enabled "Add To Cart" button that
bounced them. Per fox: disable the button with a one-sentence caption
explaining why, instead of hiding it. A hidden button confuses users;
a disabled one with caption keeps the affordance visible and teaches
the user how to re-enable it (check out or save the current cart).
product.j2 now:
- Adds `disabled` to both Add To Cart buttons (physical + digital
paths) when `request.active_cart and request.active_cart.is_negotiated`.
- Renders a `.product-add-disabled-note` paragraph beneath with the
reason: "Your active cart is locked to an accepted offer/auction.
Save or check out that cart before adding other items."
Token-driven CSS for the caption (no inline styles, no hardcoded
colors). The button keeps its mps-button styling — browser disabled
state is sufficient visual contrast.
Test test_product_page_disables_add_to_cart_on_negotiated_cart walks
the realistic flow: buyer accepts an offer on product A, then visits
product B (a separate buy-now product on the same shop) and sees the
button disabled with the caption.
The cart override returns offer.current_amount_in_cents regardless
of line-item quantity. So a buyer who:
1. Got an offer accepted at $21 (list $42)
2. Hit /o/{id}/checkout → got a cart with 1 unit + cart_offer
3. Went back to the product page and clicked "Add to cart"
…would end up with a cart showing 2 units of a $42 product but
charged the single negotiated $21. Seller eats $84 of merch for $21.
Same hole on /cart/{id}/quantity — bumping quantity directly skipped
the override re-check.
Plug both:
- cart_add_product refuses when active_cart.is_negotiated. Flashes
"This cart is locked to your accepted offer/auction — save or
check out this cart before adding other items."
- cart_quantity_product refuses when cart.is_negotiated. Flashes
"Quantity is locked on an accepted offer/auction — the agreed
price is for one unit only."
Two regression tests cover the gap: one POSTs /cart/add of the same
product, one POSTs /cart/{id}/quantity setting quantity=2. Both
assert cart.get_product_quantity(product) stays at 1 and the
response flashes "locked".
UI tightening (hiding the add-to-cart button on the product page
when the active cart is already negotiated to a different product)
is a follow-up — this commit is the server-side defense.
The ACCEPTED state-notice alert floated between the offer-header
well and the offer-pay-cta well — a green stripe in the middle of
the page with nothing visually anchoring it. Worse, the message it
carried duplicated content the next block already showed:
- Buyer: the "Pay $X now" CTA right below is itself the call to
action. "Offer accepted — pay now to complete your purchase" was
noise on top.
- Seller: the "Awaiting payment" well right below already names the
buyer + amount and explains the auto-email + share link.
Drop the is_accepted branch. The state badge in the offer header
still shows "Accepted" — so the state is never invisible — and the
pay / awaiting blocks carry the per-role copy.
Other state-notice alerts (DECLINED, WITHDRAWN, EXPIRED, PAID,
can_act, is_open) stay — they're useful precisely because their
states have no follow-on action block.
Each feature commit was being followed by a "bump GIT_HASH to X"
commit whose value was always one behind HEAD (the bump itself
shifted HEAD again). The file in git was effectively a stale
record that setup.py overwrote on every CI install anyway via
`git rev-parse --short HEAD`. Pure churn — half the commit log
was these bump commits.
Untrack the file, .gitignore it, drop the bump from CLAUDE.md's
AUTO-PUSH and post-work-chores guidance. setup.py keeps writing
the real HEAD at install; views/version.py still reads it. The
/version endpoint behavior is unchanged — it just stops requiring
a follow-up commit per ship.
7 days for a seller to even respond to a buyer's offer was too
generous. eBay-style Best Offer caps at 48 hours; nobody enjoys
waiting a week to find out their offer is dead.
Change is purely the new-shop default — existing shops keep
whatever their offer_expiration_hours column is set to. Operators
can tighten or widen via the offer-settings form on their shop
settings page.
(Default-to-default coverage in test_integration.py updated to
match.)
The offer page already showed a pay-by countdown once the offer
was ACCEPTED. The negotiation window (pre-acceptance) had a
deadline server-side (offer.expires_timestamp) but no countdown
in the UI — buyers and sellers had to guess how long they had to
respond.
offer_page view now exposes respond_deadline_human (ago.human)
and respond_deadline_timestamp_ms alongside the existing pay
deadline pair. offer.j2 surfaces it in two places:
- "Your turn" panel: "Respond in 5 days, 12 hours, or this offer
auto-expires." (the user is the current_party, can act).
- "Waiting on the other party" panel: "They have in 5 days, 12
hours to respond, or this offer auto-expires." (the other
party owes the next move).
Both render through the same [data-pay-deadline] attribute the
existing ticker scans — the surrounding copy disambiguates
respond-vs-pay. One countdown shape, two semantic uses, depending
on state.
Regression test test_pending_offer_renders_respond_countdown locks
in the markup (PENDING offer, seller view, "Respond" + the regex
for the prose ago.human() output).
Two coupled fixes the live shop.unturf.com data exposed:
1. Legacy accepted offers (those flipped to ACCEPTED before the
accepted_timestamp column existed) have NULL there, so
acceptance_pay_deadline_ms returned None and the countdown never
rendered. Fall back to last_action_timestamp — for an
untouched-since-acceptance offer that IS the moment of acceptance
(the accept event was the last action recorded). Also guard the
property to only return a deadline when state == ACCEPTED, so
PAID / EXPIRED / WITHDRAWN offers don't accidentally surface
stale deadlines.
2. Cart page (/cart/{id}) had no countdown — the buyer landed in
the cart from the offer accept email, saw the agreed price, but
no live indicator of when this deal expires. Cart.negotiation_pay_
deadline_ms exposes the linked offer or auction's deadline;
cart.negotiation_pay_deadline_human renders ago.human() for the
no-JS fallback. cart.j2 adds a "Pay <strong>in 23 hours, 14
minutes</strong>, or this offer expires." line inside the green
negotiation card.
Pulled the countdown tick out of offer.js into a shared
static/js/pay-countdown.js so cart.j2 can include just the ticker
without pulling the offer-detail form wiring it doesn't need.
Other pages still load their own JS — offer.js and auction.js keep
their own implementations for now; this is the cart-page addition.
Shop.offer_enabled is the shop-level *default* — products can override
via allow_offers=True even when the shop default is off. The original
button gate on /u/settings only checked the shop-level flag, so a
buyer in a shop with offer_enabled=False but at least one product
opting in via allow_offers=True saw no button.
Add Shop.has_offer_products mirroring has_auction_products, but
accounting for the override:
product accepts offers iff
product.allow_offers IS TRUE
OR (product.allow_offers IS NULL AND shop.offer_enabled IS TRUE)
Wire user_settings.j2 to gate on has_offer_products, and update the
/u/offers view's 404 guard to the same property — otherwise the
button appeared but the page 404'd.
Tests:
- test_shop_has_offer_products_property covers the four-cell matrix
(shop default × product override).
- test_settings_offers_button_for_product_level_opt_in is the
regression for the case fox hit on shop.unturf.com.
Two reorderings on the cart checkout right column:
1. The "Save PayPal for faster checkout next time" checkbox now lives
*under* the PayPal button instead of above it. The primary action
(the yellow PayPal button) stays at the top of the panel; the
secondary toggle (remember this method?) follows. Saved-PayPal
buyers see a "PayPal saved for quick checkout" banner above the
button instead.
2. The "You can manage saved payment methods…" copy was inline under
the checkbox. It's now a footnote at the bottom of the right
column, with "account settings" linking to /billing — the actual
surface where the user can disconnect PayPal or manage cards.
Lives outside the save-toggle branch so saved-PayPal users see it
too (they may want to disconnect from there).
Cleanup:
- All inline styles on the saved-banner / save-checkbox replaced
with tokenized .cart-paypal-saved-banner / .cart-paypal-save-row /
.cart-paypal-save-label / .cart-paypal-saved-check /
.cart-paypal-manage-note classes. Grid only, design tokens only.
Replaces the previous "2026-05-14 11:00 UTC" deadline strings and
the secondary "23h 14m 8s remaining" pill with a single in-place
prose delta on both offer and auction pages.
Server (no-JS fallback): ago.human(deadline, future_tense="in {}")
renders "in 23 hours, 14 minutes". Reaches for the same precision
the buyer cares about, in their reading style, without a wall-clock
string to mentally subtract from. Same library Russell Ballestrini
wrote — public domain, already a dep.
Client (JS-enhanced): offer.js / auction.js rewrite the same
<strong data-pay-deadline="..."> element once per second with a
prose delta computed locally ("in 23 hours, 14 minutes, 8 seconds").
The previous fmtRemaining returned compact "23h 14m 8s" which read
as code — switched to prose to match the server fallback.
Auction page also drops the dual element (separate countdown chip +
human deadline span); JS rewrites in place so the markup is half
the size.
Test test_accepted_offer_renders_pay_countdown_for_buyer locks in
the new markup: a `data-pay-deadline="…">in N units` regex match.
When JS is available, the buyer now sees a live countdown next to the
absolute pay-by date on both the accepted-offer page and the
auction-won page. Without JS, the existing static "You have until
<date>" copy still renders — the countdown element is .js-only.
Offer (/o/{id}):
- offer_page view now exposes pay_deadline_timestamp_ms alongside the
human string.
- offer.j2 adds a [data-pay-deadline] span next to the deadline copy
on both the buyer (pay-now) and seller (awaiting-payment) sides.
- offer.js scans for [data-pay-deadline] every second and writes the
formatted remaining time into .offer-pay-countdown-value. Reuses the
same fmtRemaining shape as auction.js (Nd Nh Nm / Nh Nm Ns / Nm Ns).
Auction (/a/{id}):
- _serialize_auction adds payment_deadline_timestamp, user_is_winner,
and is_settled.
- auction.j2 renders a new "You won this auction!" well when state is
ENDED, the current user is the winner, the auction isn't SETTLED,
and payment_deadline_timestamp is set. The well carries the pay
button + a countdown that auction.js fills in. The human deadline
is also resolved client-side (toLocaleString) so the buyer sees
it in their own timezone.
- auction.js adds tickPayCountdown() in addition to the existing
tickCountdown() that counts auction end.
Test fixture _accepted_offer now sets offer.accepted_timestamp (the
fixture bypasses accept_offer() which would set it for free).
test_accepted_offer_renders_pay_countdown_for_buyer locks in the
markup.
Test suite hit GitLab's 1-hour pipeline timeout (58:41) — the test
step alone exceeded the cap and the deploy step never ran. Root cause
was per-test infrastructure cost:
- FunctionalTests.setUp/tearDown rebuilt the entire WSGI app and ran
Base.metadata.create_all + drop_all for *every* test. Measured at
~640ms of pure DDL per test (36 tables + indexes); the app boot adds
another ~400ms. ~1s of overhead per test before the test body even
starts.
- DatabaseIntegrationTests had the same pattern.
Fix: lift app + engine + schema to classmethods that run *once per
worker process*. Per-test setUp now just hands the shared infra to
instance attrs and creates a fresh webtest.TestApp + dbsession.
Per-test tearDown aborts the pyramid_tm txn and wipes every row via
table.delete() in reverse FK order, with PRAGMA foreign_keys OFF
around the wipe so we don't have to compute a safe order for
circular refs.
Class-level state lives on FunctionalTests / DatabaseIntegrationTests
themselves (not `cls`) so all subclasses see the same instances on
attribute lookup. pytest-xdist worker isolation is unchanged — each
worker has its own sqlite file (conftest.py) and its own Python
process, so the class-level cache is per-worker.
Local timings (8 cores, -n auto):
- test_functional.py: 3:30 → 2:14 (36% faster, 291/291 pass)
- full suite: ~7m → 3:49 (1012/1012 pass)
On CI (fewer cores), expected to drop from 58:41 to roughly
25-30 min — well under the 1h pipeline cap.
The page was using the .two-column class (designed for the product
page mobile stack) which left the Stripe Element floating to the
right with massive whitespace and orphaned Review Order / Checkout
buttons disconnected from the content above. Inline styles all over
the PayPal section meant no token consumption.
Rebuild:
- New .billing-page wrapper, max-width 1000px, centered, CSS Grid.
- Active Card + Add Card now sit in a .settings-form-grid (1 col
mobile, 2 cols desktop) so they align as equal-width siblings.
Heading copy adapts: "Add a Card" when no card on file, "Add
Another Card" when there is one.
- PayPal section moved to its own full-width well below; inline
styles replaced with tokenized .billing-paypal-card,
.billing-paypal-header, .billing-meta classes. Grid only.
- Review Order + Checkout buttons land in a .billing-actions well
centered as a 2-col grid; Checkout is the green primary CTA.
Collapses to a single stretched column on mobile.
No design system tokens are hard-coded — every color, gap, radius,
and font size pulls from tokens.css. CSS Grid only, no flexbox.
The left column used to always render when stripe was enabled and the
shop was stripe-ready, even when the buyer had no card on file —
showing a duplicate "Add a credit card payment method" CTA next to the
right-column "Pay with Credit Card — Add Card" button. Two identical
CTAs in two columns read as a broken page.
Left column now renders only when it has concrete content:
- an Active Card to display, or
- an Active Shipping Address for a physical product in the cart.
Otherwise the page collapses to a centered single column (the CSS
:has(.checkout-left) selector already handled this layout case).
Existing assertion test_cart_checkout_for_shop now also asserts the
left-column "no card configured" copy no longer appears.
Two coupled additions to make-an-offer:
1. Buyer back-out after acceptance. New terminal state
OFFER_STATE_BUYER_CANCELLED, route POST /o/{id}/cancel, and
lib/offer.cancel_offer_after_accept(). Distinct from WITHDRAWN
(which is pre-acceptance buyer pullout) so seller's inbox can
visually distinguish "they ghosted after acceptance" from "they
pulled it before I responded." Confirm dialog on the button —
it's a destructive action.
2. Post-acceptance pay window. New shop-level setting
offer_acceptance_payment_hours (default 24h, configurable in
offer-settings form) bounds how long the buyer has to pay
after acceptance. accept_offer() (both manual and auto-accept)
stamps offer.accepted_timestamp; offer.acceptance_pay_deadline_ms
is derived. offer_tick now expires ACCEPTED-but-unpaid offers past
their deadline alongside the existing PENDING/COUNTERED expiry.
The offer detail page now shows the deadline to both buyer and seller,
and gives the buyer a "Cancel this offer" button alongside the pay-now
CTA.
Migration 632878c8f243 adds the two columns idempotently
(offer_acceptance_payment_hours on mps_shop, accepted_timestamp on
mps_offer). Existing accepted offers have accepted_timestamp = NULL;
the tick treats NULL as "no deadline" so legacy rows aren't
suddenly expired.
Tests:
- test_accepted_offer_expires_after_pay_window (integration)
- test_accepted_offer_inside_pay_window_not_touched (integration)
- test_buyer_cancel_after_accept_flips_state (integration, includes
the paid-offer-cannot-be-cancelled guard)
- test_buyer_can_cancel_accepted_offer (functional)
- test_seller_cannot_cancel_accepted_offer (functional)
Cart checkout had two payment-UX defects:
1. PayPal Smart Buttons rendered three buttons by default: the yellow
PayPal button, "Pay Later" financing, and "Debit or Credit Card"
(PayPal-branded card flow). For MPS, credit-card checkout goes
through Stripe — the PayPal card button is redundant and pushes a
competing flow into the same panel.
Fix: append `disable-funding=paylater,card` to the PayPal SDK URL
so only the single PayPal Smart Button renders.
2. Stripe lost visibility on the right column when the buyer had no
card on file yet. The "Add a credit card payment method" CTA only
appeared in the left panel; next to PayPal + crypto on the right,
the credit-card path looked unsupported.
Fix: when stripe is enabled and the shop is stripe-ready but the
buyer has no active card, surface a "Pay with Credit Card — Add
Card" CTA in the right column, alongside the PayPal Smart Button.
/billing then runs the existing card-add flow.
Tests:
- test_cart_checkout_for_shop asserts "Pay with Credit Card" renders
in the right column when no card is on file.
- test_paypal_smart_buttons_collapsed_to_one is a template-grep
asserting the SDK URL carries disable-funding=paylater,card.
Two coupled fixes on the accepted-offer flow:
1. Single redemption. offer_checkout was creating a fresh cart on
every POST. While offer.state == ACCEPTED, a buyer could spawn N
parallel carts on one offer; mark_paid is idempotent on the offer
but the *other* carts still carried the override and could each
complete checkout, double-charging the buyer. Now: if any
cart_offer already exists for the offer, reuse that cart (and
re-activate it). Only one cart_offer row can ever exist per offer.
2. Seller copy on the "Awaiting payment" panel said "they need to
sign in and pay from this same page — send them the link", which
implied the seller had to manually deliver the link. The system
already emails the buyer on accept (send_offer_accepted_email is
wired in views/offer.py for both auto-accept and manual paths).
The copy now reflects that: "We emailed them a one-time checkout
link — this offer can be redeemed only once." The shareable link
stays as a fallback for if the buyer asks for it again.
Functional test test_offer_checkout_is_single_redemption asserts
three consecutive POSTs to /o/{id}/checkout redirect to the same
cart URL and produce exactly one cart_offer row. Existing
test_accepted_offer_seller_sees_pay_link_to_share extended to
assert the new copy ("emailed", "one-time checkout link").
Two new buyer-side pages mirror /u/purchases — scoped to request.shop,
listing every offer or bid the user has placed within the current shop:
- /u/offers — open offers (pending/countered) on top, terminal below.
404s when the shop has offer_enabled=False. Wired to user_offers.j2.
- /u/bids — latest bid per auction in this shop. 404s when the shop
has zero products in auction pricing_mode. Wired to user_bids.j2.
Gating exposed on /u/settings:
- "My Offers" button: visible iff request.shop.offer_enabled is True.
- "My Bids" button: visible iff request.shop.has_auction_products.
New property Shop.has_auction_products: returns True when the shop
has at least one product with pricing_mode in (1, 2). Auctions have
no shop-level toggle — they're enabled per product — so the buyer
gate is derived. Unit-test coverage in test_integration.py.
Tests:
- TestAuctionFoundation.test_shop_has_auction_products_property
covers all three pricing-mode transitions on the same shop.
- TestUserOffersBidsDashboards (7 tests) covers 404 paths, page
renders, and button visibility on plain / offer / auction shops.
Cart polish for offer/auction carts:
- Negotiation card at top of cart-left: eyebrow ("Offer accepted" /
"Auction won"), list price (strike) vs agreed price (bold green),
savings line, link to /o/{id} or /a/{id}.
- Shop subtotal honors the override: strikethrough list price, bold
negotiated price. (is_discounted was rightly False after the prior
fix, but the visual cue was lost — restored without conflating it
with coupon discounting.)
- Line item rendering: replaces quantity field + remove button with a
"quantity locked" pill on the negotiated product, since offers and
auctions are single-unit transactions buyers cannot edit mid-cart.
- Right column total: shows agreed price big, list-vs-savings line
beneath. No conflicting strikethrough.
- Gift card apply hidden on negotiated carts (does not stack).
New Cart properties (test coverage in test_integration.py):
- is_negotiated, negotiation_kind, negotiation_path, negotiated_product
- list_total_in_cents / list_total
- savings_in_cents / savings (clamped to >= 0)
CSS: cart-negotiation-card / cart-negotiation-* / cart-negotiation-pill
all live in common.css, Grid only, design tokens only.
Sandbox-gated artifact storage:
The Artifact Storage section on /u/settings (S3-compatible bucket for
the in-browser sandbox export feature) now renders only when the
current shop has sandbox_mode enabled. The bucket has exactly one
consumer (views/user_sandbox.py via static/js/sandbox.js), so when
sandbox is off there is no reason to surface the credential form.
Functional test in test_functional.py asserts both states.