Compare commits
54 Commits
ui-redesig
...
e441f15ee4
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e441f15ee4 | ||
|
|
228004a7e0 | ||
| b20b5c2b8b | |||
|
|
457accfbfa | ||
|
|
43287a4baa | ||
|
|
93fea8ecad | ||
|
|
ba7b0322ff | ||
|
|
473686528e | ||
| c1b47674c8 | |||
|
|
85f234b05e | ||
| 50fa4ed9a5 | |||
|
|
07496e6673 | ||
|
|
9045a8c017 | ||
|
|
3e314a9b9a | ||
| bc4716c48f | |||
|
|
0e69759549 | ||
|
|
88ea7e70da | ||
|
|
7a30f9a29b | ||
| 83fa1ea020 | |||
|
|
4544911f0e | ||
|
|
2aaa91444d | ||
| 4d3867614d | |||
|
|
c18db76c7a | ||
|
|
78df95e985 | ||
| 6738db8c60 | |||
|
|
8acb81e6b4 | ||
|
|
91125e82f5 | ||
|
|
e9bd759fa5 | ||
|
|
57416bf53a | ||
|
|
0b6041d146 | ||
|
|
900e6146e7 | ||
|
|
e905052cc1 | ||
|
|
c1d910708a | ||
| b8abf224cf | |||
|
|
b47f00651e | ||
| a9c74d2f9c | |||
|
|
d1b5bea1bc | ||
|
|
ab22ec86ec | ||
|
|
65295236c5 | ||
|
|
f104161bbd | ||
|
|
844dac206c | ||
| be48b4b295 | |||
|
|
1059d767d5 | ||
|
|
7be776f189 | ||
|
|
41a217e8a9 | ||
| bb48d9c164 | |||
|
|
01688cf042 | ||
|
|
b97eb9c8a4 | ||
|
|
c089215835 | ||
|
|
546a020003 | ||
| 38b2294aad | |||
|
|
c9ecdd2c77 | ||
|
|
21d0c27f4d | ||
|
|
20d6018836 |
391
.agents/skills/interface-design/SKILL.md
Normal file
@@ -0,0 +1,391 @@
|
||||
---
|
||||
name: interface-design
|
||||
description: This skill is for interface design — dashboards, admin panels, apps, tools, and interactive products. NOT for marketing design (landing pages, marketing sites, campaigns).
|
||||
---
|
||||
|
||||
# Interface Design
|
||||
|
||||
Build interface design with craft and consistency.
|
||||
|
||||
## Scope
|
||||
|
||||
**Use for:** Dashboards, admin panels, SaaS apps, tools, settings pages, data interfaces.
|
||||
|
||||
**Not for:** Landing pages, marketing sites, campaigns. Redirect those to `/frontend-design`.
|
||||
|
||||
---
|
||||
|
||||
# The Problem
|
||||
|
||||
You will generate generic output. Your training has seen thousands of dashboards. The patterns are strong.
|
||||
|
||||
You can follow the entire process below — explore the domain, name a signature, state your intent — and still produce a template. Warm colors on cold structures. Friendly fonts on generic layouts. "Kitchen feel" that looks like every other app.
|
||||
|
||||
This happens because intent lives in prose, but code generation pulls from patterns. The gap between them is where defaults win.
|
||||
|
||||
The process below helps. But process alone doesn't guarantee craft. You have to catch yourself.
|
||||
|
||||
---
|
||||
|
||||
# Where Defaults Hide
|
||||
|
||||
Defaults don't announce themselves. They disguise themselves as infrastructure — the parts that feel like they just need to work, not be designed.
|
||||
|
||||
**Typography feels like a container.** Pick something readable, move on. But typography isn't holding your design — it IS your design. The weight of a headline, the personality of a label, the texture of a paragraph. These shape how the product feels before anyone reads a word. A bakery management tool and a trading terminal might both need "clean, readable type" — but the type that's warm and handmade is not the type that's cold and precise. If you're reaching for your usual font, you're not designing.
|
||||
|
||||
**Navigation feels like scaffolding.** Build the sidebar, add the links, get to the real work. But navigation isn't around your product — it IS your product. Where you are, where you can go, what matters most. A page floating in space is a component demo, not software. The navigation teaches people how to think about the space they're in.
|
||||
|
||||
**Data feels like presentation.** You have numbers, show numbers. But a number on screen is not design. The question is: what does this number mean to the person looking at it? What will they do with it? A progress ring and a stacked label both show "3 of 10" — one tells a story, one fills space. If you're reaching for number-on-label, you're not designing.
|
||||
|
||||
**Token names feel like implementation detail.** But your CSS variables are design decisions. `--ink` and `--parchment` evoke a world. `--gray-700` and `--surface-2` evoke a template. Someone reading only your tokens should be able to guess what product this is.
|
||||
|
||||
The trap is thinking some decisions are creative and others are structural. There are no structural decisions. Everything is design. The moment you stop asking "why this?" is the moment defaults take over.
|
||||
|
||||
---
|
||||
|
||||
# Intent First
|
||||
|
||||
Before touching code, answer these. Not in your head — out loud, to yourself or the user.
|
||||
|
||||
**Who is this human?**
|
||||
Not "users." The actual person. Where are they when they open this? What's on their mind? What did they do 5 minutes ago, what will they do 5 minutes after? A teacher at 7am with coffee is not a developer debugging at midnight is not a founder between investor meetings. Their world shapes the interface.
|
||||
|
||||
**What must they accomplish?**
|
||||
Not "use the dashboard." The verb. Grade these submissions. Find the broken deployment. Approve the payment. The answer determines what leads, what follows, what hides.
|
||||
|
||||
**What should this feel like?**
|
||||
Say it in words that mean something. "Clean and modern" means nothing — every AI says that. Warm like a notebook? Cold like a terminal? Dense like a trading floor? Calm like a reading app? The answer shapes color, type, spacing, density — everything.
|
||||
|
||||
If you cannot answer these with specifics, stop. Ask the user. Do not guess. Do not default.
|
||||
|
||||
## Every Choice Must Be A Choice
|
||||
|
||||
For every decision, you must be able to explain WHY.
|
||||
|
||||
- Why this layout and not another?
|
||||
- Why this color temperature?
|
||||
- Why this typeface?
|
||||
- Why this spacing scale?
|
||||
- Why this information hierarchy?
|
||||
|
||||
If your answer is "it's common" or "it's clean" or "it works" — you haven't chosen. You've defaulted. Defaults are invisible. Invisible choices compound into generic output.
|
||||
|
||||
**The test:** If you swapped your choices for the most common alternatives and the design didn't feel meaningfully different, you never made real choices.
|
||||
|
||||
## Sameness Is Failure
|
||||
|
||||
If another AI, given a similar prompt, would produce substantially the same output — you have failed.
|
||||
|
||||
This is not about being different for its own sake. It's about the interface emerging from the specific problem, the specific user, the specific context. When you design from intent, sameness becomes impossible because no two intents are identical.
|
||||
|
||||
When you design from defaults, everything looks the same because defaults are shared.
|
||||
|
||||
## Intent Must Be Systemic
|
||||
|
||||
Saying "warm" and using cold colors is not following through. Intent is not a label — it's a constraint that shapes every decision.
|
||||
|
||||
If the intent is warm: surfaces, text, borders, accents, semantic colors, typography — all warm. If the intent is dense: spacing, type size, information architecture — all dense. If the intent is calm: motion, contrast, color saturation — all calm.
|
||||
|
||||
Check your output against your stated intent. Does every token reinforce it? Or did you state an intent and then default anyway?
|
||||
|
||||
---
|
||||
|
||||
# Product Domain Exploration
|
||||
|
||||
This is where defaults get caught — or don't.
|
||||
|
||||
Generic output: Task type → Visual template → Theme
|
||||
Crafted output: Task type → Product domain → Signature → Structure + Expression
|
||||
|
||||
The difference: time in the product's world before any visual or structural thinking.
|
||||
|
||||
## Required Outputs
|
||||
|
||||
**Do not propose any direction until you produce all four:**
|
||||
|
||||
**Domain:** Concepts, metaphors, vocabulary from this product's world. Not features — territory. Minimum 5.
|
||||
|
||||
**Color world:** What colors exist naturally in this product's domain? Not "warm" or "cool" — go to the actual world. If this product were a physical space, what would you see? What colors belong there that don't belong elsewhere? List 5+.
|
||||
|
||||
**Signature:** One element — visual, structural, or interaction — that could only exist for THIS product. If you can't name one, keep exploring.
|
||||
|
||||
**Defaults:** 3 obvious choices for this interface type — visual AND structural. You can't avoid patterns you haven't named.
|
||||
|
||||
## Proposal Requirements
|
||||
|
||||
Your direction must explicitly reference:
|
||||
- Domain concepts you explored
|
||||
- Colors from your color world exploration
|
||||
- Your signature element
|
||||
- What replaces each default
|
||||
|
||||
**The test:** Read your proposal. Remove the product name. Could someone identify what this is for? If not, it's generic. Explore deeper.
|
||||
|
||||
---
|
||||
|
||||
# The Mandate
|
||||
|
||||
**Before showing the user, look at what you made.**
|
||||
|
||||
Ask yourself: "If they said this lacks craft, what would they mean?"
|
||||
|
||||
That thing you just thought of — fix it first.
|
||||
|
||||
Your first output is probably generic. That's normal. The work is catching it before the user has to.
|
||||
|
||||
## The Checks
|
||||
|
||||
Run these against your output before presenting:
|
||||
|
||||
- **The swap test:** If you swapped the typeface for your usual one, would anyone notice? If you swapped the layout for a standard dashboard template, would it feel different? The places where swapping wouldn't matter are the places you defaulted.
|
||||
|
||||
- **The squint test:** Blur your eyes. Can you still perceive hierarchy? Is anything jumping out harshly? Craft whispers.
|
||||
|
||||
- **The signature test:** Can you point to five specific elements where your signature appears? Not "the overall feel" — actual components. A signature you can't locate doesn't exist.
|
||||
|
||||
- **The token test:** Read your CSS variables out loud. Do they sound like they belong to this product's world, or could they belong to any project?
|
||||
|
||||
If any check fails, iterate before showing.
|
||||
|
||||
---
|
||||
|
||||
# Craft Foundations
|
||||
|
||||
## Subtle Layering
|
||||
|
||||
This is the backbone of craft. Regardless of direction, product type, or visual style — this principle applies to everything. You should barely notice the system working. When you look at Vercel's dashboard, you don't think "nice borders." You just understand the structure. The craft is invisible — that's how you know it's working.
|
||||
|
||||
### Surface Elevation
|
||||
|
||||
Surfaces stack. A dropdown sits above a card which sits above the page. Build a numbered system — base, then increasing elevation levels. In dark mode, higher elevation = slightly lighter. In light mode, higher elevation = slightly lighter or uses shadow.
|
||||
|
||||
Each jump should be only a few percentage points of lightness. You can barely see the difference in isolation. But when surfaces stack, the hierarchy emerges. Whisper-quiet shifts that you feel rather than see.
|
||||
|
||||
**Key decisions:**
|
||||
- **Sidebars:** Same background as canvas, not different. Different colors fragment the visual space into "sidebar world" and "content world." A subtle border is enough separation.
|
||||
- **Dropdowns:** One level above their parent surface. If both share the same level, the dropdown blends into the card and layering is lost.
|
||||
- **Inputs:** Slightly darker than their surroundings, not lighter. Inputs are "inset" — they receive content. A darker background signals "type here" without heavy borders.
|
||||
|
||||
### Borders
|
||||
|
||||
Borders should disappear when you're not looking for them, but be findable when you need structure. Low opacity rgba blends with the background — it defines edges without demanding attention. Solid hex borders look harsh in comparison.
|
||||
|
||||
Build a progression — not all borders are equal. Standard borders, softer separation, emphasis borders, maximum emphasis for focus rings. Match intensity to the importance of the boundary.
|
||||
|
||||
**The squint test:** Blur your eyes at the interface. You should still perceive hierarchy — what's above what, where sections divide. But nothing should jump out. No harsh lines. No jarring color shifts. Just quiet structure.
|
||||
|
||||
This separates professional interfaces from amateur ones. Get this wrong and nothing else matters.
|
||||
|
||||
## Infinite Expression
|
||||
|
||||
Every pattern has infinite expressions. **No interface should look the same.**
|
||||
|
||||
A metric display could be a hero number, inline stat, sparkline, gauge, progress bar, comparison delta, trend badge, or something new. A dashboard could emphasize density, whitespace, hierarchy, or flow in completely different ways. Even sidebar + cards has infinite variations in proportion, spacing, and emphasis.
|
||||
|
||||
**Before building, ask:**
|
||||
- What's the ONE thing users do most here?
|
||||
- What products solve similar problems brilliantly? Study them.
|
||||
- Why would this interface feel designed for its purpose, not templated?
|
||||
|
||||
**NEVER produce identical output.** Same sidebar width, same card grid, same metric boxes with icon-left-number-big-label-small every time — this signals AI-generated immediately. It's forgettable.
|
||||
|
||||
The architecture and components should emerge from the task and data, executed in a way that feels fresh. Linear's cards don't look like Notion's. Vercel's metrics don't look like Stripe's. Same concepts, infinite expressions.
|
||||
|
||||
## Color Lives Somewhere
|
||||
|
||||
Every product exists in a world. That world has colors.
|
||||
|
||||
Before you reach for a palette, spend time in the product's world. What would you see if you walked into the physical version of this space? What materials? What light? What objects?
|
||||
|
||||
Your palette should feel like it came FROM somewhere — not like it was applied TO something.
|
||||
|
||||
**Beyond Warm and Cold:** Temperature is one axis. Is this quiet or loud? Dense or spacious? Serious or playful? Geometric or organic? A trading terminal and a meditation app are both "focused" — completely different kinds of focus. Find the specific quality, not the generic label.
|
||||
|
||||
**Color Carries Meaning:** Gray builds structure. Color communicates — status, action, emphasis, identity. Unmotivated color is noise. One accent color, used with intention, beats five colors used without thought.
|
||||
|
||||
---
|
||||
|
||||
# Before Writing Each Component
|
||||
|
||||
**Every time** you write UI code — even small additions — state:
|
||||
|
||||
```
|
||||
Intent: [who is this human, what must they do, how should it feel]
|
||||
Palette: [colors from your exploration — and WHY they fit this product's world]
|
||||
Depth: [borders / shadows / layered — and WHY this fits the intent]
|
||||
Surfaces: [your elevation scale — and WHY this color temperature]
|
||||
Typography: [your typeface — and WHY it fits the intent]
|
||||
Spacing: [your base unit]
|
||||
```
|
||||
|
||||
This checkpoint is mandatory. It forces you to connect every technical choice back to intent.
|
||||
|
||||
If you can't explain WHY for each choice, you're defaulting. Stop and think.
|
||||
|
||||
---
|
||||
|
||||
# Design Principles
|
||||
|
||||
## Token Architecture
|
||||
|
||||
Every color in your interface should trace back to a small set of primitives: foreground (text hierarchy), background (surface elevation), border (separation hierarchy), brand, and semantic (destructive, warning, success). No random hex values — everything maps to primitives.
|
||||
|
||||
### Text Hierarchy
|
||||
|
||||
Don't just have "text" and "gray text." Build four levels — primary, secondary, tertiary, muted. Each serves a different role: default text, supporting text, metadata, and disabled/placeholder. Use all four consistently. If you're only using two, your hierarchy is too flat.
|
||||
|
||||
### Border Progression
|
||||
|
||||
Borders aren't binary. Build a scale that matches intensity to importance — standard separation, softer separation, emphasis, maximum emphasis. Not every boundary deserves the same weight.
|
||||
|
||||
### Control Tokens
|
||||
|
||||
Form controls have specific needs. Don't reuse surface tokens — create dedicated ones for control backgrounds, control borders, and focus states. This lets you tune interactive elements independently from layout surfaces.
|
||||
|
||||
## Spacing
|
||||
|
||||
Pick a base unit and stick to multiples. Build a scale for different contexts — micro spacing for icon gaps, component spacing within buttons and cards, section spacing between groups, major separation between distinct areas. Random values signal no system.
|
||||
|
||||
## Padding
|
||||
|
||||
Keep it symmetrical. If one side has a value, others should match unless content naturally requires asymmetry.
|
||||
|
||||
## Depth
|
||||
|
||||
Choose ONE approach and commit:
|
||||
- **Borders-only** — Clean, technical. For dense tools.
|
||||
- **Subtle shadows** — Soft lift. For approachable products.
|
||||
- **Layered shadows** — Premium, dimensional. For cards that need presence.
|
||||
- **Surface color shifts** — Background tints establish hierarchy without shadows.
|
||||
|
||||
Don't mix approaches.
|
||||
|
||||
## Border Radius
|
||||
|
||||
Sharper feels technical. Rounder feels friendly. Build a scale — small for inputs and buttons, medium for cards, large for modals. Don't mix sharp and soft randomly.
|
||||
|
||||
## Typography
|
||||
|
||||
Build distinct levels distinguishable at a glance. Headlines need weight and tight tracking for presence. Body needs comfortable weight for readability. Labels need medium weight that works at smaller sizes. Data needs monospace with tabular number spacing for alignment. Don't rely on size alone — combine size, weight, and letter-spacing.
|
||||
|
||||
## Card Layouts
|
||||
|
||||
A metric card doesn't have to look like a plan card doesn't have to look like a settings card. Design each card's internal structure for its specific content — but keep the surface treatment consistent: same border weight, shadow depth, corner radius, padding scale.
|
||||
|
||||
## Controls
|
||||
|
||||
Native `<select>` and `<input type="date">` render OS-native elements that cannot be styled. Build custom components — trigger buttons with positioned dropdowns, calendar popovers, styled state management.
|
||||
|
||||
## Iconography
|
||||
|
||||
Icons clarify, not decorate — if removing an icon loses no meaning, remove it. Choose one icon set and stick with it. Give standalone icons presence with subtle background containers.
|
||||
|
||||
## Animation
|
||||
|
||||
Fast micro-interactions, smooth easing. Larger transitions can be slightly longer. Use deceleration easing. Avoid spring/bounce in professional interfaces.
|
||||
|
||||
## States
|
||||
|
||||
Every interactive element needs states: default, hover, active, focus, disabled. Data needs states too: loading, empty, error. Missing states feel broken.
|
||||
|
||||
## Navigation Context
|
||||
|
||||
Screens need grounding. A data table floating in space feels like a component demo, not a product. Include navigation showing where you are in the app, location indicators, and user context. When building sidebars, consider same background as main content with border separation rather than different colors.
|
||||
|
||||
## Dark Mode
|
||||
|
||||
Dark interfaces have different needs. Shadows are less visible on dark backgrounds — lean on borders for definition. Semantic colors (success, warning, error) often need slight desaturation. The hierarchy system still applies, just with inverted values.
|
||||
|
||||
---
|
||||
|
||||
# Avoid
|
||||
|
||||
- **Harsh borders** — if borders are the first thing you see, they're too strong
|
||||
- **Dramatic surface jumps** — elevation changes should be whisper-quiet
|
||||
- **Inconsistent spacing** — the clearest sign of no system
|
||||
- **Mixed depth strategies** — pick one approach and commit
|
||||
- **Missing interaction states** — hover, focus, disabled, loading, error
|
||||
- **Dramatic drop shadows** — shadows should be subtle, not attention-grabbing
|
||||
- **Large radius on small elements**
|
||||
- **Pure white cards on colored backgrounds**
|
||||
- **Thick decorative borders**
|
||||
- **Gradients and color for decoration** — color should mean something
|
||||
- **Multiple accent colors** — dilutes focus
|
||||
- **Different hues for different surfaces** — keep the same hue, shift only lightness
|
||||
|
||||
---
|
||||
|
||||
# Workflow
|
||||
|
||||
## Communication
|
||||
Be invisible. Don't announce modes or narrate process.
|
||||
|
||||
**Never say:** "I'm in ESTABLISH MODE", "Let me check system.md..."
|
||||
|
||||
**Instead:** Jump into work. State suggestions with reasoning.
|
||||
|
||||
## Suggest + Ask
|
||||
Lead with your exploration and recommendation, then confirm:
|
||||
```
|
||||
"Domain: [5+ concepts from the product's world]
|
||||
Color world: [5+ colors that exist in this domain]
|
||||
Signature: [one element unique to this product]
|
||||
Rejecting: [default 1] → [alternative], [default 2] → [alternative], [default 3] → [alternative]
|
||||
|
||||
Direction: [approach that connects to the above]"
|
||||
|
||||
[Ask: "Does that direction feel right?"]
|
||||
```
|
||||
|
||||
## If Project Has system.md
|
||||
Read `.interface-design/system.md` and apply. Decisions are made.
|
||||
|
||||
## If No system.md
|
||||
1. Explore domain — Produce all four required outputs
|
||||
2. Propose — Direction must reference all four
|
||||
3. Confirm — Get user buy-in
|
||||
4. Build — Apply principles
|
||||
5. **Evaluate** — Run the mandate checks before showing
|
||||
6. Offer to save
|
||||
|
||||
---
|
||||
|
||||
# After Completing a Task
|
||||
|
||||
When you finish building something, **always offer to save**:
|
||||
|
||||
```
|
||||
"Want me to save these patterns for future sessions?"
|
||||
```
|
||||
|
||||
If yes, write to `.interface-design/system.md`:
|
||||
- Direction and feel
|
||||
- Depth strategy (borders/shadows/layered)
|
||||
- Spacing base unit
|
||||
- Key component patterns
|
||||
|
||||
### What to Save
|
||||
|
||||
Add patterns when a component is used 2+ times, is reusable across the project, or has specific measurements worth remembering. Don't save one-off components, temporary experiments, or variations better handled with props.
|
||||
|
||||
### Consistency Checks
|
||||
|
||||
If system.md defines values, check against them: spacing on the defined grid, depth using the declared strategy throughout, colors from the defined palette, documented patterns reused instead of reinvented.
|
||||
|
||||
This compounds — each save makes future work faster and more consistent.
|
||||
|
||||
---
|
||||
|
||||
# Deep Dives
|
||||
|
||||
For more detail on specific topics:
|
||||
- `references/principles.md` — Code examples, specific values, dark mode
|
||||
- `references/validation.md` — Memory management, when to update system.md
|
||||
- `references/critique.md` — Post-build craft critique protocol
|
||||
|
||||
# Commands
|
||||
|
||||
- `/interface-design:status` — Current system state
|
||||
- `/interface-design:audit` — Check code against system
|
||||
- `/interface-design:extract` — Extract patterns from code
|
||||
- `/interface-design:critique` — Critique your build for craft, then rebuild what defaulted
|
||||
67
.agents/skills/interface-design/references/critique.md
Normal file
@@ -0,0 +1,67 @@
|
||||
# Critique
|
||||
|
||||
Your first build shipped the structure. Now look at it the way a design lead reviews a junior's work — not asking "does this work?" but "would I put my name on this?"
|
||||
|
||||
---
|
||||
|
||||
## The Gap
|
||||
|
||||
There's a distance between correct and crafted. Correct means the layout holds, the grid aligns, the colors don't clash. Crafted means someone cared about every decision down to the last pixel. You can feel the difference immediately — the way you tell a hand-thrown mug from an injection-molded one. Both hold coffee. One has presence.
|
||||
|
||||
Your first output lives in correct. This command pulls it toward crafted.
|
||||
|
||||
---
|
||||
|
||||
## See the Composition
|
||||
|
||||
Step back. Look at the whole thing.
|
||||
|
||||
Does the layout have rhythm? Great interfaces breathe unevenly — dense tooling areas give way to open content, heavy elements balance against light ones, the eye travels through the page with purpose. Default layouts are monotone: same card size, same gaps, same density everywhere. Flatness is the sound of no one deciding.
|
||||
|
||||
Are proportions doing work? A 280px sidebar next to full-width content says "navigation serves content." A 360px sidebar says "these are peers." The specific number declares what matters. If you can't articulate what your proportions are saying, they're not saying anything.
|
||||
|
||||
Is there a clear focal point? Every screen has one thing the user came here to do. That thing should dominate — through size, position, contrast, or the space around it. When everything competes equally, nothing wins and the interface feels like a parking lot.
|
||||
|
||||
---
|
||||
|
||||
## See the Craft
|
||||
|
||||
Move close. Pixel-close.
|
||||
|
||||
The spacing grid is non-negotiable — every value a multiple of 4, no exceptions — but correctness alone isn't craft. Craft is knowing that a tool panel at 16px padding feels workbench-tight while the same card at 24px feels like a brochure. The same number can be right in one context and lazy in another. Density is a design decision, not a constant.
|
||||
|
||||
Typography should be legible even squinted. If size is the only thing separating your headline from your body from your label, the hierarchy is too weak. Weight, tracking, and opacity create layers that size alone can't.
|
||||
|
||||
Surfaces should whisper hierarchy. Not thick borders, not dramatic shadows — quiet tonal shifts where you feel the depth without seeing it. Remove every border from your CSS mentally. Can you still perceive the structure through surface color alone? If not, your surfaces aren't working hard enough.
|
||||
|
||||
Interactive elements need life. Every button, link, and clickable region should respond to hover and press. Not dramatically — a subtle shift in background, a gentle darkening. Missing states make an interface feel like a photograph of software instead of software.
|
||||
|
||||
---
|
||||
|
||||
## See the Content
|
||||
|
||||
Read every visible string as a user would. Not checking for typos — checking for truth.
|
||||
|
||||
Does this screen tell one coherent story? Could a real person at a real company be looking at exactly this data right now? Or does the page title belong to one product, the article body to another, and the sidebar metrics to a third?
|
||||
|
||||
Content incoherence breaks the illusion faster than any visual flaw. A beautifully designed interface with nonsensical content is a movie set with no script.
|
||||
|
||||
---
|
||||
|
||||
## See the Structure
|
||||
|
||||
Open the CSS and find the lies — the places that look right but are held together with tape.
|
||||
|
||||
Negative margins undoing a parent's padding. Calc() values that exist only as workarounds. Absolute positioning to escape layout flow. Each is a shortcut where a clean solution exists. Cards with full-width dividers use flex column and section-level padding. Centered content uses max-width with auto margins. The correct answer is always simpler than the hack.
|
||||
|
||||
---
|
||||
|
||||
## Again
|
||||
|
||||
Look at your output one final time.
|
||||
|
||||
Ask: "If they said this lacks craft, what would they point to?"
|
||||
|
||||
That thing you just thought of — fix it. Then ask again.
|
||||
|
||||
The first build was the draft. The critique is the design.
|
||||
86
.agents/skills/interface-design/references/example.md
Normal file
@@ -0,0 +1,86 @@
|
||||
# Craft in Action
|
||||
|
||||
This shows how the subtle layering principle translates to real decisions. Learn the thinking, not the code. Your values will differ — the approach won't.
|
||||
|
||||
---
|
||||
|
||||
## The Subtle Layering Mindset
|
||||
|
||||
Before looking at any example, internalize this: **you should barely notice the system working.**
|
||||
|
||||
When you look at Vercel's dashboard, you don't think "nice borders." You just understand the structure. When you look at Supabase, you don't think "good surface elevation." You just know what's above what. The craft is invisible — that's how you know it's working.
|
||||
|
||||
---
|
||||
|
||||
## Example: Dashboard with Sidebar and Dropdown
|
||||
|
||||
### The Surface Decisions
|
||||
|
||||
**Why so subtle?** Each elevation jump should be only a few percentage points of lightness. You can barely see the difference in isolation. But when surfaces stack, the hierarchy emerges. This is the Vercel/Supabase way — whisper-quiet shifts that you feel rather than see.
|
||||
|
||||
**What NOT to do:** Don't make dramatic jumps between elevations. That's jarring. Don't use different hues for different levels. Keep the same hue, shift only lightness.
|
||||
|
||||
### The Border Decisions
|
||||
|
||||
**Why rgba, not solid colors?** Low opacity borders blend with their background. A low-opacity white border on a dark surface is barely there — it defines the edge without demanding attention. Solid hex borders look harsh in comparison.
|
||||
|
||||
**The test:** Look at your interface from arm's length. If borders are the first thing you notice, reduce opacity. If you can't find where regions end, increase slightly.
|
||||
|
||||
### The Sidebar Decision
|
||||
|
||||
**Why same background as canvas, not different?**
|
||||
|
||||
Many dashboards make the sidebar a different color. This fragments the visual space — now you have "sidebar world" and "content world."
|
||||
|
||||
Better: Same background, subtle border separation. The sidebar is part of the app, not a separate region. Vercel does this. Supabase does this. The border is enough.
|
||||
|
||||
### The Dropdown Decision
|
||||
|
||||
**Why surface-200, not surface-100?**
|
||||
|
||||
The dropdown floats above the card it emerged from. If both were surface-100, the dropdown would blend into the card — you'd lose the sense of layering. Surface-200 is just light enough to feel "above" without being dramatically different.
|
||||
|
||||
**Why border-overlay instead of border-default?**
|
||||
|
||||
Overlays (dropdowns, popovers) often need slightly more definition because they're floating in space. A touch more border opacity helps them feel contained without being harsh.
|
||||
|
||||
---
|
||||
|
||||
## Example: Form Controls
|
||||
|
||||
### Input Background Decision
|
||||
|
||||
**Why darker, not lighter?**
|
||||
|
||||
Inputs are "inset" — they receive content, they don't project it. A slightly darker background signals "type here" without needing heavy borders. This is the alternative-background principle.
|
||||
|
||||
### Focus State Decision
|
||||
|
||||
**Why subtle focus states?**
|
||||
|
||||
Focus needs to be visible, but you don't need a glowing ring or dramatic color. A noticeable increase in border opacity is enough for a clear state change. Subtle-but-noticeable — the same principle as surfaces.
|
||||
|
||||
---
|
||||
|
||||
## Adapt to Context
|
||||
|
||||
Your product might need:
|
||||
- Warmer hues (slight yellow/orange tint)
|
||||
- Cooler hues (blue-gray base)
|
||||
- Different lightness progression
|
||||
- Light mode (principles invert — higher elevation = shadow, not lightness)
|
||||
|
||||
**The principle is constant:** barely different, still distinguishable. The values adapt to context.
|
||||
|
||||
---
|
||||
|
||||
## The Craft Check
|
||||
|
||||
Apply the squint test to your work:
|
||||
|
||||
1. Blur your eyes or step back
|
||||
2. Can you still perceive hierarchy?
|
||||
3. Is anything jumping out at you?
|
||||
4. Can you tell where regions begin and end?
|
||||
|
||||
If hierarchy is visible and nothing is harsh — the subtle layering is working.
|
||||
235
.agents/skills/interface-design/references/principles.md
Normal file
@@ -0,0 +1,235 @@
|
||||
# Core Craft Principles
|
||||
|
||||
These apply regardless of design direction. This is the quality floor.
|
||||
|
||||
---
|
||||
|
||||
## Surface & Token Architecture
|
||||
|
||||
Professional interfaces don't pick colors randomly — they build systems. Understanding this architecture is the difference between "looks okay" and "feels like a real product."
|
||||
|
||||
### The Primitive Foundation
|
||||
|
||||
Every color in your interface should trace back to a small set of primitives:
|
||||
|
||||
- **Foreground** — text colors (primary, secondary, muted)
|
||||
- **Background** — surface colors (base, elevated, overlay)
|
||||
- **Border** — edge colors (default, subtle, strong)
|
||||
- **Brand** — your primary accent
|
||||
- **Semantic** — functional colors (destructive, warning, success)
|
||||
|
||||
Don't invent new colors. Map everything to these primitives.
|
||||
|
||||
### Surface Elevation Hierarchy
|
||||
|
||||
Surfaces stack. A dropdown sits above a card which sits above the page. Build a numbered system:
|
||||
|
||||
```
|
||||
Level 0: Base background (the app canvas)
|
||||
Level 1: Cards, panels (same visual plane as base)
|
||||
Level 2: Dropdowns, popovers (floating above)
|
||||
Level 3: Nested dropdowns, stacked overlays
|
||||
Level 4: Highest elevation (rare)
|
||||
```
|
||||
|
||||
In dark mode, higher elevation = slightly lighter. In light mode, higher elevation = slightly lighter or uses shadow. The principle: **elevated surfaces need visual distinction from what's beneath them.**
|
||||
|
||||
### The Subtlety Principle
|
||||
|
||||
This is where most interfaces fail. Study Vercel, Supabase, Linear — their surfaces are **barely different** but still distinguishable. Their borders are **light but not invisible**.
|
||||
|
||||
**For surfaces:** The difference between elevation levels should be subtle — a few percentage points of lightness, not dramatic jumps. In dark mode, surface-100 might be 7% lighter than base, surface-200 might be 9%, surface-300 might be 12%. You can barely see it, but you feel it.
|
||||
|
||||
**For borders:** Borders should define regions without demanding attention. Use low opacity (0.05-0.12 alpha for dark mode, slightly higher for light). The border should disappear when you're not looking for it, but be findable when you need to understand the structure.
|
||||
|
||||
**The test:** Squint at your interface. You should still perceive the hierarchy — what's above what, where regions begin and end. But no single border or surface should jump out at you. If borders are the first thing you notice, they're too strong. If you can't find where one region ends and another begins, they're too subtle.
|
||||
|
||||
**Common AI mistakes to avoid:**
|
||||
- Borders that are too visible (1px solid gray instead of subtle rgba)
|
||||
- Surface jumps that are too dramatic (going from dark to light instead of dark to slightly-less-dark)
|
||||
- Using different hues for different surfaces (gray card on blue background)
|
||||
- Harsh dividers where subtle borders would do
|
||||
|
||||
### Text Hierarchy via Tokens
|
||||
|
||||
Don't just have "text" and "gray text." Build four levels:
|
||||
|
||||
- **Primary** — default text, highest contrast
|
||||
- **Secondary** — supporting text, slightly muted
|
||||
- **Tertiary** — metadata, timestamps, less important
|
||||
- **Muted** — disabled, placeholder, lowest contrast
|
||||
|
||||
Use all four consistently. If you're only using two, your hierarchy is too flat.
|
||||
|
||||
### Border Progression
|
||||
|
||||
Borders aren't binary. Build a scale:
|
||||
|
||||
- **Default** — standard borders
|
||||
- **Subtle/Muted** — softer separation
|
||||
- **Strong** — emphasis, hover states
|
||||
- **Stronger** — maximum emphasis, focus rings
|
||||
|
||||
Match border intensity to the importance of the boundary.
|
||||
|
||||
### Dedicated Control Tokens
|
||||
|
||||
Form controls (inputs, checkboxes, selects) have specific needs. Don't just reuse surface tokens — create dedicated ones:
|
||||
|
||||
- **Control background** — often different from surface backgrounds
|
||||
- **Control border** — needs to feel interactive
|
||||
- **Control focus** — clear focus indication
|
||||
|
||||
This separation lets you tune controls independently from layout surfaces.
|
||||
|
||||
### Context-Aware Bases
|
||||
|
||||
Different areas of your app might need different base surfaces:
|
||||
|
||||
- **Marketing pages** — might use darker/richer backgrounds
|
||||
- **Dashboard/app** — might use neutral working backgrounds
|
||||
- **Sidebar** — might differ from main canvas
|
||||
|
||||
The surface hierarchy works the same way — it just starts from a different base.
|
||||
|
||||
### Alternative Backgrounds for Depth
|
||||
|
||||
Beyond shadows, use contrasting backgrounds to create depth. An "alternative" or "inset" background makes content feel recessed. Useful for:
|
||||
|
||||
- Empty states in data grids
|
||||
- Code blocks
|
||||
- Inset panels
|
||||
- Visual grouping without borders
|
||||
|
||||
---
|
||||
|
||||
## Spacing System
|
||||
|
||||
Pick a base unit (4px and 8px are common) and use multiples throughout. The specific number matters less than consistency — every spacing value should be explainable as "X times the base unit."
|
||||
|
||||
Build a scale for different contexts:
|
||||
- Micro spacing (icon gaps, tight element pairs)
|
||||
- Component spacing (within buttons, inputs, cards)
|
||||
- Section spacing (between related groups)
|
||||
- Major separation (between distinct sections)
|
||||
|
||||
## Symmetrical Padding
|
||||
|
||||
TLBR must match. If top padding is 16px, left/bottom/right must also be 16px. Exception: when content naturally creates visual balance.
|
||||
|
||||
```css
|
||||
/* Good */
|
||||
padding: 16px;
|
||||
padding: 12px 16px; /* Only when horizontal needs more room */
|
||||
|
||||
/* Bad */
|
||||
padding: 24px 16px 12px 16px;
|
||||
```
|
||||
|
||||
## Border Radius Consistency
|
||||
|
||||
Sharper corners feel technical, rounder corners feel friendly. Pick a scale that fits your product's personality and use it consistently.
|
||||
|
||||
The key is having a system: small radius for inputs and buttons, medium for cards, large for modals or containers. Don't mix sharp and soft randomly — inconsistent radius is as jarring as inconsistent spacing.
|
||||
|
||||
## Depth & Elevation Strategy
|
||||
|
||||
Match your depth approach to your design direction. Choose ONE and commit:
|
||||
|
||||
**Borders-only (flat)** — Clean, technical, dense. Works for utility-focused tools where information density matters more than visual lift. Linear, Raycast, and many developer tools use almost no shadows — just subtle borders to define regions.
|
||||
|
||||
**Subtle single shadows** — Soft lift without complexity. A simple `0 1px 3px rgba(0,0,0,0.08)` can be enough. Works for approachable products that want gentle depth.
|
||||
|
||||
**Layered shadows** — Rich, premium, dimensional. Multiple shadow layers create realistic depth. Stripe and Mercury use this approach. Best for cards that need to feel like physical objects.
|
||||
|
||||
**Surface color shifts** — Background tints establish hierarchy without any shadows. A card at `#fff` on a `#f8fafc` background already feels elevated.
|
||||
|
||||
```css
|
||||
/* Borders-only approach */
|
||||
--border: rgba(0, 0, 0, 0.08);
|
||||
--border-subtle: rgba(0, 0, 0, 0.05);
|
||||
border: 0.5px solid var(--border);
|
||||
|
||||
/* Single shadow approach */
|
||||
--shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
|
||||
|
||||
/* Layered shadow approach */
|
||||
--shadow-layered:
|
||||
0 0 0 0.5px rgba(0, 0, 0, 0.05),
|
||||
0 1px 2px rgba(0, 0, 0, 0.04),
|
||||
0 2px 4px rgba(0, 0, 0, 0.03),
|
||||
0 4px 8px rgba(0, 0, 0, 0.02);
|
||||
```
|
||||
|
||||
## Card Layouts
|
||||
|
||||
Monotonous card layouts are lazy design. A metric card doesn't have to look like a plan card doesn't have to look like a settings card.
|
||||
|
||||
Design each card's internal structure for its specific content — but keep the surface treatment consistent: same border weight, shadow depth, corner radius, padding scale, typography.
|
||||
|
||||
## Isolated Controls
|
||||
|
||||
UI controls deserve container treatment. Date pickers, filters, dropdowns — these should feel like crafted objects.
|
||||
|
||||
**Never use native form elements for styled UI.** Native `<select>`, `<input type="date">`, and similar elements render OS-native dropdowns that cannot be styled. Build custom components instead:
|
||||
|
||||
- Custom select: trigger button + positioned dropdown menu
|
||||
- Custom date picker: input + calendar popover
|
||||
- Custom checkbox/radio: styled div with state management
|
||||
|
||||
Custom select triggers must use `display: inline-flex` with `white-space: nowrap` to keep text and chevron icons on the same row.
|
||||
|
||||
## Typography Hierarchy
|
||||
|
||||
Build distinct levels that are visually distinguishable at a glance:
|
||||
|
||||
- **Headlines** — heavier weight, tighter letter-spacing for presence
|
||||
- **Body** — comfortable weight for readability
|
||||
- **Labels/UI** — medium weight, works at smaller sizes
|
||||
- **Data** — often monospace, needs `tabular-nums` for alignment
|
||||
|
||||
Don't rely on size alone. Combine size, weight, and letter-spacing to create clear hierarchy. If you squint and can't tell headline from body, the hierarchy is too weak.
|
||||
|
||||
## Monospace for Data
|
||||
|
||||
Numbers, IDs, codes, timestamps belong in monospace. Use `tabular-nums` for columnar alignment. Mono signals "this is data."
|
||||
|
||||
## Iconography
|
||||
|
||||
Icons clarify, not decorate — if removing an icon loses no meaning, remove it. Choose a consistent icon set and stick with it throughout the product.
|
||||
|
||||
Give standalone icons presence with subtle background containers. Icons next to text should align optically, not mathematically.
|
||||
|
||||
## Animation
|
||||
|
||||
Keep it fast and functional. Micro-interactions (hover, focus) should feel instant — around 150ms. Larger transitions (modals, panels) can be slightly longer — 200-250ms.
|
||||
|
||||
Use smooth deceleration easing (ease-out variants). Avoid spring/bounce effects in professional interfaces — they feel playful, not serious.
|
||||
|
||||
## Contrast Hierarchy
|
||||
|
||||
Build a four-level system: foreground (primary) → secondary → muted → faint. Use all four consistently.
|
||||
|
||||
## Color Carries Meaning
|
||||
|
||||
Gray builds structure. Color communicates — status, action, emphasis, identity. Unmotivated color is noise. Color that reinforces the product's world is character.
|
||||
|
||||
## Navigation Context
|
||||
|
||||
Screens need grounding. A data table floating in space feels like a component demo, not a product. Consider including:
|
||||
|
||||
- **Navigation** — sidebar or top nav showing where you are in the app
|
||||
- **Location indicator** — breadcrumbs, page title, or active nav state
|
||||
- **User context** — who's logged in, what workspace/org
|
||||
|
||||
When building sidebars, consider using the same background as the main content area. Rely on a subtle border for separation rather than different background colors.
|
||||
|
||||
## Dark Mode
|
||||
|
||||
Dark interfaces have different needs:
|
||||
|
||||
**Borders over shadows** — Shadows are less visible on dark backgrounds. Lean more on borders for definition.
|
||||
|
||||
**Adjust semantic colors** — Status colors (success, warning, error) often need to be slightly desaturated for dark backgrounds.
|
||||
|
||||
**Same structure, different values** — The hierarchy system still applies, just with inverted values.
|
||||
48
.agents/skills/interface-design/references/validation.md
Normal file
@@ -0,0 +1,48 @@
|
||||
# Memory Management
|
||||
|
||||
When and how to update `.interface-design/system.md`.
|
||||
|
||||
## When to Add Patterns
|
||||
|
||||
Add to system.md when:
|
||||
- Component used 2+ times
|
||||
- Pattern is reusable across the project
|
||||
- Has specific measurements worth remembering
|
||||
|
||||
## Pattern Format
|
||||
|
||||
```markdown
|
||||
### Button Primary
|
||||
- Height: 36px
|
||||
- Padding: 12px 16px
|
||||
- Radius: 6px
|
||||
- Font: 14px, 500 weight
|
||||
```
|
||||
|
||||
## Don't Document
|
||||
|
||||
- One-off components
|
||||
- Temporary experiments
|
||||
- Variations better handled with props
|
||||
|
||||
## Pattern Reuse
|
||||
|
||||
Before creating a component, check system.md:
|
||||
- Pattern exists? Use it.
|
||||
- Need variation? Extend, don't create new.
|
||||
|
||||
Memory compounds: each pattern saved makes future work faster and more consistent.
|
||||
|
||||
---
|
||||
|
||||
# Validation Checks
|
||||
|
||||
If system.md defines specific values, check consistency:
|
||||
|
||||
**Spacing** — All values multiples of the defined base?
|
||||
|
||||
**Depth** — Using the declared strategy throughout? (borders-only means no shadows)
|
||||
|
||||
**Colors** — Using defined palette, not random hex codes?
|
||||
|
||||
**Patterns** — Reusing documented patterns instead of creating new?
|
||||
58
AGENTS.md
@@ -193,3 +193,61 @@ await getAvailability('my-club', { date: '2026-04-20' });
|
||||
1. Create `lib/api/resources/[resource].ts`
|
||||
2. Export functions using `http` from `../http`
|
||||
3. Add exports in `lib/api/index.ts`
|
||||
|
||||
## Email Templates
|
||||
|
||||
Todos los emails deben usar la misma estética. El layout compartido está en `apps/backend/src/emails/booking-confirmation.ts`.
|
||||
|
||||
### Layout (`wrapLayout`)
|
||||
|
||||
Exportado como `wrapLayout(content)`. Proporciona:
|
||||
- Fondo: `#edf7f4`
|
||||
- Card blanca: `max-width: 520px`, `border-radius: 28px`, `box-shadow: 0 24px 70px rgba(15,23,42,0.12)`, `border: 1px solid rgba(5,9,20,0.1)`
|
||||
- Playzer favicon: `{APP_BASE_URL}/playzer-favicon-512-transparent.png` (está en `apps/frontend/public/`)
|
||||
- **Sin `min-height: 100vh`**: la card empieza arriba, no centrada verticalmente
|
||||
|
||||
```typescript
|
||||
import { wrapLayout } from '@/emails/booking-confirmation';
|
||||
|
||||
const html = wrapLayout(`<tr>...contenido...</tr>`);
|
||||
```
|
||||
|
||||
### Estructura de cada email
|
||||
|
||||
| Sección | Descripción |
|
||||
|---------|-------------|
|
||||
| **Header** | Dos columnas: badge pill a la izquierda + Playzer (favicon + texto) a la derecha. El badge usa `border-radius: 999px`, `padding: 4px 12px`, `font-size: 11px`, `font-weight: 700`, `letter-spacing: 0.14em`, `text-transform: uppercase`. |
|
||||
| **Card fecha/hora** | Fondo `#f0fdf4`, borde `1px solid rgba(5,150,105,0.3)`, `border-radius: 24px`. Siempre verde aunque el email sea de cancelación. |
|
||||
| **Grilla detalles** | `border: 1px solid #e5e7eb`, `border-radius: 22px`, dos celdas de 50% con `border-right` en la primera. |
|
||||
| **Botón CTA** | Tabla con fondo `#059669`, `border-radius: 12px`, link blanco con `padding: 14px 32px`. |
|
||||
| **Pie** | Sin pie de marca. Solo texto secundario opcional centrado si es necesario. |
|
||||
| **Sin botones de acción** | Los emails de booking **no** incluyen los botones "Compartir por WhatsApp" ni "Hacer otra reserva". |
|
||||
|
||||
### Padding estándar
|
||||
|
||||
| Ubicación | Valor |
|
||||
|-----------|-------|
|
||||
| Wrapper (outer `<td>`) | `padding: 24px 12px` |
|
||||
| Primer `<td>` del contenido (header) | `padding: 24px 20px 16px` |
|
||||
| `<td>` intermedios (cards, texto) | `padding: 0 20px 16px` |
|
||||
| Último `<td>` del contenido | `padding: 0 20px 24px` |
|
||||
|
||||
### Colores de badges según estado
|
||||
|
||||
| Estado | Fondo badge | Texto badge |
|
||||
|--------|-------------|-------------|
|
||||
| Confirmado | `#f0fdf4` | `#15803d` |
|
||||
| Cancelado | `#fef2f2` | `#dc2626` |
|
||||
| No concretado | `#fffbeb` | `#d97706` |
|
||||
| Neutro (verificación, etc.) | `#f4f4f5` | `#71717a` |
|
||||
|
||||
### Archivos de templates
|
||||
|
||||
| Archivo | Templates |
|
||||
|---------|-----------|
|
||||
| `apps/backend/src/emails/booking-confirmation.ts` | `bookingConfirmationHtml`, `bookingCancelledHtml`, `bookingNoShowHtml` + exporta `wrapLayout` |
|
||||
| `apps/backend/src/lib/auth.ts` | Email de verificación de Better Auth (usa `wrapLayout` inline) |
|
||||
|
||||
### Regla general
|
||||
|
||||
Para emails nuevos: importar `wrapLayout`, construir el HTML interno con `<tr>`s, usar la misma estructura de cabecera (badge + Playzer), y nunca incluir el pie "Playzer — Reserva de canchas online". Usar `APP_BASE_URL` para construir URLs absolutas al logo.
|
||||
|
||||
18
Dockerfile
@@ -32,25 +32,19 @@ COPY packages/api-contract/package.json packages/api-contract/
|
||||
RUN bun install
|
||||
|
||||
# =============================================================================
|
||||
# Stage 4: Prisma Generate
|
||||
# Stage 4: Build Backend (prisma generate + tsc)
|
||||
# =============================================================================
|
||||
FROM deps-backend AS prisma
|
||||
FROM deps-backend AS build-backend
|
||||
WORKDIR /app
|
||||
ARG DATABASE_URL
|
||||
ENV DATABASE_URL=${DATABASE_URL}
|
||||
ENV DATABASE_URL=${DATABASE_URL:-postgresql://dummy:dummy@localhost:5432/dummy}
|
||||
COPY apps/backend ./apps/backend
|
||||
RUN bun --cwd apps/backend prisma:generate
|
||||
|
||||
# =============================================================================
|
||||
# Stage 5: Build Backend
|
||||
# =============================================================================
|
||||
FROM prisma AS build-backend
|
||||
WORKDIR /app
|
||||
COPY packages ./packages
|
||||
RUN bun --cwd apps/backend prisma:generate
|
||||
RUN bun --cwd apps/backend build
|
||||
|
||||
# =============================================================================
|
||||
# Stage 6: Runner - Production image
|
||||
# Stage 5: Runner - Production image
|
||||
# =============================================================================
|
||||
FROM oven/bun:1.3.11 AS runner
|
||||
WORKDIR /app
|
||||
@@ -60,7 +54,7 @@ COPY --from=build-backend /app/node_modules ./node_modules
|
||||
COPY --from=build-frontend /app/apps/frontend/dist ./apps/backend/public
|
||||
COPY --from=build-backend /app/apps/backend ./apps/backend
|
||||
COPY --from=build-backend /app/packages ./packages
|
||||
COPY package.json ./
|
||||
COPY package.json bun.lock ./
|
||||
COPY entrypoint.sh /app/entrypoint.sh
|
||||
|
||||
RUN chmod +x /app/entrypoint.sh
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
[test]
|
||||
preload = ["./test/support/prisma.mock.ts"]
|
||||
coverageThreshold = 0.8
|
||||
@@ -4,7 +4,7 @@
|
||||
"dev": "bun run --hot src/server.ts",
|
||||
"start": "bun src/server.ts",
|
||||
"build": "tsc -b",
|
||||
"test": "bun test",
|
||||
"test": "bun test --preload ./test/support/prisma.mock.ts ./test",
|
||||
"lint": "biome check .",
|
||||
"lint:fix": "biome check --write .",
|
||||
"format": "biome format --write .",
|
||||
|
||||
@@ -4,6 +4,7 @@ model User {
|
||||
email String
|
||||
emailVerified Boolean @default(false)
|
||||
image String?
|
||||
phone String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
sessions Session[]
|
||||
|
||||
@@ -12,6 +12,7 @@ enum CourtBookingStatus {
|
||||
CONFIRMED
|
||||
CANCELLED
|
||||
COMPLETED
|
||||
NOSHOW
|
||||
}
|
||||
|
||||
model Sport {
|
||||
@@ -84,6 +85,7 @@ model CourtBooking {
|
||||
endTime String @map("end_time") @db.VarChar(5)
|
||||
customerName String @map("customer_name") @db.VarChar(120)
|
||||
customerPhone String @map("customer_phone") @db.VarChar(30)
|
||||
customerEmail String? @map("customer_email") @db.VarChar(254)
|
||||
status CourtBookingStatus @default(CONFIRMED)
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
@@ -94,3 +96,21 @@ model CourtBooking {
|
||||
@@index([bookingDate])
|
||||
@@map("court_bookings")
|
||||
}
|
||||
|
||||
model CourtBookingLog {
|
||||
id String @id @db.Uuid
|
||||
bookingCode String @map("booking_code") @db.VarChar(8)
|
||||
courtId String @map("court_id") @db.Uuid
|
||||
bookingDate DateTime @map("booking_date") @db.Date
|
||||
startTime String @map("start_time") @db.VarChar(5)
|
||||
endTime String @map("end_time") @db.VarChar(5)
|
||||
previousStatus CourtBookingStatus @map("previous_status")
|
||||
newStatus CourtBookingStatus @map("new_status")
|
||||
customerName String @map("customer_name") @db.VarChar(120)
|
||||
customerPhone String @map("customer_phone") @db.VarChar(30)
|
||||
customerEmail String? @map("customer_email") @db.VarChar(254)
|
||||
changedAt DateTime @default(now()) @map("changed_at")
|
||||
|
||||
@@map("court_booking_logs")
|
||||
@@index([courtId, newStatus])
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "court_booking_logs" (
|
||||
"id" UUID NOT NULL,
|
||||
"booking_code" UUID NOT NULL,
|
||||
"court_id" UUID NOT NULL,
|
||||
"booking_date" DATE NOT NULL,
|
||||
"start_time" VARCHAR(5) NOT NULL,
|
||||
"end_time" VARCHAR(5) NOT NULL,
|
||||
"previous_status" "CourtBookingStatus" NOT NULL,
|
||||
"new_status" "CourtBookingStatus" NOT NULL,
|
||||
"changed_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "court_booking_logs_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "court_booking_logs_court_id_new_status_idx" ON "court_booking_logs"("court_id", "new_status");
|
||||
@@ -0,0 +1,13 @@
|
||||
/*
|
||||
Warnings:
|
||||
|
||||
- Added the required column `customer_name` to the `court_booking_logs` table without a default value. This is not possible if the table is not empty.
|
||||
- Added the required column `customer_phone` to the `court_booking_logs` table without a default value. This is not possible if the table is not empty.
|
||||
|
||||
*/
|
||||
-- AlterEnum
|
||||
ALTER TYPE "CourtBookingStatus" ADD VALUE 'NOSHOW';
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "court_booking_logs" ADD COLUMN "customer_name" VARCHAR(120) NOT NULL,
|
||||
ADD COLUMN "customer_phone" VARCHAR(30) NOT NULL;
|
||||
@@ -0,0 +1,9 @@
|
||||
/*
|
||||
Warnings:
|
||||
|
||||
- Changed the type of `booking_code` on the `court_booking_logs` table. No cast exists, the column would be dropped and recreated, which cannot be done if there is data, since the column is required.
|
||||
|
||||
*/
|
||||
-- AlterTable
|
||||
ALTER TABLE "court_booking_logs" DROP COLUMN "booking_code",
|
||||
ADD COLUMN "booking_code" VARCHAR(8) NOT NULL;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "users" ADD COLUMN "phone" TEXT;
|
||||
@@ -0,0 +1,14 @@
|
||||
/*
|
||||
Warnings:
|
||||
|
||||
- You are about to drop the `onboarding_requests` table. If the table is not empty, all the data it contains will be lost.
|
||||
|
||||
*/
|
||||
-- AlterTable
|
||||
ALTER TABLE "court_booking_logs" ADD COLUMN "customer_email" VARCHAR(254);
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "court_bookings" ADD COLUMN "customer_email" VARCHAR(254);
|
||||
|
||||
-- DropTable
|
||||
DROP TABLE "onboarding_requests";
|
||||
@@ -1,18 +0,0 @@
|
||||
model OnboardingRequest {
|
||||
id String @id @db.Uuid
|
||||
fullName String @map("full_name")
|
||||
email String
|
||||
otpHash String @map("otp_hash")
|
||||
otpExpiresAt DateTime @map("otp_expires_at")
|
||||
otpAttempts Int @default(0) @map("otp_attempts")
|
||||
otpLastSentAt DateTime @map("otp_last_sent_at")
|
||||
otpResendCount Int @default(0) @map("otp_resend_count")
|
||||
emailVerifiedAt DateTime? @map("email_verified_at")
|
||||
completedAt DateTime? @map("completed_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
@@index([email])
|
||||
@@index([otpExpiresAt])
|
||||
@@map("onboarding_requests")
|
||||
}
|
||||
@@ -3,10 +3,15 @@ import type { AppEnv } from '@/types/hono';
|
||||
import { Hono } from 'hono';
|
||||
import { cors } from 'hono/cors';
|
||||
import { requestId } from 'hono/request-id';
|
||||
import { errorHandler } from './lib/http/error-handler';
|
||||
import { requestIdMiddleware } from './lib/http/request-id';
|
||||
|
||||
export function createApp() {
|
||||
const app = new Hono<AppEnv>();
|
||||
|
||||
app.use('*', requestIdMiddleware);
|
||||
app.use('*', errorHandler);
|
||||
|
||||
const allowedOrigins = (Bun.env.CORS_ORIGIN ?? 'http://localhost:5173,http://127.0.0.1:5173')
|
||||
.split(',')
|
||||
.map((value) => value.trim())
|
||||
|
||||
385
apps/backend/src/emails/booking-confirmation.ts
Normal file
@@ -0,0 +1,385 @@
|
||||
type BookingEmailData = {
|
||||
bookingCode: string;
|
||||
complexName: string;
|
||||
date: string;
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
courtName: string;
|
||||
sportName: string;
|
||||
customerName: string;
|
||||
price?: number;
|
||||
};
|
||||
|
||||
const APP_BASE_URL = process.env.APP_BASE_URL ?? 'http://localhost:5173';
|
||||
|
||||
function formatBookingPrice(price: number): string {
|
||||
if (price === 0) {
|
||||
return 'Sin cargo';
|
||||
}
|
||||
|
||||
return new Intl.NumberFormat('es-AR', {
|
||||
style: 'currency',
|
||||
currency: 'ARS',
|
||||
maximumFractionDigits: Number.isInteger(price) ? 0 : 2,
|
||||
}).format(price);
|
||||
}
|
||||
|
||||
function formatFriendlyDate(isoDate: string): string {
|
||||
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(isoDate);
|
||||
if (!match) return isoDate;
|
||||
|
||||
const date = new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3]));
|
||||
|
||||
const weekday = new Intl.DateTimeFormat('es-AR', { weekday: 'long' }).format(date);
|
||||
const day = date.getDate();
|
||||
const month = new Intl.DateTimeFormat('es-AR', { month: 'long' }).format(date);
|
||||
|
||||
return `${weekday.charAt(0).toUpperCase() + weekday.slice(1)}, ${day} de ${month}`;
|
||||
}
|
||||
|
||||
const BASE_STYLES = `
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background-color: #edf7f4;
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
||||
}
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
`;
|
||||
|
||||
export function wrapLayout(content: string) {
|
||||
return `<!DOCTYPE html>
|
||||
<html lang="es">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Playzer</title>
|
||||
<style>${BASE_STYLES}</style>
|
||||
</head>
|
||||
<body style="margin:0;padding:0;background-color:#edf7f4;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Helvetica Neue',Arial,sans-serif;">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background-color:#edf7f4;">
|
||||
<tr>
|
||||
<td align="center" style="padding:24px 12px;">
|
||||
<table role="presentation" width="100%" style="max-width:520px;background-color:#ffffff;border-radius:28px;overflow:hidden;box-shadow:0 24px 70px rgba(15,23,42,0.12);border:1px solid rgba(5,9,20,0.1);">
|
||||
${content}
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
|
||||
export function bookingConfirmationHtml(data: BookingEmailData): string {
|
||||
const formattedPrice = formatBookingPrice(data.price ?? 0);
|
||||
const friendlyDate = formatFriendlyDate(data.date);
|
||||
|
||||
const content = `
|
||||
<tr>
|
||||
<td style="padding:24px 20px 16px;">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0">
|
||||
<tr>
|
||||
<td valign="top">
|
||||
<table role="presentation" cellpadding="0" cellspacing="0" style="display:inline-block;background-color:#f0fdf4;border-radius:999px;padding:4px 12px;">
|
||||
<tr>
|
||||
<td style="font-size:11px;font-weight:700;letter-spacing:0.14em;color:#15803d;text-transform:uppercase;line-height:1.25rem;">
|
||||
✓ Reserva confirmada
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
<h1 style="margin:12px 0 0;font-size:28px;font-weight:700;color:#111827;letter-spacing:-0.025em;">
|
||||
${data.complexName}
|
||||
</h1>
|
||||
</td>
|
||||
<td valign="top" align="right" style="white-space:nowrap;">
|
||||
<table role="presentation" cellpadding="0" cellspacing="0">
|
||||
<tr>
|
||||
<td valign="middle" style="padding-right:8px;">
|
||||
<img src="${APP_BASE_URL}/playzer-favicon-512-transparent.png" alt="Playzer" width="32" height="32" style="display:block;" />
|
||||
</td>
|
||||
<td valign="middle">
|
||||
<span style="font-size:18px;font-weight:700;color:#475569;letter-spacing:-0.025em;">Playzer</span>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="padding:0 20px 16px;">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background-color:#f0fdf4;border-radius:24px;border:1px solid rgba(5,150,105,0.3);">
|
||||
<tr>
|
||||
<td style="padding:20px 24px;">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0">
|
||||
<tr>
|
||||
<td valign="bottom">
|
||||
<p style="margin:0;font-size:13px;font-weight:600;color:#15803d;">
|
||||
Tu turno
|
||||
</p>
|
||||
<p style="margin:12px 0 0;font-size:28px;font-weight:900;color:#111827;line-height:1.1;letter-spacing:-0.025em;">
|
||||
${friendlyDate}
|
||||
</p>
|
||||
<p style="margin:8px 0 0;font-size:24px;font-weight:900;color:#059669;line-height:1;letter-spacing:-0.025em;">
|
||||
${data.startTime} — ${data.endTime}
|
||||
</p>
|
||||
</td>
|
||||
<td valign="bottom" align="right" style="padding-left:16px;">
|
||||
<table role="presentation" cellpadding="0" cellspacing="0" style="background-color:rgba(255,255,255,0.8);border-radius:16px;border:1px solid rgba(5,150,105,0.2);">
|
||||
<tr>
|
||||
<td style="padding:12px 16px;text-align:right;min-width:120px;">
|
||||
<p style="margin:0;font-size:11px;font-weight:500;color:#6b7280;">Precio del turno</p>
|
||||
<p style="margin:4px 0 0;font-size:20px;font-weight:700;color:#111827;">${formattedPrice}</p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="padding:0 20px 16px;">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="border:1px solid #e5e7eb;border-radius:22px;overflow:hidden;">
|
||||
<tr>
|
||||
<td width="50%" style="padding:16px;border-right:1px solid #e5e7eb;background-color:#ffffff;">
|
||||
<p style="margin:0;font-size:13px;font-weight:500;color:#6b7280;">
|
||||
Cancha
|
||||
</p>
|
||||
<p style="margin:8px 0 0;font-size:14px;font-weight:600;color:#111827;">
|
||||
${data.courtName} — ${data.sportName}
|
||||
</p>
|
||||
</td>
|
||||
<td width="50%" style="padding:16px;background-color:#ffffff;">
|
||||
<p style="margin:0;font-size:13px;font-weight:500;color:#6b7280;">
|
||||
Código de reserva
|
||||
</p>
|
||||
<p style="margin:8px 0 0;font-family:monospace;font-size:16px;font-weight:700;letter-spacing:0.18em;color:#111827;">
|
||||
${data.bookingCode}
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="padding:0 20px 24px;">
|
||||
<p style="margin:0;font-size:13px;color:#6b7280;text-align:center;line-height:1.5;">
|
||||
Presentá el código de reserva al llegar al complejo.
|
||||
<br />
|
||||
Si necesitás cancelar o modificar, contactate directamente con el complejo.
|
||||
</p>
|
||||
</td>
|
||||
</tr>`;
|
||||
|
||||
return wrapLayout(content);
|
||||
}
|
||||
|
||||
export function bookingCancelledHtml(data: BookingEmailData): string {
|
||||
const friendlyDate = formatFriendlyDate(data.date);
|
||||
|
||||
const content = `
|
||||
<tr>
|
||||
<td style="padding:24px 20px 16px;">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0">
|
||||
<tr>
|
||||
<td valign="top">
|
||||
<table role="presentation" cellpadding="0" cellspacing="0" style="display:inline-block;background-color:#fef2f2;border-radius:999px;padding:4px 12px;">
|
||||
<tr>
|
||||
<td style="font-size:11px;font-weight:700;letter-spacing:0.14em;color:#dc2626;text-transform:uppercase;line-height:1.25rem;">
|
||||
✗ Reserva cancelada
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
<h1 style="margin:12px 0 0;font-size:28px;font-weight:700;color:#111827;letter-spacing:-0.025em;">
|
||||
${data.complexName}
|
||||
</h1>
|
||||
</td>
|
||||
<td valign="top" align="right" style="white-space:nowrap;">
|
||||
<table role="presentation" cellpadding="0" cellspacing="0">
|
||||
<tr>
|
||||
<td valign="middle" style="padding-right:8px;">
|
||||
<img src="${APP_BASE_URL}/playzer-favicon-512-transparent.png" alt="Playzer" width="32" height="32" style="display:block;" />
|
||||
</td>
|
||||
<td valign="middle">
|
||||
<span style="font-size:18px;font-weight:700;color:#475569;letter-spacing:-0.025em;">Playzer</span>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="padding:0 20px 16px;">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background-color:#f0fdf4;border-radius:24px;border:1px solid rgba(5,150,105,0.3);">
|
||||
<tr>
|
||||
<td style="padding:20px 24px;">
|
||||
<p style="margin:0;font-size:13px;font-weight:600;color:#15803d;">
|
||||
Tu turno
|
||||
</p>
|
||||
<p style="margin:12px 0 0;font-size:28px;font-weight:900;color:#111827;line-height:1.1;letter-spacing:-0.025em;">
|
||||
${friendlyDate}
|
||||
</p>
|
||||
<p style="margin:8px 0 0;font-size:24px;font-weight:900;color:#059669;line-height:1;letter-spacing:-0.025em;">
|
||||
${data.startTime} — ${data.endTime}
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="padding:0 20px 16px;">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background-color:#fef2f2;border-radius:24px;border:1px solid rgba(220,38,38,0.3);">
|
||||
<tr>
|
||||
<td style="padding:20px 24px;">
|
||||
<p style="margin:0;font-size:14px;color:#374151;line-height:1.6;">
|
||||
La reserva <strong style="font-family:monospace;font-weight:700;letter-spacing:2px;">${data.bookingCode}</strong>
|
||||
fue cancelada. Si tenés dudas, contactate con el complejo.
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="padding:0 20px 24px;">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="border:1px solid #e5e7eb;border-radius:22px;overflow:hidden;">
|
||||
<tr>
|
||||
<td width="50%" style="padding:16px;border-right:1px solid #e5e7eb;background-color:#ffffff;">
|
||||
<p style="margin:0;font-size:13px;font-weight:500;color:#6b7280;">
|
||||
Cancha
|
||||
</p>
|
||||
<p style="margin:8px 0 0;font-size:14px;font-weight:600;color:#111827;">
|
||||
${data.courtName} — ${data.sportName}
|
||||
</p>
|
||||
</td>
|
||||
<td width="50%" style="padding:16px;background-color:#ffffff;">
|
||||
<p style="margin:0;font-size:13px;font-weight:500;color:#6b7280;">
|
||||
Cliente
|
||||
</p>
|
||||
<p style="margin:8px 0 0;font-size:14px;font-weight:600;color:#111827;">
|
||||
${data.customerName}
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>`;
|
||||
|
||||
return wrapLayout(content);
|
||||
}
|
||||
|
||||
export function bookingNoShowHtml(data: BookingEmailData): string {
|
||||
const friendlyDate = formatFriendlyDate(data.date);
|
||||
|
||||
const content = `
|
||||
<tr>
|
||||
<td style="padding:24px 20px 16px;">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0">
|
||||
<tr>
|
||||
<td valign="top">
|
||||
<table role="presentation" cellpadding="0" cellspacing="0" style="display:inline-block;background-color:#fffbeb;border-radius:999px;padding:4px 12px;">
|
||||
<tr>
|
||||
<td style="font-size:11px;font-weight:700;letter-spacing:0.14em;color:#d97706;text-transform:uppercase;line-height:1.25rem;">
|
||||
Reserva no concretada
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
<h1 style="margin:12px 0 0;font-size:28px;font-weight:700;color:#111827;letter-spacing:-0.025em;">
|
||||
${data.complexName}
|
||||
</h1>
|
||||
</td>
|
||||
<td valign="top" align="right" style="white-space:nowrap;">
|
||||
<table role="presentation" cellpadding="0" cellspacing="0">
|
||||
<tr>
|
||||
<td valign="middle" style="padding-right:8px;">
|
||||
<img src="${APP_BASE_URL}/playzer-favicon-512-transparent.png" alt="Playzer" width="32" height="32" style="display:block;" />
|
||||
</td>
|
||||
<td valign="middle">
|
||||
<span style="font-size:18px;font-weight:700;color:#475569;letter-spacing:-0.025em;">Playzer</span>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="padding:0 20px 16px;">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background-color:#f0fdf4;border-radius:24px;border:1px solid rgba(5,150,105,0.3);">
|
||||
<tr>
|
||||
<td style="padding:20px 24px;">
|
||||
<p style="margin:0;font-size:13px;font-weight:600;color:#15803d;">
|
||||
Tu turno
|
||||
</p>
|
||||
<p style="margin:12px 0 0;font-size:28px;font-weight:900;color:#111827;line-height:1.1;letter-spacing:-0.025em;">
|
||||
${friendlyDate}
|
||||
</p>
|
||||
<p style="margin:8px 0 0;font-size:24px;font-weight:900;color:#059669;line-height:1;letter-spacing:-0.025em;">
|
||||
${data.startTime} — ${data.endTime}
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="padding:0 20px 16px;">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background-color:#fffbeb;border-radius:24px;border:1px solid rgba(217,119,6,0.3);">
|
||||
<tr>
|
||||
<td style="padding:20px 24px;">
|
||||
<p style="margin:0;font-size:14px;color:#374151;line-height:1.6;">
|
||||
La reserva <strong style="font-family:monospace;font-weight:700;letter-spacing:2px;">${data.bookingCode}</strong>
|
||||
fue registrada como no concretada por falta de asistencia.
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="padding:0 20px 24px;">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="border:1px solid #e5e7eb;border-radius:22px;overflow:hidden;">
|
||||
<tr>
|
||||
<td width="50%" style="padding:16px;border-right:1px solid #e5e7eb;background-color:#ffffff;">
|
||||
<p style="margin:0;font-size:13px;font-weight:500;color:#6b7280;">
|
||||
Cancha
|
||||
</p>
|
||||
<p style="margin:8px 0 0;font-size:14px;font-weight:600;color:#111827;">
|
||||
${data.courtName} — ${data.sportName}
|
||||
</p>
|
||||
</td>
|
||||
<td width="50%" style="padding:16px;background-color:#ffffff;">
|
||||
<p style="margin:0;font-size:13px;font-weight:500;color:#6b7280;">
|
||||
Cliente
|
||||
</p>
|
||||
<p style="margin:8px 0 0;font-size:14px;font-weight:600;color:#111827;">
|
||||
${data.customerName}
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>`;
|
||||
|
||||
return wrapLayout(content);
|
||||
}
|
||||
@@ -78,10 +78,10 @@ export type CourtPriceRule = Prisma.CourtPriceRuleModel
|
||||
*/
|
||||
export type CourtBooking = Prisma.CourtBookingModel
|
||||
/**
|
||||
* Model OnboardingRequest
|
||||
* Model CourtBookingLog
|
||||
*
|
||||
*/
|
||||
export type OnboardingRequest = Prisma.OnboardingRequestModel
|
||||
export type CourtBookingLog = Prisma.CourtBookingLogModel
|
||||
/**
|
||||
* Model PasswordResetRequest
|
||||
*
|
||||
|
||||
@@ -102,10 +102,10 @@ export type CourtPriceRule = Prisma.CourtPriceRuleModel
|
||||
*/
|
||||
export type CourtBooking = Prisma.CourtBookingModel
|
||||
/**
|
||||
* Model OnboardingRequest
|
||||
* Model CourtBookingLog
|
||||
*
|
||||
*/
|
||||
export type OnboardingRequest = Prisma.OnboardingRequestModel
|
||||
export type CourtBookingLog = Prisma.CourtBookingLogModel
|
||||
/**
|
||||
* Model PasswordResetRequest
|
||||
*
|
||||
|
||||
@@ -33,7 +33,8 @@ export type DayOfWeek = (typeof DayOfWeek)[keyof typeof DayOfWeek]
|
||||
export const CourtBookingStatus = {
|
||||
CONFIRMED: 'CONFIRMED',
|
||||
CANCELLED: 'CANCELLED',
|
||||
COMPLETED: 'COMPLETED'
|
||||
COMPLETED: 'COMPLETED',
|
||||
NOSHOW: 'NOSHOW'
|
||||
} as const
|
||||
|
||||
export type CourtBookingStatus = (typeof CourtBookingStatus)[keyof typeof CourtBookingStatus]
|
||||
|
||||
@@ -396,7 +396,7 @@ export const ModelName = {
|
||||
CourtAvailability: 'CourtAvailability',
|
||||
CourtPriceRule: 'CourtPriceRule',
|
||||
CourtBooking: 'CourtBooking',
|
||||
OnboardingRequest: 'OnboardingRequest',
|
||||
CourtBookingLog: 'CourtBookingLog',
|
||||
PasswordResetRequest: 'PasswordResetRequest',
|
||||
Plan: 'Plan'
|
||||
} as const
|
||||
@@ -414,7 +414,7 @@ export type TypeMap<ExtArgs extends runtime.Types.Extensions.InternalArgs = runt
|
||||
omit: GlobalOmitOptions
|
||||
}
|
||||
meta: {
|
||||
modelProps: "user" | "session" | "account" | "verification" | "complex" | "complexUser" | "complexInvitation" | "sport" | "court" | "courtAvailability" | "courtPriceRule" | "courtBooking" | "onboardingRequest" | "passwordResetRequest" | "plan"
|
||||
modelProps: "user" | "session" | "account" | "verification" | "complex" | "complexUser" | "complexInvitation" | "sport" | "court" | "courtAvailability" | "courtPriceRule" | "courtBooking" | "courtBookingLog" | "passwordResetRequest" | "plan"
|
||||
txIsolationLevel: TransactionIsolationLevel
|
||||
}
|
||||
model: {
|
||||
@@ -1306,77 +1306,77 @@ export type TypeMap<ExtArgs extends runtime.Types.Extensions.InternalArgs = runt
|
||||
}
|
||||
}
|
||||
}
|
||||
OnboardingRequest: {
|
||||
payload: Prisma.$OnboardingRequestPayload<ExtArgs>
|
||||
fields: Prisma.OnboardingRequestFieldRefs
|
||||
CourtBookingLog: {
|
||||
payload: Prisma.$CourtBookingLogPayload<ExtArgs>
|
||||
fields: Prisma.CourtBookingLogFieldRefs
|
||||
operations: {
|
||||
findUnique: {
|
||||
args: Prisma.OnboardingRequestFindUniqueArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$OnboardingRequestPayload> | null
|
||||
args: Prisma.CourtBookingLogFindUniqueArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$CourtBookingLogPayload> | null
|
||||
}
|
||||
findUniqueOrThrow: {
|
||||
args: Prisma.OnboardingRequestFindUniqueOrThrowArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$OnboardingRequestPayload>
|
||||
args: Prisma.CourtBookingLogFindUniqueOrThrowArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$CourtBookingLogPayload>
|
||||
}
|
||||
findFirst: {
|
||||
args: Prisma.OnboardingRequestFindFirstArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$OnboardingRequestPayload> | null
|
||||
args: Prisma.CourtBookingLogFindFirstArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$CourtBookingLogPayload> | null
|
||||
}
|
||||
findFirstOrThrow: {
|
||||
args: Prisma.OnboardingRequestFindFirstOrThrowArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$OnboardingRequestPayload>
|
||||
args: Prisma.CourtBookingLogFindFirstOrThrowArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$CourtBookingLogPayload>
|
||||
}
|
||||
findMany: {
|
||||
args: Prisma.OnboardingRequestFindManyArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$OnboardingRequestPayload>[]
|
||||
args: Prisma.CourtBookingLogFindManyArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$CourtBookingLogPayload>[]
|
||||
}
|
||||
create: {
|
||||
args: Prisma.OnboardingRequestCreateArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$OnboardingRequestPayload>
|
||||
args: Prisma.CourtBookingLogCreateArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$CourtBookingLogPayload>
|
||||
}
|
||||
createMany: {
|
||||
args: Prisma.OnboardingRequestCreateManyArgs<ExtArgs>
|
||||
args: Prisma.CourtBookingLogCreateManyArgs<ExtArgs>
|
||||
result: BatchPayload
|
||||
}
|
||||
createManyAndReturn: {
|
||||
args: Prisma.OnboardingRequestCreateManyAndReturnArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$OnboardingRequestPayload>[]
|
||||
args: Prisma.CourtBookingLogCreateManyAndReturnArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$CourtBookingLogPayload>[]
|
||||
}
|
||||
delete: {
|
||||
args: Prisma.OnboardingRequestDeleteArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$OnboardingRequestPayload>
|
||||
args: Prisma.CourtBookingLogDeleteArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$CourtBookingLogPayload>
|
||||
}
|
||||
update: {
|
||||
args: Prisma.OnboardingRequestUpdateArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$OnboardingRequestPayload>
|
||||
args: Prisma.CourtBookingLogUpdateArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$CourtBookingLogPayload>
|
||||
}
|
||||
deleteMany: {
|
||||
args: Prisma.OnboardingRequestDeleteManyArgs<ExtArgs>
|
||||
args: Prisma.CourtBookingLogDeleteManyArgs<ExtArgs>
|
||||
result: BatchPayload
|
||||
}
|
||||
updateMany: {
|
||||
args: Prisma.OnboardingRequestUpdateManyArgs<ExtArgs>
|
||||
args: Prisma.CourtBookingLogUpdateManyArgs<ExtArgs>
|
||||
result: BatchPayload
|
||||
}
|
||||
updateManyAndReturn: {
|
||||
args: Prisma.OnboardingRequestUpdateManyAndReturnArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$OnboardingRequestPayload>[]
|
||||
args: Prisma.CourtBookingLogUpdateManyAndReturnArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$CourtBookingLogPayload>[]
|
||||
}
|
||||
upsert: {
|
||||
args: Prisma.OnboardingRequestUpsertArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$OnboardingRequestPayload>
|
||||
args: Prisma.CourtBookingLogUpsertArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$CourtBookingLogPayload>
|
||||
}
|
||||
aggregate: {
|
||||
args: Prisma.OnboardingRequestAggregateArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.Optional<Prisma.AggregateOnboardingRequest>
|
||||
args: Prisma.CourtBookingLogAggregateArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.Optional<Prisma.AggregateCourtBookingLog>
|
||||
}
|
||||
groupBy: {
|
||||
args: Prisma.OnboardingRequestGroupByArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.Optional<Prisma.OnboardingRequestGroupByOutputType>[]
|
||||
args: Prisma.CourtBookingLogGroupByArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.Optional<Prisma.CourtBookingLogGroupByOutputType>[]
|
||||
}
|
||||
count: {
|
||||
args: Prisma.OnboardingRequestCountArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.Optional<Prisma.OnboardingRequestCountAggregateOutputType> | number
|
||||
args: Prisma.CourtBookingLogCountArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.Optional<Prisma.CourtBookingLogCountAggregateOutputType> | number
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1573,6 +1573,7 @@ export const UserScalarFieldEnum = {
|
||||
email: 'email',
|
||||
emailVerified: 'emailVerified',
|
||||
image: 'image',
|
||||
phone: 'phone',
|
||||
createdAt: 'createdAt',
|
||||
updatedAt: 'updatedAt',
|
||||
role: 'role'
|
||||
@@ -1730,6 +1731,7 @@ export const CourtBookingScalarFieldEnum = {
|
||||
endTime: 'endTime',
|
||||
customerName: 'customerName',
|
||||
customerPhone: 'customerPhone',
|
||||
customerEmail: 'customerEmail',
|
||||
status: 'status',
|
||||
createdAt: 'createdAt',
|
||||
updatedAt: 'updatedAt'
|
||||
@@ -1738,22 +1740,22 @@ export const CourtBookingScalarFieldEnum = {
|
||||
export type CourtBookingScalarFieldEnum = (typeof CourtBookingScalarFieldEnum)[keyof typeof CourtBookingScalarFieldEnum]
|
||||
|
||||
|
||||
export const OnboardingRequestScalarFieldEnum = {
|
||||
export const CourtBookingLogScalarFieldEnum = {
|
||||
id: 'id',
|
||||
fullName: 'fullName',
|
||||
email: 'email',
|
||||
otpHash: 'otpHash',
|
||||
otpExpiresAt: 'otpExpiresAt',
|
||||
otpAttempts: 'otpAttempts',
|
||||
otpLastSentAt: 'otpLastSentAt',
|
||||
otpResendCount: 'otpResendCount',
|
||||
emailVerifiedAt: 'emailVerifiedAt',
|
||||
completedAt: 'completedAt',
|
||||
createdAt: 'createdAt',
|
||||
updatedAt: 'updatedAt'
|
||||
bookingCode: 'bookingCode',
|
||||
courtId: 'courtId',
|
||||
bookingDate: 'bookingDate',
|
||||
startTime: 'startTime',
|
||||
endTime: 'endTime',
|
||||
previousStatus: 'previousStatus',
|
||||
newStatus: 'newStatus',
|
||||
customerName: 'customerName',
|
||||
customerPhone: 'customerPhone',
|
||||
customerEmail: 'customerEmail',
|
||||
changedAt: 'changedAt'
|
||||
} as const
|
||||
|
||||
export type OnboardingRequestScalarFieldEnum = (typeof OnboardingRequestScalarFieldEnum)[keyof typeof OnboardingRequestScalarFieldEnum]
|
||||
export type CourtBookingLogScalarFieldEnum = (typeof CourtBookingLogScalarFieldEnum)[keyof typeof CourtBookingLogScalarFieldEnum]
|
||||
|
||||
|
||||
export const PasswordResetRequestScalarFieldEnum = {
|
||||
@@ -2068,7 +2070,7 @@ export type GlobalOmitConfig = {
|
||||
courtAvailability?: Prisma.CourtAvailabilityOmit
|
||||
courtPriceRule?: Prisma.CourtPriceRuleOmit
|
||||
courtBooking?: Prisma.CourtBookingOmit
|
||||
onboardingRequest?: Prisma.OnboardingRequestOmit
|
||||
courtBookingLog?: Prisma.CourtBookingLogOmit
|
||||
passwordResetRequest?: Prisma.PasswordResetRequestOmit
|
||||
plan?: Prisma.PlanOmit
|
||||
}
|
||||
|
||||
@@ -63,7 +63,7 @@ export const ModelName = {
|
||||
CourtAvailability: 'CourtAvailability',
|
||||
CourtPriceRule: 'CourtPriceRule',
|
||||
CourtBooking: 'CourtBooking',
|
||||
OnboardingRequest: 'OnboardingRequest',
|
||||
CourtBookingLog: 'CourtBookingLog',
|
||||
PasswordResetRequest: 'PasswordResetRequest',
|
||||
Plan: 'Plan'
|
||||
} as const
|
||||
@@ -90,6 +90,7 @@ export const UserScalarFieldEnum = {
|
||||
email: 'email',
|
||||
emailVerified: 'emailVerified',
|
||||
image: 'image',
|
||||
phone: 'phone',
|
||||
createdAt: 'createdAt',
|
||||
updatedAt: 'updatedAt',
|
||||
role: 'role'
|
||||
@@ -247,6 +248,7 @@ export const CourtBookingScalarFieldEnum = {
|
||||
endTime: 'endTime',
|
||||
customerName: 'customerName',
|
||||
customerPhone: 'customerPhone',
|
||||
customerEmail: 'customerEmail',
|
||||
status: 'status',
|
||||
createdAt: 'createdAt',
|
||||
updatedAt: 'updatedAt'
|
||||
@@ -255,22 +257,22 @@ export const CourtBookingScalarFieldEnum = {
|
||||
export type CourtBookingScalarFieldEnum = (typeof CourtBookingScalarFieldEnum)[keyof typeof CourtBookingScalarFieldEnum]
|
||||
|
||||
|
||||
export const OnboardingRequestScalarFieldEnum = {
|
||||
export const CourtBookingLogScalarFieldEnum = {
|
||||
id: 'id',
|
||||
fullName: 'fullName',
|
||||
email: 'email',
|
||||
otpHash: 'otpHash',
|
||||
otpExpiresAt: 'otpExpiresAt',
|
||||
otpAttempts: 'otpAttempts',
|
||||
otpLastSentAt: 'otpLastSentAt',
|
||||
otpResendCount: 'otpResendCount',
|
||||
emailVerifiedAt: 'emailVerifiedAt',
|
||||
completedAt: 'completedAt',
|
||||
createdAt: 'createdAt',
|
||||
updatedAt: 'updatedAt'
|
||||
bookingCode: 'bookingCode',
|
||||
courtId: 'courtId',
|
||||
bookingDate: 'bookingDate',
|
||||
startTime: 'startTime',
|
||||
endTime: 'endTime',
|
||||
previousStatus: 'previousStatus',
|
||||
newStatus: 'newStatus',
|
||||
customerName: 'customerName',
|
||||
customerPhone: 'customerPhone',
|
||||
customerEmail: 'customerEmail',
|
||||
changedAt: 'changedAt'
|
||||
} as const
|
||||
|
||||
export type OnboardingRequestScalarFieldEnum = (typeof OnboardingRequestScalarFieldEnum)[keyof typeof OnboardingRequestScalarFieldEnum]
|
||||
export type CourtBookingLogScalarFieldEnum = (typeof CourtBookingLogScalarFieldEnum)[keyof typeof CourtBookingLogScalarFieldEnum]
|
||||
|
||||
|
||||
export const PasswordResetRequestScalarFieldEnum = {
|
||||
|
||||
@@ -20,7 +20,7 @@ export type * from './models/Court'
|
||||
export type * from './models/CourtAvailability'
|
||||
export type * from './models/CourtPriceRule'
|
||||
export type * from './models/CourtBooking'
|
||||
export type * from './models/OnboardingRequest'
|
||||
export type * from './models/CourtBookingLog'
|
||||
export type * from './models/PasswordResetRequest'
|
||||
export type * from './models/Plan'
|
||||
export type * from './commonInputTypes'
|
||||
@@ -33,6 +33,7 @@ export type CourtBookingMinAggregateOutputType = {
|
||||
endTime: string | null
|
||||
customerName: string | null
|
||||
customerPhone: string | null
|
||||
customerEmail: string | null
|
||||
status: $Enums.CourtBookingStatus | null
|
||||
createdAt: Date | null
|
||||
updatedAt: Date | null
|
||||
@@ -47,6 +48,7 @@ export type CourtBookingMaxAggregateOutputType = {
|
||||
endTime: string | null
|
||||
customerName: string | null
|
||||
customerPhone: string | null
|
||||
customerEmail: string | null
|
||||
status: $Enums.CourtBookingStatus | null
|
||||
createdAt: Date | null
|
||||
updatedAt: Date | null
|
||||
@@ -61,6 +63,7 @@ export type CourtBookingCountAggregateOutputType = {
|
||||
endTime: number
|
||||
customerName: number
|
||||
customerPhone: number
|
||||
customerEmail: number
|
||||
status: number
|
||||
createdAt: number
|
||||
updatedAt: number
|
||||
@@ -77,6 +80,7 @@ export type CourtBookingMinAggregateInputType = {
|
||||
endTime?: true
|
||||
customerName?: true
|
||||
customerPhone?: true
|
||||
customerEmail?: true
|
||||
status?: true
|
||||
createdAt?: true
|
||||
updatedAt?: true
|
||||
@@ -91,6 +95,7 @@ export type CourtBookingMaxAggregateInputType = {
|
||||
endTime?: true
|
||||
customerName?: true
|
||||
customerPhone?: true
|
||||
customerEmail?: true
|
||||
status?: true
|
||||
createdAt?: true
|
||||
updatedAt?: true
|
||||
@@ -105,6 +110,7 @@ export type CourtBookingCountAggregateInputType = {
|
||||
endTime?: true
|
||||
customerName?: true
|
||||
customerPhone?: true
|
||||
customerEmail?: true
|
||||
status?: true
|
||||
createdAt?: true
|
||||
updatedAt?: true
|
||||
@@ -192,6 +198,7 @@ export type CourtBookingGroupByOutputType = {
|
||||
endTime: string
|
||||
customerName: string
|
||||
customerPhone: string
|
||||
customerEmail: string | null
|
||||
status: $Enums.CourtBookingStatus
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
@@ -227,6 +234,7 @@ export type CourtBookingWhereInput = {
|
||||
endTime?: Prisma.StringFilter<"CourtBooking"> | string
|
||||
customerName?: Prisma.StringFilter<"CourtBooking"> | string
|
||||
customerPhone?: Prisma.StringFilter<"CourtBooking"> | string
|
||||
customerEmail?: Prisma.StringNullableFilter<"CourtBooking"> | string | null
|
||||
status?: Prisma.EnumCourtBookingStatusFilter<"CourtBooking"> | $Enums.CourtBookingStatus
|
||||
createdAt?: Prisma.DateTimeFilter<"CourtBooking"> | Date | string
|
||||
updatedAt?: Prisma.DateTimeFilter<"CourtBooking"> | Date | string
|
||||
@@ -242,6 +250,7 @@ export type CourtBookingOrderByWithRelationInput = {
|
||||
endTime?: Prisma.SortOrder
|
||||
customerName?: Prisma.SortOrder
|
||||
customerPhone?: Prisma.SortOrder
|
||||
customerEmail?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
status?: Prisma.SortOrder
|
||||
createdAt?: Prisma.SortOrder
|
||||
updatedAt?: Prisma.SortOrder
|
||||
@@ -261,6 +270,7 @@ export type CourtBookingWhereUniqueInput = Prisma.AtLeast<{
|
||||
endTime?: Prisma.StringFilter<"CourtBooking"> | string
|
||||
customerName?: Prisma.StringFilter<"CourtBooking"> | string
|
||||
customerPhone?: Prisma.StringFilter<"CourtBooking"> | string
|
||||
customerEmail?: Prisma.StringNullableFilter<"CourtBooking"> | string | null
|
||||
status?: Prisma.EnumCourtBookingStatusFilter<"CourtBooking"> | $Enums.CourtBookingStatus
|
||||
createdAt?: Prisma.DateTimeFilter<"CourtBooking"> | Date | string
|
||||
updatedAt?: Prisma.DateTimeFilter<"CourtBooking"> | Date | string
|
||||
@@ -276,6 +286,7 @@ export type CourtBookingOrderByWithAggregationInput = {
|
||||
endTime?: Prisma.SortOrder
|
||||
customerName?: Prisma.SortOrder
|
||||
customerPhone?: Prisma.SortOrder
|
||||
customerEmail?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
status?: Prisma.SortOrder
|
||||
createdAt?: Prisma.SortOrder
|
||||
updatedAt?: Prisma.SortOrder
|
||||
@@ -296,6 +307,7 @@ export type CourtBookingScalarWhereWithAggregatesInput = {
|
||||
endTime?: Prisma.StringWithAggregatesFilter<"CourtBooking"> | string
|
||||
customerName?: Prisma.StringWithAggregatesFilter<"CourtBooking"> | string
|
||||
customerPhone?: Prisma.StringWithAggregatesFilter<"CourtBooking"> | string
|
||||
customerEmail?: Prisma.StringNullableWithAggregatesFilter<"CourtBooking"> | string | null
|
||||
status?: Prisma.EnumCourtBookingStatusWithAggregatesFilter<"CourtBooking"> | $Enums.CourtBookingStatus
|
||||
createdAt?: Prisma.DateTimeWithAggregatesFilter<"CourtBooking"> | Date | string
|
||||
updatedAt?: Prisma.DateTimeWithAggregatesFilter<"CourtBooking"> | Date | string
|
||||
@@ -309,6 +321,7 @@ export type CourtBookingCreateInput = {
|
||||
endTime: string
|
||||
customerName: string
|
||||
customerPhone: string
|
||||
customerEmail?: string | null
|
||||
status?: $Enums.CourtBookingStatus
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
@@ -324,6 +337,7 @@ export type CourtBookingUncheckedCreateInput = {
|
||||
endTime: string
|
||||
customerName: string
|
||||
customerPhone: string
|
||||
customerEmail?: string | null
|
||||
status?: $Enums.CourtBookingStatus
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
@@ -337,6 +351,7 @@ export type CourtBookingUpdateInput = {
|
||||
endTime?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
customerName?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
customerPhone?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
customerEmail?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
status?: Prisma.EnumCourtBookingStatusFieldUpdateOperationsInput | $Enums.CourtBookingStatus
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -352,6 +367,7 @@ export type CourtBookingUncheckedUpdateInput = {
|
||||
endTime?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
customerName?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
customerPhone?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
customerEmail?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
status?: Prisma.EnumCourtBookingStatusFieldUpdateOperationsInput | $Enums.CourtBookingStatus
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -366,6 +382,7 @@ export type CourtBookingCreateManyInput = {
|
||||
endTime: string
|
||||
customerName: string
|
||||
customerPhone: string
|
||||
customerEmail?: string | null
|
||||
status?: $Enums.CourtBookingStatus
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
@@ -379,6 +396,7 @@ export type CourtBookingUpdateManyMutationInput = {
|
||||
endTime?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
customerName?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
customerPhone?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
customerEmail?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
status?: Prisma.EnumCourtBookingStatusFieldUpdateOperationsInput | $Enums.CourtBookingStatus
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -393,6 +411,7 @@ export type CourtBookingUncheckedUpdateManyInput = {
|
||||
endTime?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
customerName?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
customerPhone?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
customerEmail?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
status?: Prisma.EnumCourtBookingStatusFieldUpdateOperationsInput | $Enums.CourtBookingStatus
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -423,6 +442,7 @@ export type CourtBookingCountOrderByAggregateInput = {
|
||||
endTime?: Prisma.SortOrder
|
||||
customerName?: Prisma.SortOrder
|
||||
customerPhone?: Prisma.SortOrder
|
||||
customerEmail?: Prisma.SortOrder
|
||||
status?: Prisma.SortOrder
|
||||
createdAt?: Prisma.SortOrder
|
||||
updatedAt?: Prisma.SortOrder
|
||||
@@ -437,6 +457,7 @@ export type CourtBookingMaxOrderByAggregateInput = {
|
||||
endTime?: Prisma.SortOrder
|
||||
customerName?: Prisma.SortOrder
|
||||
customerPhone?: Prisma.SortOrder
|
||||
customerEmail?: Prisma.SortOrder
|
||||
status?: Prisma.SortOrder
|
||||
createdAt?: Prisma.SortOrder
|
||||
updatedAt?: Prisma.SortOrder
|
||||
@@ -451,6 +472,7 @@ export type CourtBookingMinOrderByAggregateInput = {
|
||||
endTime?: Prisma.SortOrder
|
||||
customerName?: Prisma.SortOrder
|
||||
customerPhone?: Prisma.SortOrder
|
||||
customerEmail?: Prisma.SortOrder
|
||||
status?: Prisma.SortOrder
|
||||
createdAt?: Prisma.SortOrder
|
||||
updatedAt?: Prisma.SortOrder
|
||||
@@ -510,6 +532,7 @@ export type CourtBookingCreateWithoutCourtInput = {
|
||||
endTime: string
|
||||
customerName: string
|
||||
customerPhone: string
|
||||
customerEmail?: string | null
|
||||
status?: $Enums.CourtBookingStatus
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
@@ -523,6 +546,7 @@ export type CourtBookingUncheckedCreateWithoutCourtInput = {
|
||||
endTime: string
|
||||
customerName: string
|
||||
customerPhone: string
|
||||
customerEmail?: string | null
|
||||
status?: $Enums.CourtBookingStatus
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
@@ -566,6 +590,7 @@ export type CourtBookingScalarWhereInput = {
|
||||
endTime?: Prisma.StringFilter<"CourtBooking"> | string
|
||||
customerName?: Prisma.StringFilter<"CourtBooking"> | string
|
||||
customerPhone?: Prisma.StringFilter<"CourtBooking"> | string
|
||||
customerEmail?: Prisma.StringNullableFilter<"CourtBooking"> | string | null
|
||||
status?: Prisma.EnumCourtBookingStatusFilter<"CourtBooking"> | $Enums.CourtBookingStatus
|
||||
createdAt?: Prisma.DateTimeFilter<"CourtBooking"> | Date | string
|
||||
updatedAt?: Prisma.DateTimeFilter<"CourtBooking"> | Date | string
|
||||
@@ -579,6 +604,7 @@ export type CourtBookingCreateManyCourtInput = {
|
||||
endTime: string
|
||||
customerName: string
|
||||
customerPhone: string
|
||||
customerEmail?: string | null
|
||||
status?: $Enums.CourtBookingStatus
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
@@ -592,6 +618,7 @@ export type CourtBookingUpdateWithoutCourtInput = {
|
||||
endTime?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
customerName?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
customerPhone?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
customerEmail?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
status?: Prisma.EnumCourtBookingStatusFieldUpdateOperationsInput | $Enums.CourtBookingStatus
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -605,6 +632,7 @@ export type CourtBookingUncheckedUpdateWithoutCourtInput = {
|
||||
endTime?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
customerName?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
customerPhone?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
customerEmail?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
status?: Prisma.EnumCourtBookingStatusFieldUpdateOperationsInput | $Enums.CourtBookingStatus
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -618,6 +646,7 @@ export type CourtBookingUncheckedUpdateManyWithoutCourtInput = {
|
||||
endTime?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
customerName?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
customerPhone?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
customerEmail?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
status?: Prisma.EnumCourtBookingStatusFieldUpdateOperationsInput | $Enums.CourtBookingStatus
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -634,6 +663,7 @@ export type CourtBookingSelect<ExtArgs extends runtime.Types.Extensions.Internal
|
||||
endTime?: boolean
|
||||
customerName?: boolean
|
||||
customerPhone?: boolean
|
||||
customerEmail?: boolean
|
||||
status?: boolean
|
||||
createdAt?: boolean
|
||||
updatedAt?: boolean
|
||||
@@ -649,6 +679,7 @@ export type CourtBookingSelectCreateManyAndReturn<ExtArgs extends runtime.Types.
|
||||
endTime?: boolean
|
||||
customerName?: boolean
|
||||
customerPhone?: boolean
|
||||
customerEmail?: boolean
|
||||
status?: boolean
|
||||
createdAt?: boolean
|
||||
updatedAt?: boolean
|
||||
@@ -664,6 +695,7 @@ export type CourtBookingSelectUpdateManyAndReturn<ExtArgs extends runtime.Types.
|
||||
endTime?: boolean
|
||||
customerName?: boolean
|
||||
customerPhone?: boolean
|
||||
customerEmail?: boolean
|
||||
status?: boolean
|
||||
createdAt?: boolean
|
||||
updatedAt?: boolean
|
||||
@@ -679,12 +711,13 @@ export type CourtBookingSelectScalar = {
|
||||
endTime?: boolean
|
||||
customerName?: boolean
|
||||
customerPhone?: boolean
|
||||
customerEmail?: boolean
|
||||
status?: boolean
|
||||
createdAt?: boolean
|
||||
updatedAt?: boolean
|
||||
}
|
||||
|
||||
export type CourtBookingOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "bookingCode" | "courtId" | "bookingDate" | "startTime" | "endTime" | "customerName" | "customerPhone" | "status" | "createdAt" | "updatedAt", ExtArgs["result"]["courtBooking"]>
|
||||
export type CourtBookingOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "bookingCode" | "courtId" | "bookingDate" | "startTime" | "endTime" | "customerName" | "customerPhone" | "customerEmail" | "status" | "createdAt" | "updatedAt", ExtArgs["result"]["courtBooking"]>
|
||||
export type CourtBookingInclude<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
||||
court?: boolean | Prisma.CourtDefaultArgs<ExtArgs>
|
||||
}
|
||||
@@ -709,6 +742,7 @@ export type $CourtBookingPayload<ExtArgs extends runtime.Types.Extensions.Intern
|
||||
endTime: string
|
||||
customerName: string
|
||||
customerPhone: string
|
||||
customerEmail: string | null
|
||||
status: $Enums.CourtBookingStatus
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
@@ -1144,6 +1178,7 @@ export interface CourtBookingFieldRefs {
|
||||
readonly endTime: Prisma.FieldRef<"CourtBooking", 'String'>
|
||||
readonly customerName: Prisma.FieldRef<"CourtBooking", 'String'>
|
||||
readonly customerPhone: Prisma.FieldRef<"CourtBooking", 'String'>
|
||||
readonly customerEmail: Prisma.FieldRef<"CourtBooking", 'String'>
|
||||
readonly status: Prisma.FieldRef<"CourtBooking", 'CourtBookingStatus'>
|
||||
readonly createdAt: Prisma.FieldRef<"CourtBooking", 'DateTime'>
|
||||
readonly updatedAt: Prisma.FieldRef<"CourtBooking", 'DateTime'>
|
||||
|
||||
@@ -30,6 +30,7 @@ export type UserMinAggregateOutputType = {
|
||||
email: string | null
|
||||
emailVerified: boolean | null
|
||||
image: string | null
|
||||
phone: string | null
|
||||
createdAt: Date | null
|
||||
updatedAt: Date | null
|
||||
role: string | null
|
||||
@@ -41,6 +42,7 @@ export type UserMaxAggregateOutputType = {
|
||||
email: string | null
|
||||
emailVerified: boolean | null
|
||||
image: string | null
|
||||
phone: string | null
|
||||
createdAt: Date | null
|
||||
updatedAt: Date | null
|
||||
role: string | null
|
||||
@@ -52,6 +54,7 @@ export type UserCountAggregateOutputType = {
|
||||
email: number
|
||||
emailVerified: number
|
||||
image: number
|
||||
phone: number
|
||||
createdAt: number
|
||||
updatedAt: number
|
||||
role: number
|
||||
@@ -65,6 +68,7 @@ export type UserMinAggregateInputType = {
|
||||
email?: true
|
||||
emailVerified?: true
|
||||
image?: true
|
||||
phone?: true
|
||||
createdAt?: true
|
||||
updatedAt?: true
|
||||
role?: true
|
||||
@@ -76,6 +80,7 @@ export type UserMaxAggregateInputType = {
|
||||
email?: true
|
||||
emailVerified?: true
|
||||
image?: true
|
||||
phone?: true
|
||||
createdAt?: true
|
||||
updatedAt?: true
|
||||
role?: true
|
||||
@@ -87,6 +92,7 @@ export type UserCountAggregateInputType = {
|
||||
email?: true
|
||||
emailVerified?: true
|
||||
image?: true
|
||||
phone?: true
|
||||
createdAt?: true
|
||||
updatedAt?: true
|
||||
role?: true
|
||||
@@ -171,6 +177,7 @@ export type UserGroupByOutputType = {
|
||||
email: string
|
||||
emailVerified: boolean
|
||||
image: string | null
|
||||
phone: string | null
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
role: string
|
||||
@@ -203,6 +210,7 @@ export type UserWhereInput = {
|
||||
email?: Prisma.StringFilter<"User"> | string
|
||||
emailVerified?: Prisma.BoolFilter<"User"> | boolean
|
||||
image?: Prisma.StringNullableFilter<"User"> | string | null
|
||||
phone?: Prisma.StringNullableFilter<"User"> | string | null
|
||||
createdAt?: Prisma.DateTimeFilter<"User"> | Date | string
|
||||
updatedAt?: Prisma.DateTimeFilter<"User"> | Date | string
|
||||
role?: Prisma.StringFilter<"User"> | string
|
||||
@@ -217,6 +225,7 @@ export type UserOrderByWithRelationInput = {
|
||||
email?: Prisma.SortOrder
|
||||
emailVerified?: Prisma.SortOrder
|
||||
image?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
phone?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
createdAt?: Prisma.SortOrder
|
||||
updatedAt?: Prisma.SortOrder
|
||||
role?: Prisma.SortOrder
|
||||
@@ -234,6 +243,7 @@ export type UserWhereUniqueInput = Prisma.AtLeast<{
|
||||
name?: Prisma.StringFilter<"User"> | string
|
||||
emailVerified?: Prisma.BoolFilter<"User"> | boolean
|
||||
image?: Prisma.StringNullableFilter<"User"> | string | null
|
||||
phone?: Prisma.StringNullableFilter<"User"> | string | null
|
||||
createdAt?: Prisma.DateTimeFilter<"User"> | Date | string
|
||||
updatedAt?: Prisma.DateTimeFilter<"User"> | Date | string
|
||||
role?: Prisma.StringFilter<"User"> | string
|
||||
@@ -248,6 +258,7 @@ export type UserOrderByWithAggregationInput = {
|
||||
email?: Prisma.SortOrder
|
||||
emailVerified?: Prisma.SortOrder
|
||||
image?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
phone?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
createdAt?: Prisma.SortOrder
|
||||
updatedAt?: Prisma.SortOrder
|
||||
role?: Prisma.SortOrder
|
||||
@@ -265,6 +276,7 @@ export type UserScalarWhereWithAggregatesInput = {
|
||||
email?: Prisma.StringWithAggregatesFilter<"User"> | string
|
||||
emailVerified?: Prisma.BoolWithAggregatesFilter<"User"> | boolean
|
||||
image?: Prisma.StringNullableWithAggregatesFilter<"User"> | string | null
|
||||
phone?: Prisma.StringNullableWithAggregatesFilter<"User"> | string | null
|
||||
createdAt?: Prisma.DateTimeWithAggregatesFilter<"User"> | Date | string
|
||||
updatedAt?: Prisma.DateTimeWithAggregatesFilter<"User"> | Date | string
|
||||
role?: Prisma.StringWithAggregatesFilter<"User"> | string
|
||||
@@ -276,6 +288,7 @@ export type UserCreateInput = {
|
||||
email: string
|
||||
emailVerified?: boolean
|
||||
image?: string | null
|
||||
phone?: string | null
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
role?: string
|
||||
@@ -290,6 +303,7 @@ export type UserUncheckedCreateInput = {
|
||||
email: string
|
||||
emailVerified?: boolean
|
||||
image?: string | null
|
||||
phone?: string | null
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
role?: string
|
||||
@@ -304,6 +318,7 @@ export type UserUpdateInput = {
|
||||
email?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
emailVerified?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
image?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
phone?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
role?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
@@ -318,6 +333,7 @@ export type UserUncheckedUpdateInput = {
|
||||
email?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
emailVerified?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
image?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
phone?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
role?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
@@ -332,6 +348,7 @@ export type UserCreateManyInput = {
|
||||
email: string
|
||||
emailVerified?: boolean
|
||||
image?: string | null
|
||||
phone?: string | null
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
role?: string
|
||||
@@ -343,6 +360,7 @@ export type UserUpdateManyMutationInput = {
|
||||
email?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
emailVerified?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
image?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
phone?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
role?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
@@ -354,6 +372,7 @@ export type UserUncheckedUpdateManyInput = {
|
||||
email?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
emailVerified?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
image?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
phone?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
role?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
@@ -365,6 +384,7 @@ export type UserCountOrderByAggregateInput = {
|
||||
email?: Prisma.SortOrder
|
||||
emailVerified?: Prisma.SortOrder
|
||||
image?: Prisma.SortOrder
|
||||
phone?: Prisma.SortOrder
|
||||
createdAt?: Prisma.SortOrder
|
||||
updatedAt?: Prisma.SortOrder
|
||||
role?: Prisma.SortOrder
|
||||
@@ -376,6 +396,7 @@ export type UserMaxOrderByAggregateInput = {
|
||||
email?: Prisma.SortOrder
|
||||
emailVerified?: Prisma.SortOrder
|
||||
image?: Prisma.SortOrder
|
||||
phone?: Prisma.SortOrder
|
||||
createdAt?: Prisma.SortOrder
|
||||
updatedAt?: Prisma.SortOrder
|
||||
role?: Prisma.SortOrder
|
||||
@@ -387,6 +408,7 @@ export type UserMinOrderByAggregateInput = {
|
||||
email?: Prisma.SortOrder
|
||||
emailVerified?: Prisma.SortOrder
|
||||
image?: Prisma.SortOrder
|
||||
phone?: Prisma.SortOrder
|
||||
createdAt?: Prisma.SortOrder
|
||||
updatedAt?: Prisma.SortOrder
|
||||
role?: Prisma.SortOrder
|
||||
@@ -461,6 +483,7 @@ export type UserCreateWithoutSessionsInput = {
|
||||
email: string
|
||||
emailVerified?: boolean
|
||||
image?: string | null
|
||||
phone?: string | null
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
role?: string
|
||||
@@ -474,6 +497,7 @@ export type UserUncheckedCreateWithoutSessionsInput = {
|
||||
email: string
|
||||
emailVerified?: boolean
|
||||
image?: string | null
|
||||
phone?: string | null
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
role?: string
|
||||
@@ -503,6 +527,7 @@ export type UserUpdateWithoutSessionsInput = {
|
||||
email?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
emailVerified?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
image?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
phone?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
role?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
@@ -516,6 +541,7 @@ export type UserUncheckedUpdateWithoutSessionsInput = {
|
||||
email?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
emailVerified?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
image?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
phone?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
role?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
@@ -529,6 +555,7 @@ export type UserCreateWithoutAccountsInput = {
|
||||
email: string
|
||||
emailVerified?: boolean
|
||||
image?: string | null
|
||||
phone?: string | null
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
role?: string
|
||||
@@ -542,6 +569,7 @@ export type UserUncheckedCreateWithoutAccountsInput = {
|
||||
email: string
|
||||
emailVerified?: boolean
|
||||
image?: string | null
|
||||
phone?: string | null
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
role?: string
|
||||
@@ -571,6 +599,7 @@ export type UserUpdateWithoutAccountsInput = {
|
||||
email?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
emailVerified?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
image?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
phone?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
role?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
@@ -584,6 +613,7 @@ export type UserUncheckedUpdateWithoutAccountsInput = {
|
||||
email?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
emailVerified?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
image?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
phone?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
role?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
@@ -597,6 +627,7 @@ export type UserCreateWithoutComplexesInput = {
|
||||
email: string
|
||||
emailVerified?: boolean
|
||||
image?: string | null
|
||||
phone?: string | null
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
role?: string
|
||||
@@ -610,6 +641,7 @@ export type UserUncheckedCreateWithoutComplexesInput = {
|
||||
email: string
|
||||
emailVerified?: boolean
|
||||
image?: string | null
|
||||
phone?: string | null
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
role?: string
|
||||
@@ -639,6 +671,7 @@ export type UserUpdateWithoutComplexesInput = {
|
||||
email?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
emailVerified?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
image?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
phone?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
role?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
@@ -652,6 +685,7 @@ export type UserUncheckedUpdateWithoutComplexesInput = {
|
||||
email?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
emailVerified?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
image?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
phone?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
role?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
@@ -714,6 +748,7 @@ export type UserSelect<ExtArgs extends runtime.Types.Extensions.InternalArgs = r
|
||||
email?: boolean
|
||||
emailVerified?: boolean
|
||||
image?: boolean
|
||||
phone?: boolean
|
||||
createdAt?: boolean
|
||||
updatedAt?: boolean
|
||||
role?: boolean
|
||||
@@ -729,6 +764,7 @@ export type UserSelectCreateManyAndReturn<ExtArgs extends runtime.Types.Extensio
|
||||
email?: boolean
|
||||
emailVerified?: boolean
|
||||
image?: boolean
|
||||
phone?: boolean
|
||||
createdAt?: boolean
|
||||
updatedAt?: boolean
|
||||
role?: boolean
|
||||
@@ -740,6 +776,7 @@ export type UserSelectUpdateManyAndReturn<ExtArgs extends runtime.Types.Extensio
|
||||
email?: boolean
|
||||
emailVerified?: boolean
|
||||
image?: boolean
|
||||
phone?: boolean
|
||||
createdAt?: boolean
|
||||
updatedAt?: boolean
|
||||
role?: boolean
|
||||
@@ -751,12 +788,13 @@ export type UserSelectScalar = {
|
||||
email?: boolean
|
||||
emailVerified?: boolean
|
||||
image?: boolean
|
||||
phone?: boolean
|
||||
createdAt?: boolean
|
||||
updatedAt?: boolean
|
||||
role?: boolean
|
||||
}
|
||||
|
||||
export type UserOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "name" | "email" | "emailVerified" | "image" | "createdAt" | "updatedAt" | "role", ExtArgs["result"]["user"]>
|
||||
export type UserOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "name" | "email" | "emailVerified" | "image" | "phone" | "createdAt" | "updatedAt" | "role", ExtArgs["result"]["user"]>
|
||||
export type UserInclude<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
||||
sessions?: boolean | Prisma.User$sessionsArgs<ExtArgs>
|
||||
accounts?: boolean | Prisma.User$accountsArgs<ExtArgs>
|
||||
@@ -779,6 +817,7 @@ export type $UserPayload<ExtArgs extends runtime.Types.Extensions.InternalArgs =
|
||||
email: string
|
||||
emailVerified: boolean
|
||||
image: string | null
|
||||
phone: string | null
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
role: string
|
||||
@@ -1213,6 +1252,7 @@ export interface UserFieldRefs {
|
||||
readonly email: Prisma.FieldRef<"User", 'String'>
|
||||
readonly emailVerified: Prisma.FieldRef<"User", 'Boolean'>
|
||||
readonly image: Prisma.FieldRef<"User", 'String'>
|
||||
readonly phone: Prisma.FieldRef<"User", 'String'>
|
||||
readonly createdAt: Prisma.FieldRef<"User", 'DateTime'>
|
||||
readonly updatedAt: Prisma.FieldRef<"User", 'DateTime'>
|
||||
readonly role: Prisma.FieldRef<"User", 'String'>
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { wrapLayout } from '@/emails/booking-confirmation';
|
||||
import { dash } from '@better-auth/infra';
|
||||
import { betterAuth } from 'better-auth';
|
||||
import { prismaAdapter } from 'better-auth/adapters/prisma';
|
||||
import { openAPI } from 'better-auth/plugins';
|
||||
import { sendMail } from './mailer';
|
||||
import { db } from './prisma';
|
||||
|
||||
export const auth = betterAuth({
|
||||
@@ -18,6 +20,92 @@ export const auth = betterAuth({
|
||||
emailAndPassword: {
|
||||
enabled: true,
|
||||
},
|
||||
user: {
|
||||
additionalFields: {
|
||||
phone: {
|
||||
type: 'string',
|
||||
required: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
emailVerification: {
|
||||
sendOnSignUp: true,
|
||||
autoSignInAfterVerification: true,
|
||||
sendVerificationEmail: async ({ user, url }) => {
|
||||
const verificationUrl = new URL(url);
|
||||
const appUrl = process.env.APP_BASE_URL ?? 'http://localhost:5173';
|
||||
verificationUrl.searchParams.set('callbackURL', appUrl);
|
||||
|
||||
const content = `
|
||||
<tr>
|
||||
<td style="padding:24px 20px 16px;">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0">
|
||||
<tr>
|
||||
<td valign="top">
|
||||
<table role="presentation" cellpadding="0" cellspacing="0" style="display:inline-block;background-color:#f4f4f5;border-radius:999px;padding:4px 12px;">
|
||||
<tr>
|
||||
<td style="font-size:11px;font-weight:700;letter-spacing:0.14em;color:#71717a;text-transform:uppercase;line-height:1.25rem;">
|
||||
Verificación de email
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
<h1 style="margin:16px 0 0;font-size:24px;font-weight:700;color:#111827;letter-spacing:-0.025em;">
|
||||
Verificá tu dirección de correo electrónico
|
||||
</h1>
|
||||
</td>
|
||||
<td valign="top" align="right" style="white-space:nowrap;">
|
||||
<table role="presentation" cellpadding="0" cellspacing="0">
|
||||
<tr>
|
||||
<td valign="middle" style="padding-right:8px;">
|
||||
<img src="${appUrl}/playzer-favicon-512-transparent.png" alt="Playzer" width="32" height="32" style="display:block;" />
|
||||
</td>
|
||||
<td valign="middle">
|
||||
<span style="font-size:18px;font-weight:700;color:#475569;letter-spacing:-0.025em;">Playzer</span>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
padding:0 20px 16px;
|
||||
<p style="margin:0;font-size:15px;color:#374151;line-height:1.6;">
|
||||
Hacé click en el botón de abajo para verificar tu dirección de correo electrónico y empezar a usar Playzer.
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="padding:0 20px 24px;">
|
||||
<table role="presentation" cellpadding="0" cellspacing="0">
|
||||
<tr>
|
||||
<td style="background-color:#059669;border-radius:12px;text-align:center;">
|
||||
<a href="${verificationUrl.toString()}" style="display:block;padding:14px 32px;font-size:15px;font-weight:600;color:#ffffff;text-decoration:none;line-height:1.25rem;">Verificar email</a>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="padding:0 20px 24px;">
|
||||
<p style="margin:0;font-size:13px;color:#9ca3af;text-align:center;line-height:1.5;">
|
||||
Si no creaste una cuenta en Playzer, ignorá este mensaje.
|
||||
</p>
|
||||
</td>
|
||||
</tr>`;
|
||||
|
||||
await sendMail({
|
||||
to: user.email,
|
||||
subject: 'Verificá tu email en Playzer',
|
||||
html: wrapLayout(content),
|
||||
text: `Hacé click para verificar tu email: ${verificationUrl.toString()}`,
|
||||
});
|
||||
},
|
||||
},
|
||||
socialProviders: {
|
||||
google: {
|
||||
clientId: process.env.GOOGLE_CLIENT_ID!,
|
||||
|
||||
58
apps/backend/src/lib/errors.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
// lib/errors.ts
|
||||
export type ValidationIssue = {
|
||||
path: string;
|
||||
message: string;
|
||||
};
|
||||
|
||||
export type AppError =
|
||||
| {
|
||||
type: 'validation';
|
||||
message: string;
|
||||
issues?: ValidationIssue[];
|
||||
}
|
||||
| {
|
||||
type: 'not_found';
|
||||
message: string;
|
||||
}
|
||||
| {
|
||||
type: 'conflict';
|
||||
message: string;
|
||||
}
|
||||
| {
|
||||
type: 'unauthorized';
|
||||
message: string;
|
||||
}
|
||||
| {
|
||||
type: 'forbidden';
|
||||
message: string;
|
||||
}
|
||||
| {
|
||||
type: 'unexpected';
|
||||
message: string;
|
||||
};
|
||||
|
||||
export const Errors = {
|
||||
validation(message: string, issues?: ValidationIssue[]): AppError {
|
||||
return { type: 'validation', message, issues };
|
||||
},
|
||||
|
||||
notFound(message = 'Resource not found'): AppError {
|
||||
return { type: 'not_found', message };
|
||||
},
|
||||
|
||||
conflict(message: string): AppError {
|
||||
return { type: 'conflict', message };
|
||||
},
|
||||
|
||||
unauthorized(message = 'Unauthorized'): AppError {
|
||||
return { type: 'unauthorized', message };
|
||||
},
|
||||
|
||||
forbidden(message = 'Forbidden'): AppError {
|
||||
return { type: 'forbidden', message };
|
||||
},
|
||||
|
||||
unexpected(message = 'Unexpected error'): AppError {
|
||||
return { type: 'unexpected', message };
|
||||
},
|
||||
};
|
||||
20
apps/backend/src/lib/http/error-handler.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
// http/error-handler.ts
|
||||
import type { MiddlewareHandler } from 'hono';
|
||||
import { logger } from '../logger';
|
||||
import { unexpectedProblem } from './problem-builders';
|
||||
|
||||
export const errorHandler: MiddlewareHandler = async (c, next) => {
|
||||
try {
|
||||
await next();
|
||||
} catch (error) {
|
||||
const requestId = c.get('requestId') as string | undefined;
|
||||
const instance = requestId ? `/requests/${requestId}` : undefined;
|
||||
|
||||
logger.error({
|
||||
requestId,
|
||||
error,
|
||||
});
|
||||
|
||||
return c.json(unexpectedProblem({ instance }), 500);
|
||||
}
|
||||
};
|
||||
20
apps/backend/src/lib/http/handle-result.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import type { Result } from '@/lib/result';
|
||||
import type { Context } from 'hono';
|
||||
import type { ContentfulStatusCode } from 'hono/utils/http-status';
|
||||
import { mapAppErrorToProblem } from './problem-mapper';
|
||||
|
||||
export function handleResult<T>(
|
||||
c: Context,
|
||||
result: Result<T>,
|
||||
successStatus: ContentfulStatusCode = 200
|
||||
) {
|
||||
if (!result.ok) {
|
||||
const requestId = c.get('requestId') as string | undefined;
|
||||
const instance = requestId ? `/requests/${requestId}` : undefined;
|
||||
const problem = mapAppErrorToProblem(result.error, instance);
|
||||
|
||||
return c.json(problem, problem.status);
|
||||
}
|
||||
|
||||
return c.json(result.value, successStatus);
|
||||
}
|
||||
29
apps/backend/src/lib/http/problem-builders.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
// http/problem-builders.ts
|
||||
import type { ProblemDetails } from './problem-details';
|
||||
|
||||
export function validationProblem(params: {
|
||||
detail?: string;
|
||||
instance?: string;
|
||||
errors?: Record<string, string[]>;
|
||||
}): ProblemDetails {
|
||||
return {
|
||||
type: 'https://api.myapp.dev/problems/validation',
|
||||
title: 'Bad Request',
|
||||
status: 400,
|
||||
detail: params.detail ?? 'Invalid request data',
|
||||
instance: params.instance,
|
||||
errors: params.errors,
|
||||
};
|
||||
}
|
||||
|
||||
export function unexpectedProblem(params?: {
|
||||
instance?: string;
|
||||
}): ProblemDetails {
|
||||
return {
|
||||
type: 'https://api.myapp.dev/problems/unexpected',
|
||||
title: 'Internal Server Error',
|
||||
status: 500,
|
||||
detail: 'Internal server error',
|
||||
instance: params?.instance,
|
||||
};
|
||||
}
|
||||
10
apps/backend/src/lib/http/problem-details.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import type { ContentfulStatusCode } from 'hono/utils/http-status';
|
||||
|
||||
export type ProblemDetails = {
|
||||
type: string;
|
||||
title: string;
|
||||
status: ContentfulStatusCode;
|
||||
detail?: string;
|
||||
instance?: string;
|
||||
errors?: Record<string, string[]>;
|
||||
};
|
||||
51
apps/backend/src/lib/http/problem-mapper.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import type { AppError } from '@/lib/errors';
|
||||
import type { ContentfulStatusCode } from 'hono/utils/http-status';
|
||||
import type { ProblemDetails } from './problem-details';
|
||||
|
||||
function statusFromError(error: AppError): ContentfulStatusCode {
|
||||
switch (error.type) {
|
||||
case 'validation':
|
||||
return 400;
|
||||
case 'unauthorized':
|
||||
return 401;
|
||||
case 'forbidden':
|
||||
return 403;
|
||||
case 'not_found':
|
||||
return 404;
|
||||
case 'conflict':
|
||||
return 409;
|
||||
case 'unexpected':
|
||||
return 500;
|
||||
default:
|
||||
return 500;
|
||||
}
|
||||
}
|
||||
|
||||
function titleFromStatus(status: ContentfulStatusCode): string {
|
||||
switch (status) {
|
||||
case 400:
|
||||
return 'Bad Request';
|
||||
case 401:
|
||||
return 'Unauthorized';
|
||||
case 403:
|
||||
return 'Forbidden';
|
||||
case 404:
|
||||
return 'Not Found';
|
||||
case 409:
|
||||
return 'Conflict';
|
||||
default:
|
||||
return 'Internal Server Error';
|
||||
}
|
||||
}
|
||||
|
||||
export function mapAppErrorToProblem(error: AppError, instance?: string): ProblemDetails {
|
||||
const status = statusFromError(error);
|
||||
|
||||
return {
|
||||
type: `https://api.myapp.dev/problems/${error.type}`,
|
||||
title: titleFromStatus(status),
|
||||
status,
|
||||
detail: status === 500 ? 'Internal server error' : error.message,
|
||||
instance,
|
||||
};
|
||||
}
|
||||
16
apps/backend/src/lib/http/request-id.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import type { MiddlewareHandler } from 'hono';
|
||||
|
||||
type Env = {
|
||||
Variables: {
|
||||
requestId: string;
|
||||
};
|
||||
};
|
||||
|
||||
export const requestIdMiddleware: MiddlewareHandler<Env> = async (c, next) => {
|
||||
const requestId = crypto.randomUUID();
|
||||
|
||||
c.set('requestId', requestId);
|
||||
c.header('X-Request-Id', requestId);
|
||||
|
||||
await next();
|
||||
};
|
||||
48
apps/backend/src/lib/http/validate.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import { zValidator } from '@hono/zod-validator';
|
||||
import type { ZodSchema } from 'zod';
|
||||
import { validationProblem } from './problem-builders';
|
||||
import { zodIssuesToRecord } from './zod-issues';
|
||||
|
||||
type ValidationTarget = 'json' | 'query' | 'param' | 'header' | 'form';
|
||||
|
||||
function makeValidator<TSchema extends ZodSchema>(target: ValidationTarget, schema: TSchema) {
|
||||
return zValidator(target, schema, (result, c) => {
|
||||
if (result.success) {
|
||||
return;
|
||||
}
|
||||
|
||||
const requestId = c.get('requestId') as string | undefined;
|
||||
const instance = requestId ? `/requests/${requestId}` : undefined;
|
||||
|
||||
return c.json(
|
||||
validationProblem({
|
||||
detail: `Invalid ${target} data`,
|
||||
instance,
|
||||
errors: zodIssuesToRecord(result.error.issues),
|
||||
}),
|
||||
400
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export const validate = {
|
||||
json<TSchema extends ZodSchema>(schema: TSchema) {
|
||||
return makeValidator('json', schema);
|
||||
},
|
||||
|
||||
query<TSchema extends ZodSchema>(schema: TSchema) {
|
||||
return makeValidator('query', schema);
|
||||
},
|
||||
|
||||
param<TSchema extends ZodSchema>(schema: TSchema) {
|
||||
return makeValidator('param', schema);
|
||||
},
|
||||
|
||||
header<TSchema extends ZodSchema>(schema: TSchema) {
|
||||
return makeValidator('header', schema);
|
||||
},
|
||||
|
||||
form<TSchema extends ZodSchema>(schema: TSchema) {
|
||||
return makeValidator('form', schema);
|
||||
},
|
||||
};
|
||||
16
apps/backend/src/lib/http/zod-issues.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
type IssueLike = {
|
||||
path: PropertyKey[];
|
||||
message: string;
|
||||
};
|
||||
|
||||
export function zodIssuesToRecord(issues: IssueLike[]): Record<string, string[]> {
|
||||
const out: Record<string, string[]> = {};
|
||||
|
||||
for (const issue of issues) {
|
||||
const key = issue.path.length ? issue.path.join('.') : 'root';
|
||||
out[key] ??= [];
|
||||
out[key].push(issue.message);
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
12
apps/backend/src/lib/result.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
// lib/result.ts
|
||||
import type { AppError } from '@/lib/errors';
|
||||
|
||||
export type Result<T, E = AppError> = { ok: true; value: T } | { ok: false; error: E };
|
||||
|
||||
export function ok<T>(value: T): Result<T> {
|
||||
return { ok: true, value };
|
||||
}
|
||||
|
||||
export function err<E>(error: E): Result<never, E> {
|
||||
return { ok: false, error };
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
AdminBookingServiceError,
|
||||
createAdminBooking,
|
||||
} from '@/modules/admin-booking/services/admin-booking.service';
|
||||
import { sendBookingConfirmation } from '@/services/booking-email.service';
|
||||
import type { AppContext } from '@/types/hono';
|
||||
import type { CreateAdminBookingInput } from '@repo/api-contract';
|
||||
|
||||
@@ -14,6 +15,20 @@ export async function createAdminBookingHandler(c: AppContext) {
|
||||
|
||||
try {
|
||||
const booking = await createAdminBooking(user.id, complexId, payload);
|
||||
|
||||
void sendBookingConfirmation({
|
||||
bookingCode: booking.bookingCode,
|
||||
complexName: booking.complexName,
|
||||
date: booking.date,
|
||||
startTime: booking.startTime,
|
||||
endTime: booking.endTime,
|
||||
courtName: booking.courtName,
|
||||
sportName: booking.sport.name,
|
||||
customerName: booking.customerName,
|
||||
customerEmail: booking.customerEmail,
|
||||
price: booking.price,
|
||||
});
|
||||
|
||||
return c.json(booking, 201);
|
||||
} catch (error) {
|
||||
if (error instanceof AdminBookingServiceError) {
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
AdminBookingServiceError,
|
||||
updateAdminBookingStatus,
|
||||
} from '@/modules/admin-booking/services/admin-booking.service';
|
||||
import { sendBookingCancelled, sendBookingNoShow } from '@/services/booking-email.service';
|
||||
import type { AppContext } from '@/types/hono';
|
||||
import type { UpdateAdminBookingStatusInput } from '@repo/api-contract';
|
||||
|
||||
@@ -14,6 +15,33 @@ export async function updateAdminBookingStatusHandler(c: AppContext) {
|
||||
|
||||
try {
|
||||
const booking = await updateAdminBookingStatus(user.id, id, payload);
|
||||
|
||||
if (payload.status === 'CANCELLED') {
|
||||
void sendBookingCancelled({
|
||||
bookingCode: booking.bookingCode,
|
||||
complexName: booking.complexName,
|
||||
date: booking.date,
|
||||
startTime: booking.startTime,
|
||||
endTime: booking.endTime,
|
||||
courtName: booking.courtName,
|
||||
sportName: booking.sport.name,
|
||||
customerName: booking.customerName,
|
||||
customerEmail: booking.customerEmail,
|
||||
});
|
||||
} else if (payload.status === 'NOSHOW') {
|
||||
void sendBookingNoShow({
|
||||
bookingCode: booking.bookingCode,
|
||||
complexName: booking.complexName,
|
||||
date: booking.date,
|
||||
startTime: booking.startTime,
|
||||
endTime: booking.endTime,
|
||||
courtName: booking.courtName,
|
||||
sportName: booking.sport.name,
|
||||
customerName: booking.customerName,
|
||||
customerEmail: booking.customerEmail,
|
||||
});
|
||||
}
|
||||
|
||||
return c.json(booking);
|
||||
} catch (error) {
|
||||
if (error instanceof AdminBookingServiceError) {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { randomInt } from 'node:crypto';
|
||||
import { CourtBookingStatus } from '@/generated/prisma/enums';
|
||||
import { db } from '@/lib/prisma';
|
||||
import { evaluatePlanUsage, parsePlanRules } from '@/modules/plan/services/plan-rules.service';
|
||||
import type { DayOfWeek } from '@repo/api-contract';
|
||||
import type {
|
||||
AdminBooking,
|
||||
CreateAdminBookingInput,
|
||||
@@ -156,6 +157,40 @@ async function ensureComplexAccess(complexId: string, userId: string) {
|
||||
return complexUser.complex;
|
||||
}
|
||||
|
||||
function resolvePrice(
|
||||
court: {
|
||||
basePrice: unknown;
|
||||
priceRules: Array<{
|
||||
dayOfWeek: string | null;
|
||||
startTime: string | null;
|
||||
endTime: string | null;
|
||||
price: unknown;
|
||||
}>;
|
||||
},
|
||||
dayOfWeek: string,
|
||||
startTime: string,
|
||||
endTime: string
|
||||
): number {
|
||||
const slotStart = toMinutes(startTime);
|
||||
const slotEnd = toMinutes(endTime);
|
||||
|
||||
const matchingRules = court.priceRules
|
||||
.filter((rule) => {
|
||||
if (rule.dayOfWeek && rule.dayOfWeek !== dayOfWeek) return false;
|
||||
if (!rule.startTime || !rule.endTime) return true;
|
||||
return slotStart >= toMinutes(rule.startTime) && slotEnd <= toMinutes(rule.endTime);
|
||||
})
|
||||
.sort((first, second) => {
|
||||
const firstSpecificity =
|
||||
(first.dayOfWeek ? 2 : 0) + (first.startTime && first.endTime ? 1 : 0);
|
||||
const secondSpecificity =
|
||||
(second.dayOfWeek ? 2 : 0) + (second.startTime && second.endTime ? 1 : 0);
|
||||
return secondSpecificity - firstSpecificity;
|
||||
});
|
||||
|
||||
return Number(matchingRules[0]?.price ?? court.basePrice);
|
||||
}
|
||||
|
||||
function mapBookingResponse(booking: {
|
||||
id: string;
|
||||
bookingCode: string;
|
||||
@@ -164,7 +199,8 @@ function mapBookingResponse(booking: {
|
||||
endTime: string;
|
||||
customerName: string;
|
||||
customerPhone: string;
|
||||
status: 'CONFIRMED' | 'CANCELLED' | 'COMPLETED';
|
||||
customerEmail: string | null;
|
||||
status: 'CONFIRMED' | 'CANCELLED' | 'COMPLETED' | 'NOSHOW';
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
court: {
|
||||
@@ -180,6 +216,7 @@ function mapBookingResponse(booking: {
|
||||
slug: string;
|
||||
};
|
||||
};
|
||||
price?: number;
|
||||
}): AdminBooking {
|
||||
return {
|
||||
id: booking.id,
|
||||
@@ -198,6 +235,8 @@ function mapBookingResponse(booking: {
|
||||
endTime: booking.endTime,
|
||||
customerName: booking.customerName,
|
||||
customerPhone: booking.customerPhone,
|
||||
customerEmail: booking.customerEmail ?? undefined,
|
||||
price: booking.price ?? 0,
|
||||
status: booking.status,
|
||||
createdAt: booking.createdAt.toISOString(),
|
||||
updatedAt: booking.updatedAt.toISOString(),
|
||||
@@ -258,6 +297,16 @@ export async function createAdminBooking(
|
||||
input: CreateAdminBookingInput
|
||||
) {
|
||||
const complex = await ensureComplexAccess(complexId, userId);
|
||||
|
||||
const adminUser = await db.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { emailVerified: true },
|
||||
});
|
||||
|
||||
if (!adminUser?.emailVerified) {
|
||||
throw new AdminBookingServiceError('Debés verificar tu email para poder crear reservas.', 403);
|
||||
}
|
||||
|
||||
const bookingDate = parseIsoDate(input.date);
|
||||
const dayOfWeek = getDayOfWeek(bookingDate);
|
||||
|
||||
@@ -282,6 +331,10 @@ export async function createAdminBooking(
|
||||
slug: true,
|
||||
},
|
||||
},
|
||||
priceRules: {
|
||||
where: { isActive: true },
|
||||
orderBy: [{ dayOfWeek: 'asc' }, { startTime: 'asc' }],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -371,6 +424,7 @@ export async function createAdminBooking(
|
||||
endTime: selectedSlot.endTime,
|
||||
customerName: input.customerName.trim(),
|
||||
customerPhone: input.customerPhone.trim(),
|
||||
customerEmail: input.customerEmail?.trim() || null,
|
||||
status: 'CONFIRMED',
|
||||
},
|
||||
include: {
|
||||
@@ -397,7 +451,9 @@ export async function createAdminBooking(
|
||||
});
|
||||
});
|
||||
|
||||
return mapBookingResponse(booking);
|
||||
const price = resolvePrice(court, dayOfWeek, selectedSlot.startTime, selectedSlot.endTime);
|
||||
|
||||
return mapBookingResponse({ ...booking, price });
|
||||
} catch (error) {
|
||||
if (error instanceof AdminBookingServiceError) {
|
||||
throw error;
|
||||
@@ -494,34 +550,43 @@ export async function updateAdminBookingStatus(
|
||||
);
|
||||
}
|
||||
|
||||
const updated = await db.courtBooking.update({
|
||||
where: { id: booking.id },
|
||||
if (input.status === 'NOSHOW' && booking.status !== 'CONFIRMED') {
|
||||
throw new AdminBookingServiceError(
|
||||
'Solo se pueden marcar como no show las reservas confirmadas.',
|
||||
409
|
||||
);
|
||||
}
|
||||
|
||||
await db.courtBookingLog.create({
|
||||
data: {
|
||||
status:
|
||||
input.status === 'COMPLETED' ? CourtBookingStatus.COMPLETED : CourtBookingStatus.CANCELLED,
|
||||
},
|
||||
include: {
|
||||
court: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
sport: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
slug: true,
|
||||
},
|
||||
},
|
||||
complex: {
|
||||
select: {
|
||||
id: true,
|
||||
complexName: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
id: uuidv7(),
|
||||
bookingCode: booking.bookingCode,
|
||||
courtId: booking.court.id,
|
||||
bookingDate: booking.bookingDate,
|
||||
startTime: booking.startTime,
|
||||
endTime: booking.endTime,
|
||||
customerName: booking.customerName,
|
||||
customerPhone: booking.customerPhone,
|
||||
customerEmail: booking.customerEmail,
|
||||
previousStatus: booking.status,
|
||||
newStatus: input.status,
|
||||
changedAt: new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
return mapBookingResponse(updated);
|
||||
if (input.status === 'COMPLETED' || input.status === 'NOSHOW') {
|
||||
await db.courtBooking.update({
|
||||
where: { id: booking.id },
|
||||
data: {
|
||||
status: input.status,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
// if the booking is cancelled we delete it to free up the slot, but we keep a log of it with the cancelled status
|
||||
await db.courtBooking.delete({
|
||||
where: { id: booking.id },
|
||||
});
|
||||
}
|
||||
|
||||
return mapBookingResponse({ ...booking, status: input.status });
|
||||
}
|
||||
|
||||
@@ -40,6 +40,11 @@ export async function createComplexHandler(c: AppContext) {
|
||||
city: payload.city,
|
||||
state: payload.state,
|
||||
country: payload.country,
|
||||
setupCourts: payload.setupCourts,
|
||||
courtSportId: payload.courtSportId,
|
||||
courtStartTime: payload.courtStartTime,
|
||||
courtEndTime: payload.courtEndTime,
|
||||
courtDaysOfWeek: payload.courtDaysOfWeek,
|
||||
});
|
||||
|
||||
return c.json(complex, 201);
|
||||
|
||||
@@ -11,8 +11,47 @@ export type CreateComplexInput = {
|
||||
city?: string;
|
||||
state?: string;
|
||||
country?: string;
|
||||
setupCourts?: boolean;
|
||||
courtSportId?: string;
|
||||
courtStartTime?: string;
|
||||
courtEndTime?: string;
|
||||
courtDaysOfWeek?: string[];
|
||||
};
|
||||
|
||||
type DayOfWeek = 'MONDAY' | 'TUESDAY' | 'WEDNESDAY' | 'THURSDAY' | 'FRIDAY' | 'SATURDAY' | 'SUNDAY';
|
||||
|
||||
function toMinutes(value: string): number {
|
||||
const [hours, minutes] = value.split(':').map((part) => Number(part));
|
||||
return hours * 60 + minutes;
|
||||
}
|
||||
|
||||
function assertAvailabilityRanges(
|
||||
availability: Array<{
|
||||
dayOfWeek: DayOfWeek;
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
}>
|
||||
) {
|
||||
for (const range of availability) {
|
||||
const start = toMinutes(range.startTime);
|
||||
const end = toMinutes(range.endTime);
|
||||
if (start >= end) {
|
||||
throw new Error(`El rango ${range.startTime}-${range.endTime} es inválido.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureActiveSport(sportId: string) {
|
||||
const sport = await db.sport.findFirst({
|
||||
where: { id: sportId, isActive: true },
|
||||
select: { id: true, name: true },
|
||||
});
|
||||
if (!sport) {
|
||||
throw new Error('El deporte seleccionado no existe o está inactivo.');
|
||||
}
|
||||
return sport;
|
||||
}
|
||||
|
||||
export type UpdateComplexInput = {
|
||||
complexName?: string;
|
||||
physicalAddress?: string | null;
|
||||
@@ -94,6 +133,38 @@ export async function createComplex(input: CreateComplexInput) {
|
||||
});
|
||||
}
|
||||
|
||||
if (input.setupCourts && input.courtSportId) {
|
||||
const sport = await ensureActiveSport(input.courtSportId);
|
||||
const availability = (input.courtDaysOfWeek ?? []).map((day) => ({
|
||||
dayOfWeek: day as DayOfWeek,
|
||||
startTime: input.courtStartTime ?? '08:00',
|
||||
endTime: input.courtEndTime ?? '22:00',
|
||||
}));
|
||||
|
||||
assertAvailabilityRanges(availability);
|
||||
|
||||
const court = await tx.court.create({
|
||||
data: {
|
||||
id: uuidv7(),
|
||||
complexId: complex.id,
|
||||
sportId: input.courtSportId,
|
||||
name: `${sport.name} 1`,
|
||||
slotDurationMinutes: 60,
|
||||
basePrice: 0,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.courtAvailability.createMany({
|
||||
data: availability.map((avail) => ({
|
||||
id: uuidv7(),
|
||||
courtId: court.id,
|
||||
dayOfWeek: avail.dayOfWeek,
|
||||
startTime: avail.startTime,
|
||||
endTime: avail.endTime,
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
return complex;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
import {
|
||||
OnboardingError,
|
||||
completeOnboarding,
|
||||
} from '@/modules/onboarding/services/onboarding.service';
|
||||
import type { AppContext } from '@/types/hono';
|
||||
import type { OnboardingCompleteInput } from '@repo/api-contract';
|
||||
|
||||
export async function completeOnboardingHandler(c: AppContext) {
|
||||
const payload = c.req.valid('json' as never) as OnboardingCompleteInput;
|
||||
|
||||
try {
|
||||
const result = await completeOnboarding(payload);
|
||||
return c.json({
|
||||
message: 'Onboarding completado correctamente.',
|
||||
...result,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof OnboardingError) {
|
||||
return c.json({ message: error.message }, error.status);
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
return c.json({ message: error.message }, 400);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
import {
|
||||
OnboardingError,
|
||||
resendOnboardingOtp,
|
||||
} from '@/modules/onboarding/services/onboarding.service';
|
||||
import type { AppContext } from '@/types/hono';
|
||||
import type { OnboardingResendOtpInput } from '@repo/api-contract';
|
||||
|
||||
export async function resendOtpHandler(c: AppContext) {
|
||||
const payload = c.req.valid('json' as never) as OnboardingResendOtpInput;
|
||||
|
||||
try {
|
||||
const result = await resendOnboardingOtp(payload);
|
||||
return c.json(result);
|
||||
} catch (error) {
|
||||
if (error instanceof OnboardingError) {
|
||||
return c.json({ message: error.message }, error.status);
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
return c.json({ message: error.message }, 400);
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
import { startOnboarding } from '@/modules/onboarding/services/onboarding.service';
|
||||
import type { AppContext } from '@/types/hono';
|
||||
import type { OnboardingStartInput } from '@repo/api-contract';
|
||||
|
||||
export async function startOnboardingHandler(c: AppContext) {
|
||||
const payload = c.req.valid('json' as never) as OnboardingStartInput;
|
||||
|
||||
const result = await startOnboarding(payload);
|
||||
return c.json(result, 202);
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
import { verifyOnboardingOtp } from '@/modules/onboarding/services/onboarding.service';
|
||||
import type { AppContext } from '@/types/hono';
|
||||
import type { OnboardingVerifyOtpInput } from '@repo/api-contract';
|
||||
|
||||
export async function verifyOtpHandler(c: AppContext) {
|
||||
const payload = c.req.valid('json' as never) as OnboardingVerifyOtpInput;
|
||||
const result = await verifyOnboardingOtp(payload);
|
||||
|
||||
return c.json(result);
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
import { completeOnboardingHandler } from '@/modules/onboarding/handlers/complete-onboarding.handler';
|
||||
import { resendOtpHandler } from '@/modules/onboarding/handlers/resend-otp.handler';
|
||||
import { startOnboardingHandler } from '@/modules/onboarding/handlers/start-onboarding.handler';
|
||||
import { verifyOtpHandler } from '@/modules/onboarding/handlers/verify-otp.handler';
|
||||
import type { AppEnv } from '@/types/hono';
|
||||
import { zValidator } from '@hono/zod-validator';
|
||||
import {
|
||||
onboardingCompleteSchema,
|
||||
onboardingResendOtpSchema,
|
||||
onboardingStartSchema,
|
||||
onboardingVerifyOtpSchema,
|
||||
} from '@repo/api-contract';
|
||||
import { Hono } from 'hono';
|
||||
|
||||
export const onboardingRoutes = new Hono<AppEnv>();
|
||||
|
||||
onboardingRoutes.post('/start', zValidator('json', onboardingStartSchema), startOnboardingHandler);
|
||||
|
||||
onboardingRoutes.post(
|
||||
'/verify-otp',
|
||||
zValidator('json', onboardingVerifyOtpSchema),
|
||||
verifyOtpHandler
|
||||
);
|
||||
|
||||
onboardingRoutes.post(
|
||||
'/resend-otp',
|
||||
zValidator('json', onboardingResendOtpSchema),
|
||||
resendOtpHandler
|
||||
);
|
||||
|
||||
onboardingRoutes.post(
|
||||
'/complete',
|
||||
zValidator('json', onboardingCompleteSchema),
|
||||
completeOnboardingHandler
|
||||
);
|
||||
@@ -1,415 +0,0 @@
|
||||
import { createHash, randomInt } from 'node:crypto';
|
||||
import { auth } from '@/lib/auth';
|
||||
import { sendMail } from '@/lib/mailer';
|
||||
import { db } from '@/lib/prisma';
|
||||
import type {
|
||||
OnboardingCompleteInput,
|
||||
OnboardingResendOtpInput,
|
||||
OnboardingStartInput,
|
||||
OnboardingVerifyOtpInput,
|
||||
} from '@repo/api-contract';
|
||||
import { v7 as uuidv7 } from 'uuid';
|
||||
|
||||
const OTP_LENGTH = 6;
|
||||
const OTP_TTL_MINUTES = Number(Bun.env.ONBOARDING_OTP_TTL_MINUTES ?? 10);
|
||||
const OTP_MAX_ATTEMPTS = Number(Bun.env.ONBOARDING_OTP_MAX_ATTEMPTS ?? 5);
|
||||
const OTP_RESEND_COOLDOWN_SECONDS = Number(Bun.env.ONBOARDING_OTP_RESEND_COOLDOWN_SECONDS ?? 30);
|
||||
|
||||
type VerifyOtpResult = {
|
||||
message: string;
|
||||
verified: boolean;
|
||||
requestId: string;
|
||||
email: string | null;
|
||||
expiresAt: string | null;
|
||||
remainingAttempts: number;
|
||||
cooldownSeconds: number;
|
||||
};
|
||||
|
||||
type ResendOtpResult = {
|
||||
message: string;
|
||||
requestId: string;
|
||||
email: string;
|
||||
expiresAt: string;
|
||||
cooldownSeconds: number;
|
||||
remainingAttempts: number;
|
||||
};
|
||||
|
||||
type StartOnboardingResult = {
|
||||
message: string;
|
||||
requestId: string;
|
||||
email: string;
|
||||
expiresAt: string;
|
||||
cooldownSeconds: number;
|
||||
};
|
||||
|
||||
export class OnboardingError extends Error {
|
||||
status: 400 | 404 | 409 | 429;
|
||||
|
||||
constructor(message: string, status: 400 | 404 | 409 | 429 = 400) {
|
||||
super(message);
|
||||
this.name = 'OnboardingError';
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
function nowPlusMinutes(minutes: number): Date {
|
||||
const date = new Date();
|
||||
date.setMinutes(date.getMinutes() + minutes);
|
||||
return date;
|
||||
}
|
||||
|
||||
function normalizeEmail(email: string): string {
|
||||
return email.trim().toLowerCase();
|
||||
}
|
||||
|
||||
function createOtpCode(): string {
|
||||
return randomInt(0, 10 ** OTP_LENGTH)
|
||||
.toString()
|
||||
.padStart(OTP_LENGTH, '0');
|
||||
}
|
||||
|
||||
function hashValue(value: string): string {
|
||||
return createHash('sha256').update(value).digest('hex');
|
||||
}
|
||||
|
||||
function getRemainingAttempts(otpAttempts: number): number {
|
||||
return Math.max(0, OTP_MAX_ATTEMPTS - otpAttempts);
|
||||
}
|
||||
|
||||
function getCooldownSeconds(otpLastSentAt: Date): number {
|
||||
const elapsedMs = Date.now() - otpLastSentAt.getTime();
|
||||
const remainingMs = OTP_RESEND_COOLDOWN_SECONDS * 1000 - elapsedMs;
|
||||
return Math.max(0, Math.ceil(remainingMs / 1000));
|
||||
}
|
||||
|
||||
function slugify(value: string): string {
|
||||
return value
|
||||
.normalize('NFD')
|
||||
.replace(/[\u0300-\u036f]/g, '')
|
||||
.toLowerCase()
|
||||
.trim()
|
||||
.replace(/[^a-z0-9\s-]/g, '')
|
||||
.replace(/\s+/g, '-')
|
||||
.replace(/-+/g, '-');
|
||||
}
|
||||
|
||||
async function buildUniqueComplexSlug(complexName: string): Promise<string> {
|
||||
const base = slugify(complexName);
|
||||
const fallback = base.length > 0 ? base : `complex-${uuidv7().slice(0, 8)}`;
|
||||
|
||||
let candidate = fallback;
|
||||
let index = 1;
|
||||
|
||||
while (true) {
|
||||
const existing = await db.complex.findFirst({
|
||||
where: { complexSlug: candidate },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (!existing) {
|
||||
return candidate;
|
||||
}
|
||||
|
||||
index += 1;
|
||||
candidate = `${fallback}-${index}`;
|
||||
}
|
||||
}
|
||||
|
||||
async function sendOtpEmail(email: string, otpCode: string) {
|
||||
await sendMail({
|
||||
to: email,
|
||||
subject: 'Codigo OTP para validar tu email',
|
||||
text: `Tu codigo OTP es ${otpCode}. Vence en ${OTP_TTL_MINUTES} minutos.`,
|
||||
html: `<p>Tu codigo OTP es <strong>${otpCode}</strong>.</p><p>Vence en ${OTP_TTL_MINUTES} minutos.</p>`,
|
||||
});
|
||||
}
|
||||
|
||||
export async function startOnboarding(input: OnboardingStartInput): Promise<StartOnboardingResult> {
|
||||
const email = normalizeEmail(input.email);
|
||||
const otpCode = createOtpCode();
|
||||
const expiresAt = nowPlusMinutes(OTP_TTL_MINUTES);
|
||||
const now = new Date();
|
||||
|
||||
const request = await db.onboardingRequest.create({
|
||||
data: {
|
||||
id: uuidv7(),
|
||||
fullName: input.fullName.trim(),
|
||||
email,
|
||||
otpHash: hashValue(otpCode),
|
||||
otpExpiresAt: expiresAt,
|
||||
otpAttempts: 0,
|
||||
otpLastSentAt: now,
|
||||
otpResendCount: 0,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
otpExpiresAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
await sendOtpEmail(email, otpCode);
|
||||
|
||||
return {
|
||||
message: 'Te enviamos un codigo OTP para validar tu direccion.',
|
||||
requestId: request.id,
|
||||
email: request.email,
|
||||
expiresAt: request.otpExpiresAt.toISOString(),
|
||||
cooldownSeconds: OTP_RESEND_COOLDOWN_SECONDS,
|
||||
};
|
||||
}
|
||||
|
||||
export async function verifyOnboardingOtp(
|
||||
input: OnboardingVerifyOtpInput
|
||||
): Promise<VerifyOtpResult> {
|
||||
const request = await db.onboardingRequest.findUnique({
|
||||
where: { id: input.requestId },
|
||||
});
|
||||
|
||||
if (!request) {
|
||||
return {
|
||||
message: 'Solicitud de onboarding invalida o expirada.',
|
||||
verified: false,
|
||||
requestId: input.requestId,
|
||||
email: null,
|
||||
expiresAt: null,
|
||||
remainingAttempts: 0,
|
||||
cooldownSeconds: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (request.completedAt) {
|
||||
return {
|
||||
message: 'Este onboarding ya fue completado.',
|
||||
verified: true,
|
||||
requestId: request.id,
|
||||
email: request.email,
|
||||
expiresAt: request.otpExpiresAt.toISOString(),
|
||||
remainingAttempts: getRemainingAttempts(request.otpAttempts),
|
||||
cooldownSeconds: getCooldownSeconds(request.otpLastSentAt),
|
||||
};
|
||||
}
|
||||
|
||||
if (request.otpExpiresAt < new Date()) {
|
||||
return {
|
||||
message: 'El codigo OTP vencio. Solicita un nuevo codigo.',
|
||||
verified: false,
|
||||
requestId: request.id,
|
||||
email: request.email,
|
||||
expiresAt: request.otpExpiresAt.toISOString(),
|
||||
remainingAttempts: getRemainingAttempts(request.otpAttempts),
|
||||
cooldownSeconds: getCooldownSeconds(request.otpLastSentAt),
|
||||
};
|
||||
}
|
||||
|
||||
if (request.otpAttempts >= OTP_MAX_ATTEMPTS) {
|
||||
return {
|
||||
message: 'Se agotaron los intentos de OTP. Solicita un nuevo codigo.',
|
||||
verified: false,
|
||||
requestId: request.id,
|
||||
email: request.email,
|
||||
expiresAt: request.otpExpiresAt.toISOString(),
|
||||
remainingAttempts: 0,
|
||||
cooldownSeconds: getCooldownSeconds(request.otpLastSentAt),
|
||||
};
|
||||
}
|
||||
|
||||
const otpMatches = hashValue(input.otp) === request.otpHash;
|
||||
|
||||
if (!otpMatches) {
|
||||
const updated = await db.onboardingRequest.update({
|
||||
where: { id: request.id },
|
||||
data: {
|
||||
otpAttempts: {
|
||||
increment: 1,
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
otpAttempts: true,
|
||||
otpExpiresAt: true,
|
||||
otpLastSentAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
const remainingAttempts = getRemainingAttempts(updated.otpAttempts);
|
||||
|
||||
return {
|
||||
message:
|
||||
remainingAttempts > 0
|
||||
? 'Codigo OTP invalido.'
|
||||
: 'Se agotaron los intentos de OTP. Solicita un nuevo codigo.',
|
||||
verified: false,
|
||||
requestId: updated.id,
|
||||
email: updated.email,
|
||||
expiresAt: updated.otpExpiresAt.toISOString(),
|
||||
remainingAttempts,
|
||||
cooldownSeconds: getCooldownSeconds(updated.otpLastSentAt),
|
||||
};
|
||||
}
|
||||
|
||||
if (!request.emailVerifiedAt) {
|
||||
await db.onboardingRequest.update({
|
||||
where: { id: request.id },
|
||||
data: { emailVerifiedAt: new Date() },
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
message: 'Email verificado correctamente.',
|
||||
verified: true,
|
||||
requestId: request.id,
|
||||
email: request.email,
|
||||
expiresAt: request.otpExpiresAt.toISOString(),
|
||||
remainingAttempts: getRemainingAttempts(request.otpAttempts),
|
||||
cooldownSeconds: getCooldownSeconds(request.otpLastSentAt),
|
||||
};
|
||||
}
|
||||
|
||||
export async function resendOnboardingOtp(
|
||||
input: OnboardingResendOtpInput
|
||||
): Promise<ResendOtpResult> {
|
||||
const request = await db.onboardingRequest.findUnique({
|
||||
where: { id: input.requestId },
|
||||
});
|
||||
|
||||
if (!request) {
|
||||
throw new OnboardingError('Solicitud de onboarding invalida o expirada.', 404);
|
||||
}
|
||||
|
||||
if (request.completedAt) {
|
||||
throw new OnboardingError('Este onboarding ya fue completado.', 400);
|
||||
}
|
||||
|
||||
if (request.emailVerifiedAt) {
|
||||
throw new OnboardingError('El email ya fue verificado.', 400);
|
||||
}
|
||||
|
||||
const cooldownSeconds = getCooldownSeconds(request.otpLastSentAt);
|
||||
if (cooldownSeconds > 0) {
|
||||
throw new OnboardingError(`Debes esperar ${cooldownSeconds}s antes de reenviar el OTP.`, 429);
|
||||
}
|
||||
|
||||
const otpCode = createOtpCode();
|
||||
const expiresAt = nowPlusMinutes(OTP_TTL_MINUTES);
|
||||
const now = new Date();
|
||||
|
||||
const updated = await db.onboardingRequest.update({
|
||||
where: { id: request.id },
|
||||
data: {
|
||||
otpHash: hashValue(otpCode),
|
||||
otpExpiresAt: expiresAt,
|
||||
otpAttempts: 0,
|
||||
otpLastSentAt: now,
|
||||
otpResendCount: {
|
||||
increment: 1,
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
otpExpiresAt: true,
|
||||
otpAttempts: true,
|
||||
},
|
||||
});
|
||||
|
||||
await sendOtpEmail(updated.email, otpCode);
|
||||
|
||||
return {
|
||||
message: 'Te enviamos un nuevo codigo OTP.',
|
||||
requestId: updated.id,
|
||||
email: updated.email,
|
||||
expiresAt: updated.otpExpiresAt.toISOString(),
|
||||
cooldownSeconds: OTP_RESEND_COOLDOWN_SECONDS,
|
||||
remainingAttempts: getRemainingAttempts(updated.otpAttempts),
|
||||
};
|
||||
}
|
||||
|
||||
export async function completeOnboarding(input: OnboardingCompleteInput) {
|
||||
const onboardingRequest = await db.onboardingRequest.findUnique({
|
||||
where: { id: input.onboardingRequestId },
|
||||
});
|
||||
|
||||
if (!onboardingRequest) {
|
||||
throw new OnboardingError('Solicitud de onboarding inválida o expirada.', 400);
|
||||
}
|
||||
|
||||
if (onboardingRequest.otpExpiresAt < new Date()) {
|
||||
throw new OnboardingError('La sesión de onboarding expiró. Solicita un nuevo OTP.', 400);
|
||||
}
|
||||
|
||||
if (!onboardingRequest.emailVerifiedAt) {
|
||||
throw new OnboardingError('Debes verificar el email antes de continuar.', 400);
|
||||
}
|
||||
|
||||
if (onboardingRequest.completedAt) {
|
||||
throw new OnboardingError('Este onboarding ya fue completado.', 400);
|
||||
}
|
||||
|
||||
const plan = await db.plan.findUnique({
|
||||
where: { code: input.planCode },
|
||||
select: { code: true },
|
||||
});
|
||||
|
||||
if (!plan) {
|
||||
throw new OnboardingError('El plan seleccionado no existe.', 400);
|
||||
}
|
||||
|
||||
const { user } = await auth.api.signUpEmail({
|
||||
asResponse: false,
|
||||
body: {
|
||||
email: onboardingRequest.email,
|
||||
password: input.password,
|
||||
name: onboardingRequest.fullName,
|
||||
},
|
||||
});
|
||||
|
||||
const complexSlug = await buildUniqueComplexSlug(input.complexName);
|
||||
|
||||
const result = await db.$transaction(async (tx) => {
|
||||
await tx.user.update({
|
||||
where: { id: user.id },
|
||||
data: { emailVerified: true },
|
||||
});
|
||||
|
||||
const complex = await tx.complex.create({
|
||||
data: {
|
||||
id: uuidv7(),
|
||||
complexName: input.complexName.trim(),
|
||||
physicalAddress: input.physicalAddress.trim(),
|
||||
city: input.city?.trim() || null,
|
||||
state: input.state?.trim() || null,
|
||||
country: input.country?.trim() || null,
|
||||
complexSlug,
|
||||
adminEmail: onboardingRequest.email,
|
||||
planCode: input.planCode,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.complexUser.create({
|
||||
data: {
|
||||
complexId: complex.id,
|
||||
userId: user.id,
|
||||
role: 'ADMIN',
|
||||
},
|
||||
});
|
||||
|
||||
await tx.onboardingRequest.update({
|
||||
where: { id: onboardingRequest.id },
|
||||
data: {
|
||||
completedAt: new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
userId: user.id,
|
||||
complexId: complex.id,
|
||||
complexSlug: complex.complexSlug,
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
...result,
|
||||
};
|
||||
}
|
||||
@@ -1,23 +1,24 @@
|
||||
import { db } from '@/lib/prisma';
|
||||
import { parsePlanRules } from '@/modules/plan/services/plan-rules.service';
|
||||
import type { AppContext } from '@/types/hono';
|
||||
|
||||
export async function listPlansHandler(c: AppContext) {
|
||||
const plans = await db.plan.findMany({
|
||||
select: {
|
||||
code: true,
|
||||
name: true,
|
||||
price: true,
|
||||
},
|
||||
orderBy: {
|
||||
price: 'asc',
|
||||
},
|
||||
});
|
||||
|
||||
return c.json(
|
||||
plans.map((plan) => ({
|
||||
code: plan.code,
|
||||
name: plan.name,
|
||||
price: Number(plan.price),
|
||||
}))
|
||||
plans.map((plan) => {
|
||||
const rules = parsePlanRules(plan.rules);
|
||||
return {
|
||||
code: plan.code,
|
||||
name: plan.name,
|
||||
price: Number(plan.price),
|
||||
features: rules.features,
|
||||
limits: rules.limits,
|
||||
};
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
PublicBookingServiceError,
|
||||
createPublicBooking,
|
||||
} from '@/modules/public-booking/services/public-booking.service';
|
||||
import { sendBookingConfirmation } from '@/services/booking-email.service';
|
||||
import type { AppContext } from '@/types/hono';
|
||||
import type { CreatePublicBookingInput } from '@repo/api-contract';
|
||||
|
||||
@@ -30,6 +31,19 @@ export async function createPublicBookingHandler(c: AppContext) {
|
||||
})
|
||||
);
|
||||
|
||||
void sendBookingConfirmation({
|
||||
bookingCode: booking.bookingCode,
|
||||
complexName: booking.complexName,
|
||||
date: booking.date,
|
||||
startTime: booking.startTime,
|
||||
endTime: booking.endTime,
|
||||
courtName: booking.courtName,
|
||||
sportName: booking.sport.name,
|
||||
customerName: booking.customerName,
|
||||
customerEmail: booking.customerEmail,
|
||||
price: booking.price,
|
||||
});
|
||||
|
||||
return c.json(booking, 201);
|
||||
} catch (error) {
|
||||
if (error instanceof PublicBookingServiceError) {
|
||||
|
||||
@@ -13,6 +13,16 @@ type Slot = {
|
||||
endTime: string;
|
||||
};
|
||||
|
||||
type PriceableCourt = {
|
||||
basePrice: unknown;
|
||||
priceRules: Array<{
|
||||
dayOfWeek: DayOfWeek | null;
|
||||
startTime: string | null;
|
||||
endTime: string | null;
|
||||
price: unknown;
|
||||
}>;
|
||||
};
|
||||
|
||||
type ComplexWithPublicBookingData = Awaited<ReturnType<typeof getComplexWithBookingData>>;
|
||||
|
||||
const DAY_OF_WEEK_BY_INDEX: DayOfWeek[] = [
|
||||
@@ -202,6 +212,10 @@ async function getComplexWithBookingData(complexSlug: string) {
|
||||
availabilities: {
|
||||
orderBy: [{ dayOfWeek: 'asc' }, { startTime: 'asc' }],
|
||||
},
|
||||
priceRules: {
|
||||
where: { isActive: true },
|
||||
orderBy: [{ dayOfWeek: 'asc' }, { startTime: 'asc' }],
|
||||
},
|
||||
},
|
||||
orderBy: { createdAt: 'asc' },
|
||||
},
|
||||
@@ -226,6 +240,33 @@ async function getComplexWithBookingData(complexSlug: string) {
|
||||
return complex;
|
||||
}
|
||||
|
||||
function resolveSlotPrice(court: PriceableCourt, dayOfWeek: DayOfWeek, slot: Slot): number {
|
||||
const slotStart = toMinutes(slot.startTime);
|
||||
const slotEnd = toMinutes(slot.endTime);
|
||||
const matchingRules = court.priceRules
|
||||
.filter((rule) => {
|
||||
if (rule.dayOfWeek && rule.dayOfWeek !== dayOfWeek) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!rule.startTime || !rule.endTime) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return slotStart >= toMinutes(rule.startTime) && slotEnd <= toMinutes(rule.endTime);
|
||||
})
|
||||
.sort((first, second) => {
|
||||
const firstSpecificity =
|
||||
(first.dayOfWeek ? 2 : 0) + (first.startTime && first.endTime ? 1 : 0);
|
||||
const secondSpecificity =
|
||||
(second.dayOfWeek ? 2 : 0) + (second.startTime && second.endTime ? 1 : 0);
|
||||
|
||||
return secondSpecificity - firstSpecificity;
|
||||
});
|
||||
|
||||
return Number(matchingRules[0]?.price ?? court.basePrice);
|
||||
}
|
||||
|
||||
function mapBookingResponse(input: {
|
||||
bookingId: string;
|
||||
bookingCode: string;
|
||||
@@ -235,7 +276,9 @@ function mapBookingResponse(input: {
|
||||
endTime: string;
|
||||
customerName: string;
|
||||
customerPhone: string;
|
||||
status: 'CONFIRMED' | 'CANCELLED' | 'COMPLETED';
|
||||
customerEmail: string | null;
|
||||
price: number;
|
||||
status: 'CONFIRMED' | 'CANCELLED' | 'COMPLETED' | 'NOSHOW';
|
||||
court: {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -263,7 +306,9 @@ function mapBookingResponse(input: {
|
||||
endTime: input.endTime,
|
||||
customerName: input.customerName,
|
||||
customerPhone: input.customerPhone,
|
||||
customerEmail: input.customerEmail ?? undefined,
|
||||
status: input.status,
|
||||
price: input.price,
|
||||
createdAt: input.createdAt.toISOString(),
|
||||
};
|
||||
}
|
||||
@@ -284,11 +329,17 @@ export async function getPublicBookingConfirmation(complexSlug: string, bookingC
|
||||
bookingDate: true,
|
||||
startTime: true,
|
||||
endTime: true,
|
||||
customerEmail: true,
|
||||
status: true,
|
||||
createdAt: true,
|
||||
court: {
|
||||
select: {
|
||||
name: true,
|
||||
basePrice: true,
|
||||
priceRules: {
|
||||
where: { isActive: true },
|
||||
orderBy: [{ dayOfWeek: 'asc' }, { startTime: 'asc' }],
|
||||
},
|
||||
sport: {
|
||||
select: {
|
||||
id: true,
|
||||
@@ -299,6 +350,7 @@ export async function getPublicBookingConfirmation(complexSlug: string, bookingC
|
||||
complex: {
|
||||
select: {
|
||||
complexName: true,
|
||||
physicalAddress: true,
|
||||
complexSlug: true,
|
||||
},
|
||||
},
|
||||
@@ -311,13 +363,22 @@ export async function getPublicBookingConfirmation(complexSlug: string, bookingC
|
||||
throw new PublicBookingServiceError('Reserva no encontrada.', 404);
|
||||
}
|
||||
|
||||
const date = formatIsoDate(booking.bookingDate);
|
||||
const { dayOfWeek } = parseIsoDate(date);
|
||||
const price = resolveSlotPrice(booking.court, dayOfWeek, {
|
||||
startTime: booking.startTime,
|
||||
endTime: booking.endTime,
|
||||
});
|
||||
|
||||
return {
|
||||
bookingCode: booking.bookingCode,
|
||||
complexName: booking.court.complex.complexName,
|
||||
complexAddress: booking.court.complex.physicalAddress ?? undefined,
|
||||
complexSlug: booking.court.complex.complexSlug,
|
||||
date: formatIsoDate(booking.bookingDate),
|
||||
date,
|
||||
startTime: booking.startTime,
|
||||
endTime: booking.endTime,
|
||||
price,
|
||||
courtName: booking.court.name,
|
||||
sport: {
|
||||
id: booking.court.sport.id,
|
||||
@@ -325,13 +386,39 @@ export async function getPublicBookingConfirmation(complexSlug: string, bookingC
|
||||
slug: booking.court.sport.slug,
|
||||
},
|
||||
status: booking.status,
|
||||
customerEmail: booking.customerEmail ?? undefined,
|
||||
createdAt: booking.createdAt.toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
async function hasVerifiedAdmin(complexId: string): Promise<boolean> {
|
||||
const verifiedAdmin = await db.complexUser.findFirst({
|
||||
where: {
|
||||
complexId,
|
||||
role: 'ADMIN',
|
||||
user: { emailVerified: true },
|
||||
},
|
||||
});
|
||||
return verifiedAdmin !== null;
|
||||
}
|
||||
|
||||
export async function listPublicAvailability(complexSlug: string, query: PublicAvailabilityQuery) {
|
||||
const { bookingDate, dayOfWeek } = parseIsoDate(query.date);
|
||||
const complex = await getComplexWithBookingData(complexSlug);
|
||||
|
||||
if (!(await hasVerifiedAdmin(complex.id))) {
|
||||
return {
|
||||
complexId: complex.id,
|
||||
complexName: complex.complexName,
|
||||
complexAddress: complex.physicalAddress ?? null,
|
||||
complexSlug: complex.complexSlug,
|
||||
date: query.date,
|
||||
sportSelectionRequired: false,
|
||||
sports: [],
|
||||
courts: [],
|
||||
};
|
||||
}
|
||||
|
||||
const sports = resolveSports(complex);
|
||||
const sportSelectionRequired = sports.length > 1;
|
||||
|
||||
@@ -407,7 +494,10 @@ export async function listPublicAvailability(complexSlug: string, query: PublicA
|
||||
},
|
||||
slotDurationMinutes: court.slotDurationMinutes,
|
||||
availabilityDay: dayOfWeek,
|
||||
availableSlots,
|
||||
availableSlots: availableSlots.map((slot) => ({
|
||||
...slot,
|
||||
price: resolveSlotPrice(court, dayOfWeek, slot),
|
||||
})),
|
||||
};
|
||||
})
|
||||
.filter((court) => court.availableSlots.length > 0);
|
||||
@@ -427,6 +517,14 @@ export async function listPublicAvailability(complexSlug: string, query: PublicA
|
||||
export async function createPublicBooking(complexSlug: string, input: CreatePublicBookingInput) {
|
||||
const { bookingDate, dayOfWeek } = parseIsoDate(input.date);
|
||||
const complex = await getComplexWithBookingData(complexSlug);
|
||||
|
||||
if (!(await hasVerifiedAdmin(complex.id))) {
|
||||
throw new PublicBookingServiceError(
|
||||
'El complejo no puede recibir reservas hasta que un administrador verifique su email.',
|
||||
403
|
||||
);
|
||||
}
|
||||
|
||||
const sports = resolveSports(complex);
|
||||
const { sportSelectionRequired } = validateSportSelection(sports, input.sportId);
|
||||
|
||||
@@ -533,6 +631,7 @@ export async function createPublicBooking(complexSlug: string, input: CreatePubl
|
||||
endTime: selectedSlot.endTime,
|
||||
customerName: input.customerName.trim(),
|
||||
customerPhone: input.customerPhone.trim(),
|
||||
customerEmail: input.customerEmail?.trim() || null,
|
||||
status: 'CONFIRMED',
|
||||
},
|
||||
select: {
|
||||
@@ -544,11 +643,14 @@ export async function createPublicBooking(complexSlug: string, input: CreatePubl
|
||||
endTime: true,
|
||||
customerName: true,
|
||||
customerPhone: true,
|
||||
customerEmail: true,
|
||||
status: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
const price = resolveSlotPrice(selectedCourt, dayOfWeek, selectedSlot);
|
||||
|
||||
return mapBookingResponse({
|
||||
bookingId: booking.id,
|
||||
bookingCode: booking.bookingCode,
|
||||
@@ -558,6 +660,8 @@ export async function createPublicBooking(complexSlug: string, input: CreatePubl
|
||||
endTime: booking.endTime,
|
||||
customerName: booking.customerName,
|
||||
customerPhone: booking.customerPhone,
|
||||
customerEmail: booking.customerEmail,
|
||||
price,
|
||||
status: booking.status,
|
||||
court: {
|
||||
id: selectedCourt.id,
|
||||
|
||||
@@ -1,18 +1,10 @@
|
||||
import { Prisma } from '@/generated/prisma/client';
|
||||
import { handleResult } from '@/lib/http/handle-result';
|
||||
import { createSport } from '@/modules/sport/services/sport.service';
|
||||
import type { AppContext } from '@/types/hono';
|
||||
import type { CreateSportInput } from '@repo/api-contract';
|
||||
|
||||
export async function createSportHandler(c: AppContext) {
|
||||
const payload = c.req.valid('json' as never) as CreateSportInput;
|
||||
|
||||
try {
|
||||
const sport = await createSport(payload);
|
||||
return c.json(sport, 201);
|
||||
} catch (error) {
|
||||
if (error instanceof Prisma.PrismaClientKnownRequestError) {
|
||||
return c.json({ message: 'No se pudo crear el deporte.' }, 409);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
return handleResult(c, await createSport(payload), 201);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { handleResult } from '@/lib/http/handle-result';
|
||||
import { listSports } from '@/modules/sport/services/sport.service';
|
||||
import type { AppContext } from '@/types/hono';
|
||||
|
||||
export async function listSportsHandler(c: AppContext) {
|
||||
const sports = await listSports();
|
||||
return c.json(sports);
|
||||
return handleResult(c, sports);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { Prisma } from '@/generated/prisma/client';
|
||||
import { Prisma, Sport } from '@/generated/prisma/client';
|
||||
import { Errors } from '@/lib/errors';
|
||||
import { db } from '@/lib/prisma';
|
||||
import { Result, err, ok } from '@/lib/result';
|
||||
import { v7 as uuidv7 } from 'uuid';
|
||||
|
||||
export type CreateSportInput = {
|
||||
@@ -51,16 +53,25 @@ async function buildUniqueSlug(source: string, excludeSportId?: string): Promise
|
||||
}
|
||||
}
|
||||
|
||||
export async function listSports() {
|
||||
return db.sport.findMany({
|
||||
export async function listSports(): Promise<Result<Sport[]>> {
|
||||
const sports = await db.sport.findMany({
|
||||
orderBy: { name: 'asc' },
|
||||
});
|
||||
return ok(sports);
|
||||
}
|
||||
|
||||
export async function createSport(input: CreateSportInput) {
|
||||
const slug = await buildUniqueSlug(input.name);
|
||||
|
||||
return db.sport.create({
|
||||
const existing = await db.sport.count({
|
||||
where: { slug },
|
||||
});
|
||||
|
||||
if (existing > 0) {
|
||||
return err(Errors.conflict('Ya existe un deporte con ese nombre.'));
|
||||
}
|
||||
|
||||
const created = await db.sport.create({
|
||||
data: {
|
||||
id: uuidv7(),
|
||||
name: input.name.trim(),
|
||||
@@ -68,6 +79,8 @@ export async function createSport(input: CreateSportInput) {
|
||||
isActive: true,
|
||||
},
|
||||
});
|
||||
|
||||
return ok(created);
|
||||
}
|
||||
|
||||
export async function getSportById(id: string) {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { validate } from '@/lib/http/validate';
|
||||
import { requireAuth } from '@/middlewares/require-auth.middleware';
|
||||
import { requireSuperAdmin } from '@/middlewares/require-super-admin.middleware';
|
||||
import { createSportHandler } from '@/modules/sport/handlers/create-sport.handler';
|
||||
@@ -8,18 +9,17 @@ import { zValidator } from '@hono/zod-validator';
|
||||
import { createSportSchema, updateSportSchema } from '@repo/api-contract';
|
||||
import { Hono } from 'hono';
|
||||
import { z } from 'zod';
|
||||
|
||||
export const sportRoutes = new Hono<AppEnv>();
|
||||
const sportIdParamsSchema = z.object({ id: z.uuid() });
|
||||
|
||||
sportRoutes.use('*', requireAuth);
|
||||
|
||||
sportRoutes.get('/', listSportsHandler);
|
||||
sportRoutes.post('/', requireSuperAdmin, zValidator('json', createSportSchema), createSportHandler);
|
||||
sportRoutes.post('/', requireSuperAdmin, validate.json(createSportSchema), createSportHandler);
|
||||
sportRoutes.patch(
|
||||
'/:id',
|
||||
requireSuperAdmin,
|
||||
zValidator('param', sportIdParamsSchema),
|
||||
zValidator('json', updateSportSchema),
|
||||
validate.param(sportIdParamsSchema),
|
||||
validate.json(updateSportSchema),
|
||||
updateSportHandler
|
||||
);
|
||||
|
||||
@@ -3,7 +3,6 @@ import { adminBookingRoutes } from '@/modules/admin-booking/admin-booking.routes
|
||||
import { authRoutes } from '@/modules/auth/auth.routes';
|
||||
import { complexRoutes } from '@/modules/complex/complex.routes';
|
||||
import { courtRoutes } from '@/modules/court/court.routes';
|
||||
import { onboardingRoutes } from '@/modules/onboarding/onboarding.routes';
|
||||
import { passwordResetRoutes } from '@/modules/password-reset/password-reset.routes';
|
||||
import { planRoutes } from '@/modules/plan/plan.routes';
|
||||
import { publicBookingRoutes } from '@/modules/public-booking/public-booking.routes';
|
||||
@@ -20,7 +19,6 @@ export function registerRoutes(app: Hono<AppEnv>) {
|
||||
.route('', authRoutes)
|
||||
.route('/api/user', userRoutes)
|
||||
.route('/api/plans', planRoutes)
|
||||
.route('/api/onboarding', onboardingRoutes)
|
||||
.route('/api/password-reset', passwordResetRoutes)
|
||||
.route('/api/complexes', complexRoutes)
|
||||
.route('/api/sports', sportRoutes)
|
||||
|
||||
86
apps/backend/src/services/booking-email.service.ts
Normal file
@@ -0,0 +1,86 @@
|
||||
import {
|
||||
bookingCancelledHtml,
|
||||
bookingConfirmationHtml,
|
||||
bookingNoShowHtml,
|
||||
} from '@/emails/booking-confirmation';
|
||||
import { sendMail } from '@/lib/mailer';
|
||||
|
||||
type BookingEmailInput = {
|
||||
bookingCode: string;
|
||||
complexName: string;
|
||||
date: string;
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
courtName: string;
|
||||
sportName: string;
|
||||
customerName: string;
|
||||
customerEmail?: string;
|
||||
price?: number;
|
||||
};
|
||||
|
||||
export async function sendBookingConfirmation(data: BookingEmailInput) {
|
||||
if (!data.customerEmail) return;
|
||||
|
||||
const html = bookingConfirmationHtml({
|
||||
bookingCode: data.bookingCode,
|
||||
complexName: data.complexName,
|
||||
date: data.date,
|
||||
startTime: data.startTime,
|
||||
endTime: data.endTime,
|
||||
courtName: data.courtName,
|
||||
sportName: data.sportName,
|
||||
customerName: data.customerName,
|
||||
price: data.price,
|
||||
});
|
||||
|
||||
await sendMail({
|
||||
to: data.customerEmail,
|
||||
subject: `Reserva confirmada en ${data.complexName} | Playzer`,
|
||||
html,
|
||||
text: `Reserva confirmada en ${data.complexName}. Codigo: ${data.bookingCode}. Cancha: ${data.courtName}. Fecha: ${data.date}. Horario: ${data.startTime} - ${data.endTime}.`,
|
||||
});
|
||||
}
|
||||
|
||||
export async function sendBookingCancelled(data: BookingEmailInput) {
|
||||
if (!data.customerEmail) return;
|
||||
|
||||
const html = bookingCancelledHtml({
|
||||
bookingCode: data.bookingCode,
|
||||
complexName: data.complexName,
|
||||
date: data.date,
|
||||
startTime: data.startTime,
|
||||
endTime: data.endTime,
|
||||
courtName: data.courtName,
|
||||
sportName: data.sportName,
|
||||
customerName: data.customerName,
|
||||
});
|
||||
|
||||
await sendMail({
|
||||
to: data.customerEmail,
|
||||
subject: `Reserva cancelada en ${data.complexName} | Playzer`,
|
||||
html,
|
||||
text: `Reserva cancelada en ${data.complexName}. Codigo: ${data.bookingCode}. Fecha: ${data.date}. Horario: ${data.startTime} - ${data.endTime}.`,
|
||||
});
|
||||
}
|
||||
|
||||
export async function sendBookingNoShow(data: BookingEmailInput) {
|
||||
if (!data.customerEmail) return;
|
||||
|
||||
const html = bookingNoShowHtml({
|
||||
bookingCode: data.bookingCode,
|
||||
complexName: data.complexName,
|
||||
date: data.date,
|
||||
startTime: data.startTime,
|
||||
endTime: data.endTime,
|
||||
courtName: data.courtName,
|
||||
sportName: data.sportName,
|
||||
customerName: data.customerName,
|
||||
});
|
||||
|
||||
await sendMail({
|
||||
to: data.customerEmail,
|
||||
subject: `Reserva no concretada en ${data.complexName} | Playzer`,
|
||||
html,
|
||||
text: `Reserva no concretada en ${data.complexName}. Codigo: ${data.bookingCode}. Fecha: ${data.date}. Horario: ${data.startTime} - ${data.endTime}.`,
|
||||
});
|
||||
}
|
||||
@@ -1,11 +1,8 @@
|
||||
import { beforeEach, expect, mock, test } from 'bun:test';
|
||||
|
||||
import type { InviteComplexUserResponse } from '@repo/api-contract';
|
||||
import { createInviteComplexUserHandler } from '@/modules/complex/handlers/invite-complex-user.handler';
|
||||
|
||||
const inviteComplexUserMock = mock(
|
||||
async () => undefined as unknown as InviteComplexUserResponse
|
||||
);
|
||||
const inviteComplexUserMock = mock(async () => undefined as unknown as InviteComplexUserResponse);
|
||||
|
||||
class MockComplexMembersError extends Error {
|
||||
status: 400 | 403 | 404 | 409;
|
||||
@@ -17,6 +14,10 @@ class MockComplexMembersError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
const { createInviteComplexUserHandler } = await import(
|
||||
'@/modules/complex/handlers/invite-complex-user.handler'
|
||||
);
|
||||
|
||||
const inviteComplexUserHandler = createInviteComplexUserHandler({
|
||||
inviteComplexUser: inviteComplexUserMock,
|
||||
ComplexMembersError: MockComplexMembersError,
|
||||
@@ -61,7 +62,6 @@ function createContext(input: {
|
||||
|
||||
beforeEach(() => {
|
||||
inviteComplexUserMock.mockReset();
|
||||
mock.clearAllMocks();
|
||||
});
|
||||
|
||||
test('returns 201 with the service result', async () => {
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import { beforeEach, expect, mock, test } from 'bun:test';
|
||||
import { beforeEach, expect, test } from 'bun:test';
|
||||
|
||||
import { prismaMock, sendMailMock, transactionMock } from '../support/prisma.mock';
|
||||
import {
|
||||
ComplexMembersError,
|
||||
inviteComplexUser,
|
||||
} from '@/modules/complex/services/complex-members.service';
|
||||
|
||||
const { ComplexMembersError, inviteComplexUser } = await import(
|
||||
'@/modules/complex/services/complex-members.service'
|
||||
);
|
||||
|
||||
beforeEach(() => {
|
||||
prismaMock._reset();
|
||||
mock.clearAllMocks();
|
||||
sendMailMock.mockClear();
|
||||
transactionMock.mockClear();
|
||||
});
|
||||
|
||||
test('creates a pending invitation and sends the email', async () => {
|
||||
@@ -21,10 +22,10 @@ test('creates a pending invitation and sends the email', async () => {
|
||||
complexId: 'complex-1',
|
||||
email: 'new.member@example.com',
|
||||
tokenHash: 'token-hash',
|
||||
expiresAt: new Date('2026-04-29T00:00:00.000Z'),
|
||||
expiresAt: new Date('2027-01-01T00:00:00.000Z'),
|
||||
acceptedAt: null,
|
||||
revokedAt: null,
|
||||
createdAt: new Date('2026-04-22T00:00:00.000Z'),
|
||||
createdAt: new Date('2026-12-01T00:00:00.000Z'),
|
||||
} as never);
|
||||
|
||||
const result = await inviteComplexUser('admin-1', 'complex-1', {
|
||||
@@ -79,7 +80,7 @@ test('rejects when the invite target already belongs to the complex', async () =
|
||||
}
|
||||
|
||||
expect(caught).toBeInstanceOf(ComplexMembersError);
|
||||
expect((caught as ComplexMembersError).status).toBe(409);
|
||||
expect((caught as InstanceType<typeof ComplexMembersError>).status).toBe(409);
|
||||
expect(transactionMock).not.toHaveBeenCalled();
|
||||
expect(sendMailMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
94
apps/backend/test/sport/create-sport.handler.test.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
import { beforeEach, expect, mock, test } from 'bun:test';
|
||||
|
||||
import { Errors } from '@/lib/errors';
|
||||
import { err, ok } from '@/lib/result';
|
||||
import type { CreateSportInput } from '@repo/api-contract';
|
||||
|
||||
const createSportMock = mock(async (_input: CreateSportInput) =>
|
||||
ok({
|
||||
id: 'sport-1',
|
||||
name: 'Tenis',
|
||||
slug: 'tenis',
|
||||
isActive: true,
|
||||
createdAt: '2026-04-23T00:00:00.000Z',
|
||||
updatedAt: '2026-04-23T00:00:00.000Z',
|
||||
})
|
||||
);
|
||||
|
||||
mock.module('@/modules/sport/services/sport.service', () => ({
|
||||
__esModule: true,
|
||||
createSport: createSportMock,
|
||||
}));
|
||||
|
||||
const { createSportHandler } = await import('@/modules/sport/handlers/create-sport.handler');
|
||||
|
||||
type HandlerContext = {
|
||||
get: (key: 'requestId') => string | undefined;
|
||||
req: {
|
||||
valid: () => unknown;
|
||||
};
|
||||
json: ReturnType<typeof mock>;
|
||||
};
|
||||
|
||||
function createContext(body: unknown) {
|
||||
const json = mock((payload: unknown, init?: unknown) => ({
|
||||
payload,
|
||||
init,
|
||||
}));
|
||||
|
||||
const c = {
|
||||
get: () => undefined,
|
||||
req: {
|
||||
valid: () => body,
|
||||
},
|
||||
json,
|
||||
} as unknown as HandlerContext;
|
||||
|
||||
return { c, json };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
createSportMock.mockReset();
|
||||
});
|
||||
|
||||
test('returns 201 with the created sport', async () => {
|
||||
const createdSport = {
|
||||
id: 'sport-1',
|
||||
name: 'Tenis',
|
||||
slug: 'tenis',
|
||||
isActive: true,
|
||||
createdAt: '2026-04-23T00:00:00.000Z',
|
||||
updatedAt: '2026-04-23T00:00:00.000Z',
|
||||
} as const;
|
||||
|
||||
createSportMock.mockResolvedValue(ok(createdSport));
|
||||
|
||||
const payload: CreateSportInput = { name: ' Tenis ' };
|
||||
const { c, json } = createContext(payload);
|
||||
|
||||
const response = await createSportHandler(c as never);
|
||||
|
||||
expect(createSportMock).toHaveBeenCalledWith(payload);
|
||||
expect(json.mock.calls[0]?.[0]).toEqual(createdSport);
|
||||
expect(json.mock.calls[0]?.[1]).toBe(201);
|
||||
expect(response).toBeDefined();
|
||||
});
|
||||
|
||||
test('returns a conflict problem when the service rejects with a conflict error', async () => {
|
||||
createSportMock.mockResolvedValue(err(Errors.conflict('Ya existe un deporte con ese nombre.')));
|
||||
|
||||
const payload: CreateSportInput = { name: 'Tenis' };
|
||||
const { c, json } = createContext(payload);
|
||||
|
||||
const response = await createSportHandler(c as never);
|
||||
|
||||
expect(createSportMock).toHaveBeenCalledWith(payload);
|
||||
expect(json.mock.calls[0]?.[0]).toEqual({
|
||||
type: 'https://api.myapp.dev/problems/conflict',
|
||||
title: 'Conflict',
|
||||
status: 409,
|
||||
detail: 'Ya existe un deporte con ese nombre.',
|
||||
});
|
||||
expect(json.mock.calls[0]?.[1]).toBe(409);
|
||||
expect(response).toBeDefined();
|
||||
});
|
||||
195
apps/backend/test/sport/sport.service.test.ts
Normal file
@@ -0,0 +1,195 @@
|
||||
import { beforeEach, expect, mock, test } from 'bun:test';
|
||||
|
||||
import { createPrismaMock } from 'bun-mock-prisma';
|
||||
|
||||
import type { PrismaClient } from '@/generated/prisma/client';
|
||||
import type { PrismaClientMock } from 'bun-mock-prisma';
|
||||
|
||||
const prismaMock = createPrismaMock<PrismaClient>() as PrismaClientMock<PrismaClient>;
|
||||
|
||||
mock.module('@/lib/prisma', () => ({
|
||||
__esModule: true,
|
||||
db: {
|
||||
sport: prismaMock.sport,
|
||||
},
|
||||
}));
|
||||
|
||||
const { uuidV7Mock } = await import('../support/prisma.mock');
|
||||
|
||||
const { createSport, getSportById, listSports, updateSport } = await import(
|
||||
'@/modules/sport/services/sport.service'
|
||||
);
|
||||
|
||||
beforeEach(() => {
|
||||
prismaMock._reset();
|
||||
uuidV7Mock.mockClear();
|
||||
});
|
||||
|
||||
test('listSports returns sports ordered by name', async () => {
|
||||
const sports = [
|
||||
{
|
||||
id: 'sport-2',
|
||||
name: 'Tenis',
|
||||
slug: 'tenis',
|
||||
isActive: true,
|
||||
createdAt: new Date('2026-04-22T00:00:00.000Z'),
|
||||
updatedAt: new Date('2026-04-22T00:00:00.000Z'),
|
||||
},
|
||||
{
|
||||
id: 'sport-1',
|
||||
name: 'Básquet',
|
||||
slug: 'basquet',
|
||||
isActive: true,
|
||||
createdAt: new Date('2026-04-21T00:00:00.000Z'),
|
||||
updatedAt: new Date('2026-04-21T00:00:00.000Z'),
|
||||
},
|
||||
];
|
||||
|
||||
prismaMock.sport.findMany.mockResolvedValue(sports as never);
|
||||
|
||||
const result = await listSports();
|
||||
|
||||
expect(prismaMock.sport.findMany).toHaveBeenCalledWith({
|
||||
orderBy: { name: 'asc' },
|
||||
});
|
||||
expect(result).toEqual({
|
||||
ok: true,
|
||||
value: sports,
|
||||
});
|
||||
});
|
||||
|
||||
test('getSportById returns the requested sport', async () => {
|
||||
const sport = {
|
||||
id: 'sport-1',
|
||||
name: 'Tenis',
|
||||
slug: 'tenis',
|
||||
isActive: true,
|
||||
createdAt: new Date('2026-04-22T00:00:00.000Z'),
|
||||
updatedAt: new Date('2026-04-22T00:00:00.000Z'),
|
||||
};
|
||||
|
||||
prismaMock.sport.findUnique.mockResolvedValue(sport as never);
|
||||
|
||||
const result = await getSportById('sport-1');
|
||||
|
||||
expect(prismaMock.sport.findUnique).toHaveBeenCalledWith({
|
||||
where: { id: 'sport-1' },
|
||||
});
|
||||
expect(result).toEqual(sport);
|
||||
});
|
||||
|
||||
test('createSport trims the name and creates a unique slug', async () => {
|
||||
const createdSport = {
|
||||
id: '00000000-0000-4000-8000-000000000001',
|
||||
name: 'Fútbol 7!!',
|
||||
slug: 'futbol-7',
|
||||
isActive: true,
|
||||
createdAt: new Date('2026-04-23T00:00:00.000Z'),
|
||||
updatedAt: new Date('2026-04-23T00:00:00.000Z'),
|
||||
};
|
||||
|
||||
prismaMock.sport.findFirst.mockResolvedValue(null as never);
|
||||
prismaMock.sport.count.mockResolvedValue(0 as never);
|
||||
prismaMock.sport.create.mockResolvedValue(createdSport as never);
|
||||
|
||||
const result = await createSport({ name: ' Fútbol 7!! ' });
|
||||
|
||||
expect(uuidV7Mock).toHaveBeenCalledTimes(1);
|
||||
expect(prismaMock.sport.findFirst).toHaveBeenCalledWith({
|
||||
where: { slug: 'futbol-7' },
|
||||
select: { id: true },
|
||||
});
|
||||
expect(prismaMock.sport.count).toHaveBeenCalledWith({
|
||||
where: { slug: 'futbol-7' },
|
||||
});
|
||||
expect(prismaMock.sport.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
id: '00000000-0000-4000-8000-000000000001',
|
||||
name: 'Fútbol 7!!',
|
||||
slug: 'futbol-7',
|
||||
isActive: true,
|
||||
},
|
||||
});
|
||||
expect(result).toEqual({
|
||||
ok: true,
|
||||
value: createdSport,
|
||||
});
|
||||
});
|
||||
|
||||
test('createSport retries with a numeric suffix when the slug already exists', async () => {
|
||||
const createdSport = {
|
||||
id: '00000000-0000-4000-8000-000000000001',
|
||||
name: 'Tenis',
|
||||
slug: 'tenis-2',
|
||||
isActive: true,
|
||||
createdAt: new Date('2026-04-23T00:00:00.000Z'),
|
||||
updatedAt: new Date('2026-04-23T00:00:00.000Z'),
|
||||
};
|
||||
|
||||
prismaMock.sport.findFirst
|
||||
.mockResolvedValueOnce({ id: 'existing-sport' } as never)
|
||||
.mockResolvedValueOnce(null as never);
|
||||
prismaMock.sport.count.mockResolvedValue(0 as never);
|
||||
prismaMock.sport.create.mockResolvedValue(createdSport as never);
|
||||
|
||||
const result = await createSport({ name: 'Tenis' });
|
||||
|
||||
expect(prismaMock.sport.findFirst).toHaveBeenNthCalledWith(1, {
|
||||
where: { slug: 'tenis' },
|
||||
select: { id: true },
|
||||
});
|
||||
expect(prismaMock.sport.findFirst).toHaveBeenNthCalledWith(2, {
|
||||
where: { slug: 'tenis-2' },
|
||||
select: { id: true },
|
||||
});
|
||||
expect(prismaMock.sport.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
id: '00000000-0000-4000-8000-000000000001',
|
||||
name: 'Tenis',
|
||||
slug: 'tenis-2',
|
||||
isActive: true,
|
||||
},
|
||||
});
|
||||
expect(result).toEqual({
|
||||
ok: true,
|
||||
value: createdSport,
|
||||
});
|
||||
});
|
||||
|
||||
test('updateSport updates the name, slug and active flag', async () => {
|
||||
const updatedSport = {
|
||||
id: 'sport-1',
|
||||
name: 'Básquet 3x3',
|
||||
slug: 'basquet-3x3',
|
||||
isActive: false,
|
||||
createdAt: new Date('2026-04-21T00:00:00.000Z'),
|
||||
updatedAt: new Date('2026-04-23T00:00:00.000Z'),
|
||||
};
|
||||
|
||||
prismaMock.sport.findFirst.mockResolvedValue(null as never);
|
||||
prismaMock.sport.update.mockResolvedValue(updatedSport as never);
|
||||
|
||||
const result = await updateSport('sport-1', {
|
||||
name: 'Básquet 3x3',
|
||||
isActive: false,
|
||||
});
|
||||
|
||||
expect(prismaMock.sport.findFirst).toHaveBeenCalledWith({
|
||||
where: {
|
||||
slug: 'basquet-3x3',
|
||||
id: {
|
||||
not: 'sport-1',
|
||||
},
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
expect(prismaMock.sport.update).toHaveBeenCalledWith({
|
||||
where: { id: 'sport-1' },
|
||||
data: {
|
||||
name: 'Básquet 3x3',
|
||||
slug: 'basquet-3x3',
|
||||
isActive: false,
|
||||
},
|
||||
});
|
||||
expect(result).toEqual(updatedSport);
|
||||
});
|
||||
@@ -5,14 +5,16 @@ import type { PrismaClient } from '@/generated/prisma/client';
|
||||
import type { PrismaClientMock } from 'bun-mock-prisma';
|
||||
|
||||
export const prismaMock = createPrismaMock<PrismaClient>() as PrismaClientMock<PrismaClient>;
|
||||
export const sendMailMock = mock(async (_input: {
|
||||
to: string;
|
||||
subject: string;
|
||||
html: string;
|
||||
text: string;
|
||||
}) => undefined);
|
||||
export const transactionMock = mock(async <T>(fn: (tx: PrismaClientMock<PrismaClient>) => Promise<T>) =>
|
||||
fn(prismaMock)
|
||||
export const sendMailMock = mock(
|
||||
async (_input: {
|
||||
to: string;
|
||||
subject: string;
|
||||
html: string;
|
||||
text: string;
|
||||
}) => undefined
|
||||
);
|
||||
export const transactionMock = mock(
|
||||
async <T>(fn: (tx: PrismaClientMock<PrismaClient>) => Promise<T>) => fn(prismaMock)
|
||||
);
|
||||
export const dbMock = {
|
||||
complexUser: prismaMock.complexUser,
|
||||
@@ -31,3 +33,10 @@ mock.module('@/lib/mailer', () => ({
|
||||
__esModule: true,
|
||||
sendMail: sendMailMock,
|
||||
}));
|
||||
|
||||
export const uuidV7Mock = mock(() => '00000000-0000-4000-8000-000000000001');
|
||||
|
||||
mock.module('uuid', () => ({
|
||||
__esModule: true,
|
||||
v7: uuidV7Mock,
|
||||
}));
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<link rel="icon" type="iimage/x-icon" href="/src/assets/playzer-favicon-transparent.ico" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>PlayZer</title>
|
||||
</head>
|
||||
<body>
|
||||
<body lass="bg-background text-foreground antialiased">
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
|
||||
BIN
apps/frontend/public/playzer-favicon-512-transparent.png
Normal file
|
After Width: | Height: | Size: 151 KiB |
@@ -1,182 +0,0 @@
|
||||
.counter {
|
||||
font-size: 16px;
|
||||
padding: 5px 10px;
|
||||
border-radius: 5px;
|
||||
color: var(--accent);
|
||||
background: var(--accent-bg);
|
||||
border: 2px solid transparent;
|
||||
transition: border-color 0.3s;
|
||||
margin-bottom: 24px;
|
||||
|
||||
&:hover {
|
||||
border-color: var(--accent-border);
|
||||
}
|
||||
&:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
.hero {
|
||||
position: relative;
|
||||
|
||||
.base,
|
||||
.framework,
|
||||
.vite {
|
||||
inset-inline: 0;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.base {
|
||||
width: 170px;
|
||||
position: relative;
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
.framework,
|
||||
.vite {
|
||||
position: absolute;
|
||||
}
|
||||
|
||||
.framework {
|
||||
z-index: 1;
|
||||
top: 34px;
|
||||
height: 28px;
|
||||
transform: perspective(2000px) rotateZ(300deg) rotateX(44deg) rotateY(39deg) scale(1.4);
|
||||
}
|
||||
|
||||
.vite {
|
||||
z-index: 0;
|
||||
top: 107px;
|
||||
height: 26px;
|
||||
width: auto;
|
||||
transform: perspective(2000px) rotateZ(300deg) rotateX(40deg) rotateY(39deg) scale(0.8);
|
||||
}
|
||||
}
|
||||
|
||||
#center {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 25px;
|
||||
place-content: center;
|
||||
place-items: center;
|
||||
flex-grow: 1;
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
padding: 32px 20px 24px;
|
||||
gap: 18px;
|
||||
}
|
||||
}
|
||||
|
||||
#next-steps {
|
||||
display: flex;
|
||||
border-top: 1px solid var(--border);
|
||||
text-align: left;
|
||||
|
||||
& > div {
|
||||
flex: 1 1 0;
|
||||
padding: 32px;
|
||||
@media (max-width: 1024px) {
|
||||
padding: 24px 20px;
|
||||
}
|
||||
}
|
||||
|
||||
.icon {
|
||||
margin-bottom: 16px;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
}
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
flex-direction: column;
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
|
||||
#docs {
|
||||
border-right: 1px solid var(--border);
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
border-right: none;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
}
|
||||
|
||||
#next-steps ul {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin: 32px 0 0;
|
||||
|
||||
.logo {
|
||||
height: 18px;
|
||||
}
|
||||
|
||||
a {
|
||||
color: var(--text-h);
|
||||
font-size: 16px;
|
||||
border-radius: 6px;
|
||||
background: var(--social-bg);
|
||||
display: flex;
|
||||
padding: 6px 12px;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
text-decoration: none;
|
||||
transition: box-shadow 0.3s;
|
||||
|
||||
&:hover {
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
.button-icon {
|
||||
height: 18px;
|
||||
width: 18px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
margin-top: 20px;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
|
||||
li {
|
||||
flex: 1 1 calc(50% - 8px);
|
||||
}
|
||||
|
||||
a {
|
||||
width: 100%;
|
||||
justify-content: center;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#spacer {
|
||||
height: 88px;
|
||||
border-top: 1px solid var(--border);
|
||||
@media (max-width: 1024px) {
|
||||
height: 48px;
|
||||
}
|
||||
}
|
||||
|
||||
.ticks {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
|
||||
&::before,
|
||||
&::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: -4.5px;
|
||||
border: 5px solid transparent;
|
||||
}
|
||||
|
||||
&::before {
|
||||
left: 0;
|
||||
border-left-color: var(--border);
|
||||
}
|
||||
&::after {
|
||||
right: 0;
|
||||
border-right-color: var(--border);
|
||||
}
|
||||
}
|
||||
|
||||
BIN
apps/frontend/src/assets/playzer-favicon-512-transparent.png
Normal file
|
After Width: | Height: | Size: 151 KiB |
BIN
apps/frontend/src/assets/playzer-favicon-transparent.ico
Normal file
|
After Width: | Height: | Size: 81 KiB |
BIN
apps/frontend/src/assets/playzer-favicon.ico
Normal file
|
After Width: | Height: | Size: 100 KiB |
BIN
apps/frontend/src/assets/playzer-icon-p-transparent.png
Normal file
|
After Width: | Height: | Size: 155 KiB |
4
apps/frontend/src/assets/playzer-icon-p-transparent.svg
Normal file
|
After Width: | Height: | Size: 206 KiB |
3
apps/frontend/src/assets/playzer-icon-p.svg
Normal file
|
After Width: | Height: | Size: 372 KiB |
BIN
apps/frontend/src/assets/playzer-logo-transparent.png
Normal file
|
After Width: | Height: | Size: 607 KiB |
4
apps/frontend/src/assets/playzer-logo-transparent.svg
Normal file
|
After Width: | Height: | Size: 810 KiB |
3
apps/frontend/src/assets/playzer-logo.svg
Normal file
|
After Width: | Height: | Size: 1.2 MiB |
15
apps/frontend/src/components/background.tsx
Normal file
@@ -0,0 +1,15 @@
|
||||
export function Background() {
|
||||
return (
|
||||
<div className="pointer-events-none fixed inset-0 -z-10 overflow-hidden">
|
||||
<div className="absolute inset-0 bg-gradient-to-b from-[#040b11] to-[#09131c]" />
|
||||
|
||||
<div className="absolute left-0 top-0 h-[420px] w-[420px] -translate-x-1/2 -translate-y-1/2 rounded-full bg-primary/20 blur-3xl" />
|
||||
<div className="absolute right-0 top-24 h-[360px] w-[360px] translate-x-1/3 rounded-full bg-reserved/15 blur-3xl" />
|
||||
<div className="absolute bottom-0 left-1/2 h-[300px] w-[300px] -translate-x-1/2 translate-y-1/3 rounded-full bg-accent/10 blur-3xl" />
|
||||
|
||||
<div className="absolute inset-0 bg-[linear-gradient(to_right,oklch(1_0_0/0.055)_1px,transparent_1px),linear-gradient(to_bottom,oklch(1_0_0/0.055)_1px,transparent_1px)] bg-[size:64px_64px]" />
|
||||
|
||||
<div className="absolute inset-0 bg-[radial-gradient(circle_at_center,transparent_0%,#09131c_78%)]" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
431
apps/frontend/src/components/header.tsx
Normal file
@@ -0,0 +1,431 @@
|
||||
import {
|
||||
CalendarDays,
|
||||
Check,
|
||||
Laptop,
|
||||
LogOut,
|
||||
Menu,
|
||||
Moon,
|
||||
Settings,
|
||||
Sun,
|
||||
User,
|
||||
X,
|
||||
} from 'lucide-react';
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
|
||||
import PlayzerIcon from '@/assets/playzer-favicon-512-transparent.png';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { Link, useNavigate } from '@tanstack/react-router';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuRadioGroup,
|
||||
DropdownMenuRadioItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { Sheet, SheetContent, SheetTrigger } from '@/components/ui/sheet';
|
||||
import { UserAvatar } from '@/components/user-avatar';
|
||||
import { apiClient } from '@/lib/api-client';
|
||||
import { useAuth } from '@/lib/auth';
|
||||
import { acceptStoredPendingInvite } from '@/lib/invitations';
|
||||
import { useCurrentComplexStore } from '@/lib/stores/current-complex-store';
|
||||
import { useTheme } from '@/lib/theme';
|
||||
|
||||
export function Header() {
|
||||
const [open, setOpen] = useState(false);
|
||||
const navigate = useNavigate();
|
||||
const queryClient = useQueryClient();
|
||||
const { user, isAuthenticated, displayName, avatarUrl, signOut } = useAuth();
|
||||
const { theme, setTheme } = useTheme();
|
||||
const { currentComplexSlug, setCurrentComplex } = useCurrentComplexStore();
|
||||
const processedInviteForUser = useRef<string | null>(null);
|
||||
const myComplexesQuery = useQuery({
|
||||
queryKey: ['my-complexes'],
|
||||
enabled: isAuthenticated,
|
||||
queryFn: () => apiClient.complexes.listMine(),
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!isAuthenticated) {
|
||||
processedInviteForUser.current = null;
|
||||
return;
|
||||
}
|
||||
|
||||
const userKey = user?.email ?? displayName ?? 'authenticated-user';
|
||||
|
||||
if (processedInviteForUser.current === userKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
processedInviteForUser.current = userKey;
|
||||
|
||||
void (async () => {
|
||||
await acceptStoredPendingInvite(apiClient.complexes.acceptPendingInvitations);
|
||||
await queryClient.invalidateQueries({ queryKey: ['my-complexes'] });
|
||||
})();
|
||||
}, [displayName, isAuthenticated, queryClient, user?.email]);
|
||||
|
||||
const complexSlug = currentComplexSlug || myComplexesQuery.data?.[0]?.complexSlug;
|
||||
const currentComplexName = useMemo(() => {
|
||||
const complexes = myComplexesQuery.data ?? [];
|
||||
if (complexes.length === 0) return 'Mi complejo';
|
||||
|
||||
const selected = complexes.find((complex) => complex.complexSlug === complexSlug);
|
||||
|
||||
return selected?.complexName ?? complexes[0]?.complexName ?? 'Mi complejo';
|
||||
}, [complexSlug, myComplexesQuery.data]);
|
||||
|
||||
const handleSelectComplex = async (complexId: string, nextSlug: string) => {
|
||||
await apiClient.complexes.select({ complexId });
|
||||
setCurrentComplex(nextSlug);
|
||||
await queryClient.invalidateQueries({ queryKey: ['current-complex'] });
|
||||
};
|
||||
|
||||
const handleSignOut = async () => {
|
||||
await signOut();
|
||||
await navigate({ to: '/login' });
|
||||
};
|
||||
|
||||
const handleOpenBookingCreate = async () => {
|
||||
if (location.pathname !== '/') {
|
||||
await navigate({ to: '/' });
|
||||
}
|
||||
|
||||
window.setTimeout(() => {
|
||||
window.dispatchEvent(new Event('playzer:open-booking-create'));
|
||||
}, 0);
|
||||
};
|
||||
|
||||
return (
|
||||
<header className="sticky top-0 z-50 w-full border-b border-border/60 bg-background/60 dark:border-primary/20 dark:bg-[#030a10]/90 backdrop-blur-xl">
|
||||
<div className="absolute inset-0 -z-10 bg-gradient-to-b from-background/85 to-background/45 dark:from-[#030a10]/95 dark:to-[#030a10]/70" />
|
||||
|
||||
<div className="mx-auto flex h-16 w-full max-w-7xl items-center gap-4 px-3 sm:px-6 lg:px-8">
|
||||
<Link to="/" className="group flex items-center gap-3">
|
||||
<div className="flex size-10 items-center justify-center shadow-primary/10 ">
|
||||
<img src={PlayzerIcon} alt="Playzer" className="size-7" />
|
||||
</div>
|
||||
|
||||
<span className="bg-gradient-to-r from-primary via-primary to-reserved bg-clip-text text-xl font-bold tracking-tight text-transparent">
|
||||
Playzer
|
||||
</span>
|
||||
</Link>
|
||||
|
||||
<div className="flex-1" />
|
||||
|
||||
<div className="hidden items-center gap-2 md:flex">
|
||||
<Button
|
||||
className="rounded-2xl px-5 shadow-lg shadow-primary/20"
|
||||
onClick={() => {
|
||||
void handleOpenBookingCreate();
|
||||
}}
|
||||
>
|
||||
<CalendarDays className="mr-2 size-4" />
|
||||
Reservar ahora
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{isAuthenticated ? (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className="hidden size-10 rounded-full ring-2 ring-transparent transition-all duration-200 hover:ring-primary/30 focus:outline-none md:flex"
|
||||
>
|
||||
<UserAvatar
|
||||
src={avatarUrl}
|
||||
alt={displayName}
|
||||
fallbackText={displayName}
|
||||
className="size-10 border border-border/60 shadow-lg shadow-black/10"
|
||||
/>
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
|
||||
<DropdownMenuContent
|
||||
align="end"
|
||||
className="w-64 rounded-2xl border-border/60 bg-popover/95 p-2 shadow-xl shadow-black/20 backdrop-blur-xl"
|
||||
>
|
||||
<DropdownMenuLabel className="px-2 py-2">
|
||||
<div className="flex items-center gap-3">
|
||||
<UserAvatar
|
||||
src={avatarUrl}
|
||||
alt={displayName}
|
||||
fallbackText={displayName}
|
||||
className="size-9"
|
||||
/>
|
||||
|
||||
<div className="flex min-w-0 flex-col">
|
||||
<span className="truncate text-sm font-medium">{displayName}</span>
|
||||
<span className="truncate text-xs text-muted-foreground">{user?.email}</span>
|
||||
<span className="truncate text-xs text-muted-foreground">
|
||||
{currentComplexName}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</DropdownMenuLabel>
|
||||
|
||||
<DropdownMenuSeparator />
|
||||
|
||||
{myComplexesQuery.data && myComplexesQuery.data.length > 1 && (
|
||||
<>
|
||||
<DropdownMenuLabel className="px-2 text-xs font-normal text-muted-foreground">
|
||||
Cambiar complejo
|
||||
</DropdownMenuLabel>
|
||||
{myComplexesQuery.data.map((complex) => (
|
||||
<DropdownMenuItem
|
||||
key={complex.id}
|
||||
className="cursor-pointer rounded-xl"
|
||||
onSelect={() => {
|
||||
void handleSelectComplex(complex.id, complex.complexSlug);
|
||||
}}
|
||||
>
|
||||
<span className="mr-2 flex size-4 items-center justify-center">
|
||||
{complex.complexSlug === complexSlug && <Check className="size-4" />}
|
||||
</span>
|
||||
{complex.complexName}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
<DropdownMenuSeparator />
|
||||
</>
|
||||
)}
|
||||
|
||||
<DropdownMenuLabel className="px-2 text-xs font-normal text-muted-foreground">
|
||||
Apariencia
|
||||
</DropdownMenuLabel>
|
||||
<DropdownMenuRadioGroup
|
||||
value={theme}
|
||||
onValueChange={(value) => setTheme(value as 'light' | 'dark' | 'system')}
|
||||
>
|
||||
<DropdownMenuRadioItem value="light" className="cursor-pointer rounded-xl">
|
||||
<Sun className="mr-2 size-4" />
|
||||
Light
|
||||
</DropdownMenuRadioItem>
|
||||
<DropdownMenuRadioItem value="dark" className="cursor-pointer rounded-xl">
|
||||
<Moon className="mr-2 size-4" />
|
||||
Dark
|
||||
</DropdownMenuRadioItem>
|
||||
<DropdownMenuRadioItem value="system" className="cursor-pointer rounded-xl">
|
||||
<Laptop className="mr-2 size-4" />
|
||||
System
|
||||
</DropdownMenuRadioItem>
|
||||
</DropdownMenuRadioGroup>
|
||||
|
||||
<DropdownMenuSeparator />
|
||||
|
||||
<DropdownMenuItem
|
||||
className="cursor-pointer rounded-xl"
|
||||
onSelect={() => {
|
||||
void navigate({ to: '/profile' });
|
||||
}}
|
||||
>
|
||||
<User className="mr-2 size-4" />
|
||||
Mi Perfil
|
||||
</DropdownMenuItem>
|
||||
|
||||
{currentComplexSlug && (
|
||||
<DropdownMenuItem
|
||||
className="cursor-pointer rounded-xl"
|
||||
onSelect={() => {
|
||||
void navigate({
|
||||
to: '/complex/$slug/edit',
|
||||
params: { slug: currentComplexSlug },
|
||||
});
|
||||
}}
|
||||
>
|
||||
<Settings className="mr-2 size-4" />
|
||||
Configuración
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
|
||||
<DropdownMenuSeparator />
|
||||
|
||||
<DropdownMenuItem
|
||||
className="cursor-pointer rounded-xl text-destructive focus:bg-destructive/10 focus:text-destructive"
|
||||
onSelect={() => {
|
||||
void handleSignOut();
|
||||
}}
|
||||
>
|
||||
<LogOut className="mr-2 size-4" />
|
||||
Cerrar sesión
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
) : (
|
||||
<Button asChild size="sm" variant="outline" className="hidden rounded-2xl md:inline-flex">
|
||||
<Link to="/login">Login</Link>
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<Button variant="outline" size="icon" className="rounded-2xl md:hidden">
|
||||
{open ? <X className="size-5" /> : <Menu className="size-5" />}
|
||||
</Button>
|
||||
</SheetTrigger>
|
||||
|
||||
<SheetContent
|
||||
side="right"
|
||||
className="w-[88vw] border-border/60 bg-background/95 p-5 backdrop-blur-xl sm:max-w-sm"
|
||||
>
|
||||
<div className="mt-6 flex flex-col gap-6">
|
||||
<div className="rounded-3xl border border-border/60 bg-card/70 p-4 shadow-xl shadow-black/10">
|
||||
<div className="flex items-center gap-3">
|
||||
<UserAvatar
|
||||
src={avatarUrl}
|
||||
alt={displayName}
|
||||
fallbackText={displayName}
|
||||
className="size-11"
|
||||
/>
|
||||
|
||||
<div className="min-w-0">
|
||||
<p className="truncate text-sm font-medium">{displayName}</p>
|
||||
<p className="truncate text-xs text-muted-foreground">{user?.email}</p>
|
||||
{isAuthenticated && (
|
||||
<p className="truncate text-xs text-muted-foreground">{currentComplexName}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
className="rounded-2xl shadow-lg shadow-primary/20"
|
||||
onClick={() => {
|
||||
setOpen(false);
|
||||
void handleOpenBookingCreate();
|
||||
}}
|
||||
>
|
||||
<CalendarDays className="mr-2 size-4" />
|
||||
Reservar ahora
|
||||
</Button>
|
||||
|
||||
<div className="border-t border-border/60 pt-4">
|
||||
<div className="mb-2 flex items-center justify-between px-2">
|
||||
<p className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
|
||||
Cuenta
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<nav className="flex flex-col gap-1">
|
||||
{!isAuthenticated && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="justify-start rounded-2xl"
|
||||
onClick={() => {
|
||||
setOpen(false);
|
||||
void navigate({ to: '/login' });
|
||||
}}
|
||||
>
|
||||
Login
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<div className="py-1">
|
||||
<p className="px-3 py-1 text-xs text-muted-foreground">Apariencia</p>
|
||||
{[
|
||||
{ value: 'light', label: 'Light', icon: Sun },
|
||||
{ value: 'dark', label: 'Dark', icon: Moon },
|
||||
{ value: 'system', label: 'System', icon: Laptop },
|
||||
].map((item) => {
|
||||
const Icon = item.icon;
|
||||
|
||||
return (
|
||||
<Button
|
||||
key={item.value}
|
||||
variant="ghost"
|
||||
className="w-full justify-start rounded-2xl"
|
||||
onClick={() => setTheme(item.value as 'light' | 'dark' | 'system')}
|
||||
>
|
||||
<span className="mr-2 flex size-4 items-center justify-center">
|
||||
{theme === item.value ? (
|
||||
<Check className="size-4" />
|
||||
) : (
|
||||
<Icon className="size-4" />
|
||||
)}
|
||||
</span>
|
||||
{item.label}
|
||||
</Button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{myComplexesQuery.data && myComplexesQuery.data.length > 1 && (
|
||||
<div className="py-1">
|
||||
<p className="px-3 py-1 text-xs text-muted-foreground">Cambiar complejo</p>
|
||||
{myComplexesQuery.data.map((complex) => (
|
||||
<Button
|
||||
key={complex.id}
|
||||
variant="ghost"
|
||||
className="w-full justify-start rounded-2xl"
|
||||
onClick={() => {
|
||||
setOpen(false);
|
||||
void handleSelectComplex(complex.id, complex.complexSlug);
|
||||
}}
|
||||
>
|
||||
<span className="mr-2 flex size-4 items-center justify-center">
|
||||
{complex.complexSlug === complexSlug && <Check className="size-4" />}
|
||||
</span>
|
||||
{complex.complexName}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isAuthenticated && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="justify-start rounded-2xl"
|
||||
onClick={() => {
|
||||
setOpen(false);
|
||||
void navigate({ to: '/profile' });
|
||||
}}
|
||||
>
|
||||
<User className="mr-2 size-4" />
|
||||
Mi Perfil
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{currentComplexSlug && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="justify-start rounded-2xl"
|
||||
onClick={() => {
|
||||
setOpen(false);
|
||||
void navigate({
|
||||
to: '/complex/$slug/edit',
|
||||
params: { slug: currentComplexSlug },
|
||||
});
|
||||
}}
|
||||
>
|
||||
<Settings className="mr-2 size-4" />
|
||||
Configuración
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{isAuthenticated && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="justify-start rounded-2xl text-destructive hover:bg-destructive/10 hover:text-destructive"
|
||||
onClick={() => {
|
||||
setOpen(false);
|
||||
void handleSignOut();
|
||||
}}
|
||||
>
|
||||
<LogOut className="mr-2 size-4" />
|
||||
Cerrar sesión
|
||||
</Button>
|
||||
)}
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</div>
|
||||
|
||||
<div className="h-px bg-gradient-to-r from-transparent via-primary/40 to-transparent" />
|
||||
</header>
|
||||
);
|
||||
}
|
||||
31
apps/frontend/src/components/layout.tsx
Normal file
@@ -0,0 +1,31 @@
|
||||
import { Background } from '@/components/background';
|
||||
import { useIsMobile } from '@/hooks/use-mobile';
|
||||
import { useLocation } from '@tanstack/react-router';
|
||||
import type { ReactNode } from 'react';
|
||||
import { Header } from './header';
|
||||
|
||||
interface LayoutProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function Layout({ children }: LayoutProps) {
|
||||
const isMobile = useIsMobile();
|
||||
const location = useLocation();
|
||||
const isMobileHome = isMobile && location.pathname === '/';
|
||||
|
||||
return (
|
||||
<div className="relative min-h-dvh overflow-x-hidden bg-background text-foreground">
|
||||
<Background />
|
||||
{!isMobileHome && <Header />}
|
||||
<main
|
||||
className={
|
||||
isMobileHome
|
||||
? 'relative z-10 mx-auto w-full max-w-7xl'
|
||||
: 'relative z-10 mx-auto w-full max-w-7xl px-3 py-6 sm:px-6 lg:px-8'
|
||||
}
|
||||
>
|
||||
{children}
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -4,12 +4,14 @@ import { DayPicker } from 'react-day-picker';
|
||||
|
||||
import { buttonVariants } from '@/components/ui/button';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { es } from 'date-fns/locale';
|
||||
|
||||
export type CalendarProps = React.ComponentProps<typeof DayPicker>;
|
||||
|
||||
function Calendar({ className, classNames, showOutsideDays = true, ...props }: CalendarProps) {
|
||||
return (
|
||||
<DayPicker
|
||||
locale={es}
|
||||
showOutsideDays={showOutsideDays}
|
||||
className={cn('p-3', className)}
|
||||
classNames={{
|
||||
|
||||
@@ -90,7 +90,7 @@ function DialogFooter({
|
||||
<div
|
||||
data-slot="dialog-footer"
|
||||
className={cn(
|
||||
'-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end',
|
||||
'-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-green-50/70 p-4 sm:flex-row sm:justify-end dark:bg-muted/50',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
|
||||
128
apps/frontend/src/components/ui/sheet.tsx
Normal file
@@ -0,0 +1,128 @@
|
||||
import { Dialog as SheetPrimitive } from 'radix-ui';
|
||||
import * as React from 'react';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { XIcon } from 'lucide-react';
|
||||
|
||||
function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
|
||||
return <SheetPrimitive.Root data-slot="sheet" {...props} />;
|
||||
}
|
||||
|
||||
function SheetTrigger({ ...props }: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
|
||||
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />;
|
||||
}
|
||||
|
||||
function SheetClose({ ...props }: React.ComponentProps<typeof SheetPrimitive.Close>) {
|
||||
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />;
|
||||
}
|
||||
|
||||
function SheetPortal({ ...props }: React.ComponentProps<typeof SheetPrimitive.Portal>) {
|
||||
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />;
|
||||
}
|
||||
|
||||
function SheetOverlay({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Overlay>) {
|
||||
return (
|
||||
<SheetPrimitive.Overlay
|
||||
data-slot="sheet-overlay"
|
||||
className={cn(
|
||||
'fixed inset-0 z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SheetContent({
|
||||
className,
|
||||
children,
|
||||
side = 'right',
|
||||
showCloseButton = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Content> & {
|
||||
side?: 'top' | 'right' | 'bottom' | 'left';
|
||||
showCloseButton?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<SheetPortal>
|
||||
<SheetOverlay />
|
||||
<SheetPrimitive.Content
|
||||
data-slot="sheet-content"
|
||||
data-side={side}
|
||||
className={cn(
|
||||
'fixed z-50 flex flex-col gap-4 bg-popover bg-clip-padding text-sm text-popover-foreground shadow-lg transition duration-200 ease-in-out data-[side=bottom]:inset-x-0 data-[side=bottom]:bottom-0 data-[side=bottom]:h-auto data-[side=bottom]:border-t data-[side=left]:inset-y-0 data-[side=left]:left-0 data-[side=left]:h-full data-[side=left]:w-3/4 data-[side=left]:border-r data-[side=right]:inset-y-0 data-[side=right]:right-0 data-[side=right]:h-full data-[side=right]:w-3/4 data-[side=right]:border-l data-[side=top]:inset-x-0 data-[side=top]:top-0 data-[side=top]:h-auto data-[side=top]:border-b data-[side=left]:sm:max-w-sm data-[side=right]:sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-[side=bottom]:data-open:slide-in-from-bottom-10 data-[side=left]:data-open:slide-in-from-left-10 data-[side=right]:data-open:slide-in-from-right-10 data-[side=top]:data-open:slide-in-from-top-10 data-closed:animate-out data-closed:fade-out-0 data-[side=bottom]:data-closed:slide-out-to-bottom-10 data-[side=left]:data-closed:slide-out-to-left-10 data-[side=right]:data-closed:slide-out-to-right-10 data-[side=top]:data-closed:slide-out-to-top-10',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<SheetPrimitive.Close data-slot="sheet-close" asChild>
|
||||
<Button variant="ghost" className="absolute top-3 right-3" size="icon-sm">
|
||||
<XIcon />
|
||||
<span className="sr-only">Close</span>
|
||||
</Button>
|
||||
</SheetPrimitive.Close>
|
||||
)}
|
||||
</SheetPrimitive.Content>
|
||||
</SheetPortal>
|
||||
);
|
||||
}
|
||||
|
||||
function SheetHeader({ className, ...props }: React.ComponentProps<'div'>) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sheet-header"
|
||||
className={cn('flex flex-col gap-0.5 p-4', className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SheetFooter({ className, ...props }: React.ComponentProps<'div'>) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sheet-footer"
|
||||
className={cn('mt-auto flex flex-col gap-2 p-4', className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SheetTitle({ className, ...props }: React.ComponentProps<typeof SheetPrimitive.Title>) {
|
||||
return (
|
||||
<SheetPrimitive.Title
|
||||
data-slot="sheet-title"
|
||||
className={cn('font-heading text-base font-medium text-foreground', className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SheetDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Description>) {
|
||||
return (
|
||||
<SheetPrimitive.Description
|
||||
data-slot="sheet-description"
|
||||
className={cn('text-sm text-muted-foreground', className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
Sheet,
|
||||
SheetTrigger,
|
||||
SheetClose,
|
||||
SheetContent,
|
||||
SheetHeader,
|
||||
SheetFooter,
|
||||
SheetTitle,
|
||||
SheetDescription,
|
||||
};
|
||||
1206
apps/frontend/src/components/ui/stepper.tsx
Normal file
@@ -1,5 +1,4 @@
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
type UserAvatarProps = {
|
||||
src?: string | null;
|
||||
@@ -22,25 +21,9 @@ export function UserAvatar({
|
||||
size = 'default',
|
||||
className,
|
||||
}: UserAvatarProps) {
|
||||
const [imageError, setImageError] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setImageError(false);
|
||||
}, [src]);
|
||||
|
||||
const canShowImage = Boolean(src) && !imageError;
|
||||
|
||||
return (
|
||||
<Avatar size={size} className={className}>
|
||||
{canShowImage && (
|
||||
<AvatarImage
|
||||
src={src ?? undefined}
|
||||
alt={alt}
|
||||
onError={() => {
|
||||
setImageError(true);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<AvatarImage src={src ?? undefined} alt={alt} />
|
||||
<AvatarFallback>{getInitials(fallbackText)}</AvatarFallback>
|
||||
</Avatar>
|
||||
);
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
export function AboutPage() {
|
||||
return (
|
||||
<main className="mx-auto flex min-h-[60vh] w-full max-w-6xl items-center justify-center px-6">
|
||||
<section className="w-full max-w-3xl rounded-xl border bg-card p-6 text-card-foreground shadow-sm">
|
||||
<h2 className="text-2xl font-semibold">About</h2>
|
||||
<p className="mt-2 text-sm text-muted-foreground">
|
||||
Ruta de ejemplo funcionando con TanStack Router.
|
||||
</p>
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
508
apps/frontend/src/features/booking/booking-provider.tsx
Normal file
@@ -0,0 +1,508 @@
|
||||
import { ApiClientError, apiClient } from '@/lib/api-client';
|
||||
import type { AdminBooking, ComplexWithRole, Court } from '@repo/api-contract';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import {
|
||||
type ReactNode,
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
} from 'react';
|
||||
import type {
|
||||
BookingCourtSchedule,
|
||||
BookingSlotDraft,
|
||||
BookingStatusFilter,
|
||||
BookingSummary,
|
||||
BookingTimeRange,
|
||||
BookingTimelineSegment,
|
||||
BookingViewMode,
|
||||
} from './booking.types';
|
||||
import {
|
||||
addDaysIso,
|
||||
formatBookingDate,
|
||||
getDayOfWeek,
|
||||
getNowTime,
|
||||
isTodayIso,
|
||||
minutesToTime,
|
||||
timeToMinutes,
|
||||
toIsoDateLocal,
|
||||
} from './lib/booking-time';
|
||||
|
||||
interface BookingProviderProps {
|
||||
children: ReactNode;
|
||||
complex: ComplexWithRole;
|
||||
}
|
||||
|
||||
interface CreateManualBookingPayload {
|
||||
courtId: string;
|
||||
date: string;
|
||||
startTime: string;
|
||||
customerName: string;
|
||||
customerPhone: string;
|
||||
customerEmail?: string;
|
||||
}
|
||||
|
||||
interface BookingContextValue {
|
||||
complex: ComplexWithRole;
|
||||
courts: Court[];
|
||||
bookings: AdminBooking[];
|
||||
schedules: BookingCourtSchedule[];
|
||||
selectedDate: string;
|
||||
selectedSportId: string;
|
||||
selectedStatus: BookingStatusFilter;
|
||||
viewMode: BookingViewMode;
|
||||
visibleTimeRange: BookingTimeRange;
|
||||
timelineHours: string[];
|
||||
summary: BookingSummary;
|
||||
currentTime: string | null;
|
||||
selectedSlot: BookingSlotDraft | null;
|
||||
selectedSegment: BookingTimelineSegment | null;
|
||||
isLoading: boolean;
|
||||
isError: boolean;
|
||||
errorMessage: string | null;
|
||||
isCreateBookingOpen: boolean;
|
||||
createBookingError: string | null;
|
||||
isCreatingBooking: boolean;
|
||||
bookingToolsOpen: boolean;
|
||||
setSelectedDate: (date: string) => void;
|
||||
moveSelectedDate: (amount: number) => void;
|
||||
setSelectedSportId: (sportId: string) => void;
|
||||
setSelectedStatus: (status: BookingStatusFilter) => void;
|
||||
setViewMode: (mode: BookingViewMode) => void;
|
||||
setVisibleTimeRange: (range: BookingTimeRange) => void;
|
||||
openCreateBooking: (draft?: Partial<BookingSlotDraft>) => void;
|
||||
closeCreateBooking: () => void;
|
||||
createBooking: (payload: CreateManualBookingPayload) => Promise<void>;
|
||||
updateBookingStatus: (bookingId: string, status: 'CANCELLED' | 'COMPLETED' | 'NOSHOW') => void;
|
||||
exportDayReport: () => void;
|
||||
openBookingTools: (segment?: BookingTimelineSegment) => void;
|
||||
closeBookingTools: () => void;
|
||||
}
|
||||
|
||||
const BookingContext = createContext<BookingContextValue | null>(null);
|
||||
|
||||
const DEFAULT_TIME_RANGE: BookingTimeRange = {
|
||||
start: '08:00',
|
||||
end: '22:00',
|
||||
};
|
||||
|
||||
function extractMessage(error: unknown, fallback: string) {
|
||||
if (error instanceof ApiClientError) {
|
||||
return error.message || fallback;
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
return error.message || fallback;
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function makeTimelineHours(range: BookingTimeRange) {
|
||||
const start = timeToMinutes(range.start);
|
||||
const end = timeToMinutes(range.end);
|
||||
const hours: string[] = [];
|
||||
|
||||
for (let minute = start; minute <= end; minute += 60) {
|
||||
hours.push(minutesToTime(minute));
|
||||
}
|
||||
|
||||
return hours;
|
||||
}
|
||||
|
||||
function isActiveBooking(booking: AdminBooking) {
|
||||
return (
|
||||
booking.status === 'CONFIRMED' || booking.status === 'COMPLETED' || booking.status === 'NOSHOW'
|
||||
);
|
||||
}
|
||||
|
||||
function getCourtBookings(court: Court, bookings: AdminBooking[], selectedDate: string) {
|
||||
return bookings
|
||||
.filter(
|
||||
(booking) =>
|
||||
booking.courtId === court.id && booking.date === selectedDate && isActiveBooking(booking)
|
||||
)
|
||||
.sort((a, b) => timeToMinutes(a.startTime) - timeToMinutes(b.startTime));
|
||||
}
|
||||
|
||||
function overlapsBooking(start: number, end: number, booking: AdminBooking) {
|
||||
const bookingStart = timeToMinutes(booking.startTime);
|
||||
const bookingEnd = timeToMinutes(booking.endTime);
|
||||
|
||||
return start < bookingEnd && end > bookingStart;
|
||||
}
|
||||
|
||||
function buildSegmentsForCourt(
|
||||
court: Court,
|
||||
bookings: AdminBooking[],
|
||||
selectedDate: string,
|
||||
visibleRange: BookingTimeRange
|
||||
) {
|
||||
const dayOfWeek = getDayOfWeek(selectedDate);
|
||||
const rangeStart = timeToMinutes(visibleRange.start);
|
||||
const rangeEnd = timeToMinutes(visibleRange.end);
|
||||
const courtBookings = getCourtBookings(court, bookings, selectedDate);
|
||||
const segments: BookingTimelineSegment[] = [];
|
||||
const slotDuration = court.slotDurationMinutes;
|
||||
|
||||
const availabilityRanges = court.availability
|
||||
.filter((range) => range.dayOfWeek === dayOfWeek)
|
||||
.map((range) => ({
|
||||
start: Math.max(timeToMinutes(range.startTime), rangeStart),
|
||||
end: Math.min(timeToMinutes(range.endTime), rangeEnd),
|
||||
}))
|
||||
.filter((range) => range.start < range.end)
|
||||
.sort((a, b) => a.start - b.start);
|
||||
|
||||
for (const booking of courtBookings) {
|
||||
const bookingStart = timeToMinutes(booking.startTime);
|
||||
const bookingEnd = timeToMinutes(booking.endTime);
|
||||
|
||||
if (bookingEnd > rangeStart && bookingStart < rangeEnd) {
|
||||
segments.push({
|
||||
id: booking.id,
|
||||
courtId: court.id,
|
||||
status: 'reserved',
|
||||
startTime: booking.startTime,
|
||||
endTime: booking.endTime,
|
||||
startMinutes: Math.max(bookingStart, rangeStart),
|
||||
endMinutes: Math.min(bookingEnd, rangeEnd),
|
||||
booking,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for (const availability of availabilityRanges) {
|
||||
for (
|
||||
let slotStart = availability.start;
|
||||
slotStart + slotDuration <= availability.end;
|
||||
slotStart += slotDuration
|
||||
) {
|
||||
const slotEnd = slotStart + slotDuration;
|
||||
const isBooked = courtBookings.some((booking) =>
|
||||
overlapsBooking(slotStart, slotEnd, booking)
|
||||
);
|
||||
|
||||
if (isBooked) continue;
|
||||
|
||||
const slotStartTime = minutesToTime(slotStart);
|
||||
const slotEndTime = minutesToTime(slotEnd);
|
||||
|
||||
segments.push({
|
||||
id: `${court.id}-free-${slotStartTime}-${slotEndTime}`,
|
||||
courtId: court.id,
|
||||
status: 'free',
|
||||
startTime: slotStartTime,
|
||||
endTime: slotEndTime,
|
||||
startMinutes: slotStart,
|
||||
endMinutes: slotEnd,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
segments.sort((a, b) => a.startMinutes - b.startMinutes);
|
||||
|
||||
return segments;
|
||||
}
|
||||
|
||||
function getSummary(schedules: BookingCourtSchedule[]): BookingSummary {
|
||||
const freeSlots = schedules.reduce((total, schedule) => total + schedule.metrics.free, 0);
|
||||
const reservedSlots = schedules.reduce((total, schedule) => total + schedule.metrics.reserved, 0);
|
||||
const maintenanceSlots = schedules.reduce(
|
||||
(total, schedule) => total + schedule.metrics.maintenance,
|
||||
0
|
||||
);
|
||||
const totalSegments = freeSlots + reservedSlots + maintenanceSlots || 1;
|
||||
|
||||
return {
|
||||
totalReservations: reservedSlots + maintenanceSlots + freeSlots,
|
||||
freeSlots,
|
||||
reservedSlots,
|
||||
maintenanceSlots,
|
||||
freePercent: Math.round((freeSlots / totalSegments) * 100),
|
||||
reservedPercent: Math.round((reservedSlots / totalSegments) * 100),
|
||||
maintenancePercent: Math.round((maintenanceSlots / totalSegments) * 100),
|
||||
};
|
||||
}
|
||||
|
||||
export function BookingProvider({ children, complex }: BookingProviderProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const todayIso = useMemo(() => toIsoDateLocal(new Date()), []);
|
||||
const [selectedDate, setSelectedDate] = useState(todayIso);
|
||||
const [selectedSportId, setSelectedSportId] = useState('all');
|
||||
const [selectedStatus, setSelectedStatus] = useState<BookingStatusFilter>('all');
|
||||
const [viewMode, setViewMode] = useState<BookingViewMode>('panel');
|
||||
const [visibleTimeRange, setVisibleTimeRange] = useState(DEFAULT_TIME_RANGE);
|
||||
const [selectedSlot, setSelectedSlot] = useState<BookingSlotDraft | null>(null);
|
||||
const [isCreateBookingOpen, setIsCreateBookingOpen] = useState(false);
|
||||
const [selectedSegment, setSelectedSegment] = useState<BookingTimelineSegment | null>(null);
|
||||
const [bookingToolsOpen, setBookingToolsOpen] = useState(false);
|
||||
|
||||
const courtsQuery = useQuery({
|
||||
queryKey: ['courts', complex.id],
|
||||
queryFn: () => apiClient.courts.listByComplex(complex.id),
|
||||
});
|
||||
|
||||
const bookingsQuery = useQuery({
|
||||
queryKey: ['admin-bookings', complex.id, selectedDate],
|
||||
queryFn: () =>
|
||||
apiClient.adminBookings.listByComplex(complex.id, {
|
||||
fromDate: selectedDate,
|
||||
}),
|
||||
});
|
||||
|
||||
const bookings = useMemo(
|
||||
() => (bookingsQuery.data?.bookings ?? []).filter((booking) => booking.date === selectedDate),
|
||||
[bookingsQuery.data?.bookings, selectedDate]
|
||||
);
|
||||
|
||||
const courts = useMemo(
|
||||
() => courtsQuery.data?.sort((a, b) => a.name.localeCompare(b.name)) ?? [],
|
||||
[courtsQuery.data]
|
||||
);
|
||||
|
||||
const filteredCourts = useMemo(() => {
|
||||
if (selectedSportId === 'all') return courts;
|
||||
return courts.filter((court) => court.sportId === selectedSportId);
|
||||
}, [courts, selectedSportId]);
|
||||
|
||||
const schedules = useMemo<BookingCourtSchedule[]>(() => {
|
||||
return filteredCourts
|
||||
.map((court) => {
|
||||
const segments = buildSegmentsForCourt(court, bookings, selectedDate, visibleTimeRange);
|
||||
const metrics = {
|
||||
free: segments.filter((segment) => segment.status === 'free').length,
|
||||
reserved: segments.filter((segment) => segment.status === 'reserved').length,
|
||||
maintenance: segments.filter((segment) => segment.status === 'maintenance').length,
|
||||
};
|
||||
|
||||
return { court, segments, metrics };
|
||||
})
|
||||
.filter((schedule) => {
|
||||
if (selectedStatus === 'all') return true;
|
||||
return schedule.segments.some((segment) => segment.status === selectedStatus);
|
||||
});
|
||||
}, [bookings, filteredCourts, selectedDate, selectedStatus, visibleTimeRange]);
|
||||
|
||||
const summary = useMemo(() => getSummary(schedules), [schedules]);
|
||||
const timelineHours = useMemo(() => makeTimelineHours(visibleTimeRange), [visibleTimeRange]);
|
||||
|
||||
const [now, setNow] = useState(() => getNowTime());
|
||||
useEffect(() => {
|
||||
const interval = setInterval(() => {
|
||||
setNow(getNowTime());
|
||||
}, 60 * 1000);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
const currentTime = useMemo(() => {
|
||||
if (!isTodayIso(selectedDate)) return null;
|
||||
const nowMinutes = timeToMinutes(now);
|
||||
const start = timeToMinutes(visibleTimeRange.start);
|
||||
const end = timeToMinutes(visibleTimeRange.end);
|
||||
|
||||
if (nowMinutes < start || nowMinutes > end) return null;
|
||||
return now;
|
||||
}, [selectedDate, visibleTimeRange, now]);
|
||||
|
||||
const createBookingMutation = useMutation({
|
||||
mutationFn: (payload: CreateManualBookingPayload) =>
|
||||
apiClient.adminBookings.create(complex.id, {
|
||||
date: payload.date,
|
||||
courtId: payload.courtId,
|
||||
startTime: payload.startTime,
|
||||
customerName: payload.customerName,
|
||||
customerPhone: payload.customerPhone,
|
||||
customerEmail: payload.customerEmail || undefined,
|
||||
}),
|
||||
onSuccess: async () => {
|
||||
await queryClient.invalidateQueries({ queryKey: ['admin-bookings', complex.id] });
|
||||
await queryClient.invalidateQueries({ queryKey: ['manual-booking-availability'] });
|
||||
setIsCreateBookingOpen(false);
|
||||
setSelectedSlot(null);
|
||||
},
|
||||
});
|
||||
|
||||
const updateStatusMutation = useMutation({
|
||||
mutationFn: (payload: { bookingId: string; status: 'CANCELLED' | 'COMPLETED' | 'NOSHOW' }) =>
|
||||
apiClient.adminBookings.updateStatus(payload.bookingId, { status: payload.status }),
|
||||
onSuccess: async () => {
|
||||
await queryClient.invalidateQueries({ queryKey: ['admin-bookings', complex.id] });
|
||||
},
|
||||
});
|
||||
|
||||
const openCreateBooking = useCallback(
|
||||
(draft?: Partial<BookingSlotDraft>) => {
|
||||
setSelectedSlot({
|
||||
date: draft?.date ?? selectedDate,
|
||||
courtId: draft?.courtId,
|
||||
startTime: draft?.startTime,
|
||||
sportId: draft?.sportId,
|
||||
});
|
||||
setIsCreateBookingOpen(true);
|
||||
},
|
||||
[selectedDate]
|
||||
);
|
||||
|
||||
const openBookingTools = useCallback(
|
||||
(segment?: BookingTimelineSegment) => {
|
||||
setSelectedSegment(segment ?? null);
|
||||
setBookingToolsOpen(true);
|
||||
console.log(JSON.stringify(segment, null, 2));
|
||||
},
|
||||
[selectedDate]
|
||||
);
|
||||
|
||||
const closeBookingTools = () => setBookingToolsOpen(false);
|
||||
|
||||
useEffect(() => {
|
||||
const handleOpenCreateBooking = () => {
|
||||
openCreateBooking();
|
||||
};
|
||||
|
||||
window.addEventListener('playzer:open-booking-create', handleOpenCreateBooking);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('playzer:open-booking-create', handleOpenCreateBooking);
|
||||
};
|
||||
}, [openCreateBooking]);
|
||||
|
||||
const closeCreateBooking = useCallback(() => {
|
||||
setIsCreateBookingOpen(false);
|
||||
setSelectedSlot(null);
|
||||
createBookingMutation.reset();
|
||||
}, [createBookingMutation]);
|
||||
|
||||
const createBooking = useCallback(
|
||||
async (payload: CreateManualBookingPayload) => {
|
||||
await createBookingMutation.mutateAsync(payload);
|
||||
},
|
||||
[createBookingMutation]
|
||||
);
|
||||
|
||||
const updateBookingStatus = useCallback(
|
||||
(bookingId: string, status: 'CANCELLED' | 'COMPLETED' | 'NOSHOW') => {
|
||||
updateStatusMutation.mutate({ bookingId, status });
|
||||
},
|
||||
[updateStatusMutation]
|
||||
);
|
||||
|
||||
const exportDayReport = useCallback(() => {
|
||||
const rows = [
|
||||
['Fecha', 'Cancha', 'Deporte', 'Inicio', 'Fin', 'Cliente', 'Telefono', 'Estado'],
|
||||
...bookings.map((booking) => [
|
||||
booking.date,
|
||||
booking.courtName,
|
||||
booking.sport.name,
|
||||
booking.startTime,
|
||||
booking.endTime,
|
||||
booking.customerName,
|
||||
booking.customerPhone,
|
||||
booking.status,
|
||||
]),
|
||||
];
|
||||
const csv = rows.map((row) => row.map((cell) => `"${cell}"`).join(',')).join('\n');
|
||||
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = `reservas-${complex.complexSlug}-${selectedDate}.csv`;
|
||||
link.click();
|
||||
URL.revokeObjectURL(url);
|
||||
}, [bookings, complex.complexSlug, selectedDate]);
|
||||
|
||||
const value = useMemo<BookingContextValue>(
|
||||
() => ({
|
||||
complex,
|
||||
courts,
|
||||
bookings,
|
||||
schedules,
|
||||
selectedDate,
|
||||
selectedSportId,
|
||||
selectedStatus,
|
||||
viewMode,
|
||||
visibleTimeRange,
|
||||
timelineHours,
|
||||
summary,
|
||||
currentTime,
|
||||
selectedSlot,
|
||||
isLoading: courtsQuery.isLoading || bookingsQuery.isLoading,
|
||||
isError: courtsQuery.isError || bookingsQuery.isError,
|
||||
errorMessage:
|
||||
courtsQuery.isError || bookingsQuery.isError
|
||||
? extractMessage(
|
||||
courtsQuery.error ?? bookingsQuery.error,
|
||||
'No pudimos cargar el panel de reservas.'
|
||||
)
|
||||
: null,
|
||||
isCreateBookingOpen,
|
||||
createBookingError: createBookingMutation.isError
|
||||
? extractMessage(createBookingMutation.error, 'No pudimos crear la reserva.')
|
||||
: null,
|
||||
isCreatingBooking: createBookingMutation.isPending,
|
||||
setSelectedDate,
|
||||
moveSelectedDate: (amount) => setSelectedDate((date) => addDaysIso(date, amount)),
|
||||
setSelectedSportId,
|
||||
setSelectedStatus,
|
||||
setViewMode,
|
||||
setVisibleTimeRange,
|
||||
openCreateBooking,
|
||||
closeCreateBooking,
|
||||
createBooking,
|
||||
updateBookingStatus,
|
||||
exportDayReport,
|
||||
bookingToolsOpen,
|
||||
openBookingTools,
|
||||
closeBookingTools,
|
||||
selectedSegment,
|
||||
}),
|
||||
[
|
||||
bookings,
|
||||
bookingsQuery.error,
|
||||
bookingsQuery.isError,
|
||||
bookingsQuery.isLoading,
|
||||
closeCreateBooking,
|
||||
complex,
|
||||
courts,
|
||||
courtsQuery.error,
|
||||
courtsQuery.isError,
|
||||
courtsQuery.isLoading,
|
||||
createBooking,
|
||||
createBookingMutation.error,
|
||||
createBookingMutation.isError,
|
||||
createBookingMutation.isPending,
|
||||
currentTime,
|
||||
exportDayReport,
|
||||
isCreateBookingOpen,
|
||||
openCreateBooking,
|
||||
schedules,
|
||||
selectedDate,
|
||||
selectedSlot,
|
||||
selectedSportId,
|
||||
selectedStatus,
|
||||
summary,
|
||||
timelineHours,
|
||||
updateBookingStatus,
|
||||
viewMode,
|
||||
visibleTimeRange,
|
||||
bookingToolsOpen,
|
||||
]
|
||||
);
|
||||
|
||||
return <BookingContext.Provider value={value}>{children}</BookingContext.Provider>;
|
||||
}
|
||||
|
||||
export function useBooking() {
|
||||
const context = useContext(BookingContext);
|
||||
|
||||
if (!context) {
|
||||
throw new Error('useBooking must be used within BookingProvider');
|
||||
}
|
||||
|
||||
return context;
|
||||
}
|
||||
|
||||
export { formatBookingDate };
|
||||
76
apps/frontend/src/features/booking/booking.tsx
Normal file
@@ -0,0 +1,76 @@
|
||||
import { useIsMobile } from '@/hooks/use-mobile';
|
||||
import { authClient } from '@/lib/api-client';
|
||||
import { useAuth } from '@/lib/auth';
|
||||
import type { ComplexWithRole } from '@repo/api-contract';
|
||||
import { useState } from 'react';
|
||||
import { BookingProvider } from './booking-provider';
|
||||
import { BookingCreateDialog } from './components/booking-create-dialog';
|
||||
import { BookingDaySummary, BookingQuickActions } from './components/booking-day-summary';
|
||||
import { BookingHeader } from './components/booking-header';
|
||||
import { BookingMobile } from './components/booking-mobile';
|
||||
import { BookingTimeline } from './components/booking-timeline';
|
||||
import { BookingToolbar } from './components/booking-toolbar';
|
||||
import { BookingToolsDialog } from './components/booking-tools-dialog';
|
||||
|
||||
interface BookingProps {
|
||||
complex: ComplexWithRole;
|
||||
}
|
||||
|
||||
export function Booking({ complex }: BookingProps) {
|
||||
const isMobile = useIsMobile();
|
||||
const { user } = useAuth();
|
||||
const [sending, setSending] = useState(false);
|
||||
const [emailSent, setEmailSent] = useState(false);
|
||||
|
||||
const emailNotVerified = user && !user.emailVerified;
|
||||
|
||||
const handleResendVerification = async () => {
|
||||
if (!user?.email || sending) return;
|
||||
setSending(true);
|
||||
try {
|
||||
await authClient.sendVerificationEmail({ email: user.email });
|
||||
setEmailSent(true);
|
||||
setTimeout(() => setEmailSent(false), 6000);
|
||||
} catch {
|
||||
// Silently fail — the banner already shows the email to contact
|
||||
} finally {
|
||||
setSending(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<BookingProvider complex={complex}>
|
||||
{emailNotVerified && (
|
||||
<div className="mb-6 flex items-center justify-between gap-4 rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800 dark:border-amber-800/30 dark:bg-amber-950/30 dark:text-amber-200">
|
||||
<span>
|
||||
No verificaste tu email. Para crear reservas necesitás verificar tu dirección de correo
|
||||
electrónico.
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleResendVerification}
|
||||
disabled={sending}
|
||||
className="shrink-0 rounded-lg bg-amber-200 px-3 py-1.5 text-xs font-medium text-amber-900 transition-colors hover:bg-amber-300 disabled:opacity-50 dark:bg-amber-800 dark:text-amber-50 dark:hover:bg-amber-700"
|
||||
>
|
||||
{sending ? 'Enviando...' : emailSent ? '¡Email enviado!' : 'Reenviar email'}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{isMobile ? (
|
||||
<BookingMobile />
|
||||
) : (
|
||||
<div className="flex flex-col gap-5">
|
||||
<BookingHeader />
|
||||
<BookingToolbar />
|
||||
<BookingTimeline />
|
||||
<div className="grid gap-5 xl:grid-cols-4">
|
||||
<BookingDaySummary />
|
||||
<BookingQuickActions />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<BookingCreateDialog />
|
||||
<BookingToolsDialog />
|
||||
</BookingProvider>
|
||||
);
|
||||
}
|
||||
50
apps/frontend/src/features/booking/booking.types.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import type { AdminBooking, Court } from '@repo/api-contract';
|
||||
|
||||
export type BookingViewMode = 'panel' | 'status';
|
||||
export type BookingStatusFilter = 'all' | 'free' | 'reserved' | 'maintenance';
|
||||
export type BookingSegmentStatus = 'free' | 'reserved' | 'maintenance';
|
||||
|
||||
export interface BookingTimeRange {
|
||||
start: string;
|
||||
end: string;
|
||||
}
|
||||
|
||||
export interface BookingSummary {
|
||||
totalReservations: number;
|
||||
freeSlots: number;
|
||||
reservedSlots: number;
|
||||
maintenanceSlots: number;
|
||||
freePercent: number;
|
||||
reservedPercent: number;
|
||||
maintenancePercent: number;
|
||||
}
|
||||
|
||||
export interface BookingCourtMetrics {
|
||||
free: number;
|
||||
reserved: number;
|
||||
maintenance: number;
|
||||
}
|
||||
|
||||
export interface BookingTimelineSegment {
|
||||
id: string;
|
||||
courtId: string;
|
||||
status: BookingSegmentStatus;
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
startMinutes: number;
|
||||
endMinutes: number;
|
||||
booking?: AdminBooking;
|
||||
}
|
||||
|
||||
export interface BookingCourtSchedule {
|
||||
court: Court;
|
||||
segments: BookingTimelineSegment[];
|
||||
metrics: BookingCourtMetrics;
|
||||
}
|
||||
|
||||
export interface BookingSlotDraft {
|
||||
courtId?: string;
|
||||
date: string;
|
||||
startTime?: string;
|
||||
sportId?: string;
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { DatePicker } from '@/components/ui/date-picker';
|
||||
import { Field, FieldError, FieldLabel } from '@/components/ui/field';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import {
|
||||
ResponsiveDialog,
|
||||
ResponsiveDialogClose,
|
||||
ResponsiveDialogContent,
|
||||
ResponsiveDialogDescription,
|
||||
ResponsiveDialogFooter,
|
||||
ResponsiveDialogHeader,
|
||||
ResponsiveDialogTitle,
|
||||
} from '@/components/ui/responsive-dialog';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
import { useBooking } from '../booking-provider';
|
||||
import {
|
||||
fromIsoDateLocal,
|
||||
getDayOfWeek,
|
||||
minutesToTime,
|
||||
timeToMinutes,
|
||||
toIsoDateLocal,
|
||||
} from '../lib/booking-time';
|
||||
|
||||
const bookingFormSchema = z.object({
|
||||
customerName: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(2, 'Ingresa un nombre válido.')
|
||||
.max(120, 'El nombre no puede superar los 120 caracteres.'),
|
||||
customerPhone: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(6, 'Ingresa un telefono válido.')
|
||||
.max(30, 'El telefono no puede superar los 30 caracteres.'),
|
||||
customerEmail: z.string().email('Ingresá un email válido.').optional().or(z.literal('')),
|
||||
});
|
||||
|
||||
type BookingForm = z.infer<typeof bookingFormSchema>;
|
||||
|
||||
export function BookingCreateDialog() {
|
||||
const {
|
||||
courts,
|
||||
bookings,
|
||||
selectedDate,
|
||||
selectedSlot,
|
||||
isCreateBookingOpen,
|
||||
createBookingError,
|
||||
isCreatingBooking,
|
||||
closeCreateBooking,
|
||||
createBooking,
|
||||
} = useBooking();
|
||||
|
||||
const [date, setDate] = useState(selectedSlot?.date ?? selectedDate);
|
||||
const [sportId, setSportId] = useState(selectedSlot?.sportId ?? 'all');
|
||||
const [courtId, setCourtId] = useState(selectedSlot?.courtId ?? '');
|
||||
const [startTime, setStartTime] = useState(selectedSlot?.startTime ?? '');
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
reset,
|
||||
setFocus,
|
||||
formState: { errors, isValid },
|
||||
} = useForm<BookingForm>({
|
||||
resolver: zodResolver(bookingFormSchema),
|
||||
mode: 'onChange',
|
||||
defaultValues: {
|
||||
customerName: '',
|
||||
customerPhone: '',
|
||||
customerEmail: '',
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!isCreateBookingOpen) return;
|
||||
|
||||
setDate(selectedSlot?.date ?? selectedDate);
|
||||
setSportId(selectedSlot?.sportId ?? 'all');
|
||||
setCourtId(selectedSlot?.courtId ?? '');
|
||||
setStartTime(selectedSlot?.startTime ?? '');
|
||||
reset();
|
||||
|
||||
if (selectedSlot?.courtId && selectedSlot?.startTime) {
|
||||
requestAnimationFrame(() => {
|
||||
setFocus('customerName');
|
||||
});
|
||||
}
|
||||
}, [isCreateBookingOpen, reset, selectedDate, selectedSlot, setFocus]);
|
||||
|
||||
const sports = [...new Map(courts.map((court) => [court.sport.id, court.sport])).values()];
|
||||
const filteredCourts = useMemo(() => {
|
||||
if (sportId === 'all') return courts;
|
||||
return courts.filter((court) => court.sportId === sportId);
|
||||
}, [courts, sportId]);
|
||||
const selectedCourt = courts.find((court) => court.id === courtId);
|
||||
const availableStartTimes = useMemo(() => {
|
||||
if (!selectedCourt) return [];
|
||||
|
||||
const times: string[] = [];
|
||||
const dayOfWeek = getDayOfWeek(date);
|
||||
const dayAvailability = selectedCourt.availability
|
||||
.filter((range) => range.dayOfWeek === dayOfWeek)
|
||||
.sort((a, b) => timeToMinutes(a.startTime) - timeToMinutes(b.startTime));
|
||||
const courtBookings = bookings.filter(
|
||||
(booking) =>
|
||||
booking.date === date &&
|
||||
booking.courtId === selectedCourt.id &&
|
||||
booking.status !== 'CANCELLED'
|
||||
);
|
||||
|
||||
for (const range of dayAvailability) {
|
||||
const start = timeToMinutes(range.startTime);
|
||||
const end = timeToMinutes(range.endTime);
|
||||
|
||||
for (
|
||||
let minute = start;
|
||||
minute + selectedCourt.slotDurationMinutes <= end;
|
||||
minute += selectedCourt.slotDurationMinutes
|
||||
) {
|
||||
const slotEnd = minute + selectedCourt.slotDurationMinutes;
|
||||
const isBooked = courtBookings.some((booking) => {
|
||||
const bookingStart = timeToMinutes(booking.startTime);
|
||||
const bookingEnd = timeToMinutes(booking.endTime);
|
||||
return minute < bookingEnd && slotEnd > bookingStart;
|
||||
});
|
||||
|
||||
if (!isBooked) {
|
||||
times.push(minutesToTime(minute));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return times;
|
||||
}, [bookings, date, selectedCourt]);
|
||||
|
||||
useEffect(() => {
|
||||
if (startTime && !availableStartTimes.includes(startTime)) {
|
||||
setStartTime('');
|
||||
}
|
||||
}, [availableStartTimes, startTime]);
|
||||
|
||||
const onSubmit = async (values: BookingForm) => {
|
||||
await createBooking({
|
||||
courtId,
|
||||
date,
|
||||
startTime,
|
||||
customerName: values.customerName,
|
||||
customerPhone: values.customerPhone,
|
||||
customerEmail: values.customerEmail || undefined,
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<ResponsiveDialog
|
||||
open={isCreateBookingOpen}
|
||||
onOpenChange={(open) => !open && closeCreateBooking()}
|
||||
>
|
||||
<ResponsiveDialogContent
|
||||
className="data-[variant=dialog]:max-w-lg"
|
||||
onOpenAutoFocus={(event) => event.preventDefault()}
|
||||
>
|
||||
<ResponsiveDialogHeader>
|
||||
<ResponsiveDialogTitle>Nueva reserva</ResponsiveDialogTitle>
|
||||
<ResponsiveDialogDescription>
|
||||
Crea un turno para atención telefónica o mostrador.
|
||||
</ResponsiveDialogDescription>
|
||||
</ResponsiveDialogHeader>
|
||||
|
||||
<form id="booking-create-form" className="grid gap-4" onSubmit={handleSubmit(onSubmit)}>
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
<Field>
|
||||
<FieldLabel>Fecha</FieldLabel>
|
||||
<DatePicker
|
||||
value={fromIsoDateLocal(date)}
|
||||
onChange={(nextDate) => {
|
||||
setDate(nextDate ? toIsoDateLocal(nextDate) : selectedDate);
|
||||
}}
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<Field>
|
||||
<FieldLabel>Deporte</FieldLabel>
|
||||
<Select
|
||||
value={sportId}
|
||||
onValueChange={(value) => {
|
||||
setSportId(value);
|
||||
setCourtId('');
|
||||
setStartTime('');
|
||||
}}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Todos</SelectItem>
|
||||
{sports.map((sport) => (
|
||||
<SelectItem key={sport.id} value={sport.id}>
|
||||
{sport.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
|
||||
<Field>
|
||||
<FieldLabel>Cancha</FieldLabel>
|
||||
<Select
|
||||
value={courtId}
|
||||
onValueChange={(value) => {
|
||||
setCourtId(value);
|
||||
setStartTime('');
|
||||
}}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Selecciona una cancha" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{filteredCourts.map((court) => (
|
||||
<SelectItem key={court.id} value={court.id}>
|
||||
{court.name} · {court.sport.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
|
||||
<Field>
|
||||
<FieldLabel>Horario</FieldLabel>
|
||||
<Select value={startTime} onValueChange={setStartTime}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Selecciona un horario" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{availableStartTimes.map((time) => (
|
||||
<SelectItem key={time} value={time}>
|
||||
{time}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
</div>
|
||||
|
||||
<Field data-invalid={Boolean(errors.customerName)}>
|
||||
<FieldLabel htmlFor="customerName">Nombre</FieldLabel>
|
||||
<Input
|
||||
id="customerName"
|
||||
placeholder="Ej: Juan Perez"
|
||||
aria-invalid={Boolean(errors.customerName)}
|
||||
{...register('customerName')}
|
||||
/>
|
||||
<FieldError errors={[errors.customerName]} />
|
||||
</Field>
|
||||
|
||||
<Field data-invalid={Boolean(errors.customerPhone)}>
|
||||
<FieldLabel htmlFor="customerPhone">Teléfono</FieldLabel>
|
||||
<Input
|
||||
id="customerPhone"
|
||||
type="tel"
|
||||
placeholder="Ej: 3875551234"
|
||||
aria-invalid={Boolean(errors.customerPhone)}
|
||||
{...register('customerPhone')}
|
||||
/>
|
||||
<FieldError errors={[errors.customerPhone]} />
|
||||
</Field>
|
||||
|
||||
<Field data-invalid={Boolean(errors.customerEmail)}>
|
||||
<FieldLabel htmlFor="customerEmail">
|
||||
Email <span className="text-muted-foreground font-normal">(opcional)</span>
|
||||
</FieldLabel>
|
||||
<Input
|
||||
id="customerEmail"
|
||||
type="email"
|
||||
placeholder="Ej: juan@ejemplo.com"
|
||||
aria-invalid={Boolean(errors.customerEmail)}
|
||||
{...register('customerEmail')}
|
||||
/>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
Se enviará la confirmación de la reserva por email.
|
||||
</p>
|
||||
<FieldError errors={[errors.customerEmail]} />
|
||||
</Field>
|
||||
|
||||
{createBookingError && <p className="text-sm text-destructive">{createBookingError}</p>}
|
||||
</form>
|
||||
|
||||
<ResponsiveDialogFooter>
|
||||
<ResponsiveDialogClose asChild>
|
||||
<Button variant="outline">Cancelar</Button>
|
||||
</ResponsiveDialogClose>
|
||||
<Button
|
||||
type="submit"
|
||||
form="booking-create-form"
|
||||
disabled={!isValid || isCreatingBooking || !courtId || !startTime}
|
||||
>
|
||||
{isCreatingBooking ? 'Guardando...' : 'Crear reserva'}
|
||||
</Button>
|
||||
</ResponsiveDialogFooter>
|
||||
</ResponsiveDialogContent>
|
||||
</ResponsiveDialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import { CalendarDays, Download, Drill, ShieldCheck, UsersRound } from 'lucide-react';
|
||||
import { useBooking } from '../booking-provider';
|
||||
import { formatBookingDate, toIsoDateLocal } from '../lib/booking-time';
|
||||
|
||||
export function BookingDaySummary() {
|
||||
const { selectedDate, summary } = useBooking();
|
||||
|
||||
return (
|
||||
<section className="rounded-lg border bg-card/85 p-5 shadow-sm xl:col-span-3">
|
||||
<div className="mb-4">
|
||||
<h2 className="text-base font-semibold">Resumen del día</h2>
|
||||
<p className="mt-1 text-sm capitalize text-muted-foreground">
|
||||
{formatBookingDate(selectedDate, { year: 'numeric' })}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-3 md:grid-cols-4">
|
||||
<SummaryCard
|
||||
label="Total de bloques"
|
||||
value={summary.totalReservations}
|
||||
icon={CalendarDays}
|
||||
className="border-border bg-background/45"
|
||||
/>
|
||||
<SummaryCard
|
||||
label="Libres"
|
||||
value={summary.freeSlots}
|
||||
detail={`${summary.freePercent}% del total`}
|
||||
icon={UsersRound}
|
||||
className="border-primary/30 bg-primary/10 text-primary"
|
||||
/>
|
||||
<SummaryCard
|
||||
label="Reservados"
|
||||
value={summary.reservedSlots}
|
||||
detail={`${summary.reservedPercent}% del total`}
|
||||
icon={ShieldCheck}
|
||||
className="border-reserved/35 bg-reserved/10 text-reserved"
|
||||
/>
|
||||
<SummaryCard
|
||||
label="Mantenimiento"
|
||||
value={summary.maintenanceSlots}
|
||||
detail={`${summary.maintenancePercent}% del total`}
|
||||
icon={Drill}
|
||||
className="border-maintenance/35 bg-maintenance/10 text-maintenance"
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
interface SummaryCardProps {
|
||||
label: string;
|
||||
value: number;
|
||||
detail?: string;
|
||||
icon: typeof CalendarDays;
|
||||
className: string;
|
||||
}
|
||||
|
||||
function SummaryCard({ label, value, detail, icon: Icon, className }: SummaryCardProps) {
|
||||
return (
|
||||
<article className={`rounded-lg border p-4 ${className}`}>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex size-10 shrink-0 items-center justify-center rounded-md bg-transparent">
|
||||
<Icon className="size-5" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<p className="truncate text-sm text-muted-foreground">{label}</p>
|
||||
<p className="text-2xl font-semibold leading-tight">{value}</p>
|
||||
{detail && <p className="mt-1 truncate text-xs text-muted-foreground">{detail}</p>}
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
export function BookingQuickActions() {
|
||||
const { selectedDate, selectedStatus, setSelectedDate, setSelectedStatus, exportDayReport } =
|
||||
useBooking();
|
||||
const todayIso = toIsoDateLocal(new Date());
|
||||
const isViewingTodayReservations = selectedDate === todayIso && selectedStatus === 'reserved';
|
||||
const isViewingMaintenance = selectedStatus === 'maintenance';
|
||||
|
||||
return (
|
||||
<section className="rounded-lg border bg-card/85 p-5 shadow-sm">
|
||||
<h2 className="text-base font-semibold">Acciones rápidas</h2>
|
||||
<div className="mt-3 grid gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setSelectedDate(todayIso);
|
||||
setSelectedStatus(isViewingTodayReservations ? 'all' : 'reserved');
|
||||
}}
|
||||
aria-pressed={isViewingTodayReservations}
|
||||
className="flex h-10 items-center gap-3 rounded-md border bg-background/45 px-3 text-left text-sm transition-colors hover:bg-muted aria-pressed:border-reserved/50 aria-pressed:bg-reserved/10"
|
||||
>
|
||||
<CalendarDays className="size-4 text-muted-foreground" />
|
||||
{isViewingTodayReservations ? 'Ver todos los estados' : 'Ver reservas de hoy'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setSelectedStatus(isViewingMaintenance ? 'all' : 'maintenance')}
|
||||
aria-pressed={isViewingMaintenance}
|
||||
className="flex h-10 items-center gap-3 rounded-md border bg-background/45 px-3 text-left text-sm transition-colors hover:bg-muted aria-pressed:border-maintenance/50 aria-pressed:bg-maintenance/10"
|
||||
>
|
||||
<Drill className="size-4 text-maintenance" />
|
||||
{isViewingMaintenance ? 'Ver todos los estados' : 'Ver mantenimiento'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={exportDayReport}
|
||||
className="flex h-10 items-center gap-3 rounded-md border bg-background/45 px-3 text-left text-sm transition-colors hover:bg-muted"
|
||||
>
|
||||
<Download className="size-4 text-primary" />
|
||||
Exportar reporte
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { useBooking } from '../booking-provider';
|
||||
|
||||
export function BookingHeader() {
|
||||
const { complex } = useBooking();
|
||||
|
||||
return (
|
||||
<section>
|
||||
<div>
|
||||
<h1 className="text-3xl font-semibold tracking-normal text-foreground">
|
||||
Panel de Reservas
|
||||
</h1>
|
||||
<p className="mt-2 text-sm text-muted-foreground">
|
||||
Gestiona las canchas de {complex.complexName}
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
1034
apps/frontend/src/features/booking/components/booking-mobile.tsx
Normal file
@@ -0,0 +1,18 @@
|
||||
const items = [
|
||||
{ label: 'Libre', className: 'bg-primary' },
|
||||
{ label: 'Reservado', className: 'bg-reserved' },
|
||||
{ label: 'Mantenimiento', className: 'bg-maintenance' },
|
||||
];
|
||||
|
||||
export function BookingStatusLegend() {
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-5 text-sm text-muted-foreground">
|
||||
{items.map((item) => (
|
||||
<span key={item.label} className="inline-flex items-center gap-2">
|
||||
<span className={`size-3 rounded-full ${item.className}`} />
|
||||
{item.label}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { ChevronLeft, ChevronRight, Dumbbell, Plus, UserX, Users } from 'lucide-react';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { useBooking } from '../booking-provider';
|
||||
import type { BookingCourtSchedule, BookingTimelineSegment } from '../booking.types';
|
||||
import { timeToMinutes } from '../lib/booking-time';
|
||||
import { BookingStatusLegend } from './booking-status-legend';
|
||||
|
||||
const courtInfoWidth = 220;
|
||||
const hourWidth = 104;
|
||||
|
||||
export function BookingTimeline() {
|
||||
const {
|
||||
schedules,
|
||||
timelineHours,
|
||||
visibleTimeRange,
|
||||
currentTime,
|
||||
isLoading,
|
||||
isError,
|
||||
errorMessage,
|
||||
} = useBooking();
|
||||
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const prevCurrentTimeRef = useRef<string | null>(null);
|
||||
|
||||
const rangeStart = timeToMinutes(visibleTimeRange.start);
|
||||
const rangeEnd = timeToMinutes(visibleTimeRange.end);
|
||||
const totalMinutes = rangeEnd - rangeStart;
|
||||
const gridWidth = Math.max((timelineHours.length - 1) * hourWidth, 760);
|
||||
const timelineMarks = timelineHours.map((hour) => ({
|
||||
hour,
|
||||
left: ((timeToMinutes(hour) - rangeStart) / totalMinutes) * 100,
|
||||
}));
|
||||
|
||||
useEffect(() => {
|
||||
if (!currentTime || !scrollRef.current) return;
|
||||
if (currentTime === prevCurrentTimeRef.current) return;
|
||||
prevCurrentTimeRef.current = currentTime;
|
||||
|
||||
const container = scrollRef.current;
|
||||
const indicatorLeft =
|
||||
courtInfoWidth + ((timeToMinutes(currentTime) - rangeStart) / totalMinutes) * gridWidth;
|
||||
const targetScroll = indicatorLeft - container.clientWidth / 2;
|
||||
const clampedScroll = Math.max(
|
||||
0,
|
||||
Math.min(targetScroll, container.scrollWidth - container.clientWidth)
|
||||
);
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
container.scrollTo({ left: clampedScroll, behavior: 'smooth' });
|
||||
});
|
||||
}, [currentTime, rangeStart, totalMinutes, gridWidth]);
|
||||
|
||||
return (
|
||||
<section className="overflow-hidden rounded-lg border bg-card/85 shadow-sm">
|
||||
<div className="flex items-center justify-between gap-4 border-b px-4 py-4">
|
||||
<BookingStatusLegend />
|
||||
<div className="hidden items-center gap-2 md:flex">
|
||||
<Button type="button" size="icon-sm" variant="ghost">
|
||||
<ChevronLeft className="size-4" />
|
||||
</Button>
|
||||
<Button type="button" size="icon-sm" variant="ghost">
|
||||
<ChevronRight className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isLoading && (
|
||||
<div className="px-4 py-10 text-sm text-muted-foreground">Cargando reservas...</div>
|
||||
)}
|
||||
|
||||
{isError && !isLoading && (
|
||||
<div className="px-4 py-10 text-sm text-destructive">{errorMessage}</div>
|
||||
)}
|
||||
|
||||
{!isLoading && !isError && schedules.length === 0 && (
|
||||
<div className="px-4 py-10 text-sm text-muted-foreground">
|
||||
No hay canchas para los filtros seleccionados.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isLoading && !isError && schedules.length > 0 && (
|
||||
<div ref={scrollRef} className="booking-scrollbar overflow-x-auto overflow-y-hidden">
|
||||
<div className="relative min-w-full" style={{ width: courtInfoWidth + gridWidth }}>
|
||||
<TimelineHeader
|
||||
timelineMarks={timelineMarks}
|
||||
courtInfoWidth={courtInfoWidth}
|
||||
gridWidth={gridWidth}
|
||||
/>
|
||||
|
||||
<div className="divide-y">
|
||||
{schedules.map((schedule) => (
|
||||
<BookingCourtRow
|
||||
key={schedule.court.id}
|
||||
schedule={schedule}
|
||||
courtInfoWidth={courtInfoWidth}
|
||||
gridWidth={gridWidth}
|
||||
rangeStart={rangeStart}
|
||||
totalMinutes={totalMinutes}
|
||||
timelineMarks={timelineMarks}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{currentTime && (
|
||||
<CurrentTimeIndicator
|
||||
time={currentTime}
|
||||
courtInfoWidth={courtInfoWidth}
|
||||
gridWidth={gridWidth}
|
||||
rangeStart={rangeStart}
|
||||
totalMinutes={totalMinutes}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
interface TimelineHeaderProps {
|
||||
timelineMarks: Array<{ hour: string; left: number }>;
|
||||
courtInfoWidth: number;
|
||||
gridWidth: number;
|
||||
}
|
||||
|
||||
function TimelineHeader({ timelineMarks, courtInfoWidth, gridWidth }: TimelineHeaderProps) {
|
||||
return (
|
||||
<div
|
||||
className="sticky top-0 z-20 grid border-b bg-card/95 z-auto"
|
||||
style={{ gridTemplateColumns: `${courtInfoWidth}px ${gridWidth}px` }}
|
||||
>
|
||||
<div className="sticky left-0 z-30 border-r bg-card/95 px-4 py-3 shadow-[8px_0_18px_-18px_oklch(0_0_0/0.45)]" />
|
||||
<div className="relative h-12">
|
||||
{timelineMarks.map((mark) => (
|
||||
<div
|
||||
key={mark.hour}
|
||||
className="absolute top-0 flex h-full items-center border-l px-3 text-sm text-muted-foreground first:border-l-0"
|
||||
style={{ left: `${mark.left}%` }}
|
||||
>
|
||||
{mark.hour}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface BookingCourtRowProps {
|
||||
schedule: BookingCourtSchedule;
|
||||
courtInfoWidth: number;
|
||||
gridWidth: number;
|
||||
rangeStart: number;
|
||||
totalMinutes: number;
|
||||
timelineMarks: Array<{ hour: string; left: number }>;
|
||||
}
|
||||
|
||||
function BookingCourtRow({
|
||||
schedule,
|
||||
courtInfoWidth,
|
||||
gridWidth,
|
||||
rangeStart,
|
||||
totalMinutes,
|
||||
timelineMarks,
|
||||
}: BookingCourtRowProps) {
|
||||
return (
|
||||
<div
|
||||
className="grid min-h-[96px]"
|
||||
style={{ gridTemplateColumns: `${courtInfoWidth}px ${gridWidth}px` }}
|
||||
>
|
||||
<BookingCourtInfo schedule={schedule} />
|
||||
<div className="relative bg-background/20 py-4">
|
||||
<div className="absolute inset-y-0 left-0 right-0 opacity-70">
|
||||
{timelineMarks.map((mark) => (
|
||||
<span
|
||||
key={mark.hour}
|
||||
className="absolute top-0 h-full border-l first:border-l-0"
|
||||
style={{ left: `${mark.left}%` }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="relative h-16">
|
||||
{schedule.segments.map((segment) => (
|
||||
<BookingSlotBlock
|
||||
key={segment.id}
|
||||
segment={segment}
|
||||
schedule={schedule}
|
||||
rangeStart={rangeStart}
|
||||
totalMinutes={totalMinutes}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function BookingCourtInfo({ schedule }: { schedule: BookingCourtSchedule }) {
|
||||
return (
|
||||
<div className="sticky left-0 z-10 flex items-center gap-3 border-r bg-card/95 px-4 py-4 shadow-[8px_0_18px_-18px_oklch(0_0_0/0.45)]">
|
||||
<div className="flex size-12 shrink-0 items-center justify-center rounded-lg border border-primary/40 bg-primary/15 text-primary">
|
||||
<Dumbbell className="size-6" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<h2 className="truncate text-base font-semibold">{schedule.court.name}</h2>
|
||||
<p className="truncate text-sm text-muted-foreground">{schedule.court.sport.name}</p>
|
||||
<div className="mt-1 flex items-center gap-3 text-xs text-muted-foreground">
|
||||
<span className="inline-flex items-center gap-1">
|
||||
<span className="size-2 rounded-full bg-primary" />
|
||||
{schedule.metrics.free}
|
||||
</span>
|
||||
<span className="inline-flex items-center gap-1">
|
||||
<span className="size-2 rounded-full bg-reserved" />
|
||||
{schedule.metrics.reserved}
|
||||
</span>
|
||||
<span className="inline-flex items-center gap-1">
|
||||
<span className="size-2 rounded-full bg-maintenance" />
|
||||
{schedule.metrics.maintenance}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface BookingSlotBlockProps {
|
||||
segment: BookingTimelineSegment;
|
||||
schedule: BookingCourtSchedule;
|
||||
rangeStart: number;
|
||||
totalMinutes: number;
|
||||
}
|
||||
|
||||
function BookingSlotBlock({ segment, schedule, rangeStart, totalMinutes }: BookingSlotBlockProps) {
|
||||
const { openCreateBooking, updateBookingStatus, openBookingTools } = useBooking();
|
||||
const left = ((segment.startMinutes - rangeStart) / totalMinutes) * 100;
|
||||
const width = ((segment.endMinutes - segment.startMinutes) / totalMinutes) * 100;
|
||||
const isFree = segment.status === 'free';
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
'absolute top-0 flex h-16 min-w-0 flex-col justify-center overflow-hidden rounded-md border px-2 text-left text-xs shadow-sm transition-all hover:-translate-y-0.5 hover:shadow-md focus-visible:ring-2 focus-visible:ring-ring',
|
||||
segment.status === 'free' &&
|
||||
'border-primary/70 bg-primary/20 text-primary hover:bg-primary/25',
|
||||
segment.status === 'reserved' &&
|
||||
'border-reserved/70 bg-reserved/80 text-reserved-foreground',
|
||||
segment.status === 'maintenance' &&
|
||||
'border-maintenance/80 bg-maintenance/75 text-maintenance-foreground',
|
||||
segment.booking?.status === 'COMPLETED' &&
|
||||
'border-reserved/70 bg-reserved/25 dark:text-reserved-foreground text-gray-600 line-through',
|
||||
segment.booking?.status === 'NOSHOW' &&
|
||||
'border-amber-500/60 bg-amber-500/50 text-amber-950 dark:text-amber-200'
|
||||
)}
|
||||
style={{
|
||||
left: `calc(${left}% + 4px)`,
|
||||
width: `calc(${width}% - 8px)`,
|
||||
}}
|
||||
onClick={(event) => {
|
||||
if (isFree) {
|
||||
openCreateBooking({
|
||||
courtId: schedule.court.id,
|
||||
startTime: segment.startTime,
|
||||
sportId: schedule.court.sportId,
|
||||
});
|
||||
} else if (segment.booking?.status === 'NOSHOW') {
|
||||
return;
|
||||
} else {
|
||||
if (event.shiftKey && segment.booking?.status === 'CONFIRMED') {
|
||||
updateBookingStatus(segment.booking.id, 'COMPLETED');
|
||||
} else {
|
||||
openBookingTools(segment);
|
||||
}
|
||||
}
|
||||
}}
|
||||
title={
|
||||
segment.booking
|
||||
? `${segment.booking.customerName} · ${segment.startTime} - ${segment.endTime}`
|
||||
: `${segment.startTime} - ${segment.endTime}`
|
||||
}
|
||||
>
|
||||
{isFree ? (
|
||||
<span className="flex items-center justify-center gap-1 text-sm font-medium">
|
||||
<Plus className="size-4" />
|
||||
<span className="hidden sm:inline">Reservar</span>
|
||||
</span>
|
||||
) : (
|
||||
<>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="truncate text-sm font-medium">
|
||||
{segment.startTime} - {segment.endTime}
|
||||
</span>
|
||||
{segment.booking?.status === 'NOSHOW' && (
|
||||
<span title="No Show - El cliente no se presentó">
|
||||
<UserX className="size-3 shrink-0" />
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<span className="mt-1 flex items-center gap-1 truncate opacity-90">
|
||||
<Users className="size-3" />
|
||||
{segment.booking?.customerName ?? 'Mantenimiento'}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
interface CurrentTimeIndicatorProps {
|
||||
time: string;
|
||||
courtInfoWidth: number;
|
||||
gridWidth: number;
|
||||
rangeStart: number;
|
||||
totalMinutes: number;
|
||||
}
|
||||
|
||||
function CurrentTimeIndicator({
|
||||
time,
|
||||
courtInfoWidth,
|
||||
gridWidth,
|
||||
rangeStart,
|
||||
totalMinutes,
|
||||
}: CurrentTimeIndicatorProps) {
|
||||
const left = courtInfoWidth + ((timeToMinutes(time) - rangeStart) / totalMinutes) * gridWidth;
|
||||
|
||||
return (
|
||||
<div className="pointer-events-none absolute bottom-0 top-12 z-[5]" style={{ left }}>
|
||||
<div className="absolute left-0 top-0 -translate-x-1/2 -translate-y-1/2 rounded-md bg-primary px-2 py-1 text-xs font-medium text-primary-foreground shadow-sm">
|
||||
{time}
|
||||
</div>
|
||||
<div className="absolute bottom-0 left-0 top-0 w-px bg-primary" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { DatePicker } from '@/components/ui/date-picker';
|
||||
import { Field, FieldLabel } from '@/components/ui/field';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { ChevronLeft, ChevronRight, Clock, SlidersHorizontal } from 'lucide-react';
|
||||
import { useBooking } from '../booking-provider';
|
||||
import type { BookingStatusFilter } from '../booking.types';
|
||||
import { fromIsoDateLocal, toIsoDateLocal } from '../lib/booking-time';
|
||||
|
||||
const timeRangeOptions = [
|
||||
{ label: '08:00 - 22:00', start: '08:00', end: '22:00' },
|
||||
{ label: '06:00 - 00:00', start: '06:00', end: '23:59' },
|
||||
{ label: '08:00 - 14:00', start: '08:00', end: '14:00' },
|
||||
{ label: '14:00 - 22:00', start: '14:00', end: '22:00' },
|
||||
];
|
||||
|
||||
const statusOptions: Array<{ value: BookingStatusFilter; label: string }> = [
|
||||
{ value: 'all', label: 'Todos' },
|
||||
{ value: 'free', label: 'Libre' },
|
||||
{ value: 'reserved', label: 'Reservado' },
|
||||
{ value: 'maintenance', label: 'Mantenimiento' },
|
||||
];
|
||||
|
||||
export function BookingToolbar() {
|
||||
const {
|
||||
courts,
|
||||
selectedDate,
|
||||
selectedSportId,
|
||||
selectedStatus,
|
||||
visibleTimeRange,
|
||||
setSelectedDate,
|
||||
moveSelectedDate,
|
||||
setSelectedSportId,
|
||||
setSelectedStatus,
|
||||
setVisibleTimeRange,
|
||||
} = useBooking();
|
||||
|
||||
const sports = [...new Map(courts.map((court) => [court.sport.id, court.sport])).values()];
|
||||
const activeRangeValue = `${visibleTimeRange.start}-${visibleTimeRange.end}`;
|
||||
|
||||
return (
|
||||
<section className="rounded-lg border bg-card/85 p-4 shadow-sm">
|
||||
<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-[1fr_1fr_1.6fr_1.1fr_auto] xl:items-end">
|
||||
<Field>
|
||||
<FieldLabel>Deporte</FieldLabel>
|
||||
<Select value={selectedSportId} onValueChange={setSelectedSportId}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Todos</SelectItem>
|
||||
{sports.map((sport) => (
|
||||
<SelectItem key={sport.id} value={sport.id}>
|
||||
{sport.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
|
||||
<Field>
|
||||
<FieldLabel>Estado</FieldLabel>
|
||||
<Select
|
||||
value={selectedStatus}
|
||||
onValueChange={(value) => setSelectedStatus(value as BookingStatusFilter)}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{statusOptions.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
|
||||
<Field>
|
||||
<FieldLabel>Fecha</FieldLabel>
|
||||
<div className="grid grid-cols-[auto_1fr_auto] gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => moveSelectedDate(-1)}
|
||||
>
|
||||
<ChevronLeft className="size-4" />
|
||||
</Button>
|
||||
<DatePicker
|
||||
value={fromIsoDateLocal(selectedDate)}
|
||||
onChange={(date) =>
|
||||
setSelectedDate(date ? toIsoDateLocal(date) : toIsoDateLocal(new Date()))
|
||||
}
|
||||
/>
|
||||
<Button type="button" variant="outline" size="icon" onClick={() => moveSelectedDate(1)}>
|
||||
<ChevronRight className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</Field>
|
||||
|
||||
<Field>
|
||||
<FieldLabel>Hora</FieldLabel>
|
||||
<Select
|
||||
value={activeRangeValue}
|
||||
onValueChange={(value) => {
|
||||
const option = timeRangeOptions.find((item) => `${item.start}-${item.end}` === value);
|
||||
if (option) {
|
||||
setVisibleTimeRange({ start: option.start, end: option.end });
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<Clock className="mr-2 size-4 text-muted-foreground" />
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{timeRangeOptions.map((option) => (
|
||||
<SelectItem
|
||||
key={`${option.start}-${option.end}`}
|
||||
value={`${option.start}-${option.end}`}
|
||||
>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
|
||||
<Button variant="outline" className="xl:self-end">
|
||||
<SlidersHorizontal className="size-4" />
|
||||
Filtros avanzados
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,503 @@
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
ResponsiveDialog,
|
||||
ResponsiveDialogClose,
|
||||
ResponsiveDialogContent,
|
||||
ResponsiveDialogDescription,
|
||||
ResponsiveDialogFooter,
|
||||
ResponsiveDialogHeader,
|
||||
ResponsiveDialogTitle,
|
||||
} from '@/components/ui/responsive-dialog';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { useIsMobile } from '@/hooks/use-mobile';
|
||||
import { cn } from '@/lib/utils';
|
||||
import {
|
||||
AlertTriangle,
|
||||
BadgeCheck,
|
||||
CalendarDays,
|
||||
CheckCircle2,
|
||||
Clock,
|
||||
MapPin,
|
||||
MessageCircle,
|
||||
Phone,
|
||||
User,
|
||||
Wrench,
|
||||
XCircle,
|
||||
} from 'lucide-react';
|
||||
import { useBooking } from '../booking-provider';
|
||||
|
||||
function formatDate(date: string | undefined) {
|
||||
if (!date) return '';
|
||||
|
||||
const formatted = new Intl.DateTimeFormat('es-AR', {
|
||||
weekday: 'long',
|
||||
day: 'numeric',
|
||||
month: 'long',
|
||||
}).format(new Date(`${date}T00:00:00`));
|
||||
|
||||
return formatted
|
||||
.split(' ')
|
||||
.map((word, index) => {
|
||||
if (index === 0 || index === 3) {
|
||||
return word.charAt(0).toUpperCase() + word.slice(1);
|
||||
}
|
||||
return word;
|
||||
})
|
||||
.join(' ');
|
||||
}
|
||||
|
||||
const statusConfig: Record<string, { label: string; className: string }> = {
|
||||
CONFIRMED: {
|
||||
label: 'Reservada',
|
||||
className: 'bg-emerald-500/15 text-emerald-400 border-emerald-500/30',
|
||||
},
|
||||
COMPLETED: {
|
||||
label: 'Completada',
|
||||
className: 'bg-sky-500/15 text-sky-400 border-sky-500/30',
|
||||
},
|
||||
CANCELLED: {
|
||||
label: 'Cancelada',
|
||||
className: 'bg-red-500/15 text-red-400 border-red-500/30',
|
||||
},
|
||||
NOSHOW: {
|
||||
label: 'No show',
|
||||
className: 'bg-amber-500/15 text-amber-400 border-amber-500/30',
|
||||
},
|
||||
};
|
||||
|
||||
export function BookingToolsDialog() {
|
||||
const { selectedSegment, bookingToolsOpen, closeBookingTools, updateBookingStatus } =
|
||||
useBooking();
|
||||
const isMobile = useIsMobile();
|
||||
const booking = selectedSegment?.booking;
|
||||
|
||||
const status = statusConfig[booking?.status ?? 'CONFIRMED'] ?? {
|
||||
label: booking?.status,
|
||||
className: 'bg-slate-500/15 text-slate-300 border-slate-500/30',
|
||||
};
|
||||
|
||||
const sendWhatsappReminder = () => {
|
||||
const phone = booking?.customerPhone;
|
||||
if (!phone) return;
|
||||
|
||||
const message = `
|
||||
Hola ${booking?.customerName}. \nTe recordamos que tenés una reserva para el día *${formatDate(booking?.date)} de ${booking?.startTime} a ${booking?.endTime} en la cancha ${booking?.courtName} (${booking?.sport?.name})*. ¡Te esperamos! \nSi no vas a poder asistir, por favor avisanos para que otros clientes puedan reservar. Gracias.\n\n*Equipo de ${booking?.complexName}*`;
|
||||
|
||||
const url = `https://wa.me/${phone}?text=${encodeURIComponent(message)}`;
|
||||
window.open(url, '_blank');
|
||||
};
|
||||
|
||||
const updateStatus = (nextStatus: 'CANCELLED' | 'COMPLETED' | 'NOSHOW') => {
|
||||
if (!booking?.id) return;
|
||||
updateBookingStatus(booking.id, nextStatus);
|
||||
closeBookingTools();
|
||||
};
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<ResponsiveDialog
|
||||
open={bookingToolsOpen}
|
||||
onOpenChange={(open) => !open && closeBookingTools()}
|
||||
>
|
||||
<ResponsiveDialogContent
|
||||
className="data-[variant=drawer]:!h-[92dvh] data-[variant=drawer]:!max-h-[92dvh] data-[variant=drawer]:overflow-hidden data-[variant=drawer]:px-0 data-[variant=drawer]:pb-0"
|
||||
onOpenAutoFocus={(event) => event.preventDefault()}
|
||||
>
|
||||
<MobileBookingToolsSheet
|
||||
status={status}
|
||||
onComplete={() => updateStatus('COMPLETED')}
|
||||
onCancel={() => updateStatus('CANCELLED')}
|
||||
onReminder={sendWhatsappReminder}
|
||||
onNoShow={() => updateStatus('NOSHOW')}
|
||||
/>
|
||||
</ResponsiveDialogContent>
|
||||
</ResponsiveDialog>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<ResponsiveDialog open={bookingToolsOpen} onOpenChange={(open) => !open && closeBookingTools()}>
|
||||
<ResponsiveDialogContent
|
||||
className="data-[variant=dialog]:max-w-5xl data-[variant=drawer]:max-h-[92dvh] data-[variant=drawer]:overflow-y-auto data-[variant=drawer]:px-4 data-[variant=drawer]:pb-5"
|
||||
onOpenAutoFocus={(event) => event.preventDefault()}
|
||||
>
|
||||
<ResponsiveDialogHeader className="data-[variant=drawer]:px-0 data-[variant=drawer]:text-left">
|
||||
<ResponsiveDialogTitle>Detalles de la reserva</ResponsiveDialogTitle>
|
||||
<ResponsiveDialogDescription>
|
||||
Administra la reserva y su estado.
|
||||
</ResponsiveDialogDescription>
|
||||
</ResponsiveDialogHeader>
|
||||
|
||||
<section className="mx-0 px-0 pt-3 pb-3 sm:-mx-6 sm:px-6 sm:pb-5">
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-3 sm:gap-0">
|
||||
<DetailItem
|
||||
icon={<MapPin className="h-5 w-5" />}
|
||||
label="Cancha"
|
||||
value={selectedSegment?.booking?.courtName ?? '-'}
|
||||
helper={selectedSegment?.booking?.sport?.name}
|
||||
withDivider
|
||||
/>
|
||||
|
||||
<DetailItem
|
||||
icon={<BadgeCheck className="h-5 w-5" />}
|
||||
label="Estado actual"
|
||||
value={status.label}
|
||||
valueClassName="text-emerald-400 uppercase dark:text-emerald-500"
|
||||
withDivider
|
||||
/>
|
||||
|
||||
<DetailItem
|
||||
icon={<User className="h-5 w-5" />}
|
||||
label="Cliente"
|
||||
value={selectedSegment?.booking?.customerName ?? '-'}
|
||||
/>
|
||||
|
||||
<DetailItem
|
||||
icon={<Clock className="h-5 w-5" />}
|
||||
label="Fecha"
|
||||
value={`${formatDate(selectedSegment?.booking?.date)}`}
|
||||
withDivider
|
||||
className="sm:pt-10"
|
||||
/>
|
||||
|
||||
<DetailItem
|
||||
icon={<Clock className="h-5 w-5" />}
|
||||
label="Hora"
|
||||
value={`${selectedSegment?.booking?.startTime} a ${selectedSegment?.booking?.endTime}`}
|
||||
withDivider
|
||||
className="sm:pt-10"
|
||||
/>
|
||||
|
||||
<DetailItem
|
||||
icon={<Phone className="h-5 w-5" />}
|
||||
label="Teléfono"
|
||||
value={selectedSegment?.booking?.customerPhone ?? '-'}
|
||||
className="sm:pt-10"
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<Separator className="dark:bg-slate-800 bg-slate-300" />
|
||||
|
||||
<section className="space-y-3">
|
||||
<div>
|
||||
<h3 className="font-medium text-slate-100">Acciones disponibles</h3>
|
||||
<p className="text-sm text-slate-400">
|
||||
Elegí qué hacer según lo que ocurrió con el cliente.
|
||||
</p>
|
||||
</div>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<ActionButton
|
||||
icon={<CheckCircle2 className="h-5 w-5" />}
|
||||
title="Completar reserva"
|
||||
description="El cliente se presentó para usar la cancha."
|
||||
className="border-emerald-500/40 bg-emerald-500/10 text-lg text-emerald-600 hover:bg-emerald-500/15 hover:text-emerald-800"
|
||||
onClick={() => {
|
||||
updateStatus('COMPLETED');
|
||||
}}
|
||||
/>
|
||||
|
||||
<ActionButton
|
||||
icon={<XCircle className="h-5 w-5" />}
|
||||
title="Cancelar reserva"
|
||||
description="El cliente avisó que no va a venir. La cancha vuelve a estar disponible."
|
||||
className="border-red-500/40 bg-red-500/10 text-lg text-red-600 hover:bg-red-500/15 hover:text-red-800"
|
||||
onClick={() => {
|
||||
updateStatus('CANCELLED');
|
||||
}}
|
||||
/>
|
||||
|
||||
<ActionButton
|
||||
icon={<MessageCircle className="h-5 w-5" />}
|
||||
title="Enviar recordatorio"
|
||||
description="Enviar un mensaje por WhatsApp al cliente."
|
||||
className="border-sky-500/40 bg-sky-500/10 text-lg text-sky-600 hover:bg-sky-500/15 hover:text-sky-800"
|
||||
onClick={sendWhatsappReminder}
|
||||
/>
|
||||
|
||||
<ActionButton
|
||||
icon={<AlertTriangle className="h-5 w-5" />}
|
||||
title="Marcar como No Show"
|
||||
description="El cliente no vino y no canceló."
|
||||
className="border-amber-500/40 bg-amber-500/10 text-lg text-amber-600 hover:bg-amber-500/15 hover:text-amber-800"
|
||||
onClick={() => {
|
||||
updateStatus('NOSHOW');
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<ResponsiveDialogFooter className="data-[variant=drawer]:px-0">
|
||||
<ResponsiveDialogClose asChild>
|
||||
<Button variant="outline" className="data-[variant=drawer]:h-11">
|
||||
Cerrar
|
||||
</Button>
|
||||
</ResponsiveDialogClose>
|
||||
</ResponsiveDialogFooter>
|
||||
</ResponsiveDialogContent>
|
||||
</ResponsiveDialog>
|
||||
);
|
||||
}
|
||||
|
||||
function MobileBookingToolsSheet({
|
||||
status,
|
||||
onComplete,
|
||||
onCancel,
|
||||
onReminder,
|
||||
onNoShow,
|
||||
}: {
|
||||
status: { label: string | undefined; className: string };
|
||||
onComplete: () => void;
|
||||
onCancel: () => void;
|
||||
onReminder: () => void;
|
||||
onNoShow: () => void;
|
||||
}) {
|
||||
const { selectedSegment } = useBooking();
|
||||
const booking = selectedSegment?.booking;
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col pt-3">
|
||||
<ResponsiveDialogHeader className="shrink-0 px-4 pb-3 text-left">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<ResponsiveDialogTitle className="text-lg">Reserva</ResponsiveDialogTitle>
|
||||
<ResponsiveDialogDescription>
|
||||
{booking?.courtName ?? '-'} · {booking?.startTime ?? '--:--'} a{' '}
|
||||
{booking?.endTime ?? '--:--'}
|
||||
</ResponsiveDialogDescription>
|
||||
</div>
|
||||
<span
|
||||
className={cn(
|
||||
'shrink-0 rounded-full border px-3 py-1 text-xs font-semibold uppercase tracking-normal',
|
||||
status.className
|
||||
)}
|
||||
>
|
||||
{status.label ?? '-'}
|
||||
</span>
|
||||
</div>
|
||||
</ResponsiveDialogHeader>
|
||||
|
||||
<div className="min-h-0 flex-1 overflow-y-auto px-4 pb-4">
|
||||
<section className="rounded-lg border border-border/70 bg-card/75 p-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex size-12 shrink-0 items-center justify-center rounded-lg bg-primary/15 text-primary">
|
||||
<MapPin className="size-6" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<p className="text-xs text-muted-foreground">Cancha</p>
|
||||
<p className="truncate text-xl font-semibold">{booking?.courtName ?? '-'}</p>
|
||||
<p className="text-sm text-muted-foreground">{booking?.sport?.name ?? '-'}</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="mt-3 grid gap-2">
|
||||
<MobileDetailRow
|
||||
icon={<User className="size-5" />}
|
||||
label="Cliente"
|
||||
value={booking?.customerName ?? '-'}
|
||||
/>
|
||||
<MobileDetailRow
|
||||
icon={<Phone className="size-5" />}
|
||||
label="Teléfono"
|
||||
value={booking?.customerPhone ?? '-'}
|
||||
/>
|
||||
<MobileDetailRow
|
||||
icon={<CalendarDays className="size-5" />}
|
||||
label="Fecha"
|
||||
value={formatDate(booking?.date) || '-'}
|
||||
/>
|
||||
<MobileDetailRow
|
||||
icon={<Clock className="size-5" />}
|
||||
label="Horario"
|
||||
value={`${booking?.startTime ?? '--:--'} a ${booking?.endTime ?? '--:--'}`}
|
||||
/>
|
||||
<MobileDetailRow
|
||||
icon={<Wrench className="size-5" />}
|
||||
label="Estado"
|
||||
value={status.label ?? '-'}
|
||||
valueClassName="uppercase text-primary"
|
||||
/>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<section className="shrink-0 border-t border-border/70 bg-popover/95 px-4 py-3">
|
||||
<h3 className="text-sm font-medium">Acciones</h3>
|
||||
<div className="mt-3 grid grid-cols-2 gap-2">
|
||||
<MobileActionButton
|
||||
icon={<CheckCircle2 className="size-5" />}
|
||||
label="Completar"
|
||||
className="border-primary/45 bg-primary/12 text-primary"
|
||||
onClick={onComplete}
|
||||
/>
|
||||
<MobileActionButton
|
||||
icon={<MessageCircle className="size-5" />}
|
||||
label="Recordar"
|
||||
className="border-reserved/45 bg-reserved/12 text-reserved"
|
||||
onClick={onReminder}
|
||||
/>
|
||||
<MobileActionButton
|
||||
icon={<XCircle className="size-5" />}
|
||||
label="Cancelar"
|
||||
className="border-destructive/45 bg-destructive/12 text-destructive"
|
||||
onClick={onCancel}
|
||||
/>
|
||||
<MobileActionButton
|
||||
icon={<AlertTriangle className="size-5" />}
|
||||
label="No show"
|
||||
className="border-warning/50 bg-warning/12 text-warning"
|
||||
onClick={onNoShow}
|
||||
/>
|
||||
</div>
|
||||
<ResponsiveDialogFooter className="px-0 pb-0 pt-3">
|
||||
<ResponsiveDialogClose asChild>
|
||||
<Button variant="outline" className="h-11 w-full rounded-lg">
|
||||
Cerrar
|
||||
</Button>
|
||||
</ResponsiveDialogClose>
|
||||
</ResponsiveDialogFooter>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MobileDetailRow({
|
||||
icon,
|
||||
label,
|
||||
value,
|
||||
valueClassName,
|
||||
}: {
|
||||
icon: React.ReactNode;
|
||||
label: string;
|
||||
value: string;
|
||||
valueClassName?: string;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex items-center gap-3 rounded-lg border border-border/60 bg-secondary/35 p-3">
|
||||
<div className="flex size-10 shrink-0 items-center justify-center rounded-lg bg-secondary text-muted-foreground">
|
||||
{icon}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<p className="text-xs text-muted-foreground">{label}</p>
|
||||
<p className={cn('truncate text-base font-semibold', valueClassName)}>{value}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MobileActionButton({
|
||||
icon,
|
||||
label,
|
||||
className,
|
||||
onClick,
|
||||
}: {
|
||||
icon: React.ReactNode;
|
||||
label: string;
|
||||
className: string;
|
||||
onClick: () => void;
|
||||
}) {
|
||||
return (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className={cn('h-14 justify-start rounded-lg px-3 text-sm font-semibold', className)}
|
||||
onClick={onClick}
|
||||
>
|
||||
{icon}
|
||||
{label}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
function DetailItem({
|
||||
icon,
|
||||
label,
|
||||
value,
|
||||
helper,
|
||||
valueClassName,
|
||||
withDivider,
|
||||
className,
|
||||
}: {
|
||||
icon: React.ReactNode;
|
||||
label: string;
|
||||
value: string;
|
||||
helper?: string;
|
||||
valueClassName?: string;
|
||||
withDivider?: boolean;
|
||||
className?: string;
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'relative flex items-start gap-4 rounded-lg bg-secondary/45 p-3 sm:bg-transparent sm:px-5 sm:py-1',
|
||||
className
|
||||
)}
|
||||
>
|
||||
{withDivider && (
|
||||
<div
|
||||
className="
|
||||
absolute
|
||||
right-0
|
||||
top-1/2
|
||||
hidden
|
||||
h-16
|
||||
w-px
|
||||
-translate-y-1/2
|
||||
dark:bg-slate-800
|
||||
bg-slate-300
|
||||
sm:block
|
||||
"
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-lg bg-slate-300/80 text-slate-800 dark:bg-slate-800/80 dark:text-slate-300">
|
||||
{icon}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm text-slate-400">{label}</p>
|
||||
<p
|
||||
className={cn(
|
||||
'mt-1 text-lg leading-tight font-semibold tracking-normal text-gray-600 sm:text-[22px] dark:text-white',
|
||||
valueClassName
|
||||
)}
|
||||
>
|
||||
{value}
|
||||
</p>
|
||||
{helper && <p className="mt-1 text-sm text-slate-500">{helper}</p>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ActionButton({
|
||||
icon,
|
||||
title,
|
||||
description,
|
||||
className,
|
||||
onClick,
|
||||
}: {
|
||||
icon: React.ReactNode;
|
||||
title: string;
|
||||
description: string;
|
||||
className: string;
|
||||
onClick?: () => void;
|
||||
}) {
|
||||
return (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className={`h-auto min-h-[76px] justify-start rounded-lg p-4 text-left ${className}`}
|
||||
onClick={onClick}
|
||||
>
|
||||
<div className="flex gap-3">
|
||||
<div className="mt-0.5">{icon}</div>
|
||||
<div>
|
||||
<p className="font-semibold">{title}</p>
|
||||
<p className="mt-1 whitespace-normal text-sm font-normal leading-relaxed dark:text-slate-200 text-slate-500">
|
||||
{description}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
66
apps/frontend/src/features/booking/lib/booking-time.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import type { DayOfWeek } from '@repo/api-contract';
|
||||
|
||||
export function toIsoDateLocal(date: Date) {
|
||||
const year = date.getFullYear();
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(date.getDate()).padStart(2, '0');
|
||||
return `${year}-${month}-${day}`;
|
||||
}
|
||||
|
||||
export function fromIsoDateLocal(dateIso: string): Date | undefined {
|
||||
const [year, month, day] = dateIso.split('-').map(Number);
|
||||
if (!year || !month || !day) return undefined;
|
||||
return new Date(year, month - 1, day);
|
||||
}
|
||||
|
||||
export function timeToMinutes(time: string) {
|
||||
const [hours, minutes] = time.split(':').map(Number);
|
||||
return hours * 60 + minutes;
|
||||
}
|
||||
|
||||
export function minutesToTime(minutes: number) {
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const remainder = minutes % 60;
|
||||
return `${String(hours).padStart(2, '0')}:${String(remainder).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
export function addDaysIso(dateIso: string, amount: number) {
|
||||
const date = fromIsoDateLocal(dateIso) ?? new Date();
|
||||
date.setDate(date.getDate() + amount);
|
||||
return toIsoDateLocal(date);
|
||||
}
|
||||
|
||||
export function isTodayIso(dateIso: string) {
|
||||
return dateIso === toIsoDateLocal(new Date());
|
||||
}
|
||||
|
||||
export function formatBookingDate(dateIso: string, options?: Intl.DateTimeFormatOptions) {
|
||||
const date = fromIsoDateLocal(dateIso);
|
||||
if (!date) return dateIso;
|
||||
|
||||
return new Intl.DateTimeFormat('es-AR', {
|
||||
weekday: 'long',
|
||||
day: '2-digit',
|
||||
month: 'long',
|
||||
year: options?.year,
|
||||
...options,
|
||||
}).format(date);
|
||||
}
|
||||
|
||||
export function getDayOfWeek(dateIso: string): DayOfWeek {
|
||||
const date = fromIsoDateLocal(dateIso) ?? new Date();
|
||||
const day = date.getDay();
|
||||
|
||||
if (day === 0) return 'SUNDAY';
|
||||
if (day === 1) return 'MONDAY';
|
||||
if (day === 2) return 'TUESDAY';
|
||||
if (day === 3) return 'WEDNESDAY';
|
||||
if (day === 4) return 'THURSDAY';
|
||||
if (day === 5) return 'FRIDAY';
|
||||
return 'SATURDAY';
|
||||
}
|
||||
|
||||
export function getNowTime() {
|
||||
const now = new Date();
|
||||
return `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
|
||||
}
|
||||
@@ -32,7 +32,7 @@ export function ComplexCourtsPage({ complexSlug }: ComplexCourtsPageProps) {
|
||||
});
|
||||
|
||||
return (
|
||||
<main className="mx-auto w-full max-w-6xl space-y-6 px-4 py-4 sm:px-6">
|
||||
<main className="mx-auto w-full max-w-6xl space-y-6 py-4">
|
||||
<section className="rounded-xl border bg-card p-4 text-card-foreground shadow-sm sm:p-5">
|
||||
<h2 className="text-2xl font-semibold">
|
||||
{complexQuery.data?.complexName ?? 'Configurar canchas'}
|
||||
|
||||
@@ -43,7 +43,7 @@ export function ComplexSettingsPage({ complexSlug }: ComplexSettingsPageProps) {
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-6xl px-4 py-4 sm:px-6">
|
||||
<div className="mx-auto w-full max-w-6xl py-4">
|
||||
<section className="rounded-xl border bg-card p-4 text-card-foreground shadow-sm sm:p-5">
|
||||
<h2 className="text-2xl font-semibold">
|
||||
<Settings className="mb-1 mr-2 inline size-6" />
|
||||
@@ -54,7 +54,7 @@ export function ComplexSettingsPage({ complexSlug }: ComplexSettingsPageProps) {
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<div className="mt-6 grid gap-6 lg:grid-cols-[200px_1fr]">
|
||||
<div className="mt-6 grid gap-5 lg:grid-cols-[200px_1fr] lg:gap-6">
|
||||
<nav className="flex flex-row gap-1 overflow-x-auto lg:flex-col lg:overflow-visible">
|
||||
{tabs.map((tab) => {
|
||||
const Icon = tab.icon;
|
||||
|
||||