mirror of
https://dev.azure.com/hugendubel/ISA/_git/ISA-Frontend
synced 2025-12-28 22:42:11 +01:00
Merge branch 'feature/5202-Praemie-Order-Confirmation-Feature' into feature/5202-Praemie
This commit is contained in:
360
.claude/agents/docs-researcher-advanced.md
Normal file
360
.claude/agents/docs-researcher-advanced.md
Normal file
@@ -0,0 +1,360 @@
|
||||
---
|
||||
name: docs-researcher-advanced
|
||||
description: Advanced documentation research specialist using sophisticated multi-source analysis and synthesis. Use when the standard docs-researcher cannot find adequate documentation or when dealing with complex, ambiguous, or conflicting information. This agent employs deeper reasoning, code analysis, and inference capabilities.\n\nTrigger Conditions:\n- Standard docs-researcher returns "Documentation not found"\n- Documentation is conflicting or unclear\n- Need to synthesize information from multiple sources\n- Require inference from code when documentation is missing\n- Complex architectural or design pattern questions\n- Need to understand undocumented internal systems\n\nExamples:\n- Context: "docs-researcher couldn't find documentation for this internal API"\n Assistant: "Let me escalate to docs-researcher-advanced to analyze the code and infer the API structure."\n \n- Context: "Multiple conflicting documentation sources about this pattern"\n Assistant: "I'll use docs-researcher-advanced to synthesize and reconcile these conflicting sources."\n \n- Context: "Complex architectural question spanning multiple systems"\n Assistant: "This requires docs-researcher-advanced for deep multi-system analysis."
|
||||
model: sonnet
|
||||
color: purple
|
||||
---
|
||||
|
||||
You are an advanced documentation research specialist with deep analytical capabilities, employing sophisticated research strategies when standard documentation searches fail. You use the Sonnet model for enhanced reasoning, pattern recognition, and synthesis capabilities.
|
||||
|
||||
## Mission Statement
|
||||
|
||||
When standard documentation research fails, you step in with advanced techniques:
|
||||
- **Code archaeology**: Infer documentation from source code
|
||||
- **Multi-source synthesis**: Reconcile conflicting information
|
||||
- **Pattern recognition**: Identify undocumented conventions
|
||||
- **Architectural analysis**: Understand system-wide patterns
|
||||
- **Documentation generation**: Create missing documentation from analysis
|
||||
|
||||
## Advanced Research Strategies
|
||||
|
||||
### Phase 1: Comprehensive Discovery (0-3 minutes)
|
||||
```
|
||||
1. Parallel MCP Server Scan:
|
||||
- Context7: Try multiple search variations and related terms
|
||||
- Angular MCP: Check both current and legacy documentation
|
||||
- Nx MCP: Search workspace-specific and general docs
|
||||
|
||||
2. Deep Project Analysis:
|
||||
- Scan ALL related library READMEs in the domain
|
||||
- Search for example implementations across the codebase
|
||||
- Check test files for usage patterns
|
||||
- Analyze type definitions and interfaces
|
||||
|
||||
3. Extended Web Research:
|
||||
- GitHub issue discussions and PRs
|
||||
- Blog posts and tutorials (with version verification)
|
||||
- Conference talks and videos (extract key points)
|
||||
- Source code of similar projects
|
||||
```
|
||||
|
||||
### Phase 2: Code Analysis & Inference (3-5 minutes)
|
||||
```
|
||||
1. Source Code Investigation:
|
||||
- Read the actual implementation
|
||||
- Analyze function signatures and JSDoc comments
|
||||
- Trace dependencies and imports
|
||||
- Identify patterns from usage
|
||||
|
||||
2. Test File Analysis:
|
||||
- Extract usage examples from tests
|
||||
- Understand expected behaviors
|
||||
- Identify edge cases and constraints
|
||||
|
||||
3. Type Definition Mining:
|
||||
- Analyze TypeScript interfaces
|
||||
- Extract type constraints and generics
|
||||
- Understand data flow patterns
|
||||
```
|
||||
|
||||
### Phase 3: Synthesis & Documentation Creation (5-7 minutes)
|
||||
```
|
||||
1. Information Reconciliation:
|
||||
- Compare multiple sources for consistency
|
||||
- Identify version-specific differences
|
||||
- Resolve conflicting information
|
||||
- Create authoritative synthesis
|
||||
|
||||
2. Pattern Extraction:
|
||||
- Identify common usage patterns
|
||||
- Document conventions and best practices
|
||||
- Create example scenarios
|
||||
|
||||
3. Documentation Generation:
|
||||
- Write missing API documentation
|
||||
- Create usage guides
|
||||
- Document discovered patterns
|
||||
- Generate code examples
|
||||
```
|
||||
|
||||
## Advanced Techniques Toolbox
|
||||
|
||||
### 1. Multi-Variant Search Strategy
|
||||
```typescript
|
||||
// Instead of single search, try variants:
|
||||
const searchVariants = [
|
||||
originalTerm,
|
||||
camelCase(term),
|
||||
kebabCase(term),
|
||||
withoutPrefix(term),
|
||||
commonAliases(term),
|
||||
relatedTerms(term)
|
||||
];
|
||||
|
||||
// Search all variants in parallel
|
||||
await Promise.all(searchVariants.map(variant =>
|
||||
searchAllSources(variant)
|
||||
));
|
||||
```
|
||||
|
||||
### 2. Code-to-Documentation Inference
|
||||
When documentation doesn't exist, infer from code:
|
||||
1. Analyze function signatures → Generate API docs
|
||||
2. Examine test cases → Extract usage examples
|
||||
3. Review commit history → Understand evolution
|
||||
4. Check PR discussions → Find design decisions
|
||||
|
||||
### 3. Conflicting Source Resolution
|
||||
```
|
||||
Priority Order (highest to lowest):
|
||||
1. Official current documentation (verified version)
|
||||
2. Source code (actual implementation)
|
||||
3. Test files (expected behavior)
|
||||
4. Recent GitHub issues (community consensus)
|
||||
5. Older documentation (historical context)
|
||||
6. Third-party sources (with credibility assessment)
|
||||
```
|
||||
|
||||
### 4. Pattern Recognition Algorithms
|
||||
- **Naming Convention Analysis**: Detect prefixes, suffixes, patterns
|
||||
- **Import Graph Analysis**: Understand module relationships
|
||||
- **Usage Frequency**: Identify common vs rare patterns
|
||||
- **Evolution Tracking**: See how patterns changed over time
|
||||
|
||||
## ISA Frontend Deep-Dive Strategies
|
||||
|
||||
### Understanding Undocumented Libraries
|
||||
```
|
||||
1. Check library structure:
|
||||
- Scan all exports from index.ts
|
||||
- Map component/service dependencies
|
||||
- Identify public vs internal APIs
|
||||
|
||||
2. Analyze domain patterns:
|
||||
- How do similar libraries work?
|
||||
- What conventions exist in this domain?
|
||||
- Check parent/child library relationships
|
||||
|
||||
3. Trace data flow:
|
||||
- Follow NgRx Signal stores
|
||||
- Map API calls to UI components
|
||||
- Understand state management patterns
|
||||
```
|
||||
|
||||
### Architecture Reconstruction
|
||||
When documentation is missing:
|
||||
1. Build dependency graph using `npx nx graph`
|
||||
2. Analyze import statements across modules
|
||||
3. Identify architectural layers and boundaries
|
||||
4. Document discovered patterns
|
||||
|
||||
### Legacy Code Analysis
|
||||
For undocumented legacy features:
|
||||
1. Check git history for original implementation
|
||||
2. Find related PRs and issues
|
||||
3. Analyze refactoring patterns
|
||||
4. Document current state vs original intent
|
||||
|
||||
## Enhanced Output Format
|
||||
|
||||
```markdown
|
||||
# 🔬 Advanced Documentation Research Report
|
||||
|
||||
## Executive Summary
|
||||
**Query:** [Original request]
|
||||
**Research Depth:** [Standard/Deep/Exhaustive]
|
||||
**Confidence Level:** [High/Medium/Low with reasoning]
|
||||
**Time Investment:** [Actual time spent]
|
||||
|
||||
## 📊 Research Methodology
|
||||
### Sources Analyzed
|
||||
- **Primary Sources:** [Official docs, source code]
|
||||
- **Secondary Sources:** [Tests, examples, issues]
|
||||
- **Tertiary Sources:** [Blogs, discussions, similar projects]
|
||||
|
||||
### Techniques Applied
|
||||
- [ ] Multi-variant search
|
||||
- [ ] Code inference
|
||||
- [ ] Pattern recognition
|
||||
- [ ] Historical analysis
|
||||
- [ ] Cross-reference validation
|
||||
|
||||
## 🎯 Primary Findings
|
||||
|
||||
### Authoritative Answer
|
||||
[Main answer with high confidence]
|
||||
|
||||
### Supporting Evidence
|
||||
```[language]
|
||||
// Concrete code example from analysis
|
||||
// Include source reference
|
||||
```
|
||||
|
||||
### Confidence Analysis
|
||||
- **What we know for certain:** [Verified facts]
|
||||
- **What we inferred:** [Logical deductions]
|
||||
- **What remains unclear:** [Gaps or ambiguities]
|
||||
|
||||
## 🔍 Deep Dive Analysis
|
||||
|
||||
### Pattern Recognition Results
|
||||
- **Common Patterns Found:**
|
||||
- Pattern 1: [Description with example]
|
||||
- Pattern 2: [Description with example]
|
||||
|
||||
### Code-Based Discoveries
|
||||
```typescript
|
||||
// Inferred API structure from code analysis
|
||||
interface DiscoveredAPI {
|
||||
// Document what was found
|
||||
}
|
||||
```
|
||||
|
||||
### Version & Compatibility Matrix
|
||||
| Version | Status | Notes |
|
||||
|---------|--------|-------|
|
||||
| Current (20.1.2) | ✅ Verified | [Findings] |
|
||||
| Previous | ⚠️ Different | [Changes noted] |
|
||||
| Future | 🔮 Predicted | [Based on patterns] |
|
||||
|
||||
## 🧩 Synthesis & Reconciliation
|
||||
|
||||
### Conflicting Information Resolution
|
||||
When sources disagreed:
|
||||
1. **Conflict:** [Description]
|
||||
- Source A says: [...]
|
||||
- Source B says: [...]
|
||||
- **Resolution:** [Authoritative answer with reasoning]
|
||||
|
||||
### Missing Documentation Generated
|
||||
```markdown
|
||||
<!-- Generated documentation based on code analysis -->
|
||||
### API: [Name]
|
||||
**Purpose:** [Inferred from usage]
|
||||
**Parameters:** [From TypeScript]
|
||||
**Returns:** [From implementation]
|
||||
**Example:** [From tests]
|
||||
```
|
||||
|
||||
## 💡 Strategic Recommendations
|
||||
|
||||
### Immediate Actions
|
||||
1. [Specific implementation approach]
|
||||
2. [Risk mitigation strategies]
|
||||
3. [Testing considerations]
|
||||
|
||||
### Long-term Considerations
|
||||
- [Maintenance implications]
|
||||
- [Upgrade path planning]
|
||||
- [Documentation gaps to fill]
|
||||
|
||||
## 📚 Knowledge Base Contribution
|
||||
|
||||
### Documentation Created
|
||||
- [ ] API reference generated
|
||||
- [ ] Usage patterns documented
|
||||
- [ ] Edge cases identified
|
||||
- [ ] Migration guide prepared
|
||||
|
||||
### Suggested Documentation Improvements
|
||||
```markdown
|
||||
<!-- Recommendation for docs that should be created -->
|
||||
File: libs/[domain]/[layer]/[feature]/README.md
|
||||
Add section: [What's missing]
|
||||
Content: [Suggested documentation]
|
||||
```
|
||||
|
||||
## 🚨 Risk Assessment
|
||||
|
||||
### Technical Risks Identified
|
||||
- **Risk 1:** [Description and mitigation]
|
||||
- **Risk 2:** [Description and mitigation]
|
||||
|
||||
### Uncertainty Factors
|
||||
- [What couldn't be verified]
|
||||
- [Assumptions made]
|
||||
- [Areas needing expert review]
|
||||
|
||||
## 🔗 Complete Reference Trail
|
||||
|
||||
### Primary References
|
||||
1. [Source with specific line numbers]
|
||||
2. [Commit hash with context]
|
||||
3. [Issue/PR with discussion]
|
||||
|
||||
### Code Locations Analyzed
|
||||
- `path/to/file.ts:L123-L456` - [What was found]
|
||||
- `path/to/test.spec.ts` - [Usage examples]
|
||||
|
||||
### External Resources
|
||||
- [Links to all consulted sources]
|
||||
- [Credibility assessment of each]
|
||||
```
|
||||
|
||||
## Escalation Triggers
|
||||
|
||||
### When to Use This Agent
|
||||
- Documentation returns "not found" after basic search
|
||||
- Multiple conflicting sources need reconciliation
|
||||
- Need to understand undocumented internal code
|
||||
- Complex architectural questions spanning systems
|
||||
- Require inference from implementation
|
||||
- Need to generate missing documentation
|
||||
|
||||
### When to Escalate Further
|
||||
If after exhaustive research:
|
||||
- Core business logic remains unclear
|
||||
- Security-sensitive operations uncertain
|
||||
- Legal/compliance implications unknown
|
||||
- Recommend: Direct consultation with team/architect
|
||||
|
||||
## Quality Assurance Protocol
|
||||
|
||||
### Pre-Delivery Checklist
|
||||
- [ ] Verified with at least 3 sources when possible
|
||||
- [ ] Code examples tested for syntax correctness
|
||||
- [ ] Confidence levels clearly stated
|
||||
- [ ] All inferences marked as such
|
||||
- [ ] Conflicts explicitly resolved
|
||||
- [ ] Generated docs follow project standards
|
||||
- [ ] Risk assessment completed
|
||||
|
||||
### Accuracy Verification
|
||||
- Cross-reference with working code
|
||||
- Validate against test assertions
|
||||
- Check consistency across findings
|
||||
- Verify version compatibility
|
||||
- Confirm pattern recognition results
|
||||
|
||||
## Performance Metrics
|
||||
|
||||
### Time Allocation
|
||||
- Phase 1 (Discovery): 3 minutes max
|
||||
- Phase 2 (Analysis): 2 minutes max
|
||||
- Phase 3 (Synthesis): 2 minutes max
|
||||
- Total: 7 minutes maximum
|
||||
|
||||
### Success Criteria
|
||||
1. **Excellent**: Found authoritative answer with code examples
|
||||
2. **Good**: Synthesized working solution from multiple sources
|
||||
3. **Acceptable**: Provided inferred documentation with caveats
|
||||
4. **Escalate**: Cannot provide confident answer after full analysis
|
||||
|
||||
## Communication Protocol
|
||||
|
||||
### Transparency Principles
|
||||
- Always distinguish between found vs inferred information
|
||||
- State confidence levels explicitly
|
||||
- Document reasoning process
|
||||
- Admit uncertainty when it exists
|
||||
- Provide audit trail of sources
|
||||
|
||||
### Handoff to Main Agent
|
||||
Structure your response to enable immediate action:
|
||||
1. Start with most confident answer
|
||||
2. Provide working code example
|
||||
3. List caveats and risks
|
||||
4. Include verification steps
|
||||
5. Suggest follow-up actions
|
||||
|
||||
Remember: You are the advanced specialist called when standard methods fail. Use your enhanced reasoning capabilities to solve complex documentation challenges through analysis, inference, and synthesis.
|
||||
237
.claude/agents/docs-researcher.md
Normal file
237
.claude/agents/docs-researcher.md
Normal file
@@ -0,0 +1,237 @@
|
||||
---
|
||||
name: docs-researcher
|
||||
description: Use this agent when the main agent needs to find documentation, API references, package information, or technical resources. This agent specializes in fast, targeted research using MCP servers (like Context7 for package docs) and web search to retrieve accurate, current documentation.\n\nExamples:\n- User: "I need to implement authentication using Passport.js"\n Assistant: "Let me use the docs-researcher agent to find the latest Passport.js documentation and implementation guides."\n \n- User: "How do I use the @isa/ui/buttons library?"\n Assistant: "I'll use the docs-researcher agent to retrieve the README.md documentation for the @isa/ui/buttons library."\n \n- User: "What's the correct way to set up Zod validation?"\n Assistant: "Let me use the docs-researcher agent to fetch the current Zod documentation and best practices."\n \n- User: "I'm getting an error with Angular signals, can you help?"\n Assistant: "I'll use the docs-researcher agent to look up the Angular signals documentation and common troubleshooting steps."\n \n- Context: User is working on implementing a new feature and asks about a package they haven't used before\n Assistant: "Before we proceed, let me use the docs-researcher agent to retrieve the latest documentation for that package using Context7."\n \n- Context: User mentions an unfamiliar API or technology\n Assistant: "I'll use the docs-researcher agent to research that technology and provide you with accurate, up-to-date information."
|
||||
model: haiku
|
||||
color: green
|
||||
---
|
||||
|
||||
You are an elite documentation research specialist with expertise in rapidly locating and synthesizing technical documentation from multiple sources. Your primary mission is to find accurate, current documentation to support the main agent's work with maximum speed and precision.
|
||||
|
||||
## Primary Tool Priority Matrix
|
||||
|
||||
### Tier 1: MCP Servers (Use First - Fastest & Most Authoritative)
|
||||
1. **Context7** (`mcp__context7__*`)
|
||||
- Use `resolve-library-id` first to get the correct library ID
|
||||
- Then use `get-library-docs` with appropriate token limits (default: 5000, max: 10000 for complex topics)
|
||||
- Best for: NPM packages, external libraries, frameworks
|
||||
|
||||
2. **Angular MCP** (`mcp__angular-mcp__*`)
|
||||
- Use `search_documentation` for Angular-specific queries
|
||||
- Use `get_best_practices` for Angular conventions
|
||||
- Best for: Angular APIs, components, directives, services
|
||||
|
||||
3. **Nx MCP** (`mcp__nx-mcp__*`)
|
||||
- Use `nx_docs` for Nx-specific documentation
|
||||
- Use `nx_workspace` for monorepo structure understanding
|
||||
- Best for: Nx commands, configuration, generators, executors
|
||||
|
||||
### Tier 2: Local Documentation (Use for ISA-specific)
|
||||
- **Read tool**: For internal library READMEs (`libs/[domain]/[layer]/[feature]/README.md`)
|
||||
- **Grep tool**: For searching code patterns and examples within the project
|
||||
- **Glob tool**: For finding relevant files by pattern
|
||||
|
||||
### Tier 3: Web Resources (Use as Fallback)
|
||||
- **WebSearch**: Official docs, GitHub repos, technical articles
|
||||
- **WebFetch**: Direct documentation pages when URL is known
|
||||
|
||||
## Research Workflows by Query Type
|
||||
|
||||
### Package/Library Documentation
|
||||
```
|
||||
1. Identify package name from query
|
||||
2. IF external package:
|
||||
- Use mcp__context7__resolve-library-id
|
||||
- Use mcp__context7__get-library-docs with focused topic
|
||||
3. IF internal ISA library:
|
||||
- Read libs/[domain]/[layer]/[feature]/README.md
|
||||
- Check library-reference.md for overview
|
||||
4. Extract: API surface, usage patterns, examples, version info
|
||||
```
|
||||
|
||||
### Angular-Specific Queries
|
||||
```
|
||||
1. Use mcp__angular-mcp__search_documentation with concise query
|
||||
2. IF best practices needed:
|
||||
- Use mcp__angular-mcp__get_best_practices
|
||||
3. Extract: Modern patterns (signals, standalone), migration notes
|
||||
4. Verify against project's Angular 20.1.2 version
|
||||
```
|
||||
|
||||
### Nx/Monorepo Queries
|
||||
```
|
||||
1. Use mcp__nx-mcp__nx_docs with user query
|
||||
2. IF workspace-specific:
|
||||
- Use mcp__nx-mcp__nx_workspace for structure
|
||||
- Use mcp__nx-mcp__nx_project_details for specific projects
|
||||
3. Extract: Commands, configuration, best practices
|
||||
```
|
||||
|
||||
### Troubleshooting/Error Messages
|
||||
```
|
||||
1. Search error message verbatim with WebSearch
|
||||
2. Add context: "[framework] [version] [error]"
|
||||
3. Check GitHub issues for the specific library
|
||||
4. Look for: Root cause, verified solutions, workarounds
|
||||
5. Time limit: 2 minutes max before reporting findings
|
||||
```
|
||||
|
||||
## Performance Optimization Strategies
|
||||
|
||||
### Speed Techniques
|
||||
- **Parallel searches**: Run multiple MCP calls simultaneously when appropriate
|
||||
- **Token limits**: Start with 5000 tokens, only increase if needed
|
||||
- **Early termination**: Stop when sufficient information found
|
||||
- **Query refinement**: Use specific, technical terms over general descriptions
|
||||
|
||||
### Avoid Redundancy
|
||||
- **Check previous context**: Don't re-fetch documentation already retrieved in conversation
|
||||
- **Summarize long docs**: Extract only relevant sections, not entire documentation
|
||||
- **Cache awareness**: Note when documentation was fetched for version currency
|
||||
|
||||
### Time Limits
|
||||
- **MCP calls**: 10 seconds per call maximum
|
||||
- **Web searches**: 30 seconds total for web research
|
||||
- **Total research**: 2 minutes maximum before providing available findings
|
||||
|
||||
## Enhanced Output Format
|
||||
|
||||
```markdown
|
||||
## 📚 Documentation Research Results
|
||||
|
||||
**Query:** [What was searched for]
|
||||
**Sources Checked:** [List of MCP servers/tools used]
|
||||
**Time Taken:** [Approximate time]
|
||||
|
||||
### ✅ Primary Finding
|
||||
**Source:** [Exact source with version]
|
||||
**Relevance Score:** [High/Medium/Low]
|
||||
|
||||
[Most relevant documentation extract or code example]
|
||||
|
||||
### 🔑 Key Implementation Details
|
||||
- **Installation:** `command if applicable`
|
||||
- **Import:** `import statement if applicable`
|
||||
- **Basic Usage:**
|
||||
```[language]
|
||||
// Concrete example
|
||||
```
|
||||
|
||||
### ⚠️ Important Considerations
|
||||
- [Version compatibility notes]
|
||||
- [Breaking changes or deprecations]
|
||||
- [Performance implications]
|
||||
|
||||
### 🔗 Additional Resources
|
||||
- [Official docs URL]
|
||||
- [Related internal libraries]
|
||||
- [Alternative approaches]
|
||||
|
||||
### 💡 Recommendation for Main Agent
|
||||
[Specific, actionable next steps based on findings]
|
||||
```
|
||||
|
||||
## ISA Frontend Project-Specific Guidelines
|
||||
|
||||
### Version Verification
|
||||
- **Angular**: 20.1.2 (verify compatibility with docs)
|
||||
- **Nx**: 21.3.2 (check for version-specific features)
|
||||
- **Node**: ≥22.0.0 (consider for package compatibility)
|
||||
- **TypeScript**: Check tsconfig.json for version
|
||||
|
||||
### Internal Library Research
|
||||
1. Check library-reference.md for quick overview
|
||||
2. Read the library's README.md for detailed API
|
||||
3. Look for usage examples in feature libraries
|
||||
4. Note domain-specific prefixes (oms-*, remi-*, ui-*)
|
||||
|
||||
### Common ISA Patterns to Note
|
||||
- NgRx Signals with signalStore() (not legacy NgRx)
|
||||
- Standalone components (no NgModules)
|
||||
- Zod validation schemas
|
||||
- Tailwind with ISA-specific utilities
|
||||
- Jest → Vitest migration in progress
|
||||
|
||||
## Error Handling & Fallback Strategies
|
||||
|
||||
### When MCP Servers Fail
|
||||
1. Try alternative MCP server if available
|
||||
2. Fall back to WebSearch with site-specific operators
|
||||
3. Check GitHub repository directly
|
||||
4. Report: "MCP unavailable, using web sources"
|
||||
|
||||
### When Documentation Not Found
|
||||
```markdown
|
||||
## ⚠️ Limited Documentation Available
|
||||
|
||||
**Searched:** [List all sources checked]
|
||||
**Result:** Documentation not found or incomplete
|
||||
|
||||
**Possible Reasons:**
|
||||
- Package may be internal/private
|
||||
- Documentation may be outdated
|
||||
- Feature might be experimental
|
||||
|
||||
**Recommended Actions:**
|
||||
1. [Check source code directly]
|
||||
2. [Look for similar implementations]
|
||||
3. [Ask for clarification on specific aspect]
|
||||
|
||||
## 🔄 Escalation to docs-researcher-advanced
|
||||
|
||||
**When to escalate:**
|
||||
- Documentation not found after exhaustive search
|
||||
- Conflicting information from multiple sources
|
||||
- Need to infer API from code
|
||||
- Complex multi-system analysis required
|
||||
|
||||
**Recommendation:** Use `docs-researcher-advanced` agent for deeper analysis with:
|
||||
- Code archaeology and inference
|
||||
- Multi-source synthesis
|
||||
- Pattern recognition
|
||||
- Documentation generation from implementation
|
||||
```
|
||||
|
||||
### Version Mismatch Handling
|
||||
- Always note version differences
|
||||
- Highlight breaking changes prominently
|
||||
- Suggest migration paths when applicable
|
||||
- Warn about compatibility issues
|
||||
|
||||
## Quality Checklist
|
||||
|
||||
Before returning results, verify:
|
||||
- [ ] Used fastest appropriate tool (MCP > Local > Web)
|
||||
- [ ] Included concrete code examples
|
||||
- [ ] Verified version compatibility
|
||||
- [ ] Extracted actionable information
|
||||
- [ ] Cited all sources with links/paths
|
||||
- [ ] Formatted for easy scanning
|
||||
- [ ] Provided clear next steps
|
||||
|
||||
## Communication Principles
|
||||
|
||||
### Do's
|
||||
- ✅ Prioritize speed without sacrificing accuracy
|
||||
- ✅ Provide concrete, runnable examples
|
||||
- ✅ Highlight critical warnings prominently
|
||||
- ✅ Format code with proper syntax highlighting
|
||||
- ✅ Include installation/setup commands
|
||||
- ✅ Note ISA-specific patterns when relevant
|
||||
|
||||
### Don'ts
|
||||
- ❌ Don't include irrelevant documentation sections
|
||||
- ❌ Don't guess if unsure - state uncertainty clearly
|
||||
- ❌ Don't exceed 2-minute research time
|
||||
- ❌ Don't provide outdated information without warnings
|
||||
- ❌ Don't forget to check project-specific versions
|
||||
|
||||
## Success Metrics
|
||||
|
||||
Your research is successful when:
|
||||
1. Main agent can immediately proceed with implementation
|
||||
2. All necessary API details are provided
|
||||
3. Potential pitfalls are highlighted
|
||||
4. Sources are authoritative and current
|
||||
5. Response time is under 2 minutes
|
||||
|
||||
Remember: You are the speed-optimized research specialist using Haiku model. Prioritize fast, focused, accurate results that enable the main agent to work confidently.
|
||||
197
.claude/commands/dev:add-e2e-attrs.md
Normal file
197
.claude/commands/dev:add-e2e-attrs.md
Normal file
@@ -0,0 +1,197 @@
|
||||
# /dev:add-e2e-attrs - Add E2E Test Attributes
|
||||
|
||||
Add required E2E test attributes (`data-what`, `data-which`, dynamic `data-*`) to component templates for QA automation.
|
||||
|
||||
## Parameters
|
||||
- `component-path`: Path to component directory or HTML template file
|
||||
|
||||
## Required E2E Attributes
|
||||
|
||||
### Core Attributes (Required)
|
||||
1. **`data-what`**: Semantic description of element's purpose
|
||||
- Example: `data-what="submit-button"`, `data-what="search-input"`
|
||||
2. **`data-which`**: Unique identifier for the specific instance
|
||||
- Example: `data-which="primary"`, `data-which="customer-{{ customerId }}"`
|
||||
|
||||
### Dynamic Attributes (Contextual)
|
||||
3. **`data-*`**: Additional context based on state/data
|
||||
- Example: `data-status="active"`, `data-index="0"`
|
||||
|
||||
## Tasks
|
||||
|
||||
### 1. Analyze Component Template
|
||||
- Read component HTML template
|
||||
- Identify interactive elements that need E2E attributes:
|
||||
- Buttons (`button`, `ui-button`)
|
||||
- Inputs (`input`, `textarea`, `select`)
|
||||
- Links (`a`, `routerLink`)
|
||||
- Custom interactive components
|
||||
- Form elements
|
||||
- Clickable elements (`(click)` handlers)
|
||||
|
||||
### 2. Add Missing Attributes
|
||||
|
||||
**Buttons:**
|
||||
```html
|
||||
<!-- BEFORE -->
|
||||
<button (click)="submit()">Submit</button>
|
||||
|
||||
<!-- AFTER -->
|
||||
<button
|
||||
(click)="submit()"
|
||||
data-what="submit-button"
|
||||
data-which="form-primary">
|
||||
Submit
|
||||
</button>
|
||||
```
|
||||
|
||||
**Inputs:**
|
||||
```html
|
||||
<!-- BEFORE -->
|
||||
<input [(ngModel)]="searchTerm" placeholder="Search..." />
|
||||
|
||||
<!-- AFTER -->
|
||||
<input
|
||||
[(ngModel)]="searchTerm"
|
||||
placeholder="Search..."
|
||||
data-what="search-input"
|
||||
data-which="main-search" />
|
||||
```
|
||||
|
||||
**Dynamic Lists:**
|
||||
```html
|
||||
<!-- BEFORE -->
|
||||
@for (item of items; track item.id) {
|
||||
<li (click)="selectItem(item)">{{ item.name }}</li>
|
||||
}
|
||||
|
||||
<!-- AFTER -->
|
||||
@for (item of items; track item.id) {
|
||||
<li
|
||||
(click)="selectItem(item)"
|
||||
data-what="list-item"
|
||||
[attr.data-which]="item.id"
|
||||
[attr.data-status]="item.status">
|
||||
{{ item.name }}
|
||||
</li>
|
||||
}
|
||||
```
|
||||
|
||||
**Links:**
|
||||
```html
|
||||
<!-- BEFORE -->
|
||||
<a routerLink="/orders/{{ orderId }}">View Order</a>
|
||||
|
||||
<!-- AFTER -->
|
||||
<a
|
||||
[routerLink]="['/orders', orderId]"
|
||||
data-what="order-link"
|
||||
[attr.data-which]="orderId">
|
||||
View Order
|
||||
</a>
|
||||
```
|
||||
|
||||
**Custom Components:**
|
||||
```html
|
||||
<!-- BEFORE -->
|
||||
<ui-button (click)="save()">Save</ui-button>
|
||||
|
||||
<!-- AFTER -->
|
||||
<ui-button
|
||||
(click)="save()"
|
||||
data-what="save-button"
|
||||
data-which="order-form">
|
||||
Save
|
||||
</ui-button>
|
||||
```
|
||||
|
||||
### 3. Naming Conventions
|
||||
|
||||
**`data-what` Guidelines:**
|
||||
- Use kebab-case
|
||||
- Be descriptive but concise
|
||||
- Common patterns:
|
||||
- `*-button` (submit-button, cancel-button, delete-button)
|
||||
- `*-input` (email-input, search-input, quantity-input)
|
||||
- `*-link` (product-link, order-link, customer-link)
|
||||
- `*-item` (list-item, menu-item, card-item)
|
||||
- `*-dialog` (confirm-dialog, error-dialog)
|
||||
- `*-dropdown` (status-dropdown, category-dropdown)
|
||||
|
||||
**`data-which` Guidelines:**
|
||||
- Unique identifier for the instance
|
||||
- Use dynamic binding for list items: `[attr.data-which]="item.id"`
|
||||
- Static for unique elements: `data-which="primary"`
|
||||
- Combine with context: `data-which="customer-{{ customerId }}-edit"`
|
||||
|
||||
### 4. Scan for Coverage
|
||||
Check template coverage:
|
||||
```bash
|
||||
# Count interactive elements
|
||||
grep -E '(click)=|routerLink|button|input|select|textarea' [template-file]
|
||||
|
||||
# Count elements with data-what
|
||||
grep -c 'data-what=' [template-file]
|
||||
|
||||
# List elements missing E2E attributes
|
||||
grep -E '(click)=|button' [template-file] | grep -v 'data-what='
|
||||
```
|
||||
|
||||
### 5. Validate Attributes
|
||||
- No duplicates in `data-which` within same view
|
||||
- All interactive elements have both `data-what` and `data-which`
|
||||
- Dynamic attributes use proper Angular binding: `[attr.data-*]`
|
||||
- Attributes don't contain sensitive data (passwords, tokens)
|
||||
|
||||
### 6. Update Component Tests
|
||||
Add E2E attribute selectors to tests:
|
||||
```typescript
|
||||
// Use E2E attributes for element selection
|
||||
const submitButton = fixture.nativeElement.querySelector('[data-what="submit-button"][data-which="primary"]');
|
||||
expect(submitButton).toBeTruthy();
|
||||
```
|
||||
|
||||
### 7. Document Attributes
|
||||
Add comment block at top of template:
|
||||
```html
|
||||
<!--
|
||||
E2E Test Attributes:
|
||||
- data-what="submit-button" data-which="primary" - Main form submission
|
||||
- data-what="cancel-button" data-which="primary" - Cancel action
|
||||
- data-what="search-input" data-which="main" - Product search field
|
||||
-->
|
||||
```
|
||||
|
||||
## Output
|
||||
Provide summary:
|
||||
- Template analyzed: [path]
|
||||
- Interactive elements found: [count]
|
||||
- Attributes added: [count]
|
||||
- Coverage: [percentage]% (elements with E2E attrs / total interactive elements)
|
||||
- List of added attributes with descriptions
|
||||
- Validation status: ✅/❌
|
||||
|
||||
## Common Patterns by Component Type
|
||||
|
||||
**Form Components:**
|
||||
- `data-what="[field]-input" data-which="[form-name]"`
|
||||
- `data-what="submit-button" data-which="[form-name]"`
|
||||
- `data-what="cancel-button" data-which="[form-name]"`
|
||||
|
||||
**List/Table Components:**
|
||||
- `data-what="list-item" [attr.data-which]="item.id"`
|
||||
- `data-what="edit-button" [attr.data-which]="item.id"`
|
||||
- `data-what="delete-button" [attr.data-which]="item.id"`
|
||||
|
||||
**Navigation Components:**
|
||||
- `data-what="nav-link" data-which="[destination]"`
|
||||
- `data-what="breadcrumb" data-which="[level]"`
|
||||
|
||||
**Dialog Components:**
|
||||
- `data-what="confirm-button" data-which="dialog"`
|
||||
- `data-what="close-button" data-which="dialog"`
|
||||
|
||||
## References
|
||||
- CLAUDE.md Code Quality section (E2E Testing Requirements)
|
||||
- docs/guidelines/testing.md
|
||||
- QA team E2E test documentation (if available)
|
||||
535
.claude/commands/docs:library.md
Normal file
535
.claude/commands/docs:library.md
Normal file
@@ -0,0 +1,535 @@
|
||||
# /docs:library - Generate/Update Library README
|
||||
|
||||
Generate or update README.md for a specific library with comprehensive documentation.
|
||||
|
||||
## Parameters
|
||||
- `library-name`: Name of library (e.g., `oms-feature-return-search`)
|
||||
|
||||
## Tasks
|
||||
|
||||
### 1. Locate Library
|
||||
|
||||
```bash
|
||||
# Find library directory
|
||||
find libs/ -name "project.json" -path "*[library-name]*"
|
||||
|
||||
# Verify library exists
|
||||
if [ ! -d "libs/[path-to-library]" ]; then
|
||||
echo "Library not found"
|
||||
exit 1
|
||||
fi
|
||||
```
|
||||
|
||||
### 2. Extract Library Information
|
||||
|
||||
Read `project.json`:
|
||||
- Library name
|
||||
- Source root
|
||||
- Available targets (build, test, lint)
|
||||
- Tags (domain, type)
|
||||
|
||||
Read `tsconfig.base.json`:
|
||||
- Path alias (`@isa/domain/layer/name`)
|
||||
- Entry point (`src/index.ts`)
|
||||
|
||||
### 3. Analyze Library Structure
|
||||
|
||||
Scan library contents:
|
||||
```bash
|
||||
# List main source files
|
||||
ls -la libs/[path]/src/lib/
|
||||
|
||||
# Identify components
|
||||
find libs/[path]/src -name "*.component.ts"
|
||||
|
||||
# Identify services
|
||||
find libs/[path]/src -name "*.service.ts"
|
||||
|
||||
# Identify models/types
|
||||
find libs/[path]/src -name "*.model.ts" -o -name "*.interface.ts"
|
||||
|
||||
# Check for exports
|
||||
cat libs/[path]/src/index.ts
|
||||
```
|
||||
|
||||
### 4. Use docs-researcher for Similar READMEs
|
||||
|
||||
Use `docs-researcher` agent to find similar library READMEs in the same domain for reference structure and style.
|
||||
|
||||
### 5. Determine Library Type and Template
|
||||
|
||||
**Feature Library Template:**
|
||||
```markdown
|
||||
# [Library Name]
|
||||
|
||||
> **Type:** Feature Library
|
||||
> **Domain:** [OMS/Remission/Checkout/etc]
|
||||
> **Path:** `libs/[domain]/feature/[name]`
|
||||
|
||||
## Overview
|
||||
|
||||
[Brief description of what this feature does]
|
||||
|
||||
## Features
|
||||
|
||||
- Feature 1: [Description]
|
||||
- Feature 2: [Description]
|
||||
- Feature 3: [Description]
|
||||
|
||||
## Installation
|
||||
|
||||
This library is part of the ISA-Frontend monorepo. Import it using:
|
||||
|
||||
```typescript
|
||||
import { ComponentName } from '@isa/[domain]/feature/[name]';
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
### Basic Example
|
||||
|
||||
```typescript
|
||||
import { Component } from '@angular/core';
|
||||
import { FeatureComponent } from '@isa/[domain]/feature/[name]';
|
||||
|
||||
@Component({
|
||||
selector: 'app-example',
|
||||
standalone: true,
|
||||
imports: [FeatureComponent],
|
||||
template: `
|
||||
<feature-component [input]="value" (output)="handleEvent($event)">
|
||||
</feature-component>
|
||||
`
|
||||
})
|
||||
export class ExampleComponent {
|
||||
value = 'example';
|
||||
|
||||
handleEvent(event: any) {
|
||||
console.log(event);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Advanced Usage
|
||||
|
||||
[More complex examples if applicable]
|
||||
|
||||
## API Reference
|
||||
|
||||
### Components
|
||||
|
||||
#### FeatureComponent
|
||||
|
||||
**Selector:** `feature-component`
|
||||
|
||||
**Inputs:**
|
||||
- `input` (string): Description of input
|
||||
|
||||
**Outputs:**
|
||||
- `output` (EventEmitter<any>): Description of output
|
||||
|
||||
**Example:**
|
||||
```html
|
||||
<feature-component [input]="value" (output)="handleEvent($event)">
|
||||
</feature-component>
|
||||
```
|
||||
|
||||
### Services
|
||||
|
||||
[If applicable]
|
||||
|
||||
### Models
|
||||
|
||||
[If applicable]
|
||||
|
||||
## Testing
|
||||
|
||||
This library uses [Vitest/Jest] for testing.
|
||||
|
||||
Run tests:
|
||||
```bash
|
||||
npx nx test [library-name] --skip-nx-cache
|
||||
```
|
||||
|
||||
Run with coverage:
|
||||
```bash
|
||||
npx nx test [library-name] --skip-nx-cache --coverage
|
||||
```
|
||||
|
||||
## Dependencies
|
||||
|
||||
**External Dependencies:**
|
||||
- [List of external packages if any]
|
||||
|
||||
**Internal Dependencies:**
|
||||
- [`@isa/[dependency]`](../[path]) - Description
|
||||
|
||||
## Development
|
||||
|
||||
### Project Structure
|
||||
|
||||
```
|
||||
libs/[domain]/feature/[name]/
|
||||
├── src/
|
||||
│ ├── lib/
|
||||
│ │ ├── components/
|
||||
│ │ ├── services/
|
||||
│ │ └── models/
|
||||
│ ├── index.ts
|
||||
│ └── test-setup.ts
|
||||
├── project.json
|
||||
└── README.md
|
||||
```
|
||||
|
||||
### Build
|
||||
|
||||
```bash
|
||||
npx nx build [library-name]
|
||||
```
|
||||
|
||||
### Lint
|
||||
|
||||
```bash
|
||||
npx nx lint [library-name]
|
||||
```
|
||||
|
||||
## Related Documentation
|
||||
|
||||
- [CLAUDE.md](../../../../CLAUDE.md) - Project guidelines
|
||||
- [Testing Guidelines](../../../../docs/guidelines/testing.md)
|
||||
- [Library Reference](../../../../docs/library-reference.md)
|
||||
|
||||
## Related Libraries
|
||||
|
||||
- [`@isa/[related-lib-1]`](../[path]) - Description
|
||||
- [`@isa/[related-lib-2]`](../[path]) - Description
|
||||
```
|
||||
|
||||
**Data Access Library Template:**
|
||||
```markdown
|
||||
# [Library Name]
|
||||
|
||||
> **Type:** Data Access Library
|
||||
> **Domain:** [Domain]
|
||||
> **Path:** `libs/[domain]/data-access`
|
||||
|
||||
## Overview
|
||||
|
||||
Data access layer for [Domain] domain. Provides services and state management for [domain-specific functionality].
|
||||
|
||||
## Features
|
||||
|
||||
- API client integration with [API names]
|
||||
- NgRx Signals store for state management
|
||||
- Type-safe data models with Zod validation
|
||||
- Error handling and retry logic
|
||||
|
||||
## Installation
|
||||
|
||||
```typescript
|
||||
import { ServiceName } from '@isa/[domain]/data-access';
|
||||
```
|
||||
|
||||
## Services
|
||||
|
||||
### ServiceName
|
||||
|
||||
[Service description]
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `getById(id: string): Observable<Model>`
|
||||
[Method description]
|
||||
|
||||
**Parameters:**
|
||||
- `id` (string): Description
|
||||
|
||||
**Returns:** `Observable<Model>`
|
||||
|
||||
**Example:**
|
||||
```typescript
|
||||
this.service.getById('123').subscribe({
|
||||
next: (data) => console.log(data),
|
||||
error: (err) => console.error(err)
|
||||
});
|
||||
```
|
||||
|
||||
## State Management
|
||||
|
||||
This library uses NgRx Signals for state management.
|
||||
|
||||
### Store
|
||||
|
||||
```typescript
|
||||
import { injectStore } from '@isa/[domain]/data-access';
|
||||
|
||||
export class Component {
|
||||
store = injectStore();
|
||||
|
||||
// Access state
|
||||
items = this.store.items;
|
||||
loading = this.store.loading;
|
||||
|
||||
// Call methods
|
||||
ngOnInit() {
|
||||
this.store.loadItems();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Models
|
||||
|
||||
### Model Name
|
||||
|
||||
```typescript
|
||||
interface ModelName {
|
||||
id: string;
|
||||
property: type;
|
||||
}
|
||||
```
|
||||
|
||||
Validated with Zod schema for runtime type safety.
|
||||
|
||||
## Testing
|
||||
|
||||
[Testing section similar to feature library]
|
||||
|
||||
## API Integration
|
||||
|
||||
This library integrates with the following Swagger-generated API clients:
|
||||
|
||||
- `@generated/swagger/[api-name]`
|
||||
|
||||
[Additional API documentation]
|
||||
```
|
||||
|
||||
**UI Component Library Template:**
|
||||
```markdown
|
||||
# [Library Name]
|
||||
|
||||
> **Type:** UI Component Library
|
||||
> **Path:** `libs/ui/[name]`
|
||||
|
||||
## Overview
|
||||
|
||||
Reusable UI components for [purpose]. Part of the ISA design system.
|
||||
|
||||
## Components
|
||||
|
||||
### ComponentName
|
||||
|
||||
[Component description]
|
||||
|
||||
**Selector:** `ui-component-name`
|
||||
|
||||
**Styling:** Uses Tailwind CSS with ISA design tokens
|
||||
|
||||
**Example:**
|
||||
```html
|
||||
<ui-component-name variant="primary" size="md">
|
||||
Content
|
||||
</ui-component-name>
|
||||
```
|
||||
|
||||
## Variants
|
||||
|
||||
- **primary**: Default primary styling
|
||||
- **secondary**: Secondary styling
|
||||
- **accent**: Accent color
|
||||
|
||||
## Sizes
|
||||
|
||||
- **sm**: Small (24px height)
|
||||
- **md**: Medium (32px height)
|
||||
- **lg**: Large (40px height)
|
||||
|
||||
## Accessibility
|
||||
|
||||
- ARIA labels included
|
||||
- Keyboard navigation supported
|
||||
- Screen reader friendly
|
||||
|
||||
## Storybook
|
||||
|
||||
View component documentation and examples:
|
||||
|
||||
```bash
|
||||
npm run storybook
|
||||
```
|
||||
|
||||
Navigate to: UI Components → [Component Name]
|
||||
|
||||
## Testing
|
||||
|
||||
Includes E2E test attributes:
|
||||
- `data-what="component-name"`
|
||||
- `data-which="variant"`
|
||||
|
||||
[Rest of testing section]
|
||||
```
|
||||
|
||||
### 6. Extract Code Examples
|
||||
|
||||
Scan library code for:
|
||||
- Public component selectors
|
||||
- Public API methods
|
||||
- Input/Output properties
|
||||
- Common usage patterns
|
||||
|
||||
Use `Read` tool to extract from source files.
|
||||
|
||||
### 7. Document Exports
|
||||
|
||||
Parse `src/index.ts` to document public API:
|
||||
```typescript
|
||||
// Read barrel export
|
||||
export * from './lib/component';
|
||||
export * from './lib/service';
|
||||
export { PublicInterface } from './lib/models';
|
||||
```
|
||||
|
||||
Document each export with:
|
||||
- Type (Component/Service/Interface/Function)
|
||||
- Purpose
|
||||
- Basic usage
|
||||
|
||||
### 8. Add Testing Information
|
||||
|
||||
Based on test framework (from project.json):
|
||||
- Test command
|
||||
- Framework (Vitest/Jest)
|
||||
- Coverage command
|
||||
- Link to testing guidelines
|
||||
|
||||
### 9. Create Dependency Graph
|
||||
|
||||
List internal and external dependencies:
|
||||
```bash
|
||||
# Use Nx to show dependencies
|
||||
npx nx graph --focus=[library-name]
|
||||
|
||||
# Extract from package.json and imports
|
||||
```
|
||||
|
||||
### 10. Add E2E Attributes Documentation
|
||||
|
||||
For UI/Feature libraries, document E2E attributes:
|
||||
```markdown
|
||||
## E2E Testing
|
||||
|
||||
This library includes E2E test attributes for automated testing:
|
||||
|
||||
| Element | data-what | data-which | Purpose |
|
||||
|---------|-----------|------------|---------|
|
||||
| Submit button | submit-button | form-primary | Main form submission |
|
||||
| Cancel button | cancel-button | form-primary | Cancel action |
|
||||
|
||||
Use these attributes in your E2E tests:
|
||||
```typescript
|
||||
const submitBtn = page.locator('[data-what="submit-button"][data-which="form-primary"]');
|
||||
```
|
||||
```
|
||||
|
||||
### 11. Generate/Update README
|
||||
|
||||
Write or update `libs/[path]/README.md` with generated content.
|
||||
|
||||
### 12. Validate README
|
||||
|
||||
Checks:
|
||||
- All links work (relative paths correct)
|
||||
- Code examples are valid TypeScript
|
||||
- Import paths use correct aliases
|
||||
- No TODO or placeholder text
|
||||
- Consistent formatting
|
||||
- Proper markdown syntax
|
||||
|
||||
### 13. Add to Git (if new)
|
||||
|
||||
```bash
|
||||
git add libs/[path]/README.md
|
||||
```
|
||||
|
||||
## Output Format
|
||||
```
|
||||
Library README Generated
|
||||
========================
|
||||
|
||||
Library: [library-name]
|
||||
Type: [Feature/Data Access/UI/Util]
|
||||
Path: libs/[domain]/[layer]/[name]
|
||||
|
||||
📝 README Sections
|
||||
------------------
|
||||
✅ Overview
|
||||
✅ Features
|
||||
✅ Installation
|
||||
✅ Usage Examples
|
||||
✅ API Reference
|
||||
✅ Testing
|
||||
✅ Dependencies
|
||||
✅ Development Guide
|
||||
|
||||
📊 Documentation Stats
|
||||
----------------------
|
||||
Total sections: XX
|
||||
Code examples: XX
|
||||
API methods documented: XX
|
||||
Components documented: XX
|
||||
|
||||
🔗 Links Validated
|
||||
-------------------
|
||||
Internal links: XX/XX valid
|
||||
Relative paths: ✅ Correct
|
||||
|
||||
💡 Highlights
|
||||
-------------
|
||||
- Documented XX public exports
|
||||
- XX code examples included
|
||||
- E2E attributes documented
|
||||
- Related libraries linked
|
||||
|
||||
📁 File Updated
|
||||
---------------
|
||||
Path: libs/[domain]/[layer]/[name]/README.md
|
||||
Size: XX KB
|
||||
Lines: XX
|
||||
|
||||
🎯 Next Steps
|
||||
-------------
|
||||
1. Review generated README
|
||||
2. Add any domain-specific details
|
||||
3. Add usage examples if needed
|
||||
4. Commit: git add libs/[path]/README.md
|
||||
```
|
||||
|
||||
## Auto-Enhancement
|
||||
|
||||
If existing README found:
|
||||
- Preserve custom sections
|
||||
- Update outdated examples
|
||||
- Add missing sections
|
||||
- Fix broken links
|
||||
- Update import paths
|
||||
|
||||
Prompt:
|
||||
```
|
||||
Existing README found. What would you like to do?
|
||||
1. Generate new (overwrite)
|
||||
2. Enhance existing (preserve custom content)
|
||||
3. Cancel
|
||||
```
|
||||
|
||||
## Quality Checks
|
||||
|
||||
- Import examples use correct path aliases
|
||||
- Code examples are syntactically correct
|
||||
- Links to related docs work
|
||||
- API documentation complete
|
||||
- Testing section accurate
|
||||
|
||||
## References
|
||||
- CLAUDE.md Library Organization section
|
||||
- Use `docs-researcher` to find reference READMEs
|
||||
- Storybook for UI component examples
|
||||
- project.json for library configuration
|
||||
295
.claude/commands/docs:refresh-reference.md
Normal file
295
.claude/commands/docs:refresh-reference.md
Normal file
@@ -0,0 +1,295 @@
|
||||
# /docs:refresh-reference - Regenerate Library Reference
|
||||
|
||||
Regenerate the library reference documentation (`docs/library-reference.md`) by scanning all libraries in the monorepo.
|
||||
|
||||
## Tasks
|
||||
|
||||
### 1. Scan Monorepo Structure
|
||||
```bash
|
||||
# List all libraries
|
||||
find libs/ -name "project.json" -type f | sort
|
||||
|
||||
# Count total libraries
|
||||
find libs/ -name "project.json" -type f | wc -l
|
||||
```
|
||||
|
||||
### 2. Extract Library Information
|
||||
|
||||
For each library, extract from `project.json`:
|
||||
- **Project name**: `name` field
|
||||
- **Path**: Directory path
|
||||
- **Tags**: For categorization (type, domain)
|
||||
- **Targets**: Available commands (build, test, lint)
|
||||
|
||||
### 3. Determine Path Aliases
|
||||
|
||||
Read `tsconfig.base.json` to get path mappings:
|
||||
```bash
|
||||
# Extract paths section
|
||||
cat tsconfig.base.json | grep -A 200 '"paths"'
|
||||
```
|
||||
|
||||
Map each library to its `@isa/*` alias.
|
||||
|
||||
### 4. Categorize Libraries by Domain
|
||||
|
||||
Group libraries into categories:
|
||||
- **Availability** (1 library)
|
||||
- **Catalogue** (1 library)
|
||||
- **Checkout** (6 libraries)
|
||||
- **Common** (3 libraries)
|
||||
- **Core** (5 libraries)
|
||||
- **CRM** (1 library)
|
||||
- **Icons** (1 library)
|
||||
- **OMS** (9 libraries)
|
||||
- **Remission** (8 libraries)
|
||||
- **Shared Components** (7 libraries)
|
||||
- **UI Components** (17 libraries)
|
||||
- **Utilities** (3 libraries)
|
||||
|
||||
### 5. Read Library READMEs
|
||||
|
||||
For each library, use `docs-researcher` agent to:
|
||||
- Read library README.md (if exists)
|
||||
- Extract description/purpose
|
||||
- Extract key features
|
||||
- Extract usage examples
|
||||
|
||||
### 6. Generate Library Entries
|
||||
|
||||
For each library, create entry with:
|
||||
```markdown
|
||||
#### `@isa/domain/layer/name`
|
||||
**Path:** `libs/domain/layer/name`
|
||||
**Type:** [Feature/Data Access/UI/Util]
|
||||
|
||||
Brief description from README or inferred from structure.
|
||||
|
||||
**Key Features:**
|
||||
- Feature 1
|
||||
- Feature 2
|
||||
|
||||
**Usage:**
|
||||
```typescript
|
||||
import { Component } from '@isa/domain/layer/name';
|
||||
```
|
||||
```
|
||||
|
||||
### 7. Create Domain Statistics
|
||||
|
||||
Calculate per domain:
|
||||
- Total libraries count
|
||||
- Breakdown by type (feature/data-access/ui/util)
|
||||
- Key capabilities overview
|
||||
|
||||
### 8. Generate Table of Contents
|
||||
|
||||
Create hierarchical TOC:
|
||||
```markdown
|
||||
## Table of Contents
|
||||
1. [Overview](#overview)
|
||||
2. [Quick Stats](#quick-stats)
|
||||
3. [Library Categories](#library-categories)
|
||||
- [Availability](#availability)
|
||||
- [Catalogue](#catalogue)
|
||||
- [Checkout](#checkout)
|
||||
...
|
||||
```
|
||||
|
||||
### 9. Add Metadata Header
|
||||
|
||||
Include document metadata:
|
||||
```markdown
|
||||
# Library Reference Guide
|
||||
|
||||
> **Last Updated:** [Current Date]
|
||||
> **Total Libraries:** XX
|
||||
> **Domains:** 12
|
||||
|
||||
## Quick Stats
|
||||
- Availability: 1 | Catalogue: 1 | Checkout: 6 | Common: 3
|
||||
- Core: 5 | CRM: 1 | Icons: 1 | OMS: 9 | Remission: 8
|
||||
- Shared Components: 7 | UI Components: 17 | Utilities: 3
|
||||
```
|
||||
|
||||
### 10. Add Usage Guidelines
|
||||
|
||||
Include quick reference section:
|
||||
```markdown
|
||||
## How to Use This Guide
|
||||
|
||||
### Finding a Library
|
||||
1. Check the domain category (e.g., OMS, Checkout, UI Components)
|
||||
2. Look for the specific feature or component you need
|
||||
3. Note the import path alias (e.g., `@isa/oms/feature-return-search`)
|
||||
|
||||
### Import Syntax
|
||||
All libraries use path aliases defined in `tsconfig.base.json`:
|
||||
|
||||
```typescript
|
||||
// Feature libraries
|
||||
import { Component } from '@isa/domain/feature/name';
|
||||
|
||||
// Data access services
|
||||
import { Service } from '@isa/domain/data-access';
|
||||
|
||||
// UI components
|
||||
import { ButtonComponent } from '@isa/ui/buttons';
|
||||
|
||||
// Utilities
|
||||
import { helper } from '@isa/utils/validation';
|
||||
```
|
||||
```
|
||||
|
||||
### 11. Add Cross-References
|
||||
|
||||
Link related libraries:
|
||||
```markdown
|
||||
**Related Libraries:**
|
||||
- [`@isa/oms/data-access`](#isaomsdataaccess) - OMS data services
|
||||
- [`@isa/ui/buttons`](#isauibuttons) - Button components
|
||||
```
|
||||
|
||||
### 12. Include Testing Information
|
||||
|
||||
For each library, note test framework:
|
||||
```markdown
|
||||
**Testing:** Vitest | Jest
|
||||
**Test Command:** `npx nx test [library-name] --skip-nx-cache`
|
||||
```
|
||||
|
||||
### 13. Validate Generated Documentation
|
||||
|
||||
Checks:
|
||||
- All libraries included (compare count)
|
||||
- All path aliases correct
|
||||
- No broken internal links
|
||||
- Consistent formatting
|
||||
- Alphabetical ordering within categories
|
||||
|
||||
### 14. Update CLAUDE.md Reference
|
||||
|
||||
Update CLAUDE.md to reference new library-reference.md:
|
||||
```markdown
|
||||
#### Library Reference Guide
|
||||
|
||||
The monorepo contains **62 libraries** organized across 12 domains.
|
||||
For quick lookup, see **[`docs/library-reference.md`](docs/library-reference.md)**.
|
||||
```
|
||||
|
||||
### 15. Create Backup
|
||||
|
||||
Before overwriting:
|
||||
```bash
|
||||
# Backup existing file
|
||||
cp docs/library-reference.md docs/library-reference.md.backup.$(date +%s)
|
||||
```
|
||||
|
||||
### 16. Write New Documentation
|
||||
|
||||
Write to `docs/library-reference.md` with generated content.
|
||||
|
||||
## Output Format
|
||||
|
||||
**Generated File Structure:**
|
||||
```markdown
|
||||
# Library Reference Guide
|
||||
|
||||
> Last Updated: [Date]
|
||||
> Total Libraries: XX
|
||||
> Domains: 12
|
||||
|
||||
## Table of Contents
|
||||
[Auto-generated TOC]
|
||||
|
||||
## Overview
|
||||
[Introduction and usage guide]
|
||||
|
||||
## Quick Stats
|
||||
[Statistics by domain]
|
||||
|
||||
## Library Categories
|
||||
|
||||
### Availability
|
||||
#### @isa/availability/data-access
|
||||
[Details...]
|
||||
|
||||
### Catalogue
|
||||
[Details...]
|
||||
|
||||
[... all domains ...]
|
||||
|
||||
## Appendix
|
||||
|
||||
### Path Aliases
|
||||
[Quick reference table]
|
||||
|
||||
### Testing Frameworks
|
||||
[Framework by library]
|
||||
|
||||
### Nx Commands
|
||||
[Common commands]
|
||||
```
|
||||
|
||||
## Output Summary
|
||||
```
|
||||
Library Reference Documentation Generated
|
||||
==========================================
|
||||
|
||||
📊 Statistics
|
||||
-------------
|
||||
Total libraries scanned: XX
|
||||
Libraries documented: XX
|
||||
Domains covered: 12
|
||||
|
||||
📝 Documentation Structure
|
||||
--------------------------
|
||||
- Table of Contents: ✅
|
||||
- Quick Stats: ✅
|
||||
- Library categories: XX
|
||||
- Total entries: XX
|
||||
|
||||
🔍 Quality Checks
|
||||
-----------------
|
||||
- All libraries included: ✅/❌
|
||||
- Path aliases validated: ✅/❌
|
||||
- Internal links verified: ✅/❌
|
||||
- Consistent formatting: ✅/❌
|
||||
|
||||
💾 Files Updated
|
||||
----------------
|
||||
- docs/library-reference.md: ✅
|
||||
- Backup created: docs/library-reference.md.backup.[timestamp]
|
||||
|
||||
📈 Changes from Previous Version
|
||||
---------------------------------
|
||||
- Libraries added: XX
|
||||
- Libraries removed: XX
|
||||
- Descriptions updated: XX
|
||||
|
||||
🎯 Next Steps
|
||||
-------------
|
||||
1. Review generated documentation
|
||||
2. Verify library descriptions are accurate
|
||||
3. Add missing usage examples if needed
|
||||
4. Commit changes: git add docs/library-reference.md
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
- Missing project.json: Skip and report
|
||||
- No README found: Use generic description
|
||||
- Path alias mismatch: Flag for manual review
|
||||
- Broken links: List for correction
|
||||
|
||||
## Automation Tips
|
||||
Can be run:
|
||||
- After adding new libraries
|
||||
- During documentation updates
|
||||
- As pre-release validation
|
||||
- In CI/CD pipeline
|
||||
|
||||
## References
|
||||
- CLAUDE.md Library Organization section
|
||||
- tsconfig.base.json (path aliases)
|
||||
- Individual library README.md files
|
||||
- docs/library-reference.md (existing documentation)
|
||||
129
.claude/commands/quality:bundle-analyze.md
Normal file
129
.claude/commands/quality:bundle-analyze.md
Normal file
@@ -0,0 +1,129 @@
|
||||
# /quality:bundle-analyze - Analyze Bundle Sizes
|
||||
|
||||
Analyze production bundle sizes and provide optimization recommendations. Project thresholds: 2MB warning, 5MB error.
|
||||
|
||||
## Tasks
|
||||
|
||||
### 1. Run Production Build
|
||||
```bash
|
||||
# Clean previous build
|
||||
rm -rf dist/
|
||||
|
||||
# Build for production
|
||||
npm run build-prod
|
||||
```
|
||||
|
||||
### 2. Analyze Bundle Output
|
||||
```bash
|
||||
# List bundle files with sizes
|
||||
ls -lh dist/apps/isa-app/browser/*.js | awk '{print $9, $5}'
|
||||
|
||||
# Get total bundle size
|
||||
du -sh dist/apps/isa-app/browser/
|
||||
```
|
||||
|
||||
### 3. Identify Large Files
|
||||
Parse build output and identify:
|
||||
- Main bundle size
|
||||
- Lazy-loaded chunk sizes
|
||||
- Vendor chunks
|
||||
- Files exceeding thresholds:
|
||||
- **Warning**: > 2MB
|
||||
- **Error**: > 5MB
|
||||
|
||||
### 4. Analyze Dependencies
|
||||
```bash
|
||||
# Check for duplicate dependencies
|
||||
npm ls --depth=0 | grep -E "UNMET|deduped"
|
||||
|
||||
# Show largest node_modules packages
|
||||
du -sh node_modules/* | sort -rh | head -20
|
||||
```
|
||||
|
||||
### 5. Source Map Analysis
|
||||
Use source maps to identify large contributors:
|
||||
```bash
|
||||
# Install source-map-explorer if needed
|
||||
npm install -g source-map-explorer
|
||||
|
||||
# Analyze main bundle
|
||||
source-map-explorer dist/apps/isa-app/browser/main.*.js
|
||||
```
|
||||
|
||||
### 6. Generate Recommendations
|
||||
Based on analysis, provide actionable recommendations:
|
||||
|
||||
**If bundle > 2MB:**
|
||||
- Identify heavy dependencies to replace or remove
|
||||
- Suggest lazy loading opportunities
|
||||
- Check for unused imports
|
||||
|
||||
**Code Splitting Opportunities:**
|
||||
- Large feature modules that could be lazy-loaded
|
||||
- Heavy libraries that could be dynamically imported
|
||||
- Vendor code that could be split into separate chunks
|
||||
|
||||
**Dependency Optimization:**
|
||||
- Replace large libraries with smaller alternatives
|
||||
- Remove unused dependencies
|
||||
- Use tree-shakeable imports
|
||||
|
||||
**Build Configuration:**
|
||||
- Enable/optimize compression
|
||||
- Check for source maps in production (should be disabled)
|
||||
- Verify optimization flags
|
||||
|
||||
### 7. Comparative Analysis
|
||||
If previous build data exists:
|
||||
```bash
|
||||
# Compare with previous build
|
||||
# (Requires manual tracking or CI/CD integration)
|
||||
echo "Current build: $(du -sh dist/apps/isa-app/browser/ | awk '{print $1}')"
|
||||
```
|
||||
|
||||
### 8. Generate Report
|
||||
Create formatted report with:
|
||||
- Total bundle size with threshold status (✅ < 2MB, ⚠️ 2-5MB, ❌ > 5MB)
|
||||
- Main bundle and largest chunks
|
||||
- Top 10 largest dependencies
|
||||
- Optimization recommendations prioritized by impact
|
||||
- Lazy loading opportunities
|
||||
|
||||
## Output Format
|
||||
```
|
||||
Bundle Analysis Report
|
||||
======================
|
||||
|
||||
Total Size: X.XX MB [STATUS]
|
||||
Main Bundle: X.XX MB
|
||||
Largest Chunks:
|
||||
- chunk-name.js: X.XX MB
|
||||
- ...
|
||||
|
||||
Largest Dependencies:
|
||||
1. dependency-name: X.XX MB
|
||||
...
|
||||
|
||||
Recommendations:
|
||||
🔴 Critical (> 5MB):
|
||||
- [Action items]
|
||||
|
||||
⚠️ Warning (2-5MB):
|
||||
- [Action items]
|
||||
|
||||
✅ Optimization Opportunities:
|
||||
- [Action items]
|
||||
|
||||
Lazy Loading Candidates:
|
||||
- [Feature modules]
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
- Build failures: Show error and suggest fixes
|
||||
- Missing tools: Offer to install (source-map-explorer)
|
||||
- No dist folder: Run build first
|
||||
|
||||
## References
|
||||
- CLAUDE.md Build Configuration section
|
||||
- Angular build optimization: https://angular.dev/tools/cli/build
|
||||
- package.json (build-prod script)
|
||||
201
.claude/commands/quality:coverage.md
Normal file
201
.claude/commands/quality:coverage.md
Normal file
@@ -0,0 +1,201 @@
|
||||
# /quality:coverage - Generate Test Coverage Report
|
||||
|
||||
Generate comprehensive test coverage report with recommendations for improving coverage.
|
||||
|
||||
## Parameters
|
||||
- `library-name` (optional): Specific library to analyze. If omitted, analyzes all libraries.
|
||||
|
||||
## Tasks
|
||||
|
||||
### 1. Run Coverage Analysis
|
||||
```bash
|
||||
# Single library
|
||||
npx nx test [library-name] --skip-nx-cache --coverage
|
||||
|
||||
# All libraries (if no library specified)
|
||||
npm run ci # Runs all tests with coverage
|
||||
```
|
||||
|
||||
### 2. Parse Coverage Report
|
||||
Coverage output typically in:
|
||||
- `coverage/libs/[domain]/[layer]/[name]/`
|
||||
- Look for `coverage-summary.json` or text output
|
||||
|
||||
Extract metrics:
|
||||
- **Line coverage**: % of executable lines tested
|
||||
- **Branch coverage**: % of conditional branches tested
|
||||
- **Function coverage**: % of functions called in tests
|
||||
- **Statement coverage**: % of statements executed
|
||||
|
||||
### 3. Identify Uncovered Code
|
||||
Parse coverage report to find:
|
||||
- **Uncovered files**: Files with 0% coverage
|
||||
- **Partially covered files**: < 80% coverage
|
||||
- **Uncovered lines**: Specific line numbers not tested
|
||||
- **Uncovered branches**: Conditional paths not tested
|
||||
|
||||
```bash
|
||||
# List files with coverage below 80%
|
||||
# (Parse from coverage JSON output)
|
||||
```
|
||||
|
||||
### 4. Categorize Coverage Gaps
|
||||
|
||||
**Critical (High Risk):**
|
||||
- Service methods handling business logic
|
||||
- Data transformation functions
|
||||
- Error handling code paths
|
||||
- Security-related functions
|
||||
- State management store actions
|
||||
|
||||
**Important (Medium Risk):**
|
||||
- Component public methods
|
||||
- Utility functions
|
||||
- Validators
|
||||
- Pipes and filters
|
||||
- Guard functions
|
||||
|
||||
**Low Priority:**
|
||||
- Getters/setters
|
||||
- Simple property assignments
|
||||
- Console logging
|
||||
- Type definitions
|
||||
|
||||
### 5. Generate Recommendations
|
||||
|
||||
For each coverage gap, provide:
|
||||
- **File and line numbers**
|
||||
- **Risk level** (Critical/Important/Low)
|
||||
- **Suggested test type** (unit/integration)
|
||||
- **Test approach** (example test scenario)
|
||||
|
||||
Example:
|
||||
```
|
||||
📍 libs/oms/data-access/src/lib/services/order.service.ts:45-52
|
||||
🔴 Critical - Business Logic
|
||||
❌ 0% coverage - Error handling path
|
||||
|
||||
Recommended test:
|
||||
it('should handle API error when fetching order', async () => {
|
||||
// Mock API to return error
|
||||
// Call method
|
||||
// Verify error handling
|
||||
});
|
||||
```
|
||||
|
||||
### 6. Calculate Coverage Trends
|
||||
If historical data available:
|
||||
- Compare with previous coverage percentage
|
||||
- Show improvement/regression
|
||||
- Identify files with declining coverage
|
||||
|
||||
### 7. Generate HTML Report
|
||||
```bash
|
||||
# Open coverage report in browser (if available)
|
||||
open coverage/libs/[domain]/[layer]/[name]/index.html
|
||||
```
|
||||
|
||||
### 8. Create Coverage Summary Report
|
||||
|
||||
**Overall Metrics:**
|
||||
```
|
||||
Coverage Summary for [library-name]
|
||||
====================================
|
||||
|
||||
Line Coverage: XX.X% (XXX/XXX lines)
|
||||
Branch Coverage: XX.X% (XXX/XXX branches)
|
||||
Function Coverage: XX.X% (XXX/XXX functions)
|
||||
Statement Coverage: XX.X% (XXX/XXX statements)
|
||||
|
||||
Target: 80% (Recommended minimum)
|
||||
Status: ✅ Met / ⚠️ Below Target / 🔴 Critical
|
||||
```
|
||||
|
||||
**Files Needing Attention:**
|
||||
```
|
||||
🔴 Critical (< 50% coverage):
|
||||
1. service-name.service.ts - 35% (business logic)
|
||||
2. data-processor.ts - 42% (transformations)
|
||||
|
||||
⚠️ Below Target (50-79% coverage):
|
||||
3. component-name.component.ts - 68%
|
||||
4. validator.ts - 72%
|
||||
|
||||
✅ Well Covered (≥ 80% coverage):
|
||||
- Other files maintaining good coverage
|
||||
```
|
||||
|
||||
**Top Priority Tests to Add:**
|
||||
1. [File:Line] - [Description] - [Risk Level]
|
||||
2. ...
|
||||
|
||||
### 9. Framework-Specific Notes
|
||||
|
||||
**Vitest:**
|
||||
- Coverage provider: v8 or istanbul
|
||||
- Config in `vitest.config.ts`
|
||||
- Coverage thresholds configurable
|
||||
|
||||
**Jest:**
|
||||
- Coverage collected via `--coverage` flag
|
||||
- Config in `jest.config.ts`
|
||||
- Coverage directory: `coverage/`
|
||||
|
||||
### 10. Set Coverage Thresholds (Optional)
|
||||
Suggest adding to test config:
|
||||
```typescript
|
||||
// vitest.config.ts
|
||||
coverage: {
|
||||
thresholds: {
|
||||
lines: 80,
|
||||
functions: 80,
|
||||
branches: 80,
|
||||
statements: 80
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Output Format
|
||||
```
|
||||
Test Coverage Report
|
||||
====================
|
||||
|
||||
Library: [name]
|
||||
Test Framework: [Vitest/Jest]
|
||||
Generated: [timestamp]
|
||||
|
||||
📊 Coverage Metrics
|
||||
-------------------
|
||||
Lines: XX.X% ████████░░ (XXX/XXX)
|
||||
Branches: XX.X% ███████░░░ (XXX/XXX)
|
||||
Functions: XX.X% █████████░ (XXX/XXX)
|
||||
Statements: XX.X% ████████░░ (XXX/XXX)
|
||||
|
||||
🎯 Target: 80% | Status: [✅/⚠️/🔴]
|
||||
|
||||
🔍 Coverage Gaps
|
||||
----------------
|
||||
[Categorized list with priorities]
|
||||
|
||||
💡 Recommendations
|
||||
------------------
|
||||
[Prioritized list of tests to add]
|
||||
|
||||
📈 Next Steps
|
||||
-------------
|
||||
1. Focus on critical coverage gaps first
|
||||
2. Add tests for business logic in [files]
|
||||
3. Consider setting coverage thresholds
|
||||
4. Re-run: npx nx test [library-name] --skip-nx-cache --coverage
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
- No coverage data: Ensure `--coverage` flag used
|
||||
- Missing library: Verify library name is correct
|
||||
- Coverage tool not configured: Check test config for coverage setup
|
||||
|
||||
## References
|
||||
- docs/guidelines/testing.md
|
||||
- CLAUDE.md Testing Framework section
|
||||
- Vitest coverage: https://vitest.dev/guide/coverage
|
||||
- Jest coverage: https://jestjs.io/docs/configuration#collectcoverage-boolean
|
||||
151
.claude/skills/api-change-analyzer/SKILL.md
Normal file
151
.claude/skills/api-change-analyzer/SKILL.md
Normal file
@@ -0,0 +1,151 @@
|
||||
---
|
||||
name: api-change-analyzer
|
||||
description: This skill should be used when analyzing Swagger/OpenAPI specification changes BEFORE regenerating API clients. It compares old vs new specs, categorizes changes as breaking/compatible/warnings, finds affected code, and generates migration strategies. Use this skill when the user wants to check API changes safely before sync, mentions "check breaking changes", or needs impact assessment.
|
||||
---
|
||||
|
||||
# API Change Analyzer
|
||||
|
||||
## Overview
|
||||
|
||||
Analyze Swagger/OpenAPI specification changes to detect breaking changes before regeneration. Provides detailed comparison, impact analysis, and migration recommendations.
|
||||
|
||||
## When to Use This Skill
|
||||
|
||||
Invoke when user wants to:
|
||||
- Check API changes before regeneration
|
||||
- Assess impact of backend updates
|
||||
- Plan migration for breaking changes
|
||||
- Mentioned "breaking changes" or "API diff"
|
||||
|
||||
## Analysis Workflow
|
||||
|
||||
### Step 1: Backup and Generate Temporarily
|
||||
|
||||
```bash
|
||||
cp -r generated/swagger/[api-name] /tmp/[api-name].backup
|
||||
npm run generate:swagger:[api-name]
|
||||
```
|
||||
|
||||
### Step 2: Compare Files
|
||||
|
||||
```bash
|
||||
diff -u /tmp/[api-name].backup/models.ts generated/swagger/[api-name]/models.ts
|
||||
diff -u /tmp/[api-name].backup/services.ts generated/swagger/[api-name]/services.ts
|
||||
```
|
||||
|
||||
### Step 3: Categorize Changes
|
||||
|
||||
**🔴 Breaking (Critical):**
|
||||
- Removed properties from response models
|
||||
- Changed property types (string → number)
|
||||
- Removed endpoints
|
||||
- Optional → required fields
|
||||
- Removed enum values
|
||||
|
||||
**✅ Compatible (Safe):**
|
||||
- Added properties (non-breaking)
|
||||
- New endpoints
|
||||
- Added optional parameters
|
||||
- New enum values
|
||||
|
||||
**⚠️ Warnings (Review):**
|
||||
- Property renamed (old removed + new added)
|
||||
- Changed default values
|
||||
- Changed validation rules
|
||||
- Added required request fields
|
||||
|
||||
### Step 4: Analyze Impact
|
||||
|
||||
For each breaking change, use `Explore` agent to find usages:
|
||||
|
||||
```bash
|
||||
# Example: Find usages of removed property
|
||||
grep -r "removedProperty" libs/*/data-access --include="*.ts"
|
||||
```
|
||||
|
||||
List:
|
||||
- Affected files
|
||||
- Services impacted
|
||||
- Estimated refactoring effort
|
||||
|
||||
### Step 5: Generate Migration Strategy
|
||||
|
||||
Based on severity:
|
||||
|
||||
**High Impact (multiple breaking changes):**
|
||||
1. Create migration branch
|
||||
2. Document all changes
|
||||
3. Update services incrementally
|
||||
4. Comprehensive testing
|
||||
|
||||
**Medium Impact:**
|
||||
1. Fix compilation errors
|
||||
2. Update affected tests
|
||||
3. Deploy with monitoring
|
||||
|
||||
**Low Impact:**
|
||||
1. Minor updates
|
||||
2. Deploy
|
||||
|
||||
### Step 6: Create Report
|
||||
|
||||
```
|
||||
API Breaking Changes Analysis
|
||||
==============================
|
||||
|
||||
API: [api-name]
|
||||
Analysis Date: [timestamp]
|
||||
|
||||
📊 Summary
|
||||
----------
|
||||
Breaking Changes: XX
|
||||
Warnings: XX
|
||||
Compatible Changes: XX
|
||||
|
||||
🔴 Breaking Changes
|
||||
-------------------
|
||||
1. Removed Property: OrderResponse.deliveryDate
|
||||
Files Affected: 2
|
||||
- libs/oms/data-access/src/lib/services/order.service.ts:45
|
||||
- libs/oms/feature/order-detail/src/lib/component.ts:78
|
||||
Impact: Medium
|
||||
Fix: Remove references or use alternativeDate
|
||||
|
||||
2. Type Changed: ProductResponse.price (string → number)
|
||||
Files Affected: 1
|
||||
- libs/catalogue/data-access/src/lib/services/product.service.ts:32
|
||||
Impact: High
|
||||
Fix: Update parsing logic
|
||||
|
||||
⚠️ Warnings
|
||||
-----------
|
||||
1. Possible Rename: CustomerResponse.customerName → fullName
|
||||
Action: Verify with backend team
|
||||
|
||||
✅ Compatible Changes
|
||||
---------------------
|
||||
1. Added Property: OrderResponse.estimatedDelivery
|
||||
2. New Endpoint: GET /api/v2/orders/bulk
|
||||
|
||||
💡 Migration Strategy
|
||||
---------------------
|
||||
Approach: [High/Medium/Low Impact]
|
||||
Estimated Effort: [hours]
|
||||
Steps: [numbered list]
|
||||
|
||||
🎯 Recommendation
|
||||
-----------------
|
||||
[Proceed with sync / Fix critical issues first / Coordinate with backend]
|
||||
```
|
||||
|
||||
### Step 7: Cleanup
|
||||
|
||||
```bash
|
||||
rm -rf /tmp/[api-name].backup
|
||||
# Or restore if needed
|
||||
```
|
||||
|
||||
## References
|
||||
|
||||
- CLAUDE.md API Integration
|
||||
- Semantic Versioning: https://semver.org
|
||||
208
.claude/skills/architecture-enforcer/SKILL.md
Normal file
208
.claude/skills/architecture-enforcer/SKILL.md
Normal file
@@ -0,0 +1,208 @@
|
||||
---
|
||||
name: architecture-enforcer
|
||||
description: This skill should be used when validating import boundaries and architectural rules in the ISA-Frontend monorepo. It checks for circular dependencies, layer violations (Feature→Feature), domain violations (OMS→Remission), and relative imports. Use this skill when the user wants to check architecture, mentions "validate boundaries", "check imports", or needs dependency analysis.
|
||||
---
|
||||
|
||||
# Architecture Enforcer
|
||||
|
||||
## Overview
|
||||
|
||||
Validate and enforce architectural boundaries in the monorepo. Checks import rules, detects violations, generates dependency graphs, and suggests refactoring.
|
||||
|
||||
## When to Use This Skill
|
||||
|
||||
Invoke when user wants to:
|
||||
- Validate import boundaries
|
||||
- Check architectural rules
|
||||
- Find dependency violations
|
||||
- Mentioned "check architecture" or "validate imports"
|
||||
|
||||
## Architectural Rules
|
||||
|
||||
**✅ Allowed:**
|
||||
- Feature → Data Access
|
||||
- Feature → UI
|
||||
- Feature → Util
|
||||
- Data Access → Util
|
||||
|
||||
**❌ Forbidden:**
|
||||
- Feature → Feature
|
||||
- Data Access → Feature
|
||||
- UI → Feature
|
||||
- Cross-domain (OMS ↔ Remission)
|
||||
|
||||
## Enforcement Workflow
|
||||
|
||||
### Step 1: Run Nx Dependency Checks
|
||||
|
||||
```bash
|
||||
# Lint all (includes boundary checks)
|
||||
npx nx run-many --target=lint --all
|
||||
|
||||
# Or specific library
|
||||
npx nx lint [library-name]
|
||||
```
|
||||
|
||||
### Step 2: Generate Dependency Graph
|
||||
|
||||
```bash
|
||||
# Visual graph
|
||||
npx nx graph
|
||||
|
||||
# Focus on specific project
|
||||
npx nx graph --focus=[library-name]
|
||||
|
||||
# Affected projects
|
||||
npx nx affected:graph
|
||||
```
|
||||
|
||||
### Step 3: Scan for Violations
|
||||
|
||||
**Check for Circular Dependencies:**
|
||||
Use `Explore` agent to find A→B→A patterns.
|
||||
|
||||
**Check Layer Violations:**
|
||||
```bash
|
||||
# Find feature-to-feature imports
|
||||
grep -r "from '@isa/[^/]*/feature" libs/*/feature/ --include="*.ts"
|
||||
```
|
||||
|
||||
**Check Relative Imports:**
|
||||
```bash
|
||||
# Should use path aliases, not relative
|
||||
grep -r "from '\.\./\.\./\.\." libs/ --include="*.ts"
|
||||
```
|
||||
|
||||
**Check Direct Swagger Imports:**
|
||||
```bash
|
||||
# Should go through data-access
|
||||
grep -r "from '@generated/swagger" libs/*/feature/ --include="*.ts"
|
||||
```
|
||||
|
||||
### Step 4: Categorize Violations
|
||||
|
||||
**🔴 Critical:**
|
||||
- Circular dependencies
|
||||
- Feature → Feature
|
||||
- Data Access → Feature
|
||||
- Cross-domain dependencies
|
||||
|
||||
**⚠️ Warnings:**
|
||||
- Relative imports (should use aliases)
|
||||
- Missing tags in project.json
|
||||
- Deep import paths
|
||||
|
||||
**ℹ️ Info:**
|
||||
- Potential shared utilities
|
||||
|
||||
### Step 5: Generate Violation Report
|
||||
|
||||
For each violation:
|
||||
```
|
||||
📍 libs/oms/feature/return-search/src/lib/component.ts:12
|
||||
🔴 Layer Violation
|
||||
❌ Feature importing from another feature
|
||||
|
||||
Import: import { OrderList } from '@isa/oms/feature-order-list';
|
||||
Issue: Feature libraries should not depend on other features
|
||||
Fix: Move shared component to @isa/shared/* or @isa/ui/*
|
||||
```
|
||||
|
||||
### Step 6: Suggest Refactoring
|
||||
|
||||
**For repeated patterns:**
|
||||
- Create shared library for common components
|
||||
- Extract shared utilities to util library
|
||||
- Move API clients to data-access layer
|
||||
- Create facade services
|
||||
|
||||
### Step 7: Visualize Problems
|
||||
|
||||
```bash
|
||||
npx nx graph --focus=[problematic-library]
|
||||
```
|
||||
|
||||
### Step 8: Generate Report
|
||||
|
||||
```
|
||||
Import Boundary Analysis
|
||||
========================
|
||||
|
||||
Scope: [All | Specific library]
|
||||
|
||||
📊 Summary
|
||||
----------
|
||||
Total violations: XX
|
||||
🔴 Critical: XX
|
||||
⚠️ Warnings: XX
|
||||
ℹ️ Info: XX
|
||||
|
||||
🔍 Violations by Type
|
||||
---------------------
|
||||
Layer violations: XX
|
||||
Domain violations: XX
|
||||
Circular dependencies: XX
|
||||
Path alias violations: XX
|
||||
|
||||
🔴 Critical Violations
|
||||
----------------------
|
||||
1. [File:Line]
|
||||
Issue: Feature → Feature dependency
|
||||
Fix: Extract to @isa/shared/component-name
|
||||
|
||||
2. [File:Line]
|
||||
Issue: Circular dependency
|
||||
Fix: Extract interface to util library
|
||||
|
||||
💡 Refactoring Recommendations
|
||||
-------------------------------
|
||||
1. Create @isa/shared/order-components
|
||||
- Move: [list of shared components]
|
||||
- Benefits: Reusable, breaks circular deps
|
||||
|
||||
2. Extract interfaces to @isa/oms/util
|
||||
- Move: [list of interfaces]
|
||||
- Benefits: Breaks circular dependencies
|
||||
|
||||
📈 Dependency Graph
|
||||
-------------------
|
||||
npx nx graph --focus=[library]
|
||||
|
||||
🎯 Next Steps
|
||||
-------------
|
||||
1. Fix critical violations
|
||||
2. Update ESLint config
|
||||
3. Refactor shared components
|
||||
4. Re-run: architecture-enforcer
|
||||
```
|
||||
|
||||
## Common Fixes
|
||||
|
||||
**Circular Dependencies:**
|
||||
```typescript
|
||||
// Extract shared interface to util
|
||||
// @isa/oms/util
|
||||
export interface OrderId { id: string; }
|
||||
|
||||
// Both services import from util
|
||||
import { OrderId } from '@isa/oms/util';
|
||||
```
|
||||
|
||||
**Layer Violations:**
|
||||
```typescript
|
||||
// Move shared component from feature to ui
|
||||
// Before: @isa/oms/feature-shared
|
||||
// After: @isa/ui/order-components
|
||||
```
|
||||
|
||||
**Path Alias Usage:**
|
||||
```typescript
|
||||
// BEFORE: import { Service } from '../../../data-access/src/lib/service';
|
||||
// AFTER: import { Service } from '@isa/oms/data-access';
|
||||
```
|
||||
|
||||
## References
|
||||
|
||||
- CLAUDE.md Architecture section
|
||||
- Nx enforce-module-boundaries: https://nx.dev/nx-api/eslint-plugin/documents/enforce-module-boundaries
|
||||
- tsconfig.base.json (path aliases)
|
||||
249
.claude/skills/circular-dependency-resolver/SKILL.md
Normal file
249
.claude/skills/circular-dependency-resolver/SKILL.md
Normal file
@@ -0,0 +1,249 @@
|
||||
---
|
||||
name: circular-dependency-resolver
|
||||
description: This skill should be used when detecting and resolving circular dependencies in the ISA-Frontend monorepo. It uses graph algorithms to find A→B→C→A cycles, categorizes by severity, provides multiple fix strategies (DI, interface extraction, shared code), and validates fixes. Use this skill when the user mentions "circular dependencies", "dependency cycles", or has build/runtime issues from circular imports.
|
||||
---
|
||||
|
||||
# Circular Dependency Resolver
|
||||
|
||||
## Overview
|
||||
|
||||
Detect and resolve circular dependencies using graph analysis, multiple fix strategies, and automated validation. Prevents runtime and build issues caused by dependency cycles.
|
||||
|
||||
## When to Use This Skill
|
||||
|
||||
Invoke when user:
|
||||
- Mentions "circular dependencies"
|
||||
- Has import cycle errors
|
||||
- Requests dependency analysis
|
||||
- Build fails with circular import warnings
|
||||
|
||||
## Resolution Workflow
|
||||
|
||||
### Step 1: Detect Circular Dependencies
|
||||
|
||||
**Using Nx:**
|
||||
```bash
|
||||
npx nx run-many --target=lint --all 2>&1 | grep -i "circular"
|
||||
```
|
||||
|
||||
**Using madge (if installed):**
|
||||
```bash
|
||||
npm install -g madge
|
||||
madge --circular --extensions ts libs/
|
||||
madge --circular --image circular-deps.svg libs/
|
||||
```
|
||||
|
||||
**Using TypeScript:**
|
||||
```bash
|
||||
npx tsc --noEmit --strict 2>&1 | grep -i "circular\|cycle"
|
||||
```
|
||||
|
||||
### Step 2: Analyze Each Cycle
|
||||
|
||||
For each cycle found:
|
||||
```
|
||||
📍 Circular Dependency Detected
|
||||
|
||||
Cycle Path:
|
||||
1. libs/oms/data-access/src/lib/services/order.service.ts
|
||||
→ imports OrderValidator
|
||||
2. libs/oms/data-access/src/lib/validators/order.validator.ts
|
||||
→ imports OrderService
|
||||
3. Back to order.service.ts
|
||||
|
||||
Type: Service-Validator circular reference
|
||||
Severity: 🔴 Critical
|
||||
Files Involved: 2
|
||||
```
|
||||
|
||||
### Step 3: Categorize by Severity
|
||||
|
||||
**🔴 Critical (Must Fix):**
|
||||
- Service-to-service cycles
|
||||
- Data-access layer cycles
|
||||
- Store dependencies creating cycles
|
||||
|
||||
**⚠️ Warning (Should Fix):**
|
||||
- Component-to-component cycles
|
||||
- Model cross-references
|
||||
- Utility function cycles
|
||||
|
||||
**ℹ️ Info (Review):**
|
||||
- Type-only circular references (may be acceptable)
|
||||
- Test file circular imports
|
||||
|
||||
### Step 4: Choose Fix Strategy
|
||||
|
||||
**Strategy 1: Extract to Shared Utility**
|
||||
```typescript
|
||||
// BEFORE (Circular)
|
||||
// order.service.ts imports validator.ts
|
||||
// validator.ts imports order.service.ts
|
||||
|
||||
// AFTER (Fixed)
|
||||
// Create @isa/oms/util/types.ts
|
||||
export interface OrderData { id: string; }
|
||||
|
||||
// order.service.ts imports types
|
||||
// validator.ts imports types
|
||||
// No more cycle
|
||||
```
|
||||
|
||||
**Strategy 2: Dependency Injection (Lazy)**
|
||||
```typescript
|
||||
// BEFORE
|
||||
import { ServiceB } from './service-b';
|
||||
export class ServiceA {
|
||||
constructor(private serviceB: ServiceB) {}
|
||||
}
|
||||
|
||||
// AFTER
|
||||
import { Injector } from '@angular/core';
|
||||
export class ServiceA {
|
||||
private serviceB!: ServiceB;
|
||||
|
||||
constructor(private injector: Injector) {
|
||||
setTimeout(() => {
|
||||
this.serviceB = this.injector.get(ServiceB);
|
||||
});
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Strategy 3: Interface Extraction**
|
||||
```typescript
|
||||
// BEFORE (Models with circular reference)
|
||||
// order.ts ↔ customer.ts
|
||||
|
||||
// AFTER
|
||||
// order.interface.ts - no imports
|
||||
export interface IOrder { customerId: string; }
|
||||
|
||||
// customer.interface.ts - no imports
|
||||
export interface ICustomer { orderIds: string[]; }
|
||||
|
||||
// order.ts imports only ICustomer
|
||||
// customer.ts imports only IOrder
|
||||
```
|
||||
|
||||
**Strategy 4: Move Shared Code**
|
||||
```typescript
|
||||
// BEFORE
|
||||
// feature-a imports feature-b
|
||||
// feature-b imports feature-a
|
||||
|
||||
// AFTER
|
||||
// Extract to @isa/shared/[name]
|
||||
// Both features import from shared
|
||||
```
|
||||
|
||||
**Strategy 5: Forward References (Angular)**
|
||||
```typescript
|
||||
// Use forwardRef for components
|
||||
import { forwardRef } from '@angular/core';
|
||||
|
||||
@Component({
|
||||
imports: [forwardRef(() => ChildComponent)]
|
||||
})
|
||||
```
|
||||
|
||||
### Step 5: Implement Fix
|
||||
|
||||
Apply chosen strategy:
|
||||
1. Create new files if needed (util library, interfaces)
|
||||
2. Update imports in both files
|
||||
3. Remove circular import
|
||||
|
||||
### Step 6: Validate Fix
|
||||
|
||||
```bash
|
||||
# Check cycle resolved
|
||||
madge --circular --extensions ts libs/
|
||||
|
||||
# TypeScript compilation
|
||||
npx tsc --noEmit
|
||||
|
||||
# Run tests
|
||||
npx nx affected:test --skip-nx-cache
|
||||
|
||||
# Lint
|
||||
npx nx affected:lint
|
||||
```
|
||||
|
||||
### Step 7: Generate Report
|
||||
|
||||
```
|
||||
Circular Dependency Resolution
|
||||
===============================
|
||||
|
||||
Analysis Date: [timestamp]
|
||||
|
||||
📊 Summary
|
||||
----------
|
||||
Circular dependencies found: XX
|
||||
🔴 Critical: XX
|
||||
⚠️ Warning: XX
|
||||
Fixed: XX
|
||||
|
||||
🔍 Detected Cycles
|
||||
------------------
|
||||
|
||||
🔴 Critical Cycle #1 (FIXED)
|
||||
Path: order.service → validator → order.service
|
||||
Strategy Used: Extract to Util Library
|
||||
Created: @isa/oms/util/order-types.ts
|
||||
Files Modified: 2
|
||||
Status: ✅ Resolved
|
||||
|
||||
⚠️ Warning Cycle #2 (FIXED)
|
||||
Path: component-a → component-b → component-a
|
||||
Strategy Used: Move Shared to @isa/ui
|
||||
Created: @isa/ui/shared-component
|
||||
Files Modified: 3
|
||||
Status: ✅ Resolved
|
||||
|
||||
💡 Fix Strategies Applied
|
||||
--------------------------
|
||||
1. Extract to Util: XX cycles
|
||||
2. Interface Extraction: XX cycles
|
||||
3. Move Shared Code: XX cycles
|
||||
4. Dependency Injection: XX cycles
|
||||
|
||||
✅ Validation
|
||||
-------------
|
||||
- madge check: ✅ No cycles
|
||||
- TypeScript: ✅ Compiles
|
||||
- Tests: ✅ XX/XX passing
|
||||
- Lint: ✅ Passed
|
||||
|
||||
🎯 Prevention Tips
|
||||
------------------
|
||||
1. Add ESLint rule: import/no-cycle
|
||||
2. Pre-commit hook for cycle detection
|
||||
3. Regular architecture reviews
|
||||
```
|
||||
|
||||
## Prevention
|
||||
|
||||
**ESLint Configuration:**
|
||||
```json
|
||||
{
|
||||
"import/no-cycle": ["error", { "maxDepth": 1 }]
|
||||
}
|
||||
```
|
||||
|
||||
**Pre-commit Hook:**
|
||||
```bash
|
||||
#!/bin/bash
|
||||
madge --circular --extensions ts libs/
|
||||
if [ $? -ne 0 ]; then
|
||||
echo "❌ Circular dependencies detected"
|
||||
exit 1
|
||||
fi
|
||||
```
|
||||
|
||||
## References
|
||||
|
||||
- Madge: https://github.com/pahen/madge
|
||||
- Nx dependency graph: https://nx.dev/features/explore-graph
|
||||
- ESLint import plugin: https://github.com/import-js/eslint-plugin-import
|
||||
223
.claude/skills/library-scaffolder/SKILL.md
Normal file
223
.claude/skills/library-scaffolder/SKILL.md
Normal file
@@ -0,0 +1,223 @@
|
||||
---
|
||||
name: library-scaffolder
|
||||
description: This skill should be used when creating new Angular libraries in the ISA-Frontend monorepo. It handles Nx library generation with proper naming conventions, Vitest configuration with JUnit/Cobertura reporters, path alias setup, and validation. Use this skill when the user wants to create a new library, scaffold a feature/data-access/ui/util library, or requests "new library" creation.
|
||||
---
|
||||
|
||||
# Library Scaffolder
|
||||
|
||||
## Overview
|
||||
|
||||
Automate the creation of new Angular libraries following ISA-Frontend conventions. This skill handles the complete scaffolding workflow including Nx generation, Vitest configuration with CI/CD integration, path alias verification, and initial validation.
|
||||
|
||||
## When to Use This Skill
|
||||
|
||||
Invoke this skill when:
|
||||
- User requests creating a new library
|
||||
- User mentions "new library", "scaffold library", or "create feature"
|
||||
- User wants to add a new domain/layer/feature to the monorepo
|
||||
|
||||
## Required Parameters
|
||||
|
||||
User must provide:
|
||||
- **domain**: Domain name (oms, remission, checkout, ui, core, shared, utils)
|
||||
- **layer**: Layer type (feature, data-access, ui, util)
|
||||
- **name**: Library name in kebab-case
|
||||
|
||||
## Scaffolding Workflow
|
||||
|
||||
### Step 1: Validate Input
|
||||
|
||||
1. **Verify Domain**
|
||||
- Use `docs-researcher` to check `docs/library-reference.md`
|
||||
- Ensure domain follows existing patterns
|
||||
|
||||
2. **Validate Layer**
|
||||
- Must be one of: feature, data-access, ui, util
|
||||
|
||||
3. **Check Name**
|
||||
- Must be kebab-case
|
||||
- Must not conflict with existing libraries
|
||||
|
||||
4. **Determine Path Depth**
|
||||
- 3 levels: `libs/domain/layer/name` → `../../../`
|
||||
- 4 levels: `libs/domain/type/layer/name` → `../../../../`
|
||||
|
||||
### Step 2: Run Dry-Run
|
||||
|
||||
Execute Nx generator with `--dry-run`:
|
||||
|
||||
```bash
|
||||
npx nx generate @nx/angular:library \
|
||||
--name=[domain]-[layer]-[name] \
|
||||
--directory=libs/[domain]/[layer]/[name] \
|
||||
--importPath=@isa/[domain]/[layer]/[name] \
|
||||
--style=css \
|
||||
--unitTestRunner=vitest \
|
||||
--standalone=true \
|
||||
--skipTests=false \
|
||||
--dry-run
|
||||
```
|
||||
|
||||
Review output with user before proceeding.
|
||||
|
||||
### Step 3: Generate Library
|
||||
|
||||
Execute without `--dry-run`:
|
||||
|
||||
```bash
|
||||
npx nx generate @nx/angular:library \
|
||||
--name=[domain]-[layer]-[name] \
|
||||
--directory=libs/[domain]/[layer]/[name] \
|
||||
--importPath=@isa/[domain]/[layer]/[name] \
|
||||
--style=css \
|
||||
--unitTestRunner=vitest \
|
||||
--standalone=true \
|
||||
--skipTests=false
|
||||
```
|
||||
|
||||
### Step 4: Configure Vitest with JUnit and Cobertura
|
||||
|
||||
Update `libs/[path]/vite.config.mts`:
|
||||
|
||||
```typescript
|
||||
/// <reference types='vitest' />
|
||||
import { defineConfig } from 'vite';
|
||||
import angular from '@analogjs/vite-plugin-angular';
|
||||
import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin';
|
||||
import { nxCopyAssetsPlugin } from '@nx/vite/plugins/nx-copy-assets.plugin';
|
||||
|
||||
export default
|
||||
// @ts-expect-error - Vitest reporter tuple types have complex inference issues
|
||||
defineConfig(() => ({
|
||||
root: __dirname,
|
||||
cacheDir: '../../../node_modules/.vite/libs/[path]',
|
||||
plugins: [angular(), nxViteTsPaths(), nxCopyAssetsPlugin(['*.md'])],
|
||||
test: {
|
||||
watch: false,
|
||||
globals: true,
|
||||
environment: 'jsdom',
|
||||
include: ['{src,tests}/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
|
||||
setupFiles: ['src/test-setup.ts'],
|
||||
reporters: [
|
||||
'default',
|
||||
['junit', { outputFile: '../../../testresults/junit-[library-name].xml' }],
|
||||
],
|
||||
coverage: {
|
||||
reportsDirectory: '../../../coverage/libs/[path]',
|
||||
provider: 'v8' as const,
|
||||
reporter: ['text', 'cobertura'],
|
||||
},
|
||||
},
|
||||
}));
|
||||
```
|
||||
|
||||
**Critical**: Adjust path depth based on library location.
|
||||
|
||||
### Step 5: Verify Configuration
|
||||
|
||||
1. **Check Path Alias**
|
||||
- Verify `tsconfig.base.json` was updated
|
||||
- Should have: `"@isa/[domain]/[layer]/[name]": ["libs/[domain]/[layer]/[name]/src/index.ts"]`
|
||||
|
||||
2. **Run Initial Test**
|
||||
```bash
|
||||
npx nx test [library-name] --coverage.enabled=true --skip-nx-cache
|
||||
```
|
||||
|
||||
3. **Verify CI/CD Files Created**
|
||||
- JUnit XML: `testresults/junit-[library-name].xml`
|
||||
- Cobertura XML: `coverage/libs/[path]/cobertura-coverage.xml`
|
||||
|
||||
### Step 6: Create Library README
|
||||
|
||||
Use `docs-researcher` to find similar library READMEs, then create comprehensive documentation including:
|
||||
- Overview and purpose
|
||||
- Installation/import instructions
|
||||
- API documentation
|
||||
- Usage examples
|
||||
- Testing information (Vitest + Angular Testing Utilities)
|
||||
|
||||
### Step 7: Update Library Reference
|
||||
|
||||
Add entry to `docs/library-reference.md` under appropriate domain:
|
||||
|
||||
```markdown
|
||||
#### `@isa/[domain]/[layer]/[name]`
|
||||
**Path:** `libs/[domain]/[layer]/[name]`
|
||||
**Type:** [Feature/Data Access/UI/Util]
|
||||
**Testing:** Vitest
|
||||
|
||||
[Brief description]
|
||||
```
|
||||
|
||||
### Step 8: Run Full Validation
|
||||
|
||||
```bash
|
||||
# Lint
|
||||
npx nx lint [library-name]
|
||||
|
||||
# Test with coverage
|
||||
npx nx test [library-name] --coverage.enabled=true --skip-nx-cache
|
||||
|
||||
# Build (if buildable)
|
||||
npx nx build [library-name]
|
||||
|
||||
# Dependency graph
|
||||
npx nx graph --focus=[library-name]
|
||||
```
|
||||
|
||||
### Step 9: Generate Creation Report
|
||||
|
||||
```
|
||||
Library Created Successfully
|
||||
============================
|
||||
|
||||
Library Name: [domain]-[layer]-[name]
|
||||
Path: libs/[domain]/[layer]/[name]
|
||||
Import Alias: @isa/[domain]/[layer]/[name]
|
||||
|
||||
✅ Configuration
|
||||
----------------
|
||||
Test Framework: Vitest with Angular Testing Utilities
|
||||
Style: CSS
|
||||
Standalone: Yes
|
||||
JUnit Reporter: ✅ testresults/junit-[library-name].xml
|
||||
Cobertura Coverage: ✅ coverage/libs/[path]/cobertura-coverage.xml
|
||||
|
||||
📦 Import Statement
|
||||
-------------------
|
||||
import { Component } from '@isa/[domain]/[layer]/[name]';
|
||||
|
||||
🧪 Test Commands
|
||||
----------------
|
||||
npx nx test [library-name] --skip-nx-cache
|
||||
npx nx test [library-name] --coverage.enabled=true --skip-nx-cache
|
||||
|
||||
📝 Next Steps
|
||||
-------------
|
||||
1. Develop library features
|
||||
2. Write tests using Vitest + Angular Testing Utilities
|
||||
3. Add E2E attributes (data-what, data-which) to templates
|
||||
4. Update README with usage examples
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
**Issue: Path depth mismatch**
|
||||
- Count directory levels from workspace root
|
||||
- Adjust `../` in outputFile and reportsDirectory
|
||||
|
||||
**Issue: TypeScript errors in vite.config.mts**
|
||||
- Add `// @ts-expect-error` before `defineConfig()`
|
||||
|
||||
**Issue: Path alias not working**
|
||||
- Check tsconfig.base.json
|
||||
- Run `npx nx reset`
|
||||
- Restart TypeScript server
|
||||
|
||||
## References
|
||||
|
||||
- docs/guidelines/testing.md (Vitest, JUnit, Cobertura sections)
|
||||
- docs/library-reference.md (domain patterns)
|
||||
- CLAUDE.md (Library Organization, Testing Framework sections)
|
||||
- Nx Angular Library Generator: https://nx.dev/nx-api/angular/generators/library
|
||||
202
.claude/skills/skill-creator/LICENSE.txt
Normal file
202
.claude/skills/skill-creator/LICENSE.txt
Normal file
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
209
.claude/skills/skill-creator/SKILL.md
Normal file
209
.claude/skills/skill-creator/SKILL.md
Normal file
@@ -0,0 +1,209 @@
|
||||
---
|
||||
name: skill-creator
|
||||
description: Guide for creating effective skills. This skill should be used when users want to create a new skill (or update an existing skill) that extends Claude's capabilities with specialized knowledge, workflows, or tool integrations.
|
||||
license: Complete terms in LICENSE.txt
|
||||
---
|
||||
|
||||
# Skill Creator
|
||||
|
||||
This skill provides guidance for creating effective skills.
|
||||
|
||||
## About Skills
|
||||
|
||||
Skills are modular, self-contained packages that extend Claude's capabilities by providing
|
||||
specialized knowledge, workflows, and tools. Think of them as "onboarding guides" for specific
|
||||
domains or tasks—they transform Claude from a general-purpose agent into a specialized agent
|
||||
equipped with procedural knowledge that no model can fully possess.
|
||||
|
||||
### What Skills Provide
|
||||
|
||||
1. Specialized workflows - Multi-step procedures for specific domains
|
||||
2. Tool integrations - Instructions for working with specific file formats or APIs
|
||||
3. Domain expertise - Company-specific knowledge, schemas, business logic
|
||||
4. Bundled resources - Scripts, references, and assets for complex and repetitive tasks
|
||||
|
||||
### Anatomy of a Skill
|
||||
|
||||
Every skill consists of a required SKILL.md file and optional bundled resources:
|
||||
|
||||
```
|
||||
skill-name/
|
||||
├── SKILL.md (required)
|
||||
│ ├── YAML frontmatter metadata (required)
|
||||
│ │ ├── name: (required)
|
||||
│ │ └── description: (required)
|
||||
│ └── Markdown instructions (required)
|
||||
└── Bundled Resources (optional)
|
||||
├── scripts/ - Executable code (Python/Bash/etc.)
|
||||
├── references/ - Documentation intended to be loaded into context as needed
|
||||
└── assets/ - Files used in output (templates, icons, fonts, etc.)
|
||||
```
|
||||
|
||||
#### SKILL.md (required)
|
||||
|
||||
**Metadata Quality:** The `name` and `description` in YAML frontmatter determine when Claude will use the skill. Be specific about what the skill does and when to use it. Use the third-person (e.g. "This skill should be used when..." instead of "Use this skill when...").
|
||||
|
||||
#### Bundled Resources (optional)
|
||||
|
||||
##### Scripts (`scripts/`)
|
||||
|
||||
Executable code (Python/Bash/etc.) for tasks that require deterministic reliability or are repeatedly rewritten.
|
||||
|
||||
- **When to include**: When the same code is being rewritten repeatedly or deterministic reliability is needed
|
||||
- **Example**: `scripts/rotate_pdf.py` for PDF rotation tasks
|
||||
- **Benefits**: Token efficient, deterministic, may be executed without loading into context
|
||||
- **Note**: Scripts may still need to be read by Claude for patching or environment-specific adjustments
|
||||
|
||||
##### References (`references/`)
|
||||
|
||||
Documentation and reference material intended to be loaded as needed into context to inform Claude's process and thinking.
|
||||
|
||||
- **When to include**: For documentation that Claude should reference while working
|
||||
- **Examples**: `references/finance.md` for financial schemas, `references/mnda.md` for company NDA template, `references/policies.md` for company policies, `references/api_docs.md` for API specifications
|
||||
- **Use cases**: Database schemas, API documentation, domain knowledge, company policies, detailed workflow guides
|
||||
- **Benefits**: Keeps SKILL.md lean, loaded only when Claude determines it's needed
|
||||
- **Best practice**: If files are large (>10k words), include grep search patterns in SKILL.md
|
||||
- **Avoid duplication**: Information should live in either SKILL.md or references files, not both. Prefer references files for detailed information unless it's truly core to the skill—this keeps SKILL.md lean while making information discoverable without hogging the context window. Keep only essential procedural instructions and workflow guidance in SKILL.md; move detailed reference material, schemas, and examples to references files.
|
||||
|
||||
##### Assets (`assets/`)
|
||||
|
||||
Files not intended to be loaded into context, but rather used within the output Claude produces.
|
||||
|
||||
- **When to include**: When the skill needs files that will be used in the final output
|
||||
- **Examples**: `assets/logo.png` for brand assets, `assets/slides.pptx` for PowerPoint templates, `assets/frontend-template/` for HTML/React boilerplate, `assets/font.ttf` for typography
|
||||
- **Use cases**: Templates, images, icons, boilerplate code, fonts, sample documents that get copied or modified
|
||||
- **Benefits**: Separates output resources from documentation, enables Claude to use files without loading them into context
|
||||
|
||||
### Progressive Disclosure Design Principle
|
||||
|
||||
Skills use a three-level loading system to manage context efficiently:
|
||||
|
||||
1. **Metadata (name + description)** - Always in context (~100 words)
|
||||
2. **SKILL.md body** - When skill triggers (<5k words)
|
||||
3. **Bundled resources** - As needed by Claude (Unlimited*)
|
||||
|
||||
*Unlimited because scripts can be executed without reading into context window.
|
||||
|
||||
## Skill Creation Process
|
||||
|
||||
To create a skill, follow the "Skill Creation Process" in order, skipping steps only if there is a clear reason why they are not applicable.
|
||||
|
||||
### Step 1: Understanding the Skill with Concrete Examples
|
||||
|
||||
Skip this step only when the skill's usage patterns are already clearly understood. It remains valuable even when working with an existing skill.
|
||||
|
||||
To create an effective skill, clearly understand concrete examples of how the skill will be used. This understanding can come from either direct user examples or generated examples that are validated with user feedback.
|
||||
|
||||
For example, when building an image-editor skill, relevant questions include:
|
||||
|
||||
- "What functionality should the image-editor skill support? Editing, rotating, anything else?"
|
||||
- "Can you give some examples of how this skill would be used?"
|
||||
- "I can imagine users asking for things like 'Remove the red-eye from this image' or 'Rotate this image'. Are there other ways you imagine this skill being used?"
|
||||
- "What would a user say that should trigger this skill?"
|
||||
|
||||
To avoid overwhelming users, avoid asking too many questions in a single message. Start with the most important questions and follow up as needed for better effectiveness.
|
||||
|
||||
Conclude this step when there is a clear sense of the functionality the skill should support.
|
||||
|
||||
### Step 2: Planning the Reusable Skill Contents
|
||||
|
||||
To turn concrete examples into an effective skill, analyze each example by:
|
||||
|
||||
1. Considering how to execute on the example from scratch
|
||||
2. Identifying what scripts, references, and assets would be helpful when executing these workflows repeatedly
|
||||
|
||||
Example: When building a `pdf-editor` skill to handle queries like "Help me rotate this PDF," the analysis shows:
|
||||
|
||||
1. Rotating a PDF requires re-writing the same code each time
|
||||
2. A `scripts/rotate_pdf.py` script would be helpful to store in the skill
|
||||
|
||||
Example: When designing a `frontend-webapp-builder` skill for queries like "Build me a todo app" or "Build me a dashboard to track my steps," the analysis shows:
|
||||
|
||||
1. Writing a frontend webapp requires the same boilerplate HTML/React each time
|
||||
2. An `assets/hello-world/` template containing the boilerplate HTML/React project files would be helpful to store in the skill
|
||||
|
||||
Example: When building a `big-query` skill to handle queries like "How many users have logged in today?" the analysis shows:
|
||||
|
||||
1. Querying BigQuery requires re-discovering the table schemas and relationships each time
|
||||
2. A `references/schema.md` file documenting the table schemas would be helpful to store in the skill
|
||||
|
||||
To establish the skill's contents, analyze each concrete example to create a list of the reusable resources to include: scripts, references, and assets.
|
||||
|
||||
### Step 3: Initializing the Skill
|
||||
|
||||
At this point, it is time to actually create the skill.
|
||||
|
||||
Skip this step only if the skill being developed already exists, and iteration or packaging is needed. In this case, continue to the next step.
|
||||
|
||||
When creating a new skill from scratch, always run the `init_skill.py` script. The script conveniently generates a new template skill directory that automatically includes everything a skill requires, making the skill creation process much more efficient and reliable.
|
||||
|
||||
Usage:
|
||||
|
||||
```bash
|
||||
scripts/init_skill.py <skill-name> --path <output-directory>
|
||||
```
|
||||
|
||||
The script:
|
||||
|
||||
- Creates the skill directory at the specified path
|
||||
- Generates a SKILL.md template with proper frontmatter and TODO placeholders
|
||||
- Creates example resource directories: `scripts/`, `references/`, and `assets/`
|
||||
- Adds example files in each directory that can be customized or deleted
|
||||
|
||||
After initialization, customize or remove the generated SKILL.md and example files as needed.
|
||||
|
||||
### Step 4: Edit the Skill
|
||||
|
||||
When editing the (newly-generated or existing) skill, remember that the skill is being created for another instance of Claude to use. Focus on including information that would be beneficial and non-obvious to Claude. Consider what procedural knowledge, domain-specific details, or reusable assets would help another Claude instance execute these tasks more effectively.
|
||||
|
||||
#### Start with Reusable Skill Contents
|
||||
|
||||
To begin implementation, start with the reusable resources identified above: `scripts/`, `references/`, and `assets/` files. Note that this step may require user input. For example, when implementing a `brand-guidelines` skill, the user may need to provide brand assets or templates to store in `assets/`, or documentation to store in `references/`.
|
||||
|
||||
Also, delete any example files and directories not needed for the skill. The initialization script creates example files in `scripts/`, `references/`, and `assets/` to demonstrate structure, but most skills won't need all of them.
|
||||
|
||||
#### Update SKILL.md
|
||||
|
||||
**Writing Style:** Write the entire skill using **imperative/infinitive form** (verb-first instructions), not second person. Use objective, instructional language (e.g., "To accomplish X, do Y" rather than "You should do X" or "If you need to do X"). This maintains consistency and clarity for AI consumption.
|
||||
|
||||
To complete SKILL.md, answer the following questions:
|
||||
|
||||
1. What is the purpose of the skill, in a few sentences?
|
||||
2. When should the skill be used?
|
||||
3. In practice, how should Claude use the skill? All reusable skill contents developed above should be referenced so that Claude knows how to use them.
|
||||
|
||||
### Step 5: Packaging a Skill
|
||||
|
||||
Once the skill is ready, it should be packaged into a distributable zip file that gets shared with the user. The packaging process automatically validates the skill first to ensure it meets all requirements:
|
||||
|
||||
```bash
|
||||
scripts/package_skill.py <path/to/skill-folder>
|
||||
```
|
||||
|
||||
Optional output directory specification:
|
||||
|
||||
```bash
|
||||
scripts/package_skill.py <path/to/skill-folder> ./dist
|
||||
```
|
||||
|
||||
The packaging script will:
|
||||
|
||||
1. **Validate** the skill automatically, checking:
|
||||
- YAML frontmatter format and required fields
|
||||
- Skill naming conventions and directory structure
|
||||
- Description completeness and quality
|
||||
- File organization and resource references
|
||||
|
||||
2. **Package** the skill if validation passes, creating a zip file named after the skill (e.g., `my-skill.zip`) that includes all files and maintains the proper directory structure for distribution.
|
||||
|
||||
If validation fails, the script will report the errors and exit without creating a package. Fix any validation errors and run the packaging command again.
|
||||
|
||||
### Step 6: Iterate
|
||||
|
||||
After testing the skill, users may request improvements. Often this happens right after using the skill, with fresh context of how the skill performed.
|
||||
|
||||
**Iteration workflow:**
|
||||
1. Use the skill on real tasks
|
||||
2. Notice struggles or inefficiencies
|
||||
3. Identify how SKILL.md or bundled resources should be updated
|
||||
4. Implement changes and test again
|
||||
303
.claude/skills/skill-creator/scripts/init_skill.py
Executable file
303
.claude/skills/skill-creator/scripts/init_skill.py
Executable file
@@ -0,0 +1,303 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Skill Initializer - Creates a new skill from template
|
||||
|
||||
Usage:
|
||||
init_skill.py <skill-name> --path <path>
|
||||
|
||||
Examples:
|
||||
init_skill.py my-new-skill --path skills/public
|
||||
init_skill.py my-api-helper --path skills/private
|
||||
init_skill.py custom-skill --path /custom/location
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
SKILL_TEMPLATE = """---
|
||||
name: {skill_name}
|
||||
description: [TODO: Complete and informative explanation of what the skill does and when to use it. Include WHEN to use this skill - specific scenarios, file types, or tasks that trigger it.]
|
||||
---
|
||||
|
||||
# {skill_title}
|
||||
|
||||
## Overview
|
||||
|
||||
[TODO: 1-2 sentences explaining what this skill enables]
|
||||
|
||||
## Structuring This Skill
|
||||
|
||||
[TODO: Choose the structure that best fits this skill's purpose. Common patterns:
|
||||
|
||||
**1. Workflow-Based** (best for sequential processes)
|
||||
- Works well when there are clear step-by-step procedures
|
||||
- Example: DOCX skill with "Workflow Decision Tree" → "Reading" → "Creating" → "Editing"
|
||||
- Structure: ## Overview → ## Workflow Decision Tree → ## Step 1 → ## Step 2...
|
||||
|
||||
**2. Task-Based** (best for tool collections)
|
||||
- Works well when the skill offers different operations/capabilities
|
||||
- Example: PDF skill with "Quick Start" → "Merge PDFs" → "Split PDFs" → "Extract Text"
|
||||
- Structure: ## Overview → ## Quick Start → ## Task Category 1 → ## Task Category 2...
|
||||
|
||||
**3. Reference/Guidelines** (best for standards or specifications)
|
||||
- Works well for brand guidelines, coding standards, or requirements
|
||||
- Example: Brand styling with "Brand Guidelines" → "Colors" → "Typography" → "Features"
|
||||
- Structure: ## Overview → ## Guidelines → ## Specifications → ## Usage...
|
||||
|
||||
**4. Capabilities-Based** (best for integrated systems)
|
||||
- Works well when the skill provides multiple interrelated features
|
||||
- Example: Product Management with "Core Capabilities" → numbered capability list
|
||||
- Structure: ## Overview → ## Core Capabilities → ### 1. Feature → ### 2. Feature...
|
||||
|
||||
Patterns can be mixed and matched as needed. Most skills combine patterns (e.g., start with task-based, add workflow for complex operations).
|
||||
|
||||
Delete this entire "Structuring This Skill" section when done - it's just guidance.]
|
||||
|
||||
## [TODO: Replace with the first main section based on chosen structure]
|
||||
|
||||
[TODO: Add content here. See examples in existing skills:
|
||||
- Code samples for technical skills
|
||||
- Decision trees for complex workflows
|
||||
- Concrete examples with realistic user requests
|
||||
- References to scripts/templates/references as needed]
|
||||
|
||||
## Resources
|
||||
|
||||
This skill includes example resource directories that demonstrate how to organize different types of bundled resources:
|
||||
|
||||
### scripts/
|
||||
Executable code (Python/Bash/etc.) that can be run directly to perform specific operations.
|
||||
|
||||
**Examples from other skills:**
|
||||
- PDF skill: `fill_fillable_fields.py`, `extract_form_field_info.py` - utilities for PDF manipulation
|
||||
- DOCX skill: `document.py`, `utilities.py` - Python modules for document processing
|
||||
|
||||
**Appropriate for:** Python scripts, shell scripts, or any executable code that performs automation, data processing, or specific operations.
|
||||
|
||||
**Note:** Scripts may be executed without loading into context, but can still be read by Claude for patching or environment adjustments.
|
||||
|
||||
### references/
|
||||
Documentation and reference material intended to be loaded into context to inform Claude's process and thinking.
|
||||
|
||||
**Examples from other skills:**
|
||||
- Product management: `communication.md`, `context_building.md` - detailed workflow guides
|
||||
- BigQuery: API reference documentation and query examples
|
||||
- Finance: Schema documentation, company policies
|
||||
|
||||
**Appropriate for:** In-depth documentation, API references, database schemas, comprehensive guides, or any detailed information that Claude should reference while working.
|
||||
|
||||
### assets/
|
||||
Files not intended to be loaded into context, but rather used within the output Claude produces.
|
||||
|
||||
**Examples from other skills:**
|
||||
- Brand styling: PowerPoint template files (.pptx), logo files
|
||||
- Frontend builder: HTML/React boilerplate project directories
|
||||
- Typography: Font files (.ttf, .woff2)
|
||||
|
||||
**Appropriate for:** Templates, boilerplate code, document templates, images, icons, fonts, or any files meant to be copied or used in the final output.
|
||||
|
||||
---
|
||||
|
||||
**Any unneeded directories can be deleted.** Not every skill requires all three types of resources.
|
||||
"""
|
||||
|
||||
EXAMPLE_SCRIPT = '''#!/usr/bin/env python3
|
||||
"""
|
||||
Example helper script for {skill_name}
|
||||
|
||||
This is a placeholder script that can be executed directly.
|
||||
Replace with actual implementation or delete if not needed.
|
||||
|
||||
Example real scripts from other skills:
|
||||
- pdf/scripts/fill_fillable_fields.py - Fills PDF form fields
|
||||
- pdf/scripts/convert_pdf_to_images.py - Converts PDF pages to images
|
||||
"""
|
||||
|
||||
def main():
|
||||
print("This is an example script for {skill_name}")
|
||||
# TODO: Add actual script logic here
|
||||
# This could be data processing, file conversion, API calls, etc.
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
'''
|
||||
|
||||
EXAMPLE_REFERENCE = """# Reference Documentation for {skill_title}
|
||||
|
||||
This is a placeholder for detailed reference documentation.
|
||||
Replace with actual reference content or delete if not needed.
|
||||
|
||||
Example real reference docs from other skills:
|
||||
- product-management/references/communication.md - Comprehensive guide for status updates
|
||||
- product-management/references/context_building.md - Deep-dive on gathering context
|
||||
- bigquery/references/ - API references and query examples
|
||||
|
||||
## When Reference Docs Are Useful
|
||||
|
||||
Reference docs are ideal for:
|
||||
- Comprehensive API documentation
|
||||
- Detailed workflow guides
|
||||
- Complex multi-step processes
|
||||
- Information too lengthy for main SKILL.md
|
||||
- Content that's only needed for specific use cases
|
||||
|
||||
## Structure Suggestions
|
||||
|
||||
### API Reference Example
|
||||
- Overview
|
||||
- Authentication
|
||||
- Endpoints with examples
|
||||
- Error codes
|
||||
- Rate limits
|
||||
|
||||
### Workflow Guide Example
|
||||
- Prerequisites
|
||||
- Step-by-step instructions
|
||||
- Common patterns
|
||||
- Troubleshooting
|
||||
- Best practices
|
||||
"""
|
||||
|
||||
EXAMPLE_ASSET = """# Example Asset File
|
||||
|
||||
This placeholder represents where asset files would be stored.
|
||||
Replace with actual asset files (templates, images, fonts, etc.) or delete if not needed.
|
||||
|
||||
Asset files are NOT intended to be loaded into context, but rather used within
|
||||
the output Claude produces.
|
||||
|
||||
Example asset files from other skills:
|
||||
- Brand guidelines: logo.png, slides_template.pptx
|
||||
- Frontend builder: hello-world/ directory with HTML/React boilerplate
|
||||
- Typography: custom-font.ttf, font-family.woff2
|
||||
- Data: sample_data.csv, test_dataset.json
|
||||
|
||||
## Common Asset Types
|
||||
|
||||
- Templates: .pptx, .docx, boilerplate directories
|
||||
- Images: .png, .jpg, .svg, .gif
|
||||
- Fonts: .ttf, .otf, .woff, .woff2
|
||||
- Boilerplate code: Project directories, starter files
|
||||
- Icons: .ico, .svg
|
||||
- Data files: .csv, .json, .xml, .yaml
|
||||
|
||||
Note: This is a text placeholder. Actual assets can be any file type.
|
||||
"""
|
||||
|
||||
|
||||
def title_case_skill_name(skill_name):
|
||||
"""Convert hyphenated skill name to Title Case for display."""
|
||||
return ' '.join(word.capitalize() for word in skill_name.split('-'))
|
||||
|
||||
|
||||
def init_skill(skill_name, path):
|
||||
"""
|
||||
Initialize a new skill directory with template SKILL.md.
|
||||
|
||||
Args:
|
||||
skill_name: Name of the skill
|
||||
path: Path where the skill directory should be created
|
||||
|
||||
Returns:
|
||||
Path to created skill directory, or None if error
|
||||
"""
|
||||
# Determine skill directory path
|
||||
skill_dir = Path(path).resolve() / skill_name
|
||||
|
||||
# Check if directory already exists
|
||||
if skill_dir.exists():
|
||||
print(f"❌ Error: Skill directory already exists: {skill_dir}")
|
||||
return None
|
||||
|
||||
# Create skill directory
|
||||
try:
|
||||
skill_dir.mkdir(parents=True, exist_ok=False)
|
||||
print(f"✅ Created skill directory: {skill_dir}")
|
||||
except Exception as e:
|
||||
print(f"❌ Error creating directory: {e}")
|
||||
return None
|
||||
|
||||
# Create SKILL.md from template
|
||||
skill_title = title_case_skill_name(skill_name)
|
||||
skill_content = SKILL_TEMPLATE.format(
|
||||
skill_name=skill_name,
|
||||
skill_title=skill_title
|
||||
)
|
||||
|
||||
skill_md_path = skill_dir / 'SKILL.md'
|
||||
try:
|
||||
skill_md_path.write_text(skill_content)
|
||||
print("✅ Created SKILL.md")
|
||||
except Exception as e:
|
||||
print(f"❌ Error creating SKILL.md: {e}")
|
||||
return None
|
||||
|
||||
# Create resource directories with example files
|
||||
try:
|
||||
# Create scripts/ directory with example script
|
||||
scripts_dir = skill_dir / 'scripts'
|
||||
scripts_dir.mkdir(exist_ok=True)
|
||||
example_script = scripts_dir / 'example.py'
|
||||
example_script.write_text(EXAMPLE_SCRIPT.format(skill_name=skill_name))
|
||||
example_script.chmod(0o755)
|
||||
print("✅ Created scripts/example.py")
|
||||
|
||||
# Create references/ directory with example reference doc
|
||||
references_dir = skill_dir / 'references'
|
||||
references_dir.mkdir(exist_ok=True)
|
||||
example_reference = references_dir / 'api_reference.md'
|
||||
example_reference.write_text(EXAMPLE_REFERENCE.format(skill_title=skill_title))
|
||||
print("✅ Created references/api_reference.md")
|
||||
|
||||
# Create assets/ directory with example asset placeholder
|
||||
assets_dir = skill_dir / 'assets'
|
||||
assets_dir.mkdir(exist_ok=True)
|
||||
example_asset = assets_dir / 'example_asset.txt'
|
||||
example_asset.write_text(EXAMPLE_ASSET)
|
||||
print("✅ Created assets/example_asset.txt")
|
||||
except Exception as e:
|
||||
print(f"❌ Error creating resource directories: {e}")
|
||||
return None
|
||||
|
||||
# Print next steps
|
||||
print(f"\n✅ Skill '{skill_name}' initialized successfully at {skill_dir}")
|
||||
print("\nNext steps:")
|
||||
print("1. Edit SKILL.md to complete the TODO items and update the description")
|
||||
print("2. Customize or delete the example files in scripts/, references/, and assets/")
|
||||
print("3. Run the validator when ready to check the skill structure")
|
||||
|
||||
return skill_dir
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 4 or sys.argv[2] != '--path':
|
||||
print("Usage: init_skill.py <skill-name> --path <path>")
|
||||
print("\nSkill name requirements:")
|
||||
print(" - Hyphen-case identifier (e.g., 'data-analyzer')")
|
||||
print(" - Lowercase letters, digits, and hyphens only")
|
||||
print(" - Max 40 characters")
|
||||
print(" - Must match directory name exactly")
|
||||
print("\nExamples:")
|
||||
print(" init_skill.py my-new-skill --path skills/public")
|
||||
print(" init_skill.py my-api-helper --path skills/private")
|
||||
print(" init_skill.py custom-skill --path /custom/location")
|
||||
sys.exit(1)
|
||||
|
||||
skill_name = sys.argv[1]
|
||||
path = sys.argv[3]
|
||||
|
||||
print(f"🚀 Initializing skill: {skill_name}")
|
||||
print(f" Location: {path}")
|
||||
print()
|
||||
|
||||
result = init_skill(skill_name, path)
|
||||
|
||||
if result:
|
||||
sys.exit(0)
|
||||
else:
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
110
.claude/skills/skill-creator/scripts/package_skill.py
Executable file
110
.claude/skills/skill-creator/scripts/package_skill.py
Executable file
@@ -0,0 +1,110 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Skill Packager - Creates a distributable zip file of a skill folder
|
||||
|
||||
Usage:
|
||||
python utils/package_skill.py <path/to/skill-folder> [output-directory]
|
||||
|
||||
Example:
|
||||
python utils/package_skill.py skills/public/my-skill
|
||||
python utils/package_skill.py skills/public/my-skill ./dist
|
||||
"""
|
||||
|
||||
import sys
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from quick_validate import validate_skill
|
||||
|
||||
|
||||
def package_skill(skill_path, output_dir=None):
|
||||
"""
|
||||
Package a skill folder into a zip file.
|
||||
|
||||
Args:
|
||||
skill_path: Path to the skill folder
|
||||
output_dir: Optional output directory for the zip file (defaults to current directory)
|
||||
|
||||
Returns:
|
||||
Path to the created zip file, or None if error
|
||||
"""
|
||||
skill_path = Path(skill_path).resolve()
|
||||
|
||||
# Validate skill folder exists
|
||||
if not skill_path.exists():
|
||||
print(f"❌ Error: Skill folder not found: {skill_path}")
|
||||
return None
|
||||
|
||||
if not skill_path.is_dir():
|
||||
print(f"❌ Error: Path is not a directory: {skill_path}")
|
||||
return None
|
||||
|
||||
# Validate SKILL.md exists
|
||||
skill_md = skill_path / "SKILL.md"
|
||||
if not skill_md.exists():
|
||||
print(f"❌ Error: SKILL.md not found in {skill_path}")
|
||||
return None
|
||||
|
||||
# Run validation before packaging
|
||||
print("🔍 Validating skill...")
|
||||
valid, message = validate_skill(skill_path)
|
||||
if not valid:
|
||||
print(f"❌ Validation failed: {message}")
|
||||
print(" Please fix the validation errors before packaging.")
|
||||
return None
|
||||
print(f"✅ {message}\n")
|
||||
|
||||
# Determine output location
|
||||
skill_name = skill_path.name
|
||||
if output_dir:
|
||||
output_path = Path(output_dir).resolve()
|
||||
output_path.mkdir(parents=True, exist_ok=True)
|
||||
else:
|
||||
output_path = Path.cwd()
|
||||
|
||||
zip_filename = output_path / f"{skill_name}.zip"
|
||||
|
||||
# Create the zip file
|
||||
try:
|
||||
with zipfile.ZipFile(zip_filename, 'w', zipfile.ZIP_DEFLATED) as zipf:
|
||||
# Walk through the skill directory
|
||||
for file_path in skill_path.rglob('*'):
|
||||
if file_path.is_file():
|
||||
# Calculate the relative path within the zip
|
||||
arcname = file_path.relative_to(skill_path.parent)
|
||||
zipf.write(file_path, arcname)
|
||||
print(f" Added: {arcname}")
|
||||
|
||||
print(f"\n✅ Successfully packaged skill to: {zip_filename}")
|
||||
return zip_filename
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Error creating zip file: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2:
|
||||
print("Usage: python utils/package_skill.py <path/to/skill-folder> [output-directory]")
|
||||
print("\nExample:")
|
||||
print(" python utils/package_skill.py skills/public/my-skill")
|
||||
print(" python utils/package_skill.py skills/public/my-skill ./dist")
|
||||
sys.exit(1)
|
||||
|
||||
skill_path = sys.argv[1]
|
||||
output_dir = sys.argv[2] if len(sys.argv) > 2 else None
|
||||
|
||||
print(f"📦 Packaging skill: {skill_path}")
|
||||
if output_dir:
|
||||
print(f" Output directory: {output_dir}")
|
||||
print()
|
||||
|
||||
result = package_skill(skill_path, output_dir)
|
||||
|
||||
if result:
|
||||
sys.exit(0)
|
||||
else:
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
65
.claude/skills/skill-creator/scripts/quick_validate.py
Executable file
65
.claude/skills/skill-creator/scripts/quick_validate.py
Executable file
@@ -0,0 +1,65 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Quick validation script for skills - minimal version
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
def validate_skill(skill_path):
|
||||
"""Basic validation of a skill"""
|
||||
skill_path = Path(skill_path)
|
||||
|
||||
# Check SKILL.md exists
|
||||
skill_md = skill_path / 'SKILL.md'
|
||||
if not skill_md.exists():
|
||||
return False, "SKILL.md not found"
|
||||
|
||||
# Read and validate frontmatter
|
||||
content = skill_md.read_text()
|
||||
if not content.startswith('---'):
|
||||
return False, "No YAML frontmatter found"
|
||||
|
||||
# Extract frontmatter
|
||||
match = re.match(r'^---\n(.*?)\n---', content, re.DOTALL)
|
||||
if not match:
|
||||
return False, "Invalid frontmatter format"
|
||||
|
||||
frontmatter = match.group(1)
|
||||
|
||||
# Check required fields
|
||||
if 'name:' not in frontmatter:
|
||||
return False, "Missing 'name' in frontmatter"
|
||||
if 'description:' not in frontmatter:
|
||||
return False, "Missing 'description' in frontmatter"
|
||||
|
||||
# Extract name for validation
|
||||
name_match = re.search(r'name:\s*(.+)', frontmatter)
|
||||
if name_match:
|
||||
name = name_match.group(1).strip()
|
||||
# Check naming convention (hyphen-case: lowercase with hyphens)
|
||||
if not re.match(r'^[a-z0-9-]+$', name):
|
||||
return False, f"Name '{name}' should be hyphen-case (lowercase letters, digits, and hyphens only)"
|
||||
if name.startswith('-') or name.endswith('-') or '--' in name:
|
||||
return False, f"Name '{name}' cannot start/end with hyphen or contain consecutive hyphens"
|
||||
|
||||
# Extract and validate description
|
||||
desc_match = re.search(r'description:\s*(.+)', frontmatter)
|
||||
if desc_match:
|
||||
description = desc_match.group(1).strip()
|
||||
# Check for angle brackets
|
||||
if '<' in description or '>' in description:
|
||||
return False, "Description cannot contain angle brackets (< or >)"
|
||||
|
||||
return True, "Skill is valid!"
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) != 2:
|
||||
print("Usage: python quick_validate.py <skill_directory>")
|
||||
sys.exit(1)
|
||||
|
||||
valid, message = validate_skill(sys.argv[1])
|
||||
print(message)
|
||||
sys.exit(0 if valid else 1)
|
||||
212
.claude/skills/standalone-component-migrator/SKILL.md
Normal file
212
.claude/skills/standalone-component-migrator/SKILL.md
Normal file
@@ -0,0 +1,212 @@
|
||||
---
|
||||
name: standalone-component-migrator
|
||||
description: This skill should be used when converting Angular NgModule-based components to standalone architecture. It handles dependency analysis, template scanning, route refactoring, and test updates. Use this skill when the user requests component migration to standalone, mentions "convert to standalone", or wants to modernize Angular components to the latest patterns.
|
||||
---
|
||||
|
||||
# Standalone Component Migrator
|
||||
|
||||
## Overview
|
||||
|
||||
Automate the conversion of Angular components from NgModule-based architecture to standalone components with explicit imports. This skill analyzes component dependencies, updates routing configurations, migrates tests, and optionally converts to modern Angular control flow syntax (@if, @for, @switch).
|
||||
|
||||
## When to Use This Skill
|
||||
|
||||
Invoke this skill when:
|
||||
- User requests component conversion to standalone
|
||||
- User mentions "migrate to standalone" or "modernize component"
|
||||
- User wants to remove NgModule declarations
|
||||
- User references Angular's standalone component architecture
|
||||
|
||||
## Migration Workflow
|
||||
|
||||
### Step 1: Analyze Component Dependencies
|
||||
|
||||
1. **Read Component File**
|
||||
- Identify component decorator configuration
|
||||
- Note selector, template path, style paths
|
||||
- Check if already standalone
|
||||
|
||||
2. **Analyze Template**
|
||||
- Read template file (HTML)
|
||||
- Scan for directives: `*ngIf`, `*ngFor`, `*ngSwitch` → requires CommonModule
|
||||
- Scan for forms: `ngModel`, `formControl` → requires FormsModule or ReactiveFormsModule
|
||||
- Scan for built-in pipes: `async`, `date`, `json` → CommonModule
|
||||
- Scan for custom components: identify all component selectors
|
||||
- Scan for router directives: `routerLink`, `router-outlet` → RouterModule
|
||||
|
||||
3. **Find Parent NgModule**
|
||||
- Search for NgModule that declares this component
|
||||
- Read NgModule file to understand current imports
|
||||
|
||||
### Step 2: Convert Component to Standalone
|
||||
|
||||
Add `standalone: true` and explicit imports array:
|
||||
|
||||
```typescript
|
||||
// BEFORE
|
||||
import { Component } from '@angular/core';
|
||||
|
||||
@Component({
|
||||
selector: 'app-my-component',
|
||||
templateUrl: './my-component.component.html'
|
||||
})
|
||||
export class MyComponent { }
|
||||
|
||||
// AFTER
|
||||
import { Component } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { RouterModule } from '@angular/router';
|
||||
import { ChildComponent } from './child.component';
|
||||
import { CustomPipe } from '@isa/utils/pipes';
|
||||
|
||||
@Component({
|
||||
selector: 'app-my-component',
|
||||
standalone: true,
|
||||
imports: [
|
||||
CommonModule,
|
||||
FormsModule,
|
||||
RouterModule,
|
||||
ChildComponent,
|
||||
CustomPipe
|
||||
],
|
||||
templateUrl: './my-component.component.html'
|
||||
})
|
||||
export class MyComponent { }
|
||||
```
|
||||
|
||||
### Step 3: Update Parent NgModule
|
||||
|
||||
Remove component from declarations, add to imports if exported:
|
||||
|
||||
```typescript
|
||||
// BEFORE
|
||||
@NgModule({
|
||||
declarations: [MyComponent, OtherComponent],
|
||||
imports: [CommonModule],
|
||||
exports: [MyComponent]
|
||||
})
|
||||
|
||||
// AFTER
|
||||
@NgModule({
|
||||
declarations: [OtherComponent],
|
||||
imports: [CommonModule, MyComponent], // Import standalone component
|
||||
exports: [MyComponent]
|
||||
})
|
||||
```
|
||||
|
||||
If NgModule becomes empty (no declarations), consider removing it entirely.
|
||||
|
||||
### Step 4: Update Routes (if applicable)
|
||||
|
||||
Convert to lazy-loaded standalone component:
|
||||
|
||||
```typescript
|
||||
// BEFORE
|
||||
const routes: Routes = [
|
||||
{ path: 'feature', component: MyComponent }
|
||||
];
|
||||
|
||||
// AFTER (lazy loading)
|
||||
const routes: Routes = [
|
||||
{
|
||||
path: 'feature',
|
||||
loadComponent: () => import('./my-component.component').then(m => m.MyComponent)
|
||||
}
|
||||
];
|
||||
```
|
||||
|
||||
### Step 5: Update Tests
|
||||
|
||||
Convert test configuration:
|
||||
|
||||
```typescript
|
||||
// BEFORE
|
||||
TestBed.configureTestingModule({
|
||||
declarations: [MyComponent],
|
||||
imports: [CommonModule, FormsModule]
|
||||
});
|
||||
|
||||
// AFTER
|
||||
TestBed.configureTestingModule({
|
||||
imports: [MyComponent] // Component imports its own dependencies
|
||||
});
|
||||
```
|
||||
|
||||
### Step 6: Optional - Migrate to Modern Control Flow
|
||||
|
||||
If requested, convert to new Angular control flow syntax:
|
||||
|
||||
```typescript
|
||||
// OLD
|
||||
<div *ngIf="condition">Content</div>
|
||||
<div *ngFor="let item of items; trackBy: trackById">{{ item.name }}</div>
|
||||
<div [ngSwitch]="value">
|
||||
<div *ngSwitchCase="'a'">A</div>
|
||||
<div *ngSwitchDefault>Default</div>
|
||||
</div>
|
||||
|
||||
// NEW
|
||||
@if (condition) {
|
||||
<div>Content</div>
|
||||
}
|
||||
@for (item of items; track item.id) {
|
||||
<div>{{ item.name }}</div>
|
||||
}
|
||||
@switch (value) {
|
||||
@case ('a') { <div>A</div> }
|
||||
@default { <div>Default</div> }
|
||||
}
|
||||
```
|
||||
|
||||
### Step 7: Validate and Test
|
||||
|
||||
1. **Compile Check**
|
||||
```bash
|
||||
npx tsc --noEmit
|
||||
```
|
||||
|
||||
2. **Run Tests**
|
||||
```bash
|
||||
npx nx test [library-name] --skip-nx-cache
|
||||
```
|
||||
|
||||
3. **Lint Check**
|
||||
```bash
|
||||
npx nx lint [library-name]
|
||||
```
|
||||
|
||||
4. **Verify Application Runs**
|
||||
```bash
|
||||
npm start
|
||||
```
|
||||
|
||||
## Common Import Patterns
|
||||
|
||||
| Template Usage | Required Import |
|
||||
|---------------|-----------------|
|
||||
| `*ngIf`, `*ngFor`, `*ngSwitch` | `CommonModule` |
|
||||
| `ngModel` | `FormsModule` |
|
||||
| `formControl`, `formGroup` | `ReactiveFormsModule` |
|
||||
| `routerLink`, `router-outlet` | `RouterModule` |
|
||||
| `async`, `date`, `json` pipes | `CommonModule` |
|
||||
| Custom components | Direct component import |
|
||||
| Custom pipes | Direct pipe import |
|
||||
|
||||
## Error Handling
|
||||
|
||||
**Issue: Circular dependencies**
|
||||
- Extract shared interfaces to util library
|
||||
- Use dependency injection for services
|
||||
- Avoid component A importing component B when B imports A
|
||||
|
||||
**Issue: Missing imports causing template errors**
|
||||
- Check browser console for specific errors
|
||||
- Verify all template dependencies are in imports array
|
||||
- Use Angular Language Service in IDE for hints
|
||||
|
||||
## References
|
||||
|
||||
- Angular Standalone Components: https://angular.dev/guide/components/importing
|
||||
- Modern Control Flow: https://angular.dev/guide/templates/control-flow
|
||||
- CLAUDE.md Component Architecture section
|
||||
134
.claude/skills/swagger-sync-manager/SKILL.md
Normal file
134
.claude/skills/swagger-sync-manager/SKILL.md
Normal file
@@ -0,0 +1,134 @@
|
||||
---
|
||||
name: swagger-sync-manager
|
||||
description: This skill should be used when regenerating Swagger/OpenAPI TypeScript API clients in the ISA-Frontend monorepo. It handles generation of all 10 API clients (or specific ones), Unicode cleanup, breaking change detection, TypeScript validation, and affected test execution. Use this skill when the user requests API sync, mentions "regenerate swagger", or indicates backend API changes.
|
||||
---
|
||||
|
||||
# Swagger Sync Manager
|
||||
|
||||
## Overview
|
||||
|
||||
Automate the regeneration of TypeScript API clients from Swagger/OpenAPI specifications. Handles 10 API clients with automatic post-processing, breaking change detection, impact analysis, and validation.
|
||||
|
||||
## When to Use This Skill
|
||||
|
||||
Invoke when user requests:
|
||||
- API client regeneration
|
||||
- "sync swagger" or "update API clients"
|
||||
- Backend API changes need frontend updates
|
||||
|
||||
## Available APIs
|
||||
|
||||
availability-api, cat-search-api, checkout-api, crm-api, eis-api, inventory-api, isa-api, oms-api, print-api, wws-api
|
||||
|
||||
## Sync Workflow
|
||||
|
||||
### Step 1: Pre-Generation Check
|
||||
|
||||
```bash
|
||||
# Check uncommitted changes
|
||||
git status generated/swagger/
|
||||
```
|
||||
|
||||
If changes exist, warn user and ask to proceed.
|
||||
|
||||
### Step 2: Backup Current State (Optional)
|
||||
|
||||
```bash
|
||||
cp -r generated/swagger generated/swagger.backup.$(date +%s)
|
||||
```
|
||||
|
||||
### Step 3: Run Generation
|
||||
|
||||
```bash
|
||||
# All APIs
|
||||
npm run generate:swagger
|
||||
|
||||
# Specific API (if api-name provided)
|
||||
npm run generate:swagger:[api-name]
|
||||
```
|
||||
|
||||
### Step 4: Verify Unicode Cleanup
|
||||
|
||||
Check `tools/fix-files.js` executed. Scan for remaining Unicode issues:
|
||||
|
||||
```bash
|
||||
grep -r "\\\\u00" generated/swagger/ || echo "✅ No Unicode issues"
|
||||
```
|
||||
|
||||
### Step 5: Detect Breaking Changes
|
||||
|
||||
For each modified API:
|
||||
|
||||
```bash
|
||||
git diff generated/swagger/[api-name]/
|
||||
```
|
||||
|
||||
Identify:
|
||||
- 🔴 Removed properties
|
||||
- 🔴 Changed types
|
||||
- 🔴 Removed endpoints
|
||||
- ✅ Added properties (safe)
|
||||
- ✅ New endpoints (safe)
|
||||
|
||||
### Step 6: Impact Analysis
|
||||
|
||||
Use `Explore` agent to find affected files:
|
||||
- Search for imports from `@generated/swagger/[api-name]`
|
||||
- List data-access services using changed APIs
|
||||
- Estimate refactoring scope
|
||||
|
||||
### Step 7: Validate
|
||||
|
||||
```bash
|
||||
# TypeScript compilation
|
||||
npx tsc --noEmit
|
||||
|
||||
# Run affected tests
|
||||
npx nx affected:test --skip-nx-cache
|
||||
|
||||
# Lint affected
|
||||
npx nx affected:lint
|
||||
```
|
||||
|
||||
### Step 8: Generate Report
|
||||
|
||||
```
|
||||
Swagger Sync Complete
|
||||
=====================
|
||||
|
||||
APIs Regenerated: [all | specific]
|
||||
Files Changed: XX
|
||||
Breaking Changes: XX
|
||||
|
||||
🔴 Breaking Changes
|
||||
-------------------
|
||||
- [API]: [Property removed/type changed]
|
||||
- Affected files: [list]
|
||||
|
||||
✅ Compatible Changes
|
||||
---------------------
|
||||
- [API]: [New properties/endpoints]
|
||||
|
||||
📊 Validation
|
||||
-------------
|
||||
TypeScript: ✅/❌
|
||||
Tests: XX/XX passing
|
||||
Lint: ✅/❌
|
||||
|
||||
💡 Next Steps
|
||||
-------------
|
||||
[Fix breaking changes / Deploy]
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
**Generation fails**: Check OpenAPI spec URLs in package.json
|
||||
|
||||
**Unicode cleanup fails**: Run `node tools/fix-files.js` manually
|
||||
|
||||
**TypeScript errors**: Review breaking changes, update affected services
|
||||
|
||||
## References
|
||||
|
||||
- CLAUDE.md API Integration section
|
||||
- package.json swagger generation scripts
|
||||
344
.claude/skills/test-migration-specialist/SKILL.md
Normal file
344
.claude/skills/test-migration-specialist/SKILL.md
Normal file
@@ -0,0 +1,344 @@
|
||||
---
|
||||
name: test-migration-specialist
|
||||
description: This skill should be used when migrating Angular libraries from Jest + Spectator to Vitest + Angular Testing Utilities. It handles test configuration updates, test file refactoring, mock pattern conversion, and validation. Use this skill when the user requests test framework migration, specifically for the 40 remaining Jest-based libraries in the ISA-Frontend monorepo.
|
||||
---
|
||||
|
||||
# Test Migration Specialist
|
||||
|
||||
## Overview
|
||||
|
||||
Automate the migration of Angular library tests from Jest + Spectator to Vitest + Angular Testing Utilities. This skill handles the complete migration workflow including configuration updates, test file refactoring, dependency management, and validation.
|
||||
|
||||
**Current Migration Status**: 40 libraries use Jest (65.6%), 21 libraries use Vitest (34.4%)
|
||||
|
||||
## When to Use This Skill
|
||||
|
||||
Invoke this skill when:
|
||||
- User requests test migration for a specific library
|
||||
- User mentions "migrate tests" or "Jest to Vitest"
|
||||
- User wants to update test framework for a library
|
||||
- User references the 40 remaining libraries to migrate
|
||||
|
||||
## Migration Workflow
|
||||
|
||||
### Step 1: Pre-Migration Analysis
|
||||
|
||||
Before making any changes, analyze the current state:
|
||||
|
||||
1. **Read Testing Guidelines**
|
||||
- Use `docs-researcher` agent to read `docs/guidelines/testing.md`
|
||||
- Understand migration patterns and best practices
|
||||
- Note JUnit and Cobertura configuration requirements
|
||||
|
||||
2. **Analyze Library Structure**
|
||||
- Read `libs/[path]/project.json` to identify current test executor
|
||||
- Count test files using Glob: `**/*.spec.ts`
|
||||
- Scan for Spectator usage patterns using Grep: `createComponentFactory|createServiceFactory|Spectator`
|
||||
- Identify complex mocking scenarios (ng-mocks, jest.mock patterns)
|
||||
|
||||
3. **Determine Library Depth**
|
||||
- Calculate directory levels from workspace root
|
||||
- This affects relative paths in vite.config.mts (../../../ vs ../../../../)
|
||||
|
||||
### Step 2: Update Test Configuration
|
||||
|
||||
Update the library's test configuration to use Vitest:
|
||||
|
||||
1. **Update project.json**
|
||||
Replace Jest executor with Vitest:
|
||||
```json
|
||||
{
|
||||
"test": {
|
||||
"executor": "@nx/vite:test",
|
||||
"options": {
|
||||
"configFile": "vite.config.mts"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
2. **Create vite.config.mts**
|
||||
Create configuration with JUnit and Cobertura reporters:
|
||||
```typescript
|
||||
/// <reference types='vitest' />
|
||||
import { defineConfig } from 'vite';
|
||||
import angular from '@analogjs/vite-plugin-angular';
|
||||
import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin';
|
||||
import { nxCopyAssetsPlugin } from '@nx/vite/plugins/nx-copy-assets.plugin';
|
||||
|
||||
export default
|
||||
// @ts-expect-error - Vitest reporter tuple types have complex inference issues
|
||||
defineConfig(() => ({
|
||||
root: __dirname,
|
||||
cacheDir: '../../../node_modules/.vite/libs/[path]',
|
||||
plugins: [angular(), nxViteTsPaths(), nxCopyAssetsPlugin(['*.md'])],
|
||||
test: {
|
||||
watch: false,
|
||||
globals: true,
|
||||
environment: 'jsdom',
|
||||
include: ['{src,tests}/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
|
||||
setupFiles: ['src/test-setup.ts'],
|
||||
reporters: [
|
||||
'default',
|
||||
['junit', { outputFile: '../../../testresults/junit-[library-name].xml' }],
|
||||
],
|
||||
coverage: {
|
||||
reportsDirectory: '../../../coverage/libs/[path]',
|
||||
provider: 'v8' as const,
|
||||
reporter: ['text', 'cobertura'],
|
||||
},
|
||||
},
|
||||
}));
|
||||
```
|
||||
|
||||
**Critical**: Adjust `../../../` depth based on library location
|
||||
|
||||
### Step 3: Migrate Test Files
|
||||
|
||||
For each `.spec.ts` file, perform these conversions:
|
||||
|
||||
1. **Update Imports**
|
||||
```typescript
|
||||
// REMOVE
|
||||
import { createComponentFactory, Spectator } from '@ngneat/spectator/jest';
|
||||
|
||||
// ADD
|
||||
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
```
|
||||
|
||||
2. **Convert Component Tests**
|
||||
```typescript
|
||||
// OLD (Spectator)
|
||||
const createComponent = createComponentFactory({
|
||||
component: MyComponent,
|
||||
imports: [CommonModule],
|
||||
mocks: [MyService]
|
||||
});
|
||||
|
||||
let spectator: Spectator<MyComponent>;
|
||||
beforeEach(() => spectator = createComponent());
|
||||
|
||||
it('should display title', () => {
|
||||
spectator.setInput('title', 'Test');
|
||||
expect(spectator.query('h1')).toHaveText('Test');
|
||||
});
|
||||
|
||||
// NEW (Angular Testing Utilities)
|
||||
describe('MyComponent', () => {
|
||||
let fixture: ComponentFixture<MyComponent>;
|
||||
let component: MyComponent;
|
||||
|
||||
beforeEach(async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [MyComponent, CommonModule],
|
||||
providers: [{ provide: MyService, useValue: mockService }]
|
||||
}).compileComponents();
|
||||
|
||||
fixture = TestBed.createComponent(MyComponent);
|
||||
component = fixture.componentInstance;
|
||||
});
|
||||
|
||||
it('should display title', () => {
|
||||
component.title = 'Test';
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('h1').textContent).toContain('Test');
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
3. **Convert Service Tests**
|
||||
```typescript
|
||||
// OLD (Spectator)
|
||||
const createService = createServiceFactory({
|
||||
service: MyService,
|
||||
mocks: [HttpClient]
|
||||
});
|
||||
|
||||
// NEW (Angular Testing Utilities)
|
||||
describe('MyService', () => {
|
||||
let service: MyService;
|
||||
let httpMock: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
imports: [HttpClientTestingModule],
|
||||
providers: [MyService]
|
||||
});
|
||||
|
||||
service = TestBed.inject(MyService);
|
||||
httpMock = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpMock.verify();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
4. **Update Mock Patterns**
|
||||
- Replace `jest.fn()` → `vi.fn()`
|
||||
- Replace `jest.spyOn()` → `vi.spyOn()`
|
||||
- Replace `jest.mock()` → `vi.mock()`
|
||||
- For complex mocks, use `ng-mocks` library if needed
|
||||
|
||||
5. **Update Matchers**
|
||||
- Replace Spectator matchers (`toHaveText`, `toExist`) with standard Jest/Vitest matchers
|
||||
- Use `expect().toBeTruthy()`, `expect().toContain()`, etc.
|
||||
|
||||
### Step 4: Verify E2E Attributes
|
||||
|
||||
Check component templates for E2E testing attributes:
|
||||
|
||||
1. **Scan Templates**
|
||||
Use Grep to find templates: `**/*.html`
|
||||
|
||||
2. **Validate Attributes**
|
||||
Ensure interactive elements have:
|
||||
- `data-what`: Semantic description (e.g., "submit-button")
|
||||
- `data-which`: Unique identifier (e.g., "form-primary")
|
||||
- Dynamic `data-*` for list items: `[attr.data-item-id]="item.id"`
|
||||
|
||||
3. **Add Missing Attributes**
|
||||
If missing, add them to components. See `dev:add-e2e-attrs` command or use that skill.
|
||||
|
||||
### Step 5: Run Tests and Validate
|
||||
|
||||
Execute tests to verify migration:
|
||||
|
||||
1. **Run Tests**
|
||||
```bash
|
||||
npx nx test [library-name] --skip-nx-cache
|
||||
```
|
||||
|
||||
2. **Run with Coverage**
|
||||
```bash
|
||||
npx nx test [library-name] --coverage.enabled=true --skip-nx-cache
|
||||
```
|
||||
|
||||
3. **Verify Output Files**
|
||||
Check that CI/CD integration files are created:
|
||||
- JUnit XML: `testresults/junit-[library-name].xml`
|
||||
- Cobertura XML: `coverage/libs/[path]/cobertura-coverage.xml`
|
||||
|
||||
4. **Address Failures**
|
||||
If tests fail:
|
||||
- Review test conversion (common issues: missing fixture.detectChanges(), incorrect selectors)
|
||||
- Check mock configurations
|
||||
- Verify imports are correct
|
||||
- Ensure async tests use proper patterns
|
||||
|
||||
### Step 6: Clean Up
|
||||
|
||||
Remove legacy configurations:
|
||||
|
||||
1. **Remove Jest Files**
|
||||
- Delete `jest.config.ts` or `jest.config.js` if present
|
||||
- Remove Jest-specific setup files
|
||||
|
||||
2. **Update Dependencies**
|
||||
- Note if Spectator can be removed (check if other libs still use it)
|
||||
- Note if Jest can be removed (check if other libs still use it)
|
||||
- Don't actually remove from package.json unless all libs migrated
|
||||
|
||||
3. **Update Documentation**
|
||||
Update library README.md with new test commands:
|
||||
```markdown
|
||||
## Testing
|
||||
|
||||
This library uses Vitest + Angular Testing Utilities.
|
||||
|
||||
```bash
|
||||
# Run tests
|
||||
npx nx test [library-name] --skip-nx-cache
|
||||
|
||||
# Run with coverage
|
||||
npx nx test [library-name] --coverage.enabled=true --skip-nx-cache
|
||||
```
|
||||
```
|
||||
|
||||
### Step 7: Generate Migration Report
|
||||
|
||||
Provide comprehensive migration summary:
|
||||
|
||||
```
|
||||
Test Migration Complete
|
||||
=======================
|
||||
|
||||
Library: [library-name]
|
||||
Framework: Jest + Spectator → Vitest + Angular Testing Utilities
|
||||
|
||||
📊 Migration Statistics
|
||||
-----------------------
|
||||
Test files migrated: XX
|
||||
Component tests: XX
|
||||
Service tests: XX
|
||||
Total test cases: XX
|
||||
|
||||
✅ Test Results
|
||||
---------------
|
||||
Passing: XX/XX (100%)
|
||||
Coverage: XX%
|
||||
|
||||
📝 Configuration
|
||||
----------------
|
||||
- project.json: ✅ Updated to @nx/vite:test
|
||||
- vite.config.mts: ✅ Created with JUnit + Cobertura
|
||||
- E2E attributes: ✅ Validated
|
||||
|
||||
📁 CI/CD Integration
|
||||
--------------------
|
||||
- JUnit XML: ✅ testresults/junit-[name].xml
|
||||
- Cobertura XML: ✅ coverage/libs/[path]/cobertura-coverage.xml
|
||||
|
||||
🧹 Cleanup
|
||||
----------
|
||||
- Jest config removed: ✅
|
||||
- README updated: ✅
|
||||
|
||||
💡 Next Steps
|
||||
-------------
|
||||
1. Verify tests in CI/CD pipeline
|
||||
2. Monitor for any edge cases
|
||||
3. Consider migrating related libraries
|
||||
|
||||
📚 Remaining Libraries
|
||||
----------------------
|
||||
Jest libraries remaining: XX/40
|
||||
Progress: XX% complete
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
### Common Migration Issues
|
||||
|
||||
**Issue 1: Tests fail after migration**
|
||||
- Check `fixture.detectChanges()` is called after setting inputs
|
||||
- Verify async tests use `async/await` properly
|
||||
- Check component imports are correct (standalone components)
|
||||
|
||||
**Issue 2: Mocks not working**
|
||||
- Verify `vi.fn()` syntax is correct
|
||||
- Check providers array in TestBed configuration
|
||||
- For complex mocks, consider using `ng-mocks`
|
||||
|
||||
**Issue 3: Coverage files not generated**
|
||||
- Verify path depth in vite.config.mts matches library location
|
||||
- Check reporters array includes `'cobertura'`
|
||||
- Ensure `provider: 'v8'` is set
|
||||
|
||||
**Issue 4: Type errors in vite.config.mts**
|
||||
- Add `// @ts-expect-error` comment before `defineConfig()`
|
||||
- This is expected due to Vitest reporter type complexity
|
||||
|
||||
## References
|
||||
|
||||
Use `docs-researcher` agent to access:
|
||||
- `docs/guidelines/testing.md` - Comprehensive migration guide with examples
|
||||
- `CLAUDE.md` - Testing Framework section for project conventions
|
||||
|
||||
**Key Documentation Sections:**
|
||||
- Vitest Configuration with JUnit and Cobertura
|
||||
- Angular Testing Utilities examples
|
||||
- Migration patterns and best practices
|
||||
- E2E attribute requirements
|
||||
199
.claude/skills/type-safety-engineer/SKILL.md
Normal file
199
.claude/skills/type-safety-engineer/SKILL.md
Normal file
@@ -0,0 +1,199 @@
|
||||
---
|
||||
name: type-safety-engineer
|
||||
description: This skill should be used when improving TypeScript type safety by removing `any` types, adding Zod schemas for runtime validation, creating type guards, and strengthening strictness. Use this skill when the user wants to enhance type safety, mentions "fix any types", "add Zod validation", or requests type improvements for better code quality.
|
||||
---
|
||||
|
||||
# Type Safety Engineer
|
||||
|
||||
## Overview
|
||||
|
||||
Enhance TypeScript type safety by eliminating `any` types, adding Zod schemas for runtime validation, creating type guards, and strengthening compiler strictness.
|
||||
|
||||
## When to Use This Skill
|
||||
|
||||
Invoke when user wants to:
|
||||
- Remove `any` types
|
||||
- Add runtime validation with Zod
|
||||
- Improve type safety
|
||||
- Mentioned "type safety" or "Zod schemas"
|
||||
|
||||
## Type Safety Workflow
|
||||
|
||||
### Step 1: Scan for Issues
|
||||
|
||||
```bash
|
||||
# Find explicit any
|
||||
grep -r ": any" libs/ --include="*.ts" | grep -v ".spec.ts"
|
||||
|
||||
# Find functions without return types
|
||||
grep -r "^.*function.*{$" libs/ --include="*.ts" | grep -v ": "
|
||||
|
||||
# TypeScript strict mode check
|
||||
npx tsc --noEmit --strict
|
||||
```
|
||||
|
||||
### Step 2: Categorize Issues
|
||||
|
||||
**🔴 Critical:**
|
||||
- `any` in API response handling
|
||||
- `any` in service methods
|
||||
- `any` in store state types
|
||||
|
||||
**⚠️ Important:**
|
||||
- Missing return types
|
||||
- Untyped parameters
|
||||
- Weak types (`object`, `Function`)
|
||||
|
||||
**ℹ️ Moderate:**
|
||||
- `any` in test files
|
||||
- Loose array types
|
||||
|
||||
### Step 3: Add Zod Schemas for API Responses
|
||||
|
||||
```typescript
|
||||
import { z } from 'zod';
|
||||
|
||||
// Define schema
|
||||
const OrderItemSchema = z.object({
|
||||
productId: z.string().uuid(),
|
||||
quantity: z.number().int().positive(),
|
||||
price: z.number().positive()
|
||||
});
|
||||
|
||||
const OrderResponseSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
status: z.enum(['pending', 'confirmed', 'shipped']),
|
||||
items: z.array(OrderItemSchema),
|
||||
createdAt: z.string().datetime()
|
||||
});
|
||||
|
||||
// Infer TypeScript type
|
||||
type OrderResponse = z.infer<typeof OrderResponseSchema>;
|
||||
|
||||
// Runtime validation
|
||||
const order = OrderResponseSchema.parse(apiResponse);
|
||||
```
|
||||
|
||||
### Step 4: Replace `any` with Specific Types
|
||||
|
||||
**Pattern 1: Unknown + Type Guards**
|
||||
```typescript
|
||||
// BEFORE
|
||||
function processData(data: any) {
|
||||
return data.value;
|
||||
}
|
||||
|
||||
// AFTER
|
||||
function processData(data: unknown): string {
|
||||
if (!isValidData(data)) {
|
||||
throw new Error('Invalid data');
|
||||
}
|
||||
return data.value;
|
||||
}
|
||||
|
||||
function isValidData(data: unknown): data is { value: string } {
|
||||
return typeof data === 'object' && data !== null && 'value' in data;
|
||||
}
|
||||
```
|
||||
|
||||
**Pattern 2: Generic Types**
|
||||
```typescript
|
||||
// BEFORE
|
||||
function findById(items: any[], id: string): any {
|
||||
return items.find(item => item.id === id);
|
||||
}
|
||||
|
||||
// AFTER
|
||||
function findById<T extends { id: string }>(items: T[], id: string): T | undefined {
|
||||
return items.find(item => item.id === id);
|
||||
}
|
||||
```
|
||||
|
||||
### Step 5: Add Type Guards for API Data
|
||||
|
||||
```typescript
|
||||
export function isOrderResponse(data: unknown): data is OrderResponse {
|
||||
try {
|
||||
OrderResponseSchema.parse(data);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Use in service
|
||||
getOrder(id: string): Observable<OrderResponse> {
|
||||
return this.http.get(`/api/orders/${id}`).pipe(
|
||||
map(response => {
|
||||
if (!isOrderResponse(response)) {
|
||||
throw new Error('Invalid API response');
|
||||
}
|
||||
return response;
|
||||
})
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Step 6: Validate Changes
|
||||
|
||||
```bash
|
||||
npx tsc --noEmit --strict
|
||||
npx nx affected:test --skip-nx-cache
|
||||
npx nx affected:lint
|
||||
```
|
||||
|
||||
### Step 7: Generate Report
|
||||
|
||||
```
|
||||
Type Safety Improvements
|
||||
========================
|
||||
|
||||
Path: [analyzed path]
|
||||
|
||||
🔍 Issues Found
|
||||
---------------
|
||||
`any` usages: XX → 0
|
||||
Missing return types: XX → 0
|
||||
Untyped parameters: XX → 0
|
||||
|
||||
✅ Improvements
|
||||
---------------
|
||||
- Added Zod schemas: XX
|
||||
- Created type guards: XX
|
||||
- Fixed `any` types: XX
|
||||
- Added return types: XX
|
||||
|
||||
📈 Type Safety Score
|
||||
--------------------
|
||||
Before: XX%
|
||||
After: XX% (+XX%)
|
||||
|
||||
💡 Recommendations
|
||||
------------------
|
||||
1. Enable stricter TypeScript options
|
||||
2. Add validation to remaining APIs
|
||||
```
|
||||
|
||||
## Common Patterns
|
||||
|
||||
**API Response Validation:**
|
||||
```typescript
|
||||
const schema = z.object({...});
|
||||
type Type = z.infer<typeof schema>;
|
||||
|
||||
return this.http.get<unknown>(url).pipe(
|
||||
map(response => schema.parse(response))
|
||||
);
|
||||
```
|
||||
|
||||
**Event Handlers:**
|
||||
```typescript
|
||||
// BEFORE: onClick(event: any)
|
||||
// AFTER: onClick(event: MouseEvent)
|
||||
```
|
||||
|
||||
## References
|
||||
|
||||
- Use `docs-researcher` for latest Zod documentation
|
||||
- Zod: https://zod.dev
|
||||
- TypeScript strict mode: https://www.typescriptlang.org/tsconfig#strict
|
||||
6
.gitignore
vendored
6
.gitignore
vendored
@@ -58,7 +58,11 @@ libs/swagger/src/lib/*
|
||||
.nx/cache
|
||||
.nx/workspace-data
|
||||
.angular
|
||||
.claude
|
||||
# Claude configuration
|
||||
.claude/*
|
||||
!.claude/agents
|
||||
!.claude/commands
|
||||
!.claude/skills
|
||||
|
||||
|
||||
storybook-static
|
||||
|
||||
5
.vscode/settings.json
vendored
5
.vscode/settings.json
vendored
@@ -90,5 +90,8 @@
|
||||
"cursor-global": true,
|
||||
"cursor-workspace": true
|
||||
},
|
||||
"chat.mcp.access": "all"
|
||||
"chat.mcp.access": "all",
|
||||
"typescript.inlayHints.parameterTypes.enabled": true,
|
||||
"typescript.inlayHints.variableTypes.enabled": true,
|
||||
"editor.hover.delay": 100
|
||||
}
|
||||
|
||||
568
CLAUDE.md
568
CLAUDE.md
@@ -1,6 +1,20 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||
> **Last Updated:** 2025-10-22
|
||||
> **Angular Version:** 20.1.2
|
||||
> **Nx Version:** 21.3.2
|
||||
> **Node.js:** ≥22.0.0
|
||||
> **npm:** ≥10.0.0
|
||||
|
||||
## 🔴 CRITICAL: Mandatory Agent Usage
|
||||
|
||||
**You MUST use these subagents for ALL research tasks:**
|
||||
- **`docs-researcher`**: For ALL documentation (packages, libraries, READMEs)
|
||||
- **`docs-researcher-advanced`**: Auto-escalate when docs-researcher fails
|
||||
- **`Explore`**: For ALL code pattern searches and multi-file analysis
|
||||
- **Direct tools (Read/Bash)**: ONLY for single specific files or commands
|
||||
|
||||
**Violations of this rule degrade performance and context quality. NO EXCEPTIONS.**
|
||||
|
||||
## Project Overview
|
||||
|
||||
@@ -28,7 +42,7 @@ This is a sophisticated Angular 20.1.2 monorepo managed by Nx 21.3.2. The main a
|
||||
- **Standalone Components**: All new components use Angular standalone architecture with explicit imports
|
||||
- **Feature Libraries**: Domain features organized as separate libraries (e.g., `oms-feature-return-search`, `remission-feature-remission-list`)
|
||||
- **Data Access Layer**: Separate data-access libraries for each domain with NgRx Signals stores
|
||||
- **Shared UI Components**: 15 dedicated UI component libraries with design system integration
|
||||
- **Shared UI Components**: 17 dedicated UI component libraries with design system integration
|
||||
- **Generated API Clients**: 10 auto-generated Swagger/OpenAPI clients with post-processing pipeline
|
||||
- **Path Aliases**: Comprehensive TypeScript path mapping (`@isa/domain/layer/feature`)
|
||||
- **Component Prefixes**: Domain-specific prefixes (OMS: `oms-feature-*`, Remission: `remi-*`, UI: `ui-*`)
|
||||
@@ -36,109 +50,84 @@ This is a sophisticated Angular 20.1.2 monorepo managed by Nx 21.3.2. The main a
|
||||
|
||||
## Common Development Commands
|
||||
|
||||
### Build Commands
|
||||
### Essential Commands (Project-Specific)
|
||||
```bash
|
||||
# Build the main application (development) - default configuration
|
||||
# Start development server with SSL (required for authentication flows)
|
||||
npm start
|
||||
|
||||
# Run tests for all libraries (excludes main app)
|
||||
npm test
|
||||
|
||||
# Build for development
|
||||
npm run build
|
||||
# Or: npx nx build isa-app --configuration=development
|
||||
|
||||
# Build for production
|
||||
npm run build-prod
|
||||
# Or: npx nx build isa-app --configuration=production
|
||||
|
||||
# Build without using Nx cache (for fresh builds)
|
||||
npx nx build isa-app --skip-nx-cache
|
||||
|
||||
# Serve the application with SSL (development server)
|
||||
npm start
|
||||
# Or: npx nx serve isa-app --ssl
|
||||
```
|
||||
|
||||
### Testing Commands
|
||||
```bash
|
||||
# Run tests for all libraries except the main app (default command)
|
||||
npm test
|
||||
# Or: npx nx run-many -t test --exclude isa-app --skip-nx-cache
|
||||
|
||||
# Run tests for a specific library (always use --skip-nx-cache for fresh results)
|
||||
npx nx run <project-name>:test --skip-nx-cache
|
||||
# Example: npx nx run oms-data-access:test --skip-nx-cache
|
||||
|
||||
# Skip Nx cache entirely (important for ensuring fresh builds/tests)
|
||||
npx nx run <project-name>:test --skip-nx-cache
|
||||
# Or combine with skip-cache: npx nx run <project-name>:test --skip-nx-cache --skip-nx-cache
|
||||
|
||||
# Run a single test file
|
||||
npx nx run <project-name>:test --testFile=<path-to-test-file> --skip-nx-cache
|
||||
|
||||
# Run tests with coverage
|
||||
npx nx run <project-name>:test --code-coverage --skip-nx-cache
|
||||
|
||||
# Run tests in watch mode
|
||||
npx nx run <project-name>:test --watch
|
||||
|
||||
# Run CI tests with coverage (for CI/CD)
|
||||
npm run ci
|
||||
# Or: npx nx run-many -t test --exclude isa-app -c ci
|
||||
```
|
||||
|
||||
### Linting Commands
|
||||
```bash
|
||||
# Lint a specific project
|
||||
npx nx lint <project-name>
|
||||
# Example: npx nx lint remission-data-access
|
||||
|
||||
# Run linting for all projects
|
||||
npx nx run-many -t lint
|
||||
```
|
||||
|
||||
### Other Useful Commands
|
||||
```bash
|
||||
# Generate Swagger API clients (regenerates all API clients)
|
||||
# Regenerate all API clients from Swagger/OpenAPI specs
|
||||
npm run generate:swagger
|
||||
# Or: npx nx run-many -t generate -p tag:generated,swagger
|
||||
|
||||
# Start Storybook for UI component development
|
||||
npm run storybook
|
||||
# Or: npx nx run isa-app:storybook
|
||||
# Regenerate library reference documentation
|
||||
npm run docs:generate
|
||||
|
||||
# Format code with Prettier
|
||||
npm run prettier
|
||||
|
||||
# Format staged files only (used in pre-commit hooks)
|
||||
# Format only staged files (pre-commit hook)
|
||||
npm run pretty-quick
|
||||
|
||||
# List all projects in the workspace
|
||||
npx nx list
|
||||
# Run CI tests with coverage
|
||||
npm run ci
|
||||
```
|
||||
|
||||
# Show project dependencies graph (visual)
|
||||
### Standard Nx Commands
|
||||
For complete command reference, see [Nx Documentation](https://nx.dev/reference/commands).
|
||||
|
||||
**Common patterns:**
|
||||
```bash
|
||||
# Test specific library (always use --skip-nx-cache)
|
||||
npx nx test <project-name> --skip-nx-cache
|
||||
|
||||
# Lint a project
|
||||
npx nx lint <project-name>
|
||||
|
||||
# Show project dependencies
|
||||
npx nx graph
|
||||
|
||||
# Run affected tests (based on git changes)
|
||||
npx nx affected:test
|
||||
# Run tests for affected projects (CI/CD)
|
||||
npx nx affected:test --skip-nx-cache
|
||||
```
|
||||
|
||||
**Important:** Always use `--skip-nx-cache` flag when running tests to ensure fresh results.
|
||||
|
||||
## Testing Framework
|
||||
|
||||
> **Last Reviewed:** 2025-10-22
|
||||
> **Status:** Migration in Progress (Jest → Vitest)
|
||||
|
||||
### Current Setup (Migration in Progress)
|
||||
- **Jest**: Used by 40 libraries (76% of codebase) - existing/legacy libraries
|
||||
- **Vitest**: Used by 13 libraries (24% of codebase) - newer libraries and migrations
|
||||
- **Testing Utilities Migration**:
|
||||
- **Angular Testing Utilities** (TestBed, ComponentFixture): Preferred for new tests (25 test files)
|
||||
- **Spectator**: Legacy testing utility for existing tests (56 test files)
|
||||
- **ng-mocks**: For advanced mocking scenarios and child component mocking
|
||||
- **Jest**: 40 libraries (65.6% - legacy/existing code)
|
||||
- **Vitest**: 21 libraries (34.4% - new standard)
|
||||
- All formal libraries now have test executors configured
|
||||
|
||||
### Migration Status by Domain
|
||||
- **Migrated to Vitest**: `crm-data-access`, `checkout-*`, several `ui/*` components, `remission/*` libraries
|
||||
- **Still on Jest**: Core `oms/*` libraries, main application, most legacy libraries
|
||||
- **New Libraries**: Should use Vitest + Angular Testing Utilities from the start
|
||||
### Testing Strategy
|
||||
- **New libraries**: Use Vitest + Angular Testing Utilities (TestBed, ComponentFixture)
|
||||
- **Legacy libraries**: Continue with Jest + Spectator until migrated
|
||||
- **Advanced mocking**: Use ng-mocks for complex scenarios
|
||||
|
||||
### Test File Requirements
|
||||
### Key Requirements
|
||||
- Test files must end with `.spec.ts`
|
||||
- Use AAA pattern (Arrange-Act-Assert) consistently across both frameworks
|
||||
- Include E2E testing attributes (`data-what`, `data-which`, dynamic `data-*` attributes) in HTML templates
|
||||
- Mock external dependencies and child components using appropriate framework tools
|
||||
- Verify E2E attributes are correctly applied in component unit tests
|
||||
- Use AAA pattern (Arrange-Act-Assert)
|
||||
- **Always include E2E attributes**: `data-what`, `data-which`, and dynamic `data-*` in HTML templates
|
||||
- Mock external dependencies appropriately for your framework
|
||||
|
||||
**For detailed testing guidelines, framework comparison, and migration instructions, see [`docs/guidelines/testing.md`](docs/guidelines/testing.md).**
|
||||
|
||||
**References:**
|
||||
- [Jest Documentation](https://jestjs.io/)
|
||||
- [Vitest Documentation](https://vitest.dev/)
|
||||
- [Angular Testing Guide](https://angular.io/guide/testing)
|
||||
- [Spectator](https://ngneat.github.io/spectator/)
|
||||
|
||||
## State Management
|
||||
- **NgRx Signals**: Primary state management with modern functional approach using `signalStore()`
|
||||
@@ -151,55 +140,63 @@ npx nx affected:test
|
||||
- **Navigation State**: Use `@isa/core/navigation` for temporary navigation context (return URLs, wizard state) instead of query parameters
|
||||
|
||||
## Styling and Design System
|
||||
- **Tailwind CSS**: Primary styling framework with extensive ISA-specific customization
|
||||
- **Custom Breakpoints**: `isa-desktop` (1024px), `isa-desktop-l` (1440px), `isa-desktop-xl` (1920px)
|
||||
- **Brand Color System**: Comprehensive `isa-*` color palette with semantic naming
|
||||
- **Design Tokens**: Consistent spacing, typography, shadows, and border-radius values
|
||||
- **Custom Tailwind Plugins** (7 plugins): `button`, `typography`, `menu`, `label`, `input`, `section`, `select-bullet`
|
||||
- **SCSS Integration**: Component-scoped SCSS with BEM-like naming conventions
|
||||
- **CSS Custom Properties**: Extensive use of CSS variables for theming and component variants
|
||||
- **Typography System**: 14 custom text utilities (`.isa-text-heading-1-bold`, `.isa-text-body-2-regular`)
|
||||
- **UI Component Libraries**: 15 specialized UI libraries with consistent API patterns
|
||||
- **Storybook Integration**: Component documentation and development environment
|
||||
- **Responsive Design & Breakpoints**:
|
||||
- **Breakpoint Service**: Use `@isa/ui/layout` for reactive breakpoint detection in components
|
||||
- **Available Breakpoints**:
|
||||
- `Breakpoint.Tablet`: `(max-width: 1279px)` - Mobile and tablet devices
|
||||
- `Breakpoint.Desktop`: `(min-width: 1280px) and (max-width: 1439px)` - Standard desktop screens
|
||||
- `Breakpoint.DekstopL`: `(min-width: 1440px) and (max-width: 1919px)` - Large desktop screens
|
||||
- `Breakpoint.DekstopXL`: `(min-width: 1920px)` - Extra large desktop screens
|
||||
- **Usage Pattern**:
|
||||
```typescript
|
||||
import { breakpoint, Breakpoint } from '@isa/ui/layout';
|
||||
- **Framework**: [Tailwind CSS](https://tailwindcss.com/docs) with extensive ISA-specific customization
|
||||
- **Custom Breakpoints**: `isa-desktop` (1024px), `isa-desktop-l` (1440px), `isa-desktop-xl` (1920px)
|
||||
- **Brand Color System**: `isa-*` color palette with semantic naming
|
||||
- **Custom Tailwind Plugins** (7): button, typography, menu, label, input, section, select-bullet
|
||||
- **Typography System**: 14 custom utilities (`.isa-text-heading-1-bold`, `.isa-text-body-2-regular`, etc.)
|
||||
- **UI Component Libraries**: 17 specialized libraries with consistent APIs (see Library Reference)
|
||||
- **Storybook**: Component documentation and development at `npm run storybook`
|
||||
|
||||
isDesktop = breakpoint([Breakpoint.Desktop, Breakpoint.DekstopL, Breakpoint.DekstopXL]);
|
||||
```
|
||||
- **Template Integration**: Use with `@if` control flow for conditional rendering based on screen size
|
||||
- **Note**: Prefer the breakpoint service over CSS-only solutions (hidden/flex classes) for proper server-side rendering and better maintainability
|
||||
### Responsive Design with Breakpoint Service
|
||||
Use `@isa/ui/layout` for reactive breakpoint detection instead of CSS-only solutions:
|
||||
|
||||
```typescript
|
||||
import { breakpoint, Breakpoint } from '@isa/ui/layout';
|
||||
|
||||
// Detect screen size reactively
|
||||
isDesktop = breakpoint([Breakpoint.Desktop, Breakpoint.DekstopL, Breakpoint.DekstopXL]);
|
||||
```
|
||||
|
||||
**Available Breakpoints:**
|
||||
- `Tablet`: max-width: 1279px (mobile/tablet)
|
||||
- `Desktop`: 1280px - 1439px (standard desktop)
|
||||
- `DekstopL`: 1440px - 1919px (large desktop)
|
||||
- `DekstopXL`: 1920px+ (extra large)
|
||||
|
||||
**Template Usage:**
|
||||
```html
|
||||
@if (isDesktop) {
|
||||
<!-- Desktop-specific content -->
|
||||
}
|
||||
```
|
||||
|
||||
**Why:** Prefer breakpoint service over CSS-only (hidden/flex) for SSR and maintainability.
|
||||
|
||||
## API Integration and Data Access
|
||||
- **Generated Swagger Clients**: 10 auto-generated TypeScript clients from OpenAPI specs in `generated/swagger/`
|
||||
- **Available APIs**: availability-api, cat-search-api, checkout-api, crm-api, eis-api, inventory-api, isa-api, oms-api, print-api, wws-api
|
||||
- **Generation Tool**: `ng-swagger-gen` with custom configurations per API
|
||||
- **Post-processing**: Automatic Unicode character cleanup via `tools/fix-files.js`
|
||||
- **Data Access Architecture**:
|
||||
- **Business Logic Services**: Domain-specific services that wrap generated API clients
|
||||
- **Type Safety**: Full TypeScript integration with Zod schema validation
|
||||
- **Error Handling**: Global HTTP interceptor with custom error classes and automatic re-authentication
|
||||
- **Configuration Management**: Dynamic API endpoint configuration through dependency injection
|
||||
- **Request Cancellation**: Built-in support via AbortSignal and custom operators
|
||||
- **Service Patterns**:
|
||||
- **Modern Injection**: Uses `inject()` function with private field pattern
|
||||
- **Logging Integration**: Comprehensive logging throughout data access layer
|
||||
- **Consistent API**: Standardized service interfaces across all domains
|
||||
|
||||
**Generated Swagger Clients:** 10 auto-generated TypeScript clients in `generated/swagger/`
|
||||
- Available APIs: availability-api, cat-search-api, checkout-api, crm-api, eis-api, inventory-api, isa-api, oms-api, print-api, wws-api
|
||||
- Tool: [ng-swagger-gen](https://www.npmjs.com/package/ng-swagger-gen) with custom per-API configuration
|
||||
- Post-processing: Automatic Unicode cleanup via `tools/fix-files.js`
|
||||
- Regenerate: `npm run generate:swagger`
|
||||
|
||||
**Architecture Pattern:**
|
||||
- Business logic services wrap generated API clients
|
||||
- Type safety: TypeScript + [Zod](https://zod.dev/) schema validation
|
||||
- Error handling: Global HTTP interceptor with automatic re-authentication
|
||||
- Modern injection: Uses `inject()` function with private field pattern
|
||||
- Request cancellation: Built-in via AbortSignal and custom RxJS operators (`takeUntilAborted()`, `takeUntilKeydown()`)
|
||||
|
||||
**Data Access Libraries:** See Library Reference section for domain-specific implementations (`@isa/[domain]/data-access`).
|
||||
|
||||
## Build Configuration
|
||||
- **Angular 20.1.2**: Latest Angular version
|
||||
- **TypeScript 5.8.3**: For type safety
|
||||
- **Node.js >= 22.0.0**: Required Node version (specified in package.json engines)
|
||||
- **npm >= 10.0.0**: Required npm version (specified in package.json engines)
|
||||
- **Nx 21.3.2**: Monorepo build system and development tools
|
||||
- **Vite 6.3.5**: Build tool for faster development and testing (used with Vitest)
|
||||
- **Framework**: Angular with TypeScript (see `package.json` for current versions)
|
||||
- **Requirements**:
|
||||
- Node.js >= 22.0.0 (specified in package.json engines)
|
||||
- npm >= 10.0.0 (specified in package.json engines)
|
||||
- **Build System**: Nx monorepo with Vite for testing (Vitest)
|
||||
- **Development Server**: Serves with SSL by default (required for authentication flows)
|
||||
|
||||
## Important Conventions and Patterns
|
||||
|
||||
@@ -231,34 +228,24 @@ npx nx affected:test
|
||||
|
||||
## Development Workflow and Best Practices
|
||||
|
||||
### Essential Commands
|
||||
- **Development**: `npm start` (serves with SSL enabled by default)
|
||||
- **Testing**: `npm test` (runs all library tests, skips main app)
|
||||
- **Building**: `npm run build` (development), `npm run build-prod` (production)
|
||||
- **Code Generation**: `npm run generate:swagger` (regenerates all API clients)
|
||||
- **Code Quality**: `npm run prettier` (formats all files), `npm run pretty-quick` (staged files only)
|
||||
### Project Conventions
|
||||
- **Default Branch**: `develop` (not main) - Always create PRs against develop
|
||||
- **Commit Style**: [Conventional commits](https://www.conventionalcommits.org/) without co-author tags
|
||||
- **Nx Cache**: Always use `--skip-nx-cache` for tests to ensure fresh results
|
||||
- **Testing**: New libraries use Vitest + Angular Testing Utilities; legacy use Jest + Spectator
|
||||
- **E2E Attributes**: Always include `data-what`, `data-which`, and dynamic `data-*` in templates
|
||||
- **Design System**: Use ISA-specific Tailwind utilities (`isa-accent-*`, `isa-text-*`)
|
||||
|
||||
### Nx Workflow Optimization
|
||||
- Always use `npx nx run` pattern for executing specific tasks
|
||||
- Include `--skip-nx-cache` flag when running tests to ensure fresh results
|
||||
- Use `--skip-nx-cache` to bypass Nx cache entirely for guaranteed fresh builds/tests (important for reliability)
|
||||
- Use affected commands for CI/CD optimization: `npx nx affected:test`
|
||||
- Visualize project dependencies: `npx nx graph`
|
||||
- The default git branch is `develop` (not `main`)
|
||||
### Code Quality Tools
|
||||
- **Linting**: [ESLint](https://eslint.org/) with Nx dependency checks
|
||||
- **Formatting**: [Prettier](https://prettier.io/) with Husky + lint-staged pre-commit hooks
|
||||
- **Type Safety**: [TypeScript](https://www.typescriptlang.org/) strict mode + [Zod](https://zod.dev/) validation
|
||||
- **Bundle Size**: Monitor carefully (2MB warning, 5MB error for main bundle)
|
||||
|
||||
### Testing Best Practices
|
||||
- **New Libraries**: Use Vitest + Angular Testing Utilities
|
||||
- **Legacy Libraries**: Continue using Jest + Spectator until migrated
|
||||
- **Migration Priority**: UI components and new domains migrate first
|
||||
- **E2E Attributes**: Verify `data-what`, `data-which`, and dynamic `data-*` attributes in tests
|
||||
- **Mock Strategy**: Use appropriate framework tools (Spectator's `mocks` array vs TestBed providers)
|
||||
|
||||
### Code Quality Guidelines
|
||||
- **Linting**: ESLint flat config with Nx dependency checks
|
||||
- **Formatting**: Prettier with pre-commit hooks via Husky and lint-staged
|
||||
- **Type Safety**: Zod validation for API boundaries, TypeScript strict mode
|
||||
- **Bundle Optimization**: Monitor bundle sizes (2MB warning, 5MB error for main bundle)
|
||||
- **Performance**: Use NgRx Signals for reactive state management with session persistence
|
||||
### Nx Workflow Tips
|
||||
- Use `npx nx graph` to visualize dependencies
|
||||
- Use `npx nx affected:test` for CI/CD optimization
|
||||
- Reference: [Nx Documentation](https://nx.dev/getting-started/intro)
|
||||
|
||||
## Development Notes and Guidelines
|
||||
|
||||
@@ -273,13 +260,73 @@ npx nx affected:test
|
||||
- **Code Review Standards**: Follow the structured review process in `.github/review-instructions.md` with categorized feedback (🚨 Critical, ❗ Minor, ⚠️ Warnings, ✅ Good Practices)
|
||||
- **E2E Testing Requirements**: Always include `data-what`, `data-which`, and dynamic `data-*` attributes in HTML templates - these are essential for automated testing by QA colleagues
|
||||
|
||||
### Researching and Investigating the Codebase
|
||||
|
||||
**🔴 MANDATORY: You MUST use subagents for research. Direct file reading/searching is FORBIDDEN except for single specific files.**
|
||||
|
||||
#### Required Agent Usage
|
||||
|
||||
| Task Type | Required Agent | Escalation Path |
|
||||
|-----------|---------------|-----------------|
|
||||
| **Package/Library Documentation** | `docs-researcher` | → `docs-researcher-advanced` if not found |
|
||||
| **Internal Library READMEs** | `docs-researcher` | Keep context clean |
|
||||
| **Code Pattern Search** | `Explore` | Set thoroughness level |
|
||||
| **Implementation Analysis** | `Explore` | Multiple file analysis |
|
||||
| **Single Specific File** | Read tool directly | No agent needed |
|
||||
|
||||
#### Documentation Research System (Two-Tier)
|
||||
|
||||
1. **ALWAYS start with `docs-researcher`** (Haiku, 30-120s) for any documentation need
|
||||
2. **Auto-escalate to `docs-researcher-advanced`** (Sonnet, 2-7min) when:
|
||||
- Documentation not found
|
||||
- Conflicting sources
|
||||
- Need code inference
|
||||
- Complex architectural questions
|
||||
|
||||
#### Enforcement Examples
|
||||
|
||||
```
|
||||
❌ WRONG: Read libs/ui/buttons/README.md
|
||||
✅ RIGHT: Task → docs-researcher → "Find documentation for @isa/ui/buttons"
|
||||
|
||||
❌ WRONG: Grep for "signalStore" patterns
|
||||
✅ RIGHT: Task → Explore → "Find all signalStore implementations"
|
||||
|
||||
❌ WRONG: WebSearch for Zod documentation
|
||||
✅ RIGHT: Task → docs-researcher → "Find Zod validation documentation"
|
||||
```
|
||||
|
||||
**Remember: Using subagents is NOT optional - it's mandatory for maintaining context efficiency and search quality.**
|
||||
|
||||
#### Common Research Patterns
|
||||
|
||||
| Information Need | Required Approach |
|
||||
|-----------------|-------------------|
|
||||
| **Library documentation** | `docs-researcher` → Check library-reference.md → Escalate if needed |
|
||||
| **Code patterns/examples** | `Explore` with "medium" or "very thorough" |
|
||||
| **Architecture understanding** | `npx nx graph` + `Explore` for implementation |
|
||||
| **Debugging/errors** | Direct tool use (Read specific error file, check console) |
|
||||
|
||||
#### Debugging Tips
|
||||
- **TypeScript errors**: Follow error path to exact file:line
|
||||
- **Test failures**: Use `--skip-nx-cache` for fresh output
|
||||
- **Module resolution**: Check `tsconfig.base.json` path aliases
|
||||
- **State issues**: Use Angular DevTools browser extension
|
||||
|
||||
### Library Development Patterns
|
||||
- **Library Documentation**: Use `docs-researcher` for ALL library READMEs (mandatory for context management)
|
||||
- **New Library Creation**: Use Nx generators with domain-specific naming (`[domain]-[layer]-[feature]`)
|
||||
- **Standalone Components**: All new components must be standalone with explicit imports - no more NgModules
|
||||
- **Testing Framework Selection**:
|
||||
- **New libraries**: Use Vitest + Angular Testing Utilities
|
||||
- **Existing libraries**: Continue with Jest + Spectator until migrated
|
||||
- **Path Aliases**: Always use `@isa/[domain]/[layer]/[feature]` - avoid relative imports across domain boundaries
|
||||
- **Standalone Components**: All new components must be standalone with explicit imports - no NgModules
|
||||
- **Testing Framework**: New = Vitest + Angular Testing Utilities, Legacy = Jest + Spectator
|
||||
- **Path Aliases**: Always use `@isa/[domain]/[layer]/[feature]` - avoid relative imports
|
||||
|
||||
#### Library Reference Guide
|
||||
|
||||
The monorepo contains **62 libraries** organized across 12 domains. For quick lookup, see **[`docs/library-reference.md`](docs/library-reference.md)**.
|
||||
|
||||
**Quick Overview by Domain:**
|
||||
- Availability (1) | Catalogue (1) | Checkout (6) | Common (3) | Core (5) | CRM (1) | Icons (1)
|
||||
- OMS (9) | Remission (8) | Shared Components (7) | UI Components (17) | Utilities (3)
|
||||
|
||||
### API Integration Workflow
|
||||
- **Swagger Generation**: Run `npm run generate:swagger` to regenerate all 10 API clients when backend changes
|
||||
@@ -308,214 +355,3 @@ npx nx affected:test
|
||||
- **Design System**: Use ISA-specific Tailwind utilities (`isa-accent-*`, `isa-text-*`) and custom breakpoints (`isa-desktop-*`)
|
||||
- **Logging**: Use centralized logging service (`@isa/core/logging`) with contextual information for debugging
|
||||
- **Navigation State**: Use `@isa/core/navigation` for passing temporary state between routes (return URLs, form context) instead of query parameters - keeps URLs clean and state reliable
|
||||
|
||||
## Claude Code Workflow Definition
|
||||
|
||||
Based on comprehensive analysis of development patterns and available tools/MCP servers, here's the formal workflow for handling requests using the Task tool with specialized subagents:
|
||||
|
||||
### Phase 1: Request Analysis and Routing
|
||||
|
||||
#### 1.1 Initial Analysis (Always Use Subagents)
|
||||
**Trigger**: Any user request
|
||||
**Subagents**: `general-purpose` (for research) + domain specialists as needed
|
||||
|
||||
```
|
||||
1. Parse request intent and complexity level
|
||||
2. Classify request type:
|
||||
- Feature Development (new functionality)
|
||||
- Bug Fix/Maintenance (corrections)
|
||||
- Code Quality/Refactoring (improvements)
|
||||
- Testing/QA (validation)
|
||||
- Architecture/Design (structure)
|
||||
- Research/Investigation (exploration)
|
||||
3. Assess information completeness and ambiguity
|
||||
4. Determine required domains and expertise
|
||||
```
|
||||
|
||||
#### 1.2 Clarification Decision Matrix
|
||||
```
|
||||
IF (high ambiguity + high impact) → REQUEST clarification
|
||||
IF (medium ambiguity + architectural changes) → REQUEST optional clarification
|
||||
IF (low ambiguity OR simple changes) → PROCEED with documented assumptions
|
||||
```
|
||||
|
||||
### Phase 2: Task Decomposition and Agent Assignment
|
||||
|
||||
#### 2.1 Complexity-Based Routing
|
||||
|
||||
**Simple Tasks (Single file, isolated change)**:
|
||||
- Route directly to specialist (`frontend-developer`, `typescript-pro`, etc.)
|
||||
- Single quality gate at completion
|
||||
|
||||
**Moderate Tasks (Multiple related files, limited scope)**:
|
||||
- Decompose into 2-4 parallel subagent tasks
|
||||
- Example: `angular-mcp` + `test-automator` + `docs-architect`
|
||||
|
||||
**Complex Tasks (Multiple domains, significant scope)**:
|
||||
- Hierarchical task tree with dependencies
|
||||
- Example: `general-purpose` (analysis) → `nx-mcp` (structure) → `frontend-developer` + `test-automator` (parallel) → `code-reviewer` (validation)
|
||||
|
||||
**Architectural Tasks (System-wide changes)**:
|
||||
- Multi-phase with user approval gates
|
||||
- Example: `architect-review` → user approval → `frontend-developer` + `backend-architect` + `database-optimizer` → `performance-engineer` (validation)
|
||||
|
||||
#### 2.2 Optimal Agent Combinations
|
||||
|
||||
**Feature Development Pattern**:
|
||||
```
|
||||
context7 (fetch latest APIs)
|
||||
→ frontend-developer + test-automator (parallel TDD)
|
||||
→ ui-ux-designer (if UI changes)
|
||||
→ code-reviewer (quality validation)
|
||||
```
|
||||
|
||||
**Bug Fix Pattern**:
|
||||
```
|
||||
error-detective (analyze issue)
|
||||
→ debugger (reproduce and fix)
|
||||
→ test-automator (regression tests)
|
||||
→ performance-engineer (if performance-related)
|
||||
```
|
||||
|
||||
**Refactoring Pattern**:
|
||||
```
|
||||
general-purpose (understand current state)
|
||||
→ legacy-modernizer (plan modernization)
|
||||
→ test-automator (safety tests)
|
||||
→ frontend-developer (implement changes)
|
||||
→ architect-review (validate architecture)
|
||||
```
|
||||
|
||||
### Phase 3: Execution with Progressive Quality Gates
|
||||
|
||||
#### 3.1 Standard Execution Flow
|
||||
```
|
||||
1. Each subagent receives atomic task with clear requirements
|
||||
2. Subagent performs implementation with embedded quality checks
|
||||
3. Results validated against project standards (E2E attributes, naming conventions)
|
||||
4. Integration compatibility verified
|
||||
5. Progress reported to user with next steps
|
||||
```
|
||||
|
||||
#### 3.2 Quality Gates by Task Type
|
||||
- **Code Changes**: `test-automator` → `code-reviewer` → `performance-engineer`
|
||||
- **UI Changes**: `ui-visual-validator` → `frontend-security-coder` → `code-reviewer`
|
||||
- **Architecture Changes**: `architect-review` → user approval → implementation → `performance-engineer`
|
||||
- **API Changes**: `api-documenter` → `backend-security-coder` → integration tests
|
||||
|
||||
### Phase 4: Integration and Validation
|
||||
|
||||
#### 4.1 Continuous Validation
|
||||
```
|
||||
- Every file change triggers appropriate quality subagent
|
||||
- Integration points validated by architect-review
|
||||
- Performance impacts assessed by performance-engineer
|
||||
- Security changes reviewed by security-auditor
|
||||
```
|
||||
|
||||
#### 4.2 User Communication Strategy
|
||||
```
|
||||
- Real-time: Critical decisions and blockers
|
||||
- Milestone-based: Major phase completions
|
||||
- Exception-driven: Alternative approaches or issues
|
||||
- Summary-based: Long-running workflow progress
|
||||
```
|
||||
|
||||
### Specialized Subagent Usage Patterns
|
||||
|
||||
#### **Always Use These Subagents Proactively**:
|
||||
- `general-purpose`: For codebase analysis, research, and complex multi-step tasks
|
||||
- Available specialist agents based on task requirements (see full list below)
|
||||
|
||||
#### **Available MCP Server Integration**:
|
||||
- **nx-mcp**: `nx_workspace`, `nx_project_details`, `nx_run_generator`, `nx_visualize_graph`, etc.
|
||||
- **angular-mcp**: `list_projects`, `search_documentation`
|
||||
- **context7**: `resolve-library-id`, `get-library-docs` for latest package documentation
|
||||
|
||||
#### **Project-Relevant Subagent Types**:
|
||||
|
||||
**Tier 1 - Essential (Most Frequently Needed)**:
|
||||
- `frontend-developer`: Angular 20.1.2 feature development, standalone components, domain library implementation
|
||||
- `typescript-pro`: Advanced TypeScript 5.8.3 patterns, type system optimization, interface design
|
||||
- `test-automator`: Jest→Vitest migration, Spectator→Angular Testing Utilities, unit testing, E2E attributes
|
||||
- `ui-ux-designer`: Tailwind CSS design system, UI component libraries, responsive design
|
||||
|
||||
**Tier 2 - Important (Regularly Needed)**:
|
||||
- `code-reviewer`: ESLint compliance, Angular best practices, code quality validation
|
||||
- `performance-engineer`: Angular optimization, bundle analysis, NgRx performance patterns
|
||||
- `api-documenter`: Swagger/OpenAPI integration, API client documentation
|
||||
- `docs-architect`: Technical documentation, architecture guides, CLAUDE.md maintenance
|
||||
|
||||
**Tier 3 - Specialized (Domain-Specific)**:
|
||||
- `architect-review`: Nx monorepo architecture, domain-driven design validation
|
||||
- `frontend-security-coder`: Angular security patterns, XSS prevention, authentication flows
|
||||
- `deployment-engineer`: Angular build pipelines, Nx CI/CD, npm script automation
|
||||
- `debugger`: Error analysis, RxJS debugging, state management troubleshooting
|
||||
|
||||
**Cross-Cutting Support**:
|
||||
- `general-purpose`: Complex analysis, codebase research, multi-domain investigations
|
||||
- `error-detective`: Production issue investigation, log analysis, performance bottlenecks
|
||||
|
||||
### Escalation and Error Handling
|
||||
|
||||
#### Immediate Escalation Triggers:
|
||||
- Subagent cannot access required files or resources
|
||||
- Conflicting requirements between parallel tasks
|
||||
- Security vulnerabilities discovered
|
||||
- Breaking changes with no compatibility path
|
||||
|
||||
#### Recovery Hierarchy:
|
||||
1. Subagent self-resolution (retry with different approach)
|
||||
2. Alternative subagent assignment (different specialist)
|
||||
3. Task redecomposition (break down further)
|
||||
4. User consultation (clarification or decision needed)
|
||||
|
||||
### Example Workflow: "Add Dark Mode Feature"
|
||||
|
||||
```
|
||||
1. ANALYSIS PHASE:
|
||||
Task(general-purpose, "Research Angular/Tailwind dark mode patterns and analyze ISA theme system")
|
||||
|
||||
2. PLANNING PHASE:
|
||||
Task(ui-ux-designer, "Design dark mode integration with ISA color system and Tailwind classes")
|
||||
Task(frontend-developer, "Plan component modifications and theme service architecture")
|
||||
|
||||
3. IMPLEMENTATION PHASE (can run in parallel):
|
||||
Task(frontend-developer, "Implement Angular theme service and component modifications")
|
||||
Task(typescript-pro, "Create TypeScript interfaces and type-safe theme system")
|
||||
Task(test-automator, "Create Jest/Vitest tests with E2E attributes for theme functionality")
|
||||
|
||||
4. VALIDATION PHASE:
|
||||
Task(code-reviewer, "Review Angular patterns, NgRx integration, and code quality")
|
||||
Task(performance-engineer, "Assess bundle size impact and runtime performance")
|
||||
|
||||
5. INTEGRATION PHASE:
|
||||
Task(test-automator, "Run full Nx test suite and validate E2E attributes")
|
||||
Task(docs-architect, "Update Storybook documentation and component usage guides")
|
||||
```
|
||||
|
||||
### MCP Server Integration Workflow: "Integrate New Angular Library"
|
||||
|
||||
```
|
||||
1. RESEARCH PHASE:
|
||||
- Use mcp__context7__resolve-library-id to find the library
|
||||
- Use mcp__context7__get-library-docs to understand APIs
|
||||
- Use mcp__angular-mcp__search_documentation for Angular integration patterns
|
||||
|
||||
2. PROJECT SETUP:
|
||||
- Use mcp__nx-mcp__nx_generators to find appropriate generators
|
||||
- Use mcp__nx-mcp__nx_run_generator to scaffold integration components
|
||||
- Use mcp__nx-mcp__nx_project_details to understand impact scope
|
||||
|
||||
3. IMPLEMENTATION WITH SUBAGENTS:
|
||||
Task(typescript-pro, "Create TypeScript interfaces for library integration")
|
||||
Task(frontend-developer, "Implement Angular service wrapping the library")
|
||||
Task(test-automator, "Create unit and integration tests")
|
||||
|
||||
4. VALIDATION:
|
||||
- Use mcp__nx-mcp__nx_visualize_graph to verify dependency relationships
|
||||
- Use mcp__nx-mcp__nx_current_running_tasks_details to monitor builds
|
||||
Task(code-reviewer, "Review integration patterns and code quality")
|
||||
```
|
||||
|
||||
This comprehensive workflow leverages ALL available MCP servers and specialized subagents for maximum efficiency, with each agent handling both analysis AND implementation tasks according to their expertise.
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { inject, isDevMode, NgModule } from '@angular/core';
|
||||
import { Location } from '@angular/common';
|
||||
import { RouterModule, Routes, Router } from '@angular/router';
|
||||
import { isDevMode, NgModule } from '@angular/core';
|
||||
import { RouterModule, Routes } from '@angular/router';
|
||||
import {
|
||||
CanActivateCartGuard,
|
||||
CanActivateCartWithProcessIdGuard,
|
||||
@@ -11,7 +10,6 @@ import {
|
||||
CanActivateGoodsInGuard,
|
||||
CanActivateProductGuard,
|
||||
CanActivateProductWithProcessIdGuard,
|
||||
CanActivateRemissionGuard,
|
||||
CanActivateTaskCalendarGuard,
|
||||
IsAuthenticatedGuard,
|
||||
} from './guards';
|
||||
@@ -31,12 +29,7 @@ import {
|
||||
ActivateProcessIdWithConfigKeyGuard,
|
||||
} from './guards/activate-process-id.guard';
|
||||
import { MatomoRouteData } from 'ngx-matomo-client';
|
||||
import {
|
||||
tabResolverFn,
|
||||
TabService,
|
||||
TabNavigationService,
|
||||
processResolverFn,
|
||||
} from '@isa/core/tabs';
|
||||
import { tabResolverFn, processResolverFn } from '@isa/core/tabs';
|
||||
import { provideScrollPositionRestoration } from '@isa/utils/scroll-position';
|
||||
|
||||
const routes: Routes = [
|
||||
@@ -208,6 +201,13 @@ const routes: Routes = [
|
||||
(m) => m.routes,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'order-confirmation',
|
||||
loadChildren: () =>
|
||||
import('@isa/checkout/feature/reward-order-confirmation').then(
|
||||
(m) => m.routes,
|
||||
),
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
|
||||
@@ -1024,15 +1024,15 @@ export class PurchaseOptionsStore extends ComponentStore<PurchaseOptionsState> {
|
||||
purchaseOption,
|
||||
);
|
||||
|
||||
let promotion: Promotion | null = { value: item.promoPoints };
|
||||
let loyalty: Loyalty | null = null;
|
||||
let promotion: Promotion | undefined = { value: item.promoPoints };
|
||||
let loyalty: Loyalty | undefined = undefined;
|
||||
const redemptionPoints: number | null = item.redemptionPoints || null;
|
||||
|
||||
// "Lesepunkte einlösen" logic
|
||||
// If "Lesepunkte einlösen" is checked and item has redemption points, set price to 0 and remove promotion
|
||||
if (this.useRedemptionPoints) {
|
||||
// If loyalty is set, we need to remove promotion
|
||||
promotion = null;
|
||||
promotion = undefined;
|
||||
// Set loyalty points from item
|
||||
loyalty = { value: redemptionPoints };
|
||||
// Set price to 0
|
||||
|
||||
@@ -3,7 +3,6 @@ import {
|
||||
ChangeDetectionStrategy,
|
||||
OnInit,
|
||||
OnDestroy,
|
||||
Host,
|
||||
inject,
|
||||
} from '@angular/core';
|
||||
import { CustomerSearchStore } from '../../store';
|
||||
@@ -12,7 +11,6 @@ import { debounceTime, map, switchMap, takeUntil } from 'rxjs/operators';
|
||||
import { Observable, Subject, combineLatest } from 'rxjs';
|
||||
import {
|
||||
AssignedPayerDTO,
|
||||
CustomerDTO,
|
||||
ListResponseArgsOfAssignedPayerDTO,
|
||||
} from '@generated/swagger/crm-api';
|
||||
import { AsyncPipe } from '@angular/common';
|
||||
@@ -24,7 +22,6 @@ import { UiModalService } from '@ui/modal';
|
||||
import { CustomerSearchNavigation } from '@shared/services/navigation';
|
||||
import { RouterLink } from '@angular/router';
|
||||
import { CustomerDetailsViewMainComponent } from '../details-main-view.component';
|
||||
import { PayerDTO } from '@generated/swagger/checkout-api';
|
||||
import {
|
||||
AssignedPayer,
|
||||
CrmTabMetadataService,
|
||||
@@ -165,7 +162,9 @@ export class DetailsMainViewBillingAddressesComponent
|
||||
}
|
||||
} else if (this.showCustomerAddress) {
|
||||
this._host.setPayer(
|
||||
CustomerAdapter.toPayerFromCustomer(customer as Customer),
|
||||
CustomerAdapter.toPayerFromCustomer(
|
||||
customer as unknown as Customer,
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -218,8 +217,11 @@ export class DetailsMainViewBillingAddressesComponent
|
||||
});
|
||||
};
|
||||
|
||||
handleLoadAssignedPayersError = (err: any) => {
|
||||
this._modal.error('Laden der Rechnungsadressen fehlgeschlagen', err);
|
||||
handleLoadAssignedPayersError = (err: unknown) => {
|
||||
this._modal.error(
|
||||
'Laden der Rechnungsadressen fehlgeschlagen',
|
||||
err as Error,
|
||||
);
|
||||
};
|
||||
|
||||
resetStore() {
|
||||
|
||||
@@ -3,7 +3,6 @@ import {
|
||||
ChangeDetectionStrategy,
|
||||
OnInit,
|
||||
OnDestroy,
|
||||
Host,
|
||||
inject,
|
||||
} from '@angular/core';
|
||||
import { CustomerSearchStore } from '../../store';
|
||||
@@ -11,7 +10,6 @@ import { CrmCustomerService } from '@domain/crm';
|
||||
import { map, switchMap, takeUntil } from 'rxjs/operators';
|
||||
import { Observable, Subject, combineLatest } from 'rxjs';
|
||||
import {
|
||||
CustomerDTO,
|
||||
ListResponseArgsOfAssignedPayerDTO,
|
||||
ShippingAddressDTO,
|
||||
} from '@generated/swagger/crm-api';
|
||||
@@ -189,7 +187,9 @@ export class DetailsMainViewDeliveryAddressesComponent
|
||||
);
|
||||
} else if (this.showCustomerAddress) {
|
||||
this._host.setShippingAddress(
|
||||
ShippingAddressAdapter.fromCustomer(customer as Customer),
|
||||
ShippingAddressAdapter.fromCustomer(
|
||||
customer as unknown as Customer,
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -242,8 +242,8 @@ export class DetailsMainViewDeliveryAddressesComponent
|
||||
});
|
||||
};
|
||||
|
||||
handleLoadAssignedPayersError = (err: any) => {
|
||||
this._modal.error('Laden der Lieferadressen fehlgeschlagen', err);
|
||||
handleLoadAssignedPayersError = (err: unknown) => {
|
||||
this._modal.error('Laden der Lieferadressen fehlgeschlagen', err as Error);
|
||||
};
|
||||
|
||||
resetStore() {
|
||||
|
||||
@@ -4,7 +4,6 @@ import {
|
||||
OnInit,
|
||||
OnDestroy,
|
||||
inject,
|
||||
linkedSignal,
|
||||
signal,
|
||||
} from '@angular/core';
|
||||
import { Subject, combineLatest } from 'rxjs';
|
||||
@@ -36,7 +35,6 @@ import { log, logAsync } from '@utils/common';
|
||||
import { CrmCustomerService } from '@domain/crm';
|
||||
import { MessageModalComponent, MessageModalData } from '@modal/message';
|
||||
import { GenderSettingsService } from '@shared/services/gender';
|
||||
import { injectTab } from '@isa/core/tabs';
|
||||
import { toSignal } from '@angular/core/rxjs-interop';
|
||||
import { CrmTabMetadataService, Customer } from '@isa/crm/data-access';
|
||||
import { CustomerAdapter } from '@isa/checkout/data-access';
|
||||
@@ -274,7 +272,7 @@ export class CustomerDetailsViewMainComponent
|
||||
}
|
||||
|
||||
get buyer() {
|
||||
return CustomerAdapter.toBuyer(this.customer as Customer);
|
||||
return CustomerAdapter.toBuyer(this.customer as unknown as Customer);
|
||||
}
|
||||
|
||||
get payer() {
|
||||
|
||||
@@ -1,275 +1,328 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { AuthService } from '@core/auth';
|
||||
import { DomainAvailabilityService } from '@domain/availability';
|
||||
import { OpenStreetMap, OpenStreetMapParams, PlaceDto } from '@external/openstreetmap';
|
||||
import { ComponentStore } from '@ngrx/component-store';
|
||||
import { tapResponse } from '@ngrx/operators';
|
||||
|
||||
import { BranchDTO, BranchType } from '@generated/swagger/checkout-api';
|
||||
import { UiErrorModalComponent, UiModalService } from '@ui/modal';
|
||||
import { geoDistance, GeoLocation } from '@utils/common';
|
||||
import { debounceTime, switchMap, tap, withLatestFrom } from 'rxjs/operators';
|
||||
|
||||
export interface BranchSelectorState {
|
||||
query: string;
|
||||
fetching: boolean;
|
||||
branches: BranchDTO[];
|
||||
filteredBranches: BranchDTO[];
|
||||
selectedBranch?: BranchDTO;
|
||||
online?: boolean;
|
||||
orderingEnabled?: boolean;
|
||||
shippingEnabled?: boolean;
|
||||
filterCurrentBranch?: boolean;
|
||||
currentBranchNumber?: string;
|
||||
orderBy?: 'name' | 'distance';
|
||||
branchType?: number;
|
||||
}
|
||||
|
||||
function branchSorterFn(a: BranchDTO, b: BranchDTO, userBranch: BranchDTO) {
|
||||
return (
|
||||
geoDistance(userBranch?.address?.geoLocation, a?.address?.geoLocation) -
|
||||
geoDistance(userBranch?.address?.geoLocation, b?.address?.geoLocation)
|
||||
);
|
||||
}
|
||||
|
||||
function selectBranches(state: BranchSelectorState) {
|
||||
if (!state?.branches) {
|
||||
return [];
|
||||
}
|
||||
|
||||
let branches = state.branches;
|
||||
|
||||
if (typeof state.online === 'boolean') {
|
||||
branches = branches.filter((branch) => !!branch?.isOnline === state.online);
|
||||
}
|
||||
|
||||
if (typeof state.orderingEnabled === 'boolean') {
|
||||
branches = branches.filter((branch) => !!branch?.isOrderingEnabled === state.orderingEnabled);
|
||||
}
|
||||
|
||||
if (typeof state.shippingEnabled === 'boolean') {
|
||||
branches = branches.filter((branch) => !!branch?.isShippingEnabled === state.shippingEnabled);
|
||||
}
|
||||
|
||||
if (typeof state.filterCurrentBranch === 'boolean' && typeof state.currentBranchNumber === 'string') {
|
||||
branches = branches.filter((branch) => branch?.branchNumber !== state.currentBranchNumber);
|
||||
}
|
||||
|
||||
if (typeof state.orderBy === 'string' && typeof state.currentBranchNumber === 'string') {
|
||||
switch (state.orderBy) {
|
||||
case 'name':
|
||||
branches?.sort((branchA, branchB) => branchA?.name?.localeCompare(branchB?.name));
|
||||
break;
|
||||
case 'distance':
|
||||
const currentBranch = state.branches?.find((b) => b?.branchNumber === state.currentBranchNumber);
|
||||
branches?.sort((a: BranchDTO, b: BranchDTO) => branchSorterFn(a, b, currentBranch));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof state.branchType === 'number') {
|
||||
branches = branches.filter((branch) => branch?.branchType === state.branchType);
|
||||
}
|
||||
|
||||
return branches;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class BranchSelectorStore extends ComponentStore<BranchSelectorState> {
|
||||
get query() {
|
||||
return this.get((s) => s.query);
|
||||
}
|
||||
|
||||
readonly query$ = this.select((s) => s.query);
|
||||
|
||||
get fetching() {
|
||||
return this.get((s) => s.fetching);
|
||||
}
|
||||
|
||||
readonly fetching$ = this.select((s) => s.fetching);
|
||||
|
||||
get branches() {
|
||||
return this.get(selectBranches);
|
||||
}
|
||||
|
||||
readonly branches$ = this.select(selectBranches);
|
||||
|
||||
get filteredBranches() {
|
||||
return this.get((s) => s.filteredBranches);
|
||||
}
|
||||
|
||||
readonly filteredBranches$ = this.select((s) => s.filteredBranches);
|
||||
|
||||
get selectedBranch() {
|
||||
return this.get((s) => s.selectedBranch);
|
||||
}
|
||||
|
||||
readonly selectedBranch$ = this.select((s) => s.selectedBranch);
|
||||
|
||||
constructor(
|
||||
private _availabilityService: DomainAvailabilityService,
|
||||
private _uiModal: UiModalService,
|
||||
private _openStreetMap: OpenStreetMap,
|
||||
auth: AuthService,
|
||||
) {
|
||||
super({
|
||||
query: '',
|
||||
fetching: false,
|
||||
filteredBranches: [],
|
||||
branches: [],
|
||||
online: true,
|
||||
orderingEnabled: true,
|
||||
shippingEnabled: true,
|
||||
filterCurrentBranch: undefined,
|
||||
currentBranchNumber: auth.getClaimByKey('branch_no'),
|
||||
orderBy: 'name',
|
||||
branchType: undefined,
|
||||
});
|
||||
}
|
||||
|
||||
loadBranches = this.effect(($) =>
|
||||
$.pipe(
|
||||
tap((_) => this.setFetching(true)),
|
||||
switchMap(() =>
|
||||
this._availabilityService.getBranches().pipe(
|
||||
withLatestFrom(this.selectedBranch$),
|
||||
tapResponse(
|
||||
([response, selectedBranch]) => this.loadBranchesResponseFn({ response, selectedBranch }),
|
||||
(error: Error) => this.loadBranchesErrorFn(error),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
perimeterSearch = this.effect(($) =>
|
||||
$.pipe(
|
||||
tap((_) => this.beforePerimeterSearch()),
|
||||
debounceTime(500),
|
||||
switchMap(() => {
|
||||
const queryToken = {
|
||||
country: 'Germany',
|
||||
postalcode: this.query,
|
||||
limit: 1,
|
||||
} as OpenStreetMapParams.Query;
|
||||
return this._openStreetMap.query(queryToken).pipe(
|
||||
withLatestFrom(this.branches$),
|
||||
tapResponse(
|
||||
([response, branches]) => this.perimeterSearchResponseFn({ response, branches }),
|
||||
(error: Error) => this.perimeterSearchErrorFn(error),
|
||||
),
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
beforePerimeterSearch = () => {
|
||||
this.setFilteredBranches([]);
|
||||
this.setFetching(true);
|
||||
};
|
||||
|
||||
perimeterSearchResponseFn = ({ response, branches }: { response: PlaceDto[]; branches: BranchDTO[] }) => {
|
||||
const place = response?.find((_) => true);
|
||||
const branch = this._findNearestBranchByPlace({ place, branches });
|
||||
const filteredBranches = [...branches]
|
||||
?.sort((a: BranchDTO, b: BranchDTO) => branchSorterFn(a, b, branch))
|
||||
?.slice(0, 10);
|
||||
this.setFilteredBranches(filteredBranches ?? []);
|
||||
};
|
||||
|
||||
perimeterSearchErrorFn = (error: Error) => {
|
||||
this.setFilteredBranches([]);
|
||||
console.error('OpenStreetMap Request Failed! ', error);
|
||||
};
|
||||
|
||||
loadBranchesResponseFn = ({ response, selectedBranch }: { response: BranchDTO[]; selectedBranch?: BranchDTO }) => {
|
||||
this.setBranches(response ?? []);
|
||||
if (selectedBranch) {
|
||||
this.setSelectedBranch(selectedBranch);
|
||||
}
|
||||
this.setFetching(false);
|
||||
};
|
||||
|
||||
loadBranchesErrorFn = (error: Error) => {
|
||||
this.setBranches([]);
|
||||
this._uiModal.open({
|
||||
title: 'Fehler beim Laden der Filialen',
|
||||
content: UiErrorModalComponent,
|
||||
data: error,
|
||||
config: { showScrollbarY: false },
|
||||
});
|
||||
};
|
||||
|
||||
setBranches(branches: BranchDTO[]) {
|
||||
this.patchState({ branches });
|
||||
}
|
||||
|
||||
setFilteredBranches(filteredBranches: BranchDTO[]) {
|
||||
this.patchState({ filteredBranches });
|
||||
}
|
||||
|
||||
setSelectedBranch(selectedBranch?: BranchDTO) {
|
||||
if (selectedBranch) {
|
||||
this.patchState({
|
||||
selectedBranch,
|
||||
query: this.formatBranch(selectedBranch),
|
||||
});
|
||||
} else {
|
||||
this.patchState({
|
||||
selectedBranch,
|
||||
query: '',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
setQuery(query: string) {
|
||||
this.patchState({ query });
|
||||
}
|
||||
|
||||
setFetching(fetching: boolean) {
|
||||
this.patchState({ fetching });
|
||||
}
|
||||
|
||||
formatBranch(branch?: BranchDTO) {
|
||||
return branch ? (branch.key ? branch.key + ' - ' + branch.name : branch.name) : '';
|
||||
}
|
||||
|
||||
private _findNearestBranchByPlace({ place, branches }: { place: PlaceDto; branches: BranchDTO[] }): BranchDTO {
|
||||
const placeGeoLocation = { longitude: Number(place?.lon), latitude: Number(place?.lat) } as GeoLocation;
|
||||
return (
|
||||
branches?.reduce((a, b) =>
|
||||
geoDistance(placeGeoLocation, a.address.geoLocation) > geoDistance(placeGeoLocation, b.address.geoLocation)
|
||||
? b
|
||||
: a,
|
||||
) ?? {}
|
||||
);
|
||||
}
|
||||
|
||||
getBranchById(id: number): BranchDTO {
|
||||
return this.branches.find((branch) => branch.id === id);
|
||||
}
|
||||
|
||||
setOnline(online: boolean) {
|
||||
this.patchState({ online });
|
||||
}
|
||||
|
||||
setOrderingEnabled(orderingEnabled: boolean) {
|
||||
this.patchState({ orderingEnabled });
|
||||
}
|
||||
|
||||
setShippingEnabled(shippingEnabled: boolean) {
|
||||
this.patchState({ shippingEnabled });
|
||||
}
|
||||
|
||||
setFilterCurrentBranch(filterCurrentBranch: boolean) {
|
||||
this.patchState({ filterCurrentBranch });
|
||||
}
|
||||
|
||||
setOrderBy(orderBy: 'name' | 'distance') {
|
||||
this.patchState({ orderBy });
|
||||
}
|
||||
|
||||
setBranchType(branchType: BranchType) {
|
||||
this.patchState({ branchType });
|
||||
}
|
||||
}
|
||||
import { Injectable } from '@angular/core';
|
||||
import { AuthService } from '@core/auth';
|
||||
import { DomainAvailabilityService } from '@domain/availability';
|
||||
import {
|
||||
OpenStreetMap,
|
||||
OpenStreetMapParams,
|
||||
PlaceDto,
|
||||
} from '@external/openstreetmap';
|
||||
import { ComponentStore } from '@ngrx/component-store';
|
||||
import { tapResponse } from '@ngrx/operators';
|
||||
|
||||
import { BranchDTO, BranchType } from '@generated/swagger/checkout-api';
|
||||
import { UiErrorModalComponent, UiModalService } from '@ui/modal';
|
||||
import { geoDistance, GeoLocation } from '@utils/common';
|
||||
import { debounceTime, switchMap, tap, withLatestFrom } from 'rxjs/operators';
|
||||
|
||||
export interface BranchSelectorState {
|
||||
query: string;
|
||||
fetching: boolean;
|
||||
branches: BranchDTO[];
|
||||
filteredBranches: BranchDTO[];
|
||||
selectedBranch?: BranchDTO;
|
||||
online?: boolean;
|
||||
orderingEnabled?: boolean;
|
||||
shippingEnabled?: boolean;
|
||||
filterCurrentBranch?: boolean;
|
||||
currentBranchNumber?: string;
|
||||
orderBy?: 'name' | 'distance';
|
||||
branchType?: number;
|
||||
}
|
||||
|
||||
function branchSorterFn(a: BranchDTO, b: BranchDTO, userBranch: BranchDTO) {
|
||||
return (
|
||||
geoDistance(userBranch?.address?.geoLocation, a?.address?.geoLocation) -
|
||||
geoDistance(userBranch?.address?.geoLocation, b?.address?.geoLocation)
|
||||
);
|
||||
}
|
||||
|
||||
function selectBranches(state: BranchSelectorState) {
|
||||
if (!state?.branches) {
|
||||
return [];
|
||||
}
|
||||
|
||||
let branches = state.branches;
|
||||
|
||||
if (typeof state.online === 'boolean') {
|
||||
branches = branches.filter((branch) => !!branch?.isOnline === state.online);
|
||||
}
|
||||
|
||||
if (typeof state.orderingEnabled === 'boolean') {
|
||||
branches = branches.filter(
|
||||
(branch) => !!branch?.isOrderingEnabled === state.orderingEnabled,
|
||||
);
|
||||
}
|
||||
|
||||
if (typeof state.shippingEnabled === 'boolean') {
|
||||
branches = branches.filter(
|
||||
(branch) => !!branch?.isShippingEnabled === state.shippingEnabled,
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
typeof state.filterCurrentBranch === 'boolean' &&
|
||||
typeof state.currentBranchNumber === 'string'
|
||||
) {
|
||||
branches = branches.filter(
|
||||
(branch) => branch?.branchNumber !== state.currentBranchNumber,
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
typeof state.orderBy === 'string' &&
|
||||
typeof state.currentBranchNumber === 'string'
|
||||
) {
|
||||
switch (state.orderBy) {
|
||||
case 'name':
|
||||
branches?.sort((branchA, branchB) =>
|
||||
branchA?.name?.localeCompare(branchB?.name),
|
||||
);
|
||||
break;
|
||||
case 'distance': {
|
||||
const currentBranch = state.branches?.find(
|
||||
(b) => b?.branchNumber === state.currentBranchNumber,
|
||||
);
|
||||
branches?.sort((a: BranchDTO, b: BranchDTO) =>
|
||||
branchSorterFn(a, b, currentBranch),
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof state.branchType === 'number') {
|
||||
branches = branches.filter(
|
||||
(branch) => branch?.branchType === state.branchType,
|
||||
);
|
||||
}
|
||||
|
||||
return branches;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class BranchSelectorStore extends ComponentStore<BranchSelectorState> {
|
||||
get query() {
|
||||
return this.get((s) => s.query);
|
||||
}
|
||||
|
||||
readonly query$ = this.select((s) => s.query);
|
||||
|
||||
get fetching() {
|
||||
return this.get((s) => s.fetching);
|
||||
}
|
||||
|
||||
readonly fetching$ = this.select((s) => s.fetching);
|
||||
|
||||
get branches() {
|
||||
return this.get(selectBranches);
|
||||
}
|
||||
|
||||
readonly branches$ = this.select(selectBranches);
|
||||
|
||||
get filteredBranches() {
|
||||
return this.get((s) => s.filteredBranches);
|
||||
}
|
||||
|
||||
readonly filteredBranches$ = this.select((s) => s.filteredBranches);
|
||||
|
||||
get selectedBranch() {
|
||||
return this.get((s) => s.selectedBranch);
|
||||
}
|
||||
|
||||
readonly selectedBranch$ = this.select((s) => s.selectedBranch);
|
||||
|
||||
constructor(
|
||||
private _availabilityService: DomainAvailabilityService,
|
||||
private _uiModal: UiModalService,
|
||||
private _openStreetMap: OpenStreetMap,
|
||||
auth: AuthService,
|
||||
) {
|
||||
super({
|
||||
query: '',
|
||||
fetching: false,
|
||||
filteredBranches: [],
|
||||
branches: [],
|
||||
online: true,
|
||||
orderingEnabled: true,
|
||||
shippingEnabled: true,
|
||||
filterCurrentBranch: undefined,
|
||||
currentBranchNumber: auth.getClaimByKey('branch_no'),
|
||||
orderBy: 'name',
|
||||
branchType: undefined,
|
||||
});
|
||||
}
|
||||
|
||||
loadBranches = this.effect(($) =>
|
||||
$.pipe(
|
||||
tap(() => this.setFetching(true)),
|
||||
switchMap(() =>
|
||||
this._availabilityService.getBranches().pipe(
|
||||
withLatestFrom(this.selectedBranch$),
|
||||
tapResponse(
|
||||
([response, selectedBranch]) =>
|
||||
this.loadBranchesResponseFn({ response, selectedBranch }),
|
||||
(error: Error) => this.loadBranchesErrorFn(error),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
perimeterSearch = this.effect(($) =>
|
||||
$.pipe(
|
||||
tap(() => this.beforePerimeterSearch()),
|
||||
debounceTime(500),
|
||||
switchMap(() => {
|
||||
const queryToken = {
|
||||
country: 'Germany',
|
||||
zipCode: this.query,
|
||||
limit: 1,
|
||||
} as OpenStreetMapParams.Query;
|
||||
return this._openStreetMap.query(queryToken).pipe(
|
||||
withLatestFrom(this.branches$),
|
||||
tapResponse(
|
||||
([response, branches]) =>
|
||||
this.perimeterSearchResponseFn({ response, branches }),
|
||||
(error: Error) => this.perimeterSearchErrorFn(error),
|
||||
),
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
beforePerimeterSearch = () => {
|
||||
this.setFilteredBranches([]);
|
||||
this.setFetching(true);
|
||||
};
|
||||
|
||||
perimeterSearchResponseFn = ({
|
||||
response,
|
||||
branches,
|
||||
}: {
|
||||
response: PlaceDto[];
|
||||
branches: BranchDTO[];
|
||||
}) => {
|
||||
const place = response?.[0];
|
||||
const branch = this._findNearestBranchByPlace({ place, branches });
|
||||
const filteredBranches = [...branches]
|
||||
?.sort((a: BranchDTO, b: BranchDTO) => branchSorterFn(a, b, branch))
|
||||
?.slice(0, 10);
|
||||
this.setFilteredBranches(filteredBranches ?? []);
|
||||
};
|
||||
|
||||
perimeterSearchErrorFn = (error: Error) => {
|
||||
this.setFilteredBranches([]);
|
||||
console.error('OpenStreetMap Request Failed! ', error);
|
||||
};
|
||||
|
||||
loadBranchesResponseFn = ({
|
||||
response,
|
||||
selectedBranch,
|
||||
}: {
|
||||
response: BranchDTO[];
|
||||
selectedBranch?: BranchDTO;
|
||||
}) => {
|
||||
this.setBranches(response ?? []);
|
||||
if (selectedBranch) {
|
||||
this.setSelectedBranch(selectedBranch);
|
||||
}
|
||||
this.setFetching(false);
|
||||
};
|
||||
|
||||
loadBranchesErrorFn = (error: Error) => {
|
||||
this.setBranches([]);
|
||||
this._uiModal.open({
|
||||
title: 'Fehler beim Laden der Filialen',
|
||||
content: UiErrorModalComponent,
|
||||
data: error,
|
||||
config: { showScrollbarY: false },
|
||||
});
|
||||
};
|
||||
|
||||
setBranches(branches: BranchDTO[]) {
|
||||
this.patchState({ branches });
|
||||
}
|
||||
|
||||
setFilteredBranches(filteredBranches: BranchDTO[]) {
|
||||
this.patchState({ filteredBranches });
|
||||
}
|
||||
|
||||
setSelectedBranch(selectedBranch?: BranchDTO) {
|
||||
if (selectedBranch) {
|
||||
this.patchState({
|
||||
selectedBranch,
|
||||
query: this.formatBranch(selectedBranch),
|
||||
});
|
||||
} else {
|
||||
this.patchState({
|
||||
selectedBranch,
|
||||
query: '',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
setQuery(query: string) {
|
||||
this.patchState({ query });
|
||||
}
|
||||
|
||||
setFetching(fetching: boolean) {
|
||||
this.patchState({ fetching });
|
||||
}
|
||||
|
||||
formatBranch(branch?: BranchDTO) {
|
||||
return branch
|
||||
? branch.key
|
||||
? branch.key + ' - ' + branch.name
|
||||
: branch.name
|
||||
: '';
|
||||
}
|
||||
|
||||
private _findNearestBranchByPlace({
|
||||
place,
|
||||
branches,
|
||||
}: {
|
||||
place: PlaceDto;
|
||||
branches: BranchDTO[];
|
||||
}): BranchDTO {
|
||||
const placeGeoLocation = {
|
||||
longitude: Number(place?.lon),
|
||||
latitude: Number(place?.lat),
|
||||
} as GeoLocation;
|
||||
return (
|
||||
branches?.reduce((a, b) =>
|
||||
geoDistance(placeGeoLocation, a.address.geoLocation) >
|
||||
geoDistance(placeGeoLocation, b.address.geoLocation)
|
||||
? b
|
||||
: a,
|
||||
) ?? {}
|
||||
);
|
||||
}
|
||||
|
||||
getBranchById(id: number): BranchDTO {
|
||||
return this.branches.find((branch) => branch.id === id);
|
||||
}
|
||||
|
||||
setOnline(online: boolean) {
|
||||
this.patchState({ online });
|
||||
}
|
||||
|
||||
setOrderingEnabled(orderingEnabled: boolean) {
|
||||
this.patchState({ orderingEnabled });
|
||||
}
|
||||
|
||||
setShippingEnabled(shippingEnabled: boolean) {
|
||||
this.patchState({ shippingEnabled });
|
||||
}
|
||||
|
||||
setFilterCurrentBranch(filterCurrentBranch: boolean) {
|
||||
this.patchState({ filterCurrentBranch });
|
||||
}
|
||||
|
||||
setOrderBy(orderBy: 'name' | 'distance') {
|
||||
this.patchState({ orderBy });
|
||||
}
|
||||
|
||||
setBranchType(branchType: BranchType) {
|
||||
this.patchState({ branchType });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
import {
|
||||
type Meta,
|
||||
type StoryObj,
|
||||
applicationConfig,
|
||||
moduleMetadata,
|
||||
} from '@storybook/angular';
|
||||
import { ProductInfoComponent } from '@isa/checkout/shared/product-info';
|
||||
import { provideProductImageUrl } from '@isa/shared/product-image';
|
||||
import { provideProductRouterLinkBuilder } from '@isa/shared/product-router-link';
|
||||
import { provideRouter } from '@angular/router';
|
||||
|
||||
const mockProduct = {
|
||||
ean: '9783498007706',
|
||||
name: 'Die Assistentin',
|
||||
contributors: 'Wahl, Caroline',
|
||||
};
|
||||
|
||||
const meta: Meta<ProductInfoComponent> = {
|
||||
title: 'checkout/shared/product-info/ProductInfo',
|
||||
component: ProductInfoComponent,
|
||||
decorators: [
|
||||
applicationConfig({
|
||||
providers: [
|
||||
provideRouter([{ path: ':ean', component: ProductInfoComponent }]),
|
||||
],
|
||||
}),
|
||||
moduleMetadata({
|
||||
providers: [
|
||||
provideProductImageUrl('https://produktbilder-test.paragon-data.net'),
|
||||
provideProductRouterLinkBuilder((ean: string) => ean),
|
||||
],
|
||||
}),
|
||||
],
|
||||
};
|
||||
|
||||
export default meta;
|
||||
|
||||
type Story = StoryObj<ProductInfoComponent>;
|
||||
|
||||
export const BasicWithoutContent: Story = {
|
||||
args: {
|
||||
item: mockProduct,
|
||||
nameSize: 'medium',
|
||||
},
|
||||
argTypes: {
|
||||
item: { control: 'object' },
|
||||
nameSize: {
|
||||
control: { type: 'radio' },
|
||||
options: ['small', 'medium', 'large'],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export const SmallNameSize: Story = {
|
||||
args: {
|
||||
item: mockProduct,
|
||||
nameSize: 'small',
|
||||
},
|
||||
};
|
||||
|
||||
export const MediumNameSize: Story = {
|
||||
args: {
|
||||
item: mockProduct,
|
||||
nameSize: 'medium',
|
||||
},
|
||||
};
|
||||
|
||||
export const LargeNameSize: Story = {
|
||||
args: {
|
||||
item: mockProduct,
|
||||
nameSize: 'large',
|
||||
},
|
||||
};
|
||||
|
||||
export const WithLesepunkte: Story = {
|
||||
args: {
|
||||
item: mockProduct,
|
||||
nameSize: 'medium',
|
||||
},
|
||||
render: (args) => ({
|
||||
props: args,
|
||||
template: `
|
||||
<checkout-product-info [item]="item" [nameSize]="nameSize">
|
||||
<div class="isa-text-body-2-regular">
|
||||
<span class="isa-text-body-2-bold">150</span> Lesepunkte
|
||||
</div>
|
||||
</checkout-product-info>
|
||||
`,
|
||||
}),
|
||||
};
|
||||
|
||||
export const WithManufacturer: Story = {
|
||||
args: {
|
||||
item: mockProduct,
|
||||
nameSize: 'medium',
|
||||
},
|
||||
render: (args) => ({
|
||||
props: args,
|
||||
template: `
|
||||
<checkout-product-info [item]="item" [nameSize]="nameSize">
|
||||
<div class="isa-text-body-2-regular text-neutral-600">
|
||||
Rowohlt Taschenbuch
|
||||
</div>
|
||||
</checkout-product-info>
|
||||
`,
|
||||
}),
|
||||
};
|
||||
|
||||
export const WithMultipleRows: Story = {
|
||||
args: {
|
||||
item: mockProduct,
|
||||
nameSize: 'medium',
|
||||
},
|
||||
render: (args) => ({
|
||||
props: args,
|
||||
template: `
|
||||
<checkout-product-info [item]="item" [nameSize]="nameSize">
|
||||
<div class="isa-text-body-2-regular">
|
||||
<span class="isa-text-body-2-bold">150</span> Lesepunkte
|
||||
</div>
|
||||
<div class="isa-text-body-2-regular text-neutral-600">
|
||||
Rowohlt Taschenbuch
|
||||
</div>
|
||||
<div class="isa-text-body-2-regular text-neutral-600">
|
||||
Erschienen: 01. Januar 2023
|
||||
</div>
|
||||
</checkout-product-info>
|
||||
`,
|
||||
}),
|
||||
};
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Meta, argsToTemplate } from '@storybook/angular';
|
||||
import { ProductFormatIconGroup } from '@isa/icons';
|
||||
import { ProductFormatIconComponent } from '@isa/shared/product-foramt';
|
||||
import { ProductFormatIconComponent } from '@isa/shared/product-format';
|
||||
|
||||
type ProductFormatInputs = {
|
||||
format: string;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { argsToTemplate, Meta } from '@storybook/angular';
|
||||
import { ProductFormatIconGroup } from '@isa/icons';
|
||||
import { ProductFormatComponent } from '@isa/shared/product-foramt';
|
||||
import { ProductFormatComponent } from '@isa/shared/product-format';
|
||||
|
||||
type ProductFormatInputs = {
|
||||
format: string;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -59,6 +59,8 @@ This document outlines the guidelines and best practices for writing unit tests
|
||||
|
||||
- Test files must end with `.spec.ts`.
|
||||
- **Migration to Vitest**: New libraries should use **Vitest** as the primary test runner. Existing libraries continue to use **Jest** until migrated.
|
||||
- **Current Status (as of 2025-10-22):** 40 libraries use Jest (65.6%), 21 libraries use Vitest (34.4%)
|
||||
- All formal libraries now have test executors configured (migration progressing well)
|
||||
- **Testing Framework Migration**: New tests should use **Angular Testing Utilities** (TestBed, ComponentFixture, etc.). Existing tests using **Spectator** remain until migrated.
|
||||
- Employ **ng-mocks** for mocking complex dependencies like child components.
|
||||
|
||||
|
||||
384
docs/library-reference.md
Normal file
384
docs/library-reference.md
Normal file
@@ -0,0 +1,384 @@
|
||||
# Library Reference Guide
|
||||
|
||||
> **Last Updated:** 2025-10-22
|
||||
> **Angular Version:** 20.1.2
|
||||
> **Nx Version:** 21.3.2
|
||||
> **Total Libraries:** 61
|
||||
|
||||
All 61 libraries in the monorepo have comprehensive README.md documentation located at `libs/[domain]/[layer]/[feature]/README.md`.
|
||||
|
||||
**IMPORTANT: Always use the `docs-researcher` subagent** to retrieve and analyze library documentation. This keeps the main context clean and prevents pollution.
|
||||
|
||||
---
|
||||
|
||||
## Availability Domain (1 library)
|
||||
|
||||
### `@isa/availability/data-access`
|
||||
A comprehensive product availability service for Angular applications supporting multiple order types and delivery methods across retail operations.
|
||||
|
||||
**Location:** `libs/availability/data-access/`
|
||||
|
||||
---
|
||||
|
||||
## Catalogue Domain (1 library)
|
||||
|
||||
### `@isa/catalogue/data-access`
|
||||
A comprehensive product catalogue search and availability service for Angular applications, providing catalog item search, loyalty program integration, and specialized availability validation for download and delivery order types.
|
||||
|
||||
**Location:** `libs/catalogue/data-access/`
|
||||
|
||||
---
|
||||
|
||||
## Checkout Domain (6 libraries)
|
||||
|
||||
### `@isa/checkout/data-access`
|
||||
A comprehensive checkout and shopping cart management library for Angular applications supporting multiple order types, reward redemption, and complex multi-step checkout workflows across retail and e-commerce operations.
|
||||
|
||||
**Location:** `libs/checkout/data-access/`
|
||||
|
||||
### `@isa/checkout/feature/reward-order-confirmation`
|
||||
This library was generated with [Nx](https://nx.dev).
|
||||
|
||||
**Location:** `libs/checkout/feature/reward-order-confirmation/`
|
||||
|
||||
### `@isa/checkout/feature/reward-shopping-cart`
|
||||
A comprehensive reward shopping cart feature for Angular applications supporting loyalty points redemption workflow across retail operations.
|
||||
|
||||
**Location:** `libs/checkout/feature/reward-shopping-cart/`
|
||||
|
||||
### `@isa/checkout/shared/product-info`
|
||||
A comprehensive collection of presentation components for displaying product information, destination details, and stock availability in checkout and rewards workflows.
|
||||
|
||||
**Location:** `libs/checkout/shared/product-info/`
|
||||
|
||||
### `@isa/checkout/feature/reward-catalog`
|
||||
A comprehensive loyalty rewards catalog feature for Angular applications supporting reward item browsing, selection, and checkout for customers with bonus cards.
|
||||
|
||||
**Location:** `libs/checkout/feature/reward-catalog/`
|
||||
|
||||
### `@isa/checkout/shared/reward-selection-dialog`
|
||||
Angular library for managing reward selection in shopping cart context. Allows users to toggle between regular purchase and reward redemption using bonus points.
|
||||
|
||||
**Location:** `libs/checkout/shared/reward-selection-dialog/`
|
||||
|
||||
---
|
||||
|
||||
## Common Libraries (3 libraries)
|
||||
|
||||
### `@isa/common/data-access`
|
||||
A foundational data access library providing core utilities, error handling, RxJS operators, response models, and advanced batching infrastructure for Angular applications.
|
||||
|
||||
**Location:** `libs/common/data-access/`
|
||||
|
||||
### `@isa/common/decorators`
|
||||
A comprehensive collection of TypeScript decorators for enhancing method behavior in Angular applications. This library provides decorators for validation, caching, debouncing, rate limiting, and more.
|
||||
|
||||
**Location:** `libs/common/decorators/`
|
||||
|
||||
### `@isa/common/print`
|
||||
A comprehensive print management library for Angular applications providing printer discovery, selection, and unified print operations across label and office printers.
|
||||
|
||||
**Location:** `libs/common/print/`
|
||||
|
||||
---
|
||||
|
||||
## Core Libraries (5 libraries)
|
||||
|
||||
### `@isa/core/config`
|
||||
A lightweight, type-safe configuration management system for Angular applications with runtime validation and nested object access.
|
||||
|
||||
**Location:** `libs/core/config/`
|
||||
|
||||
### `@isa/core/logging`
|
||||
A structured, high-performance logging library for Angular applications with hierarchical context support and flexible sink architecture.
|
||||
|
||||
**Location:** `libs/core/logging/`
|
||||
|
||||
### `@isa/core/navigation`
|
||||
A reusable Angular library providing **context preservation** for multi-step navigation flows with automatic tab-scoped storage.
|
||||
|
||||
**Location:** `libs/core/navigation/`
|
||||
|
||||
### `@isa/core/storage`
|
||||
A powerful, type-safe storage library for Angular applications built on top of NgRx Signals. This library provides seamless integration between NgRx Signal Stores and various storage backends including localStorage, sessionStorage, IndexedDB, and server-side user state.
|
||||
|
||||
**Location:** `libs/core/storage/`
|
||||
|
||||
### `@isa/core/tabs`
|
||||
A sophisticated tab management system for Angular applications providing browser-like navigation with intelligent history management, persistence, and configurable pruning strategies.
|
||||
|
||||
**Location:** `libs/core/tabs/`
|
||||
|
||||
---
|
||||
|
||||
## CRM Domain (1 library)
|
||||
|
||||
### `@isa/crm/data-access`
|
||||
A comprehensive Customer Relationship Management (CRM) data access library for Angular applications providing customer, shipping address, payer, and bonus card management with reactive data loading using Angular resources.
|
||||
|
||||
**Location:** `libs/crm/data-access/`
|
||||
|
||||
---
|
||||
|
||||
## Icons (1 library)
|
||||
|
||||
### `@isa/icons`
|
||||
This library was generated with [Nx](https://nx.dev).
|
||||
|
||||
**Location:** `libs/icons/`
|
||||
|
||||
---
|
||||
|
||||
## OMS Domain (9 libraries)
|
||||
|
||||
### `@isa/oms/data-access`
|
||||
A comprehensive Order Management System (OMS) data access library for Angular applications providing return processing, receipt management, order creation, and print capabilities.
|
||||
|
||||
**Location:** `libs/oms/data-access/`
|
||||
|
||||
### `@isa/oms/feature/return-details`
|
||||
A comprehensive Angular feature library for displaying receipt details and managing product returns in the Order Management System (OMS). Provides an interactive interface for viewing receipt information, selecting items for return, configuring return quantities and product categories, and initiating return processes.
|
||||
|
||||
**Location:** `libs/oms/feature/return-details/`
|
||||
|
||||
### `@isa/oms/feature/return-process`
|
||||
A comprehensive Angular feature library for managing product returns with dynamic question flows, validation, and backend integration. Part of the Order Management System (OMS) domain.
|
||||
|
||||
**Location:** `libs/oms/feature/return-process/`
|
||||
|
||||
### `@isa/oms/feature/return-search`
|
||||
A comprehensive return search feature library for Angular applications, providing intelligent receipt search, filtering, and navigation capabilities for the Order Management System (OMS).
|
||||
|
||||
**Location:** `libs/oms/feature/return-search/`
|
||||
|
||||
### `@isa/oms/feature/return-summary`
|
||||
A comprehensive Angular feature library for displaying and confirming return process summaries in the Order Management System (OMS). This library provides a review interface where users can inspect all items being returned, verify return details, and complete the return process with receipt printing.
|
||||
|
||||
**Location:** `libs/oms/feature/return-summary/`
|
||||
|
||||
### `@isa/oms/shared/product-info`
|
||||
A reusable Angular component library for displaying product information in a standardized, visually consistent format across Order Management System (OMS) workflows.
|
||||
|
||||
**Location:** `libs/oms/shared/product-info/`
|
||||
|
||||
### `@isa/oms/utils/translation`
|
||||
A lightweight translation utility library for OMS receipt types providing human-readable German translations through both service-based and pipe-based interfaces.
|
||||
|
||||
**Location:** `libs/oms/utils/translation/`
|
||||
|
||||
### `@isa/oms/feature/return-review`
|
||||
A comprehensive Angular feature library for reviewing completed return processes in the Order Management System (OMS). Provides a confirmation interface for successful returns with task review capabilities and receipt printing functionality.
|
||||
|
||||
**Location:** `libs/oms/feature/return-review/`
|
||||
|
||||
### `@isa/oms/shared/task-list`
|
||||
A specialized Angular component library for displaying and managing return receipt item tasks in the OMS (Order Management System) domain.
|
||||
|
||||
**Location:** `libs/oms/shared/task-list/`
|
||||
|
||||
---
|
||||
|
||||
## Remission Domain (8 libraries)
|
||||
|
||||
### `@isa/remission/feature/remission-list`
|
||||
Feature module providing the main remission list view with filtering, searching, item selection, and remitting capabilities for department ("Abteilung") and mandatory ("Pflicht") return workflows.
|
||||
|
||||
**Location:** `libs/remission/feature/remission-list/`
|
||||
|
||||
### `@isa/remission/data-access`
|
||||
A comprehensive remission (returns) management system for Angular applications supporting mandatory returns (Pflichtremission) and department overflow returns (Abteilungsremission) in retail inventory operations.
|
||||
|
||||
**Location:** `libs/remission/data-access/`
|
||||
|
||||
### `@isa/remission/feature/remission-return-receipt-details`
|
||||
Feature component for displaying detailed view of a return receipt ("Warenbegleitschein") with items, actions, and completion workflows.
|
||||
|
||||
**Location:** `libs/remission/feature/remission-return-receipt-details/`
|
||||
|
||||
### `@isa/remission/feature/remission-return-receipt-list`
|
||||
Feature component providing a comprehensive list view of all return receipts with filtering, sorting, and action capabilities.
|
||||
|
||||
**Location:** `libs/remission/feature/remission-return-receipt-list/`
|
||||
|
||||
### `@isa/remission/shared/return-receipt-actions`
|
||||
Angular standalone components for managing return receipt actions including deletion, continuation, and completion workflows in the remission process.
|
||||
|
||||
**Location:** `libs/remission/shared/return-receipt-actions/`
|
||||
|
||||
### `@isa/remission/shared/product`
|
||||
A collection of Angular standalone components for displaying product information in remission workflows, including product details, stock information, and shelf metadata.
|
||||
|
||||
**Location:** `libs/remission/shared/product/`
|
||||
|
||||
### `@isa/remission/shared/search-item-to-remit-dialog`
|
||||
Angular dialog component for searching and adding items to remission lists that are not on the mandatory return list (Pflichtremission).
|
||||
|
||||
**Location:** `libs/remission/shared/search-item-to-remit-dialog/`
|
||||
|
||||
### `@isa/remission/shared/remission-start-dialog`
|
||||
Angular dialog component for initiating remission processes with two-step workflow: creating return receipts and assigning package numbers.
|
||||
|
||||
**Location:** `libs/remission/shared/remission-start-dialog/`
|
||||
|
||||
---
|
||||
|
||||
## Shared Component Libraries (7 libraries)
|
||||
|
||||
### `@isa/shared/address`
|
||||
Comprehensive Angular components for displaying addresses in both multi-line and inline formats with automatic country name resolution and intelligent formatting.
|
||||
|
||||
**Location:** `libs/shared/address/`
|
||||
|
||||
### `@isa/shared/filter`
|
||||
A powerful and flexible filtering library for Angular applications that provides a complete solution for implementing filters, search functionality, and sorting capabilities.
|
||||
|
||||
**Location:** `libs/shared/filter/`
|
||||
|
||||
### `@isa/shared/product-format`
|
||||
Angular components for displaying product format information with icons and formatted text, supporting various media types like hardcover, paperback, audio, and digital formats.
|
||||
|
||||
**Location:** `libs/shared/product-format/`
|
||||
|
||||
### `@isa/shared/product-image`
|
||||
A lightweight Angular library providing a directive and service for displaying product images from a CDN with dynamic sizing and fallback support.
|
||||
|
||||
**Location:** `libs/shared/product-image/`
|
||||
|
||||
### `@isa/shared/product-router-link`
|
||||
An Angular library providing a customizable directive for creating product navigation links based on EAN codes with flexible URL generation strategies.
|
||||
|
||||
**Location:** `libs/shared/product-router-link/`
|
||||
|
||||
### `@isa/shared/quantity-control`
|
||||
An accessible, feature-rich Angular quantity selector component with dropdown presets and manual input mode.
|
||||
|
||||
**Location:** `libs/shared/quantity-control/`
|
||||
|
||||
### `@isa/shared/scanner`
|
||||
## Overview
|
||||
|
||||
**Location:** `libs/shared/scanner/`
|
||||
|
||||
---
|
||||
|
||||
## UI Component Libraries (16 libraries)
|
||||
|
||||
### `@isa/ui/label`
|
||||
A flexible label component for displaying tags and notices with configurable priority levels across Angular applications.
|
||||
|
||||
**Location:** `libs/ui/label/`
|
||||
|
||||
### `@isa/ui/bullet-list`
|
||||
A lightweight bullet list component system for Angular applications supporting customizable icons and hierarchical content presentation.
|
||||
|
||||
**Location:** `libs/ui/bullet-list/`
|
||||
|
||||
### `@isa/ui/buttons`
|
||||
A comprehensive button component library for Angular applications providing five specialized button components with consistent styling, loading states, and accessibility features.
|
||||
|
||||
**Location:** `libs/ui/buttons/`
|
||||
|
||||
### `@isa/ui/datepicker`
|
||||
A comprehensive date range picker component library for Angular applications with calendar and month/year selection views, form integration, and robust validation.
|
||||
|
||||
**Location:** `libs/ui/datepicker/`
|
||||
|
||||
### `@isa/ui/dialog`
|
||||
A comprehensive dialog system for Angular applications built on Angular CDK Dialog with preset components for common use cases.
|
||||
|
||||
**Location:** `libs/ui/dialog/`
|
||||
|
||||
### `@isa/ui/empty-state`
|
||||
A standalone Angular component library providing consistent empty state displays for various scenarios (no results, no articles, all done, select action). Part of the ISA Design System.
|
||||
|
||||
**Location:** `libs/ui/empty-state/`
|
||||
|
||||
### `@isa/ui/expandable`
|
||||
A set of Angular directives for creating expandable/collapsible content sections with proper accessibility support.
|
||||
|
||||
**Location:** `libs/ui/expandable/`
|
||||
|
||||
### `@isa/ui/input-controls`
|
||||
A comprehensive collection of form input components and directives for Angular applications supporting reactive forms, template-driven forms, and accessibility features.
|
||||
|
||||
**Location:** `libs/ui/input-controls/`
|
||||
|
||||
### `@isa/ui/item-rows`
|
||||
A collection of reusable row components for displaying structured data with consistent layouts across Angular applications.
|
||||
|
||||
**Location:** `libs/ui/item-rows/`
|
||||
|
||||
### `@isa/ui/layout`
|
||||
This library provides utilities and directives for responsive design in Angular applications.
|
||||
|
||||
**Location:** `libs/ui/layout/`
|
||||
|
||||
### `@isa/ui/menu`
|
||||
A lightweight Angular component library providing accessible menu components built on Angular CDK Menu. Part of the ISA Design System.
|
||||
|
||||
**Location:** `libs/ui/menu/`
|
||||
|
||||
### `@isa/ui/progress-bar`
|
||||
A lightweight Angular progress bar component supporting both determinate and indeterminate modes.
|
||||
|
||||
**Location:** `libs/ui/progress-bar/`
|
||||
|
||||
### `@isa/ui/search-bar`
|
||||
A feature-rich Angular search bar component with integrated clear functionality and customizable appearance modes.
|
||||
|
||||
**Location:** `libs/ui/search-bar/`
|
||||
|
||||
### `@isa/ui/skeleton-loader`
|
||||
A lightweight Angular structural directive and component for displaying skeleton loading states during asynchronous operations.
|
||||
|
||||
**Location:** `libs/ui/skeleton-loader/`
|
||||
|
||||
### `@isa/ui/toolbar`
|
||||
A flexible toolbar container component for Angular applications with configurable sizing and content projection.
|
||||
|
||||
**Location:** `libs/ui/toolbar/`
|
||||
|
||||
### `@isa/ui/tooltip`
|
||||
A flexible tooltip library for Angular applications, built with Angular CDK overlays.
|
||||
|
||||
**Location:** `libs/ui/tooltip/`
|
||||
|
||||
---
|
||||
|
||||
## Utility Libraries (3 libraries)
|
||||
|
||||
### `@isa/utils/ean-validation`
|
||||
Lightweight Angular utility library for validating EAN (European Article Number) barcodes with reactive forms integration and standalone validation functions.
|
||||
|
||||
**Location:** `libs/utils/ean-validation/`
|
||||
|
||||
### `@isa/utils/scroll-position`
|
||||
## Overview
|
||||
|
||||
**Location:** `libs/utils/scroll-position/`
|
||||
|
||||
### `@isa/utils/z-safe-parse`
|
||||
A lightweight Zod utility library for safe parsing with automatic fallback to original values on validation failures.
|
||||
|
||||
**Location:** `libs/utils/z-safe-parse/`
|
||||
|
||||
---
|
||||
|
||||
## How to Use This Guide
|
||||
|
||||
1. **Quick Lookup**: Use this guide to find the purpose of any library in the monorepo
|
||||
2. **Detailed Documentation**: Always use the `docs-researcher` subagent to read the full README.md for implementation details
|
||||
3. **Path Resolution**: Use the location information to navigate to the library source code
|
||||
4. **Architecture Understanding**: Use `npx nx graph --filter=[library-name]` to visualize dependencies
|
||||
|
||||
---
|
||||
|
||||
## Maintenance Notes
|
||||
|
||||
This file should be updated when:
|
||||
- New libraries are added to the monorepo
|
||||
- Libraries are renamed or moved
|
||||
- Library purposes significantly change
|
||||
- Angular or Nx versions are upgraded
|
||||
|
||||
**Automation:** This file is auto-generated using `npm run docs:generate`. Run this command after adding or modifying libraries to keep the documentation up-to-date.
|
||||
@@ -37,6 +37,7 @@ export { Gender } from './models/gender';
|
||||
export { DateRangeDTO } from './models/date-range-dto';
|
||||
export { PaymentType } from './models/payment-type';
|
||||
export { PaymentStatus } from './models/payment-status';
|
||||
export { LoyaltyDTO } from './models/loyalty-dto';
|
||||
export { QueryTokenDTO } from './models/query-token-dto';
|
||||
export { ListResponseArgsOfOrderItemListItemDTO } from './models/list-response-args-of-order-item-list-item-dto';
|
||||
export { ResponseArgsOfIEnumerableOfOrderItemListItemDTO } from './models/response-args-of-ienumerable-of-order-item-list-item-dto';
|
||||
@@ -130,7 +131,6 @@ export { Price } from './models/price';
|
||||
export { ShippingTarget } from './models/shipping-target';
|
||||
export { EntityDTOBaseOfShopItemDTOAndIShopItem } from './models/entity-dtobase-of-shop-item-dtoand-ishop-item';
|
||||
export { CampaignDTO } from './models/campaign-dto';
|
||||
export { LoyaltyDTO } from './models/loyalty-dto';
|
||||
export { EntityDTOBaseOfOrderItemDTOAndIOrderItem } from './models/entity-dtobase-of-order-item-dtoand-iorder-item';
|
||||
export { EntityDTOContainerOfSupplierDTO } from './models/entity-dtocontainer-of-supplier-dto';
|
||||
export { SupplierDTO } from './models/supplier-dto';
|
||||
@@ -207,6 +207,8 @@ export { EntityDTOContainerOfOrderItemSubsetTransitionDTO } from './models/entit
|
||||
export { OrderItemSubsetTransitionDTO } from './models/order-item-subset-transition-dto';
|
||||
export { EntityDTOBaseOfOrderItemSubsetTransitionDTOAndIOrderItemStatusTransition } from './models/entity-dtobase-of-order-item-subset-transition-dtoand-iorder-item-status-transition';
|
||||
export { EntityDTOBaseOfOrderItemSubsetTaskDTOAndIOrderItemStatusTask } from './models/entity-dtobase-of-order-item-subset-task-dtoand-iorder-item-status-task';
|
||||
export { LoyaltyCollectValues } from './models/loyalty-collect-values';
|
||||
export { LoyaltyCollectType } from './models/loyalty-collect-type';
|
||||
export { ResponseArgsOfBoolean } from './models/response-args-of-boolean';
|
||||
export { ResponseArgsOfOrderItemDTO } from './models/response-args-of-order-item-dto';
|
||||
export { ResponseArgsOfIEnumerableOfOrderItemDTO } from './models/response-args-of-ienumerable-of-order-item-dto';
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
/* tslint:disable */
|
||||
import { EntityDTOBaseOfDisplayOrderItemDTOAndIOrderItem } from './entity-dtobase-of-display-order-item-dtoand-iorder-item';
|
||||
import { LoyaltyDTO } from './loyalty-dto';
|
||||
import { DisplayOrderDTO } from './display-order-dto';
|
||||
import { PriceDTO } from './price-dto';
|
||||
import { ProductDTO } from './product-dto';
|
||||
@@ -23,6 +24,11 @@ export interface DisplayOrderItemDTO extends EntityDTOBaseOfDisplayOrderItemDTOA
|
||||
*/
|
||||
features?: {[key: string]: string};
|
||||
|
||||
/**
|
||||
* Loylty
|
||||
*/
|
||||
loyalty?: LoyaltyDTO;
|
||||
|
||||
/**
|
||||
* Bestellung
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
/* tslint:disable */
|
||||
export type LoyaltyCollectType = 0 | 1 | 2;
|
||||
@@ -0,0 +1,18 @@
|
||||
/* tslint:disable */
|
||||
import { LoyaltyCollectType } from './loyalty-collect-type';
|
||||
|
||||
/**
|
||||
* Loyalty collect values
|
||||
*/
|
||||
export interface LoyaltyCollectValues {
|
||||
|
||||
/**
|
||||
* Collect Type
|
||||
*/
|
||||
collectType: LoyaltyCollectType;
|
||||
|
||||
/**
|
||||
* Quantity (optional, default null)
|
||||
*/
|
||||
quantity?: number;
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { EnvironmentChannel } from './environment-channel';
|
||||
import { CRUDA } from './cruda';
|
||||
import { DateRangeDTO } from './date-range-dto';
|
||||
import { Gender } from './gender';
|
||||
import { LoyaltyDTO } from './loyalty-dto';
|
||||
import { OrderType } from './order-type';
|
||||
import { PaymentStatus } from './payment-status';
|
||||
import { PaymentType } from './payment-type';
|
||||
@@ -102,6 +103,11 @@ export interface OrderItemListItemDTO {
|
||||
*/
|
||||
lastName?: string;
|
||||
|
||||
/**
|
||||
* Loylty
|
||||
*/
|
||||
loyalty?: LoyaltyDTO;
|
||||
|
||||
/**
|
||||
* Bestellfiliale
|
||||
*/
|
||||
|
||||
@@ -1,12 +1,19 @@
|
||||
/* tslint:disable */
|
||||
import { EntityReferenceDTO } from './entity-reference-dto';
|
||||
import { KeyValueDTOOfStringAndString } from './key-value-dtoof-string-and-string';
|
||||
import { CRUDA } from './cruda';
|
||||
import { PriceDTO } from './price-dto';
|
||||
import { LoyaltyDTO } from './loyalty-dto';
|
||||
import { ProductDTO } from './product-dto';
|
||||
import { PromotionDTO } from './promotion-dto';
|
||||
import { QuantityDTO } from './quantity-dto';
|
||||
import { ReceiptListItemDTO } from './receipt-list-item-dto';
|
||||
export interface ReceiptItemListItemDTO extends EntityReferenceDTO{
|
||||
|
||||
/**
|
||||
* Mögliche Aktionen
|
||||
*/
|
||||
actions?: Array<KeyValueDTOOfStringAndString>;
|
||||
buyerComment?: string;
|
||||
|
||||
/**
|
||||
@@ -19,6 +26,11 @@ export interface ReceiptItemListItemDTO extends EntityReferenceDTO{
|
||||
*/
|
||||
discountedPrice?: PriceDTO;
|
||||
|
||||
/**
|
||||
* Zusätzliche Markierungen
|
||||
*/
|
||||
features?: {[key: string]: string};
|
||||
|
||||
/**
|
||||
* PK
|
||||
*/
|
||||
@@ -35,6 +47,11 @@ export interface ReceiptItemListItemDTO extends EntityReferenceDTO{
|
||||
*/
|
||||
lineNumber?: number;
|
||||
|
||||
/**
|
||||
* Loyalty
|
||||
*/
|
||||
loyalty?: LoyaltyDTO;
|
||||
|
||||
/**
|
||||
* Bestellnummer
|
||||
*/
|
||||
|
||||
@@ -21,6 +21,8 @@ import { ResponseArgsOfQuerySettingsDTO } from '../models/response-args-of-query
|
||||
import { ResponseArgsOfIEnumerableOfAutocompleteDTO } from '../models/response-args-of-ienumerable-of-autocomplete-dto';
|
||||
import { AutocompleteTokenDTO } from '../models/autocomplete-token-dto';
|
||||
import { ListResponseArgsOfDBHOrderItemListItemDTO } from '../models/list-response-args-of-dbhorder-item-list-item-dto';
|
||||
import { ResponseArgsOfIEnumerableOfDBHOrderItemListItemDTO } from '../models/response-args-of-ienumerable-of-dbhorder-item-list-item-dto';
|
||||
import { LoyaltyCollectValues } from '../models/loyalty-collect-values';
|
||||
import { ListResponseArgsOfOrderItemListItemDTO } from '../models/list-response-args-of-order-item-list-item-dto';
|
||||
import { ResponseArgsOfIEnumerableOfOrderItemDTO } from '../models/response-args-of-ienumerable-of-order-item-dto';
|
||||
import { OrderItemDTO } from '../models/order-item-dto';
|
||||
@@ -54,6 +56,7 @@ class OrderService extends __BaseService {
|
||||
static readonly OrderKundenbestellungenSettingsPath = '/kundenbestellungen/s/settings';
|
||||
static readonly OrderKundenbestellungenAutocompletePath = '/kundenbestellungen/s/complete';
|
||||
static readonly OrderKundenbestellungenPath = '/kundenbestellungen/s';
|
||||
static readonly OrderLoyaltyCollectPath = '/order/{orderId}/orderitem/{orderItemId}/orderitemsubset/{orderItemSubsetId}/loyaltycollect';
|
||||
static readonly OrderQueryOrderItemPath = '/order/item/s';
|
||||
static readonly OrderQueryOrderItemAutocompletePath = '/order/item/s/complete';
|
||||
static readonly OrderGetOrderItemPath = '/order/orderitem/{orderItemId}';
|
||||
@@ -636,6 +639,63 @@ class OrderService extends __BaseService {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ausgabe order Storno von Prämienbestellposten
|
||||
* Falls die Menge/Stückzahl kleiner der ursprünglichen Menge/Stückzahl ist, wird eine neue Bestellpostenteilmenge erzeugt.
|
||||
* @param params The `OrderService.OrderLoyaltyCollectParams` containing the following parameters:
|
||||
*
|
||||
* - `orderItemSubsetId`: PK Bestellpostenteilmenge
|
||||
*
|
||||
* - `orderItemId`: PK Bestellposten
|
||||
*
|
||||
* - `orderId`: PK Bestellung
|
||||
*
|
||||
* - `data`: Daten zur Änderung des Bearbeitungsstatus
|
||||
*/
|
||||
OrderLoyaltyCollectResponse(params: OrderService.OrderLoyaltyCollectParams): __Observable<__StrictHttpResponse<ResponseArgsOfIEnumerableOfDBHOrderItemListItemDTO>> {
|
||||
let __params = this.newParams();
|
||||
let __headers = new HttpHeaders();
|
||||
let __body: any = null;
|
||||
|
||||
|
||||
|
||||
__body = params.data;
|
||||
let req = new HttpRequest<any>(
|
||||
'POST',
|
||||
this.rootUrl + `/order/${encodeURIComponent(String(params.orderId))}/orderitem/${encodeURIComponent(String(params.orderItemId))}/orderitemsubset/${encodeURIComponent(String(params.orderItemSubsetId))}/loyaltycollect`,
|
||||
__body,
|
||||
{
|
||||
headers: __headers,
|
||||
params: __params,
|
||||
responseType: 'json'
|
||||
});
|
||||
|
||||
return this.http.request<any>(req).pipe(
|
||||
__filter(_r => _r instanceof HttpResponse),
|
||||
__map((_r) => {
|
||||
return _r as __StrictHttpResponse<ResponseArgsOfIEnumerableOfDBHOrderItemListItemDTO>;
|
||||
})
|
||||
);
|
||||
}
|
||||
/**
|
||||
* Ausgabe order Storno von Prämienbestellposten
|
||||
* Falls die Menge/Stückzahl kleiner der ursprünglichen Menge/Stückzahl ist, wird eine neue Bestellpostenteilmenge erzeugt.
|
||||
* @param params The `OrderService.OrderLoyaltyCollectParams` containing the following parameters:
|
||||
*
|
||||
* - `orderItemSubsetId`: PK Bestellpostenteilmenge
|
||||
*
|
||||
* - `orderItemId`: PK Bestellposten
|
||||
*
|
||||
* - `orderId`: PK Bestellung
|
||||
*
|
||||
* - `data`: Daten zur Änderung des Bearbeitungsstatus
|
||||
*/
|
||||
OrderLoyaltyCollect(params: OrderService.OrderLoyaltyCollectParams): __Observable<ResponseArgsOfIEnumerableOfDBHOrderItemListItemDTO> {
|
||||
return this.OrderLoyaltyCollectResponse(params).pipe(
|
||||
__map(_r => _r.body as ResponseArgsOfIEnumerableOfDBHOrderItemListItemDTO)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Suche nach Bestellposten
|
||||
* @param queryToken Suchkriterien
|
||||
@@ -1671,6 +1731,32 @@ module OrderService {
|
||||
buyerNumber?: null | string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parameters for OrderLoyaltyCollect
|
||||
*/
|
||||
export interface OrderLoyaltyCollectParams {
|
||||
|
||||
/**
|
||||
* PK Bestellpostenteilmenge
|
||||
*/
|
||||
orderItemSubsetId: number;
|
||||
|
||||
/**
|
||||
* PK Bestellposten
|
||||
*/
|
||||
orderItemId: number;
|
||||
|
||||
/**
|
||||
* PK Bestellung
|
||||
*/
|
||||
orderId: number;
|
||||
|
||||
/**
|
||||
* Daten zur Änderung des Bearbeitungsstatus
|
||||
*/
|
||||
data: LoyaltyCollectValues;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parameters for OrderUpdateOrderItem
|
||||
*/
|
||||
|
||||
@@ -236,6 +236,7 @@ class ReceiptService extends __BaseService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Aufgabe auf erledigt setzen
|
||||
* @param taskId undefined
|
||||
*/
|
||||
ReceiptReceiptItemTaskCompletedResponse(taskId: number): __Observable<__StrictHttpResponse<ResponseArgsOfReceiptItemTaskListItemDTO>> {
|
||||
@@ -261,6 +262,7 @@ class ReceiptService extends __BaseService {
|
||||
);
|
||||
}
|
||||
/**
|
||||
* Aufgabe auf erledigt setzen
|
||||
* @param taskId undefined
|
||||
*/
|
||||
ReceiptReceiptItemTaskCompleted(taskId: number): __Observable<ResponseArgsOfReceiptItemTaskListItemDTO> {
|
||||
|
||||
8399
graph.json
Normal file
8399
graph.json
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,980 @@
|
||||
# availability-data-access
|
||||
# @isa/availability/data-access
|
||||
|
||||
This library was generated with [Nx](https://nx.dev).
|
||||
A comprehensive product availability service for Angular applications supporting multiple order types and delivery methods across retail operations.
|
||||
|
||||
## Running unit tests
|
||||
## Overview
|
||||
|
||||
Run `nx test availability-data-access` to execute the unit tests.
|
||||
The Availability Data Access library provides a unified interface for checking product availability across six different order types: in-store pickup (Rücklage), customer pickup (Abholung), standard shipping (Versand), digital shipping (DIG-Versand), B2B shipping (B2B-Versand), and digital downloads (Download). It integrates with the generated availability API client and provides intelligent routing, validation, and transformation of availability data.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Features](#features)
|
||||
- [Quick Start](#quick-start)
|
||||
- [Core Concepts](#core-concepts)
|
||||
- [API Reference](#api-reference)
|
||||
- [Usage Examples](#usage-examples)
|
||||
- [Order Types](#order-types)
|
||||
- [Validation and Business Rules](#validation-and-business-rules)
|
||||
- [Error Handling](#error-handling)
|
||||
- [Testing](#testing)
|
||||
- [Architecture Notes](#architecture-notes)
|
||||
|
||||
## Features
|
||||
|
||||
- **Six order type support** - InStore, Pickup, Delivery, DIG-Versand, B2B-Versand, Download
|
||||
- **Intelligent routing** - Automatic endpoint selection based on order type
|
||||
- **Zod validation** - Runtime schema validation for all parameters
|
||||
- **Request cancellation** - AbortSignal support for all operations
|
||||
- **Batch and single-item APIs** - Flexible interfaces for different use cases
|
||||
- **Preferred availability selection** - Automatic selection of preferred suppliers
|
||||
- **Business rule enforcement** - Download validation, B2B logistician override
|
||||
- **Type-safe transformations** - Adapter pattern for API request/response mapping
|
||||
- **Comprehensive logging** - Integration with @isa/core/logging for debugging
|
||||
- **Stock integration** - Direct stock service integration for in-store availability
|
||||
|
||||
## Quick Start
|
||||
|
||||
### 1. Import and Inject
|
||||
|
||||
```typescript
|
||||
import { Component, inject } from '@angular/core';
|
||||
import { AvailabilityService } from '@isa/availability/data-access';
|
||||
|
||||
@Component({
|
||||
selector: 'app-product-detail',
|
||||
template: '...'
|
||||
})
|
||||
export class ProductDetailComponent {
|
||||
#availabilityService = inject(AvailabilityService);
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Check Availability for Multiple Items
|
||||
|
||||
```typescript
|
||||
async checkAvailability(): Promise<void> {
|
||||
const availabilities = await this.#availabilityService.getAvailabilities({
|
||||
orderType: 'Versand',
|
||||
items: [
|
||||
{ itemId: 123, ean: '1234567890123', quantity: 2 },
|
||||
{ itemId: 456, ean: '9876543210987', quantity: 1 }
|
||||
]
|
||||
});
|
||||
|
||||
// Result: { '123': Availability, '456': Availability }
|
||||
const item123Availability = availabilities['123'];
|
||||
console.log(`Item 123 status: ${item123Availability.status}`);
|
||||
console.log(`Item 123 quantity: ${item123Availability.qty}`);
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Check Availability for Single Item
|
||||
|
||||
```typescript
|
||||
async checkSingleItem(): Promise<void> {
|
||||
const availability = await this.#availabilityService.getAvailability({
|
||||
orderType: 'Versand',
|
||||
item: { itemId: 123, ean: '1234567890123', quantity: 1 }
|
||||
});
|
||||
|
||||
if (availability) {
|
||||
console.log(`Available: ${availability.qty} units`);
|
||||
console.log(`Price: ${availability.price?.value?.value}`);
|
||||
} else {
|
||||
console.log('Item not available');
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 4. Request Cancellation
|
||||
|
||||
```typescript
|
||||
async checkWithCancellation(): Promise<void> {
|
||||
const abortController = new AbortController();
|
||||
|
||||
// Cancel after 5 seconds
|
||||
setTimeout(() => abortController.abort(), 5000);
|
||||
|
||||
try {
|
||||
const availabilities = await this.#availabilityService.getAvailabilities(
|
||||
{
|
||||
orderType: 'Versand',
|
||||
items: [{ itemId: 123, ean: '1234567890123', quantity: 1 }]
|
||||
},
|
||||
abortController.signal
|
||||
);
|
||||
} catch (error) {
|
||||
console.log('Request cancelled or failed');
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Core Concepts
|
||||
|
||||
### Order Types
|
||||
|
||||
The library supports six distinct order types, each with specific requirements and behavior:
|
||||
|
||||
#### 1. InStore (Rücklage)
|
||||
- **Purpose**: Branch-based in-store availability for customer reservation
|
||||
- **Endpoint**: Stock service (not availability API)
|
||||
- **Required**: branchId, itemsIds array
|
||||
- **Special handling**: Uses RemissionStockService to fetch real-time stock quantities
|
||||
|
||||
#### 2. Pickup (Abholung)
|
||||
- **Purpose**: Customer pickup at branch location
|
||||
- **Endpoint**: Store availability API
|
||||
- **Required**: branchId, items array with itemId, ean, quantity
|
||||
- **Special handling**: Uses store endpoint with branch context
|
||||
|
||||
#### 3. Delivery (Versand)
|
||||
- **Purpose**: Standard shipping to customer address
|
||||
- **Endpoint**: Shipping availability API
|
||||
- **Required**: items array with itemId, ean, quantity
|
||||
- **Special handling**: Excludes supplier/logistician fields to prevent automatic orderType change
|
||||
|
||||
#### 4. DIG-Versand
|
||||
- **Purpose**: Digital shipping for webshop customers
|
||||
- **Endpoint**: Shipping availability API
|
||||
- **Required**: items array with itemId, ean, quantity
|
||||
- **Special handling**: Standard transformation, includes supplier/logistician
|
||||
|
||||
#### 5. B2B-Versand
|
||||
- **Purpose**: Business-to-business shipping with specific logistician
|
||||
- **Endpoint**: Store availability API
|
||||
- **Required**: items array with itemId, ean, quantity
|
||||
- **Special handling**:
|
||||
- Automatically fetches default branch (no branchId parameter needed)
|
||||
- Fetches logistician '2470' and overrides response logisticianId
|
||||
- Uses store endpoint (not shipping)
|
||||
|
||||
#### 6. Download
|
||||
- **Purpose**: Digital product downloads
|
||||
- **Endpoint**: Shipping availability API
|
||||
- **Required**: items array with itemId, ean (no quantity)
|
||||
- **Special handling**:
|
||||
- Quantity forced to 1
|
||||
- Validates download availability (supplier 16 with 0 stock = unavailable)
|
||||
- Validates status codes against whitelist
|
||||
|
||||
### Availability Response Structure
|
||||
|
||||
```typescript
|
||||
interface Availability {
|
||||
itemId: number; // Product item ID
|
||||
status: AvailabilityType; // Availability status code (see below)
|
||||
qty: number; // Available quantity
|
||||
ssc?: string; // Shipping service code
|
||||
sscText?: string; // Shipping service description
|
||||
supplierId?: number; // Supplier ID
|
||||
supplier?: string; // Supplier name
|
||||
logisticianId?: number; // Logistician ID
|
||||
logistician?: string; // Logistician name
|
||||
price?: Price; // Current price with VAT
|
||||
priceMaintained?: boolean; // Price maintenance flag
|
||||
at?: string; // Estimated delivery date (ISO format)
|
||||
altAt?: string; // Alternative delivery date
|
||||
requestStatusCode?: string; // Request status from API
|
||||
preferred?: number; // Preferred availability flag (1 = preferred)
|
||||
}
|
||||
```
|
||||
|
||||
### Availability Type Codes
|
||||
|
||||
```typescript
|
||||
const AvailabilityType = {
|
||||
NotSet: 0, // Not determined
|
||||
NotAvailable: 1, // Not available
|
||||
PrebookAtBuyer: 2, // Pre-order at buyer
|
||||
PrebookAtRetailer: 32, // Pre-order at retailer
|
||||
PrebookAtSupplier: 256, // Pre-order at supplier
|
||||
TemporaryNotAvailable: 512, // Temporarily unavailable
|
||||
Available: 1024, // Available for immediate delivery
|
||||
OnDemand: 2048, // Available on demand
|
||||
AtProductionDate: 4096, // Available at production date
|
||||
Discontinued: 8192, // Discontinued product
|
||||
EndOfLife: 16384, // End of life product
|
||||
};
|
||||
```
|
||||
|
||||
### Validation with Zod
|
||||
|
||||
All input parameters are validated using Zod schemas before processing:
|
||||
|
||||
```typescript
|
||||
// Example: Delivery availability params
|
||||
const params = {
|
||||
orderType: 'Versand',
|
||||
items: [
|
||||
{
|
||||
itemId: '123', // Coerced to number
|
||||
ean: '1234567890123',
|
||||
quantity: '2', // Coerced to number
|
||||
price: { ... }
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
// Validation happens automatically
|
||||
const result = await service.getAvailabilities(params);
|
||||
// Throws ZodError if validation fails
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
### AvailabilityService
|
||||
|
||||
Main service for checking product availability across order types.
|
||||
|
||||
#### `getAvailabilities(params, abortSignal?): Promise<{ [itemId: string]: Availability }>`
|
||||
|
||||
Checks availability for multiple items based on order type.
|
||||
|
||||
**Parameters:**
|
||||
- `params: GetAvailabilityInputParams` - Availability parameters (automatically validated)
|
||||
- `abortSignal?: AbortSignal` - Optional abort signal for request cancellation
|
||||
|
||||
**Returns:** Promise resolving to dictionary mapping itemId to Availability
|
||||
|
||||
**Throws:**
|
||||
- `ZodError` - If params validation fails
|
||||
- `ResponseArgsError` - If API returns an error
|
||||
- `Error` - If default branch/logistician not found (B2B only)
|
||||
|
||||
**Example:**
|
||||
```typescript
|
||||
const availabilities = await service.getAvailabilities({
|
||||
orderType: 'Versand',
|
||||
items: [
|
||||
{ itemId: 123, ean: '1234567890', quantity: 2 },
|
||||
{ itemId: 456, ean: '0987654321', quantity: 1 }
|
||||
]
|
||||
});
|
||||
|
||||
// Result: { '123': Availability, '456': Availability }
|
||||
```
|
||||
|
||||
#### `getAvailability(params, abortSignal?): Promise<Availability | undefined>`
|
||||
|
||||
Checks availability for a single item.
|
||||
|
||||
**Parameters:**
|
||||
- `params: GetSingleItemAvailabilityInputParams` - Single item parameters (automatically validated)
|
||||
- `abortSignal?: AbortSignal` - Optional abort signal for request cancellation
|
||||
|
||||
**Returns:** Promise resolving to Availability, or undefined if not available
|
||||
|
||||
**Throws:**
|
||||
- `ZodError` - If params validation fails
|
||||
- `ResponseArgsError` - If API returns an error
|
||||
|
||||
**Example:**
|
||||
```typescript
|
||||
const availability = await service.getAvailability({
|
||||
orderType: 'Versand',
|
||||
item: { itemId: 123, ean: '1234567890', quantity: 1 }
|
||||
});
|
||||
|
||||
if (availability) {
|
||||
console.log(`Available: ${availability.qty} units`);
|
||||
}
|
||||
```
|
||||
|
||||
### AvailabilityFacade
|
||||
|
||||
Pass-through facade for AvailabilityService.
|
||||
|
||||
**Note**: This facade is currently under architectural review. It provides no additional value over direct service injection and may be removed in a future refactoring. Consider injecting `AvailabilityService` directly.
|
||||
|
||||
```typescript
|
||||
// Current pattern (via facade)
|
||||
#availabilityFacade = inject(AvailabilityFacade);
|
||||
|
||||
// Recommended pattern (direct service)
|
||||
#availabilityService = inject(AvailabilityService);
|
||||
```
|
||||
|
||||
### Helper Functions
|
||||
|
||||
#### `isDownloadAvailable(availability): boolean`
|
||||
|
||||
Validates if a download item is available based on business rules.
|
||||
|
||||
**Business Rules:**
|
||||
- Supplier ID 16 with 0 stock = unavailable
|
||||
- Must have valid availability type code (see VALID_DOWNLOAD_STATUS_CODES)
|
||||
|
||||
**Parameters:**
|
||||
- `availability: Availability | null | undefined` - Availability to validate
|
||||
|
||||
**Returns:** true if download is available, false otherwise
|
||||
|
||||
**Example:**
|
||||
```typescript
|
||||
import { isDownloadAvailable } from '@isa/availability/data-access';
|
||||
|
||||
if (isDownloadAvailable(availability)) {
|
||||
console.log('Download ready');
|
||||
}
|
||||
```
|
||||
|
||||
#### `selectPreferredAvailability(availabilities): Availability | undefined`
|
||||
|
||||
Selects the preferred availability from a list (marked with `preferred === 1`).
|
||||
|
||||
**Parameters:**
|
||||
- `availabilities: Availability[]` - List of availability options
|
||||
|
||||
**Returns:** The preferred availability, or undefined if none found
|
||||
|
||||
**Example:**
|
||||
```typescript
|
||||
import { selectPreferredAvailability } from '@isa/availability/data-access';
|
||||
|
||||
const preferred = selectPreferredAvailability(apiResponse);
|
||||
```
|
||||
|
||||
#### `calculateEstimatedDate(availability): string | undefined`
|
||||
|
||||
Calculates the estimated shipping/delivery date based on API response.
|
||||
|
||||
**Business Rule:**
|
||||
- If requestStatusCode === '32', use altAt (alternative date)
|
||||
- Otherwise, use at (standard date)
|
||||
|
||||
**Parameters:**
|
||||
- `availability: Availability | null | undefined` - Availability data
|
||||
|
||||
**Returns:** The estimated date string (ISO format), or undefined
|
||||
|
||||
**Example:**
|
||||
```typescript
|
||||
import { calculateEstimatedDate } from '@isa/availability/data-access';
|
||||
|
||||
const estimatedDate = calculateEstimatedDate(availability);
|
||||
console.log(`Delivery expected: ${estimatedDate}`);
|
||||
```
|
||||
|
||||
#### `hasValidPrice(availability): boolean`
|
||||
|
||||
Type guard to check if an availability has a valid price.
|
||||
|
||||
**Parameters:**
|
||||
- `availability: Availability | null | undefined` - Availability to check
|
||||
|
||||
**Returns:** true if availability has a price with a value > 0
|
||||
|
||||
**Example:**
|
||||
```typescript
|
||||
import { hasValidPrice } from '@isa/availability/data-access';
|
||||
|
||||
if (hasValidPrice(availability)) {
|
||||
// TypeScript narrows type - price is guaranteed to exist
|
||||
console.log(`Price: ${availability.price.value.value}`);
|
||||
}
|
||||
```
|
||||
|
||||
#### `isPriceMaintained(availability): boolean`
|
||||
|
||||
Checks if an availability is price-maintained.
|
||||
|
||||
**Parameters:**
|
||||
- `availability: Availability | null | undefined` - Availability to check
|
||||
|
||||
**Returns:** true if price-maintained flag is set
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Checking In-Store Availability (Rücklage)
|
||||
|
||||
```typescript
|
||||
import { Component, inject } from '@angular/core';
|
||||
import { AvailabilityService } from '@isa/availability/data-access';
|
||||
|
||||
@Component({
|
||||
selector: 'app-in-store-check',
|
||||
template: '...'
|
||||
})
|
||||
export class InStoreCheckComponent {
|
||||
#availabilityService = inject(AvailabilityService);
|
||||
|
||||
async checkInStoreAvailability(branchId: number, itemIds: number[]): Promise<void> {
|
||||
const availabilities = await this.#availabilityService.getAvailabilities({
|
||||
orderType: 'Rücklage',
|
||||
branchId: branchId,
|
||||
itemsIds: itemIds
|
||||
});
|
||||
|
||||
for (const [itemId, availability] of Object.entries(availabilities)) {
|
||||
console.log(`Item ${itemId}: ${availability.qty} in stock`);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Checking Pickup Availability (Abholung)
|
||||
|
||||
```typescript
|
||||
async checkPickupAvailability(branchId: number): Promise<void> {
|
||||
const availabilities = await this.#availabilityService.getAvailabilities({
|
||||
orderType: 'Abholung',
|
||||
branchId: branchId,
|
||||
items: [
|
||||
{ itemId: 123, ean: '1234567890', quantity: 2 },
|
||||
{ itemId: 456, ean: '0987654321', quantity: 1 }
|
||||
]
|
||||
});
|
||||
|
||||
// Check if items are available for pickup
|
||||
for (const [itemId, availability] of Object.entries(availabilities)) {
|
||||
if (availability.status === AvailabilityType.Available) {
|
||||
console.log(`Item ${itemId} ready for pickup at branch ${branchId}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Checking Standard Delivery (Versand)
|
||||
|
||||
```typescript
|
||||
import { AvailabilityType, calculateEstimatedDate } from '@isa/availability/data-access';
|
||||
|
||||
async checkDeliveryAvailability(): Promise<void> {
|
||||
const availabilities = await this.#availabilityService.getAvailabilities({
|
||||
orderType: 'Versand',
|
||||
items: [
|
||||
{
|
||||
itemId: 123,
|
||||
ean: '1234567890',
|
||||
quantity: 1,
|
||||
price: {
|
||||
value: { value: 19.99, currency: 'EUR', currencySymbol: '€' },
|
||||
vat: { value: 3.18, inPercent: 19, label: '19%', vatType: 1 }
|
||||
}
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
const item123 = availabilities['123'];
|
||||
if (item123) {
|
||||
const estimatedDate = calculateEstimatedDate(item123);
|
||||
console.log(`Available for delivery: ${item123.qty} units`);
|
||||
console.log(`Estimated delivery: ${estimatedDate}`);
|
||||
console.log(`Supplier: ${item123.supplier} (ID: ${item123.supplierId})`);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Checking B2B Delivery (B2B-Versand)
|
||||
|
||||
```typescript
|
||||
async checkB2BDelivery(): Promise<void> {
|
||||
// No branchId required - automatically uses default branch
|
||||
// Logistician '2470' is automatically fetched and applied
|
||||
const availabilities = await this.#availabilityService.getAvailabilities({
|
||||
orderType: 'B2B-Versand',
|
||||
items: [
|
||||
{ itemId: 123, ean: '1234567890', quantity: 10 }
|
||||
]
|
||||
});
|
||||
|
||||
const item123 = availabilities['123'];
|
||||
if (item123) {
|
||||
console.log(`B2B availability: ${item123.qty} units`);
|
||||
console.log(`Logistician: ${item123.logisticianId} (overridden to 2470)`);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Checking Download Availability
|
||||
|
||||
```typescript
|
||||
import { isDownloadAvailable } from '@isa/availability/data-access';
|
||||
|
||||
async checkDownloadAvailability(): Promise<void> {
|
||||
const availabilities = await this.#availabilityService.getAvailabilities({
|
||||
orderType: 'Download',
|
||||
items: [
|
||||
{ itemId: 123, ean: '1234567890' } // No quantity needed
|
||||
]
|
||||
});
|
||||
|
||||
const item123 = availabilities['123'];
|
||||
if (item123 && isDownloadAvailable(item123)) {
|
||||
console.log('Download ready for immediate delivery');
|
||||
} else {
|
||||
console.log('Download not available');
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Single Item with AbortSignal
|
||||
|
||||
```typescript
|
||||
async checkSingleItemWithTimeout(): Promise<void> {
|
||||
const abortController = new AbortController();
|
||||
|
||||
// Set 10 second timeout
|
||||
const timeoutId = setTimeout(() => {
|
||||
abortController.abort();
|
||||
}, 10000);
|
||||
|
||||
try {
|
||||
const availability = await this.#availabilityService.getAvailability(
|
||||
{
|
||||
orderType: 'Versand',
|
||||
item: { itemId: 123, ean: '1234567890', quantity: 1 }
|
||||
},
|
||||
abortController.signal
|
||||
);
|
||||
|
||||
clearTimeout(timeoutId);
|
||||
|
||||
if (availability) {
|
||||
console.log(`Item available: ${availability.qty} units`);
|
||||
}
|
||||
} catch (error) {
|
||||
clearTimeout(timeoutId);
|
||||
console.error('Request failed or timed out', error);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Handling Multiple Order Types
|
||||
|
||||
```typescript
|
||||
import { OrderType } from '@isa/checkout/data-access';
|
||||
|
||||
async checkMultipleOrderTypes(
|
||||
orderType: OrderType,
|
||||
items: Array<{ itemId: number; ean: string; quantity: number }>
|
||||
): Promise<void> {
|
||||
let params: GetAvailabilityInputParams;
|
||||
|
||||
switch (orderType) {
|
||||
case 'Rücklage':
|
||||
params = {
|
||||
orderType: 'Rücklage',
|
||||
branchId: this.selectedBranchId,
|
||||
itemsIds: items.map(i => i.itemId)
|
||||
};
|
||||
break;
|
||||
case 'Abholung':
|
||||
params = {
|
||||
orderType: 'Abholung',
|
||||
branchId: this.selectedBranchId,
|
||||
items: items
|
||||
};
|
||||
break;
|
||||
case 'Versand':
|
||||
case 'DIG-Versand':
|
||||
params = {
|
||||
orderType: orderType,
|
||||
items: items
|
||||
};
|
||||
break;
|
||||
case 'B2B-Versand':
|
||||
params = {
|
||||
orderType: 'B2B-Versand',
|
||||
items: items
|
||||
};
|
||||
break;
|
||||
case 'Download':
|
||||
params = {
|
||||
orderType: 'Download',
|
||||
items: items.map(i => ({ itemId: i.itemId, ean: i.ean }))
|
||||
};
|
||||
break;
|
||||
}
|
||||
|
||||
const availabilities = await this.#availabilityService.getAvailabilities(params);
|
||||
|
||||
console.log(`${orderType} availability:`, availabilities);
|
||||
}
|
||||
```
|
||||
|
||||
## Order Types
|
||||
|
||||
### Parameter Requirements by Order Type
|
||||
|
||||
| Order Type | Required Parameters | Optional | Notes |
|
||||
|------------|-------------------|----------|-------|
|
||||
| **Rücklage** (InStore) | `orderType`, `itemsIds` | `branchId` | Uses stock service |
|
||||
| **Abholung** (Pickup) | `orderType`, `branchId`, `items` | - | Store endpoint |
|
||||
| **Versand** (Delivery) | `orderType`, `items` | - | Shipping endpoint, excludes supplier/logistician |
|
||||
| **DIG-Versand** | `orderType`, `items` | - | Shipping endpoint |
|
||||
| **B2B-Versand** | `orderType`, `items` | - | Fetches default branch + logistician 2470 |
|
||||
| **Download** | `orderType`, `items` (no quantity) | - | Quantity forced to 1, validation applied |
|
||||
|
||||
### Item Structure by Order Type
|
||||
|
||||
#### InStore (Rücklage)
|
||||
```typescript
|
||||
{
|
||||
orderType: 'Rücklage',
|
||||
branchId?: number, // Optional branch ID
|
||||
itemsIds: number[] // Array of item IDs only
|
||||
}
|
||||
```
|
||||
|
||||
#### Pickup, Delivery, DIG-Versand, B2B-Versand
|
||||
```typescript
|
||||
{
|
||||
orderType: 'Abholung' | 'Versand' | 'DIG-Versand' | 'B2B-Versand',
|
||||
branchId?: number, // Required only for Abholung
|
||||
items: Array<{
|
||||
itemId: number,
|
||||
ean: string,
|
||||
quantity: number,
|
||||
price?: Price // Optional price information
|
||||
}>
|
||||
}
|
||||
```
|
||||
|
||||
#### Download
|
||||
```typescript
|
||||
{
|
||||
orderType: 'Download',
|
||||
items: Array<{
|
||||
itemId: number,
|
||||
ean: string,
|
||||
price?: Price // Optional price information
|
||||
// No quantity field - always 1
|
||||
}>
|
||||
}
|
||||
```
|
||||
|
||||
## Validation and Business Rules
|
||||
|
||||
### Zod Schema Validation
|
||||
|
||||
All parameters are validated using Zod schemas before processing:
|
||||
|
||||
**Type Coercion:**
|
||||
```typescript
|
||||
// String to number coercion
|
||||
{ itemId: '123' } → { itemId: 123 }
|
||||
{ quantity: '2' } → { quantity: 2 }
|
||||
|
||||
// Validation requirements
|
||||
itemId: z.coerce.number().int().positive() // Must be positive integer
|
||||
quantity: z.coerce.number().int().positive().default(1) // Positive with default
|
||||
ean: z.string() // Required string
|
||||
```
|
||||
|
||||
**Minimum Array Lengths:**
|
||||
```typescript
|
||||
items: z.array(ItemSchema).min(1) // At least 1 item required
|
||||
itemsIds: z.array(z.coerce.number()).min(1) // At least 1 ID required
|
||||
```
|
||||
|
||||
### Download Validation Rules
|
||||
|
||||
Downloads have special validation requirements enforced by `isDownloadAvailable()`:
|
||||
|
||||
1. **Supplier 16 with 0 stock = unavailable**
|
||||
```typescript
|
||||
if (availability.supplierId === 16 && availability.qty === 0) {
|
||||
return false; // Not available
|
||||
}
|
||||
```
|
||||
|
||||
2. **Valid status codes for downloads**
|
||||
```typescript
|
||||
const VALID_CODES = [
|
||||
AvailabilityType.PrebookAtBuyer, // 2
|
||||
AvailabilityType.PrebookAtRetailer, // 32
|
||||
AvailabilityType.PrebookAtSupplier, // 256
|
||||
AvailabilityType.Available, // 1024
|
||||
AvailabilityType.OnDemand, // 2048
|
||||
AvailabilityType.AtProductionDate // 4096
|
||||
];
|
||||
```
|
||||
|
||||
### B2B Special Handling
|
||||
|
||||
B2B-Versand has unique requirements:
|
||||
|
||||
1. **Automatic default branch fetching**
|
||||
- No branchId parameter required
|
||||
- Service automatically fetches default branch via `BranchService`
|
||||
- Throws error if default branch has no ID
|
||||
|
||||
2. **Logistician 2470 override**
|
||||
- Automatically fetches logistician '2470'
|
||||
- Overrides all availability responses with this logisticianId
|
||||
- Throws error if logistician 2470 not found
|
||||
|
||||
3. **Store endpoint usage**
|
||||
- Uses store availability endpoint (not shipping)
|
||||
- Similar to Pickup but with automatic branch selection
|
||||
|
||||
### Preferred Availability Selection
|
||||
|
||||
When multiple availability options exist for an item:
|
||||
|
||||
```typescript
|
||||
// API might return multiple availabilities per item
|
||||
// The service automatically selects the preferred one
|
||||
const preferred = availabilities.find(av => av.preferred === 1);
|
||||
```
|
||||
|
||||
Only the preferred availability is included in the result dictionary.
|
||||
|
||||
## Error Handling
|
||||
|
||||
### Error Types
|
||||
|
||||
#### ZodError
|
||||
Thrown when input parameters fail validation:
|
||||
|
||||
```typescript
|
||||
try {
|
||||
await service.getAvailabilities({
|
||||
orderType: 'Versand',
|
||||
items: [] // Empty array - fails min(1) validation
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof ZodError) {
|
||||
console.error('Validation error:', error.errors);
|
||||
// error.errors contains detailed validation failures
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### ResponseArgsError
|
||||
Thrown when the API returns an error:
|
||||
|
||||
```typescript
|
||||
import { ResponseArgsError } from '@isa/common/data-access';
|
||||
|
||||
try {
|
||||
await service.getAvailabilities(params);
|
||||
} catch (error) {
|
||||
if (error instanceof ResponseArgsError) {
|
||||
console.error('API error:', error.message);
|
||||
// Check error.message for details
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Error (Generic)
|
||||
Thrown for business logic failures:
|
||||
|
||||
```typescript
|
||||
try {
|
||||
// B2B-Versand without default branch
|
||||
await service.getAvailabilities({
|
||||
orderType: 'B2B-Versand',
|
||||
items: [{ itemId: 123, ean: '123', quantity: 1 }]
|
||||
});
|
||||
} catch (error) {
|
||||
if (error.message === 'Default branch has no ID') {
|
||||
console.error('Branch configuration error');
|
||||
}
|
||||
if (error.message === 'Logistician 2470 not found') {
|
||||
console.error('Logistician configuration error');
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Error Context Logging
|
||||
|
||||
The service automatically logs errors with context:
|
||||
|
||||
```typescript
|
||||
// Logged automatically on error
|
||||
{
|
||||
orderType: 'Versand',
|
||||
itemIds: [123, 456],
|
||||
additional: { /* context-specific data */ }
|
||||
}
|
||||
```
|
||||
|
||||
### Request Cancellation
|
||||
|
||||
Use AbortSignal to cancel in-flight requests:
|
||||
|
||||
```typescript
|
||||
const controller = new AbortController();
|
||||
|
||||
// Start request
|
||||
const promise = service.getAvailabilities(params, controller.signal);
|
||||
|
||||
// Cancel if needed
|
||||
controller.abort();
|
||||
|
||||
try {
|
||||
await promise;
|
||||
} catch (error) {
|
||||
// Handle cancellation or other errors
|
||||
console.log('Request cancelled or failed');
|
||||
}
|
||||
```
|
||||
|
||||
## Testing
|
||||
|
||||
The library uses **Vitest** with **Angular Testing Utilities** for testing.
|
||||
|
||||
### Running Tests
|
||||
|
||||
```bash
|
||||
# Run tests for this library
|
||||
npx nx test availability-data-access --skip-nx-cache
|
||||
|
||||
# Run tests with coverage
|
||||
npx nx test availability-data-access --code-coverage --skip-nx-cache
|
||||
|
||||
# Run tests in watch mode
|
||||
npx nx test availability-data-access --watch
|
||||
```
|
||||
|
||||
### Test Structure
|
||||
|
||||
The library includes comprehensive unit tests covering:
|
||||
|
||||
- **Order type routing** - Validates correct endpoint selection for each order type
|
||||
- **Validation** - Tests Zod schema validation for all parameter types
|
||||
- **Business rules** - Tests download validation, B2B logistician override, etc.
|
||||
- **Error handling** - Tests API errors, validation failures, missing data
|
||||
- **Abort signal support** - Tests request cancellation
|
||||
- **Multiple items** - Tests batch processing
|
||||
- **Preferred selection** - Tests preferred availability selection logic
|
||||
|
||||
### Example Test
|
||||
|
||||
```typescript
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { AvailabilityService } from './availability.service';
|
||||
|
||||
describe('AvailabilityService', () => {
|
||||
let service: AvailabilityService;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
AvailabilityService,
|
||||
// Mock providers...
|
||||
]
|
||||
});
|
||||
service = TestBed.inject(AvailabilityService);
|
||||
});
|
||||
|
||||
it('should fetch standard delivery availability', async () => {
|
||||
const result = await service.getAvailabilities({
|
||||
orderType: 'Versand',
|
||||
items: [{ itemId: 123, ean: '1234567890', quantity: 3 }]
|
||||
});
|
||||
|
||||
expect(result).toHaveProperty('123');
|
||||
expect(result['123'].itemId).toBe(123);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## Architecture Notes
|
||||
|
||||
### Current Architecture
|
||||
|
||||
The library follows a layered architecture:
|
||||
|
||||
```
|
||||
Components/Features
|
||||
↓
|
||||
AvailabilityFacade (optional, pass-through)
|
||||
↓
|
||||
AvailabilityService (main business logic)
|
||||
↓
|
||||
├─→ RemissionStockService (InStore)
|
||||
├─→ AvailabilityRequestAdapter (request mapping)
|
||||
├─→ Generated API Client (availability-api)
|
||||
└─→ Helper functions (transformers, validators)
|
||||
```
|
||||
|
||||
### Known Architectural Considerations
|
||||
|
||||
#### 1. Facade Evaluation (Medium Priority)
|
||||
|
||||
The `AvailabilityFacade` is currently under evaluation:
|
||||
|
||||
**Current State:**
|
||||
- Pass-through wrapper with no added value
|
||||
- Just delegates to AvailabilityService
|
||||
- No orchestration logic
|
||||
|
||||
**Recommendation:**
|
||||
- Consider removal if no orchestration is planned
|
||||
- Update components to inject AvailabilityService directly
|
||||
- Keep facade only if future orchestration is planned
|
||||
|
||||
**Impact:** Low risk, reduces one layer of indirection
|
||||
|
||||
#### 2. Order Type Handler Duplication (High Priority)
|
||||
|
||||
The service contains 6 similar handler methods with significant code duplication:
|
||||
|
||||
**Current State:**
|
||||
- ~180 lines of duplicated code
|
||||
- Bug fixes need to be applied to multiple methods
|
||||
|
||||
**Proposed Refactoring:**
|
||||
- Template Method + Strategy pattern
|
||||
- Handler registry with common workflow
|
||||
- Post-processing hooks for special cases
|
||||
|
||||
**Impact:** High value, reduces complexity significantly
|
||||
|
||||
#### 3. Cross-Domain Dependency
|
||||
|
||||
The library depends on `@isa/remission/data-access` for `BranchService`:
|
||||
|
||||
**Current State:**
|
||||
- Direct dependency on remission domain
|
||||
- Availability domain cannot be used without remission domain
|
||||
|
||||
**Proposed Solution:**
|
||||
- Create abstract `DefaultBranchProvider` interface
|
||||
- Inject provider instead of concrete BranchService
|
||||
- Implement at app level for domain independence
|
||||
|
||||
**Impact:** Improves domain boundaries and testability
|
||||
|
||||
### Performance Considerations
|
||||
|
||||
1. **Parallel Requests** - B2B-Versand fetches branch and logistician in parallel
|
||||
2. **Early Validation** - Zod validation fails fast before API calls
|
||||
3. **Preferred Selection** - Efficient filtering with Array.find()
|
||||
4. **Request Cancellation** - AbortSignal support prevents wasted bandwidth
|
||||
|
||||
### Future Enhancements
|
||||
|
||||
Potential improvements identified:
|
||||
|
||||
1. **Caching Layer** - Cache availability responses for short periods
|
||||
2. **Batch Optimization** - Optimize multiple availability checks
|
||||
3. **Retry Logic** - Automatic retry for transient failures
|
||||
4. **Analytics Integration** - Track availability check patterns
|
||||
5. **Schema Simplification** - Reduce single-item schema duplication
|
||||
|
||||
## Dependencies
|
||||
|
||||
### Required Libraries
|
||||
|
||||
- `@angular/core` - Angular framework
|
||||
- `@generated/swagger/availability-api` - Generated API client
|
||||
- `@isa/common/data-access` - Common data access utilities
|
||||
- `@isa/core/logging` - Logging service
|
||||
- `@isa/checkout/data-access` - Supplier and OrderType
|
||||
- `@isa/remission/data-access` - Stock and branch services
|
||||
- `@isa/oms/data-access` - Logistician service
|
||||
- `zod` - Schema validation
|
||||
- `rxjs` - Reactive programming
|
||||
|
||||
### Path Alias
|
||||
|
||||
Import from: `@isa/availability/data-access`
|
||||
|
||||
## License
|
||||
|
||||
Internal ISA Frontend library - not for external distribution.
|
||||
|
||||
@@ -32,57 +32,57 @@ import { PriceSchema } from '@isa/common/data-access';
|
||||
|
||||
// Base item schema - used for all availability checks
|
||||
const ItemSchema = z.object({
|
||||
itemId: z.coerce.number().int().positive(),
|
||||
ean: z.string(),
|
||||
price: PriceSchema.optional(),
|
||||
quantity: z.coerce.number().int().positive().default(1),
|
||||
itemId: z.coerce.number().int().positive().describe('Unique item identifier'),
|
||||
ean: z.string().describe('European Article Number barcode'),
|
||||
price: PriceSchema.describe('Item price information').optional(),
|
||||
quantity: z.coerce.number().int().positive().default(1).describe('Quantity of items to check availability for'),
|
||||
});
|
||||
|
||||
// Download items don't require quantity (always 1)
|
||||
const DownloadItemSchema = z.object({
|
||||
itemId: z.coerce.number().int().positive(),
|
||||
ean: z.string(),
|
||||
price: PriceSchema.optional(),
|
||||
itemId: z.coerce.number().int().positive().describe('Unique item identifier'),
|
||||
ean: z.string().describe('European Article Number barcode'),
|
||||
price: PriceSchema.describe('Item price information').optional(),
|
||||
});
|
||||
|
||||
const ItemsSchema = z.array(ItemSchema).min(1);
|
||||
const DownloadItemsSchema = z.array(DownloadItemSchema).min(1);
|
||||
const ItemsSchema = z.array(ItemSchema).min(1).describe('List of items to check availability for');
|
||||
const DownloadItemsSchema = z.array(DownloadItemSchema).min(1).describe('List of download items to check availability for');
|
||||
|
||||
// In-Store availability (Rücklage) - requires branch context
|
||||
export const GetInStoreAvailabilityParamsSchema = z.object({
|
||||
orderType: z.literal(OrderType.InStore),
|
||||
branchId: z.coerce.number().int().positive().optional(),
|
||||
itemsIds: z.array(z.coerce.number().int().positive()).min(1),
|
||||
orderType: z.literal(OrderType.InStore).describe('Order type specifying in-store availability check'),
|
||||
branchId: z.coerce.number().int().positive().describe('Branch identifier for in-store availability').optional(),
|
||||
itemsIds: z.array(z.coerce.number().int().positive()).min(1).describe('List of item identifiers to check in-store availability'),
|
||||
});
|
||||
|
||||
// Pickup availability (Abholung) - requires branch context
|
||||
export const GetPickupAvailabilityParamsSchema = z.object({
|
||||
orderType: z.literal(OrderType.Pickup),
|
||||
branchId: z.coerce.number().int().positive(),
|
||||
orderType: z.literal(OrderType.Pickup).describe('Order type specifying pickup availability check'),
|
||||
branchId: z.coerce.number().int().positive().describe('Branch identifier where items will be picked up'),
|
||||
items: ItemsSchema,
|
||||
});
|
||||
|
||||
// Standard delivery availability (Versand)
|
||||
export const GetDeliveryAvailabilityParamsSchema = z.object({
|
||||
orderType: z.literal(OrderType.Delivery),
|
||||
orderType: z.literal(OrderType.Delivery).describe('Order type specifying standard delivery availability check'),
|
||||
items: ItemsSchema,
|
||||
});
|
||||
|
||||
// DIG delivery availability (DIG-Versand) - for webshop customers
|
||||
export const GetDigDeliveryAvailabilityParamsSchema = z.object({
|
||||
orderType: z.literal(OrderType.DigitalShipping),
|
||||
orderType: z.literal(OrderType.DigitalShipping).describe('Order type specifying DIG delivery availability check for webshop customers'),
|
||||
items: ItemsSchema,
|
||||
});
|
||||
|
||||
// B2B delivery availability (B2B-Versand) - uses default branch
|
||||
export const GetB2bDeliveryAvailabilityParamsSchema = z.object({
|
||||
orderType: z.literal(OrderType.B2BShipping),
|
||||
orderType: z.literal(OrderType.B2BShipping).describe('Order type specifying B2B delivery availability check'),
|
||||
items: ItemsSchema,
|
||||
});
|
||||
|
||||
// Download availability - quantity always 1
|
||||
export const GetDownloadAvailabilityParamsSchema = z.object({
|
||||
orderType: z.literal(OrderType.Download),
|
||||
orderType: z.literal(OrderType.Download).describe('Order type specifying download availability check'),
|
||||
items: DownloadItemsSchema,
|
||||
});
|
||||
|
||||
@@ -125,34 +125,34 @@ export type GetDownloadAvailabilityParams = z.infer<
|
||||
|
||||
// Single-item schemas use the same structure but accept a single item instead of an array
|
||||
const SingleInStoreAvailabilityParamsSchema = z.object({
|
||||
orderType: z.literal(OrderType.InStore),
|
||||
branchId: z.coerce.number().int().positive(),
|
||||
itemId: z.number().int().positive(),
|
||||
orderType: z.literal(OrderType.InStore).describe('Order type specifying in-store availability check'),
|
||||
branchId: z.coerce.number().int().positive().describe('Branch identifier for in-store availability').optional(),
|
||||
itemId: z.number().int().positive().describe('Unique item identifier to check in-store availability'),
|
||||
});
|
||||
|
||||
const SinglePickupAvailabilityParamsSchema = z.object({
|
||||
orderType: z.literal(OrderType.Pickup),
|
||||
branchId: z.coerce.number().int().positive(),
|
||||
orderType: z.literal(OrderType.Pickup).describe('Order type specifying pickup availability check'),
|
||||
branchId: z.coerce.number().int().positive().describe('Branch identifier where item will be picked up'),
|
||||
item: ItemSchema,
|
||||
});
|
||||
|
||||
const SingleDeliveryAvailabilityParamsSchema = z.object({
|
||||
orderType: z.literal(OrderType.Delivery),
|
||||
orderType: z.literal(OrderType.Delivery).describe('Order type specifying standard delivery availability check'),
|
||||
item: ItemSchema,
|
||||
});
|
||||
|
||||
const SingleDigDeliveryAvailabilityParamsSchema = z.object({
|
||||
orderType: z.literal(OrderType.DigitalShipping),
|
||||
orderType: z.literal(OrderType.DigitalShipping).describe('Order type specifying DIG delivery availability check for webshop customers'),
|
||||
item: ItemSchema,
|
||||
});
|
||||
|
||||
const SingleB2bDeliveryAvailabilityParamsSchema = z.object({
|
||||
orderType: z.literal(OrderType.B2BShipping),
|
||||
orderType: z.literal(OrderType.B2BShipping).describe('Order type specifying B2B delivery availability check'),
|
||||
item: ItemSchema,
|
||||
});
|
||||
|
||||
const SingleDownloadAvailabilityParamsSchema = z.object({
|
||||
orderType: z.literal(OrderType.Download),
|
||||
orderType: z.literal(OrderType.Download).describe('Order type specifying download availability check'),
|
||||
item: DownloadItemSchema,
|
||||
});
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -5,10 +5,10 @@ import { z } from 'zod';
|
||||
* Used for sorting search results.
|
||||
*/
|
||||
export const OrderBySchema = z.object({
|
||||
by: z.string(), // Field name to sort by
|
||||
label: z.string(), // Display label for the sort option
|
||||
desc: z.boolean(), // Whether sorting is descending
|
||||
selected: z.boolean(), // Whether this sort option is currently selected
|
||||
by: z.string().describe('Field name to sort by'),
|
||||
label: z.string().describe('Display label for the sort option'),
|
||||
desc: z.boolean().describe('Whether sorting is descending'),
|
||||
selected: z.boolean().describe('Whether this sort option is currently selected'),
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -16,11 +16,11 @@ export const OrderBySchema = z.object({
|
||||
* Used for search operations to ensure consistent query structure.
|
||||
*/
|
||||
export const QueryTokenSchema = z.object({
|
||||
filter: z.record(z.any()).default({}), // Filter criteria as key-value pairs
|
||||
input: z.record(z.string()).default({}).optional(),
|
||||
orderBy: z.array(OrderBySchema).default([]).optional(), // Sorting parameters
|
||||
skip: z.number().default(0),
|
||||
take: z.number().default(25),
|
||||
filter: z.record(z.any()).describe('Filter criteria as key-value pairs').default({}),
|
||||
input: z.record(z.string()).describe('Input parameters as key-value pairs').default({}).optional(),
|
||||
orderBy: z.array(OrderBySchema).describe('Sorting parameters').default([]).optional(),
|
||||
skip: z.number().describe('Number of items to skip for pagination').default(0),
|
||||
take: z.number().describe('Number of items to return per page').default(25),
|
||||
});
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,7 +1,791 @@
|
||||
# data-access
|
||||
# @isa/checkout/data-access
|
||||
|
||||
This library was generated with [Nx](https://nx.dev).
|
||||
A comprehensive checkout and shopping cart management library for Angular applications supporting multiple order types, reward redemption, and complex multi-step checkout workflows across retail and e-commerce operations.
|
||||
|
||||
## Running unit tests
|
||||
## Overview
|
||||
|
||||
Run `nx test data-access` to execute the unit tests.
|
||||
The Checkout Data Access library provides the complete infrastructure for managing shopping carts, reward catalogs, and checkout processes. It handles six distinct order types (in-store pickup, customer pickup, standard shipping, digital shipping, B2B shipping, and digital downloads), reward/loyalty redemption flows, customer/payer data transformation, and multi-phase checkout orchestration with automatic availability validation and destination management.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Features](#features)
|
||||
- [Quick Start](#quick-start)
|
||||
- [Core Concepts](#core-concepts)
|
||||
- [API Reference](#api-reference)
|
||||
- [Usage Examples](#usage-examples)
|
||||
- [Order Types](#order-types)
|
||||
- [Checkout Flow](#checkout-flow)
|
||||
- [Reward System](#reward-system)
|
||||
- [Data Transformation](#data-transformation)
|
||||
- [Error Handling](#error-handling)
|
||||
- [Testing](#testing)
|
||||
- [Architecture Notes](#architecture-notes)
|
||||
|
||||
## Features
|
||||
|
||||
- **Shopping Cart Management** - Create, update, and manage shopping carts with full CRUD operations
|
||||
- **Six Order Type Support** - InStore (Rücklage), Pickup (Abholung), Delivery (Versand), DIG-Versand, B2B-Versand, Download
|
||||
- **Reward Catalog Store** - NgRx Signals store for managing reward items and selections with tab isolation
|
||||
- **Complete Checkout Orchestration** - 13-step checkout workflow with automatic validation and transformation
|
||||
- **CRM Data Integration** - Seamless conversion between CRM and checkout-api formats
|
||||
- **Multi-Domain Adapters** - 8 specialized adapters for cross-domain data transformation
|
||||
- **Zod Validation** - Runtime schema validation for 58+ schemas
|
||||
- **Payment Type Determination** - Automatic payment type selection (FREE/CASH/INVOICE) based on order analysis
|
||||
- **Availability Validation** - Integrated download validation and shipping availability updates
|
||||
- **Destination Management** - Automatic shipping address updates and logistician assignment
|
||||
- **Session Persistence** - Reward catalog state persists across browser sessions
|
||||
- **Request Cancellation** - AbortSignal support for all async operations
|
||||
- **Comprehensive Error Handling** - Typed CheckoutCompletionError with specific error codes
|
||||
- **Tab Isolation** - Shopping carts and reward selections scoped per browser tab
|
||||
- **Business Logic Helpers** - 15+ pure functions for order analysis and validation
|
||||
|
||||
## Quick Start
|
||||
|
||||
### 1. Shopping Cart Operations
|
||||
|
||||
```typescript
|
||||
import { Component, inject } from '@angular/core';
|
||||
import { ShoppingCartFacade } from '@isa/checkout/data-access';
|
||||
|
||||
@Component({
|
||||
selector: 'app-checkout',
|
||||
template: '...'
|
||||
})
|
||||
export class CheckoutComponent {
|
||||
#shoppingCartFacade = inject(ShoppingCartFacade);
|
||||
|
||||
async createCart(): Promise<void> {
|
||||
// Create new shopping cart
|
||||
const cart = await this.#shoppingCartFacade.createShoppingCart();
|
||||
console.log('Cart created:', cart.id);
|
||||
|
||||
// Get shopping cart
|
||||
const existingCart = await this.#shoppingCartFacade.getShoppingCart(cart.id!);
|
||||
console.log('Cart items:', existingCart?.items?.length);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Complete Checkout with CRM Data
|
||||
|
||||
```typescript
|
||||
import { Component, inject } from '@angular/core';
|
||||
import { ShoppingCartFacade } from '@isa/checkout/data-access';
|
||||
import { CustomerResource } from '@isa/crm/data-access';
|
||||
|
||||
@Component({
|
||||
selector: 'app-complete-checkout',
|
||||
template: '...'
|
||||
})
|
||||
export class CompleteCheckoutComponent {
|
||||
#shoppingCartFacade = inject(ShoppingCartFacade);
|
||||
#customerResource = inject(CustomerResource);
|
||||
|
||||
async completeCheckout(shoppingCartId: number): Promise<void> {
|
||||
// Fetch customer from CRM
|
||||
const customer = await this.#customerResource.value();
|
||||
|
||||
if (!customer) {
|
||||
throw new Error('Customer not found');
|
||||
}
|
||||
|
||||
// Complete checkout with automatic CRM data transformation
|
||||
const orders = await this.#shoppingCartFacade.completeWithCrmData({
|
||||
shoppingCartId,
|
||||
crmCustomer: customer,
|
||||
crmShippingAddress: customer.shippingAddresses?.[0]?.data,
|
||||
crmPayer: customer.payers?.[0]?.payer?.data,
|
||||
notificationChannels: customer.notificationChannels ?? 1,
|
||||
specialComment: 'Please handle with care'
|
||||
});
|
||||
|
||||
console.log('Orders created:', orders.length);
|
||||
orders.forEach(order => {
|
||||
console.log(`Order ${order.orderNumber}: ${order.orderType}`);
|
||||
});
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Reward Catalog Management
|
||||
|
||||
```typescript
|
||||
import { Component, inject } from '@angular/core';
|
||||
import { RewardCatalogStore } from '@isa/checkout/data-access';
|
||||
import { Item } from '@isa/catalogue/data-access';
|
||||
|
||||
@Component({
|
||||
selector: 'app-reward-selection',
|
||||
template: '...'
|
||||
})
|
||||
export class RewardSelectionComponent {
|
||||
#rewardCatalogStore = inject(RewardCatalogStore);
|
||||
|
||||
// Access reactive signals
|
||||
items = this.#rewardCatalogStore.items;
|
||||
selectedItems = this.#rewardCatalogStore.selectedItems;
|
||||
hits = this.#rewardCatalogStore.hits;
|
||||
|
||||
selectReward(itemId: number, item: Item): void {
|
||||
this.#rewardCatalogStore.selectItem(itemId, item);
|
||||
}
|
||||
|
||||
removeReward(itemId: number): void {
|
||||
this.#rewardCatalogStore.removeItem(itemId);
|
||||
}
|
||||
|
||||
clearAllSelections(): void {
|
||||
this.#rewardCatalogStore.clearSelectedItems();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 4. Adding Items to Shopping Cart
|
||||
|
||||
```typescript
|
||||
import { ShoppingCartService } from '@isa/checkout/data-access';
|
||||
|
||||
@Component({
|
||||
selector: 'app-add-to-cart',
|
||||
template: '...'
|
||||
})
|
||||
export class AddToCartComponent {
|
||||
#shoppingCartService = inject(ShoppingCartService);
|
||||
|
||||
async addItemsToCart(shoppingCartId: number): Promise<void> {
|
||||
// Check if items can be added first
|
||||
const canAddResults = await this.#shoppingCartService.canAddItems({
|
||||
shoppingCartId,
|
||||
payload: [
|
||||
{ itemId: 123, quantity: 2 },
|
||||
{ itemId: 456, quantity: 1 }
|
||||
]
|
||||
});
|
||||
|
||||
// Process results
|
||||
canAddResults.forEach(result => {
|
||||
if (result.canAdd) {
|
||||
console.log(`Item ${result.itemId} can be added`);
|
||||
} else {
|
||||
console.log(`Item ${result.itemId} cannot be added: ${result.reason}`);
|
||||
}
|
||||
});
|
||||
|
||||
// Add items to cart
|
||||
const updatedCart = await this.#shoppingCartService.addItem({
|
||||
shoppingCartId,
|
||||
items: [
|
||||
{
|
||||
destination: { target: 2 },
|
||||
product: {
|
||||
id: 123,
|
||||
catalogProductNumber: 'PROD-123',
|
||||
description: 'Sample Product'
|
||||
},
|
||||
availability: {
|
||||
price: {
|
||||
value: { value: 29.99, currency: 'EUR' },
|
||||
vat: { value: 4.78, inPercent: 19 }
|
||||
}
|
||||
},
|
||||
quantity: 2
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
console.log('Updated cart:', updatedCart.items?.length);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Core Concepts
|
||||
|
||||
### Order Types
|
||||
|
||||
The library supports six distinct order types, each with specific characteristics and handling requirements:
|
||||
|
||||
#### 1. InStore (Rücklage)
|
||||
- **Purpose**: In-store reservation for later pickup
|
||||
- **Characteristics**: Branch-based, no shipping required
|
||||
- **Payment**: Cash (4)
|
||||
- **Features**: `{ orderType: 'Rücklage' }`
|
||||
|
||||
#### 2. Pickup (Abholung)
|
||||
- **Purpose**: Customer pickup at branch location
|
||||
- **Characteristics**: Branch-based, customer collects items
|
||||
- **Payment**: Cash (4)
|
||||
- **Features**: `{ orderType: 'Abholung' }`
|
||||
|
||||
#### 3. Delivery (Versand)
|
||||
- **Purpose**: Standard shipping to customer address
|
||||
- **Characteristics**: Requires shipping address, logistician assignment
|
||||
- **Payment**: Invoice (128)
|
||||
- **Features**: `{ orderType: 'Versand' }`
|
||||
|
||||
#### 4. Digital Shipping (DIG-Versand)
|
||||
- **Purpose**: Digital delivery for webshop customers
|
||||
- **Characteristics**: Requires special availability validation
|
||||
- **Payment**: Invoice (128)
|
||||
- **Features**: `{ orderType: 'DIG-Versand' }`
|
||||
|
||||
#### 5. B2B Shipping (B2B-Versand)
|
||||
- **Purpose**: Business-to-business delivery
|
||||
- **Characteristics**: Requires logistician 2470, default branch
|
||||
- **Payment**: Invoice (128)
|
||||
- **Features**: `{ orderType: 'B2B-Versand' }`
|
||||
|
||||
#### 6. Download
|
||||
- **Purpose**: Digital product downloads
|
||||
- **Characteristics**: Requires download availability validation
|
||||
- **Payment**: Invoice (128) or Free (2) for loyalty
|
||||
- **Features**: `{ orderType: 'Download' }`
|
||||
|
||||
### Shopping Cart State
|
||||
|
||||
```typescript
|
||||
interface ShoppingCart {
|
||||
id?: number; // Shopping cart ID
|
||||
items?: EntityContainer<ShoppingCartItem>[]; // Cart items with metadata
|
||||
createdAt?: string; // Creation timestamp
|
||||
updatedAt?: string; // Last update timestamp
|
||||
features?: Record<string, string>; // Custom features/flags
|
||||
}
|
||||
|
||||
interface ShoppingCartItem {
|
||||
id?: number; // Item ID in cart
|
||||
destination?: Destination; // Shipping/pickup destination
|
||||
product?: Product; // Product information
|
||||
availability?: OlaAvailability; // Availability and pricing
|
||||
quantity: number; // Item quantity
|
||||
loyalty?: Loyalty; // Loyalty points/rewards
|
||||
promotion?: Promotion; // Applied promotions
|
||||
features?: Record<string, string>; // Item features (orderType, etc.)
|
||||
specialComment?: string; // Item-specific instructions
|
||||
}
|
||||
```
|
||||
|
||||
### Checkout Flow Overview
|
||||
|
||||
The checkout completion process consists of 13 coordinated steps:
|
||||
|
||||
```
|
||||
1. Fetch and validate shopping cart
|
||||
2. Analyze order types (delivery, pickup, download, etc.)
|
||||
3. Analyze customer type (B2B, online, guest, staff)
|
||||
4. Determine if payer is required
|
||||
5. Create or refresh checkout entity
|
||||
6. Update destinations for customer (if needed)
|
||||
7. Set special comments on items (if provided)
|
||||
8. Validate download availabilities
|
||||
9. Update shipping availabilities (DIG-Versand, B2B-Versand)
|
||||
10. Set buyer on checkout
|
||||
11. Set notification channels
|
||||
12. Set payer (if required)
|
||||
13. Set payment type (FREE/CASH/INVOICE)
|
||||
14. Update destination shipping addresses (if delivery)
|
||||
|
||||
Result: checkoutId → Pass to OrderCreationFacade for order creation
|
||||
```
|
||||
|
||||
### Payment Type Logic
|
||||
|
||||
Payment type is automatically determined based on order analysis:
|
||||
|
||||
```typescript
|
||||
/**
|
||||
* Payment type decision tree:
|
||||
*
|
||||
* IF all items have loyalty.value > 0:
|
||||
* → FREE (2) - Loyalty redemption
|
||||
*
|
||||
* ELSE IF hasDelivery OR hasDownload OR hasDigDelivery OR hasB2BDelivery:
|
||||
* → INVOICE (128) - Invoicing required
|
||||
*
|
||||
* ELSE:
|
||||
* → CASH (4) - In-store payment
|
||||
*/
|
||||
const PaymentTypes = {
|
||||
FREE: 2, // Loyalty/reward orders
|
||||
CASH: 4, // In-store pickup/take away
|
||||
INVOICE: 128 // Delivery and download orders
|
||||
};
|
||||
```
|
||||
|
||||
### Order Options Analysis
|
||||
|
||||
The library analyzes shopping cart items to determine checkout requirements:
|
||||
|
||||
```typescript
|
||||
interface OrderOptionsAnalysis {
|
||||
hasTakeAway: boolean; // Has Rücklage items
|
||||
hasPickUp: boolean; // Has Abholung items
|
||||
hasDownload: boolean; // Has Download items
|
||||
hasDelivery: boolean; // Has Versand items
|
||||
hasDigDelivery: boolean; // Has DIG-Versand items
|
||||
hasB2BDelivery: boolean; // Has B2B-Versand items
|
||||
items: ShoppingCartItem[]; // Unwrapped items for processing
|
||||
}
|
||||
```
|
||||
|
||||
**Business Rules:**
|
||||
- **Payer Required**: B2B customers OR any delivery/download orders
|
||||
- **Destination Update Required**: Any delivery or download orders
|
||||
- **Payment Type**: Determined by order types and loyalty status
|
||||
- **Shipping Address Required**: Any delivery orders (Versand, DIG-Versand, B2B-Versand)
|
||||
|
||||
### Customer Type Analysis
|
||||
|
||||
Customer features are analyzed to determine handling requirements:
|
||||
|
||||
```typescript
|
||||
interface CustomerTypeAnalysis {
|
||||
isOnline: boolean; // Webshop customer
|
||||
isGuest: boolean; // Guest account
|
||||
isB2B: boolean; // Business customer
|
||||
hasCustomerCard: boolean; // Loyalty card holder (Pay4More)
|
||||
isStaff: boolean; // Employee/staff member
|
||||
}
|
||||
```
|
||||
|
||||
**Feature Mapping:**
|
||||
- `webshop` → `isOnline: true`
|
||||
- `guest` → `isGuest: true`
|
||||
- `b2b` → `isB2B: true`
|
||||
- `p4mUser` → `hasCustomerCard: true`
|
||||
- `staff` → `isStaff: true`
|
||||
|
||||
### Reward System Architecture
|
||||
|
||||
The reward catalog store manages reward items and selections with automatic tab isolation:
|
||||
|
||||
```typescript
|
||||
interface RewardCatalogEntity {
|
||||
tabId: number; // Browser tab ID (isolation)
|
||||
items: Item[]; // Available reward items
|
||||
hits: number; // Total search results
|
||||
selectedItems: Record<number, Item>; // Selected items by ID
|
||||
}
|
||||
```
|
||||
|
||||
**Key Features:**
|
||||
- **Tab Isolation**: Each browser tab has independent reward state
|
||||
- **Session Persistence**: State survives browser refreshes
|
||||
- **Orphan Cleanup**: Automatically removes state when tabs close
|
||||
- **Reactive Signals**: Computed signals for active tab data
|
||||
- **Dual Shopping Carts**: Separate carts for regular and reward items
|
||||
|
||||
## API Reference
|
||||
|
||||
### ShoppingCartFacade
|
||||
|
||||
Main facade for shopping cart and checkout operations.
|
||||
|
||||
#### `createShoppingCart(): Promise<ShoppingCart>`
|
||||
|
||||
Creates a new empty shopping cart.
|
||||
|
||||
**Returns:** Promise resolving to the created shopping cart
|
||||
|
||||
**Example:**
|
||||
```typescript
|
||||
const cart = await facade.createShoppingCart();
|
||||
console.log('Cart ID:', cart.id);
|
||||
```
|
||||
|
||||
#### `getShoppingCart(shoppingCartId, abortSignal?): Promise<ShoppingCart | undefined>`
|
||||
|
||||
Fetches an existing shopping cart by ID.
|
||||
|
||||
**Parameters:**
|
||||
- `shoppingCartId: number` - ID of the shopping cart to fetch
|
||||
- `abortSignal?: AbortSignal` - Optional cancellation signal
|
||||
|
||||
**Returns:** Promise resolving to the shopping cart, or undefined if not found
|
||||
|
||||
**Throws:**
|
||||
- `ResponseArgsError` - If API returns an error
|
||||
|
||||
**Example:**
|
||||
```typescript
|
||||
const cart = await facade.getShoppingCart(123, abortController.signal);
|
||||
if (cart) {
|
||||
console.log('Items:', cart.items?.length);
|
||||
}
|
||||
```
|
||||
|
||||
#### `removeItem(params): Promise<ShoppingCart>`
|
||||
|
||||
Removes an item from the shopping cart (sets quantity to 0).
|
||||
|
||||
**Parameters:**
|
||||
- `params: RemoveShoppingCartItemParams`
|
||||
- `shoppingCartId: number` - Shopping cart ID
|
||||
- `shoppingCartItemId: number` - Item ID to remove
|
||||
|
||||
**Returns:** Promise resolving to updated shopping cart
|
||||
|
||||
**Throws:**
|
||||
- `ZodError` - If params validation fails
|
||||
- `ResponseArgsError` - If API returns an error
|
||||
|
||||
**Example:**
|
||||
```typescript
|
||||
const updatedCart = await facade.removeItem({
|
||||
shoppingCartId: 123,
|
||||
shoppingCartItemId: 456
|
||||
});
|
||||
```
|
||||
|
||||
#### `updateItem(params): Promise<ShoppingCart>`
|
||||
|
||||
Updates a shopping cart item (quantity, special comment, etc.).
|
||||
|
||||
**Parameters:**
|
||||
- `params: UpdateShoppingCartItemParams`
|
||||
- `shoppingCartId: number` - Shopping cart ID
|
||||
- `shoppingCartItemId: number` - Item ID to update
|
||||
- `values: UpdateShoppingCartItemDTO` - Fields to update
|
||||
|
||||
**Returns:** Promise resolving to updated shopping cart
|
||||
|
||||
**Throws:**
|
||||
- `ZodError` - If params validation fails
|
||||
- `ResponseArgsError` - If API returns an error
|
||||
|
||||
**Example:**
|
||||
```typescript
|
||||
const updatedCart = await facade.updateItem({
|
||||
shoppingCartId: 123,
|
||||
shoppingCartItemId: 456,
|
||||
values: { quantity: 5, specialComment: 'Gift wrap please' }
|
||||
});
|
||||
```
|
||||
|
||||
#### `complete(params, abortSignal?): Promise<Order[]>`
|
||||
|
||||
Completes checkout and creates orders.
|
||||
|
||||
**Parameters:**
|
||||
- `params: CompleteOrderParams`
|
||||
- `shoppingCartId: number` - Shopping cart to process
|
||||
- `buyer: Buyer` - Buyer information
|
||||
- `notificationChannels?: NotificationChannel` - Communication channels
|
||||
- `customerFeatures: Record<string, string>` - Customer feature flags
|
||||
- `payer?: Payer` - Payer information (required for B2B/delivery/download)
|
||||
- `shippingAddress?: ShippingAddress` - Shipping address (required for delivery)
|
||||
- `specialComment?: string` - Special instructions
|
||||
- `abortSignal?: AbortSignal` - Optional cancellation signal
|
||||
|
||||
**Returns:** Promise resolving to array of created orders
|
||||
|
||||
**Throws:**
|
||||
- `CheckoutCompletionError` - For validation or business logic failures
|
||||
- `ResponseArgsError` - For API failures
|
||||
|
||||
**Example:**
|
||||
```typescript
|
||||
const orders = await facade.complete({
|
||||
shoppingCartId: 123,
|
||||
buyer: buyerDTO,
|
||||
customerFeatures: { webshop: 'webshop', p4mUser: 'p4mUser' },
|
||||
notificationChannels: 1,
|
||||
payer: payerDTO,
|
||||
shippingAddress: addressDTO
|
||||
}, abortController.signal);
|
||||
|
||||
console.log(`Created ${orders.length} orders`);
|
||||
```
|
||||
|
||||
#### `completeWithCrmData(params, abortSignal?): Promise<Order[]>`
|
||||
|
||||
Completes checkout with CRM data, automatically transforming customer/payer/address.
|
||||
|
||||
**Parameters:**
|
||||
- `params: CompleteCrmOrderParams`
|
||||
- `shoppingCartId: number` - Shopping cart to process
|
||||
- `crmCustomer: Customer` - Customer from CRM service
|
||||
- `crmPayer?: PayerDTO` - Payer from CRM service (optional)
|
||||
- `crmShippingAddress?: ShippingAddressDTO` - Shipping address from CRM (optional)
|
||||
- `notificationChannels?: NotificationChannel` - Communication channels
|
||||
- `specialComment?: string` - Special instructions
|
||||
- `abortSignal?: AbortSignal` - Optional cancellation signal
|
||||
|
||||
**Returns:** Promise resolving to array of created orders
|
||||
|
||||
**Throws:**
|
||||
- `CheckoutCompletionError` - For validation or business logic failures
|
||||
- `ResponseArgsError` - For API failures
|
||||
|
||||
**Transformation Steps:**
|
||||
1. Validates input with Zod schema
|
||||
2. Converts `crmCustomer` to `buyer` using `CustomerAdapter.toBuyer()`
|
||||
3. Converts `crmShippingAddress` using `ShippingAddressAdapter.fromCrmShippingAddress()`
|
||||
4. Converts `crmPayer` using `PayerAdapter.toCheckoutFormat()`
|
||||
5. Extracts customer features using `CustomerAdapter.extractCustomerFeatures()`
|
||||
6. Delegates to `complete()` with transformed data
|
||||
|
||||
**Example:**
|
||||
```typescript
|
||||
const customer = await customerResource.value();
|
||||
|
||||
const orders = await facade.completeWithCrmData({
|
||||
shoppingCartId: 123,
|
||||
crmCustomer: customer,
|
||||
crmShippingAddress: customer.shippingAddresses[0].data,
|
||||
crmPayer: customer.payers[0].payer.data,
|
||||
notificationChannels: customer.notificationChannels ?? 1,
|
||||
specialComment: 'Rush delivery'
|
||||
});
|
||||
```
|
||||
|
||||
### Helper Functions
|
||||
|
||||
#### Analysis Helpers
|
||||
|
||||
##### `analyzeOrderOptions(items): OrderOptionsAnalysis`
|
||||
|
||||
Analyzes shopping cart items to determine which order types are present.
|
||||
|
||||
**Parameters:**
|
||||
- `items: EntityContainer<ShoppingCartItem>[]` - Cart items to analyze
|
||||
|
||||
**Returns:** Analysis result with boolean flags for each order type
|
||||
|
||||
**Example:**
|
||||
```typescript
|
||||
const analysis = analyzeOrderOptions(cart.items);
|
||||
if (analysis.hasDelivery) {
|
||||
console.log('Delivery items present - shipping address required');
|
||||
}
|
||||
```
|
||||
|
||||
##### `analyzeCustomerTypes(features): CustomerTypeAnalysis`
|
||||
|
||||
Analyzes customer features to determine customer type characteristics.
|
||||
|
||||
**Parameters:**
|
||||
- `features: Record<string, string>` - Customer feature flags
|
||||
|
||||
**Returns:** Analysis result with boolean flags for customer types
|
||||
|
||||
##### `shouldSetPayer(options, customer): boolean`
|
||||
|
||||
Determines if payer should be set based on order and customer analysis.
|
||||
|
||||
**Business Rule:** Payer required when: `isB2B OR hasB2BDelivery OR hasDelivery OR hasDigDelivery OR hasDownload`
|
||||
|
||||
##### `needsDestinationUpdate(options): boolean`
|
||||
|
||||
Determines if destination update is needed.
|
||||
|
||||
**Business Rule:** Update needed when: `hasDownload OR hasDelivery OR hasDigDelivery OR hasB2BDelivery`
|
||||
|
||||
##### `determinePaymentType(options): PaymentType`
|
||||
|
||||
Determines payment type based on order analysis.
|
||||
|
||||
**Business Rules:**
|
||||
1. If all items have `loyalty.value > 0`: **FREE (2)**
|
||||
2. Else if has delivery/download orders: **INVOICE (128)**
|
||||
3. Else: **CASH (4)**
|
||||
|
||||
### Adapters
|
||||
|
||||
The library provides 8 specialized adapters for cross-domain data transformation:
|
||||
|
||||
#### CustomerAdapter
|
||||
|
||||
Converts CRM customer data to checkout-api format.
|
||||
|
||||
**Static Methods:**
|
||||
- `toBuyer(customer): Buyer` - Converts customer to buyer
|
||||
- `toPayerFromCustomer(customer): Payer` - Converts customer to payer (self-paying)
|
||||
- `toPayerFromAssignedPayer(assignedPayer): Payer | null` - Unwraps AssignedPayer container
|
||||
- `extractCustomerFeatures(customer): Record<string, string>` - Extracts feature flags
|
||||
|
||||
**Key Differences:**
|
||||
- **Buyer**: Includes `source` field and `dateOfBirth`
|
||||
- **Payer from Customer**: No `source`, no `dateOfBirth`, sets `payerStatus: 0`
|
||||
- **Payer from AssignedPayer**: Includes `source` field, unwraps EntityContainer
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Complete Multi-Step Checkout Workflow
|
||||
|
||||
```typescript
|
||||
import { Component, inject, signal } from '@angular/core';
|
||||
import { ShoppingCartFacade, CheckoutCompletionError } from '@isa/checkout/data-access';
|
||||
import { CustomerResource } from '@isa/crm/data-access';
|
||||
|
||||
@Component({
|
||||
selector: 'app-checkout-flow',
|
||||
template: `
|
||||
<div class="checkout">
|
||||
<h2>Checkout</h2>
|
||||
@if (loading()) { <p>Processing checkout...</p> }
|
||||
@if (error()) { <div class="error">{{ error() }}</div> }
|
||||
<button (click)="processCheckout()" [disabled]="loading()">
|
||||
Complete Checkout
|
||||
</button>
|
||||
</div>
|
||||
`
|
||||
})
|
||||
export class CheckoutFlowComponent {
|
||||
#shoppingCartFacade = inject(ShoppingCartFacade);
|
||||
#customerResource = inject(CustomerResource);
|
||||
|
||||
loading = signal(false);
|
||||
error = signal<string | null>(null);
|
||||
orders = signal<Order[]>([]);
|
||||
|
||||
shoppingCartId = 123;
|
||||
|
||||
async processCheckout(): Promise<void> {
|
||||
this.loading.set(true);
|
||||
this.error.set(null);
|
||||
|
||||
try {
|
||||
const customer = await this.#customerResource.value();
|
||||
if (!customer) throw new Error('Customer not found');
|
||||
|
||||
const createdOrders = await this.#shoppingCartFacade.completeWithCrmData({
|
||||
shoppingCartId: this.shoppingCartId,
|
||||
crmCustomer: customer,
|
||||
crmShippingAddress: customer.shippingAddresses?.[0]?.data,
|
||||
crmPayer: customer.payers?.[0]?.payer?.data,
|
||||
notificationChannels: customer.notificationChannels ?? 1
|
||||
});
|
||||
|
||||
this.orders.set(createdOrders);
|
||||
} catch (err) {
|
||||
if (err instanceof CheckoutCompletionError) {
|
||||
this.error.set(`Checkout failed: ${err.message}`);
|
||||
} else {
|
||||
this.error.set('An unexpected error occurred');
|
||||
}
|
||||
} finally {
|
||||
this.loading.set(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Order Types
|
||||
|
||||
### Parameter Requirements by Order Type
|
||||
|
||||
| Order Type | Features Flag | Payment Type | Payer Required | Shipping Address | Special Handling |
|
||||
|------------|--------------|--------------|----------------|------------------|------------------|
|
||||
| **Rücklage** (InStore) | `orderType: 'Rücklage'` | CASH (4) | No | No | In-store reservation |
|
||||
| **Abholung** (Pickup) | `orderType: 'Abholung'` | CASH (4) | No | No | Customer pickup at branch |
|
||||
| **Versand** (Delivery) | `orderType: 'Versand'` | INVOICE (128) | Yes | Yes | Standard shipping |
|
||||
| **DIG-Versand** | `orderType: 'DIG-Versand'` | INVOICE (128) | Yes | Yes | Digital delivery, availability validation |
|
||||
| **B2B-Versand** | `orderType: 'B2B-Versand'` | INVOICE (128) | Yes | Yes | Logistician 2470, default branch |
|
||||
| **Download** | `orderType: 'Download'` | INVOICE (128) or FREE (2) | Yes | No | Download validation |
|
||||
|
||||
## Checkout Flow
|
||||
|
||||
The complete checkout process consists of 13 coordinated steps that validate data, transform cross-domain entities, update availabilities, and prepare the checkout for order creation.
|
||||
|
||||
## Reward System
|
||||
|
||||
### Dual Shopping Cart Architecture
|
||||
|
||||
The reward system uses separate shopping carts:
|
||||
|
||||
1. **Regular Shopping Cart** (`shoppingCartId`) - Items purchased with money
|
||||
2. **Reward Shopping Cart** (`rewardShoppingCartId`) - Items purchased with loyalty points (zero price, loyalty.value set)
|
||||
|
||||
## Data Transformation
|
||||
|
||||
### CRM to Checkout Transformation
|
||||
|
||||
The library provides automatic transformation from CRM domain to checkout-api domain through specialized adapters.
|
||||
|
||||
## Error Handling
|
||||
|
||||
### CheckoutCompletionError Types
|
||||
|
||||
```typescript
|
||||
type CheckoutCompletionErrorCode =
|
||||
| 'SHOPPING_CART_NOT_FOUND' // Cart with ID doesn't exist
|
||||
| 'SHOPPING_CART_EMPTY' // Cart has no items
|
||||
| 'CHECKOUT_NOT_FOUND' // Checkout entity not found
|
||||
| 'INVALID_AVAILABILITY' // Availability validation failed
|
||||
| 'MISSING_BUYER' // Buyer data not provided
|
||||
| 'MISSING_REQUIRED_DATA' // Required field missing
|
||||
| 'CHECKOUT_CONFLICT' // Order already exists (HTTP 409)
|
||||
| 'ORDER_CREATION_FAILED' // Order creation failed
|
||||
| 'DOWNLOAD_UNAVAILABLE' // Download items not available
|
||||
| 'SHIPPING_AVAILABILITY_FAILED'; // Shipping availability update failed
|
||||
```
|
||||
|
||||
## Testing
|
||||
|
||||
The library uses **Vitest** with **Angular Testing Utilities** for testing.
|
||||
|
||||
### Running Tests
|
||||
|
||||
```bash
|
||||
# Run tests for this library
|
||||
npx nx test checkout-data-access --skip-nx-cache
|
||||
|
||||
# Run tests with coverage
|
||||
npx nx test checkout-data-access --code-coverage --skip-nx-cache
|
||||
|
||||
# Run tests in watch mode
|
||||
npx nx test checkout-data-access --watch
|
||||
```
|
||||
|
||||
## Architecture Notes
|
||||
|
||||
### Current Architecture
|
||||
|
||||
```
|
||||
Components/Features
|
||||
↓
|
||||
ShoppingCartFacade (orchestration)
|
||||
↓
|
||||
├─→ ShoppingCartService (cart CRUD)
|
||||
├─→ CheckoutService (checkout workflow)
|
||||
├─→ OrderCreationFacade (oms-api)
|
||||
└─→ Adapters (cross-domain transformation)
|
||||
|
||||
Stores (NgRx Signals)
|
||||
↓
|
||||
RewardCatalogStore (reward state management)
|
||||
```
|
||||
|
||||
### Key Design Decisions
|
||||
|
||||
1. **Stateless Checkout Service** - All data passed as parameters for testability
|
||||
2. **Separation of Checkout and Order Creation** - Clean domain boundaries
|
||||
3. **Dual Shopping Cart for Rewards** - Payment and pricing isolation
|
||||
4. **Extensive Adapter Pattern** - 8 adapters for cross-domain transformation
|
||||
5. **Tab-Isolated Reward Catalog** - NgRx Signals with automatic cleanup
|
||||
|
||||
## Dependencies
|
||||
|
||||
### Required Libraries
|
||||
|
||||
- `@angular/core` - Angular framework
|
||||
- `@ngrx/signals` - NgRx Signals for state management
|
||||
- `@generated/swagger/checkout-api` - Generated checkout API client
|
||||
- `@isa/common/data-access` - Common utilities
|
||||
- `@isa/core/logging` - Logging service
|
||||
- `@isa/core/storage` - Session storage
|
||||
- `@isa/core/tabs` - Tab service
|
||||
- `@isa/catalogue/data-access` - Availability services
|
||||
- `@isa/crm/data-access` - Customer types
|
||||
- `@isa/oms/data-access` - Order creation
|
||||
- `@isa/remission/data-access` - Branch service
|
||||
- `zod` - Schema validation
|
||||
- `rxjs` - Reactive programming
|
||||
|
||||
### Path Alias
|
||||
|
||||
Import from: `@isa/checkout/data-access`
|
||||
|
||||
## License
|
||||
|
||||
Internal ISA Frontend library - not for external distribution.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { PriceDTO, Price } from '@generated/swagger/checkout-api';
|
||||
import { Availability as AvaAvailability } from '@isa/availability/data-access';
|
||||
import { Availability, AvailabilityType } from '../models';
|
||||
import { Availability, AvailabilityType } from '../schemas';
|
||||
|
||||
/**
|
||||
* Availability data from catalogue-api (raw response)
|
||||
@@ -55,6 +55,8 @@ export class AvailabilityAdapter {
|
||||
data: {
|
||||
id: catalogueAvailability.supplier.id,
|
||||
},
|
||||
// Explicitly omit externalReference to avoid TypeScript errors
|
||||
// (generated DTOs require externalStatus when externalReference is present)
|
||||
},
|
||||
isPrebooked: catalogueAvailability.isPrebooked,
|
||||
estimatedShippingDate: catalogueAvailability.estimatedShippingDate,
|
||||
@@ -78,6 +80,8 @@ export class AvailabilityAdapter {
|
||||
data: {
|
||||
id: catalogueAvailability.logistician.id,
|
||||
},
|
||||
// Explicitly omit externalReference to avoid TypeScript errors
|
||||
// (generated DTOs require externalStatus when externalReference is present)
|
||||
};
|
||||
}
|
||||
|
||||
@@ -132,6 +136,8 @@ export class AvailabilityAdapter {
|
||||
data: {
|
||||
id: availability.logisticianId,
|
||||
},
|
||||
// Explicitly omit externalReference to avoid TypeScript errors
|
||||
// (generated DTOs require externalStatus when externalReference is present)
|
||||
};
|
||||
}
|
||||
|
||||
@@ -142,6 +148,8 @@ export class AvailabilityAdapter {
|
||||
data: {
|
||||
id: availability.supplierId,
|
||||
},
|
||||
// Explicitly omit externalReference to avoid TypeScript errors
|
||||
// (generated DTOs require externalStatus when externalReference is present)
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,201 +1,219 @@
|
||||
import { Customer, AssignedPayer } from '@isa/crm/data-access';
|
||||
import { Buyer, Payer } from '../models';
|
||||
|
||||
/**
|
||||
* Adapter for converting CRM customer data to checkout-api format.
|
||||
*
|
||||
* Handles three distinct conversion scenarios:
|
||||
* 1. **Customer to Buyer** (`toBuyer`): Converts customer for checkout as the buyer.
|
||||
* 2. **Customer to Payer** (`toPayerFromCustomer`): Uses customer as payer (self-paying).
|
||||
* 3. **AssignedPayer to Payer** (`toPayerFromAssignedPayer`): Unwraps separate payer entity.
|
||||
*
|
||||
* **Key Patterns:**
|
||||
* - Buyer conversion includes `dateOfBirth` and `source` field
|
||||
* - Payer from customer omits `source`, sets default `payerStatus: 0`
|
||||
* - AssignedPayer unwrapping handles `EntityContainer` structure with null safety
|
||||
*/
|
||||
export class CustomerAdapter {
|
||||
private static readonly ADAPTER_NAME = 'CustomerAdapter';
|
||||
|
||||
/**
|
||||
* Converts Customer to checkout-api Buyer.
|
||||
*
|
||||
* @remarks
|
||||
* Used when the customer is the buyer in a checkout flow. Maps all relevant
|
||||
* customer information including personal details, address, and organization.
|
||||
*
|
||||
* The buyer includes a `source` field referencing the customer entity ID,
|
||||
* and preserves the `dateOfBirth` field which is specific to buyers.
|
||||
*
|
||||
* Type mapping: `customerType` (CRM) → `buyerType` (Checkout)
|
||||
*
|
||||
* @param customer - Customer from CRM service
|
||||
* @returns Buyer compatible with checkout-api
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const customer = await crmService.getCustomer(123);
|
||||
* const buyer = CustomerAdapter.toBuyer(customer);
|
||||
* await checkoutService.complete({ buyer, ... });
|
||||
* ```
|
||||
*/
|
||||
static toBuyer(customer: Customer): Buyer {
|
||||
return {
|
||||
source: customer.id,
|
||||
reference: { id: customer.id },
|
||||
buyerType: customer.customerType,
|
||||
buyerNumber: customer.customerNumber,
|
||||
gender: customer.gender,
|
||||
title: customer.title,
|
||||
firstName: customer.firstName,
|
||||
lastName: customer.lastName,
|
||||
dateOfBirth: customer.dateOfBirth,
|
||||
communicationDetails: customer.communicationDetails
|
||||
? { ...customer.communicationDetails }
|
||||
: undefined,
|
||||
organisation: customer.organisation
|
||||
? { ...customer.organisation }
|
||||
: undefined,
|
||||
address: customer.address ? { ...customer.address } : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts Customer to checkout-api Payer.
|
||||
*
|
||||
* @remarks
|
||||
* Used when the customer acts as their own payer (self-paying scenarios,
|
||||
* B2B customers, staff, customer card holders without separate billing address).
|
||||
*
|
||||
* **Important differences from toBuyer:**
|
||||
* - No `source` field (indicates derived data, not a separate entity)
|
||||
* - No `dateOfBirth` field (not relevant for payer)
|
||||
* - Sets `payerStatus: 0` (active status by default)
|
||||
*
|
||||
* Type mapping: `customerType` (CRM) → `payerType` (Checkout)
|
||||
*
|
||||
* @param customer - Customer from CRM service
|
||||
* @returns Payer compatible with checkout-api
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const customer = await crmService.getCustomer(123);
|
||||
* const payer = CustomerAdapter.toPayerFromCustomer(customer);
|
||||
* await checkoutService.complete({ payer, ... });
|
||||
* ```
|
||||
*/
|
||||
static toPayerFromCustomer(customer: Customer): Payer {
|
||||
return {
|
||||
reference: { id: customer.id },
|
||||
payerType: customer.customerType as Payer['payerType'],
|
||||
payerNumber: customer.customerNumber,
|
||||
payerStatus: 0, // Default status: active
|
||||
gender: customer.gender,
|
||||
title: customer.title,
|
||||
firstName: customer.firstName,
|
||||
lastName: customer.lastName,
|
||||
communicationDetails: customer.communicationDetails
|
||||
? { ...customer.communicationDetails }
|
||||
: undefined,
|
||||
organisation: customer.organisation
|
||||
? { ...customer.organisation }
|
||||
: undefined,
|
||||
address: customer.address ? { ...customer.address } : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts AssignedPayer (EntityContainer wrapper) to checkout-api Payer.
|
||||
*
|
||||
* @remarks
|
||||
* Used when customer has a separate billing address/payer entity assigned.
|
||||
* Handles the CRM's `EntityContainer` structure which wraps payer data.
|
||||
*
|
||||
* **Container structure:**
|
||||
* ```typescript
|
||||
* assignedPayer: {
|
||||
* payer: {
|
||||
* id: number;
|
||||
* data?: PayerDTO; // Actual payer data
|
||||
* displayName?: string;
|
||||
* enabled?: boolean;
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* Returns `null` if the payer data is missing or the container is invalid.
|
||||
* Includes `source` field as this references a persistent payer entity.
|
||||
*
|
||||
* @param assignedPayer - AssignedPayer container from CRM service
|
||||
* @returns Payer compatible with checkout-api, or null if data is missing
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const assignedPayer = customer.payers.find(p => p.payer.id === selectedPayerId);
|
||||
* const payer = CustomerAdapter.toPayerFromAssignedPayer(assignedPayer);
|
||||
* if (payer) {
|
||||
* await checkoutService.complete({ payer, ... });
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
static toPayerFromAssignedPayer(
|
||||
assignedPayer: AssignedPayer,
|
||||
): Payer | null {
|
||||
const payer = assignedPayer?.payer?.data;
|
||||
|
||||
if (!payer) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
reference: { id: payer.id },
|
||||
payerType: payer.payerType,
|
||||
payerNumber: payer.payerNumber,
|
||||
payerStatus: payer.payerStatus,
|
||||
gender: payer.gender,
|
||||
title: payer.title,
|
||||
firstName: payer.firstName,
|
||||
lastName: payer.lastName,
|
||||
communicationDetails: payer.communicationDetails
|
||||
? { ...payer.communicationDetails }
|
||||
: undefined,
|
||||
organisation: payer.organisation ? { ...payer.organisation } : undefined,
|
||||
address: payer.address ? { ...payer.address } : undefined,
|
||||
source: payer.id,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Type guard for Customer
|
||||
*
|
||||
* @param value - Value to check
|
||||
* @returns true if value is a valid Customer with required fields
|
||||
*/
|
||||
static isValidCustomer(value: unknown): value is Customer {
|
||||
if (typeof value !== 'object' || value === null) return false;
|
||||
|
||||
const customer = value as Customer;
|
||||
return (
|
||||
typeof customer.id === 'number' &&
|
||||
(customer.customerNumber === undefined ||
|
||||
typeof customer.customerNumber === 'string')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Type guard for AssignedPayer
|
||||
*
|
||||
* @param value - Value to check
|
||||
* @returns true if value is a valid AssignedPayer with container structure
|
||||
*/
|
||||
static isValidAssignedPayer(value: unknown): value is AssignedPayer {
|
||||
if (typeof value !== 'object' || value === null) return false;
|
||||
|
||||
const assignedPayer = value as AssignedPayer;
|
||||
return (
|
||||
typeof assignedPayer.payer === 'object' &&
|
||||
assignedPayer.payer !== null &&
|
||||
typeof assignedPayer.payer.id === 'number'
|
||||
);
|
||||
}
|
||||
}
|
||||
import { Customer, AssignedPayer } from '@isa/crm/data-access';
|
||||
import { Buyer, Payer } from '../schemas';
|
||||
|
||||
/**
|
||||
* Adapter for converting CRM customer data to checkout-api format.
|
||||
*
|
||||
* Handles three distinct conversion scenarios:
|
||||
* 1. **Customer to Buyer** (`toBuyer`): Converts customer for checkout as the buyer.
|
||||
* 2. **Customer to Payer** (`toPayerFromCustomer`): Uses customer as payer (self-paying).
|
||||
* 3. **AssignedPayer to Payer** (`toPayerFromAssignedPayer`): Unwraps separate payer entity.
|
||||
*
|
||||
* **Key Patterns:**
|
||||
* - Buyer conversion includes `dateOfBirth` and `source` field
|
||||
* - Payer from customer omits `source`, sets default `payerStatus: 0`
|
||||
* - AssignedPayer unwrapping handles `EntityContainer` structure with null safety
|
||||
*/
|
||||
export class CustomerAdapter {
|
||||
private static readonly ADAPTER_NAME = 'CustomerAdapter';
|
||||
|
||||
/**
|
||||
* Converts Customer to checkout-api Buyer.
|
||||
*
|
||||
* @remarks
|
||||
* Used when the customer is the buyer in a checkout flow. Maps all relevant
|
||||
* customer information including personal details, address, and organization.
|
||||
*
|
||||
* The buyer includes a `source` field referencing the customer entity ID,
|
||||
* and preserves the `dateOfBirth` field which is specific to buyers.
|
||||
*
|
||||
* Type mapping: `customerType` (CRM) → `buyerType` (Checkout)
|
||||
*
|
||||
* @param customer - Customer from CRM service
|
||||
* @returns Buyer compatible with checkout-api
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const customer = await crmService.getCustomer(123);
|
||||
* const buyer = CustomerAdapter.toBuyer(customer);
|
||||
* await checkoutService.complete({ buyer, ... });
|
||||
* ```
|
||||
*/
|
||||
static toBuyer(customer: Customer): Buyer {
|
||||
return {
|
||||
source: customer.id,
|
||||
reference: {
|
||||
id: customer.id,
|
||||
// Explicitly omit externalReference to avoid TypeScript errors
|
||||
// (generated DTOs require externalStatus when externalReference is present)
|
||||
},
|
||||
buyerType: customer.customerType,
|
||||
buyerNumber: customer.customerNumber,
|
||||
gender: customer.gender,
|
||||
title: customer.title,
|
||||
firstName: customer.firstName,
|
||||
lastName: customer.lastName,
|
||||
dateOfBirth: customer.dateOfBirth,
|
||||
communicationDetails: customer.communicationDetails
|
||||
? { ...customer.communicationDetails }
|
||||
: undefined,
|
||||
organisation: customer.organisation
|
||||
? { ...customer.organisation }
|
||||
: undefined,
|
||||
address: customer.address ? { ...customer.address } : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts Customer to checkout-api Payer.
|
||||
*
|
||||
* @remarks
|
||||
* Used when the customer acts as their own payer (self-paying scenarios,
|
||||
* B2B customers, staff, customer card holders without separate billing address).
|
||||
*
|
||||
* **Important differences from toBuyer:**
|
||||
* - No `source` field (indicates derived data, not a separate entity)
|
||||
* - No `dateOfBirth` field (not relevant for payer)
|
||||
* - Sets `payerStatus: 0` (active status by default)
|
||||
*
|
||||
* Type mapping: `customerType` (CRM) → `payerType` (Checkout)
|
||||
*
|
||||
* @param customer - Customer from CRM service
|
||||
* @returns Payer compatible with checkout-api
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const customer = await crmService.getCustomer(123);
|
||||
* const payer = CustomerAdapter.toPayerFromCustomer(customer);
|
||||
* await checkoutService.complete({ payer, ... });
|
||||
* ```
|
||||
*/
|
||||
static toPayerFromCustomer(customer: Customer): Payer {
|
||||
return {
|
||||
reference: {
|
||||
id: customer.id,
|
||||
// Explicitly omit externalReference to avoid TypeScript errors
|
||||
// (generated DTOs require externalStatus when externalReference is present)
|
||||
},
|
||||
payerType: customer.customerType as Payer['payerType'],
|
||||
payerNumber: customer.customerNumber,
|
||||
payerStatus: 0, // Default status: active
|
||||
gender: customer.gender,
|
||||
title: customer.title,
|
||||
firstName: customer.firstName,
|
||||
lastName: customer.lastName,
|
||||
communicationDetails: customer.communicationDetails
|
||||
? { ...customer.communicationDetails }
|
||||
: undefined,
|
||||
organisation: customer.organisation
|
||||
? { ...customer.organisation }
|
||||
: undefined,
|
||||
address: customer.address ? { ...customer.address } : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts AssignedPayer (EntityContainer wrapper) to checkout-api Payer.
|
||||
*
|
||||
* @remarks
|
||||
* Used when customer has a separate billing address/payer entity assigned.
|
||||
* Handles the CRM's `EntityContainer` structure which wraps payer data.
|
||||
*
|
||||
* **Container structure:**
|
||||
* ```typescript
|
||||
* assignedPayer: {
|
||||
* payer: {
|
||||
* id: number;
|
||||
* data?: PayerDTO; // Actual payer data
|
||||
* displayName?: string;
|
||||
* enabled?: boolean;
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* Returns `null` if the payer data is missing or the container is invalid.
|
||||
* Includes `source` field as this references a persistent payer entity.
|
||||
*
|
||||
* @param assignedPayer - AssignedPayer container from CRM service
|
||||
* @returns Payer compatible with checkout-api, or null if data is missing
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const assignedPayer = customer.payers.find(p => p.payer.id === selectedPayerId);
|
||||
* const payer = CustomerAdapter.toPayerFromAssignedPayer(assignedPayer);
|
||||
* if (payer) {
|
||||
* await checkoutService.complete({ payer, ... });
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
static toPayerFromAssignedPayer(assignedPayer: AssignedPayer): Payer | null {
|
||||
const payer = assignedPayer?.payer?.data;
|
||||
|
||||
if (!payer) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
reference: {
|
||||
id: payer.id,
|
||||
// Explicitly omit externalReference to avoid TypeScript errors
|
||||
// (generated DTOs require externalStatus when externalReference is present)
|
||||
},
|
||||
payerType: payer.payerType,
|
||||
payerNumber: payer.payerNumber,
|
||||
payerStatus: payer.payerStatus,
|
||||
gender: payer.gender,
|
||||
title: payer.title,
|
||||
firstName: payer.firstName,
|
||||
lastName: payer.lastName,
|
||||
communicationDetails: payer.communicationDetails
|
||||
? { ...payer.communicationDetails }
|
||||
: undefined,
|
||||
organisation: payer.organisation ? { ...payer.organisation } : undefined,
|
||||
address: payer.address ? { ...payer.address } : undefined,
|
||||
source: payer.id,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Type guard for Customer
|
||||
*
|
||||
* @param value - Value to check
|
||||
* @returns true if value is a valid Customer with required fields
|
||||
*/
|
||||
static isValidCustomer(value: unknown): value is Customer {
|
||||
if (typeof value !== 'object' || value === null) return false;
|
||||
|
||||
const customer = value as Customer;
|
||||
return (
|
||||
typeof customer.id === 'number' &&
|
||||
(customer.customerNumber === undefined ||
|
||||
typeof customer.customerNumber === 'string')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Type guard for AssignedPayer
|
||||
*
|
||||
* @param value - Value to check
|
||||
* @returns true if value is a valid AssignedPayer with container structure
|
||||
*/
|
||||
static isValidAssignedPayer(value: unknown): value is AssignedPayer {
|
||||
if (typeof value !== 'object' || value === null) return false;
|
||||
|
||||
const assignedPayer = value as AssignedPayer;
|
||||
return (
|
||||
typeof assignedPayer.payer === 'object' &&
|
||||
assignedPayer.payer !== null &&
|
||||
typeof assignedPayer.payer.id === 'number'
|
||||
);
|
||||
}
|
||||
|
||||
static extractCustomerFeatures(customer: Customer): Record<string, any> {
|
||||
const features = customer.features || [];
|
||||
return features.reduce((acc: Record<string, string>, feature: any) => {
|
||||
acc[feature.key] = feature.key;
|
||||
return acc;
|
||||
}, {});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,73 +1,76 @@
|
||||
import { Payer as CrmPayer } from '@isa/crm/data-access';
|
||||
import { Payer } from '../models';
|
||||
|
||||
/**
|
||||
* Adapter for converting CRM-api payer responses to checkout-api format.
|
||||
*
|
||||
* Handles:
|
||||
* - Filtering CRM-specific fields (agentComment, deactivationComment, etc.)
|
||||
* - Entity reference creation (reference.id, source)
|
||||
* - Nested object copying (communicationDetails, organisation, address)
|
||||
*/
|
||||
export class PayerAdapter {
|
||||
private static readonly ADAPTER_NAME = 'PayerAdapter';
|
||||
|
||||
/**
|
||||
* Converts CRM-api payer to checkout-api Payer.
|
||||
*
|
||||
* @remarks
|
||||
* Maps payer information from the CRM domain to the checkout domain's
|
||||
* payer representation. CRM-specific fields like agentComment, deactivationComment,
|
||||
* defaultPaymentPeriod, isGuestAccount, payerGroup, paymentTypes,
|
||||
* standardInvoiceText, statusChangeComment, and statusComment are filtered out.
|
||||
*
|
||||
* Nested objects (communicationDetails, organisation, address) are shallow-copied
|
||||
* to prevent unintended mutations.
|
||||
*
|
||||
* @param crmPayer - Raw payer from CRM service
|
||||
* @returns Payer compatible with checkout-api
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const checkoutPayer = PayerAdapter.toCheckoutFormat(crmPayer);
|
||||
* await checkoutService.complete({ payer: checkoutPayer, ... });
|
||||
* ```
|
||||
*/
|
||||
static toCheckoutFormat(crmPayer: CrmPayer): Payer {
|
||||
return {
|
||||
reference: { id: crmPayer.id },
|
||||
source: crmPayer.id,
|
||||
payerType: crmPayer.payerType,
|
||||
payerNumber: crmPayer.payerNumber,
|
||||
payerStatus: crmPayer.payerStatus,
|
||||
gender: crmPayer.gender,
|
||||
title: crmPayer.title,
|
||||
firstName: crmPayer.firstName,
|
||||
lastName: crmPayer.lastName,
|
||||
communicationDetails: crmPayer.communicationDetails
|
||||
? { ...crmPayer.communicationDetails }
|
||||
: undefined,
|
||||
organisation: crmPayer.organisation
|
||||
? { ...crmPayer.organisation }
|
||||
: undefined,
|
||||
address: crmPayer.address ? { ...crmPayer.address } : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Type guard for CRM payer response
|
||||
*
|
||||
* @param value - Value to check
|
||||
* @returns true if value is a valid CRM payer with required fields
|
||||
*/
|
||||
static isValidCrmPayer(value: unknown): value is CrmPayer {
|
||||
if (typeof value !== 'object' || value === null) return false;
|
||||
|
||||
const payer = value as CrmPayer;
|
||||
return (
|
||||
typeof payer.id === 'number' &&
|
||||
(payer.payerNumber === undefined ||
|
||||
typeof payer.payerNumber === 'string')
|
||||
);
|
||||
}
|
||||
}
|
||||
import { Payer as CrmPayer } from '@isa/crm/data-access';
|
||||
import { Payer } from '../schemas';
|
||||
|
||||
/**
|
||||
* Adapter for converting CRM-api payer responses to checkout-api format.
|
||||
*
|
||||
* Handles:
|
||||
* - Filtering CRM-specific fields (agentComment, deactivationComment, etc.)
|
||||
* - Entity reference creation (reference.id, source)
|
||||
* - Nested object copying (communicationDetails, organisation, address)
|
||||
*/
|
||||
export class PayerAdapter {
|
||||
private static readonly ADAPTER_NAME = 'PayerAdapter';
|
||||
|
||||
/**
|
||||
* Converts CRM-api payer to checkout-api Payer.
|
||||
*
|
||||
* @remarks
|
||||
* Maps payer information from the CRM domain to the checkout domain's
|
||||
* payer representation. CRM-specific fields like agentComment, deactivationComment,
|
||||
* defaultPaymentPeriod, isGuestAccount, payerGroup, paymentTypes,
|
||||
* standardInvoiceText, statusChangeComment, and statusComment are filtered out.
|
||||
*
|
||||
* Nested objects (communicationDetails, organisation, address) are shallow-copied
|
||||
* to prevent unintended mutations.
|
||||
*
|
||||
* @param crmPayer - Raw payer from CRM service (optional)
|
||||
* @returns Payer compatible with checkout-api, or undefined if payer is not provided
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const checkoutPayer = PayerAdapter.toCheckoutFormat(crmPayer);
|
||||
* await checkoutService.complete({ payer: checkoutPayer, ... });
|
||||
* ```
|
||||
*/
|
||||
static toCheckoutFormat(crmPayer: CrmPayer | undefined): Payer | undefined {
|
||||
if (!crmPayer) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return {
|
||||
reference: { id: crmPayer.id },
|
||||
source: crmPayer.id,
|
||||
payerType: crmPayer.payerType,
|
||||
payerNumber: crmPayer.payerNumber,
|
||||
payerStatus: crmPayer.payerStatus,
|
||||
gender: crmPayer.gender,
|
||||
title: crmPayer.title,
|
||||
firstName: crmPayer.firstName,
|
||||
lastName: crmPayer.lastName,
|
||||
communicationDetails: crmPayer.communicationDetails
|
||||
? { ...crmPayer.communicationDetails }
|
||||
: undefined,
|
||||
organisation: crmPayer.organisation
|
||||
? { ...crmPayer.organisation }
|
||||
: undefined,
|
||||
address: crmPayer.address ? { ...crmPayer.address } : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Type guard for CRM payer response
|
||||
*
|
||||
* @param value - Value to check
|
||||
* @returns true if value is a valid CRM payer with required fields
|
||||
*/
|
||||
static isValidCrmPayer(value: unknown): value is CrmPayer {
|
||||
if (typeof value !== 'object' || value === null) return false;
|
||||
|
||||
const payer = value as CrmPayer;
|
||||
return (
|
||||
typeof payer.id === 'number' &&
|
||||
(payer.payerNumber === undefined || typeof payer.payerNumber === 'string')
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,357 +1,373 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { ShippingAddressAdapter } from './shipping-address.adapter';
|
||||
import {
|
||||
ShippingAddressDTO as CrmShippingAddressDTO,
|
||||
CustomerDTO,
|
||||
} from '@generated/swagger/crm-api';
|
||||
|
||||
describe('ShippingAddressAdapter', () => {
|
||||
describe('fromCrmShippingAddress', () => {
|
||||
it('should convert CRM shipping address to checkout format', () => {
|
||||
// Arrange
|
||||
const crmAddress: CrmShippingAddressDTO = {
|
||||
id: 789,
|
||||
gender: 2,
|
||||
title: 'Dr.',
|
||||
firstName: 'Delivery',
|
||||
lastName: 'Address',
|
||||
communicationDetails: {
|
||||
phone: '+49 123 111111',
|
||||
mobile: '+49 170 2222222',
|
||||
},
|
||||
organisation: {
|
||||
name: 'Delivery Company',
|
||||
department: 'Receiving',
|
||||
},
|
||||
address: {
|
||||
street: 'Delivery Lane',
|
||||
streetNumber: '42',
|
||||
zipCode: '67890',
|
||||
city: 'Munich',
|
||||
country: 'DE',
|
||||
},
|
||||
// CRM-specific fields (should be dropped)
|
||||
type: 1 as any,
|
||||
validated: '2024-01-01',
|
||||
validationResult: 100,
|
||||
agentComment: 'Verified address',
|
||||
isDefault: '2024-01-01',
|
||||
} as CrmShippingAddressDTO;
|
||||
|
||||
// Act
|
||||
const checkoutAddress =
|
||||
ShippingAddressAdapter.fromCrmShippingAddress(crmAddress);
|
||||
|
||||
// Assert
|
||||
expect(checkoutAddress).toEqual({
|
||||
reference: { id: 789 },
|
||||
source: 789,
|
||||
gender: 2,
|
||||
title: 'Dr.',
|
||||
firstName: 'Delivery',
|
||||
lastName: 'Address',
|
||||
communicationDetails: {
|
||||
phone: '+49 123 111111',
|
||||
mobile: '+49 170 2222222',
|
||||
},
|
||||
organisation: {
|
||||
name: 'Delivery Company',
|
||||
department: 'Receiving',
|
||||
},
|
||||
address: {
|
||||
street: 'Delivery Lane',
|
||||
streetNumber: '42',
|
||||
zipCode: '67890',
|
||||
city: 'Munich',
|
||||
country: 'DE',
|
||||
},
|
||||
});
|
||||
|
||||
// Verify CRM-specific fields are not included
|
||||
expect((checkoutAddress as any).type).toBeUndefined();
|
||||
expect((checkoutAddress as any).validated).toBeUndefined();
|
||||
expect((checkoutAddress as any).validationResult).toBeUndefined();
|
||||
expect((checkoutAddress as any).agentComment).toBeUndefined();
|
||||
expect((checkoutAddress as any).isDefault).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should handle shipping address with minimal data', () => {
|
||||
// Arrange
|
||||
const crmAddress: CrmShippingAddressDTO = {
|
||||
id: 321,
|
||||
firstName: 'Simple',
|
||||
lastName: 'Address',
|
||||
} as CrmShippingAddressDTO;
|
||||
|
||||
// Act
|
||||
const checkoutAddress =
|
||||
ShippingAddressAdapter.fromCrmShippingAddress(crmAddress);
|
||||
|
||||
// Assert
|
||||
expect(checkoutAddress.reference).toEqual({ id: 321 });
|
||||
expect(checkoutAddress.source).toBe(321);
|
||||
expect(checkoutAddress.firstName).toBe('Simple');
|
||||
expect(checkoutAddress.lastName).toBe('Address');
|
||||
expect(checkoutAddress.communicationDetails).toBeUndefined();
|
||||
expect(checkoutAddress.organisation).toBeUndefined();
|
||||
expect(checkoutAddress.address).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should copy nested objects (not reference)', () => {
|
||||
// Arrange
|
||||
const communicationDetails = { email: 'shipping@example.com' };
|
||||
const organisation = { name: 'Shipping Org' };
|
||||
const address = { street: 'Ship St', zipCode: '99999' };
|
||||
|
||||
const crmAddress: CrmShippingAddressDTO = {
|
||||
id: 555,
|
||||
firstName: 'Test',
|
||||
lastName: 'Shipping',
|
||||
communicationDetails,
|
||||
organisation,
|
||||
address,
|
||||
} as CrmShippingAddressDTO;
|
||||
|
||||
// Act
|
||||
const checkoutAddress =
|
||||
ShippingAddressAdapter.fromCrmShippingAddress(crmAddress);
|
||||
|
||||
// Assert
|
||||
expect(checkoutAddress.communicationDetails).toEqual(communicationDetails);
|
||||
expect(checkoutAddress.communicationDetails).not.toBe(communicationDetails);
|
||||
expect(checkoutAddress.organisation).toEqual(organisation);
|
||||
expect(checkoutAddress.organisation).not.toBe(organisation);
|
||||
expect(checkoutAddress.address).toEqual(address);
|
||||
expect(checkoutAddress.address).not.toBe(address);
|
||||
});
|
||||
});
|
||||
|
||||
describe('fromCustomer', () => {
|
||||
it('should convert customer to shipping address with full data', () => {
|
||||
// Arrange
|
||||
const customer: CustomerDTO = {
|
||||
id: 999,
|
||||
customerNumber: 'CUST-999',
|
||||
gender: 1,
|
||||
title: 'Mx.',
|
||||
firstName: 'Alex',
|
||||
lastName: 'Taylor',
|
||||
communicationDetails: {
|
||||
email: 'alex.taylor@example.com',
|
||||
phone: '+49 555 123456',
|
||||
},
|
||||
organisation: {
|
||||
name: 'Taylor Industries',
|
||||
},
|
||||
address: {
|
||||
street: 'Primary St',
|
||||
streetNumber: '100',
|
||||
zipCode: '10115',
|
||||
city: 'Berlin',
|
||||
country: 'DE',
|
||||
},
|
||||
} as CustomerDTO;
|
||||
|
||||
// Act
|
||||
const shippingAddress = ShippingAddressAdapter.fromCustomer(customer);
|
||||
|
||||
// Assert
|
||||
expect(shippingAddress).toEqual({
|
||||
reference: { id: 999 },
|
||||
gender: 1,
|
||||
title: 'Mx.',
|
||||
firstName: 'Alex',
|
||||
lastName: 'Taylor',
|
||||
communicationDetails: {
|
||||
email: 'alex.taylor@example.com',
|
||||
phone: '+49 555 123456',
|
||||
},
|
||||
organisation: {
|
||||
name: 'Taylor Industries',
|
||||
},
|
||||
address: {
|
||||
street: 'Primary St',
|
||||
streetNumber: '100',
|
||||
zipCode: '10115',
|
||||
city: 'Berlin',
|
||||
country: 'DE',
|
||||
},
|
||||
});
|
||||
|
||||
// No source field when derived from customer
|
||||
expect((shippingAddress as any).source).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should handle customer with minimal data', () => {
|
||||
// Arrange
|
||||
const customer: CustomerDTO = {
|
||||
id: 777,
|
||||
customerNumber: 'CUST-777',
|
||||
firstName: 'Min',
|
||||
lastName: 'Address',
|
||||
} as CustomerDTO;
|
||||
|
||||
// Act
|
||||
const shippingAddress = ShippingAddressAdapter.fromCustomer(customer);
|
||||
|
||||
// Assert
|
||||
expect(shippingAddress.reference).toEqual({ id: 777 });
|
||||
expect(shippingAddress.firstName).toBe('Min');
|
||||
expect(shippingAddress.lastName).toBe('Address');
|
||||
expect(shippingAddress.communicationDetails).toBeUndefined();
|
||||
expect(shippingAddress.organisation).toBeUndefined();
|
||||
expect(shippingAddress.address).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should copy nested objects (not reference)', () => {
|
||||
// Arrange
|
||||
const communicationDetails = { email: 'customer@address.com' };
|
||||
const organisation = { name: 'Address Org' };
|
||||
const address = { street: 'Address St', zipCode: '88888' };
|
||||
|
||||
const customer: CustomerDTO = {
|
||||
id: 888,
|
||||
customerNumber: 'CUST-888',
|
||||
firstName: 'Test',
|
||||
lastName: 'Customer',
|
||||
communicationDetails,
|
||||
organisation,
|
||||
address,
|
||||
} as CustomerDTO;
|
||||
|
||||
// Act
|
||||
const shippingAddress = ShippingAddressAdapter.fromCustomer(customer);
|
||||
|
||||
// Assert
|
||||
expect(shippingAddress.communicationDetails).toEqual(communicationDetails);
|
||||
expect(shippingAddress.communicationDetails).not.toBe(communicationDetails);
|
||||
expect(shippingAddress.organisation).toEqual(organisation);
|
||||
expect(shippingAddress.organisation).not.toBe(organisation);
|
||||
expect(shippingAddress.address).toEqual(address);
|
||||
expect(shippingAddress.address).not.toBe(address);
|
||||
});
|
||||
|
||||
it('should not include source field (different from CRM shipping address)', () => {
|
||||
// Arrange
|
||||
const customer: CustomerDTO = {
|
||||
id: 666,
|
||||
customerNumber: 'CUST-666',
|
||||
firstName: 'No',
|
||||
lastName: 'Source',
|
||||
} as CustomerDTO;
|
||||
|
||||
// Act
|
||||
const shippingAddress = ShippingAddressAdapter.fromCustomer(customer);
|
||||
|
||||
// Assert
|
||||
expect(shippingAddress).not.toHaveProperty('source');
|
||||
});
|
||||
});
|
||||
|
||||
describe('isValidCrmShippingAddress', () => {
|
||||
it('should return true for valid CRM shipping address', () => {
|
||||
// Arrange
|
||||
const validAddress: CrmShippingAddressDTO = {
|
||||
id: 123,
|
||||
firstName: 'Valid',
|
||||
lastName: 'Address',
|
||||
} as CrmShippingAddressDTO;
|
||||
|
||||
// Act & Assert
|
||||
expect(
|
||||
ShippingAddressAdapter.isValidCrmShippingAddress(validAddress),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false for invalid types', () => {
|
||||
// Act & Assert
|
||||
expect(ShippingAddressAdapter.isValidCrmShippingAddress(null)).toBe(
|
||||
false,
|
||||
);
|
||||
expect(ShippingAddressAdapter.isValidCrmShippingAddress(undefined)).toBe(
|
||||
false,
|
||||
);
|
||||
expect(ShippingAddressAdapter.isValidCrmShippingAddress('string')).toBe(
|
||||
false,
|
||||
);
|
||||
expect(ShippingAddressAdapter.isValidCrmShippingAddress([])).toBe(false);
|
||||
expect(ShippingAddressAdapter.isValidCrmShippingAddress(123)).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false for missing required id', () => {
|
||||
// Arrange
|
||||
const invalidAddress = {
|
||||
firstName: 'Invalid',
|
||||
lastName: 'Address',
|
||||
};
|
||||
|
||||
// Act & Assert
|
||||
expect(
|
||||
ShippingAddressAdapter.isValidCrmShippingAddress(invalidAddress),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isValidCustomer', () => {
|
||||
it('should return true for valid Customer', () => {
|
||||
// Arrange
|
||||
const validCustomer: CustomerDTO = {
|
||||
id: 456,
|
||||
customerNumber: 'CUST-456',
|
||||
firstName: 'Valid',
|
||||
lastName: 'Customer',
|
||||
} as CustomerDTO;
|
||||
|
||||
// Act & Assert
|
||||
expect(ShippingAddressAdapter.isValidCustomer(validCustomer)).toBe(true);
|
||||
});
|
||||
|
||||
it('should return true for customer without optional customerNumber', () => {
|
||||
// Arrange
|
||||
const validCustomer = {
|
||||
id: 789,
|
||||
firstName: 'Valid',
|
||||
lastName: 'Customer',
|
||||
};
|
||||
|
||||
// Act & Assert
|
||||
expect(ShippingAddressAdapter.isValidCustomer(validCustomer)).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false for invalid types', () => {
|
||||
// Act & Assert
|
||||
expect(ShippingAddressAdapter.isValidCustomer(null)).toBe(false);
|
||||
expect(ShippingAddressAdapter.isValidCustomer(undefined)).toBe(false);
|
||||
expect(ShippingAddressAdapter.isValidCustomer('string')).toBe(false);
|
||||
expect(ShippingAddressAdapter.isValidCustomer([])).toBe(false);
|
||||
expect(ShippingAddressAdapter.isValidCustomer(123)).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false for missing required id', () => {
|
||||
// Arrange
|
||||
const invalidCustomer = {
|
||||
customerNumber: 'CUST-123',
|
||||
firstName: 'Invalid',
|
||||
lastName: 'Customer',
|
||||
};
|
||||
|
||||
// Act & Assert
|
||||
expect(ShippingAddressAdapter.isValidCustomer(invalidCustomer)).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it('should return false for incorrect field types', () => {
|
||||
// Arrange
|
||||
const invalidCustomers = [
|
||||
{ id: 'string', customerNumber: 'CUST-123' }, // id should be number
|
||||
{ id: 123, customerNumber: 456 }, // customerNumber should be string
|
||||
];
|
||||
|
||||
// Act & Assert
|
||||
invalidCustomers.forEach((customer) => {
|
||||
expect(ShippingAddressAdapter.isValidCustomer(customer)).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { ShippingAddressAdapter } from './shipping-address.adapter';
|
||||
import {
|
||||
ShippingAddressDTO as CrmShippingAddressDTO,
|
||||
CustomerDTO,
|
||||
} from '@generated/swagger/crm-api';
|
||||
|
||||
describe('ShippingAddressAdapter', () => {
|
||||
describe('fromCrmShippingAddress', () => {
|
||||
it('should convert CRM shipping address to checkout format', () => {
|
||||
// Arrange
|
||||
const crmAddress: CrmShippingAddressDTO = {
|
||||
id: 789,
|
||||
gender: 2,
|
||||
title: 'Dr.',
|
||||
firstName: 'Delivery',
|
||||
lastName: 'Address',
|
||||
communicationDetails: {
|
||||
phone: '+49 123 111111',
|
||||
mobile: '+49 170 2222222',
|
||||
},
|
||||
organisation: {
|
||||
name: 'Delivery Company',
|
||||
department: 'Receiving',
|
||||
},
|
||||
address: {
|
||||
street: 'Delivery Lane',
|
||||
streetNumber: '42',
|
||||
zipCode: '67890',
|
||||
city: 'Munich',
|
||||
country: 'DE',
|
||||
},
|
||||
// CRM-specific fields (should be dropped)
|
||||
type: 1 as any,
|
||||
validated: '2024-01-01',
|
||||
validationResult: 100,
|
||||
agentComment: 'Verified address',
|
||||
isDefault: '2024-01-01',
|
||||
} as CrmShippingAddressDTO;
|
||||
|
||||
// Act
|
||||
const checkoutAddress =
|
||||
ShippingAddressAdapter.fromCrmShippingAddress(crmAddress);
|
||||
|
||||
// Assert
|
||||
expect(checkoutAddress).toEqual({
|
||||
reference: { id: 789 },
|
||||
source: 789,
|
||||
gender: 2,
|
||||
title: 'Dr.',
|
||||
firstName: 'Delivery',
|
||||
lastName: 'Address',
|
||||
communicationDetails: {
|
||||
phone: '+49 123 111111',
|
||||
mobile: '+49 170 2222222',
|
||||
},
|
||||
organisation: {
|
||||
name: 'Delivery Company',
|
||||
department: 'Receiving',
|
||||
},
|
||||
address: {
|
||||
street: 'Delivery Lane',
|
||||
streetNumber: '42',
|
||||
zipCode: '67890',
|
||||
city: 'Munich',
|
||||
country: 'DE',
|
||||
},
|
||||
});
|
||||
|
||||
// Verify CRM-specific fields are not included
|
||||
expect((checkoutAddress as any).type).toBeUndefined();
|
||||
expect((checkoutAddress as any).validated).toBeUndefined();
|
||||
expect((checkoutAddress as any).validationResult).toBeUndefined();
|
||||
expect((checkoutAddress as any).agentComment).toBeUndefined();
|
||||
expect((checkoutAddress as any).isDefault).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should handle shipping address with minimal data', () => {
|
||||
// Arrange
|
||||
const crmAddress: CrmShippingAddressDTO = {
|
||||
id: 321,
|
||||
firstName: 'Simple',
|
||||
lastName: 'Address',
|
||||
} as CrmShippingAddressDTO;
|
||||
|
||||
// Act
|
||||
const checkoutAddress =
|
||||
ShippingAddressAdapter.fromCrmShippingAddress(crmAddress);
|
||||
|
||||
// Assert
|
||||
expect(checkoutAddress.reference).toEqual({ id: 321 });
|
||||
expect(checkoutAddress.source).toBe(321);
|
||||
expect(checkoutAddress.firstName).toBe('Simple');
|
||||
expect(checkoutAddress.lastName).toBe('Address');
|
||||
expect(checkoutAddress.communicationDetails).toBeUndefined();
|
||||
expect(checkoutAddress.organisation).toBeUndefined();
|
||||
expect(checkoutAddress.address).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should copy nested objects (not reference)', () => {
|
||||
// Arrange
|
||||
const communicationDetails = { email: 'shipping@example.com' };
|
||||
const organisation = { name: 'Shipping Org' };
|
||||
const address = { street: 'Ship St', zipCode: '99999' };
|
||||
|
||||
const crmAddress: CrmShippingAddressDTO = {
|
||||
id: 555,
|
||||
firstName: 'Test',
|
||||
lastName: 'Shipping',
|
||||
communicationDetails,
|
||||
organisation,
|
||||
address,
|
||||
} as CrmShippingAddressDTO;
|
||||
|
||||
// Act
|
||||
const checkoutAddress =
|
||||
ShippingAddressAdapter.fromCrmShippingAddress(crmAddress);
|
||||
|
||||
// Assert
|
||||
expect(checkoutAddress.communicationDetails).toEqual(
|
||||
communicationDetails,
|
||||
);
|
||||
expect(checkoutAddress.communicationDetails).not.toBe(
|
||||
communicationDetails,
|
||||
);
|
||||
expect(checkoutAddress.organisation).toEqual(organisation);
|
||||
expect(checkoutAddress.organisation).not.toBe(organisation);
|
||||
expect(checkoutAddress.address).toEqual(address);
|
||||
expect(checkoutAddress.address).not.toBe(address);
|
||||
});
|
||||
});
|
||||
|
||||
describe('fromCustomer', () => {
|
||||
it('should convert customer to shipping address with full data', () => {
|
||||
// Arrange
|
||||
const customer: CustomerDTO = {
|
||||
id: 999,
|
||||
customerNumber: 'CUST-999',
|
||||
gender: 1,
|
||||
title: 'Mx.',
|
||||
firstName: 'Alex',
|
||||
lastName: 'Taylor',
|
||||
communicationDetails: {
|
||||
email: 'alex.taylor@example.com',
|
||||
phone: '+49 555 123456',
|
||||
},
|
||||
organisation: {
|
||||
name: 'Taylor Industries',
|
||||
},
|
||||
address: {
|
||||
street: 'Primary St',
|
||||
streetNumber: '100',
|
||||
zipCode: '10115',
|
||||
city: 'Berlin',
|
||||
country: 'DE',
|
||||
},
|
||||
} as CustomerDTO;
|
||||
|
||||
// Act
|
||||
const shippingAddress = ShippingAddressAdapter.fromCustomer(customer);
|
||||
|
||||
// Assert
|
||||
expect(shippingAddress).toEqual({
|
||||
reference: { id: 999 },
|
||||
gender: 1,
|
||||
title: 'Mx.',
|
||||
firstName: 'Alex',
|
||||
lastName: 'Taylor',
|
||||
communicationDetails: {
|
||||
email: 'alex.taylor@example.com',
|
||||
phone: '+49 555 123456',
|
||||
},
|
||||
organisation: {
|
||||
name: 'Taylor Industries',
|
||||
},
|
||||
address: {
|
||||
street: 'Primary St',
|
||||
streetNumber: '100',
|
||||
zipCode: '10115',
|
||||
city: 'Berlin',
|
||||
country: 'DE',
|
||||
additionalInfo: undefined,
|
||||
},
|
||||
});
|
||||
|
||||
// No source field when derived from customer
|
||||
expect((shippingAddress as any).source).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should handle customer with minimal data', () => {
|
||||
// Arrange
|
||||
const customer: CustomerDTO = {
|
||||
id: 777,
|
||||
customerNumber: 'CUST-777',
|
||||
firstName: 'Min',
|
||||
lastName: 'Address',
|
||||
} as CustomerDTO;
|
||||
|
||||
// Act
|
||||
const shippingAddress = ShippingAddressAdapter.fromCustomer(customer);
|
||||
|
||||
// Assert
|
||||
expect(shippingAddress.reference).toEqual({ id: 777 });
|
||||
expect(shippingAddress.firstName).toBe('Min');
|
||||
expect(shippingAddress.lastName).toBe('Address');
|
||||
expect(shippingAddress.communicationDetails).toBeUndefined();
|
||||
expect(shippingAddress.organisation).toBeUndefined();
|
||||
expect(shippingAddress.address).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should copy nested objects (not reference)', () => {
|
||||
// Arrange
|
||||
const communicationDetails = { email: 'customer@address.com' };
|
||||
const organisation = { name: 'Address Org' };
|
||||
const address = {
|
||||
street: 'Address St',
|
||||
zipCode: '88888',
|
||||
streetNumber: undefined,
|
||||
city: undefined,
|
||||
country: undefined,
|
||||
additionalInfo: undefined,
|
||||
};
|
||||
|
||||
const customer: CustomerDTO = {
|
||||
id: 888,
|
||||
customerNumber: 'CUST-888',
|
||||
firstName: 'Test',
|
||||
lastName: 'Customer',
|
||||
communicationDetails,
|
||||
organisation,
|
||||
address,
|
||||
} as CustomerDTO;
|
||||
|
||||
// Act
|
||||
const shippingAddress = ShippingAddressAdapter.fromCustomer(customer);
|
||||
|
||||
// Assert
|
||||
expect(shippingAddress.communicationDetails).toEqual(
|
||||
communicationDetails,
|
||||
);
|
||||
expect(shippingAddress.communicationDetails).not.toBe(
|
||||
communicationDetails,
|
||||
);
|
||||
expect(shippingAddress.organisation).toEqual(organisation);
|
||||
expect(shippingAddress.organisation).not.toBe(organisation);
|
||||
expect(shippingAddress.address).toEqual(address);
|
||||
expect(shippingAddress.address).not.toBe(address);
|
||||
});
|
||||
|
||||
it('should not include source field (different from CRM shipping address)', () => {
|
||||
// Arrange
|
||||
const customer: CustomerDTO = {
|
||||
id: 666,
|
||||
customerNumber: 'CUST-666',
|
||||
firstName: 'No',
|
||||
lastName: 'Source',
|
||||
} as CustomerDTO;
|
||||
|
||||
// Act
|
||||
const shippingAddress = ShippingAddressAdapter.fromCustomer(customer);
|
||||
|
||||
// Assert
|
||||
expect(shippingAddress).not.toHaveProperty('source');
|
||||
});
|
||||
});
|
||||
|
||||
describe('isValidCrmShippingAddress', () => {
|
||||
it('should return true for valid CRM shipping address', () => {
|
||||
// Arrange
|
||||
const validAddress: CrmShippingAddressDTO = {
|
||||
id: 123,
|
||||
firstName: 'Valid',
|
||||
lastName: 'Address',
|
||||
} as CrmShippingAddressDTO;
|
||||
|
||||
// Act & Assert
|
||||
expect(
|
||||
ShippingAddressAdapter.isValidCrmShippingAddress(validAddress),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false for invalid types', () => {
|
||||
// Act & Assert
|
||||
expect(ShippingAddressAdapter.isValidCrmShippingAddress(null)).toBe(
|
||||
false,
|
||||
);
|
||||
expect(ShippingAddressAdapter.isValidCrmShippingAddress(undefined)).toBe(
|
||||
false,
|
||||
);
|
||||
expect(ShippingAddressAdapter.isValidCrmShippingAddress('string')).toBe(
|
||||
false,
|
||||
);
|
||||
expect(ShippingAddressAdapter.isValidCrmShippingAddress([])).toBe(false);
|
||||
expect(ShippingAddressAdapter.isValidCrmShippingAddress(123)).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false for missing required id', () => {
|
||||
// Arrange
|
||||
const invalidAddress = {
|
||||
firstName: 'Invalid',
|
||||
lastName: 'Address',
|
||||
};
|
||||
|
||||
// Act & Assert
|
||||
expect(
|
||||
ShippingAddressAdapter.isValidCrmShippingAddress(invalidAddress),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isValidCustomer', () => {
|
||||
it('should return true for valid Customer', () => {
|
||||
// Arrange
|
||||
const validCustomer: CustomerDTO = {
|
||||
id: 456,
|
||||
customerNumber: 'CUST-456',
|
||||
firstName: 'Valid',
|
||||
lastName: 'Customer',
|
||||
} as CustomerDTO;
|
||||
|
||||
// Act & Assert
|
||||
expect(ShippingAddressAdapter.isValidCustomer(validCustomer)).toBe(true);
|
||||
});
|
||||
|
||||
it('should return true for customer without optional customerNumber', () => {
|
||||
// Arrange
|
||||
const validCustomer = {
|
||||
id: 789,
|
||||
firstName: 'Valid',
|
||||
lastName: 'Customer',
|
||||
};
|
||||
|
||||
// Act & Assert
|
||||
expect(ShippingAddressAdapter.isValidCustomer(validCustomer)).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false for invalid types', () => {
|
||||
// Act & Assert
|
||||
expect(ShippingAddressAdapter.isValidCustomer(null)).toBe(false);
|
||||
expect(ShippingAddressAdapter.isValidCustomer(undefined)).toBe(false);
|
||||
expect(ShippingAddressAdapter.isValidCustomer('string')).toBe(false);
|
||||
expect(ShippingAddressAdapter.isValidCustomer([])).toBe(false);
|
||||
expect(ShippingAddressAdapter.isValidCustomer(123)).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false for missing required id', () => {
|
||||
// Arrange
|
||||
const invalidCustomer = {
|
||||
customerNumber: 'CUST-123',
|
||||
firstName: 'Invalid',
|
||||
lastName: 'Customer',
|
||||
};
|
||||
|
||||
// Act & Assert
|
||||
expect(ShippingAddressAdapter.isValidCustomer(invalidCustomer)).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it('should return false for incorrect field types', () => {
|
||||
// Arrange
|
||||
const invalidCustomers = [
|
||||
{ id: 'string', customerNumber: 'CUST-123' }, // id should be number
|
||||
{ id: 123, customerNumber: 456 }, // customerNumber should be string
|
||||
];
|
||||
|
||||
// Act & Assert
|
||||
invalidCustomers.forEach((customer) => {
|
||||
expect(ShippingAddressAdapter.isValidCustomer(customer)).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,136 +1,156 @@
|
||||
import { Customer } from '@isa/crm/data-access';
|
||||
import { ShippingAddressDTO as CrmShippingAddressDTO } from '@generated/swagger/crm-api';
|
||||
import { ShippingAddressDTO as CheckoutShippingAddressDTO } from '@generated/swagger/checkout-api';
|
||||
|
||||
/**
|
||||
* Adapter for converting CRM shipping address data to checkout-api format.
|
||||
*
|
||||
* Handles two distinct conversion scenarios:
|
||||
* 1. **Separate Shipping Address Entity** (`fromCrmShippingAddress`): Converts a dedicated
|
||||
* shipping address from CRM with `source` field, indicating a persistent entity.
|
||||
* 2. **Customer Primary Address** (`fromCustomer`): Derives shipping address from customer's
|
||||
* primary address without `source` field, indicating transient/derived data.
|
||||
*
|
||||
* **Key Differences:**
|
||||
* - CRM ShippingAddressDTO: Filters out CRM-specific fields (type, validated, agentComment, etc.)
|
||||
* - Customer Address: Uses customer ID for reference, omits `source` field
|
||||
*/
|
||||
export class ShippingAddressAdapter {
|
||||
private static readonly ADAPTER_NAME = 'ShippingAddressAdapter';
|
||||
|
||||
/**
|
||||
* Converts CRM-api ShippingAddressDTO to checkout-api format.
|
||||
*
|
||||
* @remarks
|
||||
* Used when customer has separate delivery addresses stored in `customer.shippingAddresses[]`.
|
||||
* The resulting address includes a `source` field, indicating it references a persistent
|
||||
* shipping address entity in the CRM system.
|
||||
*
|
||||
* Filters out CRM-specific fields:
|
||||
* - `type` (ShippingAddressType)
|
||||
* - `validated` (validation flag)
|
||||
* - `validationResult` (validation status code)
|
||||
* - `agentComment` (internal notes)
|
||||
* - `isDefault` (default address flag)
|
||||
*
|
||||
* @param address - Raw shipping address from CRM service
|
||||
* @returns ShippingAddressDTO compatible with checkout-api, includes `source` field
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const crmAddress = customer.shippingAddresses[0].data;
|
||||
* const checkoutAddress = ShippingAddressAdapter.fromCrmShippingAddress(crmAddress);
|
||||
* await checkoutService.complete({ shippingAddress: checkoutAddress, ... });
|
||||
* ```
|
||||
*/
|
||||
static fromCrmShippingAddress(
|
||||
address: CrmShippingAddressDTO,
|
||||
): CheckoutShippingAddressDTO {
|
||||
return {
|
||||
reference: { id: address.id },
|
||||
gender: address.gender,
|
||||
title: address.title,
|
||||
firstName: address.firstName,
|
||||
lastName: address.lastName,
|
||||
communicationDetails: address.communicationDetails
|
||||
? { ...address.communicationDetails }
|
||||
: undefined,
|
||||
organisation: address.organisation
|
||||
? { ...address.organisation }
|
||||
: undefined,
|
||||
address: address.address ? { ...address.address } : undefined,
|
||||
source: address.id,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts Customer to checkout-api ShippingAddressDTO.
|
||||
*
|
||||
* @remarks
|
||||
* Used when customer's primary address is used for shipping (e.g., B2B customers, staff,
|
||||
* customer card holders without separate delivery addresses).
|
||||
*
|
||||
* The resulting address **does not include** a `source` field, indicating this is derived
|
||||
* from the customer entity and not a separate persistent shipping address entity.
|
||||
*
|
||||
* Uses customer's primary address data (`customer.address`) and personal information.
|
||||
*
|
||||
* @param customer - Customer from CRM service
|
||||
* @returns ShippingAddressDTO compatible with checkout-api, omits `source` field
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const customer = await crmService.getCustomer(123);
|
||||
* const checkoutAddress = ShippingAddressAdapter.fromCustomer(customer);
|
||||
* await checkoutService.complete({ shippingAddress: checkoutAddress, ... });
|
||||
* ```
|
||||
*/
|
||||
static fromCustomer(customer: Customer): CheckoutShippingAddressDTO {
|
||||
return {
|
||||
reference: { id: customer.id },
|
||||
gender: customer.gender,
|
||||
title: customer.title,
|
||||
firstName: customer.firstName,
|
||||
lastName: customer.lastName,
|
||||
communicationDetails: customer.communicationDetails
|
||||
? { ...customer.communicationDetails }
|
||||
: undefined,
|
||||
organisation: customer.organisation
|
||||
? { ...customer.organisation }
|
||||
: undefined,
|
||||
address: customer.address ? { ...customer.address } : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Type guard for CRM shipping address response
|
||||
*
|
||||
* @param value - Value to check
|
||||
* @returns true if value is a valid CRM shipping address with required fields
|
||||
*/
|
||||
static isValidCrmShippingAddress(
|
||||
value: unknown,
|
||||
): value is CrmShippingAddressDTO {
|
||||
if (typeof value !== 'object' || value === null) return false;
|
||||
|
||||
const address = value as CrmShippingAddressDTO;
|
||||
return typeof address.id === 'number';
|
||||
}
|
||||
|
||||
/**
|
||||
* Type guard for Customer
|
||||
*
|
||||
* @param value - Value to check
|
||||
* @returns true if value is a valid Customer with required fields
|
||||
*/
|
||||
static isValidCustomer(value: unknown): value is Customer {
|
||||
if (typeof value !== 'object' || value === null) return false;
|
||||
|
||||
const customer = value as Customer;
|
||||
return (
|
||||
typeof customer.id === 'number' &&
|
||||
(customer.customerNumber === undefined ||
|
||||
typeof customer.customerNumber === 'string')
|
||||
);
|
||||
}
|
||||
}
|
||||
import { Customer } from '@isa/crm/data-access';
|
||||
import { ShippingAddress as CrmShippingAddress } from '@isa/crm/data-access';
|
||||
import { ShippingAddress as CheckoutShippingAddress } from '@isa/checkout/data-access';
|
||||
|
||||
/**
|
||||
* Adapter for converting CRM shipping address data to checkout-api format.
|
||||
*
|
||||
* Handles two distinct conversion scenarios:
|
||||
* 1. **Separate Shipping Address Entity** (`fromCrmShippingAddress`): Converts a dedicated
|
||||
* shipping address from CRM with `source` field, indicating a persistent entity.
|
||||
* 2. **Customer Primary Address** (`fromCustomer`): Derives shipping address from customer's
|
||||
* primary address without `source` field, indicating transient/derived data.
|
||||
*
|
||||
* **Key Differences:**
|
||||
* - CRM ShippingAddressDTO: Filters out CRM-specific fields (type, validated, agentComment, etc.)
|
||||
* - Customer Address: Uses customer ID for reference, omits `source` field
|
||||
*/
|
||||
export class ShippingAddressAdapter {
|
||||
private static readonly ADAPTER_NAME = 'ShippingAddressAdapter';
|
||||
|
||||
/**
|
||||
* Converts CRM-api ShippingAddressDTO to checkout-api format.
|
||||
*
|
||||
* @remarks
|
||||
* Used when customer has separate delivery addresses stored in `customer.shippingAddresses[]`.
|
||||
* The resulting address includes a `source` field, indicating it references a persistent
|
||||
* shipping address entity in the CRM system.
|
||||
*
|
||||
* Filters out CRM-specific fields:
|
||||
* - `type` (ShippingAddressType)
|
||||
* - `validated` (validation flag)
|
||||
* - `validationResult` (validation status code)
|
||||
* - `agentComment` (internal notes)
|
||||
* - `isDefault` (default address flag)
|
||||
*
|
||||
* @param address - Raw shipping address from CRM service (optional)
|
||||
* @returns ShippingAddressDTO compatible with checkout-api, includes `source` field, or undefined if address is not provided
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const crmAddress = customer.shippingAddresses[0].data;
|
||||
* const checkoutAddress = ShippingAddressAdapter.fromCrmShippingAddress(crmAddress);
|
||||
* await checkoutService.complete({ shippingAddress: checkoutAddress, ... });
|
||||
* ```
|
||||
*/
|
||||
static fromCrmShippingAddress(
|
||||
address: CrmShippingAddress | undefined,
|
||||
): CheckoutShippingAddress | undefined {
|
||||
if (!address) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return {
|
||||
reference: { id: address.id },
|
||||
gender: address.gender,
|
||||
title: address.title,
|
||||
firstName: address.firstName,
|
||||
lastName: address.lastName,
|
||||
communicationDetails: address.communicationDetails
|
||||
? { ...address.communicationDetails }
|
||||
: undefined,
|
||||
organisation: address.organisation
|
||||
? { ...address.organisation }
|
||||
: undefined,
|
||||
address: address.address
|
||||
? {
|
||||
street: address.address.street,
|
||||
streetNumber: address.address.streetNumber,
|
||||
zipCode: address.address.zipCode,
|
||||
city: address.address.city,
|
||||
country: address.address.country,
|
||||
}
|
||||
: undefined,
|
||||
source: address.id,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts Customer to checkout-api ShippingAddressDTO.
|
||||
*
|
||||
* @remarks
|
||||
* Used when customer's primary address is used for shipping (e.g., B2B customers, staff,
|
||||
* customer card holders without separate delivery addresses).
|
||||
*
|
||||
* The resulting address **does not include** a `source` field, indicating this is derived
|
||||
* from the customer entity and not a separate persistent shipping address entity.
|
||||
*
|
||||
* Uses customer's primary address data (`customer.address`) and personal information.
|
||||
*
|
||||
* @param customer - Customer from CRM service
|
||||
* @returns ShippingAddressDTO compatible with checkout-api, omits `source` field
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const customer = await crmService.getCustomer(123);
|
||||
* const checkoutAddress = ShippingAddressAdapter.fromCustomer(customer);
|
||||
* await checkoutService.complete({ shippingAddress: checkoutAddress, ... });
|
||||
* ```
|
||||
*/
|
||||
static fromCustomer(customer: Customer): CheckoutShippingAddress {
|
||||
return {
|
||||
reference: { id: customer.id },
|
||||
gender: customer.gender,
|
||||
title: customer.title,
|
||||
firstName: customer.firstName,
|
||||
lastName: customer.lastName,
|
||||
communicationDetails: customer.communicationDetails
|
||||
? { ...customer.communicationDetails }
|
||||
: undefined,
|
||||
organisation: customer.organisation
|
||||
? { ...customer.organisation }
|
||||
: undefined,
|
||||
address: customer.address
|
||||
? {
|
||||
street: customer.address.street,
|
||||
streetNumber: customer.address.streetNumber,
|
||||
zipCode: customer.address.zipCode,
|
||||
city: customer.address.city,
|
||||
country: customer.address.country,
|
||||
}
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Type guard for CRM shipping address response
|
||||
*
|
||||
* @param value - Value to check
|
||||
* @returns true if value is a valid CRM shipping address with required fields
|
||||
*/
|
||||
static isValidCrmShippingAddress(
|
||||
value: unknown,
|
||||
): value is CrmShippingAddress {
|
||||
if (typeof value !== 'object' || value === null) return false;
|
||||
|
||||
const address = value as CrmShippingAddress;
|
||||
return typeof address.id === 'number';
|
||||
}
|
||||
|
||||
/**
|
||||
* Type guard for Customer
|
||||
*
|
||||
* @param value - Value to check
|
||||
* @returns true if value is a valid Customer with required fields
|
||||
*/
|
||||
static isValidCustomer(value: unknown): value is Customer {
|
||||
if (typeof value !== 'object' || value === null) return false;
|
||||
|
||||
const customer = value as Customer;
|
||||
return (
|
||||
typeof customer.id === 'number' &&
|
||||
(customer.customerNumber === undefined ||
|
||||
typeof customer.customerNumber === 'string')
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,3 +9,6 @@ export const CHECKOUT_REWARD_SHOPPING_CART_ID_METADATA_KEY =
|
||||
|
||||
export const CHECKOUT_REWARD_SELECTION_POPUP_OPENED_STATE_KEY =
|
||||
'checkout-data-access.checkoutRewardSelectionPopupOpenedState';
|
||||
|
||||
export const COMPLETED_SHOPPING_CARTS_METADATA_KEY =
|
||||
'checkout-data-access.completedShoppingCarts';
|
||||
|
||||
@@ -0,0 +1,650 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { ZodError } from 'zod';
|
||||
import { ShoppingCartFacade } from './shopping-cart.facade';
|
||||
import { CheckoutService, ShoppingCartService } from '../services';
|
||||
import { Customer, Payer as CrmPayer } from '@isa/crm/data-access';
|
||||
import { ShippingAddressDTO as CrmShippingAddressDTO } from '@generated/swagger/crm-api';
|
||||
import { Order } from '../models';
|
||||
|
||||
describe('ShoppingCartFacade', () => {
|
||||
let facade: ShoppingCartFacade;
|
||||
let mockCheckoutService: {
|
||||
complete: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let mockShoppingCartService: {
|
||||
createShoppingCart: ReturnType<typeof vi.fn>;
|
||||
getShoppingCart: ReturnType<typeof vi.fn>;
|
||||
removeItem: ReturnType<typeof vi.fn>;
|
||||
updateItem: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
mockCheckoutService = {
|
||||
complete: vi.fn(),
|
||||
};
|
||||
|
||||
mockShoppingCartService = {
|
||||
createShoppingCart: vi.fn(),
|
||||
getShoppingCart: vi.fn(),
|
||||
removeItem: vi.fn(),
|
||||
updateItem: vi.fn(),
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
ShoppingCartFacade,
|
||||
{ provide: CheckoutService, useValue: mockCheckoutService },
|
||||
{ provide: ShoppingCartService, useValue: mockShoppingCartService },
|
||||
],
|
||||
});
|
||||
|
||||
facade = TestBed.inject(ShoppingCartFacade);
|
||||
});
|
||||
|
||||
describe('completeWithCrmData', () => {
|
||||
it('should transform CRM data and complete order successfully', async () => {
|
||||
// Arrange
|
||||
const mockOrders: Order[] = [
|
||||
{ id: 1, orderNumber: 'ORDER-001' } as Order,
|
||||
];
|
||||
|
||||
mockCheckoutService.complete.mockResolvedValue(mockOrders);
|
||||
|
||||
const customer: Customer = {
|
||||
id: 123,
|
||||
customerNumber: 'CUST-123',
|
||||
customerType: 8, // B2C
|
||||
firstName: 'John',
|
||||
lastName: 'Doe',
|
||||
notificationChannels: 1,
|
||||
features: [
|
||||
{ key: 'FEATURE1', value: 'value1' },
|
||||
{ key: 'FEATURE2', value: 'value2' },
|
||||
],
|
||||
} as Customer;
|
||||
|
||||
// Act
|
||||
const result = await facade.completeWithCrmData({
|
||||
shoppingCartId: 456,
|
||||
crmCustomer: customer,
|
||||
});
|
||||
|
||||
// Assert
|
||||
expect(result).toEqual(mockOrders);
|
||||
expect(mockCheckoutService.complete).toHaveBeenCalledOnce();
|
||||
expect(mockCheckoutService.complete).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
shoppingCartId: 456,
|
||||
buyer: expect.objectContaining({
|
||||
reference: { id: 123 },
|
||||
source: 123,
|
||||
buyerType: 8,
|
||||
buyerNumber: 'CUST-123',
|
||||
firstName: 'John',
|
||||
lastName: 'Doe',
|
||||
}),
|
||||
notificationChannels: 1,
|
||||
customerFeatures: { FEATURE1: 'FEATURE1', FEATURE2: 'FEATURE2' },
|
||||
}),
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
it('should transform CRM shipping address when provided', async () => {
|
||||
// Arrange
|
||||
const mockOrders: Order[] = [
|
||||
{ id: 1, orderNumber: 'ORDER-001' } as Order,
|
||||
];
|
||||
|
||||
mockCheckoutService.complete.mockResolvedValue(mockOrders);
|
||||
|
||||
const customer: Customer = {
|
||||
id: 123,
|
||||
customerNumber: 'CUST-123',
|
||||
customerType: 8,
|
||||
firstName: 'John',
|
||||
lastName: 'Doe',
|
||||
notificationChannels: 1,
|
||||
features: [],
|
||||
} as Customer;
|
||||
|
||||
const crmShippingAddress: CrmShippingAddressDTO = {
|
||||
id: 789,
|
||||
firstName: 'Jane',
|
||||
lastName: 'Doe',
|
||||
address: {
|
||||
street: 'Main St',
|
||||
streetNumber: '123',
|
||||
zipCode: '12345',
|
||||
city: 'Berlin',
|
||||
country: 'DE',
|
||||
} as any,
|
||||
};
|
||||
|
||||
// Act
|
||||
await facade.completeWithCrmData({
|
||||
shoppingCartId: 456,
|
||||
crmCustomer: customer,
|
||||
crmShippingAddress,
|
||||
});
|
||||
|
||||
// Assert
|
||||
expect(mockCheckoutService.complete).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
shippingAddress: expect.objectContaining({
|
||||
reference: { id: 789 },
|
||||
source: 789,
|
||||
firstName: 'Jane',
|
||||
lastName: 'Doe',
|
||||
address: expect.objectContaining({
|
||||
street: 'Main St',
|
||||
streetNumber: '123',
|
||||
zipCode: '12345',
|
||||
city: 'Berlin',
|
||||
country: 'DE',
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
it('should transform CRM payer when provided', async () => {
|
||||
// Arrange
|
||||
const mockOrders: Order[] = [
|
||||
{ id: 1, orderNumber: 'ORDER-001' } as Order,
|
||||
];
|
||||
|
||||
mockCheckoutService.complete.mockResolvedValue(mockOrders);
|
||||
|
||||
const customer: Customer = {
|
||||
id: 123,
|
||||
customerNumber: 'CUST-123',
|
||||
customerType: 8,
|
||||
firstName: 'John',
|
||||
lastName: 'Doe',
|
||||
notificationChannels: 1,
|
||||
features: [],
|
||||
} as Customer;
|
||||
|
||||
const crmPayer: CrmPayer = {
|
||||
id: 999,
|
||||
payerNumber: 'PAY-999',
|
||||
payerType: 16, // B2B
|
||||
payerStatus: 0,
|
||||
firstName: 'Billing',
|
||||
lastName: 'Company',
|
||||
} as CrmPayer;
|
||||
|
||||
// Act
|
||||
await facade.completeWithCrmData({
|
||||
shoppingCartId: 456,
|
||||
crmCustomer: customer,
|
||||
crmPayer,
|
||||
});
|
||||
|
||||
// Assert
|
||||
expect(mockCheckoutService.complete).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
payer: expect.objectContaining({
|
||||
reference: { id: 999 },
|
||||
source: 999,
|
||||
payerType: 16,
|
||||
payerNumber: 'PAY-999',
|
||||
payerStatus: 0,
|
||||
firstName: 'Billing',
|
||||
lastName: 'Company',
|
||||
}),
|
||||
}),
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
it('should use provided notificationChannels over customer default', async () => {
|
||||
// Arrange
|
||||
mockCheckoutService.complete.mockResolvedValue([]);
|
||||
|
||||
const customer: Customer = {
|
||||
id: 123,
|
||||
customerNumber: 'CUST-123',
|
||||
customerType: 8,
|
||||
firstName: 'John',
|
||||
lastName: 'Doe',
|
||||
notificationChannels: 1, // Customer default
|
||||
features: [],
|
||||
} as Customer;
|
||||
|
||||
// Act
|
||||
await facade.completeWithCrmData({
|
||||
shoppingCartId: 456,
|
||||
crmCustomer: customer,
|
||||
notificationChannels: 4, // Override
|
||||
});
|
||||
|
||||
// Assert
|
||||
expect(mockCheckoutService.complete).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
notificationChannels: 4, // Should use override
|
||||
}),
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
it('should use customer notificationChannels when not provided', async () => {
|
||||
// Arrange
|
||||
mockCheckoutService.complete.mockResolvedValue([]);
|
||||
|
||||
const customer: Customer = {
|
||||
id: 123,
|
||||
customerNumber: 'CUST-123',
|
||||
customerType: 8,
|
||||
firstName: 'John',
|
||||
lastName: 'Doe',
|
||||
notificationChannels: 2, // Customer default
|
||||
features: [],
|
||||
} as Customer;
|
||||
|
||||
// Act
|
||||
await facade.completeWithCrmData({
|
||||
shoppingCartId: 456,
|
||||
crmCustomer: customer,
|
||||
});
|
||||
|
||||
// Assert
|
||||
expect(mockCheckoutService.complete).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
notificationChannels: 2, // Should use customer default
|
||||
}),
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
it('should default to 1 when customer notificationChannels is undefined', async () => {
|
||||
// Arrange
|
||||
mockCheckoutService.complete.mockResolvedValue([]);
|
||||
|
||||
const customer: Customer = {
|
||||
id: 123,
|
||||
customerNumber: 'CUST-123',
|
||||
customerType: 8,
|
||||
firstName: 'John',
|
||||
lastName: 'Doe',
|
||||
notificationChannels: undefined, // Not set
|
||||
features: [],
|
||||
} as Customer;
|
||||
|
||||
// Act
|
||||
await facade.completeWithCrmData({
|
||||
shoppingCartId: 456,
|
||||
crmCustomer: customer,
|
||||
});
|
||||
|
||||
// Assert
|
||||
expect(mockCheckoutService.complete).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
notificationChannels: 1, // Should default to 1
|
||||
}),
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
it('should handle missing optional shipping address', async () => {
|
||||
// Arrange
|
||||
mockCheckoutService.complete.mockResolvedValue([]);
|
||||
|
||||
const customer: Customer = {
|
||||
id: 123,
|
||||
customerNumber: 'CUST-123',
|
||||
customerType: 8,
|
||||
firstName: 'John',
|
||||
lastName: 'Doe',
|
||||
notificationChannels: 1,
|
||||
features: [],
|
||||
} as Customer;
|
||||
|
||||
// Act
|
||||
await facade.completeWithCrmData({
|
||||
shoppingCartId: 456,
|
||||
crmCustomer: customer,
|
||||
crmShippingAddress: undefined,
|
||||
});
|
||||
|
||||
// Assert
|
||||
expect(mockCheckoutService.complete).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
shippingAddress: undefined,
|
||||
}),
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
it('should handle missing optional payer', async () => {
|
||||
// Arrange
|
||||
mockCheckoutService.complete.mockResolvedValue([]);
|
||||
|
||||
const customer: Customer = {
|
||||
id: 123,
|
||||
customerNumber: 'CUST-123',
|
||||
customerType: 8,
|
||||
firstName: 'John',
|
||||
lastName: 'Doe',
|
||||
notificationChannels: 1,
|
||||
features: [],
|
||||
} as Customer;
|
||||
|
||||
// Act
|
||||
await facade.completeWithCrmData({
|
||||
shoppingCartId: 456,
|
||||
crmCustomer: customer,
|
||||
crmPayer: undefined,
|
||||
});
|
||||
|
||||
// Assert
|
||||
expect(mockCheckoutService.complete).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
payer: undefined,
|
||||
}),
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
it('should pass abort signal to underlying service', async () => {
|
||||
// Arrange
|
||||
mockCheckoutService.complete.mockResolvedValue([]);
|
||||
|
||||
const customer: Customer = {
|
||||
id: 123,
|
||||
customerNumber: 'CUST-123',
|
||||
customerType: 8,
|
||||
firstName: 'John',
|
||||
lastName: 'Doe',
|
||||
notificationChannels: 1,
|
||||
features: [],
|
||||
} as Customer;
|
||||
|
||||
const abortController = new AbortController();
|
||||
|
||||
// Act
|
||||
await facade.completeWithCrmData(
|
||||
{
|
||||
shoppingCartId: 456,
|
||||
crmCustomer: customer,
|
||||
},
|
||||
abortController.signal,
|
||||
);
|
||||
|
||||
// Assert
|
||||
expect(mockCheckoutService.complete).toHaveBeenCalledWith(
|
||||
expect.any(Object),
|
||||
abortController.signal,
|
||||
);
|
||||
});
|
||||
|
||||
it('should extract customer features correctly', async () => {
|
||||
// Arrange
|
||||
mockCheckoutService.complete.mockResolvedValue([]);
|
||||
|
||||
const customer: Customer = {
|
||||
id: 123,
|
||||
customerNumber: 'CUST-123',
|
||||
customerType: 8,
|
||||
firstName: 'John',
|
||||
lastName: 'Doe',
|
||||
notificationChannels: 1,
|
||||
features: [
|
||||
{ key: 'FEATURE_A', value: 'some value' },
|
||||
{ key: 'FEATURE_B', value: 'another value' },
|
||||
{ key: 'FEATURE_C', value: 'third value' },
|
||||
],
|
||||
} as Customer;
|
||||
|
||||
// Act
|
||||
await facade.completeWithCrmData({
|
||||
shoppingCartId: 456,
|
||||
crmCustomer: customer,
|
||||
});
|
||||
|
||||
// Assert
|
||||
expect(mockCheckoutService.complete).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
customerFeatures: {
|
||||
FEATURE_A: 'FEATURE_A',
|
||||
FEATURE_B: 'FEATURE_B',
|
||||
FEATURE_C: 'FEATURE_C',
|
||||
},
|
||||
}),
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
it('should handle empty customer features', async () => {
|
||||
// Arrange
|
||||
mockCheckoutService.complete.mockResolvedValue([]);
|
||||
|
||||
const customer: Customer = {
|
||||
id: 123,
|
||||
customerNumber: 'CUST-123',
|
||||
customerType: 8,
|
||||
firstName: 'John',
|
||||
lastName: 'Doe',
|
||||
notificationChannels: 1,
|
||||
features: [],
|
||||
} as Customer;
|
||||
|
||||
// Act
|
||||
await facade.completeWithCrmData({
|
||||
shoppingCartId: 456,
|
||||
crmCustomer: customer,
|
||||
});
|
||||
|
||||
// Assert
|
||||
expect(mockCheckoutService.complete).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
customerFeatures: {},
|
||||
}),
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
it('should throw error for invalid shopping cart ID', async () => {
|
||||
// Arrange
|
||||
const customer: Customer = {
|
||||
id: 123,
|
||||
customerNumber: 'CUST-123',
|
||||
customerType: 8,
|
||||
firstName: 'John',
|
||||
lastName: 'Doe',
|
||||
notificationChannels: 1,
|
||||
features: [],
|
||||
} as Customer;
|
||||
|
||||
// Act & Assert
|
||||
try {
|
||||
await facade.completeWithCrmData({
|
||||
shoppingCartId: -1, // Invalid ID
|
||||
crmCustomer: customer,
|
||||
});
|
||||
expect.fail('Should have thrown ZodError');
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(ZodError);
|
||||
}
|
||||
});
|
||||
|
||||
it('should throw error for invalid customer data', async () => {
|
||||
// Act & Assert
|
||||
try {
|
||||
await facade.completeWithCrmData({
|
||||
shoppingCartId: 456,
|
||||
customer: { invalid: 'data' } as any, // Invalid customer
|
||||
});
|
||||
expect.fail('Should have thrown ZodError');
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(ZodError);
|
||||
}
|
||||
});
|
||||
|
||||
it('should propagate errors from checkout service', async () => {
|
||||
// Arrange
|
||||
const checkoutError = new Error('Checkout failed');
|
||||
mockCheckoutService.complete.mockRejectedValue(checkoutError);
|
||||
|
||||
const customer: Customer = {
|
||||
id: 123,
|
||||
customerNumber: 'CUST-123',
|
||||
customerType: 8,
|
||||
firstName: 'John',
|
||||
lastName: 'Doe',
|
||||
notificationChannels: 1,
|
||||
features: [],
|
||||
} as Customer;
|
||||
|
||||
// Act & Assert
|
||||
await expect(
|
||||
facade.completeWithCrmData({
|
||||
shoppingCartId: 456,
|
||||
crmCustomer: customer,
|
||||
}),
|
||||
).rejects.toThrow('Checkout failed');
|
||||
});
|
||||
|
||||
it('should handle all parameters together', async () => {
|
||||
// Arrange
|
||||
const mockOrders: Order[] = [
|
||||
{ id: 1, orderNumber: 'ORDER-001' } as Order,
|
||||
{ id: 2, orderNumber: 'ORDER-002' } as Order,
|
||||
];
|
||||
|
||||
mockCheckoutService.complete.mockResolvedValue(mockOrders);
|
||||
|
||||
const customer: Customer = {
|
||||
id: 123,
|
||||
customerNumber: 'CUST-123',
|
||||
customerType: 16, // B2B
|
||||
firstName: 'John',
|
||||
lastName: 'Doe',
|
||||
gender: 2,
|
||||
title: 'Mr.',
|
||||
dateOfBirth: '1980-01-15',
|
||||
notificationChannels: 4,
|
||||
features: [{ key: 'B2B_CUSTOMER', value: 'true' }],
|
||||
communicationDetails: {
|
||||
email: 'john.doe@example.com',
|
||||
phone: '+49 123 456789',
|
||||
},
|
||||
organisation: {
|
||||
name: 'ACME Corp',
|
||||
},
|
||||
address: {
|
||||
street: 'Main St',
|
||||
streetNumber: '42',
|
||||
zipCode: '12345',
|
||||
city: 'Berlin',
|
||||
country: 'DE',
|
||||
},
|
||||
} as Customer;
|
||||
|
||||
const crmShippingAddress: CrmShippingAddressDTO = {
|
||||
id: 789,
|
||||
firstName: 'Jane',
|
||||
lastName: 'Doe',
|
||||
address: {
|
||||
street: 'Delivery St',
|
||||
streetNumber: '99',
|
||||
zipCode: '54321',
|
||||
city: 'Hamburg',
|
||||
country: 'DE',
|
||||
},
|
||||
};
|
||||
|
||||
const crmPayer: CrmPayer = {
|
||||
id: 999,
|
||||
payerNumber: 'PAY-999',
|
||||
payerType: 16,
|
||||
payerStatus: 0,
|
||||
firstName: 'Billing',
|
||||
lastName: 'Department',
|
||||
address: {
|
||||
street: 'Billing St',
|
||||
streetNumber: '1',
|
||||
zipCode: '11111',
|
||||
city: 'Munich',
|
||||
country: 'DE',
|
||||
},
|
||||
} as CrmPayer;
|
||||
|
||||
const abortController = new AbortController();
|
||||
|
||||
// Act
|
||||
const result = await facade.completeWithCrmData(
|
||||
{
|
||||
shoppingCartId: 456,
|
||||
crmCustomer: customer,
|
||||
crmShippingAddress,
|
||||
crmPayer,
|
||||
notificationChannels: 8,
|
||||
},
|
||||
abortController.signal,
|
||||
);
|
||||
|
||||
// Assert
|
||||
expect(result).toEqual(mockOrders);
|
||||
expect(mockCheckoutService.complete).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
shoppingCartId: 456,
|
||||
buyer: expect.objectContaining({
|
||||
reference: { id: 123 },
|
||||
source: 123,
|
||||
buyerType: 16,
|
||||
buyerNumber: 'CUST-123',
|
||||
firstName: 'John',
|
||||
lastName: 'Doe',
|
||||
}),
|
||||
shippingAddress: expect.objectContaining({
|
||||
reference: { id: 789 },
|
||||
source: 789,
|
||||
firstName: 'Jane',
|
||||
lastName: 'Doe',
|
||||
}),
|
||||
payer: expect.objectContaining({
|
||||
reference: { id: 999 },
|
||||
source: 999,
|
||||
payerType: 16,
|
||||
payerNumber: 'PAY-999',
|
||||
}),
|
||||
notificationChannels: 8,
|
||||
customerFeatures: { B2B_CUSTOMER: 'B2B_CUSTOMER' },
|
||||
}),
|
||||
abortController.signal,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('complete', () => {
|
||||
it('should delegate to checkout service', async () => {
|
||||
// Arrange
|
||||
const mockOrders: Order[] = [
|
||||
{ id: 1, orderNumber: 'ORDER-001' } as Order,
|
||||
];
|
||||
|
||||
mockCheckoutService.complete.mockResolvedValue(mockOrders);
|
||||
|
||||
const params = {
|
||||
shoppingCartId: 123,
|
||||
buyer: { buyerType: 8 } as any,
|
||||
notificationChannels: 1 as any,
|
||||
customerFeatures: {},
|
||||
};
|
||||
|
||||
// Act
|
||||
const result = await facade.complete(params);
|
||||
|
||||
// Assert
|
||||
expect(result).toEqual(mockOrders);
|
||||
expect(mockCheckoutService.complete).toHaveBeenCalledWith(
|
||||
params,
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,11 +1,17 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { ShoppingCartService, CheckoutService } from '../services';
|
||||
import {
|
||||
CompleteCheckoutParams,
|
||||
CompleteOrderParams,
|
||||
RemoveShoppingCartItemParams,
|
||||
UpdateShoppingCartItemParams,
|
||||
CompleteCrmOrderParamsSchema,
|
||||
CompleteCrmOrderParams,
|
||||
} from '../schemas';
|
||||
import { Order } from '../models';
|
||||
import {
|
||||
CustomerAdapter,
|
||||
ShippingAddressAdapter,
|
||||
PayerAdapter,
|
||||
} from '../adapters';
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class ShoppingCartFacade {
|
||||
@@ -31,10 +37,88 @@ export class ShoppingCartFacade {
|
||||
return this.#shoppingCartService.updateItem(params);
|
||||
}
|
||||
|
||||
complete(
|
||||
params: CompleteCheckoutParams,
|
||||
/**
|
||||
* Complete checkout and create orders.
|
||||
*
|
||||
* @param params - Complete checkout parameters
|
||||
* @param abortSignal - Optional AbortSignal for cancellation
|
||||
* @returns Promise<number> - Checkout Id
|
||||
* @throws CheckoutCompletionError - If validation or order creation fails
|
||||
*/
|
||||
async complete(
|
||||
params: CompleteOrderParams,
|
||||
abortSignal?: AbortSignal,
|
||||
): Promise<Order[]> {
|
||||
return this.#checkoutService.complete(params, abortSignal);
|
||||
): Promise<number> {
|
||||
// Complete checkout preparation
|
||||
return await this.#checkoutService.complete(params, abortSignal);
|
||||
}
|
||||
|
||||
/**
|
||||
* Complete order with CRM data.
|
||||
*
|
||||
* @remarks
|
||||
* Accepts raw CRM data (customer, shipping address, payer) and transforms it
|
||||
* to checkout format before completing the order. This method encapsulates
|
||||
* the business logic of converting CRM entities to checkout entities.
|
||||
*
|
||||
* **Transformation Steps:**
|
||||
* 1. Validates input parameters with Zod schema
|
||||
* 2. Transforms customer to buyer using CustomerAdapter.toBuyer()
|
||||
* 3. Transforms CRM shipping address (if provided) using ShippingAddressAdapter
|
||||
* 4. Transforms CRM payer (if provided) using PayerAdapter
|
||||
* 5. Extracts customer features using CustomerAdapter.extractCustomerFeatures()
|
||||
* 6. Delegates to complete() with transformed data
|
||||
*
|
||||
* @param params - CRM order completion parameters
|
||||
* @param abortSignal - Optional AbortSignal for cancellation
|
||||
* @returns Promise<number> - Checkout Id
|
||||
* @throws CheckoutCompletionError - If validation or order creation fails
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const customer = await customerResource.value();
|
||||
* const orders = await facade.completeWithCrmData({
|
||||
* shoppingCartId: 123,
|
||||
* customer,
|
||||
* crmShippingAddress: customer.shippingAddresses[0].data,
|
||||
* crmPayer: customer.payers[0].payer.data,
|
||||
* notificationChannels: customer.notificationChannels ?? 1,
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
completeWithCrmData(
|
||||
params: CompleteCrmOrderParams,
|
||||
abortSignal?: AbortSignal,
|
||||
): Promise<number> {
|
||||
// Validate input parameters
|
||||
const validatedParams = CompleteCrmOrderParamsSchema.parse(params);
|
||||
|
||||
const {
|
||||
shoppingCartId,
|
||||
crmCustomer,
|
||||
crmShippingAddress,
|
||||
crmPayer,
|
||||
notificationChannels,
|
||||
specialComment,
|
||||
} = validatedParams;
|
||||
|
||||
// Build checkout parameters
|
||||
const checkoutParams: CompleteOrderParams = {
|
||||
shoppingCartId,
|
||||
buyer: CustomerAdapter.toBuyer(crmCustomer),
|
||||
shippingAddress: ShippingAddressAdapter.fromCrmShippingAddress(
|
||||
crmShippingAddress as any,
|
||||
),
|
||||
customerFeatures: CustomerAdapter.extractCustomerFeatures(
|
||||
crmCustomer as any,
|
||||
),
|
||||
payer: PayerAdapter.toCheckoutFormat(crmPayer as any),
|
||||
notificationChannels:
|
||||
notificationChannels ?? crmCustomer.notificationChannels ?? 1,
|
||||
specialComment,
|
||||
};
|
||||
|
||||
// Delegate to existing complete method
|
||||
return this.complete(checkoutParams, abortSignal);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,95 +1,95 @@
|
||||
import { EntityDTOContainerOfShoppingCartItemDTO } from '@generated/swagger/checkout-api';
|
||||
import {
|
||||
CustomerTypeAnalysis,
|
||||
OrderOptionsAnalysis,
|
||||
ShoppingCartItem,
|
||||
} from '../models';
|
||||
|
||||
/**
|
||||
* Analyzes shopping cart items to determine which order types are present.
|
||||
*
|
||||
* @remarks
|
||||
* Pure function that examines the orderType feature of each item to identify:
|
||||
* - Take away orders (Rücklage)
|
||||
* - Pick up orders (Abholung)
|
||||
* - Download orders
|
||||
* - Standard delivery (Versand)
|
||||
* - Digital delivery (DIG-Versand)
|
||||
* - B2B delivery (B2B-Versand)
|
||||
*
|
||||
* Used during checkout completion to determine payment requirements and
|
||||
* destination update needs.
|
||||
*
|
||||
* @param items - Shopping cart items to analyze
|
||||
* @returns Analysis result with boolean flags for each order type and unwrapped items
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const items = [
|
||||
* { data: { features: { orderType: 'Versand' } } },
|
||||
* { data: { features: { orderType: 'Abholung' } } }
|
||||
* ];
|
||||
* const analysis = analyzeOrderOptions(items);
|
||||
* // { hasDelivery: true, hasPickUp: true, hasTakeAway: false, ... }
|
||||
* ```
|
||||
*/
|
||||
export function analyzeOrderOptions(
|
||||
items: EntityDTOContainerOfShoppingCartItemDTO[],
|
||||
): OrderOptionsAnalysis {
|
||||
return {
|
||||
hasTakeAway: items.some(
|
||||
(item) => item.data?.features?.['orderType'] === 'Rücklage',
|
||||
),
|
||||
hasPickUp: items.some(
|
||||
(item) => item.data?.features?.['orderType'] === 'Abholung',
|
||||
),
|
||||
hasDownload: items.some(
|
||||
(item) => item.data?.features?.['orderType'] === 'Download',
|
||||
),
|
||||
hasDelivery: items.some(
|
||||
(item) => item.data?.features?.['orderType'] === 'Versand',
|
||||
),
|
||||
hasDigDelivery: items.some(
|
||||
(item) => item.data?.features?.['orderType'] === 'DIG-Versand',
|
||||
),
|
||||
hasB2BDelivery: items.some(
|
||||
(item) => item.data?.features?.['orderType'] === 'B2B-Versand',
|
||||
),
|
||||
items: items.map((d) => d.data as ShoppingCartItem),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Analyzes customer features to determine customer type characteristics.
|
||||
*
|
||||
* @remarks
|
||||
* Pure function that converts feature flags into typed boolean properties:
|
||||
* - isOnline: webshop customer
|
||||
* - isGuest: guest account
|
||||
* - isB2B: business customer
|
||||
* - hasCustomerCard: loyalty card holder (Pay4More)
|
||||
* - isStaff: employee/staff member
|
||||
*
|
||||
* Used during checkout to determine payment requirements and payer necessity.
|
||||
*
|
||||
* @param features - Customer feature flags (e.g., { webshop: 'webshop', b2b: 'b2b' })
|
||||
* @returns Analysis result with boolean flags for each customer type
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const features = { webshop: 'webshop', p4mUser: 'p4mUser' };
|
||||
* const analysis = analyzeCustomerTypes(features);
|
||||
* // { isOnline: true, hasCustomerCard: true, isB2B: false, ... }
|
||||
* ```
|
||||
*/
|
||||
export function analyzeCustomerTypes(
|
||||
features: Record<string, string>,
|
||||
): CustomerTypeAnalysis {
|
||||
return {
|
||||
isOnline: !!features?.['webshop'],
|
||||
isGuest: !!features?.['guest'],
|
||||
isB2B: !!features?.['b2b'],
|
||||
hasCustomerCard: !!features?.['p4mUser'],
|
||||
isStaff: !!features?.['staff'],
|
||||
};
|
||||
}
|
||||
import {
|
||||
CustomerTypeAnalysis,
|
||||
OrderOptionsAnalysis,
|
||||
ShoppingCartItem,
|
||||
} from '../models';
|
||||
import { EntityContainer } from '@isa/common/data-access';
|
||||
|
||||
/**
|
||||
* Analyzes shopping cart items to determine which order types are present.
|
||||
*
|
||||
* @remarks
|
||||
* Pure function that examines the orderType feature of each item to identify:
|
||||
* - Take away orders (Rücklage)
|
||||
* - Pick up orders (Abholung)
|
||||
* - Download orders
|
||||
* - Standard delivery (Versand)
|
||||
* - Digital delivery (DIG-Versand)
|
||||
* - B2B delivery (B2B-Versand)
|
||||
*
|
||||
* Used during checkout completion to determine payment requirements and
|
||||
* destination update needs.
|
||||
*
|
||||
* @param items - Shopping cart items to analyze
|
||||
* @returns Analysis result with boolean flags for each order type and unwrapped items
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const items = [
|
||||
* { data: { features: { orderType: 'Versand' } } },
|
||||
* { data: { features: { orderType: 'Abholung' } } }
|
||||
* ];
|
||||
* const analysis = analyzeOrderOptions(items);
|
||||
* // { hasDelivery: true, hasPickUp: true, hasTakeAway: false, ... }
|
||||
* ```
|
||||
*/
|
||||
export function analyzeOrderOptions(
|
||||
items: EntityContainer<ShoppingCartItem>[],
|
||||
): OrderOptionsAnalysis {
|
||||
return {
|
||||
hasTakeAway: items.some(
|
||||
(item) => item.data?.features?.['orderType'] === 'Rücklage',
|
||||
),
|
||||
hasPickUp: items.some(
|
||||
(item) => item.data?.features?.['orderType'] === 'Abholung',
|
||||
),
|
||||
hasDownload: items.some(
|
||||
(item) => item.data?.features?.['orderType'] === 'Download',
|
||||
),
|
||||
hasDelivery: items.some(
|
||||
(item) => item.data?.features?.['orderType'] === 'Versand',
|
||||
),
|
||||
hasDigDelivery: items.some(
|
||||
(item) => item.data?.features?.['orderType'] === 'DIG-Versand',
|
||||
),
|
||||
hasB2BDelivery: items.some(
|
||||
(item) => item.data?.features?.['orderType'] === 'B2B-Versand',
|
||||
),
|
||||
items: items.map((d) => d.data as ShoppingCartItem),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Analyzes customer features to determine customer type characteristics.
|
||||
*
|
||||
* @remarks
|
||||
* Pure function that converts feature flags into typed boolean properties:
|
||||
* - isOnline: webshop customer
|
||||
* - isGuest: guest account
|
||||
* - isB2B: business customer
|
||||
* - hasCustomerCard: loyalty card holder (Pay4More)
|
||||
* - isStaff: employee/staff member
|
||||
*
|
||||
* Used during checkout to determine payment requirements and payer necessity.
|
||||
*
|
||||
* @param features - Customer feature flags (e.g., { webshop: 'webshop', b2b: 'b2b' })
|
||||
* @returns Analysis result with boolean flags for each customer type
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const features = { webshop: 'webshop', p4mUser: 'p4mUser' };
|
||||
* const analysis = analyzeCustomerTypes(features);
|
||||
* // { isOnline: true, hasCustomerCard: true, isB2B: false, ... }
|
||||
* ```
|
||||
*/
|
||||
export function analyzeCustomerTypes(
|
||||
features: Record<string, string>,
|
||||
): CustomerTypeAnalysis {
|
||||
return {
|
||||
isOnline: !!features?.['webshop'],
|
||||
isGuest: !!features?.['guest'],
|
||||
isB2B: !!features?.['b2b'],
|
||||
hasCustomerCard: !!features?.['p4mUser'],
|
||||
isStaff: !!features?.['staff'],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { hasOrderTypeFeature } from './has-order-type-feature.helper';
|
||||
import { OrderType } from '../models';
|
||||
|
||||
describe('hasOrderTypeFeature', () => {
|
||||
describe('when features is undefined', () => {
|
||||
it('should return false', () => {
|
||||
// Act
|
||||
const result = hasOrderTypeFeature(undefined, [OrderType.Delivery]);
|
||||
|
||||
// Assert
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('when features is empty', () => {
|
||||
it('should return false', () => {
|
||||
// Arrange
|
||||
const features = {};
|
||||
|
||||
// Act
|
||||
const result = hasOrderTypeFeature(features, [OrderType.Delivery]);
|
||||
|
||||
// Assert
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('when orderType feature is not present', () => {
|
||||
it('should return false', () => {
|
||||
// Arrange
|
||||
const features = { someOtherFeature: 'value' };
|
||||
|
||||
// Act
|
||||
const result = hasOrderTypeFeature(features, [OrderType.Delivery]);
|
||||
|
||||
// Assert
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('when orderType feature is invalid', () => {
|
||||
it('should return false', () => {
|
||||
// Arrange
|
||||
const features = { orderType: 'InvalidOrderType' };
|
||||
|
||||
// Act
|
||||
const result = hasOrderTypeFeature(features, [OrderType.Delivery]);
|
||||
|
||||
// Assert
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('when orderType feature matches one of the provided types', () => {
|
||||
it('should return true for Delivery in delivery types', () => {
|
||||
// Arrange
|
||||
const features = { orderType: OrderType.Delivery };
|
||||
|
||||
// Act
|
||||
const result = hasOrderTypeFeature(features, [
|
||||
OrderType.Delivery,
|
||||
OrderType.DigitalShipping,
|
||||
OrderType.B2BShipping,
|
||||
]);
|
||||
|
||||
// Assert
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it('should return true for DigitalShipping in delivery types', () => {
|
||||
// Arrange
|
||||
const features = { orderType: OrderType.DigitalShipping };
|
||||
|
||||
// Act
|
||||
const result = hasOrderTypeFeature(features, [
|
||||
OrderType.Delivery,
|
||||
OrderType.DigitalShipping,
|
||||
OrderType.B2BShipping,
|
||||
]);
|
||||
|
||||
// Assert
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it('should return true for B2BShipping in delivery types', () => {
|
||||
// Arrange
|
||||
const features = { orderType: OrderType.B2BShipping };
|
||||
|
||||
// Act
|
||||
const result = hasOrderTypeFeature(features, [
|
||||
OrderType.Delivery,
|
||||
OrderType.DigitalShipping,
|
||||
OrderType.B2BShipping,
|
||||
]);
|
||||
|
||||
// Assert
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it('should return true for InStore in branch types', () => {
|
||||
// Arrange
|
||||
const features = { orderType: OrderType.InStore };
|
||||
|
||||
// Act
|
||||
const result = hasOrderTypeFeature(features, [
|
||||
OrderType.InStore,
|
||||
OrderType.Pickup,
|
||||
]);
|
||||
|
||||
// Assert
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it('should return true for Pickup in branch types', () => {
|
||||
// Arrange
|
||||
const features = { orderType: OrderType.Pickup };
|
||||
|
||||
// Act
|
||||
const result = hasOrderTypeFeature(features, [
|
||||
OrderType.InStore,
|
||||
OrderType.Pickup,
|
||||
]);
|
||||
|
||||
// Assert
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it('should return true for Download when checked alone', () => {
|
||||
// Arrange
|
||||
const features = { orderType: OrderType.Download };
|
||||
|
||||
// Act
|
||||
const result = hasOrderTypeFeature(features, [OrderType.Download]);
|
||||
|
||||
// Assert
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('when orderType feature does not match any provided types', () => {
|
||||
it('should return false for Delivery when checking branch types', () => {
|
||||
// Arrange
|
||||
const features = { orderType: OrderType.Delivery };
|
||||
|
||||
// Act
|
||||
const result = hasOrderTypeFeature(features, [
|
||||
OrderType.InStore,
|
||||
OrderType.Pickup,
|
||||
]);
|
||||
|
||||
// Assert
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false for InStore when checking delivery types', () => {
|
||||
// Arrange
|
||||
const features = { orderType: OrderType.InStore };
|
||||
|
||||
// Act
|
||||
const result = hasOrderTypeFeature(features, [
|
||||
OrderType.Delivery,
|
||||
OrderType.DigitalShipping,
|
||||
OrderType.B2BShipping,
|
||||
]);
|
||||
|
||||
// Assert
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false for Download when checking delivery types', () => {
|
||||
// Arrange
|
||||
const features = { orderType: OrderType.Download };
|
||||
|
||||
// Act
|
||||
const result = hasOrderTypeFeature(features, [
|
||||
OrderType.Delivery,
|
||||
OrderType.DigitalShipping,
|
||||
OrderType.B2BShipping,
|
||||
]);
|
||||
|
||||
// Assert
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('when checking against empty order types array', () => {
|
||||
it('should return false', () => {
|
||||
// Arrange
|
||||
const features = { orderType: OrderType.Delivery };
|
||||
|
||||
// Act
|
||||
const result = hasOrderTypeFeature(features, []);
|
||||
|
||||
// Assert
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('when checking against all order types', () => {
|
||||
it('should return true for any valid order type', () => {
|
||||
// Arrange
|
||||
const features = { orderType: OrderType.Delivery };
|
||||
|
||||
// Act
|
||||
const result = hasOrderTypeFeature(features, [
|
||||
OrderType.InStore,
|
||||
OrderType.Pickup,
|
||||
OrderType.Delivery,
|
||||
OrderType.DigitalShipping,
|
||||
OrderType.B2BShipping,
|
||||
OrderType.Download,
|
||||
]);
|
||||
|
||||
// Assert
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
import { OrderType } from '../models';
|
||||
import { getOrderTypeFeature } from './get-order-type-feature.helper';
|
||||
|
||||
/**
|
||||
* Checks if the order type feature in the provided features record matches any of the specified order types.
|
||||
*
|
||||
* @param features - Record containing feature flags with an 'orderType' key
|
||||
* @param orderTypes - Array of order types to check against
|
||||
* @returns true if the feature's order type is one of the provided types, false otherwise
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* // Check if order type is a delivery type
|
||||
* const isDelivery = hasOrderTypeFeature(features, [
|
||||
* OrderType.Delivery,
|
||||
* OrderType.DigitalShipping,
|
||||
* OrderType.B2BShipping
|
||||
* ]);
|
||||
*
|
||||
* // Check if order type requires a target branch
|
||||
* const hasTargetBranch = hasOrderTypeFeature(features, [
|
||||
* OrderType.InStore,
|
||||
* OrderType.Pickup
|
||||
* ]);
|
||||
* ```
|
||||
*/
|
||||
export function hasOrderTypeFeature(
|
||||
features: Record<string, string> | undefined,
|
||||
orderTypes: readonly OrderType[],
|
||||
): boolean {
|
||||
const orderType = getOrderTypeFeature(features);
|
||||
|
||||
if (!orderType) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return orderTypes.includes(orderType);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
export * from './get-order-type-feature.helper';
|
||||
export * from './has-order-type-feature.helper';
|
||||
export * from './checkout-analysis.helpers';
|
||||
export * from './checkout-business-logic.helpers';
|
||||
export * from './checkout-data.helpers';
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
import { AvailabilityType as GeneratedAvailabilityType } from '@generated/swagger/checkout-api';
|
||||
|
||||
export type AvailabilityType = GeneratedAvailabilityType;
|
||||
|
||||
// Helper constants for easier usage
|
||||
export const AvailabilityType = {
|
||||
Unknown: 0,
|
||||
InStock: 1,
|
||||
OutOfStock: 2,
|
||||
PreOrder: 32,
|
||||
BackOrder: 256,
|
||||
Discontinued: 512,
|
||||
OnRequest: 1024,
|
||||
SpecialOrder: 2048,
|
||||
DigitalDelivery: 4096,
|
||||
PartialStock: 8192,
|
||||
ExpectedDelivery: 16384,
|
||||
} as const;
|
||||
@@ -1,3 +0,0 @@
|
||||
import { AvailabilityDTO } from '@generated/swagger/checkout-api';
|
||||
|
||||
export type Availability = AvailabilityDTO;
|
||||
@@ -1,11 +1,10 @@
|
||||
import { BranchType } from '@generated/swagger/checkout-api';
|
||||
|
||||
export type BranchTypeEnum = BranchType;
|
||||
|
||||
export const BranchTypeEnum = {
|
||||
NotSet: 0,
|
||||
Store: 1,
|
||||
WebStore: 2,
|
||||
CallCenter: 4,
|
||||
Headquarter: 8,
|
||||
} as const;
|
||||
export const BranchType = {
|
||||
NotSet: 0,
|
||||
Store: 1,
|
||||
WebStore: 2,
|
||||
CallCenter: 4,
|
||||
Headquarter: 8,
|
||||
Warehouse: 16,
|
||||
} as const;
|
||||
|
||||
export type BranchType = (typeof BranchType)[keyof typeof BranchType];
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
import { BranchDTO } from '@generated/swagger/checkout-api';
|
||||
|
||||
export type Branch = BranchDTO;
|
||||
@@ -1,6 +0,0 @@
|
||||
import { BuyerDTO } from '@generated/swagger/checkout-api';
|
||||
import { BuyerType } from '@isa/common/data-access';
|
||||
|
||||
export type Buyer = BuyerDTO & {
|
||||
buyerType: BuyerType;
|
||||
};
|
||||
@@ -1,28 +1,21 @@
|
||||
export * from './availability-type';
|
||||
export * from './availability';
|
||||
export * from './branch';
|
||||
export * from './buyer';
|
||||
export * from './branch-type';
|
||||
export * from './campaign';
|
||||
export * from './checkout-item';
|
||||
export * from './checkout';
|
||||
export * from './customer-type-analysis';
|
||||
export * from './destination';
|
||||
export * from './gender';
|
||||
export * from './loyalty';
|
||||
export * from './ola-availability';
|
||||
export * from './order-options';
|
||||
export * from './order-type';
|
||||
export * from './order';
|
||||
export * from './payer';
|
||||
export * from './price';
|
||||
export * from './product';
|
||||
export * from './promotion';
|
||||
export * from './reward-selection-item';
|
||||
export * from './shipping-address';
|
||||
export * from './shipping-target';
|
||||
export * from './shopping-cart-item';
|
||||
export * from './supplier';
|
||||
export * from './shopping-cart';
|
||||
export * from './update-shopping-cart-item';
|
||||
export * from './vat-type';
|
||||
export * from './reward-selection-item';
|
||||
export * from './branch-type';
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
import { PayerDTO } from '@generated/swagger/checkout-api';
|
||||
import { PayerType } from '@isa/common/data-access';
|
||||
|
||||
export type Payer = PayerDTO & {
|
||||
payerType: PayerType;
|
||||
};
|
||||
@@ -1,3 +0,0 @@
|
||||
import { SupplierDTO } from '@generated/swagger/checkout-api';
|
||||
|
||||
export type Supplier = SupplierDTO;
|
||||
@@ -1,56 +1,67 @@
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
AvailabilityDTOSchema,
|
||||
CampaignDTOSchema,
|
||||
LoyaltyDTOSchema,
|
||||
ProductDTOSchema,
|
||||
PromotionDTOSchema,
|
||||
PriceSchema,
|
||||
EntityDTOContainerOfDestinationDTOSchema,
|
||||
ItemTypeSchema,
|
||||
PriceValueSchema,
|
||||
} from './base-schemas';
|
||||
import { EntityContainerSchema } from '@isa/common/data-access';
|
||||
import { AvailabilitySchema } from './availability.schema';
|
||||
import { CampaignSchema } from './campaign.schema';
|
||||
import { DestinationSchema } from './destination.schema';
|
||||
import { ItemTypeSchema } from './item-type.schema';
|
||||
import { LoyaltySchema } from './loyalty.schema';
|
||||
import { PriceFlatSchema } from './price-flat.schema';
|
||||
import { ProductSchema } from './product.schema';
|
||||
import { PromotionSchema } from './promotion.schema';
|
||||
|
||||
const AddToShoppingCartDefaultSchema = z.object({
|
||||
availability: AvailabilityDTOSchema,
|
||||
campaign: CampaignDTOSchema,
|
||||
destination: EntityDTOContainerOfDestinationDTOSchema,
|
||||
itemType: ItemTypeSchema,
|
||||
product: ProductDTOSchema,
|
||||
promotion: PromotionDTOSchema,
|
||||
quantity: z.number().int().positive(),
|
||||
retailPrice: PriceSchema,
|
||||
shopItemId: z.number().int().positive().optional(),
|
||||
// Base schema for all add to shopping cart items
|
||||
const AddToShoppingCartBaseSchema = z.object({
|
||||
availability: AvailabilitySchema.describe('Availability'),
|
||||
campaign: CampaignSchema.describe('Campaign information').optional(),
|
||||
destination: EntityContainerSchema(DestinationSchema).describe(
|
||||
'Destination information',
|
||||
),
|
||||
itemType: ItemTypeSchema.describe('Item type').optional(),
|
||||
loyalty: LoyaltySchema.describe('Loyalty information').optional(),
|
||||
product: ProductSchema.describe('Product').optional(),
|
||||
promotion: PromotionSchema.describe('Promotion information').optional(),
|
||||
quantity: z.number().int().positive().describe('Quantity'),
|
||||
retailPrice: PriceFlatSchema.describe('Retail price').optional(),
|
||||
shopItemId: z
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.describe('ShopItem identifier')
|
||||
.optional(),
|
||||
});
|
||||
|
||||
// When loyalty points are used the price value must be 0 and promotion is not allowed
|
||||
// and availability must not contain a price
|
||||
// and loyalty must be present
|
||||
const AddToShoppingCartWithRedemptionPointsSchema =
|
||||
AddToShoppingCartDefaultSchema.omit({
|
||||
availability: true,
|
||||
promotion: true,
|
||||
}).extend({
|
||||
availability: AvailabilityDTOSchema.unwrap()
|
||||
.omit({ price: true })
|
||||
.extend({
|
||||
price: PriceSchema.unwrap()
|
||||
.omit({ value: true })
|
||||
.extend({
|
||||
value: PriceValueSchema.omit({ value: true }).extend({ value: z.literal(0) }),
|
||||
}),
|
||||
}),
|
||||
loyalty: LoyaltyDTOSchema,
|
||||
});
|
||||
|
||||
const AddToShoppingCartSchema = z.union([
|
||||
AddToShoppingCartDefaultSchema,
|
||||
AddToShoppingCartWithRedemptionPointsSchema,
|
||||
]);
|
||||
// Apply business rules validation
|
||||
const AddToShoppingCartSchema = AddToShoppingCartBaseSchema.refine(
|
||||
(data) => {
|
||||
// When loyalty points are used, promotion must not be present
|
||||
if (data.loyalty && data.promotion) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
},
|
||||
{
|
||||
message: 'Promotion is not allowed when using loyalty points',
|
||||
},
|
||||
).refine(
|
||||
(data) => {
|
||||
// When loyalty points are used, price value should be 0
|
||||
if (data.loyalty && data.availability?.price?.value?.value !== 0) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
},
|
||||
{
|
||||
message: 'Price value must be 0 when using loyalty points for redemption',
|
||||
},
|
||||
);
|
||||
|
||||
export const AddItemToShoppingCartParamsSchema = z.object({
|
||||
shoppingCartId: z.number().int().positive(),
|
||||
items: z.array(AddToShoppingCartSchema).min(1),
|
||||
shoppingCartId: z
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.describe('Shopping cart identifier'),
|
||||
items: z.array(AddToShoppingCartSchema).min(1).describe('List of items'),
|
||||
});
|
||||
|
||||
export type AddItemToShoppingCartParams = z.infer<
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const AllergeneType = {
|
||||
NotSet: 0,
|
||||
SulfurDioxide: 1,
|
||||
EggWhite: 2,
|
||||
EggYolk: 4,
|
||||
Egg: 6,
|
||||
Shellfish: 8,
|
||||
Fish: 16,
|
||||
Mollusc: 32,
|
||||
Celery: 64,
|
||||
Mustard: 128,
|
||||
Sesame: 256,
|
||||
MilkProtein: 512,
|
||||
Lactose: 1024,
|
||||
Milk: 1536,
|
||||
Nuts: 2048,
|
||||
Hazelnut: 6144,
|
||||
Almond: 10240,
|
||||
Walnut: 18432,
|
||||
Cashew: 34816,
|
||||
Pecan: 67584,
|
||||
BrazilNut: 133120,
|
||||
Pistachio: 264192,
|
||||
Macadamia: 526336,
|
||||
Gluten: 1048576,
|
||||
Wheat: 3145728,
|
||||
Rye: 5242880,
|
||||
Oat: 9437184,
|
||||
Barley: 17825792,
|
||||
Spelt: 34603008,
|
||||
Kamut: 68157440,
|
||||
Emmer: 135266304,
|
||||
Pulse: 268435456,
|
||||
Peanuts: 805306368,
|
||||
Soy: 1342177280,
|
||||
Chickpea: 2415919104,
|
||||
Lentil: 4563402752,
|
||||
Peavine: 8858370048,
|
||||
Lupin: 17448304640,
|
||||
Pea: 34628173824,
|
||||
Bean: 68987912192,
|
||||
Cinnamon: 137438953472,
|
||||
} as const;
|
||||
|
||||
const ALL_FLAGS = Object.values(AllergeneType).reduce<number>(
|
||||
(a, b) => a | b,
|
||||
0,
|
||||
);
|
||||
|
||||
export const AllergeneTypeSchema = z
|
||||
.nativeEnum(AllergeneType)
|
||||
.refine(
|
||||
(val) => (val & ~ALL_FLAGS) === 0,
|
||||
() => ({ message: 'Invalid allergene type combination' }),
|
||||
)
|
||||
.describe('Allergen type classification for food items');
|
||||
|
||||
export type AllergeneType = z.infer<typeof AllergeneTypeSchema>;
|
||||
@@ -0,0 +1,19 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const AvailabilityType = {
|
||||
NotSet: 0,
|
||||
NotAvailable: 1,
|
||||
PrebookAtBuyer: 2,
|
||||
PrebookAtRetailer: 32,
|
||||
PrebookAtSupplier: 256,
|
||||
TemporarilyNotAvailable: 512,
|
||||
Available: 1024,
|
||||
OnDemand: 2048,
|
||||
AtProductionDate: 4096,
|
||||
Discontinued: 8192,
|
||||
EndOfLife: 16384,
|
||||
} as const;
|
||||
|
||||
export const AvailabilityTypeSchema = z.nativeEnum(AvailabilityType).describe('Availability type');
|
||||
|
||||
export type AvailabilityType = z.infer<typeof AvailabilityTypeSchema>;
|
||||
@@ -0,0 +1,35 @@
|
||||
import {
|
||||
EntityContainerSchema,
|
||||
PriceSchema,
|
||||
TouchBaseSchema,
|
||||
} from '@isa/common/data-access';
|
||||
import { z } from 'zod';
|
||||
import { AvailabilityTypeSchema } from './availability-type.schema';
|
||||
import { DateRangeSchema } from './data-range.schema';
|
||||
import { LogisticianSchema } from './logistician.schema';
|
||||
import { SupplierSchema } from './supplier.schema';
|
||||
|
||||
export const AvailabilitySchema = z
|
||||
.object({
|
||||
availabilityType: AvailabilityTypeSchema.describe('Availability type').optional(),
|
||||
estimatedDelivery: DateRangeSchema.describe('Estimated delivery').optional(),
|
||||
estimatedShippingDate: z.string().describe('EstimatedShipping date').optional(),
|
||||
inStock: z.number().describe('Whether item is in stock').optional(),
|
||||
isPrebooked: z.boolean().describe('Whether prebooked').optional(),
|
||||
lastRequest: z.string().describe('Last request').optional(),
|
||||
logistician: EntityContainerSchema(LogisticianSchema).describe('Logistician information').optional(),
|
||||
price: PriceSchema.describe('Price information').optional(),
|
||||
requestReference: z.string().describe('Request reference').optional(),
|
||||
shopItem: EntityContainerSchema(z.any()).describe('Shop item information').optional(),
|
||||
ssc: z.string().describe('Ssc').optional(),
|
||||
sscText: z.string().describe('Ssc text').optional(),
|
||||
supplier: EntityContainerSchema(SupplierSchema).describe('Supplier information').optional(),
|
||||
supplierInfo: z.string().describe('Supplier info').optional(),
|
||||
supplierProductNumber: z.string().describe('SupplierProduct number').optional(),
|
||||
supplierSSC: z.string().describe('Supplier s s c').optional(),
|
||||
supplierSSCText: z.string().describe('Supplier s s c text').optional(),
|
||||
supplyChannel: z.string().describe('Supply channel').optional(),
|
||||
})
|
||||
.extend(TouchBaseSchema.shape);
|
||||
|
||||
export type Availability = z.infer<typeof AvailabilitySchema>;
|
||||
@@ -0,0 +1,22 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const Avoirdupois = {
|
||||
NotSet: 0,
|
||||
Nanogramm: 1,
|
||||
Mikrogramm: 2,
|
||||
Milligramm: 4,
|
||||
Gramm: 8,
|
||||
Kilogramm: 16,
|
||||
MetrischeTonne: 32,
|
||||
Zentner: 64,
|
||||
DoppelZentner: 128,
|
||||
MetrischesKarat: 256,
|
||||
Grain: 512,
|
||||
Dram: 1024,
|
||||
Ounce: 2048,
|
||||
Pound: 4096,
|
||||
} as const;
|
||||
|
||||
export const AvoirdupoisSchema = z.nativeEnum(Avoirdupois).describe('Avoirdupois');
|
||||
|
||||
export type Avoirdupois = z.infer<typeof AvoirdupoisSchema>;
|
||||
@@ -1,338 +1,13 @@
|
||||
import { z } from 'zod';
|
||||
import { AvailabilityType, Gender, ShippingTarget } from '../models';
|
||||
import { OrderType } from '../models';
|
||||
import { BranchTypeEnum } from '../models';
|
||||
import {
|
||||
AddressSchema,
|
||||
CommunicationDetailsSchema,
|
||||
EntityContainerSchema,
|
||||
OrganisationSchema,
|
||||
PriceValueSchema,
|
||||
VatTypeSchema,
|
||||
VatValueSchema,
|
||||
} from '@isa/common/data-access';
|
||||
|
||||
// Re-export PriceValueSchema for other checkout schemas
|
||||
export { PriceValueSchema } from '@isa/common/data-access';
|
||||
|
||||
// ItemType from generated API - it's a numeric bitwise enum
|
||||
export const ItemTypeSchema = z.number().optional();
|
||||
|
||||
// Enum schemas based on generated swagger types
|
||||
export const AvailabilityTypeSchema = z.nativeEnum(AvailabilityType).optional();
|
||||
export const ShippingTargetSchema = z.nativeEnum(ShippingTarget).optional();
|
||||
|
||||
export const GenderSchema = z.nativeEnum(Gender).optional();
|
||||
|
||||
export const OrderTypeSchema = z.nativeEnum(OrderType).optional();
|
||||
|
||||
// Base schemas for nested objects
|
||||
export const DateRangeSchema = z
|
||||
.object({
|
||||
start: z.string().optional(),
|
||||
stop: z.string().optional(),
|
||||
})
|
||||
.optional();
|
||||
|
||||
// export const OrganisationSchema = z
|
||||
// .object({
|
||||
// name: z.string().optional(),
|
||||
// taxNumber: z.string().optional(),
|
||||
// })
|
||||
// .optional();
|
||||
|
||||
// DTO Schemas based on generated API types
|
||||
export const TouchedBaseSchema = z.object({
|
||||
id: z.number().optional(),
|
||||
createdAt: z.string().optional(),
|
||||
modifiedAt: z.string().optional(),
|
||||
});
|
||||
|
||||
export const PriceDTOSchema = z
|
||||
.object({
|
||||
id: z.number().optional(),
|
||||
createdAt: z.string().optional(),
|
||||
modifiedAt: z.string().optional(),
|
||||
value: PriceValueSchema.optional(),
|
||||
vat: VatValueSchema.optional(),
|
||||
})
|
||||
.optional();
|
||||
|
||||
export const PriceSchema = z
|
||||
.object({
|
||||
currency: z.string().optional(),
|
||||
currencySymbol: z.string().optional(),
|
||||
validFrom: z.string().optional(),
|
||||
value: z.number(),
|
||||
vatInPercent: z.number().optional(),
|
||||
vatType: VatTypeSchema.optional(),
|
||||
vatValue: z.number().optional(),
|
||||
})
|
||||
.optional();
|
||||
|
||||
export const CampaignDTOSchema = z
|
||||
.object({
|
||||
id: z.number().optional(),
|
||||
createdAt: z.string().optional(),
|
||||
modifiedAt: z.string().optional(),
|
||||
code: z.string().optional(),
|
||||
label: z.string().optional(),
|
||||
type: z.string().optional(),
|
||||
value: z.number().optional(),
|
||||
})
|
||||
.optional();
|
||||
|
||||
export const PromotionDTOSchema = z
|
||||
.object({
|
||||
id: z.number().optional(),
|
||||
createdAt: z.string().optional(),
|
||||
modifiedAt: z.string().optional(),
|
||||
code: z.string().optional(),
|
||||
label: z.string().optional(),
|
||||
type: z.string().optional(),
|
||||
value: z.number().optional(),
|
||||
})
|
||||
.optional();
|
||||
|
||||
export const LoyaltyDTOSchema = z
|
||||
.object({
|
||||
id: z.number().optional(),
|
||||
createdAt: z.string().optional(),
|
||||
modifiedAt: z.string().optional(),
|
||||
code: z.string().optional(),
|
||||
label: z.string().optional(),
|
||||
type: z.string().optional(),
|
||||
value: z.number().optional(),
|
||||
})
|
||||
.optional();
|
||||
|
||||
export const ProductDTOSchema = z
|
||||
.object({
|
||||
id: z.number().optional(),
|
||||
createdAt: z.string().optional(),
|
||||
modifiedAt: z.string().optional(),
|
||||
additionalName: z.string().optional(),
|
||||
catalogProductNumber: z.string().optional(),
|
||||
contributors: z.string().optional(),
|
||||
ean: z.string().optional(),
|
||||
edition: z.string().optional(),
|
||||
format: z.string().optional(),
|
||||
formatDetail: z.string().optional(),
|
||||
locale: z.string().optional(),
|
||||
manufacturer: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
productGroup: z.string().optional(),
|
||||
productGroupDetails: z.string().optional(),
|
||||
publicationDate: z.string().optional(),
|
||||
serial: z.string().optional(),
|
||||
supplierProductNumber: z.string().optional(),
|
||||
volume: z.string().optional(),
|
||||
})
|
||||
.optional();
|
||||
|
||||
export const LogisticianDTOSchema = z
|
||||
.object({
|
||||
id: z.number().optional(),
|
||||
createdAt: z.string().optional(),
|
||||
modifiedAt: z.string().optional(),
|
||||
gln: z.string().optional(),
|
||||
logisticianNumber: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
})
|
||||
.optional();
|
||||
|
||||
export const SupplierDTOSchema = z
|
||||
.object({
|
||||
id: z.number().optional(),
|
||||
createdAt: z.string().optional(),
|
||||
modifiedAt: z.string().optional(),
|
||||
key: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
supplierNumber: z.string().optional(),
|
||||
supplierType: z
|
||||
.union([z.literal(0), z.literal(1), z.literal(2), z.literal(4)])
|
||||
.optional(),
|
||||
})
|
||||
.optional();
|
||||
|
||||
export const AvailabilityDTOSchema = z
|
||||
.object({
|
||||
id: z.number().optional(),
|
||||
createdAt: z.string().optional(),
|
||||
modifiedAt: z.string().optional(),
|
||||
availabilityType: AvailabilityTypeSchema,
|
||||
estimatedDelivery: DateRangeSchema,
|
||||
estimatedShippingDate: z.string().optional(),
|
||||
inStock: z.number().optional(),
|
||||
isPrebooked: z.boolean().optional(),
|
||||
lastRequest: z.string().optional(),
|
||||
logistician: EntityContainerSchema(LogisticianDTOSchema).optional(),
|
||||
price: PriceDTOSchema,
|
||||
requestReference: z.string().optional(),
|
||||
ssc: z.string().optional(),
|
||||
sscText: z.string().optional(),
|
||||
supplier: EntityContainerSchema(SupplierDTOSchema).optional(),
|
||||
supplierInfo: z.string().optional(),
|
||||
supplierProductNumber: z.string().optional(),
|
||||
supplierSSC: z.string().optional(),
|
||||
supplierSSCText: z.string().optional(),
|
||||
supplyChannel: z.string().optional(),
|
||||
})
|
||||
.optional();
|
||||
|
||||
// LabelDTO schema for the EntityContainerSchema
|
||||
export const LabelDTOSchema = z
|
||||
.object({
|
||||
id: z.number().optional(),
|
||||
createdAt: z.string().optional(),
|
||||
modifiedAt: z.string().optional(),
|
||||
label: z.string().optional(),
|
||||
})
|
||||
.optional();
|
||||
|
||||
export const BranchDTOSchema: z.ZodOptional<z.ZodObject<any>> = z
|
||||
.object({
|
||||
id: z.number().optional(),
|
||||
createdAt: z.string().optional(),
|
||||
modifiedAt: z.string().optional(),
|
||||
address: AddressSchema.optional(),
|
||||
branchNumber: z.string().optional(),
|
||||
branchType: z.nativeEnum(BranchTypeEnum).optional(),
|
||||
isDefault: z.string().optional(),
|
||||
isOnline: z.boolean().optional(),
|
||||
isOrderingEnabled: z.boolean().optional(),
|
||||
isShippingEnabled: z.boolean().optional(),
|
||||
key: z.string().optional(),
|
||||
label: EntityContainerSchema(LabelDTOSchema),
|
||||
name: z.string().optional(),
|
||||
parent: EntityContainerSchema(
|
||||
z.lazy((): z.ZodOptional<z.ZodObject<any>> => BranchDTOSchema),
|
||||
).optional(),
|
||||
shortName: z.string().optional(),
|
||||
})
|
||||
.optional();
|
||||
|
||||
export const BranchSchema = BranchDTOSchema;
|
||||
|
||||
export const DestinationDTOSchema = z
|
||||
.object({
|
||||
id: z.number().optional(),
|
||||
createdAt: z.string().optional(),
|
||||
modifiedAt: z.string().optional(),
|
||||
address: AddressSchema.optional(),
|
||||
communicationDetails: CommunicationDetailsSchema.optional(),
|
||||
firstName: z.string().optional(),
|
||||
gender: GenderSchema,
|
||||
lastName: z.string().optional(),
|
||||
locale: z.string().optional(),
|
||||
organisation: OrganisationSchema.optional(),
|
||||
title: z.string().optional(),
|
||||
target: ShippingTargetSchema.optional(),
|
||||
targetBranch: EntityContainerSchema(BranchSchema).optional(),
|
||||
})
|
||||
.refine(
|
||||
(data) => {
|
||||
// targetBranch is only optional if target is 2 (Delivery)
|
||||
// For other targets (like Branch = 1), targetBranch should be required
|
||||
if (data?.target !== undefined && data.target !== 2) {
|
||||
return data?.targetBranch !== undefined;
|
||||
}
|
||||
return true;
|
||||
},
|
||||
{
|
||||
message: 'targetBranch is required when target is not Delivery (2)',
|
||||
path: ['targetBranch'],
|
||||
},
|
||||
)
|
||||
.optional();
|
||||
|
||||
export const EntityDTOContainerOfDestinationDTOSchema = z
|
||||
.object({
|
||||
id: z.number().optional(),
|
||||
data: DestinationDTOSchema,
|
||||
})
|
||||
.optional();
|
||||
|
||||
// NotificationChannel is a bitwise enum
|
||||
export const NotificationChannelSchema = z.union([
|
||||
z.literal(0),
|
||||
z.literal(1),
|
||||
z.literal(2),
|
||||
z.literal(4),
|
||||
z.literal(8),
|
||||
z.literal(16),
|
||||
]);
|
||||
|
||||
// EntityReferenceDTO schema
|
||||
export const EntityReferenceDTOSchema = TouchedBaseSchema.extend({
|
||||
pId: z.string().optional(),
|
||||
reference: z
|
||||
.object({
|
||||
id: z.number().optional(),
|
||||
pId: z.string().optional(),
|
||||
})
|
||||
.optional(),
|
||||
source: z.number().optional(),
|
||||
});
|
||||
|
||||
// AddresseeWithReferenceDTO schema
|
||||
export const AddresseeWithReferenceDTOSchema = EntityReferenceDTOSchema.extend({
|
||||
address: AddressSchema.optional(),
|
||||
communicationDetails: CommunicationDetailsSchema.optional(),
|
||||
firstName: z.string().optional(),
|
||||
gender: GenderSchema,
|
||||
lastName: z.string().optional(),
|
||||
locale: z.string().optional(),
|
||||
organisation: OrganisationSchema.optional(),
|
||||
title: z.string().optional(),
|
||||
});
|
||||
|
||||
// BuyerStatus and PayerStatus enum schemas (bitwise enums matching generated API)
|
||||
export const BuyerStatusSchema = z.union([
|
||||
z.literal(0),
|
||||
z.literal(1),
|
||||
z.literal(2),
|
||||
z.literal(4),
|
||||
z.literal(8),
|
||||
z.literal(16),
|
||||
]);
|
||||
|
||||
export const PayerStatusSchema = z.union([
|
||||
z.literal(0),
|
||||
z.literal(1),
|
||||
z.literal(2),
|
||||
z.literal(4),
|
||||
z.literal(8),
|
||||
z.literal(16),
|
||||
]);
|
||||
|
||||
export const BuyerTypeSchema = z.union([
|
||||
z.literal(0),
|
||||
z.literal(1),
|
||||
z.literal(2),
|
||||
z.literal(4),
|
||||
z.literal(8),
|
||||
z.literal(16),
|
||||
]);
|
||||
export const PayerTypeSchema = z.union([
|
||||
z.literal(0),
|
||||
z.literal(4),
|
||||
z.literal(8),
|
||||
z.literal(16),
|
||||
]);
|
||||
|
||||
// BuyerDTO schema
|
||||
export const BuyerDTOSchema = AddresseeWithReferenceDTOSchema.extend({
|
||||
buyerNumber: z.string().optional(),
|
||||
buyerStatus: BuyerStatusSchema.optional(),
|
||||
buyerType: BuyerTypeSchema,
|
||||
dateOfBirth: z.string().optional(),
|
||||
isTemporaryAccount: z.boolean().optional(),
|
||||
});
|
||||
|
||||
// PayerDTO schema
|
||||
export const PayerDTOSchema = AddresseeWithReferenceDTOSchema.extend({
|
||||
payerNumber: z.string().optional(),
|
||||
payerStatus: PayerStatusSchema.optional(),
|
||||
payerType: PayerTypeSchema,
|
||||
});
|
||||
import { z } from 'zod';
|
||||
|
||||
// OrderType is a union of specific string literals
|
||||
export const OrderTypeSchema = z.union([
|
||||
z.literal('Rücklage'),
|
||||
z.literal('Abholung'),
|
||||
z.literal('Versand'),
|
||||
z.literal('DIG-Versand'),
|
||||
z.literal('B2B-Versand'),
|
||||
z.literal('Download'),
|
||||
]).describe('Order type');
|
||||
|
||||
export type OrderType = z.infer<typeof OrderTypeSchema>;
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
import { z } from 'zod';
|
||||
import { BranchType } from '../models';
|
||||
|
||||
export const BranchTypeSchema = z.nativeEnum(BranchType).describe('Branch type');
|
||||
29
libs/checkout/data-access/src/lib/schemas/branch.schema.ts
Normal file
29
libs/checkout/data-access/src/lib/schemas/branch.schema.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import {
|
||||
AddressSchema,
|
||||
EntityContainerSchema,
|
||||
LabelSchema,
|
||||
} from '@isa/common/data-access';
|
||||
import { z } from 'zod';
|
||||
import { BranchType } from '../models';
|
||||
|
||||
export const BranchSchema = z.object({
|
||||
id: z.number().describe('Unique identifier').optional(),
|
||||
createdAt: z.string().describe('Creation timestamp').optional(),
|
||||
modifiedAt: z.string().describe('Modified at').optional(),
|
||||
address: AddressSchema.describe('Branch physical address').optional(),
|
||||
branchNumber: z.string().describe('Branch number identifier').optional(),
|
||||
branchType: z.nativeEnum(BranchType).describe('Branch type classification').optional(),
|
||||
isDefault: z.string().describe('Whether this is the default branch').optional(),
|
||||
isOnline: z.boolean().describe('Whether branch is online').optional(),
|
||||
isOrderingEnabled: z.boolean().describe('Whether ordering is enabled for this branch').optional(),
|
||||
isShippingEnabled: z.boolean().describe('Whether shipping is enabled for this branch').optional(),
|
||||
key: z.string().describe('Unique branch key identifier').optional(),
|
||||
label: EntityContainerSchema(LabelSchema).describe('Branch label information'),
|
||||
name: z.string().describe('Branch name').optional(),
|
||||
parent: EntityContainerSchema(
|
||||
z.lazy((): z.ZodType<any> => BranchSchema),
|
||||
).describe('Parent branch entity').optional(),
|
||||
shortName: z.string().describe('Branch short name').optional(),
|
||||
});
|
||||
|
||||
export type Branch = z.infer<typeof BranchSchema>;
|
||||
@@ -0,0 +1,14 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const BuyerStatus = {
|
||||
NotSet: 0,
|
||||
Blocked: 1,
|
||||
Check: 2,
|
||||
LowDegreeOfCreditworthiness: 4,
|
||||
Dunning1: 8,
|
||||
Dunning2: 16,
|
||||
} as const;
|
||||
|
||||
export const BuyerStatusSchema = z.nativeEnum(BuyerStatus).describe('Buyer status');
|
||||
|
||||
export type BuyerStatus = z.infer<typeof BuyerStatusSchema>;
|
||||
18
libs/checkout/data-access/src/lib/schemas/buyer.schema.ts
Normal file
18
libs/checkout/data-access/src/lib/schemas/buyer.schema.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
AddresseeWithReferenceSchema,
|
||||
BuyerTypeSchema,
|
||||
} from '@isa/common/data-access';
|
||||
import { BuyerStatusSchema } from './buyer-status.schema';
|
||||
|
||||
export const BuyerSchema = z
|
||||
.object({
|
||||
buyerNumber: z.string().describe('Unique buyer identifier number').optional(),
|
||||
buyerStatus: BuyerStatusSchema.describe('Current status of the buyer account').optional(),
|
||||
buyerType: BuyerTypeSchema.describe('Buyer type').optional(),
|
||||
dateOfBirth: z.string().describe('Date of birth').optional(),
|
||||
isTemporaryAccount: z.boolean().describe('Whether temporaryAccount').optional(),
|
||||
})
|
||||
.extend(AddresseeWithReferenceSchema.shape);
|
||||
|
||||
export type Buyer = z.infer<typeof BuyerSchema>;
|
||||
11
libs/checkout/data-access/src/lib/schemas/campaign.schema.ts
Normal file
11
libs/checkout/data-access/src/lib/schemas/campaign.schema.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { TouchBaseSchema } from '@isa/common/data-access';
|
||||
import { z } from 'zod';
|
||||
|
||||
export const CampaignSchema = z
|
||||
.object({
|
||||
code: z.string().describe('Code value').optional(),
|
||||
label: z.string().describe('Label').optional(),
|
||||
type: z.string().describe('Type').optional(),
|
||||
value: z.number().describe('Value').optional(),
|
||||
})
|
||||
.extend(TouchBaseSchema.shape);
|
||||
@@ -1,56 +1,70 @@
|
||||
import { ItemPayload } from '@generated/swagger/checkout-api';
|
||||
import { z } from 'zod';
|
||||
import { OrderTypeSchema } from './base-schemas';
|
||||
|
||||
const CanAddPriceSchema = z.object({
|
||||
value: z
|
||||
|
||||
.object({
|
||||
value: z.number().optional(),
|
||||
currency: z.string().optional(),
|
||||
currencySymbol: z.string().optional(),
|
||||
value: z.number().describe('Value').optional(),
|
||||
currency: z.string().describe('Currency code').optional(),
|
||||
currencySymbol: z.string().describe('Currency symbol').optional(),
|
||||
})
|
||||
.describe('Value')
|
||||
.optional(),
|
||||
vat: z
|
||||
|
||||
.object({
|
||||
inPercent: z.number().optional(),
|
||||
label: z.string().optional(),
|
||||
value: z.number().optional(),
|
||||
vatType: z.number().optional(),
|
||||
inPercent: z.number().describe('In percent').optional(),
|
||||
label: z.string().describe('Label').optional(),
|
||||
value: z.number().describe('Value').optional(),
|
||||
vatType: z.number().describe('VAT type').optional(),
|
||||
})
|
||||
.describe('Value Added Tax')
|
||||
.optional(),
|
||||
});
|
||||
|
||||
const CanAddOLAAvailabilitySchema = z.object({
|
||||
altAt: z.string().optional(),
|
||||
at: z.string().optional(),
|
||||
ean: z.string().optional(),
|
||||
format: z.string().optional(),
|
||||
isPrebooked: z.boolean().optional(),
|
||||
itemId: z.number().int().optional(),
|
||||
logistician: z.string().optional(),
|
||||
logisticianId: z.number().int().optional(),
|
||||
preferred: z.number().int().optional(),
|
||||
price: CanAddPriceSchema.optional(),
|
||||
qty: z.number().int().optional(),
|
||||
shop: z.number().int().optional(),
|
||||
ssc: z.string().optional(),
|
||||
sscText: z.string().optional(),
|
||||
status: z.number().int(),
|
||||
supplier: z.string().optional(),
|
||||
supplierId: z.number().int().optional(),
|
||||
supplierProductNumber: z.string().optional(),
|
||||
altAt: z.string().describe('Alt at').optional(),
|
||||
at: z.string().describe('At').optional(),
|
||||
ean: z.string().describe('European Article Number barcode').optional(),
|
||||
format: z.string().describe('Format').optional(),
|
||||
isPrebooked: z.boolean().describe('Whether prebooked').optional(),
|
||||
itemId: z.number().int().describe('Unique item identifier').optional(),
|
||||
logistician: z.string().describe('Logistician information').optional(),
|
||||
logisticianId: z.number().int().describe('Logistician identifier').optional(),
|
||||
preferred: z.number().int().describe('Preferred').optional(),
|
||||
price: CanAddPriceSchema.describe('Price information').optional(),
|
||||
qty: z.number().int().describe('Qty').optional(),
|
||||
shop: z.number().int().describe('Shop').optional(),
|
||||
ssc: z.string().describe('Ssc').optional(),
|
||||
sscText: z.string().describe('Ssc text').optional(),
|
||||
status: z.number().int().describe('Current status'),
|
||||
supplier: z.string().describe('Supplier information').optional(),
|
||||
supplierId: z.number().int().describe('Supplier identifier').optional(),
|
||||
supplierProductNumber: z
|
||||
.string()
|
||||
.describe('SupplierProduct number')
|
||||
.optional(),
|
||||
});
|
||||
|
||||
const CanAddItemPayloadSchema = z.object({
|
||||
availabilities: z.array(CanAddOLAAvailabilitySchema),
|
||||
customerFeatures: z.record(z.string().optional()),
|
||||
orderType: OrderTypeSchema,
|
||||
id: z.string(),
|
||||
availabilities: z
|
||||
.array(CanAddOLAAvailabilitySchema)
|
||||
.describe('Availabilities'),
|
||||
customerFeatures: z
|
||||
.record(z.string().optional())
|
||||
.describe('Customer features'),
|
||||
orderType: OrderTypeSchema.describe('Order type'),
|
||||
id: z.string().describe('Unique identifier'),
|
||||
});
|
||||
|
||||
export const CanAddItemsToShoppingCartParamsSchema = z.object({
|
||||
shoppingCartId: z.number().int().positive(),
|
||||
payload: z.array(CanAddItemPayloadSchema).min(1),
|
||||
shoppingCartId: z
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.describe('Shopping cart identifier'),
|
||||
payload: z.array(CanAddItemPayloadSchema).min(1).describe('Payload'),
|
||||
});
|
||||
|
||||
export type CanAddItemsToShoppingCartParams = z.infer<
|
||||
|
||||
41
libs/checkout/data-access/src/lib/schemas/category.schema.ts
Normal file
41
libs/checkout/data-access/src/lib/schemas/category.schema.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { z } from 'zod';
|
||||
import { EntitySchema, EntityContainerSchema } from '@isa/common/data-access';
|
||||
|
||||
export const CategorySchema: z.ZodType<{
|
||||
changed?: string;
|
||||
created?: string;
|
||||
id?: number;
|
||||
pId?: string;
|
||||
status?: number;
|
||||
uId?: string;
|
||||
version?: number;
|
||||
name?: string;
|
||||
parent?: {
|
||||
id?: number;
|
||||
pId?: string;
|
||||
uId?: string;
|
||||
data?: any;
|
||||
};
|
||||
type?: string;
|
||||
key?: string;
|
||||
sort?: number;
|
||||
start?: string;
|
||||
stop?: string;
|
||||
tenant?: {
|
||||
id?: number;
|
||||
pId?: string;
|
||||
uId?: string;
|
||||
data?: any;
|
||||
};
|
||||
}> = EntitySchema.extend({
|
||||
name: z.string().describe('Name').optional(),
|
||||
parent: z.lazy(() => EntityContainerSchema(CategorySchema)).describe('Parent').optional(),
|
||||
type: z.string().describe('Type').optional(),
|
||||
key: z.string().describe('Key').optional(),
|
||||
sort: z.number().int().describe('Sort criteria').optional(),
|
||||
start: z.string().describe('Start').optional(),
|
||||
stop: z.string().describe('Stop').optional(),
|
||||
tenant: EntityContainerSchema(z.any()).describe('Tenant identifier').optional(),
|
||||
});
|
||||
|
||||
export type Category = z.infer<typeof CategorySchema>;
|
||||
58
libs/checkout/data-access/src/lib/schemas/company.schema.ts
Normal file
58
libs/checkout/data-access/src/lib/schemas/company.schema.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
EntitySchema,
|
||||
EntityContainerSchema,
|
||||
AddressSchema,
|
||||
} from '@isa/common/data-access';
|
||||
|
||||
export const CompanySchema: z.ZodType<{
|
||||
changed?: string;
|
||||
created?: string;
|
||||
id?: number;
|
||||
pId?: string;
|
||||
status?: number;
|
||||
uId?: string;
|
||||
version?: number;
|
||||
parent?: {
|
||||
id?: number;
|
||||
pId?: string;
|
||||
uId?: string;
|
||||
data?: any;
|
||||
};
|
||||
companyNumber?: string;
|
||||
locale?: string;
|
||||
name?: string;
|
||||
nameSuffix?: string;
|
||||
legalForm?: string;
|
||||
department?: string;
|
||||
costUnit?: string;
|
||||
vatId?: string;
|
||||
address?: {
|
||||
street?: string;
|
||||
streetNumber?: string;
|
||||
zipCode?: string;
|
||||
city?: string;
|
||||
country?: string;
|
||||
additionalInfo?: string;
|
||||
};
|
||||
gln?: string;
|
||||
sector?: string;
|
||||
}> = EntitySchema.extend({
|
||||
parent: z
|
||||
.lazy(() => EntityContainerSchema(CompanySchema))
|
||||
.describe('Parent')
|
||||
.optional(),
|
||||
companyNumber: z.string().describe('Company number').optional(),
|
||||
locale: z.string().describe('Locale').optional(),
|
||||
name: z.string().max(64).describe('Name').optional(),
|
||||
nameSuffix: z.string().max(64).describe('Name suffix').optional(),
|
||||
legalForm: z.string().max(64).describe('Legal form').optional(),
|
||||
department: z.string().max(64).describe('Department').optional(),
|
||||
costUnit: z.string().max(64).describe('Cost unit').optional(),
|
||||
vatId: z.string().max(16).describe('Vat identifier').optional(),
|
||||
address: AddressSchema.describe('Address').optional(),
|
||||
gln: z.string().max(64).describe('Gln').optional(),
|
||||
sector: z.string().max(64).describe('Sector').optional(),
|
||||
});
|
||||
|
||||
export type Company = z.infer<typeof CompanySchema>;
|
||||
@@ -1,64 +0,0 @@
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
BuyerDTOSchema,
|
||||
PayerDTOSchema,
|
||||
NotificationChannelSchema,
|
||||
} from './base-schemas';
|
||||
import { ShippingAddressSchema } from './shipping-address.schema';
|
||||
|
||||
/**
|
||||
* Schema for checkout completion parameters.
|
||||
*
|
||||
* @remarks
|
||||
* This schema validates all data required to complete a checkout without accessing state management.
|
||||
* All customer and order information must be provided as parameters.
|
||||
*/
|
||||
export const CompleteCheckoutParamsSchema = z.object({
|
||||
/**
|
||||
* ID of the shopping cart to process
|
||||
* The checkout will be created/refreshed from this shopping cart
|
||||
*/
|
||||
shoppingCartId: z.number().int().positive(),
|
||||
|
||||
/**
|
||||
* Buyer information (required)
|
||||
* Will be set on the checkout before order creation
|
||||
*/
|
||||
buyer: BuyerDTOSchema,
|
||||
|
||||
/**
|
||||
* Notification channels for customer communications (required)
|
||||
*/
|
||||
notificationChannels: NotificationChannelSchema,
|
||||
|
||||
/**
|
||||
* Customer features for business logic determination
|
||||
* Used to analyze customer type and determine order handling
|
||||
*/
|
||||
customerFeatures: z.record(z.string(), z.string()),
|
||||
|
||||
/**
|
||||
* Payer information (optional)
|
||||
* Required only for B2B, delivery, or download orders
|
||||
*/
|
||||
payer: PayerDTOSchema.optional(),
|
||||
|
||||
/**
|
||||
* Shipping address (optional)
|
||||
* Required only for delivery orders
|
||||
* Will be merged into destination objects
|
||||
*/
|
||||
shippingAddress: ShippingAddressSchema.optional(),
|
||||
|
||||
/**
|
||||
* Special comment to apply to all shopping cart items (optional)
|
||||
*/
|
||||
specialComment: z.string().optional(),
|
||||
});
|
||||
|
||||
/**
|
||||
* TypeScript type inferred from the Zod schema
|
||||
*/
|
||||
export type CompleteCheckoutParams = z.infer<
|
||||
typeof CompleteCheckoutParamsSchema
|
||||
>;
|
||||
@@ -0,0 +1,97 @@
|
||||
import { z } from 'zod';
|
||||
import { NotificationChannelSchema } from '@isa/common/data-access';
|
||||
import {
|
||||
CustomerSchema,
|
||||
PayerSchema as CrmPayerSchema,
|
||||
ShippingAddressSchema as CrmShippingAddressSchema,
|
||||
} from '@isa/crm/data-access';
|
||||
import { BuyerSchema } from './buyer.schema';
|
||||
import { PayerSchema } from './payer.schema';
|
||||
import { ShippingAddressSchema } from './shipping-address.schema';
|
||||
|
||||
/**
|
||||
* Schema for checkout completion parameters.
|
||||
*
|
||||
* @remarks
|
||||
* This schema validates all data required to complete a checkout without accessing state management.
|
||||
* All customer and order information must be provided as parameters.
|
||||
*/
|
||||
export const CompleteOrderParamsSchema = z.object({
|
||||
/**
|
||||
* ID of the shopping cart to process
|
||||
* The checkout will be created/refreshed from this shopping cart
|
||||
*/
|
||||
shoppingCartId: z
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.describe('Shopping cart identifier'),
|
||||
|
||||
/**
|
||||
* Buyer information (required)
|
||||
* Will be set on the checkout before order creation
|
||||
*/
|
||||
buyer: BuyerSchema.describe('Buyer information'),
|
||||
|
||||
/**
|
||||
* Notification channels for customer communications (required)
|
||||
*/
|
||||
notificationChannels: NotificationChannelSchema.describe(
|
||||
'Notification channels',
|
||||
).optional(),
|
||||
|
||||
/**
|
||||
* Customer features for business logic determination
|
||||
* Used to analyze customer type and determine order handling
|
||||
*/
|
||||
customerFeatures: z.record(
|
||||
z.string().describe('Customer features'),
|
||||
z.string(),
|
||||
),
|
||||
|
||||
/**
|
||||
* Payer information (optional)
|
||||
* Required only for B2B, delivery, or download orders
|
||||
*/
|
||||
payer: PayerSchema.describe('Payer information').optional(),
|
||||
|
||||
/**
|
||||
* Shipping address (optional)
|
||||
* Required only for delivery orders
|
||||
* Will be merged into destination objects
|
||||
*/
|
||||
shippingAddress: ShippingAddressSchema.describe(
|
||||
'Shipping address information',
|
||||
).optional(),
|
||||
|
||||
/**
|
||||
* Special comment to apply to all shopping cart items (optional)
|
||||
*/
|
||||
specialComment: z.string().describe('Special comment').optional(),
|
||||
});
|
||||
|
||||
/**
|
||||
* TypeScript type inferred from the Zod schema
|
||||
*/
|
||||
export type CompleteOrderParams = z.infer<typeof CompleteOrderParamsSchema>;
|
||||
|
||||
export const CompleteCrmOrderParamsSchema = z.object({
|
||||
shoppingCartId: z
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.describe('Shopping cart identifier'),
|
||||
crmCustomer: CustomerSchema.describe('Crm customer'),
|
||||
crmPayer: CrmPayerSchema.describe('Crm payer').optional(),
|
||||
crmShippingAddress: CrmShippingAddressSchema.describe(
|
||||
'Crm shipping address',
|
||||
).optional(),
|
||||
notificationChannels: NotificationChannelSchema.describe(
|
||||
'Notification channels',
|
||||
).optional(),
|
||||
specialComment: z.string().describe('Special comment').optional(),
|
||||
});
|
||||
|
||||
export type CompleteCrmOrderParams = z.infer<
|
||||
typeof CompleteCrmOrderParamsSchema
|
||||
>;
|
||||
@@ -0,0 +1,15 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const ComponentItemDisplayType = {
|
||||
Visible: 0,
|
||||
Hidden: 1,
|
||||
Emphasize: 2,
|
||||
} as const;
|
||||
|
||||
export const ComponentItemDisplayTypeSchema = z.nativeEnum(
|
||||
ComponentItemDisplayType,
|
||||
).describe('ComponentItemDisplay type');
|
||||
|
||||
export type ComponentItemDisplayType = z.infer<
|
||||
typeof ComponentItemDisplayTypeSchema
|
||||
>;
|
||||
@@ -0,0 +1,27 @@
|
||||
import {
|
||||
EntityContainerSchema,
|
||||
QuantityUnitTypeSchema,
|
||||
TouchBaseSchema,
|
||||
} from '@isa/common/data-access';
|
||||
import { z } from 'zod';
|
||||
import { CategorySchema } from './category.schema';
|
||||
import { ComponentItemDisplayTypeSchema } from './component-item-display-type.schema';
|
||||
|
||||
export const ComponentItemSchema = z
|
||||
.object({
|
||||
name: z.string().describe('Name').optional(),
|
||||
description: z.string().describe('Description text').optional(),
|
||||
item: EntityContainerSchema(z.lazy(() => z.any())).describe('Item').optional(), // ItemSchema would create circular dependency
|
||||
category: EntityContainerSchema(CategorySchema).describe('Category information').optional(),
|
||||
required: z.boolean().describe('Whether this is required').optional(),
|
||||
quantityMin: z.number().describe('Quantity min').optional(),
|
||||
quantityMax: z.number().describe('Quantity max').optional(),
|
||||
quantityUnitType: QuantityUnitTypeSchema.describe('QuantityUnit type').optional(),
|
||||
unit: z.string().describe('Unit').optional(),
|
||||
displayType: ComponentItemDisplayTypeSchema.describe('Display type').optional(),
|
||||
start: z.string().describe('Start').optional(),
|
||||
stop: z.string().describe('Stop').optional(),
|
||||
})
|
||||
.extend(TouchBaseSchema.shape);
|
||||
|
||||
export type ComponentItem = z.infer<typeof ComponentItemSchema>;
|
||||
@@ -0,0 +1,21 @@
|
||||
import {
|
||||
EntitySchema,
|
||||
QuantityUnitTypeSchema,
|
||||
} from '@isa/common/data-access';
|
||||
import { z } from 'zod';
|
||||
import { ComponentItemSchema } from './component-item.schema';
|
||||
import { SetTypeSchema } from './set-type.schema';
|
||||
|
||||
export const ComponentsSchema = z
|
||||
.object({
|
||||
items: z.array(ComponentItemSchema).describe('List of items').optional(),
|
||||
type: SetTypeSchema.describe('Type').optional(),
|
||||
overallQuantityMin: z.number().describe('Overall quantity min').optional(),
|
||||
overallQuantityMax: z.number().describe('Overall quantity max').optional(),
|
||||
quantityUnitType: QuantityUnitTypeSchema.describe('QuantityUnit type').optional(),
|
||||
unit: z.string().describe('Unit').optional(),
|
||||
referenceQuantity: z.number().describe('Reference quantity').optional(),
|
||||
})
|
||||
.extend(EntitySchema.shape);
|
||||
|
||||
export type Components = z.infer<typeof ComponentsSchema>;
|
||||
@@ -0,0 +1,9 @@
|
||||
import { z } from 'zod';
|
||||
import { TouchBaseSchema, EntityContainerSchema } from '@isa/common/data-access';
|
||||
|
||||
export const ContributorHelperSchema = TouchBaseSchema.extend({
|
||||
type: z.string().describe('Type').optional(),
|
||||
contributor: EntityContainerSchema(z.any()).describe('Contributor information').optional(),
|
||||
});
|
||||
|
||||
export type ContributorHelper = z.infer<typeof ContributorHelperSchema>;
|
||||
@@ -0,0 +1,11 @@
|
||||
import { TouchBaseSchema } from '@isa/common/data-access';
|
||||
import { z } from 'zod';
|
||||
|
||||
export const DateRangeSchema = z
|
||||
.object({
|
||||
start: z.string().describe('Start').optional(),
|
||||
stop: z.string().describe('Stop').optional(),
|
||||
})
|
||||
.extend(TouchBaseSchema.shape);
|
||||
|
||||
export type DateRange = z.infer<typeof DateRangeSchema>;
|
||||
@@ -0,0 +1,30 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const DeclarableFoodAdditives = {
|
||||
NotSet: 0,
|
||||
NatriumcyclymatUndSaccarinNatrium: 1,
|
||||
Suessungsmitteln: 2,
|
||||
Phenylaninquelle: 4,
|
||||
MitEinerZuckerartUndSuessungsmitteln: 8,
|
||||
Geschmacksverstaerker: 16,
|
||||
Geschwefelt: 32,
|
||||
Geschwaerzt: 64,
|
||||
Gewachst: 128,
|
||||
Phosphat: 256,
|
||||
Konservierungsstoff: 512,
|
||||
Farbstoff: 1024,
|
||||
Antioxidationsmittel: 2048,
|
||||
Koffeinhaltig: 4096,
|
||||
Saeurungsmittel: 8192,
|
||||
Rauch: 16384,
|
||||
Lachsersatz: 32768,
|
||||
Vorderschinken: 65536,
|
||||
} as const;
|
||||
|
||||
export const DeclarableFoodAdditivesSchema = z.nativeEnum(
|
||||
DeclarableFoodAdditives,
|
||||
).describe('Declarable food additives');
|
||||
|
||||
export type DeclarableFoodAdditives = z.infer<
|
||||
typeof DeclarableFoodAdditivesSchema
|
||||
>;
|
||||
@@ -0,0 +1,34 @@
|
||||
import {
|
||||
AddressSchema,
|
||||
CommunicationDetailsSchema,
|
||||
EntityContainerSchema,
|
||||
GenderSchema,
|
||||
OrganisationSchema,
|
||||
} from '@isa/common/data-access';
|
||||
import { z } from 'zod';
|
||||
import { ShippingTargetSchema } from './shipping-target.schema';
|
||||
import { BranchSchema } from './branch.schema';
|
||||
|
||||
export const DestinationSchema = z.object({
|
||||
id: z.number().describe('Unique identifier').optional(),
|
||||
createdAt: z.string().describe('Creation timestamp').optional(),
|
||||
modifiedAt: z.string().describe('Modified at').optional(),
|
||||
address: AddressSchema.describe('Address').optional(),
|
||||
communicationDetails: CommunicationDetailsSchema.describe(
|
||||
'Communication details',
|
||||
).optional(),
|
||||
firstName: z.string().describe('First name').optional(),
|
||||
gender: GenderSchema.describe('Gender').default(0),
|
||||
lastName: z.string().describe('Last name').optional(),
|
||||
locale: z.string().describe('Locale').optional(),
|
||||
organisation: OrganisationSchema.describe(
|
||||
'Organisation information',
|
||||
).optional(),
|
||||
title: z.string().describe('Title').optional(),
|
||||
target: ShippingTargetSchema.describe('Target').optional(),
|
||||
targetBranch: EntityContainerSchema(BranchSchema)
|
||||
.describe('Target branch')
|
||||
.optional(),
|
||||
});
|
||||
|
||||
export type Destination = z.infer<typeof DestinationSchema>;
|
||||
18
libs/checkout/data-access/src/lib/schemas/file.schema.ts
Normal file
18
libs/checkout/data-access/src/lib/schemas/file.schema.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { z } from 'zod';
|
||||
import { EntitySchema } from '@isa/common/data-access';
|
||||
|
||||
export const FileSchema = EntitySchema.extend({
|
||||
name: z.string().describe('Name').optional(),
|
||||
type: z.string().describe('Type').optional(),
|
||||
path: z.string().describe('Path').optional(),
|
||||
mime: z.string().describe('Mime').optional(),
|
||||
hash: z.string().describe('Whether has h').optional(),
|
||||
size: z.number().describe('Size').optional(),
|
||||
subtitle: z.string().describe('Subtitle').optional(),
|
||||
copyright: z.string().describe('Copyright').optional(),
|
||||
locale: z.string().describe('Locale').optional(),
|
||||
license: z.string().describe('License').optional(),
|
||||
sort: z.number().int().describe('Sort criteria').optional(),
|
||||
});
|
||||
|
||||
export type File = z.infer<typeof FileSchema>;
|
||||
@@ -0,0 +1,26 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const FoodLabel = {
|
||||
NotSet: 0,
|
||||
Organic: 1,
|
||||
Vegetarian: 2,
|
||||
Vegan: 4,
|
||||
Halal: 8,
|
||||
Kashrut: 16,
|
||||
Pasteurised: 32,
|
||||
ExtendedShelfLife: 64,
|
||||
UltraHighTemperature: 128,
|
||||
RawFood: 256,
|
||||
NotSuitableForPregnantWomen: 512,
|
||||
NotSuitableForChildren: 1024,
|
||||
ContainsAlcolhol: 3584,
|
||||
ContainsCaffein: 5632,
|
||||
ContainsBeef: 8192,
|
||||
ContainsPork: 16384,
|
||||
ContainsFish: 32768,
|
||||
ContainsRawMilk: 66048,
|
||||
} as const;
|
||||
|
||||
export const FoodLabelSchema = z.nativeEnum(FoodLabel).describe('Food label');
|
||||
|
||||
export type FoodLabel = z.infer<typeof FoodLabelSchema>;
|
||||
19
libs/checkout/data-access/src/lib/schemas/food.schema.ts
Normal file
19
libs/checkout/data-access/src/lib/schemas/food.schema.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { z } from 'zod';
|
||||
import { TouchBaseSchema } from '@isa/common/data-access';
|
||||
import { FoodLabelSchema } from './food-label.schema';
|
||||
import { AllergeneTypeSchema } from './allergene-type.schema';
|
||||
import { DeclarableFoodAdditivesSchema } from './declarable-food-additives.schema';
|
||||
import { NutritionFactsSchema } from './nutrition-facts.schema';
|
||||
|
||||
export const FoodSchema = TouchBaseSchema.extend({
|
||||
alcohol: z.number().describe('Alcohol').optional(),
|
||||
foodLabel: FoodLabelSchema.describe('Food label information').optional(),
|
||||
allergenes: AllergeneTypeSchema.describe('Allergenes').optional(),
|
||||
allergenesDescription: z.string().describe('Allergenes description').optional(),
|
||||
mayContainTracesOf: AllergeneTypeSchema.describe('May contain traces of').optional(),
|
||||
mayContainTracesOfDescription: z.string().describe('May contain traces of description').optional(),
|
||||
declarableFoodAdditives: DeclarableFoodAdditivesSchema.describe('Declarable food additives').optional(),
|
||||
nutritionFacts: NutritionFactsSchema.describe('Nutrition facts information').optional(),
|
||||
});
|
||||
|
||||
export type Food = z.infer<typeof FoodSchema>;
|
||||
@@ -0,0 +1,9 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const ImageSchema = z.object({
|
||||
alt: z.string().describe('Alt').optional(),
|
||||
path: z.string().describe('Path').optional(),
|
||||
subtitle: z.string().describe('Subtitle').optional(),
|
||||
});
|
||||
|
||||
export type Image = z.infer<typeof ImageSchema>;
|
||||
@@ -1,6 +1,56 @@
|
||||
export * from './add-item-to-shopping-cart-params.schema';
|
||||
export * from './base-schemas';
|
||||
export * from './allergene-type.schema';
|
||||
export * from './availability-type.schema';
|
||||
export * from './availability.schema';
|
||||
export * from './avoirdupois.schema';
|
||||
export * from './branch-type.schema';
|
||||
export * from './branch.schema';
|
||||
export * from './buyer-status.schema';
|
||||
export * from './buyer.schema';
|
||||
export * from './can-add-items-to-shopping-cart-params.schema';
|
||||
export * from './complete-checkout-params.schema';
|
||||
export * from './campaign.schema';
|
||||
export * from './category.schema';
|
||||
export * from './company.schema';
|
||||
export * from './component-item-display-type.schema';
|
||||
export * from './component-item.schema';
|
||||
export * from './components.schema';
|
||||
export * from './complete-order-params.schema';
|
||||
export * from './contributor-helper.schema';
|
||||
export * from './data-range.schema';
|
||||
export * from './declarable-food-additives.schema';
|
||||
export * from './destination.schema';
|
||||
export * from './file.schema';
|
||||
export * from './food-label.schema';
|
||||
export * from './food.schema';
|
||||
export * from './image.schema';
|
||||
export * from './item-label.schema';
|
||||
export * from './item-type.schema';
|
||||
export * from './item.schema';
|
||||
export * from './logistician.schema';
|
||||
export * from './loyalty.schema';
|
||||
export * from './notification-channel.schema';
|
||||
export * from './nutrition-fact-type.schema';
|
||||
export * from './nutrition-fact.schema';
|
||||
export * from './nutrition-facts.schema';
|
||||
export * from './payer-status.schema';
|
||||
export * from './payer-type.schema';
|
||||
export * from './payer.schema';
|
||||
export * from './payment-type.schema';
|
||||
export * from './price-flat.schema';
|
||||
export * from './product.schema';
|
||||
export * from './promotion.schema';
|
||||
export * from './quantity-unit-type.schema';
|
||||
export * from './remove-shopping-cart-item-params.schema';
|
||||
export * from './rezeptmasz.schema';
|
||||
export * from './set-type.schema';
|
||||
export * from './shipping-address.schema';
|
||||
export * from './shipping-target.schema';
|
||||
export * from './shop-item.schema';
|
||||
export * from './size.schema';
|
||||
export * from './supplier-type.schema';
|
||||
export * from './supplier.schema';
|
||||
export * from './tenant.schema';
|
||||
export * from './text.schema';
|
||||
export * from './update-shopping-cart-item-params.schema';
|
||||
export * from './url.schema';
|
||||
export * from './weight.schema';
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import { z } from 'zod';
|
||||
import { TouchBaseSchema } from '@isa/common/data-access';
|
||||
|
||||
export const ItemLabelSchema = TouchBaseSchema.extend({
|
||||
labelType: z.string().describe('Label type').optional(),
|
||||
cultureInfo: z.string().describe('Culture info').optional(),
|
||||
value: z.string().describe('Value').optional(),
|
||||
});
|
||||
|
||||
export type ItemLabel = z.infer<typeof ItemLabelSchema>;
|
||||
@@ -0,0 +1,27 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const ItemType = {
|
||||
NotSet: 0,
|
||||
SingleUnit: 1,
|
||||
SalesUnit: 2,
|
||||
Set: 4,
|
||||
PackagingUnit: 8,
|
||||
Configurable: 16,
|
||||
Discount: 32,
|
||||
Percentaged: 64,
|
||||
FixedPrice: 128,
|
||||
Postage: 256,
|
||||
HandlingFee: 512,
|
||||
Voucher: 1024,
|
||||
ComponentList: 2048,
|
||||
Download: 4096,
|
||||
Streaming: 8192,
|
||||
ItemPrice: 16384,
|
||||
SingleUnitItemPrice: 16385,
|
||||
ComponentPrice: 32768,
|
||||
CustomPrice: 65536,
|
||||
} as const;
|
||||
|
||||
export const ItemTypeSchema = z.nativeEnum(ItemType).describe('Item type');
|
||||
|
||||
export type ItemType = z.infer<typeof ItemTypeSchema>;
|
||||
54
libs/checkout/data-access/src/lib/schemas/item.schema.ts
Normal file
54
libs/checkout/data-access/src/lib/schemas/item.schema.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { EntityContainerSchema, EntitySchema } from '@isa/common/data-access';
|
||||
import { z } from 'zod';
|
||||
import { CategorySchema } from './category.schema';
|
||||
import { CompanySchema } from './company.schema';
|
||||
import { ComponentsSchema } from './components.schema';
|
||||
import { ContributorHelperSchema } from './contributor-helper.schema';
|
||||
import { FileSchema } from './file.schema';
|
||||
import { FoodSchema } from './food.schema';
|
||||
import { ItemLabelSchema } from './item-label.schema';
|
||||
import { ItemTypeSchema } from './item-type.schema';
|
||||
import { SizeSchema } from './size.schema';
|
||||
import { TenantSchema } from './tenant.schema';
|
||||
import { TextSchema } from './text.schema';
|
||||
import { WeightSchema } from './weight.schema';
|
||||
|
||||
export const ItemSchema = z
|
||||
.object({
|
||||
itemNumber: z.string().describe('Unique item number identifier').optional(),
|
||||
name: z.string().describe('Item name').optional(),
|
||||
subtitle: z.string().describe('Item subtitle').optional(),
|
||||
description: z.string().describe('Item description text').optional(),
|
||||
ean: z.string().describe('European Article Number barcode').optional(),
|
||||
secondaryEAN: z.string().describe('Secondary EAN barcode').optional(),
|
||||
precedingItem: EntityContainerSchema(
|
||||
z.lazy((): z.ZodType<any> => ItemSchema),
|
||||
).describe('Reference to preceding item version').optional(),
|
||||
precedingItemEAN: z.string().describe('EAN of preceding item version').optional(),
|
||||
contributors: z.array(ContributorHelperSchema).describe('List of contributors (authors, editors, etc)').optional(),
|
||||
manufacturer: EntityContainerSchema(CompanySchema).describe('Manufacturer company information').optional(),
|
||||
publicationDate: z.string().describe('Publication date of the item').optional(),
|
||||
categories: z.array(EntityContainerSchema(CategorySchema)).describe('List of item categories').optional(),
|
||||
manufacturingCosts: z.number().describe('Manufacturing costs').optional(),
|
||||
size: SizeSchema.describe('Physical size dimensions').optional(),
|
||||
weight: WeightSchema.describe('Total weight').optional(),
|
||||
netWeight: WeightSchema.describe('Net weight excluding packaging').optional(),
|
||||
weightOfPackaging: WeightSchema.describe('Weight of packaging only').optional(),
|
||||
itemType: ItemTypeSchema.describe('Type classification of the item').optional(),
|
||||
edition: z.string().describe('Edition information').optional(),
|
||||
serial: z.string().describe('Serial number').optional(),
|
||||
format: z.string().describe('Format code (e.g., HC, PB, EB)').optional(),
|
||||
formatDetail: z.string().describe('Detailed format description').optional(),
|
||||
volume: z.string().describe('Volume information').optional(),
|
||||
toxins: z.string().describe('Toxin warnings or information').optional(),
|
||||
files: z.array(EntityContainerSchema(FileSchema)).describe('List of associated files').optional(),
|
||||
texts: z.array(EntityContainerSchema(TextSchema)).describe('List of associated text content').optional(),
|
||||
set: EntityContainerSchema(ComponentsSchema).describe('Set components if item is a set').optional(),
|
||||
accessories: EntityContainerSchema(ComponentsSchema).describe('Accessory components').optional(),
|
||||
labels: z.array(ItemLabelSchema).describe('List of item labels').optional(),
|
||||
food: FoodSchema.describe('Food-specific information if applicable').optional(),
|
||||
tenant: EntityContainerSchema(TenantSchema).describe('Tenant identifier').optional(),
|
||||
})
|
||||
.extend(EntitySchema.shape);
|
||||
|
||||
export type Item = z.infer<typeof ItemSchema>;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user