feat(slack): answer the order nudge in Slack, without opening the app
ci / lint-test (push) Successful in 40s
ci / lint-test (push) Successful in 40s
Being sent to a web app to answer "was this shared?" is enough friction that the question stops getting answered — which is the exact failure the nudge exists to prevent. So the buttons now act in place: pressing "Shared 50/50" writes the transaction_splits row and edits the message, and the app is never opened. Slack does NOT reach this route directly. It posts to an n8n webhook that forwards the raw body and signature headers here (user's suggestion). That is the better shape: n8n already terminates public webhooks, so the app keeps its blanket OAuth chain and gains no internet-facing unauthenticated route, and no Traefik change is needed. n8n cannot verify the signature itself — its Code sandbox has no `require`, so no `crypto`. Two independent gates, both failing closed: the shared x-ingest-token (came from n8n) and Slack's v0 signature over the raw body (came from Slack, not replayed within 5 minutes). An unset signing secret rejects everything rather than waving it through, because the alternative turns a misconfigured deploy into an open write endpoint. An unmapped Slack user is refused rather than defaulted to the owner. In a two-person household a wrong attribution is not a rounding error, it is the other person's opinion recorded under your name. Block Kit is built in the app (ingest returns slack_blocks) rather than in n8n expressions: a template string is untestable, and this shape has to stay in step with what the interactive endpoint re-renders after each press. Null when there is no transaction yet — a card-settled order is parked until its statement arrives, so there is nothing to split or rate. Also: /transactions now honours ?q=, so the link lands on the row instead of the top of an unfiltered ledger.
This commit is contained in:
@@ -12,6 +12,7 @@ import {
|
||||
type MessageMeta,
|
||||
} from "@/lib/order-ingestion";
|
||||
import { merchantVerdict } from "@/lib/order-reviews";
|
||||
import { nudgeBlocks } from "@/lib/slack-blocks";
|
||||
|
||||
/**
|
||||
* Machine ingest endpoint for order receipts.
|
||||
@@ -99,6 +100,24 @@ export async function POST(req: NextRequest) {
|
||||
counts: verdict.counts,
|
||||
last_note: verdict.history.find((h) => h.note)?.note ?? null,
|
||||
},
|
||||
// The nudge message is built here, not in n8n expressions: Block Kit in a
|
||||
// template string is untestable, and this shape has to stay in step with
|
||||
// what /api/slack/interactive renders after a button press. Null when
|
||||
// there is no transaction to act on — a card-settled order is parked
|
||||
// until its statement arrives, so there is nothing yet to split or rate.
|
||||
slack_blocks:
|
||||
result.transactionId && !result.skipped
|
||||
? nudgeBlocks({
|
||||
transactionId: result.transactionId,
|
||||
merchant: order.merchant_name,
|
||||
currency: order.currency,
|
||||
total: Number(order.totals.total_charged),
|
||||
isFamily: order.is_family,
|
||||
shared: false,
|
||||
warn: verdict?.warn ?? false,
|
||||
warnNote: verdict?.history.find((h) => h.note)?.note ?? null,
|
||||
})
|
||||
: null,
|
||||
});
|
||||
} catch (e) {
|
||||
// Not a receipt: promotions, delivery updates, adjustment and refund
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { queryRaw, queryRow } from "@/lib/db";
|
||||
import { verifySlackSignature, participantForSlackUser } from "@/lib/slack-verify";
|
||||
import { nudgeBlocks } from "@/lib/slack-blocks";
|
||||
import {
|
||||
RATINGS,
|
||||
SECOND_CONSUMER_ID,
|
||||
merchantVerdict,
|
||||
type Rating,
|
||||
} from "@/lib/order-reviews";
|
||||
|
||||
/**
|
||||
* Slack button presses on the order nudge.
|
||||
*
|
||||
* Pressing "Shared 50/50" splits the transaction here and now and edits the
|
||||
* message in place. It deliberately does NOT link back to the app: being sent
|
||||
* to a web app to answer a yes/no question is enough friction that the question
|
||||
* stops getting answered (user, 2026-07-28).
|
||||
*
|
||||
* **Slack does not reach this route directly.** It posts to an n8n webhook,
|
||||
* which forwards the raw body and Slack's signature headers here. That was the
|
||||
* user's suggestion (2026-07-28) and it is the better shape: n8n already
|
||||
* terminates public webhooks, so the app keeps its blanket OAuth chain and
|
||||
* gains no internet-facing unauthenticated route. n8n cannot do the verifying
|
||||
* itself — its Code node sandbox has no `require`, so no `crypto`.
|
||||
*
|
||||
* Two independent gates, both fail closed:
|
||||
* 1. `x-ingest-token`, proving the call came from n8n over the internal
|
||||
* network. Same shared secret as the order ingest route.
|
||||
* 2. Slack's v0 request signature over the forwarded raw body, proving the
|
||||
* payload really came from Slack and is not a replay.
|
||||
*
|
||||
* Returning a message body directly replaces the original message. That is why
|
||||
* there is no call to `response_url`: the reply IS the update, and it keeps the
|
||||
* whole interaction inside Slack's 3-second budget.
|
||||
*/
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const expected = process.env.ORDER_INGEST_TOKEN;
|
||||
if (!expected || req.headers.get("x-ingest-token") !== expected) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
// Must be the RAW body Slack signed — re-serialising the parsed form changes
|
||||
// the bytes and every signature check fails. n8n forwards it verbatim.
|
||||
const raw = await req.text();
|
||||
if (
|
||||
!verifySlackSignature(
|
||||
raw,
|
||||
req.headers.get("x-slack-request-timestamp"),
|
||||
req.headers.get("x-slack-signature")
|
||||
)
|
||||
) {
|
||||
return NextResponse.json({ error: "bad signature" }, { status: 401 });
|
||||
}
|
||||
|
||||
const payloadRaw = new URLSearchParams(raw).get("payload");
|
||||
if (!payloadRaw) return NextResponse.json({ error: "no payload" }, { status: 400 });
|
||||
|
||||
const payload = JSON.parse(payloadRaw);
|
||||
if (payload.type !== "block_actions") return new NextResponse(null, { status: 200 });
|
||||
|
||||
const action = payload.actions?.[0];
|
||||
const [idStr, verb, arg] = String(action?.value ?? "").split(":");
|
||||
const transactionId = Number(idStr);
|
||||
if (!Number.isInteger(transactionId)) {
|
||||
return NextResponse.json({ text: "Could not tell which order that was." });
|
||||
}
|
||||
|
||||
const participantId = participantForSlackUser(payload.user?.id ?? "");
|
||||
if (!participantId) {
|
||||
// Ephemeral: only the presser sees it, so an unmapped colleague does not
|
||||
// rewrite the shared message for everyone.
|
||||
return NextResponse.json({
|
||||
response_type: "ephemeral",
|
||||
replace_original: false,
|
||||
text: `I don't know which participant ${payload.user?.id} is — add them to SLACK_USER_MAP.`,
|
||||
});
|
||||
}
|
||||
|
||||
if (verb === "share") {
|
||||
await toggleShare(transactionId);
|
||||
} else if (verb === "rate" && RATINGS.includes(arg as Rating)) {
|
||||
await setRating(transactionId, participantId, arg as Rating);
|
||||
}
|
||||
|
||||
const state = await nudgeState(transactionId);
|
||||
if (!state) return NextResponse.json({ text: "That order is no longer in the ledger." });
|
||||
|
||||
return NextResponse.json({
|
||||
replace_original: true,
|
||||
blocks: nudgeBlocks(state),
|
||||
// Notification text for clients that cannot render blocks.
|
||||
text: `${state.merchant} — ${state.currency} ${state.total.toFixed(2)}`,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Share or unshare, as a real 50/50 split.
|
||||
*
|
||||
* The split IS the record that an order was shared, so there is no separate
|
||||
* flag to keep in step. Safe to clear on an ingested order because such a row
|
||||
* is post-cutover by construction — the DB CHECK forbids credits orders before
|
||||
* 2026-01-09 — so there is no settled historical obligation to lose.
|
||||
*/
|
||||
async function toggleShare(transactionId: number) {
|
||||
const existing = await queryRaw<{ participant_id: number }>(
|
||||
`SELECT participant_id FROM transaction_splits WHERE transaction_id = $1`,
|
||||
[transactionId]
|
||||
);
|
||||
if (existing.some((e) => e.participant_id === SECOND_CONSUMER_ID)) {
|
||||
await queryRaw(`DELETE FROM transaction_splits WHERE transaction_id = $1`, [
|
||||
transactionId,
|
||||
]);
|
||||
return;
|
||||
}
|
||||
await queryRaw(
|
||||
`INSERT INTO transaction_splits (transaction_id, participant_id, share_percent)
|
||||
VALUES ($1, $2, 50)
|
||||
ON CONFLICT (transaction_id, participant_id)
|
||||
DO UPDATE SET share_percent = 50`,
|
||||
[transactionId, SECOND_CONSUMER_ID]
|
||||
);
|
||||
}
|
||||
|
||||
async function setRating(transactionId: number, participantId: number, rating: Rating) {
|
||||
await queryRaw(
|
||||
`INSERT INTO order_reviews (transaction_id, participant_id, rating, order_again)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
ON CONFLICT (transaction_id, participant_id) DO UPDATE
|
||||
SET rating = EXCLUDED.rating,
|
||||
order_again = EXCLUDED.order_again,
|
||||
updated_at = now()`,
|
||||
[transactionId, participantId, rating, rating !== "never"]
|
||||
);
|
||||
}
|
||||
|
||||
/** Everything the refreshed message needs, read back after the write. */
|
||||
async function nudgeState(transactionId: number) {
|
||||
const row = await queryRow<{
|
||||
merchant: string | null;
|
||||
currency: string | null;
|
||||
amount: string;
|
||||
}>(
|
||||
`SELECT em.merchant_normalized AS merchant,
|
||||
COALESCE(em.currency, 'AUD') AS currency,
|
||||
t.amount
|
||||
FROM transactions t
|
||||
LEFT JOIN expense_metadata em
|
||||
ON em.transaction_id = t.id OR em.matched_transaction_id = t.id
|
||||
WHERE t.id = $1`,
|
||||
[transactionId]
|
||||
);
|
||||
if (!row) return null;
|
||||
|
||||
const [splits, ratings, verdict] = await Promise.all([
|
||||
queryRaw<{ participant_id: number }>(
|
||||
`SELECT participant_id FROM transaction_splits WHERE transaction_id = $1`,
|
||||
[transactionId]
|
||||
),
|
||||
queryRaw<{ name: string; rating: Rating }>(
|
||||
`SELECT p.name, r.rating FROM order_reviews r
|
||||
JOIN participants p ON p.id = r.participant_id
|
||||
WHERE r.transaction_id = $1 AND r.rating IS NOT NULL
|
||||
ORDER BY r.participant_id`,
|
||||
[transactionId]
|
||||
),
|
||||
merchantVerdict(row.merchant, transactionId),
|
||||
]);
|
||||
|
||||
return {
|
||||
transactionId,
|
||||
merchant: row.merchant ?? "Unknown merchant",
|
||||
currency: row.currency ?? "AUD",
|
||||
total: Number(row.amount),
|
||||
shared: splits.some((s) => s.participant_id === SECOND_CONSUMER_ID),
|
||||
ratings,
|
||||
warn: verdict?.warn ?? false,
|
||||
warnNote: verdict?.history.find((h) => h.note)?.note ?? null,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user