30 problema envio emails - #33

Merged
rbxyz merged 2 commits into
mainfrom
30-problema-envio-emails
Aug 22, 2025
Merged

30 problema envio emails#33
rbxyz merged 2 commits into
mainfrom
30-problema-envio-emails

Conversation

@rbxyz

@rbxyzrbxyz commented Aug 22, 2025

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • Bug Fixes

    • Restaurant order emails now group items consistently and predictably.
    • Handles accents/case, duplicate or conflicting options, and fills missing Feijão/Salada with “Não” when absent.
    • Ensures canonical option order and clearer labels (e.g., “{prato} com Feijão: X, Salada: Y, …” or “sem adicional”).
  • Refactor

    • Improved internal naming for per-restaurant order data.
    • Added timestamp logging during daily processing.

@rbxyzrbxyz linked an issue Aug 22, 2025 that may be closed by this pull request
@coderabbitai

coderabbitaiBot commented Aug 22, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Refactors cron route logging and variable names for per-restaurant order processing without changing behavior. Overhauls email grouping logic to normalize and deterministically parse option tokens (p.opc), handling diacritics, case, duplicates, and defaults, producing canonicalized strings for grouping while preserving the existing public API.

Changes

Cohort / File(s)Summary
Cron route processing tweaks
src/app/api/cron/food_orders/route.ts
Added a log for normalized current date. Renamed inner collection from orders to ordersData and updated all references, including grouped orders source, conditionals, and logs. No public API changes.
Email grouping normalization
src/lib/mail/html-mock.ts
Introduced normalizeStr and replaced opc parsing with token-based, diacritic/case-insensitive logic. Normalizes keys/values (e.g., Feijão/Salada, Sim/Não), resolves duplicates, fills missing defaults, orders keys deterministically, and returns canonical grouping strings. Public signatures unchanged.

Sequence Diagram(s)

sequenceDiagram
autonumber
participant Cron as Cron Route
participant DB as Orders Source
participant Grouper as Opc Normalizer (updated)
participant Mail as Email Builder/Sender
Cron->>DB: Fetch today's orders
Cron->>Cron: Normalize date to midnight (log)
loop per restaurant
Cron->>Grouper: Build grouped keys from p.opc
Note right of Grouper: New deterministic parsing<br/>• normalize diacritics/case<br/>• resolve duplicates<br/>• fill defaults
Grouper-->>Cron: Canonical grouping strings
Cron->>Mail: Generate grouped email sections
Mail-->>Cron: Email content
Cron->>Mail: Send email
Mail-->>Cron: Result (success/failure)
end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • jdalmeida

Poem

A whisk of bytes, a nibble of logs,
I hop through orders, past digital fogs.
Opc now tidy—Feijão says “Sim”!
Salada replies, in canonical trim.
Grouped and mailed, with a twitch of my ear—
Ship it, ship it, lunch hour draws near! 🥕🐇

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 30-problema-envio-emails

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@vercel

vercelBot commented Aug 22, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentPreviewCommentsUpdated (UTC)
eloReadyReadyPreviewCommentAug 22, 2025 2:53pm

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
src/lib/mail/html-mock.ts (1)

598-606: Security: escape dynamic HTML to prevent injection in emails

User-controlled fields (e.g., funcionário, observações) and DB-configured strings (opções, pratos) are injected raw into HTML. Many email clients render HTML and allow URLs; this is a phishing/XSS vector. Escape all dynamic text before embedding in the template. Key strings produced by getGroupKey can also contain raw option names.

Minimal patch:

+ function escapeHtml(s: string): string {+ return String(s)+ .replace(/&/g, "&amp;")+ .replace(/</g, "&lt;")+ .replace(/>/g, "&gt;")+ .replace(/"/g, "&quot;")+ .replace(/'/g, "&#39;");+ }
...
- const totalsHtml = Array.from(groups.entries())- .map(([key, arr]) => `<li><strong>Total de pedidos de ${key}:</strong> ${arr.length}</li>`)+ const totalsHtml = Array.from(groups.entries())+ .map(([key, arr]) => `<li><strong>Total de pedidos de ${escapeHtml(key)}:</strong> ${arr.length}</li>`)
.join("");
const sectionsHtml = Array.from(groups.entries())
.map(([key, arr]) => {
const itemsHtml = arr
.map(
(p) => `
<div class="pedido">
- <div><strong>Pedido:</strong> ${p.num}</div>- <div><strong>Data:</strong> ${p.data}</div>- <div><strong>Funcionário:</strong> ${p.func}</div>- <div><strong>Prato:</strong> ${p.prato}</div>- <div><strong>Opcionais:</strong> ${(p.opc ?? "").trim() || "-"}</div>- <div><strong>Observações:</strong> ${p.obs ?? "-"}</div>+ <div><strong>Pedido:</strong> ${p.num}</div>+ <div><strong>Data:</strong> ${escapeHtml(p.data)}</div>+ <div><strong>Funcionário:</strong> ${escapeHtml(p.func)}</div>+ <div><strong>Prato:</strong> ${escapeHtml(p.prato)}</div>+ <div><strong>Opcionais:</strong> ${escapeHtml(((p.opc ?? "").trim() || "-"))}</div>+ <div><strong>Observações:</strong> ${escapeHtml(p.obs ?? "-")}</div>
</div>
`,
)
.join("");
return `
<section class="group">
- <h2>${key}</h2>- <div class="group-count">Total de pedidos de ${key}: ${arr.length}</div>+ <h2>${escapeHtml(key)}</h2>+ <div class="group-count">Total de pedidos de ${escapeHtml(key)}: ${arr.length}</div>
<div class="pedidos">
${itemsHtml}
</div>
</section>
`;
})

Optionally also escape nomeRestaurante in the header. I can provide a follow-up patch covering all templates in this file if you want.

Also applies to: 620-623, 606-617, 612-614

src/app/api/cron/food_orders/route.ts (2)

11-19: Bug: equality on Date (midnight) + server timezone likely filters out valid orders; use day range in a fixed tz

Using orderDate: today where today is set to 00:00:00.000 in the server’s local tz typically misses rows whose timestamps aren’t exactly midnight. In serverless/containers (often UTC), this gets worse for BR users. Query by [startOfDay, endOfDay) in America/Sao_Paulo and also format dataPedidos in the same tz.

Apply this diff:

- const today = new Date();- today.setHours(0, 0, 0, 0);- console.log("| CRONJOB | Data de hoje:", today);+ const now = new Date();+ const tz = "America/Sao_Paulo";+ const fmt = new Intl.DateTimeFormat("pt-BR", {+ timeZone: tz,+ year: "numeric",+ month: "2-digit",+ day: "2-digit",+ });+ const parts = fmt.formatToParts(now);+ const year = Number(parts.find(p => p.type === "year")!.value);+ const month = Number(parts.find(p => p.type === "month")!.value);+ const day = Number(parts.find(p => p.type === "day")!.value);+ const startOfDay = new Date(Date.UTC(year, month - 1, day, 0, 0, 0, 0));+ const endOfDay = new Date(Date.UTC(year, month - 1, day + 1, 0, 0, 0, 0));+ console.log("| CRONJOB | Data de hoje (America/Sao_Paulo):", fmt.format(now), "| janela:", startOfDay.toISOString(), "->", endOfDay.toISOString());
// Buscar todos os pedidos de hoje
const orders = await db.foodOrder.findMany({
where: {
- orderDate: today,+ orderDate: {+ gte: startOfDay,+ lt: endOfDay,+ },
status: "PENDING",
},

And later when building the display date:

- const dataPedidos = today.toLocaleDateString('pt-BR');+ const dataPedidos = fmt.format(now);

Also applies to: 63-64


11-19: Convert Exact-Date Filters to Day-Range Queries

We’ve identified several places where orderDate is compared by exact equality—this will miss orders with timestamps later in the day. To ensure you’re capturing the full day, each equality filter should be replaced with a half-open range filter:

where: {orderDate: {gte: startOfDay,lt: nextDayStart,},// …}

Please update the following occurrences:

src/server/api/routers/food-order.ts
– Lines ~21: orderDate: new Date(input.orderDate.setHours(0, 0, 0, 0))
– Line 67: orderDate: input.orderDate
– Line 266: { ...(input.startDate && input.endDate && { orderDate: new Date(input.startDate.setHours(0, 0, 0, 0)) }) }
– Lines ~510: orderDate: today
– Line 531: orderDate: date

src/app/api/cron/food_orders/route.ts
– Lines 17–19: orderDate: today

src/app/(authenticated)/food/page.tsx
– Line 172: client-pass-through orderDate: orderDate

src/app/(authenticated)/admin/food/page.tsx
– Line 354: orderDate: signatureExportDate

Rather than matching orderDate exactly at midnight, calculate startOfDay = today.setHours(0,0,0,0) and nextDayStart = new Date(startOfDay).setDate(startOfDay.getDate()+1), then use:

where: {orderDate: {gte: startOfDay,lt: nextDayStart},status: "PENDING",// …}

This change ensures you include all orders placed any time during the target day.

🧹 Nitpick comments (4)
src/lib/mail/html-mock.ts (2)

566-569: Nit: reuse a Collator instance to avoid repeated localeCompare setup in sort

Creating a Collator once and reusing its compare function is a tiny perf/readability improvement.

- .sort((a, b) =>- a[1].display.localeCompare(b[1].display, "pt-BR", {- sensitivity: "base",- }),- )+ .sort(() => {+ const collator = new Intl.Collator("pt-BR", { sensitivity: "base" });+ return (a, b) => collator.compare(a[1].display, b[1].display);+ }())

598-606: Optional: sort groups for deterministic email sections (e.g., by count desc, then alpha)

Stable ordering improves readability and diffability in email archives. Current Map iteration order depends on first-seen items.

- const totalsHtml = Array.from(groups.entries())+ const sortedGroups = Array.from(groups.entries()).sort((a, b) => {+ const byCount = b[1].length - a[1].length;+ return byCount !== 0 ? byCount : a[0].localeCompare(b[0], "pt-BR", { sensitivity: "base" });+ });++ const totalsHtml = sortedGroups
.map(([key, arr]) => `<li><strong>Total de pedidos de ${escapeHtml(key)}:</strong> ${arr.length}</li>`)
.join("");
- const sectionsHtml = Array.from(groups.entries())+ const sectionsHtml = sortedGroups
.map(([key, arr]) => {
...
})
.join("");

Also applies to: 602-629

src/app/api/cron/food_orders/route.ts (2)

88-101: Resilience: isolate per-restaurant sendEmail in its own try/catch to avoid aborting the loop

A single SMTP failure will currently stop processing for remaining restaurants. Wrap per-restaurant send with try/catch; continue on error.

- const emailContent = emailPedidosRestauranteAgrupado(+ const emailContent = emailPedidosRestauranteAgrupado(
restaurant.name,
dataPedidos,
pedidosAgrupados,
);
-- await sendEmail(- restaurant.email,- `Pedidos do Dia - ${restaurant.name}`,- emailContent,- "rh@boxdistribuidor.com.br"- );-- console.log(`| CRONJOB | Email enviado para ${restaurant.name} com ${ordersData.length} pedidos`);+ try {+ await sendEmail(+ restaurant.email,+ `Pedidos do Dia - ${restaurant.name}`,+ emailContent,+ "rh@boxdistribuidor.com.br"+ );+ console.log(`| CRONJOB | Email enviado para ${restaurant.name} com ${ordersData.length} pedidos`);+ } catch (e) {+ console.error(`| CRONJOB | Falha ao enviar email para ${restaurant.name}:`, e);+ }

13-14: Nit: log the human date in the same timezone used for the query

Once you adopt the tz-aware range, logging fmt.format(now) is more useful to operators than a raw Date object.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 85c45a4 and 09da98d.

📒 Files selected for processing (2)
  • src/app/api/cron/food_orders/route.ts (3 hunks)
  • src/lib/mail/html-mock.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/app/api/cron/food_orders/route.ts (1)
src/lib/mail/html-mock.ts (1)
  • GroupedEmailOrder (487-494)
🔇 Additional comments (3)
src/lib/mail/html-mock.ts (1)

496-502: LGTM on normalizeStr

Good choice for Portuguese inputs: NFD + combining mark strip + lowercase + trim covers the common diacritics in pt-BR and aligns with the “feijao/salada” normalization.

src/app/api/cron/food_orders/route.ts (2)

60-63: Rename to ordersData: clearer, avoids shadowing; LGTM

The destructuring rename clarifies intent and prevents confusion with the outer orders variable.


68-76: Stable opc generation: sorting by option then choice is a good call

This ensures deterministic opc strings fed into the grouping logic and improves email grouping predictability.

Comment on lines +520 to +545
for (const tok of tokens) {
const parts = tok.split(":");
const kRaw = parts[0]?.trim();
const vRaw = parts.slice(1).join(":").trim(); // suporta "Observação: algo: extra"
if (!kRaw || !vRaw) continue;

const kNorm = normalizeStr(kRaw);
const display =
kNorm === "feijao" ? "Feijão" : kNorm === "salada" ? "Salada" : kRaw;

const vBase = normalizeStr(vRaw);
const v = vBase.startsWith("s")
? "Sim"
: vBase.startsWith("n")
? "Não"
: vRaw;

if (map.has(kNorm)) {
// Se já existir, prioriza "Sim" se houver conflito/duplicata
const prev = map.get(kNorm)!;
const newVal = prev.value === "Sim" || v === "Sim" ? "Sim" : v;
map.set(kNorm, { display, value: newVal });
} else {
map.set(kNorm, { display, value: v });
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix: fallback when no valid "chave: valor" tokens are parsed to avoid "Prato com " keys

If every token in opc lacks a colon (e.g., "sem feijão, sem salada") or all tokens are invalid, the map stays empty. The current flow then builds an empty ordered list and returns something like "Prato com " (note the trailing space), producing a misleading and unstable grouping key.

Add a guard to treat this as “sem adicional” when map.size === 0, before the allNo check.

Apply this diff:

 // Completa pares esperados: se só veio Salada, assume Feijão: Não; e vice-versa
const hasFeijao = map.has("feijao");
const hasSalada = map.has("salada");
if (hasFeijao && !hasSalada) map.set("salada", { display: "Salada", value: "Não" });
if (hasSalada && !hasFeijao) map.set("feijao", { display: "Feijão", value: "Não" });
+ // Se nenhum par válido foi extraído, trata como "sem adicional"+ if (map.size === 0) return `${p.prato} sem adicional`;
// Se tudo é "Não", trata como "sem adicional"
const entries = Array.from(map.values());
const allNo = entries.length > 0 && entries.every((e) => e.value === "Não");
if (allNo) return `${p.prato} sem adicional`;
// Ordena: Feijão, Salada, depois demais chaves em ordem alfabética

Also applies to: 554-557, 573-577

🤖 Prompt for AI Agents
In src/lib/mail/html-mock.ts around lines 520-545 (and similarly at 554-557 and
573-577), add a guard that if after parsing tokens the map is empty (map.size
=== 0) then insert a fallback entry to represent "sem adicional" before the
existing allNo check; specifically set map.set("sem adicional", { display: "Sem
adicional", value: "Não" }) (or equivalent normalized key/display/value you use
elsewhere) so the subsequent formatting produces a stable "Sem adicional"
grouping instead of "Prato com " or an empty list.

@rbxyz
rbxyz merged commit 47d0f7e into mainAug 22, 2025
6 checks passed
@rbxyz
rbxyz deleted the 30-problema-envio-emails branch September 2, 2025 11:08
@coderabbitaicoderabbitaiBot mentioned this pull request Dec 9, 2025
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

problema-envio-emails

1 participant

@rbxyz
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

30 problema envio emails - #33

Merged
rbxyz merged 2 commits into
mainfrom
30-problema-envio-emails
Aug 22, 2025
Merged

30 problema envio emails#33
rbxyz merged 2 commits into
mainfrom
30-problema-envio-emails

Conversation

@rbxyz

@rbxyzrbxyz commented Aug 22, 2025

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • Bug Fixes

    • Restaurant order emails now group items consistently and predictably.
    • Handles accents/case, duplicate or conflicting options, and fills missing Feijão/Salada with “Não” when absent.
    • Ensures canonical option order and clearer labels (e.g., “{prato} com Feijão: X, Salada: Y, …” or “sem adicional”).
  • Refactor

    • Improved internal naming for per-restaurant order data.
    • Added timestamp logging during daily processing.

@rbxyzrbxyz linked an issue Aug 22, 2025 that may be closed by this pull request
@coderabbitai

coderabbitaiBot commented Aug 22, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Refactors cron route logging and variable names for per-restaurant order processing without changing behavior. Overhauls email grouping logic to normalize and deterministically parse option tokens (p.opc), handling diacritics, case, duplicates, and defaults, producing canonicalized strings for grouping while preserving the existing public API.

Changes

Cohort / File(s)Summary
Cron route processing tweaks
src/app/api/cron/food_orders/route.ts
Added a log for normalized current date. Renamed inner collection from orders to ordersData and updated all references, including grouped orders source, conditionals, and logs. No public API changes.
Email grouping normalization
src/lib/mail/html-mock.ts
Introduced normalizeStr and replaced opc parsing with token-based, diacritic/case-insensitive logic. Normalizes keys/values (e.g., Feijão/Salada, Sim/Não), resolves duplicates, fills missing defaults, orders keys deterministically, and returns canonical grouping strings. Public signatures unchanged.

Sequence Diagram(s)

sequenceDiagram
autonumber
participant Cron as Cron Route
participant DB as Orders Source
participant Grouper as Opc Normalizer (updated)
participant Mail as Email Builder/Sender
Cron->>DB: Fetch today's orders
Cron->>Cron: Normalize date to midnight (log)
loop per restaurant
Cron->>Grouper: Build grouped keys from p.opc
Note right of Grouper: New deterministic parsing<br/>• normalize diacritics/case<br/>• resolve duplicates<br/>• fill defaults
Grouper-->>Cron: Canonical grouping strings
Cron->>Mail: Generate grouped email sections
Mail-->>Cron: Email content
Cron->>Mail: Send email
Mail-->>Cron: Result (success/failure)
end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • jdalmeida

Poem

A whisk of bytes, a nibble of logs,
I hop through orders, past digital fogs.
Opc now tidy—Feijão says “Sim”!
Salada replies, in canonical trim.
Grouped and mailed, with a twitch of my ear—
Ship it, ship it, lunch hour draws near! 🥕🐇

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 30-problema-envio-emails

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@vercel

vercelBot commented Aug 22, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentPreviewCommentsUpdated (UTC)
eloReadyReadyPreviewCommentAug 22, 2025 2:53pm

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
src/lib/mail/html-mock.ts (1)

598-606: Security: escape dynamic HTML to prevent injection in emails

User-controlled fields (e.g., funcionário, observações) and DB-configured strings (opções, pratos) are injected raw into HTML. Many email clients render HTML and allow URLs; this is a phishing/XSS vector. Escape all dynamic text before embedding in the template. Key strings produced by getGroupKey can also contain raw option names.

Minimal patch:

+ function escapeHtml(s: string): string {+ return String(s)+ .replace(/&/g, "&amp;")+ .replace(/</g, "&lt;")+ .replace(/>/g, "&gt;")+ .replace(/"/g, "&quot;")+ .replace(/'/g, "&#39;");+ }
...
- const totalsHtml = Array.from(groups.entries())- .map(([key, arr]) => `<li><strong>Total de pedidos de ${key}:</strong> ${arr.length}</li>`)+ const totalsHtml = Array.from(groups.entries())+ .map(([key, arr]) => `<li><strong>Total de pedidos de ${escapeHtml(key)}:</strong> ${arr.length}</li>`)
.join("");
const sectionsHtml = Array.from(groups.entries())
.map(([key, arr]) => {
const itemsHtml = arr
.map(
(p) => `
<div class="pedido">
- <div><strong>Pedido:</strong> ${p.num}</div>- <div><strong>Data:</strong> ${p.data}</div>- <div><strong>Funcionário:</strong> ${p.func}</div>- <div><strong>Prato:</strong> ${p.prato}</div>- <div><strong>Opcionais:</strong> ${(p.opc ?? "").trim() || "-"}</div>- <div><strong>Observações:</strong> ${p.obs ?? "-"}</div>+ <div><strong>Pedido:</strong> ${p.num}</div>+ <div><strong>Data:</strong> ${escapeHtml(p.data)}</div>+ <div><strong>Funcionário:</strong> ${escapeHtml(p.func)}</div>+ <div><strong>Prato:</strong> ${escapeHtml(p.prato)}</div>+ <div><strong>Opcionais:</strong> ${escapeHtml(((p.opc ?? "").trim() || "-"))}</div>+ <div><strong>Observações:</strong> ${escapeHtml(p.obs ?? "-")}</div>
</div>
`,
)
.join("");
return `
<section class="group">
- <h2>${key}</h2>- <div class="group-count">Total de pedidos de ${key}: ${arr.length}</div>+ <h2>${escapeHtml(key)}</h2>+ <div class="group-count">Total de pedidos de ${escapeHtml(key)}: ${arr.length}</div>
<div class="pedidos">
${itemsHtml}
</div>
</section>
`;
})

Optionally also escape nomeRestaurante in the header. I can provide a follow-up patch covering all templates in this file if you want.

Also applies to: 620-623, 606-617, 612-614

src/app/api/cron/food_orders/route.ts (2)

11-19: Bug: equality on Date (midnight) + server timezone likely filters out valid orders; use day range in a fixed tz

Using orderDate: today where today is set to 00:00:00.000 in the server’s local tz typically misses rows whose timestamps aren’t exactly midnight. In serverless/containers (often UTC), this gets worse for BR users. Query by [startOfDay, endOfDay) in America/Sao_Paulo and also format dataPedidos in the same tz.

Apply this diff:

- const today = new Date();- today.setHours(0, 0, 0, 0);- console.log("| CRONJOB | Data de hoje:", today);+ const now = new Date();+ const tz = "America/Sao_Paulo";+ const fmt = new Intl.DateTimeFormat("pt-BR", {+ timeZone: tz,+ year: "numeric",+ month: "2-digit",+ day: "2-digit",+ });+ const parts = fmt.formatToParts(now);+ const year = Number(parts.find(p => p.type === "year")!.value);+ const month = Number(parts.find(p => p.type === "month")!.value);+ const day = Number(parts.find(p => p.type === "day")!.value);+ const startOfDay = new Date(Date.UTC(year, month - 1, day, 0, 0, 0, 0));+ const endOfDay = new Date(Date.UTC(year, month - 1, day + 1, 0, 0, 0, 0));+ console.log("| CRONJOB | Data de hoje (America/Sao_Paulo):", fmt.format(now), "| janela:", startOfDay.toISOString(), "->", endOfDay.toISOString());
// Buscar todos os pedidos de hoje
const orders = await db.foodOrder.findMany({
where: {
- orderDate: today,+ orderDate: {+ gte: startOfDay,+ lt: endOfDay,+ },
status: "PENDING",
},

And later when building the display date:

- const dataPedidos = today.toLocaleDateString('pt-BR');+ const dataPedidos = fmt.format(now);

Also applies to: 63-64


11-19: Convert Exact-Date Filters to Day-Range Queries

We’ve identified several places where orderDate is compared by exact equality—this will miss orders with timestamps later in the day. To ensure you’re capturing the full day, each equality filter should be replaced with a half-open range filter:

where: {orderDate: {gte: startOfDay,lt: nextDayStart,},// …}

Please update the following occurrences:

src/server/api/routers/food-order.ts
– Lines ~21: orderDate: new Date(input.orderDate.setHours(0, 0, 0, 0))
– Line 67: orderDate: input.orderDate
– Line 266: { ...(input.startDate && input.endDate && { orderDate: new Date(input.startDate.setHours(0, 0, 0, 0)) }) }
– Lines ~510: orderDate: today
– Line 531: orderDate: date

src/app/api/cron/food_orders/route.ts
– Lines 17–19: orderDate: today

src/app/(authenticated)/food/page.tsx
– Line 172: client-pass-through orderDate: orderDate

src/app/(authenticated)/admin/food/page.tsx
– Line 354: orderDate: signatureExportDate

Rather than matching orderDate exactly at midnight, calculate startOfDay = today.setHours(0,0,0,0) and nextDayStart = new Date(startOfDay).setDate(startOfDay.getDate()+1), then use:

where: {orderDate: {gte: startOfDay,lt: nextDayStart},status: "PENDING",// …}

This change ensures you include all orders placed any time during the target day.

🧹 Nitpick comments (4)
src/lib/mail/html-mock.ts (2)

566-569: Nit: reuse a Collator instance to avoid repeated localeCompare setup in sort

Creating a Collator once and reusing its compare function is a tiny perf/readability improvement.

- .sort((a, b) =>- a[1].display.localeCompare(b[1].display, "pt-BR", {- sensitivity: "base",- }),- )+ .sort(() => {+ const collator = new Intl.Collator("pt-BR", { sensitivity: "base" });+ return (a, b) => collator.compare(a[1].display, b[1].display);+ }())

598-606: Optional: sort groups for deterministic email sections (e.g., by count desc, then alpha)

Stable ordering improves readability and diffability in email archives. Current Map iteration order depends on first-seen items.

- const totalsHtml = Array.from(groups.entries())+ const sortedGroups = Array.from(groups.entries()).sort((a, b) => {+ const byCount = b[1].length - a[1].length;+ return byCount !== 0 ? byCount : a[0].localeCompare(b[0], "pt-BR", { sensitivity: "base" });+ });++ const totalsHtml = sortedGroups
.map(([key, arr]) => `<li><strong>Total de pedidos de ${escapeHtml(key)}:</strong> ${arr.length}</li>`)
.join("");
- const sectionsHtml = Array.from(groups.entries())+ const sectionsHtml = sortedGroups
.map(([key, arr]) => {
...
})
.join("");

Also applies to: 602-629

src/app/api/cron/food_orders/route.ts (2)

88-101: Resilience: isolate per-restaurant sendEmail in its own try/catch to avoid aborting the loop

A single SMTP failure will currently stop processing for remaining restaurants. Wrap per-restaurant send with try/catch; continue on error.

- const emailContent = emailPedidosRestauranteAgrupado(+ const emailContent = emailPedidosRestauranteAgrupado(
restaurant.name,
dataPedidos,
pedidosAgrupados,
);
-- await sendEmail(- restaurant.email,- `Pedidos do Dia - ${restaurant.name}`,- emailContent,- "rh@boxdistribuidor.com.br"- );-- console.log(`| CRONJOB | Email enviado para ${restaurant.name} com ${ordersData.length} pedidos`);+ try {+ await sendEmail(+ restaurant.email,+ `Pedidos do Dia - ${restaurant.name}`,+ emailContent,+ "rh@boxdistribuidor.com.br"+ );+ console.log(`| CRONJOB | Email enviado para ${restaurant.name} com ${ordersData.length} pedidos`);+ } catch (e) {+ console.error(`| CRONJOB | Falha ao enviar email para ${restaurant.name}:`, e);+ }

13-14: Nit: log the human date in the same timezone used for the query

Once you adopt the tz-aware range, logging fmt.format(now) is more useful to operators than a raw Date object.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 85c45a4 and 09da98d.

📒 Files selected for processing (2)
  • src/app/api/cron/food_orders/route.ts (3 hunks)
  • src/lib/mail/html-mock.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/app/api/cron/food_orders/route.ts (1)
src/lib/mail/html-mock.ts (1)
  • GroupedEmailOrder (487-494)
🔇 Additional comments (3)
src/lib/mail/html-mock.ts (1)

496-502: LGTM on normalizeStr

Good choice for Portuguese inputs: NFD + combining mark strip + lowercase + trim covers the common diacritics in pt-BR and aligns with the “feijao/salada” normalization.

src/app/api/cron/food_orders/route.ts (2)

60-63: Rename to ordersData: clearer, avoids shadowing; LGTM

The destructuring rename clarifies intent and prevents confusion with the outer orders variable.


68-76: Stable opc generation: sorting by option then choice is a good call

This ensures deterministic opc strings fed into the grouping logic and improves email grouping predictability.

Comment on lines +520 to +545
for (const tok of tokens) {
const parts = tok.split(":");
const kRaw = parts[0]?.trim();
const vRaw = parts.slice(1).join(":").trim(); // suporta "Observação: algo: extra"
if (!kRaw || !vRaw) continue;

const kNorm = normalizeStr(kRaw);
const display =
kNorm === "feijao" ? "Feijão" : kNorm === "salada" ? "Salada" : kRaw;

const vBase = normalizeStr(vRaw);
const v = vBase.startsWith("s")
? "Sim"
: vBase.startsWith("n")
? "Não"
: vRaw;

if (map.has(kNorm)) {
// Se já existir, prioriza "Sim" se houver conflito/duplicata
const prev = map.get(kNorm)!;
const newVal = prev.value === "Sim" || v === "Sim" ? "Sim" : v;
map.set(kNorm, { display, value: newVal });
} else {
map.set(kNorm, { display, value: v });
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix: fallback when no valid "chave: valor" tokens are parsed to avoid "Prato com " keys

If every token in opc lacks a colon (e.g., "sem feijão, sem salada") or all tokens are invalid, the map stays empty. The current flow then builds an empty ordered list and returns something like "Prato com " (note the trailing space), producing a misleading and unstable grouping key.

Add a guard to treat this as “sem adicional” when map.size === 0, before the allNo check.

Apply this diff:

 // Completa pares esperados: se só veio Salada, assume Feijão: Não; e vice-versa
const hasFeijao = map.has("feijao");
const hasSalada = map.has("salada");
if (hasFeijao && !hasSalada) map.set("salada", { display: "Salada", value: "Não" });
if (hasSalada && !hasFeijao) map.set("feijao", { display: "Feijão", value: "Não" });
+ // Se nenhum par válido foi extraído, trata como "sem adicional"+ if (map.size === 0) return `${p.prato} sem adicional`;
// Se tudo é "Não", trata como "sem adicional"
const entries = Array.from(map.values());
const allNo = entries.length > 0 && entries.every((e) => e.value === "Não");
if (allNo) return `${p.prato} sem adicional`;
// Ordena: Feijão, Salada, depois demais chaves em ordem alfabética

Also applies to: 554-557, 573-577

🤖 Prompt for AI Agents
In src/lib/mail/html-mock.ts around lines 520-545 (and similarly at 554-557 and
573-577), add a guard that if after parsing tokens the map is empty (map.size
=== 0) then insert a fallback entry to represent "sem adicional" before the
existing allNo check; specifically set map.set("sem adicional", { display: "Sem
adicional", value: "Não" }) (or equivalent normalized key/display/value you use
elsewhere) so the subsequent formatting produces a stable "Sem adicional"
grouping instead of "Prato com " or an empty list.

@rbxyz
rbxyz merged commit 47d0f7e into mainAug 22, 2025
6 checks passed
@rbxyz
rbxyz deleted the 30-problema-envio-emails branch September 2, 2025 11:08
@coderabbitaicoderabbitaiBot mentioned this pull request Dec 9, 2025
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

problema-envio-emails

1 participant

@rbxyz
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

30 problema envio emails - #33

Merged
rbxyz merged 2 commits into
mainfrom
30-problema-envio-emails
Aug 22, 2025
Merged

30 problema envio emails#33
rbxyz merged 2 commits into
mainfrom
30-problema-envio-emails

Conversation

@rbxyz

@rbxyzrbxyz commented Aug 22, 2025

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • Bug Fixes

    • Restaurant order emails now group items consistently and predictably.
    • Handles accents/case, duplicate or conflicting options, and fills missing Feijão/Salada with “Não” when absent.
    • Ensures canonical option order and clearer labels (e.g., “{prato} com Feijão: X, Salada: Y, …” or “sem adicional”).
  • Refactor

    • Improved internal naming for per-restaurant order data.
    • Added timestamp logging during daily processing.

@rbxyzrbxyz linked an issue Aug 22, 2025 that may be closed by this pull request
@coderabbitai

coderabbitaiBot commented Aug 22, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Refactors cron route logging and variable names for per-restaurant order processing without changing behavior. Overhauls email grouping logic to normalize and deterministically parse option tokens (p.opc), handling diacritics, case, duplicates, and defaults, producing canonicalized strings for grouping while preserving the existing public API.

Changes

Cohort / File(s)Summary
Cron route processing tweaks
src/app/api/cron/food_orders/route.ts
Added a log for normalized current date. Renamed inner collection from orders to ordersData and updated all references, including grouped orders source, conditionals, and logs. No public API changes.
Email grouping normalization
src/lib/mail/html-mock.ts
Introduced normalizeStr and replaced opc parsing with token-based, diacritic/case-insensitive logic. Normalizes keys/values (e.g., Feijão/Salada, Sim/Não), resolves duplicates, fills missing defaults, orders keys deterministically, and returns canonical grouping strings. Public signatures unchanged.

Sequence Diagram(s)

sequenceDiagram
autonumber
participant Cron as Cron Route
participant DB as Orders Source
participant Grouper as Opc Normalizer (updated)
participant Mail as Email Builder/Sender
Cron->>DB: Fetch today's orders
Cron->>Cron: Normalize date to midnight (log)
loop per restaurant
Cron->>Grouper: Build grouped keys from p.opc
Note right of Grouper: New deterministic parsing<br/>• normalize diacritics/case<br/>• resolve duplicates<br/>• fill defaults
Grouper-->>Cron: Canonical grouping strings
Cron->>Mail: Generate grouped email sections
Mail-->>Cron: Email content
Cron->>Mail: Send email
Mail-->>Cron: Result (success/failure)
end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • jdalmeida

Poem

A whisk of bytes, a nibble of logs,
I hop through orders, past digital fogs.
Opc now tidy—Feijão says “Sim”!
Salada replies, in canonical trim.
Grouped and mailed, with a twitch of my ear—
Ship it, ship it, lunch hour draws near! 🥕🐇

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 30-problema-envio-emails

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@vercel

vercelBot commented Aug 22, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentPreviewCommentsUpdated (UTC)
eloReadyReadyPreviewCommentAug 22, 2025 2:53pm

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
src/lib/mail/html-mock.ts (1)

598-606: Security: escape dynamic HTML to prevent injection in emails

User-controlled fields (e.g., funcionário, observações) and DB-configured strings (opções, pratos) are injected raw into HTML. Many email clients render HTML and allow URLs; this is a phishing/XSS vector. Escape all dynamic text before embedding in the template. Key strings produced by getGroupKey can also contain raw option names.

Minimal patch:

+ function escapeHtml(s: string): string {+ return String(s)+ .replace(/&/g, "&amp;")+ .replace(/</g, "&lt;")+ .replace(/>/g, "&gt;")+ .replace(/"/g, "&quot;")+ .replace(/'/g, "&#39;");+ }
...
- const totalsHtml = Array.from(groups.entries())- .map(([key, arr]) => `<li><strong>Total de pedidos de ${key}:</strong> ${arr.length}</li>`)+ const totalsHtml = Array.from(groups.entries())+ .map(([key, arr]) => `<li><strong>Total de pedidos de ${escapeHtml(key)}:</strong> ${arr.length}</li>`)
.join("");
const sectionsHtml = Array.from(groups.entries())
.map(([key, arr]) => {
const itemsHtml = arr
.map(
(p) => `
<div class="pedido">
- <div><strong>Pedido:</strong> ${p.num}</div>- <div><strong>Data:</strong> ${p.data}</div>- <div><strong>Funcionário:</strong> ${p.func}</div>- <div><strong>Prato:</strong> ${p.prato}</div>- <div><strong>Opcionais:</strong> ${(p.opc ?? "").trim() || "-"}</div>- <div><strong>Observações:</strong> ${p.obs ?? "-"}</div>+ <div><strong>Pedido:</strong> ${p.num}</div>+ <div><strong>Data:</strong> ${escapeHtml(p.data)}</div>+ <div><strong>Funcionário:</strong> ${escapeHtml(p.func)}</div>+ <div><strong>Prato:</strong> ${escapeHtml(p.prato)}</div>+ <div><strong>Opcionais:</strong> ${escapeHtml(((p.opc ?? "").trim() || "-"))}</div>+ <div><strong>Observações:</strong> ${escapeHtml(p.obs ?? "-")}</div>
</div>
`,
)
.join("");
return `
<section class="group">
- <h2>${key}</h2>- <div class="group-count">Total de pedidos de ${key}: ${arr.length}</div>+ <h2>${escapeHtml(key)}</h2>+ <div class="group-count">Total de pedidos de ${escapeHtml(key)}: ${arr.length}</div>
<div class="pedidos">
${itemsHtml}
</div>
</section>
`;
})

Optionally also escape nomeRestaurante in the header. I can provide a follow-up patch covering all templates in this file if you want.

Also applies to: 620-623, 606-617, 612-614

src/app/api/cron/food_orders/route.ts (2)

11-19: Bug: equality on Date (midnight) + server timezone likely filters out valid orders; use day range in a fixed tz

Using orderDate: today where today is set to 00:00:00.000 in the server’s local tz typically misses rows whose timestamps aren’t exactly midnight. In serverless/containers (often UTC), this gets worse for BR users. Query by [startOfDay, endOfDay) in America/Sao_Paulo and also format dataPedidos in the same tz.

Apply this diff:

- const today = new Date();- today.setHours(0, 0, 0, 0);- console.log("| CRONJOB | Data de hoje:", today);+ const now = new Date();+ const tz = "America/Sao_Paulo";+ const fmt = new Intl.DateTimeFormat("pt-BR", {+ timeZone: tz,+ year: "numeric",+ month: "2-digit",+ day: "2-digit",+ });+ const parts = fmt.formatToParts(now);+ const year = Number(parts.find(p => p.type === "year")!.value);+ const month = Number(parts.find(p => p.type === "month")!.value);+ const day = Number(parts.find(p => p.type === "day")!.value);+ const startOfDay = new Date(Date.UTC(year, month - 1, day, 0, 0, 0, 0));+ const endOfDay = new Date(Date.UTC(year, month - 1, day + 1, 0, 0, 0, 0));+ console.log("| CRONJOB | Data de hoje (America/Sao_Paulo):", fmt.format(now), "| janela:", startOfDay.toISOString(), "->", endOfDay.toISOString());
// Buscar todos os pedidos de hoje
const orders = await db.foodOrder.findMany({
where: {
- orderDate: today,+ orderDate: {+ gte: startOfDay,+ lt: endOfDay,+ },
status: "PENDING",
},

And later when building the display date:

- const dataPedidos = today.toLocaleDateString('pt-BR');+ const dataPedidos = fmt.format(now);

Also applies to: 63-64


11-19: Convert Exact-Date Filters to Day-Range Queries

We’ve identified several places where orderDate is compared by exact equality—this will miss orders with timestamps later in the day. To ensure you’re capturing the full day, each equality filter should be replaced with a half-open range filter:

where: {orderDate: {gte: startOfDay,lt: nextDayStart,},// …}

Please update the following occurrences:

src/server/api/routers/food-order.ts
– Lines ~21: orderDate: new Date(input.orderDate.setHours(0, 0, 0, 0))
– Line 67: orderDate: input.orderDate
– Line 266: { ...(input.startDate && input.endDate && { orderDate: new Date(input.startDate.setHours(0, 0, 0, 0)) }) }
– Lines ~510: orderDate: today
– Line 531: orderDate: date

src/app/api/cron/food_orders/route.ts
– Lines 17–19: orderDate: today

src/app/(authenticated)/food/page.tsx
– Line 172: client-pass-through orderDate: orderDate

src/app/(authenticated)/admin/food/page.tsx
– Line 354: orderDate: signatureExportDate

Rather than matching orderDate exactly at midnight, calculate startOfDay = today.setHours(0,0,0,0) and nextDayStart = new Date(startOfDay).setDate(startOfDay.getDate()+1), then use:

where: {orderDate: {gte: startOfDay,lt: nextDayStart},status: "PENDING",// …}

This change ensures you include all orders placed any time during the target day.

🧹 Nitpick comments (4)
src/lib/mail/html-mock.ts (2)

566-569: Nit: reuse a Collator instance to avoid repeated localeCompare setup in sort

Creating a Collator once and reusing its compare function is a tiny perf/readability improvement.

- .sort((a, b) =>- a[1].display.localeCompare(b[1].display, "pt-BR", {- sensitivity: "base",- }),- )+ .sort(() => {+ const collator = new Intl.Collator("pt-BR", { sensitivity: "base" });+ return (a, b) => collator.compare(a[1].display, b[1].display);+ }())

598-606: Optional: sort groups for deterministic email sections (e.g., by count desc, then alpha)

Stable ordering improves readability and diffability in email archives. Current Map iteration order depends on first-seen items.

- const totalsHtml = Array.from(groups.entries())+ const sortedGroups = Array.from(groups.entries()).sort((a, b) => {+ const byCount = b[1].length - a[1].length;+ return byCount !== 0 ? byCount : a[0].localeCompare(b[0], "pt-BR", { sensitivity: "base" });+ });++ const totalsHtml = sortedGroups
.map(([key, arr]) => `<li><strong>Total de pedidos de ${escapeHtml(key)}:</strong> ${arr.length}</li>`)
.join("");
- const sectionsHtml = Array.from(groups.entries())+ const sectionsHtml = sortedGroups
.map(([key, arr]) => {
...
})
.join("");

Also applies to: 602-629

src/app/api/cron/food_orders/route.ts (2)

88-101: Resilience: isolate per-restaurant sendEmail in its own try/catch to avoid aborting the loop

A single SMTP failure will currently stop processing for remaining restaurants. Wrap per-restaurant send with try/catch; continue on error.

- const emailContent = emailPedidosRestauranteAgrupado(+ const emailContent = emailPedidosRestauranteAgrupado(
restaurant.name,
dataPedidos,
pedidosAgrupados,
);
-- await sendEmail(- restaurant.email,- `Pedidos do Dia - ${restaurant.name}`,- emailContent,- "rh@boxdistribuidor.com.br"- );-- console.log(`| CRONJOB | Email enviado para ${restaurant.name} com ${ordersData.length} pedidos`);+ try {+ await sendEmail(+ restaurant.email,+ `Pedidos do Dia - ${restaurant.name}`,+ emailContent,+ "rh@boxdistribuidor.com.br"+ );+ console.log(`| CRONJOB | Email enviado para ${restaurant.name} com ${ordersData.length} pedidos`);+ } catch (e) {+ console.error(`| CRONJOB | Falha ao enviar email para ${restaurant.name}:`, e);+ }

13-14: Nit: log the human date in the same timezone used for the query

Once you adopt the tz-aware range, logging fmt.format(now) is more useful to operators than a raw Date object.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 85c45a4 and 09da98d.

📒 Files selected for processing (2)
  • src/app/api/cron/food_orders/route.ts (3 hunks)
  • src/lib/mail/html-mock.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/app/api/cron/food_orders/route.ts (1)
src/lib/mail/html-mock.ts (1)
  • GroupedEmailOrder (487-494)
🔇 Additional comments (3)
src/lib/mail/html-mock.ts (1)

496-502: LGTM on normalizeStr

Good choice for Portuguese inputs: NFD + combining mark strip + lowercase + trim covers the common diacritics in pt-BR and aligns with the “feijao/salada” normalization.

src/app/api/cron/food_orders/route.ts (2)

60-63: Rename to ordersData: clearer, avoids shadowing; LGTM

The destructuring rename clarifies intent and prevents confusion with the outer orders variable.


68-76: Stable opc generation: sorting by option then choice is a good call

This ensures deterministic opc strings fed into the grouping logic and improves email grouping predictability.

Comment on lines +520 to +545
for (const tok of tokens) {
const parts = tok.split(":");
const kRaw = parts[0]?.trim();
const vRaw = parts.slice(1).join(":").trim(); // suporta "Observação: algo: extra"
if (!kRaw || !vRaw) continue;

const kNorm = normalizeStr(kRaw);
const display =
kNorm === "feijao" ? "Feijão" : kNorm === "salada" ? "Salada" : kRaw;

const vBase = normalizeStr(vRaw);
const v = vBase.startsWith("s")
? "Sim"
: vBase.startsWith("n")
? "Não"
: vRaw;

if (map.has(kNorm)) {
// Se já existir, prioriza "Sim" se houver conflito/duplicata
const prev = map.get(kNorm)!;
const newVal = prev.value === "Sim" || v === "Sim" ? "Sim" : v;
map.set(kNorm, { display, value: newVal });
} else {
map.set(kNorm, { display, value: v });
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix: fallback when no valid "chave: valor" tokens are parsed to avoid "Prato com " keys

If every token in opc lacks a colon (e.g., "sem feijão, sem salada") or all tokens are invalid, the map stays empty. The current flow then builds an empty ordered list and returns something like "Prato com " (note the trailing space), producing a misleading and unstable grouping key.

Add a guard to treat this as “sem adicional” when map.size === 0, before the allNo check.

Apply this diff:

 // Completa pares esperados: se só veio Salada, assume Feijão: Não; e vice-versa
const hasFeijao = map.has("feijao");
const hasSalada = map.has("salada");
if (hasFeijao && !hasSalada) map.set("salada", { display: "Salada", value: "Não" });
if (hasSalada && !hasFeijao) map.set("feijao", { display: "Feijão", value: "Não" });
+ // Se nenhum par válido foi extraído, trata como "sem adicional"+ if (map.size === 0) return `${p.prato} sem adicional`;
// Se tudo é "Não", trata como "sem adicional"
const entries = Array.from(map.values());
const allNo = entries.length > 0 && entries.every((e) => e.value === "Não");
if (allNo) return `${p.prato} sem adicional`;
// Ordena: Feijão, Salada, depois demais chaves em ordem alfabética

Also applies to: 554-557, 573-577

🤖 Prompt for AI Agents
In src/lib/mail/html-mock.ts around lines 520-545 (and similarly at 554-557 and
573-577), add a guard that if after parsing tokens the map is empty (map.size
=== 0) then insert a fallback entry to represent "sem adicional" before the
existing allNo check; specifically set map.set("sem adicional", { display: "Sem
adicional", value: "Não" }) (or equivalent normalized key/display/value you use
elsewhere) so the subsequent formatting produces a stable "Sem adicional"
grouping instead of "Prato com " or an empty list.

@rbxyz
rbxyz merged commit 47d0f7e into mainAug 22, 2025
6 checks passed
@rbxyz
rbxyz deleted the 30-problema-envio-emails branch September 2, 2025 11:08
@coderabbitaicoderabbitaiBot mentioned this pull request Dec 9, 2025
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

problema-envio-emails

1 participant

@rbxyz
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

30 problema envio emails - #33

Merged
rbxyz merged 2 commits into
mainfrom
30-problema-envio-emails
Aug 22, 2025
Merged

30 problema envio emails#33
rbxyz merged 2 commits into
mainfrom
30-problema-envio-emails

Conversation

@rbxyz

@rbxyzrbxyz commented Aug 22, 2025

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • Bug Fixes

    • Restaurant order emails now group items consistently and predictably.
    • Handles accents/case, duplicate or conflicting options, and fills missing Feijão/Salada with “Não” when absent.
    • Ensures canonical option order and clearer labels (e.g., “{prato} com Feijão: X, Salada: Y, …” or “sem adicional”).
  • Refactor

    • Improved internal naming for per-restaurant order data.
    • Added timestamp logging during daily processing.

@rbxyzrbxyz linked an issue Aug 22, 2025 that may be closed by this pull request
@coderabbitai

coderabbitaiBot commented Aug 22, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Refactors cron route logging and variable names for per-restaurant order processing without changing behavior. Overhauls email grouping logic to normalize and deterministically parse option tokens (p.opc), handling diacritics, case, duplicates, and defaults, producing canonicalized strings for grouping while preserving the existing public API.

Changes

Cohort / File(s)Summary
Cron route processing tweaks
src/app/api/cron/food_orders/route.ts
Added a log for normalized current date. Renamed inner collection from orders to ordersData and updated all references, including grouped orders source, conditionals, and logs. No public API changes.
Email grouping normalization
src/lib/mail/html-mock.ts
Introduced normalizeStr and replaced opc parsing with token-based, diacritic/case-insensitive logic. Normalizes keys/values (e.g., Feijão/Salada, Sim/Não), resolves duplicates, fills missing defaults, orders keys deterministically, and returns canonical grouping strings. Public signatures unchanged.

Sequence Diagram(s)

sequenceDiagram
autonumber
participant Cron as Cron Route
participant DB as Orders Source
participant Grouper as Opc Normalizer (updated)
participant Mail as Email Builder/Sender
Cron->>DB: Fetch today's orders
Cron->>Cron: Normalize date to midnight (log)
loop per restaurant
Cron->>Grouper: Build grouped keys from p.opc
Note right of Grouper: New deterministic parsing<br/>• normalize diacritics/case<br/>• resolve duplicates<br/>• fill defaults
Grouper-->>Cron: Canonical grouping strings
Cron->>Mail: Generate grouped email sections
Mail-->>Cron: Email content
Cron->>Mail: Send email
Mail-->>Cron: Result (success/failure)
end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • jdalmeida

Poem

A whisk of bytes, a nibble of logs,
I hop through orders, past digital fogs.
Opc now tidy—Feijão says “Sim”!
Salada replies, in canonical trim.
Grouped and mailed, with a twitch of my ear—
Ship it, ship it, lunch hour draws near! 🥕🐇

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 30-problema-envio-emails

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@vercel

vercelBot commented Aug 22, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentPreviewCommentsUpdated (UTC)
eloReadyReadyPreviewCommentAug 22, 2025 2:53pm

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
src/lib/mail/html-mock.ts (1)

598-606: Security: escape dynamic HTML to prevent injection in emails

User-controlled fields (e.g., funcionário, observações) and DB-configured strings (opções, pratos) are injected raw into HTML. Many email clients render HTML and allow URLs; this is a phishing/XSS vector. Escape all dynamic text before embedding in the template. Key strings produced by getGroupKey can also contain raw option names.

Minimal patch:

+ function escapeHtml(s: string): string {+ return String(s)+ .replace(/&/g, "&amp;")+ .replace(/</g, "&lt;")+ .replace(/>/g, "&gt;")+ .replace(/"/g, "&quot;")+ .replace(/'/g, "&#39;");+ }
...
- const totalsHtml = Array.from(groups.entries())- .map(([key, arr]) => `<li><strong>Total de pedidos de ${key}:</strong> ${arr.length}</li>`)+ const totalsHtml = Array.from(groups.entries())+ .map(([key, arr]) => `<li><strong>Total de pedidos de ${escapeHtml(key)}:</strong> ${arr.length}</li>`)
.join("");
const sectionsHtml = Array.from(groups.entries())
.map(([key, arr]) => {
const itemsHtml = arr
.map(
(p) => `
<div class="pedido">
- <div><strong>Pedido:</strong> ${p.num}</div>- <div><strong>Data:</strong> ${p.data}</div>- <div><strong>Funcionário:</strong> ${p.func}</div>- <div><strong>Prato:</strong> ${p.prato}</div>- <div><strong>Opcionais:</strong> ${(p.opc ?? "").trim() || "-"}</div>- <div><strong>Observações:</strong> ${p.obs ?? "-"}</div>+ <div><strong>Pedido:</strong> ${p.num}</div>+ <div><strong>Data:</strong> ${escapeHtml(p.data)}</div>+ <div><strong>Funcionário:</strong> ${escapeHtml(p.func)}</div>+ <div><strong>Prato:</strong> ${escapeHtml(p.prato)}</div>+ <div><strong>Opcionais:</strong> ${escapeHtml(((p.opc ?? "").trim() || "-"))}</div>+ <div><strong>Observações:</strong> ${escapeHtml(p.obs ?? "-")}</div>
</div>
`,
)
.join("");
return `
<section class="group">
- <h2>${key}</h2>- <div class="group-count">Total de pedidos de ${key}: ${arr.length}</div>+ <h2>${escapeHtml(key)}</h2>+ <div class="group-count">Total de pedidos de ${escapeHtml(key)}: ${arr.length}</div>
<div class="pedidos">
${itemsHtml}
</div>
</section>
`;
})

Optionally also escape nomeRestaurante in the header. I can provide a follow-up patch covering all templates in this file if you want.

Also applies to: 620-623, 606-617, 612-614

src/app/api/cron/food_orders/route.ts (2)

11-19: Bug: equality on Date (midnight) + server timezone likely filters out valid orders; use day range in a fixed tz

Using orderDate: today where today is set to 00:00:00.000 in the server’s local tz typically misses rows whose timestamps aren’t exactly midnight. In serverless/containers (often UTC), this gets worse for BR users. Query by [startOfDay, endOfDay) in America/Sao_Paulo and also format dataPedidos in the same tz.

Apply this diff:

- const today = new Date();- today.setHours(0, 0, 0, 0);- console.log("| CRONJOB | Data de hoje:", today);+ const now = new Date();+ const tz = "America/Sao_Paulo";+ const fmt = new Intl.DateTimeFormat("pt-BR", {+ timeZone: tz,+ year: "numeric",+ month: "2-digit",+ day: "2-digit",+ });+ const parts = fmt.formatToParts(now);+ const year = Number(parts.find(p => p.type === "year")!.value);+ const month = Number(parts.find(p => p.type === "month")!.value);+ const day = Number(parts.find(p => p.type === "day")!.value);+ const startOfDay = new Date(Date.UTC(year, month - 1, day, 0, 0, 0, 0));+ const endOfDay = new Date(Date.UTC(year, month - 1, day + 1, 0, 0, 0, 0));+ console.log("| CRONJOB | Data de hoje (America/Sao_Paulo):", fmt.format(now), "| janela:", startOfDay.toISOString(), "->", endOfDay.toISOString());
// Buscar todos os pedidos de hoje
const orders = await db.foodOrder.findMany({
where: {
- orderDate: today,+ orderDate: {+ gte: startOfDay,+ lt: endOfDay,+ },
status: "PENDING",
},

And later when building the display date:

- const dataPedidos = today.toLocaleDateString('pt-BR');+ const dataPedidos = fmt.format(now);

Also applies to: 63-64


11-19: Convert Exact-Date Filters to Day-Range Queries

We’ve identified several places where orderDate is compared by exact equality—this will miss orders with timestamps later in the day. To ensure you’re capturing the full day, each equality filter should be replaced with a half-open range filter:

where: {orderDate: {gte: startOfDay,lt: nextDayStart,},// …}

Please update the following occurrences:

src/server/api/routers/food-order.ts
– Lines ~21: orderDate: new Date(input.orderDate.setHours(0, 0, 0, 0))
– Line 67: orderDate: input.orderDate
– Line 266: { ...(input.startDate && input.endDate && { orderDate: new Date(input.startDate.setHours(0, 0, 0, 0)) }) }
– Lines ~510: orderDate: today
– Line 531: orderDate: date

src/app/api/cron/food_orders/route.ts
– Lines 17–19: orderDate: today

src/app/(authenticated)/food/page.tsx
– Line 172: client-pass-through orderDate: orderDate

src/app/(authenticated)/admin/food/page.tsx
– Line 354: orderDate: signatureExportDate

Rather than matching orderDate exactly at midnight, calculate startOfDay = today.setHours(0,0,0,0) and nextDayStart = new Date(startOfDay).setDate(startOfDay.getDate()+1), then use:

where: {orderDate: {gte: startOfDay,lt: nextDayStart},status: "PENDING",// …}

This change ensures you include all orders placed any time during the target day.

🧹 Nitpick comments (4)
src/lib/mail/html-mock.ts (2)

566-569: Nit: reuse a Collator instance to avoid repeated localeCompare setup in sort

Creating a Collator once and reusing its compare function is a tiny perf/readability improvement.

- .sort((a, b) =>- a[1].display.localeCompare(b[1].display, "pt-BR", {- sensitivity: "base",- }),- )+ .sort(() => {+ const collator = new Intl.Collator("pt-BR", { sensitivity: "base" });+ return (a, b) => collator.compare(a[1].display, b[1].display);+ }())

598-606: Optional: sort groups for deterministic email sections (e.g., by count desc, then alpha)

Stable ordering improves readability and diffability in email archives. Current Map iteration order depends on first-seen items.

- const totalsHtml = Array.from(groups.entries())+ const sortedGroups = Array.from(groups.entries()).sort((a, b) => {+ const byCount = b[1].length - a[1].length;+ return byCount !== 0 ? byCount : a[0].localeCompare(b[0], "pt-BR", { sensitivity: "base" });+ });++ const totalsHtml = sortedGroups
.map(([key, arr]) => `<li><strong>Total de pedidos de ${escapeHtml(key)}:</strong> ${arr.length}</li>`)
.join("");
- const sectionsHtml = Array.from(groups.entries())+ const sectionsHtml = sortedGroups
.map(([key, arr]) => {
...
})
.join("");

Also applies to: 602-629

src/app/api/cron/food_orders/route.ts (2)

88-101: Resilience: isolate per-restaurant sendEmail in its own try/catch to avoid aborting the loop

A single SMTP failure will currently stop processing for remaining restaurants. Wrap per-restaurant send with try/catch; continue on error.

- const emailContent = emailPedidosRestauranteAgrupado(+ const emailContent = emailPedidosRestauranteAgrupado(
restaurant.name,
dataPedidos,
pedidosAgrupados,
);
-- await sendEmail(- restaurant.email,- `Pedidos do Dia - ${restaurant.name}`,- emailContent,- "rh@boxdistribuidor.com.br"- );-- console.log(`| CRONJOB | Email enviado para ${restaurant.name} com ${ordersData.length} pedidos`);+ try {+ await sendEmail(+ restaurant.email,+ `Pedidos do Dia - ${restaurant.name}`,+ emailContent,+ "rh@boxdistribuidor.com.br"+ );+ console.log(`| CRONJOB | Email enviado para ${restaurant.name} com ${ordersData.length} pedidos`);+ } catch (e) {+ console.error(`| CRONJOB | Falha ao enviar email para ${restaurant.name}:`, e);+ }

13-14: Nit: log the human date in the same timezone used for the query

Once you adopt the tz-aware range, logging fmt.format(now) is more useful to operators than a raw Date object.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 85c45a4 and 09da98d.

📒 Files selected for processing (2)
  • src/app/api/cron/food_orders/route.ts (3 hunks)
  • src/lib/mail/html-mock.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/app/api/cron/food_orders/route.ts (1)
src/lib/mail/html-mock.ts (1)
  • GroupedEmailOrder (487-494)
🔇 Additional comments (3)
src/lib/mail/html-mock.ts (1)

496-502: LGTM on normalizeStr

Good choice for Portuguese inputs: NFD + combining mark strip + lowercase + trim covers the common diacritics in pt-BR and aligns with the “feijao/salada” normalization.

src/app/api/cron/food_orders/route.ts (2)

60-63: Rename to ordersData: clearer, avoids shadowing; LGTM

The destructuring rename clarifies intent and prevents confusion with the outer orders variable.


68-76: Stable opc generation: sorting by option then choice is a good call

This ensures deterministic opc strings fed into the grouping logic and improves email grouping predictability.

Comment on lines +520 to +545
for (const tok of tokens) {
const parts = tok.split(":");
const kRaw = parts[0]?.trim();
const vRaw = parts.slice(1).join(":").trim(); // suporta "Observação: algo: extra"
if (!kRaw || !vRaw) continue;

const kNorm = normalizeStr(kRaw);
const display =
kNorm === "feijao" ? "Feijão" : kNorm === "salada" ? "Salada" : kRaw;

const vBase = normalizeStr(vRaw);
const v = vBase.startsWith("s")
? "Sim"
: vBase.startsWith("n")
? "Não"
: vRaw;

if (map.has(kNorm)) {
// Se já existir, prioriza "Sim" se houver conflito/duplicata
const prev = map.get(kNorm)!;
const newVal = prev.value === "Sim" || v === "Sim" ? "Sim" : v;
map.set(kNorm, { display, value: newVal });
} else {
map.set(kNorm, { display, value: v });
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix: fallback when no valid "chave: valor" tokens are parsed to avoid "Prato com " keys

If every token in opc lacks a colon (e.g., "sem feijão, sem salada") or all tokens are invalid, the map stays empty. The current flow then builds an empty ordered list and returns something like "Prato com " (note the trailing space), producing a misleading and unstable grouping key.

Add a guard to treat this as “sem adicional” when map.size === 0, before the allNo check.

Apply this diff:

 // Completa pares esperados: se só veio Salada, assume Feijão: Não; e vice-versa
const hasFeijao = map.has("feijao");
const hasSalada = map.has("salada");
if (hasFeijao && !hasSalada) map.set("salada", { display: "Salada", value: "Não" });
if (hasSalada && !hasFeijao) map.set("feijao", { display: "Feijão", value: "Não" });
+ // Se nenhum par válido foi extraído, trata como "sem adicional"+ if (map.size === 0) return `${p.prato} sem adicional`;
// Se tudo é "Não", trata como "sem adicional"
const entries = Array.from(map.values());
const allNo = entries.length > 0 && entries.every((e) => e.value === "Não");
if (allNo) return `${p.prato} sem adicional`;
// Ordena: Feijão, Salada, depois demais chaves em ordem alfabética

Also applies to: 554-557, 573-577

🤖 Prompt for AI Agents
In src/lib/mail/html-mock.ts around lines 520-545 (and similarly at 554-557 and
573-577), add a guard that if after parsing tokens the map is empty (map.size
=== 0) then insert a fallback entry to represent "sem adicional" before the
existing allNo check; specifically set map.set("sem adicional", { display: "Sem
adicional", value: "Não" }) (or equivalent normalized key/display/value you use
elsewhere) so the subsequent formatting produces a stable "Sem adicional"
grouping instead of "Prato com " or an empty list.

@rbxyz
rbxyz merged commit 47d0f7e into mainAug 22, 2025
6 checks passed
@rbxyz
rbxyz deleted the 30-problema-envio-emails branch September 2, 2025 11:08
@coderabbitaicoderabbitaiBot mentioned this pull request Dec 9, 2025
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

problema-envio-emails

1 participant

@rbxyz
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

30 problema envio emails - #33

Merged
rbxyz merged 2 commits into
mainfrom
30-problema-envio-emails
Aug 22, 2025
Merged

30 problema envio emails#33
rbxyz merged 2 commits into
mainfrom
30-problema-envio-emails

Conversation

@rbxyz

@rbxyzrbxyz commented Aug 22, 2025

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • Bug Fixes

    • Restaurant order emails now group items consistently and predictably.
    • Handles accents/case, duplicate or conflicting options, and fills missing Feijão/Salada with “Não” when absent.
    • Ensures canonical option order and clearer labels (e.g., “{prato} com Feijão: X, Salada: Y, …” or “sem adicional”).
  • Refactor

    • Improved internal naming for per-restaurant order data.
    • Added timestamp logging during daily processing.

@rbxyzrbxyz linked an issue Aug 22, 2025 that may be closed by this pull request
@coderabbitai

coderabbitaiBot commented Aug 22, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Refactors cron route logging and variable names for per-restaurant order processing without changing behavior. Overhauls email grouping logic to normalize and deterministically parse option tokens (p.opc), handling diacritics, case, duplicates, and defaults, producing canonicalized strings for grouping while preserving the existing public API.

Changes

Cohort / File(s)Summary
Cron route processing tweaks
src/app/api/cron/food_orders/route.ts
Added a log for normalized current date. Renamed inner collection from orders to ordersData and updated all references, including grouped orders source, conditionals, and logs. No public API changes.
Email grouping normalization
src/lib/mail/html-mock.ts
Introduced normalizeStr and replaced opc parsing with token-based, diacritic/case-insensitive logic. Normalizes keys/values (e.g., Feijão/Salada, Sim/Não), resolves duplicates, fills missing defaults, orders keys deterministically, and returns canonical grouping strings. Public signatures unchanged.

Sequence Diagram(s)

sequenceDiagram
autonumber
participant Cron as Cron Route
participant DB as Orders Source
participant Grouper as Opc Normalizer (updated)
participant Mail as Email Builder/Sender
Cron->>DB: Fetch today's orders
Cron->>Cron: Normalize date to midnight (log)
loop per restaurant
Cron->>Grouper: Build grouped keys from p.opc
Note right of Grouper: New deterministic parsing<br/>• normalize diacritics/case<br/>• resolve duplicates<br/>• fill defaults
Grouper-->>Cron: Canonical grouping strings
Cron->>Mail: Generate grouped email sections
Mail-->>Cron: Email content
Cron->>Mail: Send email
Mail-->>Cron: Result (success/failure)
end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • jdalmeida

Poem

A whisk of bytes, a nibble of logs,
I hop through orders, past digital fogs.
Opc now tidy—Feijão says “Sim”!
Salada replies, in canonical trim.
Grouped and mailed, with a twitch of my ear—
Ship it, ship it, lunch hour draws near! 🥕🐇

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 30-problema-envio-emails

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@vercel

vercelBot commented Aug 22, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentPreviewCommentsUpdated (UTC)
eloReadyReadyPreviewCommentAug 22, 2025 2:53pm

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
src/lib/mail/html-mock.ts (1)

598-606: Security: escape dynamic HTML to prevent injection in emails

User-controlled fields (e.g., funcionário, observações) and DB-configured strings (opções, pratos) are injected raw into HTML. Many email clients render HTML and allow URLs; this is a phishing/XSS vector. Escape all dynamic text before embedding in the template. Key strings produced by getGroupKey can also contain raw option names.

Minimal patch:

+ function escapeHtml(s: string): string {+ return String(s)+ .replace(/&/g, "&amp;")+ .replace(/</g, "&lt;")+ .replace(/>/g, "&gt;")+ .replace(/"/g, "&quot;")+ .replace(/'/g, "&#39;");+ }
...
- const totalsHtml = Array.from(groups.entries())- .map(([key, arr]) => `<li><strong>Total de pedidos de ${key}:</strong> ${arr.length}</li>`)+ const totalsHtml = Array.from(groups.entries())+ .map(([key, arr]) => `<li><strong>Total de pedidos de ${escapeHtml(key)}:</strong> ${arr.length}</li>`)
.join("");
const sectionsHtml = Array.from(groups.entries())
.map(([key, arr]) => {
const itemsHtml = arr
.map(
(p) => `
<div class="pedido">
- <div><strong>Pedido:</strong> ${p.num}</div>- <div><strong>Data:</strong> ${p.data}</div>- <div><strong>Funcionário:</strong> ${p.func}</div>- <div><strong>Prato:</strong> ${p.prato}</div>- <div><strong>Opcionais:</strong> ${(p.opc ?? "").trim() || "-"}</div>- <div><strong>Observações:</strong> ${p.obs ?? "-"}</div>+ <div><strong>Pedido:</strong> ${p.num}</div>+ <div><strong>Data:</strong> ${escapeHtml(p.data)}</div>+ <div><strong>Funcionário:</strong> ${escapeHtml(p.func)}</div>+ <div><strong>Prato:</strong> ${escapeHtml(p.prato)}</div>+ <div><strong>Opcionais:</strong> ${escapeHtml(((p.opc ?? "").trim() || "-"))}</div>+ <div><strong>Observações:</strong> ${escapeHtml(p.obs ?? "-")}</div>
</div>
`,
)
.join("");
return `
<section class="group">
- <h2>${key}</h2>- <div class="group-count">Total de pedidos de ${key}: ${arr.length}</div>+ <h2>${escapeHtml(key)}</h2>+ <div class="group-count">Total de pedidos de ${escapeHtml(key)}: ${arr.length}</div>
<div class="pedidos">
${itemsHtml}
</div>
</section>
`;
})

Optionally also escape nomeRestaurante in the header. I can provide a follow-up patch covering all templates in this file if you want.

Also applies to: 620-623, 606-617, 612-614

src/app/api/cron/food_orders/route.ts (2)

11-19: Bug: equality on Date (midnight) + server timezone likely filters out valid orders; use day range in a fixed tz

Using orderDate: today where today is set to 00:00:00.000 in the server’s local tz typically misses rows whose timestamps aren’t exactly midnight. In serverless/containers (often UTC), this gets worse for BR users. Query by [startOfDay, endOfDay) in America/Sao_Paulo and also format dataPedidos in the same tz.

Apply this diff:

- const today = new Date();- today.setHours(0, 0, 0, 0);- console.log("| CRONJOB | Data de hoje:", today);+ const now = new Date();+ const tz = "America/Sao_Paulo";+ const fmt = new Intl.DateTimeFormat("pt-BR", {+ timeZone: tz,+ year: "numeric",+ month: "2-digit",+ day: "2-digit",+ });+ const parts = fmt.formatToParts(now);+ const year = Number(parts.find(p => p.type === "year")!.value);+ const month = Number(parts.find(p => p.type === "month")!.value);+ const day = Number(parts.find(p => p.type === "day")!.value);+ const startOfDay = new Date(Date.UTC(year, month - 1, day, 0, 0, 0, 0));+ const endOfDay = new Date(Date.UTC(year, month - 1, day + 1, 0, 0, 0, 0));+ console.log("| CRONJOB | Data de hoje (America/Sao_Paulo):", fmt.format(now), "| janela:", startOfDay.toISOString(), "->", endOfDay.toISOString());
// Buscar todos os pedidos de hoje
const orders = await db.foodOrder.findMany({
where: {
- orderDate: today,+ orderDate: {+ gte: startOfDay,+ lt: endOfDay,+ },
status: "PENDING",
},

And later when building the display date:

- const dataPedidos = today.toLocaleDateString('pt-BR');+ const dataPedidos = fmt.format(now);

Also applies to: 63-64


11-19: Convert Exact-Date Filters to Day-Range Queries

We’ve identified several places where orderDate is compared by exact equality—this will miss orders with timestamps later in the day. To ensure you’re capturing the full day, each equality filter should be replaced with a half-open range filter:

where: {orderDate: {gte: startOfDay,lt: nextDayStart,},// …}

Please update the following occurrences:

src/server/api/routers/food-order.ts
– Lines ~21: orderDate: new Date(input.orderDate.setHours(0, 0, 0, 0))
– Line 67: orderDate: input.orderDate
– Line 266: { ...(input.startDate && input.endDate && { orderDate: new Date(input.startDate.setHours(0, 0, 0, 0)) }) }
– Lines ~510: orderDate: today
– Line 531: orderDate: date

src/app/api/cron/food_orders/route.ts
– Lines 17–19: orderDate: today

src/app/(authenticated)/food/page.tsx
– Line 172: client-pass-through orderDate: orderDate

src/app/(authenticated)/admin/food/page.tsx
– Line 354: orderDate: signatureExportDate

Rather than matching orderDate exactly at midnight, calculate startOfDay = today.setHours(0,0,0,0) and nextDayStart = new Date(startOfDay).setDate(startOfDay.getDate()+1), then use:

where: {orderDate: {gte: startOfDay,lt: nextDayStart},status: "PENDING",// …}

This change ensures you include all orders placed any time during the target day.

🧹 Nitpick comments (4)
src/lib/mail/html-mock.ts (2)

566-569: Nit: reuse a Collator instance to avoid repeated localeCompare setup in sort

Creating a Collator once and reusing its compare function is a tiny perf/readability improvement.

- .sort((a, b) =>- a[1].display.localeCompare(b[1].display, "pt-BR", {- sensitivity: "base",- }),- )+ .sort(() => {+ const collator = new Intl.Collator("pt-BR", { sensitivity: "base" });+ return (a, b) => collator.compare(a[1].display, b[1].display);+ }())

598-606: Optional: sort groups for deterministic email sections (e.g., by count desc, then alpha)

Stable ordering improves readability and diffability in email archives. Current Map iteration order depends on first-seen items.

- const totalsHtml = Array.from(groups.entries())+ const sortedGroups = Array.from(groups.entries()).sort((a, b) => {+ const byCount = b[1].length - a[1].length;+ return byCount !== 0 ? byCount : a[0].localeCompare(b[0], "pt-BR", { sensitivity: "base" });+ });++ const totalsHtml = sortedGroups
.map(([key, arr]) => `<li><strong>Total de pedidos de ${escapeHtml(key)}:</strong> ${arr.length}</li>`)
.join("");
- const sectionsHtml = Array.from(groups.entries())+ const sectionsHtml = sortedGroups
.map(([key, arr]) => {
...
})
.join("");

Also applies to: 602-629

src/app/api/cron/food_orders/route.ts (2)

88-101: Resilience: isolate per-restaurant sendEmail in its own try/catch to avoid aborting the loop

A single SMTP failure will currently stop processing for remaining restaurants. Wrap per-restaurant send with try/catch; continue on error.

- const emailContent = emailPedidosRestauranteAgrupado(+ const emailContent = emailPedidosRestauranteAgrupado(
restaurant.name,
dataPedidos,
pedidosAgrupados,
);
-- await sendEmail(- restaurant.email,- `Pedidos do Dia - ${restaurant.name}`,- emailContent,- "rh@boxdistribuidor.com.br"- );-- console.log(`| CRONJOB | Email enviado para ${restaurant.name} com ${ordersData.length} pedidos`);+ try {+ await sendEmail(+ restaurant.email,+ `Pedidos do Dia - ${restaurant.name}`,+ emailContent,+ "rh@boxdistribuidor.com.br"+ );+ console.log(`| CRONJOB | Email enviado para ${restaurant.name} com ${ordersData.length} pedidos`);+ } catch (e) {+ console.error(`| CRONJOB | Falha ao enviar email para ${restaurant.name}:`, e);+ }

13-14: Nit: log the human date in the same timezone used for the query

Once you adopt the tz-aware range, logging fmt.format(now) is more useful to operators than a raw Date object.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 85c45a4 and 09da98d.

📒 Files selected for processing (2)
  • src/app/api/cron/food_orders/route.ts (3 hunks)
  • src/lib/mail/html-mock.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/app/api/cron/food_orders/route.ts (1)
src/lib/mail/html-mock.ts (1)
  • GroupedEmailOrder (487-494)
🔇 Additional comments (3)
src/lib/mail/html-mock.ts (1)

496-502: LGTM on normalizeStr

Good choice for Portuguese inputs: NFD + combining mark strip + lowercase + trim covers the common diacritics in pt-BR and aligns with the “feijao/salada” normalization.

src/app/api/cron/food_orders/route.ts (2)

60-63: Rename to ordersData: clearer, avoids shadowing; LGTM

The destructuring rename clarifies intent and prevents confusion with the outer orders variable.


68-76: Stable opc generation: sorting by option then choice is a good call

This ensures deterministic opc strings fed into the grouping logic and improves email grouping predictability.

Comment on lines +520 to +545
for (const tok of tokens) {
const parts = tok.split(":");
const kRaw = parts[0]?.trim();
const vRaw = parts.slice(1).join(":").trim(); // suporta "Observação: algo: extra"
if (!kRaw || !vRaw) continue;

const kNorm = normalizeStr(kRaw);
const display =
kNorm === "feijao" ? "Feijão" : kNorm === "salada" ? "Salada" : kRaw;

const vBase = normalizeStr(vRaw);
const v = vBase.startsWith("s")
? "Sim"
: vBase.startsWith("n")
? "Não"
: vRaw;

if (map.has(kNorm)) {
// Se já existir, prioriza "Sim" se houver conflito/duplicata
const prev = map.get(kNorm)!;
const newVal = prev.value === "Sim" || v === "Sim" ? "Sim" : v;
map.set(kNorm, { display, value: newVal });
} else {
map.set(kNorm, { display, value: v });
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix: fallback when no valid "chave: valor" tokens are parsed to avoid "Prato com " keys

If every token in opc lacks a colon (e.g., "sem feijão, sem salada") or all tokens are invalid, the map stays empty. The current flow then builds an empty ordered list and returns something like "Prato com " (note the trailing space), producing a misleading and unstable grouping key.

Add a guard to treat this as “sem adicional” when map.size === 0, before the allNo check.

Apply this diff:

 // Completa pares esperados: se só veio Salada, assume Feijão: Não; e vice-versa
const hasFeijao = map.has("feijao");
const hasSalada = map.has("salada");
if (hasFeijao && !hasSalada) map.set("salada", { display: "Salada", value: "Não" });
if (hasSalada && !hasFeijao) map.set("feijao", { display: "Feijão", value: "Não" });
+ // Se nenhum par válido foi extraído, trata como "sem adicional"+ if (map.size === 0) return `${p.prato} sem adicional`;
// Se tudo é "Não", trata como "sem adicional"
const entries = Array.from(map.values());
const allNo = entries.length > 0 && entries.every((e) => e.value === "Não");
if (allNo) return `${p.prato} sem adicional`;
// Ordena: Feijão, Salada, depois demais chaves em ordem alfabética

Also applies to: 554-557, 573-577

🤖 Prompt for AI Agents
In src/lib/mail/html-mock.ts around lines 520-545 (and similarly at 554-557 and
573-577), add a guard that if after parsing tokens the map is empty (map.size
=== 0) then insert a fallback entry to represent "sem adicional" before the
existing allNo check; specifically set map.set("sem adicional", { display: "Sem
adicional", value: "Não" }) (or equivalent normalized key/display/value you use
elsewhere) so the subsequent formatting produces a stable "Sem adicional"
grouping instead of "Prato com " or an empty list.

@rbxyz
rbxyz merged commit 47d0f7e into mainAug 22, 2025
6 checks passed
@rbxyz
rbxyz deleted the 30-problema-envio-emails branch September 2, 2025 11:08
@coderabbitaicoderabbitaiBot mentioned this pull request Dec 9, 2025
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

problema-envio-emails

1 participant

@rbxyz
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

30 problema envio emails - #33

Merged
rbxyz merged 2 commits into
mainfrom
30-problema-envio-emails
Aug 22, 2025
Merged

30 problema envio emails#33
rbxyz merged 2 commits into
mainfrom
30-problema-envio-emails

Conversation

@rbxyz

@rbxyzrbxyz commented Aug 22, 2025

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • Bug Fixes

    • Restaurant order emails now group items consistently and predictably.
    • Handles accents/case, duplicate or conflicting options, and fills missing Feijão/Salada with “Não” when absent.
    • Ensures canonical option order and clearer labels (e.g., “{prato} com Feijão: X, Salada: Y, …” or “sem adicional”).
  • Refactor

    • Improved internal naming for per-restaurant order data.
    • Added timestamp logging during daily processing.

@rbxyzrbxyz linked an issue Aug 22, 2025 that may be closed by this pull request
@coderabbitai

coderabbitaiBot commented Aug 22, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Refactors cron route logging and variable names for per-restaurant order processing without changing behavior. Overhauls email grouping logic to normalize and deterministically parse option tokens (p.opc), handling diacritics, case, duplicates, and defaults, producing canonicalized strings for grouping while preserving the existing public API.

Changes

Cohort / File(s)Summary
Cron route processing tweaks
src/app/api/cron/food_orders/route.ts
Added a log for normalized current date. Renamed inner collection from orders to ordersData and updated all references, including grouped orders source, conditionals, and logs. No public API changes.
Email grouping normalization
src/lib/mail/html-mock.ts
Introduced normalizeStr and replaced opc parsing with token-based, diacritic/case-insensitive logic. Normalizes keys/values (e.g., Feijão/Salada, Sim/Não), resolves duplicates, fills missing defaults, orders keys deterministically, and returns canonical grouping strings. Public signatures unchanged.

Sequence Diagram(s)

sequenceDiagram
autonumber
participant Cron as Cron Route
participant DB as Orders Source
participant Grouper as Opc Normalizer (updated)
participant Mail as Email Builder/Sender
Cron->>DB: Fetch today's orders
Cron->>Cron: Normalize date to midnight (log)
loop per restaurant
Cron->>Grouper: Build grouped keys from p.opc
Note right of Grouper: New deterministic parsing<br/>• normalize diacritics/case<br/>• resolve duplicates<br/>• fill defaults
Grouper-->>Cron: Canonical grouping strings
Cron->>Mail: Generate grouped email sections
Mail-->>Cron: Email content
Cron->>Mail: Send email
Mail-->>Cron: Result (success/failure)
end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • jdalmeida

Poem

A whisk of bytes, a nibble of logs,
I hop through orders, past digital fogs.
Opc now tidy—Feijão says “Sim”!
Salada replies, in canonical trim.
Grouped and mailed, with a twitch of my ear—
Ship it, ship it, lunch hour draws near! 🥕🐇

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 30-problema-envio-emails

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@vercel

vercelBot commented Aug 22, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentPreviewCommentsUpdated (UTC)
eloReadyReadyPreviewCommentAug 22, 2025 2:53pm

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
src/lib/mail/html-mock.ts (1)

598-606: Security: escape dynamic HTML to prevent injection in emails

User-controlled fields (e.g., funcionário, observações) and DB-configured strings (opções, pratos) are injected raw into HTML. Many email clients render HTML and allow URLs; this is a phishing/XSS vector. Escape all dynamic text before embedding in the template. Key strings produced by getGroupKey can also contain raw option names.

Minimal patch:

+ function escapeHtml(s: string): string {+ return String(s)+ .replace(/&/g, "&amp;")+ .replace(/</g, "&lt;")+ .replace(/>/g, "&gt;")+ .replace(/"/g, "&quot;")+ .replace(/'/g, "&#39;");+ }
...
- const totalsHtml = Array.from(groups.entries())- .map(([key, arr]) => `<li><strong>Total de pedidos de ${key}:</strong> ${arr.length}</li>`)+ const totalsHtml = Array.from(groups.entries())+ .map(([key, arr]) => `<li><strong>Total de pedidos de ${escapeHtml(key)}:</strong> ${arr.length}</li>`)
.join("");
const sectionsHtml = Array.from(groups.entries())
.map(([key, arr]) => {
const itemsHtml = arr
.map(
(p) => `
<div class="pedido">
- <div><strong>Pedido:</strong> ${p.num}</div>- <div><strong>Data:</strong> ${p.data}</div>- <div><strong>Funcionário:</strong> ${p.func}</div>- <div><strong>Prato:</strong> ${p.prato}</div>- <div><strong>Opcionais:</strong> ${(p.opc ?? "").trim() || "-"}</div>- <div><strong>Observações:</strong> ${p.obs ?? "-"}</div>+ <div><strong>Pedido:</strong> ${p.num}</div>+ <div><strong>Data:</strong> ${escapeHtml(p.data)}</div>+ <div><strong>Funcionário:</strong> ${escapeHtml(p.func)}</div>+ <div><strong>Prato:</strong> ${escapeHtml(p.prato)}</div>+ <div><strong>Opcionais:</strong> ${escapeHtml(((p.opc ?? "").trim() || "-"))}</div>+ <div><strong>Observações:</strong> ${escapeHtml(p.obs ?? "-")}</div>
</div>
`,
)
.join("");
return `
<section class="group">
- <h2>${key}</h2>- <div class="group-count">Total de pedidos de ${key}: ${arr.length}</div>+ <h2>${escapeHtml(key)}</h2>+ <div class="group-count">Total de pedidos de ${escapeHtml(key)}: ${arr.length}</div>
<div class="pedidos">
${itemsHtml}
</div>
</section>
`;
})

Optionally also escape nomeRestaurante in the header. I can provide a follow-up patch covering all templates in this file if you want.

Also applies to: 620-623, 606-617, 612-614

src/app/api/cron/food_orders/route.ts (2)

11-19: Bug: equality on Date (midnight) + server timezone likely filters out valid orders; use day range in a fixed tz

Using orderDate: today where today is set to 00:00:00.000 in the server’s local tz typically misses rows whose timestamps aren’t exactly midnight. In serverless/containers (often UTC), this gets worse for BR users. Query by [startOfDay, endOfDay) in America/Sao_Paulo and also format dataPedidos in the same tz.

Apply this diff:

- const today = new Date();- today.setHours(0, 0, 0, 0);- console.log("| CRONJOB | Data de hoje:", today);+ const now = new Date();+ const tz = "America/Sao_Paulo";+ const fmt = new Intl.DateTimeFormat("pt-BR", {+ timeZone: tz,+ year: "numeric",+ month: "2-digit",+ day: "2-digit",+ });+ const parts = fmt.formatToParts(now);+ const year = Number(parts.find(p => p.type === "year")!.value);+ const month = Number(parts.find(p => p.type === "month")!.value);+ const day = Number(parts.find(p => p.type === "day")!.value);+ const startOfDay = new Date(Date.UTC(year, month - 1, day, 0, 0, 0, 0));+ const endOfDay = new Date(Date.UTC(year, month - 1, day + 1, 0, 0, 0, 0));+ console.log("| CRONJOB | Data de hoje (America/Sao_Paulo):", fmt.format(now), "| janela:", startOfDay.toISOString(), "->", endOfDay.toISOString());
// Buscar todos os pedidos de hoje
const orders = await db.foodOrder.findMany({
where: {
- orderDate: today,+ orderDate: {+ gte: startOfDay,+ lt: endOfDay,+ },
status: "PENDING",
},

And later when building the display date:

- const dataPedidos = today.toLocaleDateString('pt-BR');+ const dataPedidos = fmt.format(now);

Also applies to: 63-64


11-19: Convert Exact-Date Filters to Day-Range Queries

We’ve identified several places where orderDate is compared by exact equality—this will miss orders with timestamps later in the day. To ensure you’re capturing the full day, each equality filter should be replaced with a half-open range filter:

where: {orderDate: {gte: startOfDay,lt: nextDayStart,},// …}

Please update the following occurrences:

src/server/api/routers/food-order.ts
– Lines ~21: orderDate: new Date(input.orderDate.setHours(0, 0, 0, 0))
– Line 67: orderDate: input.orderDate
– Line 266: { ...(input.startDate && input.endDate && { orderDate: new Date(input.startDate.setHours(0, 0, 0, 0)) }) }
– Lines ~510: orderDate: today
– Line 531: orderDate: date

src/app/api/cron/food_orders/route.ts
– Lines 17–19: orderDate: today

src/app/(authenticated)/food/page.tsx
– Line 172: client-pass-through orderDate: orderDate

src/app/(authenticated)/admin/food/page.tsx
– Line 354: orderDate: signatureExportDate

Rather than matching orderDate exactly at midnight, calculate startOfDay = today.setHours(0,0,0,0) and nextDayStart = new Date(startOfDay).setDate(startOfDay.getDate()+1), then use:

where: {orderDate: {gte: startOfDay,lt: nextDayStart},status: "PENDING",// …}

This change ensures you include all orders placed any time during the target day.

🧹 Nitpick comments (4)
src/lib/mail/html-mock.ts (2)

566-569: Nit: reuse a Collator instance to avoid repeated localeCompare setup in sort

Creating a Collator once and reusing its compare function is a tiny perf/readability improvement.

- .sort((a, b) =>- a[1].display.localeCompare(b[1].display, "pt-BR", {- sensitivity: "base",- }),- )+ .sort(() => {+ const collator = new Intl.Collator("pt-BR", { sensitivity: "base" });+ return (a, b) => collator.compare(a[1].display, b[1].display);+ }())

598-606: Optional: sort groups for deterministic email sections (e.g., by count desc, then alpha)

Stable ordering improves readability and diffability in email archives. Current Map iteration order depends on first-seen items.

- const totalsHtml = Array.from(groups.entries())+ const sortedGroups = Array.from(groups.entries()).sort((a, b) => {+ const byCount = b[1].length - a[1].length;+ return byCount !== 0 ? byCount : a[0].localeCompare(b[0], "pt-BR", { sensitivity: "base" });+ });++ const totalsHtml = sortedGroups
.map(([key, arr]) => `<li><strong>Total de pedidos de ${escapeHtml(key)}:</strong> ${arr.length}</li>`)
.join("");
- const sectionsHtml = Array.from(groups.entries())+ const sectionsHtml = sortedGroups
.map(([key, arr]) => {
...
})
.join("");

Also applies to: 602-629

src/app/api/cron/food_orders/route.ts (2)

88-101: Resilience: isolate per-restaurant sendEmail in its own try/catch to avoid aborting the loop

A single SMTP failure will currently stop processing for remaining restaurants. Wrap per-restaurant send with try/catch; continue on error.

- const emailContent = emailPedidosRestauranteAgrupado(+ const emailContent = emailPedidosRestauranteAgrupado(
restaurant.name,
dataPedidos,
pedidosAgrupados,
);
-- await sendEmail(- restaurant.email,- `Pedidos do Dia - ${restaurant.name}`,- emailContent,- "rh@boxdistribuidor.com.br"- );-- console.log(`| CRONJOB | Email enviado para ${restaurant.name} com ${ordersData.length} pedidos`);+ try {+ await sendEmail(+ restaurant.email,+ `Pedidos do Dia - ${restaurant.name}`,+ emailContent,+ "rh@boxdistribuidor.com.br"+ );+ console.log(`| CRONJOB | Email enviado para ${restaurant.name} com ${ordersData.length} pedidos`);+ } catch (e) {+ console.error(`| CRONJOB | Falha ao enviar email para ${restaurant.name}:`, e);+ }

13-14: Nit: log the human date in the same timezone used for the query

Once you adopt the tz-aware range, logging fmt.format(now) is more useful to operators than a raw Date object.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 85c45a4 and 09da98d.

📒 Files selected for processing (2)
  • src/app/api/cron/food_orders/route.ts (3 hunks)
  • src/lib/mail/html-mock.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/app/api/cron/food_orders/route.ts (1)
src/lib/mail/html-mock.ts (1)
  • GroupedEmailOrder (487-494)
🔇 Additional comments (3)
src/lib/mail/html-mock.ts (1)

496-502: LGTM on normalizeStr

Good choice for Portuguese inputs: NFD + combining mark strip + lowercase + trim covers the common diacritics in pt-BR and aligns with the “feijao/salada” normalization.

src/app/api/cron/food_orders/route.ts (2)

60-63: Rename to ordersData: clearer, avoids shadowing; LGTM

The destructuring rename clarifies intent and prevents confusion with the outer orders variable.


68-76: Stable opc generation: sorting by option then choice is a good call

This ensures deterministic opc strings fed into the grouping logic and improves email grouping predictability.

Comment on lines +520 to +545
for (const tok of tokens) {
const parts = tok.split(":");
const kRaw = parts[0]?.trim();
const vRaw = parts.slice(1).join(":").trim(); // suporta "Observação: algo: extra"
if (!kRaw || !vRaw) continue;

const kNorm = normalizeStr(kRaw);
const display =
kNorm === "feijao" ? "Feijão" : kNorm === "salada" ? "Salada" : kRaw;

const vBase = normalizeStr(vRaw);
const v = vBase.startsWith("s")
? "Sim"
: vBase.startsWith("n")
? "Não"
: vRaw;

if (map.has(kNorm)) {
// Se já existir, prioriza "Sim" se houver conflito/duplicata
const prev = map.get(kNorm)!;
const newVal = prev.value === "Sim" || v === "Sim" ? "Sim" : v;
map.set(kNorm, { display, value: newVal });
} else {
map.set(kNorm, { display, value: v });
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix: fallback when no valid "chave: valor" tokens are parsed to avoid "Prato com " keys

If every token in opc lacks a colon (e.g., "sem feijão, sem salada") or all tokens are invalid, the map stays empty. The current flow then builds an empty ordered list and returns something like "Prato com " (note the trailing space), producing a misleading and unstable grouping key.

Add a guard to treat this as “sem adicional” when map.size === 0, before the allNo check.

Apply this diff:

 // Completa pares esperados: se só veio Salada, assume Feijão: Não; e vice-versa
const hasFeijao = map.has("feijao");
const hasSalada = map.has("salada");
if (hasFeijao && !hasSalada) map.set("salada", { display: "Salada", value: "Não" });
if (hasSalada && !hasFeijao) map.set("feijao", { display: "Feijão", value: "Não" });
+ // Se nenhum par válido foi extraído, trata como "sem adicional"+ if (map.size === 0) return `${p.prato} sem adicional`;
// Se tudo é "Não", trata como "sem adicional"
const entries = Array.from(map.values());
const allNo = entries.length > 0 && entries.every((e) => e.value === "Não");
if (allNo) return `${p.prato} sem adicional`;
// Ordena: Feijão, Salada, depois demais chaves em ordem alfabética

Also applies to: 554-557, 573-577

🤖 Prompt for AI Agents
In src/lib/mail/html-mock.ts around lines 520-545 (and similarly at 554-557 and
573-577), add a guard that if after parsing tokens the map is empty (map.size
=== 0) then insert a fallback entry to represent "sem adicional" before the
existing allNo check; specifically set map.set("sem adicional", { display: "Sem
adicional", value: "Não" }) (or equivalent normalized key/display/value you use
elsewhere) so the subsequent formatting produces a stable "Sem adicional"
grouping instead of "Prato com " or an empty list.

@rbxyz
rbxyz merged commit 47d0f7e into mainAug 22, 2025
6 checks passed
@rbxyz
rbxyz deleted the 30-problema-envio-emails branch September 2, 2025 11:08
@coderabbitaicoderabbitaiBot mentioned this pull request Dec 9, 2025
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

problema-envio-emails

1 participant

@rbxyz
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

30 problema envio emails - #33

Merged
rbxyz merged 2 commits into
mainfrom
30-problema-envio-emails
Aug 22, 2025
Merged

30 problema envio emails#33
rbxyz merged 2 commits into
mainfrom
30-problema-envio-emails

Conversation

@rbxyz

@rbxyzrbxyz commented Aug 22, 2025

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • Bug Fixes

    • Restaurant order emails now group items consistently and predictably.
    • Handles accents/case, duplicate or conflicting options, and fills missing Feijão/Salada with “Não” when absent.
    • Ensures canonical option order and clearer labels (e.g., “{prato} com Feijão: X, Salada: Y, …” or “sem adicional”).
  • Refactor

    • Improved internal naming for per-restaurant order data.
    • Added timestamp logging during daily processing.

@rbxyzrbxyz linked an issue Aug 22, 2025 that may be closed by this pull request
@coderabbitai

coderabbitaiBot commented Aug 22, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Refactors cron route logging and variable names for per-restaurant order processing without changing behavior. Overhauls email grouping logic to normalize and deterministically parse option tokens (p.opc), handling diacritics, case, duplicates, and defaults, producing canonicalized strings for grouping while preserving the existing public API.

Changes

Cohort / File(s)Summary
Cron route processing tweaks
src/app/api/cron/food_orders/route.ts
Added a log for normalized current date. Renamed inner collection from orders to ordersData and updated all references, including grouped orders source, conditionals, and logs. No public API changes.
Email grouping normalization
src/lib/mail/html-mock.ts
Introduced normalizeStr and replaced opc parsing with token-based, diacritic/case-insensitive logic. Normalizes keys/values (e.g., Feijão/Salada, Sim/Não), resolves duplicates, fills missing defaults, orders keys deterministically, and returns canonical grouping strings. Public signatures unchanged.

Sequence Diagram(s)

sequenceDiagram
autonumber
participant Cron as Cron Route
participant DB as Orders Source
participant Grouper as Opc Normalizer (updated)
participant Mail as Email Builder/Sender
Cron->>DB: Fetch today's orders
Cron->>Cron: Normalize date to midnight (log)
loop per restaurant
Cron->>Grouper: Build grouped keys from p.opc
Note right of Grouper: New deterministic parsing<br/>• normalize diacritics/case<br/>• resolve duplicates<br/>• fill defaults
Grouper-->>Cron: Canonical grouping strings
Cron->>Mail: Generate grouped email sections
Mail-->>Cron: Email content
Cron->>Mail: Send email
Mail-->>Cron: Result (success/failure)
end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • jdalmeida

Poem

A whisk of bytes, a nibble of logs,
I hop through orders, past digital fogs.
Opc now tidy—Feijão says “Sim”!
Salada replies, in canonical trim.
Grouped and mailed, with a twitch of my ear—
Ship it, ship it, lunch hour draws near! 🥕🐇

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 30-problema-envio-emails

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@vercel

vercelBot commented Aug 22, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentPreviewCommentsUpdated (UTC)
eloReadyReadyPreviewCommentAug 22, 2025 2:53pm

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
src/lib/mail/html-mock.ts (1)

598-606: Security: escape dynamic HTML to prevent injection in emails

User-controlled fields (e.g., funcionário, observações) and DB-configured strings (opções, pratos) are injected raw into HTML. Many email clients render HTML and allow URLs; this is a phishing/XSS vector. Escape all dynamic text before embedding in the template. Key strings produced by getGroupKey can also contain raw option names.

Minimal patch:

+ function escapeHtml(s: string): string {+ return String(s)+ .replace(/&/g, "&amp;")+ .replace(/</g, "&lt;")+ .replace(/>/g, "&gt;")+ .replace(/"/g, "&quot;")+ .replace(/'/g, "&#39;");+ }
...
- const totalsHtml = Array.from(groups.entries())- .map(([key, arr]) => `<li><strong>Total de pedidos de ${key}:</strong> ${arr.length}</li>`)+ const totalsHtml = Array.from(groups.entries())+ .map(([key, arr]) => `<li><strong>Total de pedidos de ${escapeHtml(key)}:</strong> ${arr.length}</li>`)
.join("");
const sectionsHtml = Array.from(groups.entries())
.map(([key, arr]) => {
const itemsHtml = arr
.map(
(p) => `
<div class="pedido">
- <div><strong>Pedido:</strong> ${p.num}</div>- <div><strong>Data:</strong> ${p.data}</div>- <div><strong>Funcionário:</strong> ${p.func}</div>- <div><strong>Prato:</strong> ${p.prato}</div>- <div><strong>Opcionais:</strong> ${(p.opc ?? "").trim() || "-"}</div>- <div><strong>Observações:</strong> ${p.obs ?? "-"}</div>+ <div><strong>Pedido:</strong> ${p.num}</div>+ <div><strong>Data:</strong> ${escapeHtml(p.data)}</div>+ <div><strong>Funcionário:</strong> ${escapeHtml(p.func)}</div>+ <div><strong>Prato:</strong> ${escapeHtml(p.prato)}</div>+ <div><strong>Opcionais:</strong> ${escapeHtml(((p.opc ?? "").trim() || "-"))}</div>+ <div><strong>Observações:</strong> ${escapeHtml(p.obs ?? "-")}</div>
</div>
`,
)
.join("");
return `
<section class="group">
- <h2>${key}</h2>- <div class="group-count">Total de pedidos de ${key}: ${arr.length}</div>+ <h2>${escapeHtml(key)}</h2>+ <div class="group-count">Total de pedidos de ${escapeHtml(key)}: ${arr.length}</div>
<div class="pedidos">
${itemsHtml}
</div>
</section>
`;
})

Optionally also escape nomeRestaurante in the header. I can provide a follow-up patch covering all templates in this file if you want.

Also applies to: 620-623, 606-617, 612-614

src/app/api/cron/food_orders/route.ts (2)

11-19: Bug: equality on Date (midnight) + server timezone likely filters out valid orders; use day range in a fixed tz

Using orderDate: today where today is set to 00:00:00.000 in the server’s local tz typically misses rows whose timestamps aren’t exactly midnight. In serverless/containers (often UTC), this gets worse for BR users. Query by [startOfDay, endOfDay) in America/Sao_Paulo and also format dataPedidos in the same tz.

Apply this diff:

- const today = new Date();- today.setHours(0, 0, 0, 0);- console.log("| CRONJOB | Data de hoje:", today);+ const now = new Date();+ const tz = "America/Sao_Paulo";+ const fmt = new Intl.DateTimeFormat("pt-BR", {+ timeZone: tz,+ year: "numeric",+ month: "2-digit",+ day: "2-digit",+ });+ const parts = fmt.formatToParts(now);+ const year = Number(parts.find(p => p.type === "year")!.value);+ const month = Number(parts.find(p => p.type === "month")!.value);+ const day = Number(parts.find(p => p.type === "day")!.value);+ const startOfDay = new Date(Date.UTC(year, month - 1, day, 0, 0, 0, 0));+ const endOfDay = new Date(Date.UTC(year, month - 1, day + 1, 0, 0, 0, 0));+ console.log("| CRONJOB | Data de hoje (America/Sao_Paulo):", fmt.format(now), "| janela:", startOfDay.toISOString(), "->", endOfDay.toISOString());
// Buscar todos os pedidos de hoje
const orders = await db.foodOrder.findMany({
where: {
- orderDate: today,+ orderDate: {+ gte: startOfDay,+ lt: endOfDay,+ },
status: "PENDING",
},

And later when building the display date:

- const dataPedidos = today.toLocaleDateString('pt-BR');+ const dataPedidos = fmt.format(now);

Also applies to: 63-64


11-19: Convert Exact-Date Filters to Day-Range Queries

We’ve identified several places where orderDate is compared by exact equality—this will miss orders with timestamps later in the day. To ensure you’re capturing the full day, each equality filter should be replaced with a half-open range filter:

where: {orderDate: {gte: startOfDay,lt: nextDayStart,},// …}

Please update the following occurrences:

src/server/api/routers/food-order.ts
– Lines ~21: orderDate: new Date(input.orderDate.setHours(0, 0, 0, 0))
– Line 67: orderDate: input.orderDate
– Line 266: { ...(input.startDate && input.endDate && { orderDate: new Date(input.startDate.setHours(0, 0, 0, 0)) }) }
– Lines ~510: orderDate: today
– Line 531: orderDate: date

src/app/api/cron/food_orders/route.ts
– Lines 17–19: orderDate: today

src/app/(authenticated)/food/page.tsx
– Line 172: client-pass-through orderDate: orderDate

src/app/(authenticated)/admin/food/page.tsx
– Line 354: orderDate: signatureExportDate

Rather than matching orderDate exactly at midnight, calculate startOfDay = today.setHours(0,0,0,0) and nextDayStart = new Date(startOfDay).setDate(startOfDay.getDate()+1), then use:

where: {orderDate: {gte: startOfDay,lt: nextDayStart},status: "PENDING",// …}

This change ensures you include all orders placed any time during the target day.

🧹 Nitpick comments (4)
src/lib/mail/html-mock.ts (2)

566-569: Nit: reuse a Collator instance to avoid repeated localeCompare setup in sort

Creating a Collator once and reusing its compare function is a tiny perf/readability improvement.

- .sort((a, b) =>- a[1].display.localeCompare(b[1].display, "pt-BR", {- sensitivity: "base",- }),- )+ .sort(() => {+ const collator = new Intl.Collator("pt-BR", { sensitivity: "base" });+ return (a, b) => collator.compare(a[1].display, b[1].display);+ }())

598-606: Optional: sort groups for deterministic email sections (e.g., by count desc, then alpha)

Stable ordering improves readability and diffability in email archives. Current Map iteration order depends on first-seen items.

- const totalsHtml = Array.from(groups.entries())+ const sortedGroups = Array.from(groups.entries()).sort((a, b) => {+ const byCount = b[1].length - a[1].length;+ return byCount !== 0 ? byCount : a[0].localeCompare(b[0], "pt-BR", { sensitivity: "base" });+ });++ const totalsHtml = sortedGroups
.map(([key, arr]) => `<li><strong>Total de pedidos de ${escapeHtml(key)}:</strong> ${arr.length}</li>`)
.join("");
- const sectionsHtml = Array.from(groups.entries())+ const sectionsHtml = sortedGroups
.map(([key, arr]) => {
...
})
.join("");

Also applies to: 602-629

src/app/api/cron/food_orders/route.ts (2)

88-101: Resilience: isolate per-restaurant sendEmail in its own try/catch to avoid aborting the loop

A single SMTP failure will currently stop processing for remaining restaurants. Wrap per-restaurant send with try/catch; continue on error.

- const emailContent = emailPedidosRestauranteAgrupado(+ const emailContent = emailPedidosRestauranteAgrupado(
restaurant.name,
dataPedidos,
pedidosAgrupados,
);
-- await sendEmail(- restaurant.email,- `Pedidos do Dia - ${restaurant.name}`,- emailContent,- "rh@boxdistribuidor.com.br"- );-- console.log(`| CRONJOB | Email enviado para ${restaurant.name} com ${ordersData.length} pedidos`);+ try {+ await sendEmail(+ restaurant.email,+ `Pedidos do Dia - ${restaurant.name}`,+ emailContent,+ "rh@boxdistribuidor.com.br"+ );+ console.log(`| CRONJOB | Email enviado para ${restaurant.name} com ${ordersData.length} pedidos`);+ } catch (e) {+ console.error(`| CRONJOB | Falha ao enviar email para ${restaurant.name}:`, e);+ }

13-14: Nit: log the human date in the same timezone used for the query

Once you adopt the tz-aware range, logging fmt.format(now) is more useful to operators than a raw Date object.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 85c45a4 and 09da98d.

📒 Files selected for processing (2)
  • src/app/api/cron/food_orders/route.ts (3 hunks)
  • src/lib/mail/html-mock.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/app/api/cron/food_orders/route.ts (1)
src/lib/mail/html-mock.ts (1)
  • GroupedEmailOrder (487-494)
🔇 Additional comments (3)
src/lib/mail/html-mock.ts (1)

496-502: LGTM on normalizeStr

Good choice for Portuguese inputs: NFD + combining mark strip + lowercase + trim covers the common diacritics in pt-BR and aligns with the “feijao/salada” normalization.

src/app/api/cron/food_orders/route.ts (2)

60-63: Rename to ordersData: clearer, avoids shadowing; LGTM

The destructuring rename clarifies intent and prevents confusion with the outer orders variable.


68-76: Stable opc generation: sorting by option then choice is a good call

This ensures deterministic opc strings fed into the grouping logic and improves email grouping predictability.

Comment on lines +520 to +545
for (const tok of tokens) {
const parts = tok.split(":");
const kRaw = parts[0]?.trim();
const vRaw = parts.slice(1).join(":").trim(); // suporta "Observação: algo: extra"
if (!kRaw || !vRaw) continue;

const kNorm = normalizeStr(kRaw);
const display =
kNorm === "feijao" ? "Feijão" : kNorm === "salada" ? "Salada" : kRaw;

const vBase = normalizeStr(vRaw);
const v = vBase.startsWith("s")
? "Sim"
: vBase.startsWith("n")
? "Não"
: vRaw;

if (map.has(kNorm)) {
// Se já existir, prioriza "Sim" se houver conflito/duplicata
const prev = map.get(kNorm)!;
const newVal = prev.value === "Sim" || v === "Sim" ? "Sim" : v;
map.set(kNorm, { display, value: newVal });
} else {
map.set(kNorm, { display, value: v });
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix: fallback when no valid "chave: valor" tokens are parsed to avoid "Prato com " keys

If every token in opc lacks a colon (e.g., "sem feijão, sem salada") or all tokens are invalid, the map stays empty. The current flow then builds an empty ordered list and returns something like "Prato com " (note the trailing space), producing a misleading and unstable grouping key.

Add a guard to treat this as “sem adicional” when map.size === 0, before the allNo check.

Apply this diff:

 // Completa pares esperados: se só veio Salada, assume Feijão: Não; e vice-versa
const hasFeijao = map.has("feijao");
const hasSalada = map.has("salada");
if (hasFeijao && !hasSalada) map.set("salada", { display: "Salada", value: "Não" });
if (hasSalada && !hasFeijao) map.set("feijao", { display: "Feijão", value: "Não" });
+ // Se nenhum par válido foi extraído, trata como "sem adicional"+ if (map.size === 0) return `${p.prato} sem adicional`;
// Se tudo é "Não", trata como "sem adicional"
const entries = Array.from(map.values());
const allNo = entries.length > 0 && entries.every((e) => e.value === "Não");
if (allNo) return `${p.prato} sem adicional`;
// Ordena: Feijão, Salada, depois demais chaves em ordem alfabética

Also applies to: 554-557, 573-577

🤖 Prompt for AI Agents
In src/lib/mail/html-mock.ts around lines 520-545 (and similarly at 554-557 and
573-577), add a guard that if after parsing tokens the map is empty (map.size
=== 0) then insert a fallback entry to represent "sem adicional" before the
existing allNo check; specifically set map.set("sem adicional", { display: "Sem
adicional", value: "Não" }) (or equivalent normalized key/display/value you use
elsewhere) so the subsequent formatting produces a stable "Sem adicional"
grouping instead of "Prato com " or an empty list.

@rbxyz
rbxyz merged commit 47d0f7e into mainAug 22, 2025
6 checks passed
@rbxyz
rbxyz deleted the 30-problema-envio-emails branch September 2, 2025 11:08
@coderabbitaicoderabbitaiBot mentioned this pull request Dec 9, 2025
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

problema-envio-emails

1 participant

@rbxyz
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

30 problema envio emails - #33

Merged
rbxyz merged 2 commits into
mainfrom
30-problema-envio-emails
Aug 22, 2025
Merged

30 problema envio emails#33
rbxyz merged 2 commits into
mainfrom
30-problema-envio-emails

Conversation

@rbxyz

@rbxyzrbxyz commented Aug 22, 2025

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • Bug Fixes

    • Restaurant order emails now group items consistently and predictably.
    • Handles accents/case, duplicate or conflicting options, and fills missing Feijão/Salada with “Não” when absent.
    • Ensures canonical option order and clearer labels (e.g., “{prato} com Feijão: X, Salada: Y, …” or “sem adicional”).
  • Refactor

    • Improved internal naming for per-restaurant order data.
    • Added timestamp logging during daily processing.

@rbxyzrbxyz linked an issue Aug 22, 2025 that may be closed by this pull request
@coderabbitai

coderabbitaiBot commented Aug 22, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Refactors cron route logging and variable names for per-restaurant order processing without changing behavior. Overhauls email grouping logic to normalize and deterministically parse option tokens (p.opc), handling diacritics, case, duplicates, and defaults, producing canonicalized strings for grouping while preserving the existing public API.

Changes

Cohort / File(s)Summary
Cron route processing tweaks
src/app/api/cron/food_orders/route.ts
Added a log for normalized current date. Renamed inner collection from orders to ordersData and updated all references, including grouped orders source, conditionals, and logs. No public API changes.
Email grouping normalization
src/lib/mail/html-mock.ts
Introduced normalizeStr and replaced opc parsing with token-based, diacritic/case-insensitive logic. Normalizes keys/values (e.g., Feijão/Salada, Sim/Não), resolves duplicates, fills missing defaults, orders keys deterministically, and returns canonical grouping strings. Public signatures unchanged.

Sequence Diagram(s)

sequenceDiagram
autonumber
participant Cron as Cron Route
participant DB as Orders Source
participant Grouper as Opc Normalizer (updated)
participant Mail as Email Builder/Sender
Cron->>DB: Fetch today's orders
Cron->>Cron: Normalize date to midnight (log)
loop per restaurant
Cron->>Grouper: Build grouped keys from p.opc
Note right of Grouper: New deterministic parsing<br/>• normalize diacritics/case<br/>• resolve duplicates<br/>• fill defaults
Grouper-->>Cron: Canonical grouping strings
Cron->>Mail: Generate grouped email sections
Mail-->>Cron: Email content
Cron->>Mail: Send email
Mail-->>Cron: Result (success/failure)
end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • jdalmeida

Poem

A whisk of bytes, a nibble of logs,
I hop through orders, past digital fogs.
Opc now tidy—Feijão says “Sim”!
Salada replies, in canonical trim.
Grouped and mailed, with a twitch of my ear—
Ship it, ship it, lunch hour draws near! 🥕🐇

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 30-problema-envio-emails

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@vercel

vercelBot commented Aug 22, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentPreviewCommentsUpdated (UTC)
eloReadyReadyPreviewCommentAug 22, 2025 2:53pm

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
src/lib/mail/html-mock.ts (1)

598-606: Security: escape dynamic HTML to prevent injection in emails

User-controlled fields (e.g., funcionário, observações) and DB-configured strings (opções, pratos) are injected raw into HTML. Many email clients render HTML and allow URLs; this is a phishing/XSS vector. Escape all dynamic text before embedding in the template. Key strings produced by getGroupKey can also contain raw option names.

Minimal patch:

+ function escapeHtml(s: string): string {+ return String(s)+ .replace(/&/g, "&amp;")+ .replace(/</g, "&lt;")+ .replace(/>/g, "&gt;")+ .replace(/"/g, "&quot;")+ .replace(/'/g, "&#39;");+ }
...
- const totalsHtml = Array.from(groups.entries())- .map(([key, arr]) => `<li><strong>Total de pedidos de ${key}:</strong> ${arr.length}</li>`)+ const totalsHtml = Array.from(groups.entries())+ .map(([key, arr]) => `<li><strong>Total de pedidos de ${escapeHtml(key)}:</strong> ${arr.length}</li>`)
.join("");
const sectionsHtml = Array.from(groups.entries())
.map(([key, arr]) => {
const itemsHtml = arr
.map(
(p) => `
<div class="pedido">
- <div><strong>Pedido:</strong> ${p.num}</div>- <div><strong>Data:</strong> ${p.data}</div>- <div><strong>Funcionário:</strong> ${p.func}</div>- <div><strong>Prato:</strong> ${p.prato}</div>- <div><strong>Opcionais:</strong> ${(p.opc ?? "").trim() || "-"}</div>- <div><strong>Observações:</strong> ${p.obs ?? "-"}</div>+ <div><strong>Pedido:</strong> ${p.num}</div>+ <div><strong>Data:</strong> ${escapeHtml(p.data)}</div>+ <div><strong>Funcionário:</strong> ${escapeHtml(p.func)}</div>+ <div><strong>Prato:</strong> ${escapeHtml(p.prato)}</div>+ <div><strong>Opcionais:</strong> ${escapeHtml(((p.opc ?? "").trim() || "-"))}</div>+ <div><strong>Observações:</strong> ${escapeHtml(p.obs ?? "-")}</div>
</div>
`,
)
.join("");
return `
<section class="group">
- <h2>${key}</h2>- <div class="group-count">Total de pedidos de ${key}: ${arr.length}</div>+ <h2>${escapeHtml(key)}</h2>+ <div class="group-count">Total de pedidos de ${escapeHtml(key)}: ${arr.length}</div>
<div class="pedidos">
${itemsHtml}
</div>
</section>
`;
})

Optionally also escape nomeRestaurante in the header. I can provide a follow-up patch covering all templates in this file if you want.

Also applies to: 620-623, 606-617, 612-614

src/app/api/cron/food_orders/route.ts (2)

11-19: Bug: equality on Date (midnight) + server timezone likely filters out valid orders; use day range in a fixed tz

Using orderDate: today where today is set to 00:00:00.000 in the server’s local tz typically misses rows whose timestamps aren’t exactly midnight. In serverless/containers (often UTC), this gets worse for BR users. Query by [startOfDay, endOfDay) in America/Sao_Paulo and also format dataPedidos in the same tz.

Apply this diff:

- const today = new Date();- today.setHours(0, 0, 0, 0);- console.log("| CRONJOB | Data de hoje:", today);+ const now = new Date();+ const tz = "America/Sao_Paulo";+ const fmt = new Intl.DateTimeFormat("pt-BR", {+ timeZone: tz,+ year: "numeric",+ month: "2-digit",+ day: "2-digit",+ });+ const parts = fmt.formatToParts(now);+ const year = Number(parts.find(p => p.type === "year")!.value);+ const month = Number(parts.find(p => p.type === "month")!.value);+ const day = Number(parts.find(p => p.type === "day")!.value);+ const startOfDay = new Date(Date.UTC(year, month - 1, day, 0, 0, 0, 0));+ const endOfDay = new Date(Date.UTC(year, month - 1, day + 1, 0, 0, 0, 0));+ console.log("| CRONJOB | Data de hoje (America/Sao_Paulo):", fmt.format(now), "| janela:", startOfDay.toISOString(), "->", endOfDay.toISOString());
// Buscar todos os pedidos de hoje
const orders = await db.foodOrder.findMany({
where: {
- orderDate: today,+ orderDate: {+ gte: startOfDay,+ lt: endOfDay,+ },
status: "PENDING",
},

And later when building the display date:

- const dataPedidos = today.toLocaleDateString('pt-BR');+ const dataPedidos = fmt.format(now);

Also applies to: 63-64


11-19: Convert Exact-Date Filters to Day-Range Queries

We’ve identified several places where orderDate is compared by exact equality—this will miss orders with timestamps later in the day. To ensure you’re capturing the full day, each equality filter should be replaced with a half-open range filter:

where: {orderDate: {gte: startOfDay,lt: nextDayStart,},// …}

Please update the following occurrences:

src/server/api/routers/food-order.ts
– Lines ~21: orderDate: new Date(input.orderDate.setHours(0, 0, 0, 0))
– Line 67: orderDate: input.orderDate
– Line 266: { ...(input.startDate && input.endDate && { orderDate: new Date(input.startDate.setHours(0, 0, 0, 0)) }) }
– Lines ~510: orderDate: today
– Line 531: orderDate: date

src/app/api/cron/food_orders/route.ts
– Lines 17–19: orderDate: today

src/app/(authenticated)/food/page.tsx
– Line 172: client-pass-through orderDate: orderDate

src/app/(authenticated)/admin/food/page.tsx
– Line 354: orderDate: signatureExportDate

Rather than matching orderDate exactly at midnight, calculate startOfDay = today.setHours(0,0,0,0) and nextDayStart = new Date(startOfDay).setDate(startOfDay.getDate()+1), then use:

where: {orderDate: {gte: startOfDay,lt: nextDayStart},status: "PENDING",// …}

This change ensures you include all orders placed any time during the target day.

🧹 Nitpick comments (4)
src/lib/mail/html-mock.ts (2)

566-569: Nit: reuse a Collator instance to avoid repeated localeCompare setup in sort

Creating a Collator once and reusing its compare function is a tiny perf/readability improvement.

- .sort((a, b) =>- a[1].display.localeCompare(b[1].display, "pt-BR", {- sensitivity: "base",- }),- )+ .sort(() => {+ const collator = new Intl.Collator("pt-BR", { sensitivity: "base" });+ return (a, b) => collator.compare(a[1].display, b[1].display);+ }())

598-606: Optional: sort groups for deterministic email sections (e.g., by count desc, then alpha)

Stable ordering improves readability and diffability in email archives. Current Map iteration order depends on first-seen items.

- const totalsHtml = Array.from(groups.entries())+ const sortedGroups = Array.from(groups.entries()).sort((a, b) => {+ const byCount = b[1].length - a[1].length;+ return byCount !== 0 ? byCount : a[0].localeCompare(b[0], "pt-BR", { sensitivity: "base" });+ });++ const totalsHtml = sortedGroups
.map(([key, arr]) => `<li><strong>Total de pedidos de ${escapeHtml(key)}:</strong> ${arr.length}</li>`)
.join("");
- const sectionsHtml = Array.from(groups.entries())+ const sectionsHtml = sortedGroups
.map(([key, arr]) => {
...
})
.join("");

Also applies to: 602-629

src/app/api/cron/food_orders/route.ts (2)

88-101: Resilience: isolate per-restaurant sendEmail in its own try/catch to avoid aborting the loop

A single SMTP failure will currently stop processing for remaining restaurants. Wrap per-restaurant send with try/catch; continue on error.

- const emailContent = emailPedidosRestauranteAgrupado(+ const emailContent = emailPedidosRestauranteAgrupado(
restaurant.name,
dataPedidos,
pedidosAgrupados,
);
-- await sendEmail(- restaurant.email,- `Pedidos do Dia - ${restaurant.name}`,- emailContent,- "rh@boxdistribuidor.com.br"- );-- console.log(`| CRONJOB | Email enviado para ${restaurant.name} com ${ordersData.length} pedidos`);+ try {+ await sendEmail(+ restaurant.email,+ `Pedidos do Dia - ${restaurant.name}`,+ emailContent,+ "rh@boxdistribuidor.com.br"+ );+ console.log(`| CRONJOB | Email enviado para ${restaurant.name} com ${ordersData.length} pedidos`);+ } catch (e) {+ console.error(`| CRONJOB | Falha ao enviar email para ${restaurant.name}:`, e);+ }

13-14: Nit: log the human date in the same timezone used for the query

Once you adopt the tz-aware range, logging fmt.format(now) is more useful to operators than a raw Date object.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 85c45a4 and 09da98d.

📒 Files selected for processing (2)
  • src/app/api/cron/food_orders/route.ts (3 hunks)
  • src/lib/mail/html-mock.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/app/api/cron/food_orders/route.ts (1)
src/lib/mail/html-mock.ts (1)
  • GroupedEmailOrder (487-494)
🔇 Additional comments (3)
src/lib/mail/html-mock.ts (1)

496-502: LGTM on normalizeStr

Good choice for Portuguese inputs: NFD + combining mark strip + lowercase + trim covers the common diacritics in pt-BR and aligns with the “feijao/salada” normalization.

src/app/api/cron/food_orders/route.ts (2)

60-63: Rename to ordersData: clearer, avoids shadowing; LGTM

The destructuring rename clarifies intent and prevents confusion with the outer orders variable.


68-76: Stable opc generation: sorting by option then choice is a good call

This ensures deterministic opc strings fed into the grouping logic and improves email grouping predictability.

Comment on lines +520 to +545
for (const tok of tokens) {
const parts = tok.split(":");
const kRaw = parts[0]?.trim();
const vRaw = parts.slice(1).join(":").trim(); // suporta "Observação: algo: extra"
if (!kRaw || !vRaw) continue;

const kNorm = normalizeStr(kRaw);
const display =
kNorm === "feijao" ? "Feijão" : kNorm === "salada" ? "Salada" : kRaw;

const vBase = normalizeStr(vRaw);
const v = vBase.startsWith("s")
? "Sim"
: vBase.startsWith("n")
? "Não"
: vRaw;

if (map.has(kNorm)) {
// Se já existir, prioriza "Sim" se houver conflito/duplicata
const prev = map.get(kNorm)!;
const newVal = prev.value === "Sim" || v === "Sim" ? "Sim" : v;
map.set(kNorm, { display, value: newVal });
} else {
map.set(kNorm, { display, value: v });
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix: fallback when no valid "chave: valor" tokens are parsed to avoid "Prato com " keys

If every token in opc lacks a colon (e.g., "sem feijão, sem salada") or all tokens are invalid, the map stays empty. The current flow then builds an empty ordered list and returns something like "Prato com " (note the trailing space), producing a misleading and unstable grouping key.

Add a guard to treat this as “sem adicional” when map.size === 0, before the allNo check.

Apply this diff:

 // Completa pares esperados: se só veio Salada, assume Feijão: Não; e vice-versa
const hasFeijao = map.has("feijao");
const hasSalada = map.has("salada");
if (hasFeijao && !hasSalada) map.set("salada", { display: "Salada", value: "Não" });
if (hasSalada && !hasFeijao) map.set("feijao", { display: "Feijão", value: "Não" });
+ // Se nenhum par válido foi extraído, trata como "sem adicional"+ if (map.size === 0) return `${p.prato} sem adicional`;
// Se tudo é "Não", trata como "sem adicional"
const entries = Array.from(map.values());
const allNo = entries.length > 0 && entries.every((e) => e.value === "Não");
if (allNo) return `${p.prato} sem adicional`;
// Ordena: Feijão, Salada, depois demais chaves em ordem alfabética

Also applies to: 554-557, 573-577

🤖 Prompt for AI Agents
In src/lib/mail/html-mock.ts around lines 520-545 (and similarly at 554-557 and
573-577), add a guard that if after parsing tokens the map is empty (map.size
=== 0) then insert a fallback entry to represent "sem adicional" before the
existing allNo check; specifically set map.set("sem adicional", { display: "Sem
adicional", value: "Não" }) (or equivalent normalized key/display/value you use
elsewhere) so the subsequent formatting produces a stable "Sem adicional"
grouping instead of "Prato com " or an empty list.

@rbxyz
rbxyz merged commit 47d0f7e into mainAug 22, 2025
6 checks passed
@rbxyz
rbxyz deleted the 30-problema-envio-emails branch September 2, 2025 11:08
@coderabbitaicoderabbitaiBot mentioned this pull request Dec 9, 2025
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

problema-envio-emails

1 participant

@rbxyz