diff --git a/.claude/agents/docs-researcher-advanced.md b/.claude/agents/docs-researcher-advanced.md
new file mode 100644
index 000000000..35de1dc95
--- /dev/null
+++ b/.claude/agents/docs-researcher-advanced.md
@@ -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
+
+### 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
+
+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.
\ No newline at end of file
diff --git a/.claude/agents/docs-researcher.md b/.claude/agents/docs-researcher.md
new file mode 100644
index 000000000..b0e37b688
--- /dev/null
+++ b/.claude/agents/docs-researcher.md
@@ -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.
\ No newline at end of file
diff --git a/.claude/commands/dev-add-e2e-attrs.md b/.claude/commands/dev-add-e2e-attrs.md
new file mode 100644
index 000000000..de09e5ca2
--- /dev/null
+++ b/.claude/commands/dev-add-e2e-attrs.md
@@ -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
+
+Submit
+
+
+
+ Submit
+
+```
+
+**Inputs:**
+```html
+
+
+
+
+
+```
+
+**Dynamic Lists:**
+```html
+
+@for (item of items; track item.id) {
+
{{ item.name }}
+}
+
+
+@for (item of items; track item.id) {
+
+ {{ item.name }}
+
+}
+```
+
+**Links:**
+```html
+
+View Order
+
+
+
+ View Order
+
+```
+
+**Custom Components:**
+```html
+
+Save
+
+
+
+ Save
+
+```
+
+### 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
+
+```
+
+## 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)
diff --git a/.claude/commands/docs-library.md b/.claude/commands/docs-library.md
new file mode 100644
index 000000000..b88e74db5
--- /dev/null
+++ b/.claude/commands/docs-library.md
@@ -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: `
+
+
+ `
+})
+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): Description of output
+
+**Example:**
+```html
+
+
+```
+
+### 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`
+[Method description]
+
+**Parameters:**
+- `id` (string): Description
+
+**Returns:** `Observable`
+
+**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
+
+ Content
+
+```
+
+## 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
diff --git a/.claude/commands/docs-refresh-reference.md b/.claude/commands/docs-refresh-reference.md
new file mode 100644
index 000000000..225b43c5f
--- /dev/null
+++ b/.claude/commands/docs-refresh-reference.md
@@ -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)
diff --git a/.claude/commands/quality-bundle-analyze.md b/.claude/commands/quality-bundle-analyze.md
new file mode 100644
index 000000000..24d4f8832
--- /dev/null
+++ b/.claude/commands/quality-bundle-analyze.md
@@ -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)
diff --git a/.claude/commands/quality-coverage.md b/.claude/commands/quality-coverage.md
new file mode 100644
index 000000000..af5c41d87
--- /dev/null
+++ b/.claude/commands/quality-coverage.md
@@ -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
diff --git a/.claude/skills/api-change-analyzer/SKILL.md b/.claude/skills/api-change-analyzer/SKILL.md
new file mode 100644
index 000000000..d9b541e3f
--- /dev/null
+++ b/.claude/skills/api-change-analyzer/SKILL.md
@@ -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
diff --git a/.claude/skills/architecture-enforcer/SKILL.md b/.claude/skills/architecture-enforcer/SKILL.md
new file mode 100644
index 000000000..2ca80e140
--- /dev/null
+++ b/.claude/skills/architecture-enforcer/SKILL.md
@@ -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)
diff --git a/.claude/skills/circular-dependency-resolver/SKILL.md b/.claude/skills/circular-dependency-resolver/SKILL.md
new file mode 100644
index 000000000..ecdf2eae9
--- /dev/null
+++ b/.claude/skills/circular-dependency-resolver/SKILL.md
@@ -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
diff --git a/.claude/skills/library-scaffolder/SKILL.md b/.claude/skills/library-scaffolder/SKILL.md
new file mode 100644
index 000000000..304da3602
--- /dev/null
+++ b/.claude/skills/library-scaffolder/SKILL.md
@@ -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
+///
+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
diff --git a/.claude/skills/skill-creator/LICENSE.txt b/.claude/skills/skill-creator/LICENSE.txt
new file mode 100644
index 000000000..7a4a3ea24
--- /dev/null
+++ b/.claude/skills/skill-creator/LICENSE.txt
@@ -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.
\ No newline at end of file
diff --git a/.claude/skills/skill-creator/SKILL.md b/.claude/skills/skill-creator/SKILL.md
new file mode 100644
index 000000000..40699358f
--- /dev/null
+++ b/.claude/skills/skill-creator/SKILL.md
@@ -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 --path
+```
+
+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
+```
+
+Optional output directory specification:
+
+```bash
+scripts/package_skill.py ./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
diff --git a/.claude/skills/skill-creator/scripts/init_skill.py b/.claude/skills/skill-creator/scripts/init_skill.py
new file mode 100755
index 000000000..329ad4e5a
--- /dev/null
+++ b/.claude/skills/skill-creator/scripts/init_skill.py
@@ -0,0 +1,303 @@
+#!/usr/bin/env python3
+"""
+Skill Initializer - Creates a new skill from template
+
+Usage:
+ init_skill.py --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 --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()
diff --git a/.claude/skills/skill-creator/scripts/package_skill.py b/.claude/skills/skill-creator/scripts/package_skill.py
new file mode 100755
index 000000000..3ee8e8e9f
--- /dev/null
+++ b/.claude/skills/skill-creator/scripts/package_skill.py
@@ -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 [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 [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()
diff --git a/.claude/skills/skill-creator/scripts/quick_validate.py b/.claude/skills/skill-creator/scripts/quick_validate.py
new file mode 100755
index 000000000..6fa6c6361
--- /dev/null
+++ b/.claude/skills/skill-creator/scripts/quick_validate.py
@@ -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 ")
+ sys.exit(1)
+
+ valid, message = validate_skill(sys.argv[1])
+ print(message)
+ sys.exit(0 if valid else 1)
\ No newline at end of file
diff --git a/.claude/skills/standalone-component-migrator/SKILL.md b/.claude/skills/standalone-component-migrator/SKILL.md
new file mode 100644
index 000000000..055dafad4
--- /dev/null
+++ b/.claude/skills/standalone-component-migrator/SKILL.md
@@ -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
+Content
+{{ item.name }}
+
+
+// NEW
+@if (condition) {
+ Content
+}
+@for (item of items; track item.id) {
+ {{ item.name }}
+}
+@switch (value) {
+ @case ('a') { A
}
+ @default { Default
}
+}
+```
+
+### 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
diff --git a/.claude/skills/swagger-sync-manager/SKILL.md b/.claude/skills/swagger-sync-manager/SKILL.md
new file mode 100644
index 000000000..12a715f29
--- /dev/null
+++ b/.claude/skills/swagger-sync-manager/SKILL.md
@@ -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
diff --git a/.claude/skills/test-migration-specialist/SKILL.md b/.claude/skills/test-migration-specialist/SKILL.md
new file mode 100644
index 000000000..f442c685a
--- /dev/null
+++ b/.claude/skills/test-migration-specialist/SKILL.md
@@ -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
+ ///
+ 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;
+ 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;
+ 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
diff --git a/.claude/skills/type-safety-engineer/SKILL.md b/.claude/skills/type-safety-engineer/SKILL.md
new file mode 100644
index 000000000..7bd7c5fc5
--- /dev/null
+++ b/.claude/skills/type-safety-engineer/SKILL.md
@@ -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;
+
+// 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(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 {
+ 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;
+
+return this.http.get(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
diff --git a/.gitignore b/.gitignore
index a994f7d65..e446edb4f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -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
diff --git a/.vscode/settings.json b/.vscode/settings.json
index 7b6593a5e..33b8960cf 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -20,12 +20,6 @@
"editor.formatOnSave": false
},
"exportall.config.folderListener": [
- "/libs/oms/data-access/src/lib/models",
- "/libs/oms/data-access/src/lib/schemas",
- "/libs/catalogue/data-access/src/lib/models",
- "/libs/common/data-access/src/lib/models",
- "/libs/common/data-access/src/lib/error",
- "/libs/oms/data-access/src/lib/errors/return-process"
],
"github.copilot.chat.commitMessageGeneration.instructions": [
{
@@ -96,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
}
diff --git a/CLAUDE.md b/CLAUDE.md
index ed8a57952..16c6103fe 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1,17 +1,31 @@
# 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
-This is an Angular monorepo managed by Nx. The main application is `isa-app`, which appears to be an inventory and returns management system for retail/e-commerce.
+This is a sophisticated Angular 20.1.2 monorepo managed by Nx 21.3.2. The main application is `isa-app`, a comprehensive inventory and returns management system for retail/e-commerce operations. The system handles complex workflows including order management (OMS), returns processing (remission), customer relationship management (CRM), product cataloging, and checkout/reward systems.
## Architecture
### Monorepo Structure
- **apps/isa-app**: Main Angular application
- **libs/**: Reusable libraries organized by domain and type
- - **core/**: Core utilities (config, logging, storage, tabs)
+ - **core/**: Core utilities (config, logging, storage, tabs, navigation)
- **common/**: Shared utilities (data-access, decorators, print)
- **ui/**: UI component libraries (buttons, dialogs, inputs, etc.)
- **shared/**: Shared domain components (filter, scanner, product components)
@@ -23,131 +37,321 @@ This is an Angular monorepo managed by Nx. The main application is `isa-app`, wh
- **generated/swagger/**: Auto-generated API client code from OpenAPI specs
### Key Architectural Patterns
-- **Standalone Components**: Project uses Angular standalone components
-- **Feature Libraries**: Domain features organized as separate libraries (e.g., `oms-feature-return-search`)
-- **Data Access Layer**: Separate data-access libraries for each domain (e.g., `oms-data-access`, `remission-data-access`)
-- **Shared UI Components**: Reusable UI components in `libs/ui/`
-- **Generated API Clients**: Swagger/OpenAPI clients auto-generated in `generated/swagger/`
+- **Domain-Driven Design**: Clear domain boundaries with dedicated modules (OMS, remission, CRM, catalogue, checkout)
+- **Layered Architecture**: Strict dependency hierarchy (Feature โ Shared/UI โ Data Access โ Infrastructure)
+- **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**: 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-*`)
+- **Modern State Management**: NgRx Signals with entities, session persistence, and reactive patterns
## Common Development Commands
-### Build Commands
+### Essential Commands (Project-Specific)
```bash
-# Build the main application (development)
-npx nx build isa-app --configuration=development
+# 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
# Build for production
-npx nx build isa-app --configuration=production
+npm run build-prod
-# Serve the application with SSL
-npx nx serve isa-app --ssl
-```
-
-### Testing Commands
-```bash
-# Run tests for a specific library (always use --skip-cache)
-npx nx run :test --skip-cache
-# Example: npx nx run remission-data-access:test --skip-cache
-
-# Run tests for all libraries except the main app
-npx nx run-many -t test --exclude isa-app --skip-cache
-
-# Run a single test file
-npx nx run :test --testFile= --skip-cache
-
-# Run tests with coverage
-npx nx run :test --code-coverage --skip-cache
-
-# Run tests in watch mode
-npx nx run :test --watch
-```
-
-### Linting Commands
-```bash
-# Lint a specific project
-npx nx lint
-# 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
+# Regenerate all API clients from Swagger/OpenAPI specs
npm run generate:swagger
-# Start Storybook
-npx nx run isa-app:storybook
+# Regenerate library reference documentation
+npm run docs:generate
# Format code with Prettier
npm run prettier
-# List all projects in the workspace
-npx nx list
+# Format only staged files (pre-commit hook)
+npm run pretty-quick
-# Show project dependencies graph
+# Run CI tests with coverage
+npm run ci
+```
+
+### 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 --skip-nx-cache
+
+# Lint a project
+npx nx lint
+
+# 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
-### Current Setup
-- **Jest**: Primary test runner for existing libraries
-- **Vitest**: Being adopted for new libraries (migration in progress)
-- **Testing Utilities**:
- - **Angular Testing Utilities** (TestBed, ComponentFixture): Use for new tests
- - **Spectator**: Legacy testing utility for existing tests
- - **ng-mocks**: For advanced mocking scenarios
+> **Last Reviewed:** 2025-10-22
+> **Status:** Migration in Progress (Jest โ Vitest)
-### Test File Requirements
+### Current Setup (Migration in Progress)
+- **Jest**: 40 libraries (65.6% - legacy/existing code)
+- **Vitest**: 21 libraries (34.4% - new standard)
+- All formal libraries now have test executors configured
+
+### 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
+
+### Key Requirements
- Test files must end with `.spec.ts`
- Use AAA pattern (Arrange-Act-Assert)
-- Include E2E testing attributes (`data-what`, `data-which`) in HTML templates
-- Mock external dependencies and child components
+- **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**: Store, Effects, Entity, Component Store, Signals
-- **RxJS**: For reactive programming patterns
+- **NgRx Signals**: Primary state management with modern functional approach using `signalStore()`
+- **Entity Management**: Uses `withEntities()` for normalized data storage
+- **Session Persistence**: State persistence with `withStorage()` using SessionStorageProvider
+- **Reactive Methods**: `rxMethod()` with `takeUntilKeydownEscape()` for user-cancellable operations
+- **Custom RxJS Operators**: Specialized operators like `takeUntilAborted()`, `takeUntilKeydown()`
+- **Error Handling**: `tapResponse()` for handling success/error states in stores
+- **Lifecycle Hooks**: `withHooks()` for cleanup and initialization (e.g., orphaned entity cleanup)
+- **Navigation State**: Use `@isa/core/navigation` for temporary navigation context (return URLs, wizard state) instead of query parameters
-## Styling
-- **Tailwind CSS**: Primary styling framework with custom configuration
-- **SCSS**: For component-specific styles
-- **Custom Tailwind plugins**: For buttons, inputs, menus, typography
+## Styling and Design System
+- **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`
-## API Integration
-- **Generated Swagger Clients**: Auto-generated TypeScript clients from OpenAPI specs
-- **Available APIs**: availability, cat-search, checkout, crm, eis, inventory, isa, oms, print, wws
+### 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) {
+
+}
+```
+
+**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 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
-- **npm >= 10.0.0**: Required npm version
+- **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
-- **Component Prefix**: Each library has its own prefix (e.g., `remi` for remission, `oms` for OMS)
-- **Standalone Components**: All new components should be standalone
-- **Path Aliases**: Use TypeScript path aliases defined in `tsconfig.base.json` (e.g., `@isa/core/config`)
-- **Project Names**: Can be found in each library's `project.json` file
+## Important Conventions and Patterns
-## Development Workflow Tips
-- Always use `npx nx run` pattern for executing tasks
-- Include `--skip-cache` flag when running tests to ensure fresh results
-- Use Nx's affected commands to optimize CI/CD pipelines
-- Project graph visualization helps understand dependencies: `npx nx graph`
+### Library Organization
+- **Naming Pattern**: `[domain]-[layer]-[feature]` (e.g., `oms-feature-return-search`, `ui-buttons`)
+- **Path Aliases**: `@isa/[domain]/[layer]/[feature]` (e.g., `@isa/oms/data-access`, `@isa/ui/buttons`)
+- **Project Names**: Found in each library's `project.json` file, following consistent naming
-## Git Workflow
-- **IMPORTANT**: Git commands that require credentials (e.g., `git fetch`, `git pull`, `git push`) must be executed by the user, not by Claude Code
-- Claude Code can execute local git commands that don't require credentials (e.g., `git status`, `git log`, `git diff`, `git checkout`, `git merge`, `git add`, `git commit`)
-- When a git command requiring credentials is needed, Claude Code should inform the user and wait for them to execute it
+### Component Architecture
+- **Standalone Components**: All new components must be standalone with explicit imports
+- **Component Prefixes**: Domain-specific prefixes for clear identification
+ - OMS features: `oms-feature-*` (e.g., `oms-feature-return-search-main`)
+ - Remission features: `remi-*`
+ - UI components: `ui-*`
+ - Core utilities: `core-*`
+- **Signal-based Inputs**: Use Angular signals (`input()`, `computed()`) for reactive properties
+- **Host Binding**: Dynamic CSS classes via Angular host properties
-## Development Notes
-- Use start target to start the application. Only one project can be started: isa-app
-- Make sure to have a look at @docs/guidelines/testing.md before writing tests
-- Make sure to add e2e attributes to the html. Those are important for my colleagues writen e2e tests
-- Guide for the e2e testing attributes can be found in the testing.md
-- When reviewing code follow the instructions @.github/review-instructions.md
+### Dependency Rules
+- **Unidirectional Dependencies**: Feature โ Shared/UI โ Data Access โ Infrastructure
+- **Import Boundaries**: Use path aliases, avoid relative imports across domain boundaries
+- **Generated API Imports**: Import from `@generated/swagger/[api-name]` for API clients
+
+### Code Quality
+- **Modern Angular Patterns**: Prefer `inject()` over constructor injection
+- **Type Safety**: Use Zod schemas for runtime validation alongside TypeScript
+- **Error Handling**: Custom error classes with specific error codes
+- **E2E Testing**: Always include `data-what` and `data-which` attributes in templates
+
+## Development Workflow and Best Practices
+
+### 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-*`)
+
+### 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)
+
+### 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
+
+### Getting Started
+- **Application Startup**: Only `isa-app` can be started - it's the main application entry point
+- **SSL Development**: The development server runs with SSL by default (`npm start`), which is crucial for production-like authentication flows
+- **Node Requirements**: Ensure Node.js โฅ22.0.0 and npm โฅ10.0.0 before starting development
+- **First-Time Setup**: After cloning, run `npm install` then `npm start` to verify everything works
+
+### Essential Documentation References
+- **Testing Guidelines**: Review `docs/guidelines/testing.md` before writing any tests - it covers the JestโVitest migration, SpectatorโAngular Testing Utilities transition, and E2E attribute requirements
+- **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 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
+- **Data Services**: Wrap generated API clients in domain-specific data-access services with proper error handling and Zod validation
+- **State Management**: Use NgRx Signals with `signalStore()`, entity management, and session persistence for complex state
+
+### Performance and Quality Considerations
+- **Bundle Monitoring**: Watch bundle sizes (2MB warning, 5MB error for main bundle)
+- **Testing Cache**: Always use `--skip-nx-cache` flag when running tests to ensure reliable results
+- **Code Quality**: Pre-commit hooks enforce Prettier formatting and ESLint rules automatically
+- **Memory Management**: Clean up subscriptions and use OnPush change detection for optimal performance
+
+### Common Troubleshooting
+- **Build Issues**: Check Node version and run `npm install` if encountering module resolution errors
+- **Test Failures**: Use `--skip-nx-cache` flag and ensure test isolation (no shared state between tests)
+- **Nx Cache Issues**: If you see `existing outputs match the cache, left as is` during build or testing:
+ - **Option 1**: Run `npx nx reset` to clear the Nx cache completely
+ - **Option 2**: Use `--skip-nx-cache` flag to bypass Nx cache for a specific command (e.g., `npx nx test --skip-nx-cache`)
+ - **When to use**: Always use `--skip-nx-cache` when you need guaranteed fresh builds or test results
+- **SSL Certificates**: Development server uses SSL - accept certificate warnings in browser for localhost
+- **Import Errors**: Verify path aliases in `tsconfig.base.json` and use absolute imports for cross-library dependencies
+
+### Domain-Specific Conventions
+- **Component Prefixes**: Use `oms-feature-*` for OMS, `remi-*` for remission, `ui-*` for shared components
+- **Git Workflow**: Default branch is `develop` (not main), use conventional commits without co-author tags
+- **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
diff --git a/apps/isa-app/src/app/app-routing.module.ts b/apps/isa-app/src/app/app-routing.module.ts
index 5e14f7937..8657590e7 100644
--- a/apps/isa-app/src/app/app-routing.module.ts
+++ b/apps/isa-app/src/app/app-routing.module.ts
@@ -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 = [
@@ -193,9 +186,31 @@ const routes: Routes = [
children: [
{
path: 'reward',
- loadChildren: () =>
- import('@isa/checkout/feature/reward-catalog').then((m) => m.routes),
+ children: [
+ {
+ path: '',
+ loadChildren: () =>
+ import('@isa/checkout/feature/reward-catalog').then(
+ (m) => m.routes,
+ ),
+ },
+ {
+ path: 'cart',
+ loadChildren: () =>
+ import('@isa/checkout/feature/reward-shopping-cart').then(
+ (m) => m.routes,
+ ),
+ },
+ {
+ path: 'order-confirmation',
+ loadChildren: () =>
+ import('@isa/checkout/feature/reward-order-confirmation').then(
+ (m) => m.routes,
+ ),
+ },
+ ],
},
+
{
path: 'return',
loadChildren: () =>
@@ -242,9 +257,4 @@ if (isDevMode()) {
exports: [RouterModule],
providers: [provideScrollPositionRestoration()],
})
-export class AppRoutingModule {
- constructor() {
- // Loading TabNavigationService to ensure tab state is synced with tab location
- inject(TabNavigationService);
- }
-}
+export class AppRoutingModule {}
diff --git a/apps/isa-app/src/app/app.module.ts b/apps/isa-app/src/app/app.module.ts
index f1dcb5b21..1c2d436d2 100644
--- a/apps/isa-app/src/app/app.module.ts
+++ b/apps/isa-app/src/app/app.module.ts
@@ -12,6 +12,7 @@ import {
NgModule,
inject,
provideAppInitializer,
+ signal,
} from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
@@ -76,9 +77,17 @@ import {
LogLevel,
withSink,
ConsoleLogSink,
+ logger,
} from '@isa/core/logging';
-import { IDBStorageProvider, UserStorageProvider } from '@isa/core/storage';
+import {
+ IDBStorageProvider,
+ provideUserSubFactory,
+ UserStorageProvider,
+} from '@isa/core/storage';
import { Store } from '@ngrx/store';
+import { TabNavigationService } from '@isa/core/tabs';
+import { OAuthService } from 'angular-oauth2-oidc';
+import z from 'zod';
registerLocaleData(localeDe, localeDeExtra);
registerLocaleData(localeDe, 'de', localeDeExtra);
@@ -112,10 +121,11 @@ export function _appInitializerFactory(config: Config, injector: Injector) {
const auth = injector.get(AuthService);
try {
await auth.init();
- } catch (error) {
+ } catch {
statusElement.innerHTML = 'Authentifizierung wird durchgefรผhrt...';
const strategy = injector.get(LoginStrategy);
await strategy.login();
+ return;
}
statusElement.innerHTML = 'Native Container wird initialisiert...';
@@ -137,8 +147,11 @@ export function _appInitializerFactory(config: Config, injector: Injector) {
}
// Subscribe on Store changes and save to user storage
store.pipe(debounceTime(1000)).subscribe((state) => {
- userStorage.set('store', state);
+ userStorage.set('store', { ...state, version });
});
+
+ // Inject tab navigation service to initialize it
+ injector.get(TabNavigationService).init();
} catch (error) {
console.error('Error during app initialization', error);
laoderElement.remove();
@@ -185,6 +198,31 @@ export function _notificationsHubOptionsFactory(
return options;
}
+const USER_SUB_FACTORY = () => {
+ const _logger = logger(() => ({
+ context: 'USER_SUB',
+ }));
+ const auth = inject(OAuthService);
+
+ const claims = auth.getIdentityClaims();
+
+ if (!claims || typeof claims !== 'object' || !('sub' in claims)) {
+ const err = new Error('No valid identity claims found. User is anonymous.');
+ _logger.error(err.message);
+ throw err;
+ }
+
+ const validation = z.string().safeParse(claims['sub']);
+
+ if (!validation.success) {
+ const err = new Error('Invalid "sub" claim in identity claims.');
+ _logger.error(err.message, { claims });
+ throw err;
+ }
+
+ return signal(validation.data);
+};
+
@NgModule({
declarations: [AppComponent, MainComponent],
bootstrap: [AppComponent],
@@ -258,6 +296,7 @@ export function _notificationsHubOptionsFactory(
provide: DEFAULT_CURRENCY_CODE,
useValue: 'EUR',
},
+ provideUserSubFactory(USER_SUB_FACTORY),
],
})
export class AppModule {}
diff --git a/apps/isa-app/src/app/guards/can-activate-customer.guard.ts b/apps/isa-app/src/app/guards/can-activate-customer.guard.ts
index df44356ae..61235bae9 100644
--- a/apps/isa-app/src/app/guards/can-activate-customer.guard.ts
+++ b/apps/isa-app/src/app/guards/can-activate-customer.guard.ts
@@ -1,205 +1,206 @@
-import { Injectable } from "@angular/core";
-import {
- ActivatedRouteSnapshot,
- Router,
- RouterStateSnapshot,
-} from "@angular/router";
-import { ApplicationProcess, ApplicationService } from "@core/application";
-import { DomainCheckoutService } from "@domain/checkout";
-import { logger } from "@isa/core/logging";
-import { CustomerSearchNavigation } from "@shared/services/navigation";
-import { first } from "rxjs/operators";
-
-@Injectable({ providedIn: "root" })
-export class CanActivateCustomerGuard {
- #logger = logger(() => ({
- context: "CanActivateCustomerGuard",
- tags: ["guard", "customer", "navigation"],
- }));
-
- constructor(
- private readonly _applicationService: ApplicationService,
- private readonly _checkoutService: DomainCheckoutService,
- private readonly _router: Router,
- private readonly _navigation: CustomerSearchNavigation,
- ) {}
-
- async canActivate(
- route: ActivatedRouteSnapshot,
- { url }: RouterStateSnapshot,
- ) {
- if (url.startsWith("/kunde/customer/search/")) {
- const processId = Date.now(); // Generate a new process ID
- // Extract parts before and after the pattern
- const parts = url.split("/kunde/customer/");
- if (parts.length === 2) {
- const prefix = parts[0] + "/kunde/";
- const suffix = "customer/" + parts[1];
-
- // Construct the new URL with process ID inserted
- const newUrl = `${prefix}${processId}/${suffix}`;
-
- this.#logger.info("Redirecting to URL with process ID", () => ({
- originalUrl: url,
- newUrl,
- processId,
- }));
-
- // Navigate to the new URL and prevent original navigation
- this._router.navigateByUrl(newUrl);
- return false;
- }
- }
-
- const processes = await this._applicationService
- .getProcesses$("customer")
- .pipe(first())
- .toPromise();
- const lastActivatedProcessId = (
- await this._applicationService
- .getLastActivatedProcessWithSectionAndType$("customer", "cart")
- .pipe(first())
- .toPromise()
- )?.id;
-
- const lastActivatedCartCheckoutProcessId = (
- await this._applicationService
- .getLastActivatedProcessWithSectionAndType$("customer", "cart-checkout")
- .pipe(first())
- .toPromise()
- )?.id;
-
- const lastActivatedGoodsOutProcessId = (
- await this._applicationService
- .getLastActivatedProcessWithSectionAndType$("customer", "goods-out")
- .pipe(first())
- .toPromise()
- )?.id;
-
- const activatedProcessId = await this._applicationService
- .getActivatedProcessId$()
- .pipe(first())
- .toPromise();
-
- // Darf nur reinkommen wenn der aktuell aktive Tab ein Bestellabschluss Tab ist
- if (
- !!lastActivatedCartCheckoutProcessId &&
- lastActivatedCartCheckoutProcessId === activatedProcessId
- ) {
- await this.fromCartCheckoutProcess(
- processes,
- lastActivatedCartCheckoutProcessId,
- );
- return false;
- } else if (
- !!lastActivatedGoodsOutProcessId &&
- lastActivatedGoodsOutProcessId === activatedProcessId
- ) {
- await this.fromGoodsOutProcess(processes, lastActivatedGoodsOutProcessId);
- return false;
- }
-
- if (!lastActivatedProcessId) {
- await this.fromCartProcess(processes);
- return false;
- } else {
- await this.navigateToDefaultRoute(lastActivatedProcessId);
- }
- return false;
- }
-
- async navigateToDefaultRoute(processId: number) {
- const route = this._navigation.defaultRoute({ processId });
-
- await this._router.navigate(route.path, { queryParams: route.queryParams });
- }
-
- // Bei offener Artikelsuche/Kundensuche und Klick auf Footer Kundensuche
- async fromCartProcess(processes: ApplicationProcess[]) {
- const newProcessId = Date.now();
- await this._applicationService.createProcess({
- id: newProcessId,
- type: "cart",
- section: "customer",
- name: `Vorgang ${this.processNumber(processes.filter((process) => process.type === "cart"))}`,
- });
-
- await this.navigateToDefaultRoute(newProcessId);
- }
-
- // Bei offener Bestellbestรคtigung und Klick auf Footer Kundensuche
- async fromCartCheckoutProcess(
- processes: ApplicationProcess[],
- processId: number,
- ) {
- // Um alle Checkout Daten zu resetten die mit dem Prozess assoziiert sind
- this._checkoutService.removeProcess({ processId });
-
- // รndere type cart-checkout zu cart
- this._applicationService.patchProcess(processId, {
- id: processId,
- type: "cart",
- section: "customer",
- name: `Vorgang ${this.processNumber(processes.filter((process) => process.type === "cart"))}`,
- data: {},
- });
-
- // Navigation
- await this.navigateToDefaultRoute(processId);
- }
-
- // Bei offener Warenausgabe und Klick auf Footer Kundensuche
- async fromGoodsOutProcess(
- processes: ApplicationProcess[],
- processId: number,
- ) {
- const buyer = await this._checkoutService
- .getBuyer({ processId })
- .pipe(first())
- .toPromise();
- const customerFeatures = await this._checkoutService
- .getCustomerFeatures({ processId })
- .pipe(first())
- .toPromise();
- const name = buyer
- ? customerFeatures?.b2b
- ? buyer.organisation?.name
- ? buyer.organisation?.name
- : buyer.lastName
- : buyer.lastName
- : `Vorgang ${this.processNumber(processes.filter((process) => process.type === "cart"))}`;
-
- // รndere type goods-out zu cart
- this._applicationService.patchProcess(processId, {
- id: processId,
- type: "cart",
- section: "customer",
- name,
- });
-
- // Navigation
- await this.navigateToDefaultRoute(processId);
- }
-
- processNumber(processes: ApplicationProcess[]) {
- const processNumbers = processes?.map((process) =>
- Number(process?.name?.replace(/\D/g, "")),
- );
- return !!processNumbers && processNumbers.length > 0
- ? this.findMissingNumber(processNumbers)
- : 1;
- }
-
- findMissingNumber(processNumbers: number[]) {
- for (
- let missingNumber = 1;
- missingNumber < Math.max(...processNumbers);
- missingNumber++
- ) {
- if (!processNumbers.find((number) => number === missingNumber)) {
- return missingNumber;
- }
- }
- return Math.max(...processNumbers) + 1;
- }
-}
+import { Injectable } from '@angular/core';
+import {
+ ActivatedRouteSnapshot,
+ Router,
+ RouterStateSnapshot,
+} from '@angular/router';
+import { ApplicationProcess, ApplicationService } from '@core/application';
+import { DomainCheckoutService } from '@domain/checkout';
+import { logger } from '@isa/core/logging';
+import { CustomerSearchNavigation } from '@shared/services/navigation';
+import { first } from 'rxjs/operators';
+
+@Injectable({ providedIn: 'root' })
+export class CanActivateCustomerGuard {
+ #logger = logger(() => ({
+ module: 'isa-app',
+ importMetaUrl: import.meta.url,
+ class: 'CanActivateCustomerGuard',
+ }));
+
+ constructor(
+ private readonly _applicationService: ApplicationService,
+ private readonly _checkoutService: DomainCheckoutService,
+ private readonly _router: Router,
+ private readonly _navigation: CustomerSearchNavigation,
+ ) {}
+
+ async canActivate(
+ route: ActivatedRouteSnapshot,
+ { url }: RouterStateSnapshot,
+ ) {
+ if (url.startsWith('/kunde/customer/search/')) {
+ const processId = Date.now(); // Generate a new process ID
+ // Extract parts before and after the pattern
+ const parts = url.split('/kunde/customer/');
+ if (parts.length === 2) {
+ const prefix = parts[0] + '/kunde/';
+ const suffix = 'customer/' + parts[1];
+
+ // Construct the new URL with process ID inserted
+ const newUrl = `${prefix}${processId}/${suffix}`;
+
+ this.#logger.info('Redirecting to URL with process ID', () => ({
+ originalUrl: url,
+ newUrl,
+ processId,
+ }));
+
+ // Navigate to the new URL and prevent original navigation
+ this._router.navigateByUrl(newUrl);
+ return false;
+ }
+ }
+
+ const processes = await this._applicationService
+ .getProcesses$('customer')
+ .pipe(first())
+ .toPromise();
+ const lastActivatedProcessId = (
+ await this._applicationService
+ .getLastActivatedProcessWithSectionAndType$('customer', 'cart')
+ .pipe(first())
+ .toPromise()
+ )?.id;
+
+ const lastActivatedCartCheckoutProcessId = (
+ await this._applicationService
+ .getLastActivatedProcessWithSectionAndType$('customer', 'cart-checkout')
+ .pipe(first())
+ .toPromise()
+ )?.id;
+
+ const lastActivatedGoodsOutProcessId = (
+ await this._applicationService
+ .getLastActivatedProcessWithSectionAndType$('customer', 'goods-out')
+ .pipe(first())
+ .toPromise()
+ )?.id;
+
+ const activatedProcessId = await this._applicationService
+ .getActivatedProcessId$()
+ .pipe(first())
+ .toPromise();
+
+ // Darf nur reinkommen wenn der aktuell aktive Tab ein Bestellabschluss Tab ist
+ if (
+ !!lastActivatedCartCheckoutProcessId &&
+ lastActivatedCartCheckoutProcessId === activatedProcessId
+ ) {
+ await this.fromCartCheckoutProcess(
+ processes,
+ lastActivatedCartCheckoutProcessId,
+ );
+ return false;
+ } else if (
+ !!lastActivatedGoodsOutProcessId &&
+ lastActivatedGoodsOutProcessId === activatedProcessId
+ ) {
+ await this.fromGoodsOutProcess(processes, lastActivatedGoodsOutProcessId);
+ return false;
+ }
+
+ if (!lastActivatedProcessId) {
+ await this.fromCartProcess(processes);
+ return false;
+ } else {
+ await this.navigateToDefaultRoute(lastActivatedProcessId);
+ }
+ return false;
+ }
+
+ async navigateToDefaultRoute(processId: number) {
+ const route = this._navigation.defaultRoute({ processId });
+
+ await this._router.navigate(route.path, { queryParams: route.queryParams });
+ }
+
+ // Bei offener Artikelsuche/Kundensuche und Klick auf Footer Kundensuche
+ async fromCartProcess(processes: ApplicationProcess[]) {
+ const newProcessId = Date.now();
+ await this._applicationService.createProcess({
+ id: newProcessId,
+ type: 'cart',
+ section: 'customer',
+ name: `Vorgang ${this.processNumber(processes.filter((process) => process.type === 'cart'))}`,
+ });
+
+ await this.navigateToDefaultRoute(newProcessId);
+ }
+
+ // Bei offener Bestellbestรคtigung und Klick auf Footer Kundensuche
+ async fromCartCheckoutProcess(
+ processes: ApplicationProcess[],
+ processId: number,
+ ) {
+ // Um alle Checkout Daten zu resetten die mit dem Prozess assoziiert sind
+ this._checkoutService.removeProcess({ processId });
+
+ // รndere type cart-checkout zu cart
+ this._applicationService.patchProcess(processId, {
+ id: processId,
+ type: 'cart',
+ section: 'customer',
+ name: `Vorgang ${this.processNumber(processes.filter((process) => process.type === 'cart'))}`,
+ data: {},
+ });
+
+ // Navigation
+ await this.navigateToDefaultRoute(processId);
+ }
+
+ // Bei offener Warenausgabe und Klick auf Footer Kundensuche
+ async fromGoodsOutProcess(
+ processes: ApplicationProcess[],
+ processId: number,
+ ) {
+ const buyer = await this._checkoutService
+ .getBuyer({ processId })
+ .pipe(first())
+ .toPromise();
+ const customerFeatures = await this._checkoutService
+ .getCustomerFeatures({ processId })
+ .pipe(first())
+ .toPromise();
+ const name = buyer
+ ? customerFeatures?.b2b
+ ? buyer.organisation?.name
+ ? buyer.organisation?.name
+ : buyer.lastName
+ : buyer.lastName
+ : `Vorgang ${this.processNumber(processes.filter((process) => process.type === 'cart'))}`;
+
+ // รndere type goods-out zu cart
+ this._applicationService.patchProcess(processId, {
+ id: processId,
+ type: 'cart',
+ section: 'customer',
+ name,
+ });
+
+ // Navigation
+ await this.navigateToDefaultRoute(processId);
+ }
+
+ processNumber(processes: ApplicationProcess[]) {
+ const processNumbers = processes?.map((process) =>
+ Number(process?.name?.replace(/\D/g, '')),
+ );
+ return !!processNumbers && processNumbers.length > 0
+ ? this.findMissingNumber(processNumbers)
+ : 1;
+ }
+
+ findMissingNumber(processNumbers: number[]) {
+ for (
+ let missingNumber = 1;
+ missingNumber < Math.max(...processNumbers);
+ missingNumber++
+ ) {
+ if (!processNumbers.find((number) => number === missingNumber)) {
+ return missingNumber;
+ }
+ }
+ return Math.max(...processNumbers) + 1;
+ }
+}
diff --git a/apps/isa-app/src/app/interceptors/http-error.interceptor.ts b/apps/isa-app/src/app/interceptors/http-error.interceptor.ts
index 71ef22f2c..8c2b40cf8 100644
--- a/apps/isa-app/src/app/interceptors/http-error.interceptor.ts
+++ b/apps/isa-app/src/app/interceptors/http-error.interceptor.ts
@@ -1,42 +1,50 @@
-import { inject, Injectable, Injector } from '@angular/core';
-import { HttpInterceptor, HttpEvent, HttpHandler, HttpRequest, HttpErrorResponse } from '@angular/common/http';
-import { from, NEVER, Observable, throwError } from 'rxjs';
-import { UiMessageModalComponent, UiModalService } from '@ui/modal';
-import { catchError, filter, mergeMap, takeUntil, tap } from 'rxjs/operators';
-import { AuthService, LoginStrategy } from '@core/auth';
-import { IsaLogProvider } from '../providers';
-import { LogLevel } from '@core/logger';
-import { injectOnline$ } from '../services/network-status.service';
-
-@Injectable()
-export class HttpErrorInterceptor implements HttpInterceptor {
- readonly offline$ = injectOnline$().pipe(filter((online) => !online));
- readonly injector = inject(Injector);
-
- constructor(
- private _modal: UiModalService,
- private _auth: AuthService,
- private _isaLogProvider: IsaLogProvider,
- ) {}
-
- intercept(req: HttpRequest, next: HttpHandler): Observable> {
- return next.handle(req).pipe(
- takeUntil(this.offline$),
- catchError((error: HttpErrorResponse, caught: any) => this.handleError(error)),
- );
- }
-
- handleError(error: HttpErrorResponse): Observable {
- if (error.status === 401) {
- const strategy = this.injector.get(LoginStrategy);
-
- return from(strategy.login('Sie sind nicht mehr angemeldet')).pipe(mergeMap(() => NEVER));
- }
-
- if (!error.url.endsWith('/isa/logging')) {
- this._isaLogProvider.log(LogLevel.ERROR, 'Http Error', error);
- }
-
- return throwError(error);
- }
-}
+import { inject, Injectable, Injector } from '@angular/core';
+import {
+ HttpInterceptor,
+ HttpEvent,
+ HttpHandler,
+ HttpRequest,
+ HttpErrorResponse,
+} from '@angular/common/http';
+import { from, NEVER, Observable, throwError } from 'rxjs';
+import { catchError, filter, mergeMap, takeUntil } from 'rxjs/operators';
+import { LoginStrategy } from '@core/auth';
+import { IsaLogProvider } from '../providers';
+import { LogLevel } from '@core/logger';
+import { injectOnline$ } from '../services/network-status.service';
+
+@Injectable()
+export class HttpErrorInterceptor implements HttpInterceptor {
+ readonly offline$ = injectOnline$().pipe(filter((online) => !online));
+ readonly injector = inject(Injector);
+
+ constructor(private _isaLogProvider: IsaLogProvider) {}
+
+ intercept(
+ req: HttpRequest,
+ next: HttpHandler,
+ ): Observable> {
+ return next.handle(req).pipe(
+ takeUntil(this.offline$),
+ catchError((error: HttpErrorResponse, caught: any) =>
+ this.handleError(error),
+ ),
+ );
+ }
+
+ handleError(error: HttpErrorResponse): Observable {
+ if (error.status === 401) {
+ const strategy = this.injector.get(LoginStrategy);
+
+ return from(strategy.login('Sie sind nicht mehr angemeldet')).pipe(
+ mergeMap(() => NEVER),
+ );
+ }
+
+ if (!error.url.endsWith('/isa/logging')) {
+ this._isaLogProvider.log(LogLevel.ERROR, 'Http Error', error);
+ }
+
+ return throwError(error);
+ }
+}
diff --git a/apps/isa-app/src/core/application/application.service-adapter.ts b/apps/isa-app/src/core/application/application.service-adapter.ts
index 6e25b5d96..7966583d8 100644
--- a/apps/isa-app/src/core/application/application.service-adapter.ts
+++ b/apps/isa-app/src/core/application/application.service-adapter.ts
@@ -142,7 +142,6 @@ export class ApplicationServiceAdapter extends ApplicationService {
patchProcessData(processId: number, data: Record): void {
const currentProcess = this.#tabService.entityMap()[processId];
-
const currentData: TabMetadata =
(currentProcess?.metadata?.['process_data'] as TabMetadata) ?? {};
diff --git a/apps/isa-app/src/core/auth/auth.service.ts b/apps/isa-app/src/core/auth/auth.service.ts
index c801b8b49..f8a1f7291 100644
--- a/apps/isa-app/src/core/auth/auth.service.ts
+++ b/apps/isa-app/src/core/auth/auth.service.ts
@@ -1,174 +1,178 @@
-import { coerceArray } from "@angular/cdk/coercion";
-import { inject, Injectable } from "@angular/core";
-import { Config } from "@core/config";
-import { isNullOrUndefined } from "@utils/common";
-import { AuthConfig, OAuthService } from "angular-oauth2-oidc";
-import { JwksValidationHandler } from "angular-oauth2-oidc-jwks";
-import { BehaviorSubject } from "rxjs";
-
-/**
- * Storage key for the URL to redirect to after login
- */
-const REDIRECT_URL_KEY = "auth_redirect_url";
-
-@Injectable({
- providedIn: "root",
-})
-export class AuthService {
- private readonly _initialized = new BehaviorSubject(false);
- get initialized$() {
- return this._initialized.asObservable();
- }
-
- private _authConfig: AuthConfig;
- constructor(
- private _config: Config,
- private readonly _oAuthService: OAuthService,
- ) {
- this._oAuthService.events?.subscribe((event) => {
- if (event.type === "token_received") {
- console.log(
- "SSO Token Expiration:",
- new Date(this._oAuthService.getAccessTokenExpiration()),
- );
-
- // Handle redirect after successful authentication
- setTimeout(() => {
- const redirectUrl = this._getAndClearRedirectUrl();
- if (redirectUrl) {
- window.location.href = redirectUrl;
- }
- }, 100);
- }
- });
- }
-
- async init() {
- if (this._initialized.getValue()) {
- throw new Error("AuthService is already initialized");
- }
-
- this._authConfig = this._config.get("@core/auth");
-
- this._authConfig.redirectUri = window.location.origin;
-
- this._authConfig.silentRefreshRedirectUri =
- window.location.origin + "/silent-refresh.html";
- this._authConfig.useSilentRefresh = true;
-
- this._oAuthService.configure(this._authConfig);
- this._oAuthService.tokenValidationHandler = new JwksValidationHandler();
-
- this._oAuthService.setupAutomaticSilentRefresh();
-
- await this._oAuthService.loadDiscoveryDocumentAndTryLogin();
-
- this._initialized.next(true);
- }
-
- isAuthenticated() {
- return this.isIdTokenValid();
- }
-
- isIdTokenValid() {
- console.log(
- "ID Token Expiration:",
- new Date(this._oAuthService.getIdTokenExpiration()),
- );
- return this._oAuthService.hasValidIdToken();
- }
-
- isAccessTokenValid() {
- console.log(
- "ACCESS Token Expiration:",
- new Date(this._oAuthService.getAccessTokenExpiration()),
- );
- return this._oAuthService.hasValidAccessToken();
- }
-
- getToken() {
- return this._oAuthService.getAccessToken();
- }
-
- getClaims() {
- const token = this._oAuthService.getAccessToken();
- return this.parseJwt(token);
- }
-
- getClaimByKey(key: string) {
- const claims = this.getClaims();
- if (isNullOrUndefined(claims)) {
- return null;
- }
- return claims[key];
- }
-
- parseJwt(token: string) {
- if (isNullOrUndefined(token)) {
- return null;
- }
- const base64Url = token.split(".")[1];
- const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
-
- const encoded = window.atob(base64);
- return JSON.parse(encoded);
- }
-
- /**
- * Saves the URL to redirect to after successful login
- */
- _saveRedirectUrl(): void {
- localStorage.setItem(REDIRECT_URL_KEY, window.location.href);
- }
-
- /**
- * Gets and clears the saved redirect URL
- */
- _getAndClearRedirectUrl(): string | null {
- const url = localStorage.getItem(REDIRECT_URL_KEY);
- localStorage.removeItem(REDIRECT_URL_KEY);
- return url;
- }
-
- login() {
- this._saveRedirectUrl();
- this._oAuthService.initLoginFlow();
- }
-
- setKeyCardToken(token: string) {
- this._oAuthService.customQueryParams = {
- temp_token: token,
- };
- }
-
- async logout() {
- await this._oAuthService.revokeTokenAndLogout();
- }
-
- hasRole(role: string | string[]) {
- const roles = coerceArray(role);
-
- const userRoles = this.getClaimByKey("role");
-
- if (isNullOrUndefined(userRoles)) {
- return false;
- }
-
- return roles.every((r) => userRoles.includes(r));
- }
-
- async refresh() {
- try {
- if (
- this._authConfig.responseType.includes("code") &&
- this._authConfig.scope.includes("offline_access")
- ) {
- await this._oAuthService.refreshToken();
- } else {
- await this._oAuthService.silentRefresh();
- }
- } catch (error) {
- console.error(error);
- }
- }
-}
+import { coerceArray } from '@angular/cdk/coercion';
+import { inject, Injectable } from '@angular/core';
+import { Config } from '@core/config';
+import { isNullOrUndefined } from '@utils/common';
+import { AuthConfig, OAuthService } from 'angular-oauth2-oidc';
+import { JwksValidationHandler } from 'angular-oauth2-oidc-jwks';
+import { BehaviorSubject } from 'rxjs';
+
+/**
+ * Storage key for the URL to redirect to after login
+ */
+const REDIRECT_URL_KEY = 'auth_redirect_url';
+
+@Injectable({
+ providedIn: 'root',
+})
+export class AuthService {
+ private readonly _initialized = new BehaviorSubject(false);
+ get initialized$() {
+ return this._initialized.asObservable();
+ }
+
+ private _authConfig: AuthConfig;
+ constructor(
+ private _config: Config,
+ private readonly _oAuthService: OAuthService,
+ ) {
+ this._oAuthService.events?.subscribe((event) => {
+ if (event.type === 'token_received') {
+ console.log(
+ 'SSO Token Expiration:',
+ new Date(this._oAuthService.getAccessTokenExpiration()),
+ );
+
+ // Handle redirect after successful authentication
+ setTimeout(() => {
+ const redirectUrl = this._getAndClearRedirectUrl();
+ if (redirectUrl) {
+ window.location.href = redirectUrl;
+ }
+ }, 100);
+ }
+ });
+ }
+
+ async init() {
+ if (this._initialized.getValue()) {
+ throw new Error('AuthService is already initialized');
+ }
+
+ this._authConfig = this._config.get('@core/auth');
+
+ this._authConfig.redirectUri = window.location.origin;
+
+ this._authConfig.silentRefreshRedirectUri =
+ window.location.origin + '/silent-refresh.html';
+ this._authConfig.useSilentRefresh = true;
+
+ this._oAuthService.configure(this._authConfig);
+ this._oAuthService.tokenValidationHandler = new JwksValidationHandler();
+
+ this._oAuthService.setupAutomaticSilentRefresh();
+
+ await this._oAuthService.loadDiscoveryDocumentAndTryLogin();
+
+ if (!this._oAuthService.getAccessToken()) {
+ throw new Error('No access token. User is not authenticated.');
+ }
+
+ this._initialized.next(true);
+ }
+
+ isAuthenticated() {
+ return this.isIdTokenValid();
+ }
+
+ isIdTokenValid() {
+ console.log(
+ 'ID Token Expiration:',
+ new Date(this._oAuthService.getIdTokenExpiration()),
+ );
+ return this._oAuthService.hasValidIdToken();
+ }
+
+ isAccessTokenValid() {
+ console.log(
+ 'ACCESS Token Expiration:',
+ new Date(this._oAuthService.getAccessTokenExpiration()),
+ );
+ return this._oAuthService.hasValidAccessToken();
+ }
+
+ getToken() {
+ return this._oAuthService.getAccessToken();
+ }
+
+ getClaims() {
+ const token = this._oAuthService.getAccessToken();
+ return this.parseJwt(token);
+ }
+
+ getClaimByKey(key: string) {
+ const claims = this.getClaims();
+ if (isNullOrUndefined(claims)) {
+ return null;
+ }
+ return claims[key];
+ }
+
+ parseJwt(token: string) {
+ if (isNullOrUndefined(token)) {
+ return null;
+ }
+ const base64Url = token.split('.')[1];
+ const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
+
+ const encoded = window.atob(base64);
+ return JSON.parse(encoded);
+ }
+
+ /**
+ * Saves the URL to redirect to after successful login
+ */
+ _saveRedirectUrl(): void {
+ localStorage.setItem(REDIRECT_URL_KEY, window.location.href);
+ }
+
+ /**
+ * Gets and clears the saved redirect URL
+ */
+ _getAndClearRedirectUrl(): string | null {
+ const url = localStorage.getItem(REDIRECT_URL_KEY);
+ localStorage.removeItem(REDIRECT_URL_KEY);
+ return url;
+ }
+
+ login() {
+ this._saveRedirectUrl();
+ this._oAuthService.initLoginFlow();
+ }
+
+ setKeyCardToken(token: string) {
+ this._oAuthService.customQueryParams = {
+ temp_token: token,
+ };
+ }
+
+ async logout() {
+ await this._oAuthService.revokeTokenAndLogout();
+ }
+
+ hasRole(role: string | string[]) {
+ const roles = coerceArray(role);
+
+ const userRoles = this.getClaimByKey('role');
+
+ if (isNullOrUndefined(userRoles)) {
+ return false;
+ }
+
+ return roles.every((r) => userRoles.includes(r));
+ }
+
+ async refresh() {
+ try {
+ if (
+ this._authConfig.responseType.includes('code') &&
+ this._authConfig.scope.includes('offline_access')
+ ) {
+ await this._oAuthService.refreshToken();
+ } else {
+ await this._oAuthService.silentRefresh();
+ }
+ } catch (error) {
+ console.error(error);
+ }
+ }
+}
diff --git a/apps/isa-app/src/domain/checkout/checkout.service.ts b/apps/isa-app/src/domain/checkout/checkout.service.ts
index dfd6be3c0..b87bbeed5 100644
--- a/apps/isa-app/src/domain/checkout/checkout.service.ts
+++ b/apps/isa-app/src/domain/checkout/checkout.service.ts
@@ -1,1249 +1,1639 @@
-import { Injectable } from '@angular/core';
-import { Store } from '@ngrx/store';
-import {
- AddToShoppingCartDTO,
- AvailabilityDTO,
- BranchDTO,
- BuyerDTO,
- BuyerResult,
- CheckoutDTO,
- CommunicationDetailsDTO,
- DestinationDTO,
- NotificationChannel,
- OLAAvailabilityDTO,
- PayerDTO,
- PaymentDTO,
- PaymentType,
- ResponseArgsOfDestinationDTO,
- ShippingAddressDTO,
- ShoppingCartDTO,
- StoreCheckoutService,
- UpdateShoppingCartItemDTO,
- InputDTO,
- ItemPayload,
- StoreCheckoutShoppingCartService,
- StoreCheckoutPaymentService,
- StoreCheckoutBuyerService,
- StoreCheckoutPayerService,
- StoreCheckoutBranchService,
- ItemsResult,
- KulturPassService,
- ProductDTO,
- KulturPassResult,
-} from '@generated/swagger/checkout-api';
-import {
- DisplayOrderDTO,
- DisplayOrderItemDTO,
- OrderCheckoutService,
- ReorderValues,
- ResponseArgsOfValueTupleOfIEnumerableOfDisplayOrderDTOAndIEnumerableOfKeyValueDTOOfStringAndString,
-} from '@generated/swagger/oms-api';
-import { isNullOrUndefined, memorize } from '@utils/common';
-import { combineLatest, Observable, of, concat, isObservable, throwError, interval as rxjsInterval } from 'rxjs';
-import {
- bufferCount,
- catchError,
- distinctUntilChanged,
- filter,
- first,
- map,
- mergeMap,
- shareReplay,
- switchMap,
- tap,
- withLatestFrom,
- startWith,
-} from 'rxjs/operators';
-
-import * as DomainCheckoutSelectors from './store/domain-checkout.selectors';
-import * as DomainCheckoutActions from './store/domain-checkout.actions';
-import { DomainAvailabilityService, ItemData } from '@domain/availability';
-import { HttpErrorResponse } from '@angular/common/http';
-import { ApplicationService } from '@core/application';
-import { CustomerDTO } from '@generated/swagger/crm-api';
-import { Config } from '@core/config';
-import parseDuration from 'parse-duration';
-
-@Injectable()
-export class DomainCheckoutService {
- get olaExpiration() {
- const exp = this._config.get('@domain/checkout.olaExpiration') ?? '5m';
- return parseDuration(exp);
- }
-
- constructor(
- private store: Store,
- private _config: Config,
- private applicationService: ApplicationService,
- private storeCheckoutService: StoreCheckoutService,
- private orderCheckoutService: OrderCheckoutService,
- private availabilityService: DomainAvailabilityService,
- private _shoppingCartService: StoreCheckoutShoppingCartService,
- private _paymentService: StoreCheckoutPaymentService,
- private _buyerService: StoreCheckoutBuyerService,
- private _payerService: StoreCheckoutPayerService,
- private _branchService: StoreCheckoutBranchService,
- private _kulturpassService: KulturPassService,
- ) {}
-
- //#region shoppingcart
- @memorize()
- getShoppingCart({ processId, latest }: { processId: number; latest?: boolean }): Observable {
- let _latest = latest;
- return this.store.select(DomainCheckoutSelectors.selectShoppingCartByProcessId, { processId }).pipe(
- filter((cart) => {
- if (isNullOrUndefined(cart)) {
- console.log('createShoppingCart', processId);
- this.createShoppingCart({ processId }).subscribe();
- return false;
- } else if (cart && _latest) {
- _latest = false;
- this._shoppingCartService
- .StoreCheckoutShoppingCartGetShoppingCart({
- shoppingCartId: cart.id,
- })
- .pipe(
- map((response) => response.result),
- tap((shoppingCart) =>
- this.store.dispatch(
- DomainCheckoutActions.setShoppingCart({
- processId,
- shoppingCart,
- }),
- ),
- ),
- )
- .subscribe();
- return false;
- }
- return true;
- }),
- );
- }
-
- createShoppingCart({ processId }: { processId: number }): Observable {
- return this._shoppingCartService.StoreCheckoutShoppingCartCreateShoppingCart().pipe(
- map((response) => response.result),
- tap((shoppingCart) =>
- this.store.dispatch(
- DomainCheckoutActions.setShoppingCart({
- processId,
- shoppingCart,
- }),
- ),
- ),
- );
- }
-
- addItemToShoppingCart({
- processId,
- items,
- }: {
- processId: number;
- items: AddToShoppingCartDTO[];
- }): Observable {
- return this.getShoppingCart({ processId }).pipe(
- first(),
- mergeMap((cart) =>
- this._shoppingCartService
- .StoreCheckoutShoppingCartAddItemToShoppingCart({
- items,
- shoppingCartId: cart.id,
- })
- .pipe(
- map((response) => response.result),
- tap((shoppingCart) => {
- this.store.dispatch(
- DomainCheckoutActions.setShoppingCart({
- processId,
- shoppingCart,
- }),
- );
- }),
- tap((shoppingCart) => this.updateProcessCount(processId, shoppingCart?.items?.length)),
- ),
- ),
- );
- }
-
- setDestinationForCustomer({
- processId,
- customerFeatures,
- }: {
- processId: number;
- customerFeatures: { [key: string]: string };
- }): Observable {
- return this.getShoppingCart({ processId }).pipe(
- first(),
- mergeMap((shoppingCart) =>
- this._shoppingCartService
- .StoreCheckoutShoppingCartSetLogisticianOnDestinationsByBuyer({
- shoppingCartId: shoppingCart?.id,
- payload: { customerFeatures },
- })
- .pipe(map((response) => response.result)),
- ),
- );
- }
-
- canAddDestination({ processId, destinationDTO }: { processId: number; destinationDTO: DestinationDTO }) {
- return this.getShoppingCart({ processId }).pipe(
- first(),
- mergeMap((cart) =>
- this._shoppingCartService.StoreCheckoutShoppingCartCanAddDestination({
- shoppingCartId: cart.id,
- payload: destinationDTO,
- }),
- ),
- map((response) => {
- if (response.result?.ok) {
- return true;
- }
- return Object.values(response.invalidProperties).join('; ') || response.message;
- }),
- );
- }
-
- canAddItem({
- processId,
- availability,
- orderType,
- }: {
- processId: number;
- availability: OLAAvailabilityDTO;
- orderType: string;
- }): Observable {
- return this.getShoppingCart({ processId }).pipe(
- first(),
- withLatestFrom(this.store.select(DomainCheckoutSelectors.selectCustomerFeaturesByProcessId, { processId })),
- mergeMap(([shoppingCart, customerFeatures]) =>
- this._shoppingCartService
- .StoreCheckoutShoppingCartCanAddItem({
- shoppingCartId: shoppingCart?.id,
- payload: {
- customerFeatures,
- availabilities: [availability],
- orderType,
- },
- })
- .pipe(
- map((response) => {
- if (response.result.ok) {
- return true;
- }
- return response.message;
- }),
- ),
- ),
- );
- }
-
- canAddItemsKulturpass(payload: ProductDTO[]): Observable {
- return this._kulturpassService.KulturPassCanAddForKulturPass({ payload }).pipe(map((response) => response?.result));
- }
-
- canAddItems({
- processId,
- payload,
- orderType,
- }: {
- processId: number;
- payload: ItemPayload[];
- orderType: string;
- }): Observable {
- return this.getShoppingCart({ processId }).pipe(
- first(),
- withLatestFrom(this.store.select(DomainCheckoutSelectors.selectCustomerFeaturesByProcessId, { processId })),
- mergeMap(([shoppingCart, customerFeatures]) => {
- payload = payload?.map((p) => {
- return {
- ...p,
- customerFeatures,
- orderType,
- };
- });
- return this._shoppingCartService
- .StoreCheckoutShoppingCartCanAddItems({
- shoppingCartId: shoppingCart.id,
- payload,
- })
- .pipe(
- map((response) => {
- // TODO: remove this when the API is fixed
- return response.result as unknown as ItemsResult[];
- }),
- );
- }),
- );
- }
-
- updateShoppingCartItemAvailability({
- shoppingCartId,
- shoppingCartItemId,
- availability,
- }: {
- shoppingCartId: number;
- shoppingCartItemId: number;
- availability: AvailabilityDTO;
- }) {
- return this._shoppingCartService
- .StoreCheckoutShoppingCartUpdateShoppingCartItemAvailability({
- shoppingCartId,
- shoppingCartItemId,
- availability,
- })
- .pipe(
- map((response) => response.result),
- tap((shoppingCart) => {
- this.store.dispatch(
- DomainCheckoutActions.addShoppingCartItemAvailabilityToHistoryByShoppingCartId({
- shoppingCartId,
- availability,
- shoppingCartItemId,
- }),
- );
- }),
- );
- }
-
- updateItemInShoppingCart({
- processId,
- shoppingCartItemId,
- update,
- }: {
- processId: number;
- shoppingCartItemId: number;
- update: UpdateShoppingCartItemDTO;
- }): Observable {
- return this.getShoppingCart({ processId, latest: true }).pipe(
- first(),
- mergeMap((shoppingCart) =>
- this._shoppingCartService
- .StoreCheckoutShoppingCartUpdateShoppingCartItem({
- shoppingCartId: shoppingCart.id,
- shoppingCartItemId,
- values: update,
- })
- .pipe(
- map((response) => response.result),
- tap((shoppingCart) => {
- this.store.dispatch(DomainCheckoutActions.setShoppingCart({ processId, shoppingCart }));
-
- if (update.availability) {
- this.store.dispatch(
- DomainCheckoutActions.addShoppingCartItemAvailabilityToHistory({
- processId,
- availability: update.availability,
- shoppingCartItemId,
- }),
- );
- }
-
- this.updateProcessCount(processId, shoppingCart?.items?.length);
- }),
- ),
- ),
- );
- }
-
- //#endregion
-
- //#region Checkout
-
- getCheckout({ processId, refresh }: { processId: number; refresh?: boolean }): Observable {
- let _refresh = refresh;
- return this.store.select(DomainCheckoutSelectors.selectCheckoutByProcessId, { processId }).pipe(
- filter((checkout) => {
- if (isNullOrUndefined(checkout) || _refresh) {
- _refresh = false;
- this.createCheckout({ processId }).subscribe();
- return false;
- }
- return true;
- }),
- );
- }
-
- createCheckout({ processId }: { processId: number }) {
- return this.getShoppingCart({ processId }).pipe(
- first(),
- mergeMap((shoppingCart) =>
- this.storeCheckoutService
- .StoreCheckoutCreateOrRefreshCheckout({
- shoppingCartId: shoppingCart?.id,
- })
- .pipe(
- map((response) => response.result),
- tap((checkout) => this.store.dispatch(DomainCheckoutActions.setCheckout({ processId, checkout }))),
- ),
- ),
- );
- }
-
- /* @internal */
- _setNotificationChannels({
- processId,
- notificationChannels,
- }: {
- processId: number;
- notificationChannels: NotificationChannel;
- }): Observable {
- return this.getCheckout({ processId }).pipe(
- first(),
- mergeMap((checkout) =>
- this.storeCheckoutService
- .StoreCheckoutSetNotificationChannels({
- checkoutId: checkout.id,
- notificationChannel: notificationChannels,
- })
- .pipe(
- map((response) => response.result),
- tap((checkout) => this.store.dispatch(DomainCheckoutActions.setCheckout({ processId, checkout }))),
- ),
- ),
- );
- }
-
- getPayment({ processId }: { processId: number }): Observable {
- return this.getCheckout({ processId }).pipe(
- first(),
- mergeMap((checkout) =>
- this._paymentService
- .StoreCheckoutPaymentGetCheckoutPayment({
- checkoutId: checkout.id,
- })
- .pipe(map((response) => response.result)),
- ),
- );
- }
-
- getOlaErrors({ processId }: { processId: number }): Observable {
- return this.store.select(DomainCheckoutSelectors.selectOlaErrorsByProcessId, { processId });
- }
-
- setPayment({ processId, paymentType }: { processId: number; paymentType: PaymentType }): Observable {
- return this.getCheckout({ processId }).pipe(
- first(),
- mergeMap((checkout) =>
- this._paymentService
- .StoreCheckoutPaymentSetPaymentType({
- checkoutId: checkout?.id,
- paymentType,
- })
- .pipe(
- map((response) => response.result),
- tap((checkout) => this.store.dispatch(DomainCheckoutActions.setCheckout({ processId, checkout }))),
- ),
- ),
- );
- }
-
- _setBuyer({ processId, buyer }: { processId: number; buyer: BuyerDTO }): Observable {
- return this.getCheckout({ processId }).pipe(
- first(),
- mergeMap((checkout) => {
- console.log('checkout', checkout, processId);
- return this._buyerService
- .StoreCheckoutBuyerSetBuyerPOST({
- checkoutId: checkout?.id,
- buyerDTO: buyer,
- })
- .pipe(
- map((response) => response.result),
- tap((checkout) => this.store.dispatch(DomainCheckoutActions.setCheckout({ processId, checkout }))),
- );
- }),
- );
- }
-
- _setPayer({ processId, payer }: { processId: number; payer: PayerDTO }): Observable {
- return this.getCheckout({ processId }).pipe(
- first(),
- mergeMap((checkout) =>
- this._payerService
- .StoreCheckoutPayerSetPayerPOST({
- checkoutId: checkout?.id,
- payerDTO: payer,
- })
- .pipe(
- map((response) => response.result),
- tap((checkout) => this.store.dispatch(DomainCheckoutActions.setCheckout({ processId, checkout }))),
- ),
- ),
- );
- }
-
- setSpecialCommentOnItem({ processId, specialComment }: { processId: number; specialComment: string }) {
- const shoppingCart$ = this.getShoppingCart({ processId }).pipe(first());
-
- return shoppingCart$.pipe(
- mergeMap((cart) =>
- concat(
- ...cart.items.map((item) =>
- this._shoppingCartService.StoreCheckoutShoppingCartUpdateShoppingCartItem({
- shoppingCartId: cart.id,
- shoppingCartItemId: item.id,
- values: { specialComment },
- }),
- ),
- ).pipe(bufferCount(cart.items?.length)),
- ),
- );
- }
-
- checkAvailabilities({ processId }: { processId: number }): Observable {
- const shoppingCart$ = this.getShoppingCart({ processId }).pipe(first());
- const itemsToCheck$ = shoppingCart$.pipe(
- map((cart) =>
- cart?.items?.filter(
- (item) => item?.data?.features?.orderType === 'Download' && !item.data.availability.lastRequest,
- ),
- ),
- );
-
- return itemsToCheck$.pipe(
- withLatestFrom(shoppingCart$),
- switchMap(async ([items, cart]) => {
- const errorIds = [];
-
- for (const item of items) {
- const availability = await this.availabilityService
- .getDownloadAvailability({
- item: {
- ean: item.data.product.ean,
- itemId: Number(item.data.product.catalogProductNumber),
- price: item.data.availability.price,
- },
- })
- .toPromise();
-
- if (!availability || !this.availabilityService.isAvailable({ availability })) {
- errorIds.push(item.id);
- } else {
- await this.updateShoppingCartItemAvailability({
- shoppingCartId: cart.id,
- shoppingCartItemId: item.id,
- availability: {
- ...availability,
- lastRequest: new Date().toISOString(),
- },
- }).toPromise();
- }
- }
-
- this.setOlaErrors({ processId, errorIds });
-
- if (errorIds.length > 0) {
- throw throwError(new Error(`Artikel nicht verfรผgbar`));
- } else {
- return of(undefined);
- }
- }),
- );
- }
-
- updateAvailabilities({ processId }: { processId: number }): Observable {
- const shoppingCart$ = this.getShoppingCart({ processId }).pipe(first());
- const itemsToUpdate$ = shoppingCart$.pipe(
- map((cart) =>
- cart?.items?.filter(
- (item) =>
- item?.data?.features?.orderType === 'DIG-Versand' || item?.data?.features?.orderType === 'B2B-Versand',
- ),
- ),
- );
-
- return itemsToUpdate$.pipe(
- mergeMap((itemsToUpdate) => {
- if (!(itemsToUpdate?.length > 0)) {
- return of(undefined);
- }
-
- return concat(
- ...itemsToUpdate.map(async (itemToUpdate) => {
- const orderType = itemToUpdate?.data?.features?.orderType;
- let availability$: Observable;
- if (orderType === 'DIG-Versand') {
- availability$ = this.availabilityService.getDigDeliveryAvailability({
- item: {
- ean: itemToUpdate.data.product.ean,
- itemId: Number(itemToUpdate.data.product.catalogProductNumber),
- price: itemToUpdate.data.availability.price,
- },
- quantity: itemToUpdate.data.quantity,
- });
- } else if (orderType === 'B2B-Versand') {
- const branch = await this.applicationService.getSelectedBranch$(processId).pipe(first()).toPromise();
- availability$ = this.availabilityService.getB2bDeliveryAvailability({
- item: {
- ean: itemToUpdate.data.product.ean,
- itemId: Number(itemToUpdate.data.product.catalogProductNumber),
- price: itemToUpdate.data.availability.price,
- },
- quantity: itemToUpdate.data.quantity,
- branch,
- });
- }
-
- if (!isObservable(availability$)) {
- return of(undefined);
- }
-
- return availability$.pipe(
- mergeMap((availability) => {
- let updatedAvailability = availability;
- // Bei Preisupdate der Versandoptionen soll immer der Preis genommen werden, der im Warenkorb steht
- if (orderType === 'DIG-Versand' || orderType === 'B2B-Versand') {
- const itemPrice = itemToUpdate.data.availability.price;
- updatedAvailability = {
- ...availability,
- price: itemPrice,
- };
- }
- return this.updateItemInShoppingCart({
- processId,
- shoppingCartItemId: itemToUpdate.id,
- update: {
- availability: updatedAvailability,
- },
- });
- }),
- );
- }),
- ).pipe(bufferCount(itemsToUpdate.length));
- }),
- );
- }
-
- async refreshAvailability({
- processId,
- shoppingCartItemId,
- }: {
- processId: number;
- shoppingCartItemId: number;
- }): Promise {
- const shoppingCart = await this.getShoppingCart({ processId }).pipe(first()).toPromise();
- const item = shoppingCart?.items.find((item) => item.id === shoppingCartItemId)?.data;
-
- if (!item) {
- return;
- }
-
- const itemData: ItemData = {
- ean: item.product.ean,
- itemId: Number(item.product.catalogProductNumber),
- price: item.availability.price,
- };
-
- let availability: AvailabilityDTO;
-
- switch (item.features.orderType) {
- case 'Abholung':
- const abholung = await this.availabilityService
- .getPickUpAvailability({
- item: itemData,
- branch: item.destination?.data?.targetBranch?.data,
- quantity: item.quantity,
- })
- .toPromise();
- availability = abholung[0];
- break;
- case 'Rรผcklage':
- const ruecklage = await this.availabilityService
- .getTakeAwayAvailability({
- item: itemData,
- quantity: item.quantity,
- branch: item.destination?.data?.targetBranch?.data,
- })
- .toPromise();
- availability = ruecklage;
- break;
- case 'Download':
- const download = await this.availabilityService
- .getDownloadAvailability({
- item: itemData,
- })
- .toPromise();
-
- availability = download;
- break;
-
- case 'Versand':
- const versand = await this.availabilityService
- .getDeliveryAvailability({
- item: itemData,
- quantity: item.quantity,
- })
- .toPromise();
-
- availability = versand;
- break;
-
- case 'DIG-Versand':
- const digVersand = await this.availabilityService
- .getDigDeliveryAvailability({
- item: itemData,
- quantity: item.quantity,
- })
- .toPromise();
-
- availability = digVersand;
- break;
-
- case 'B2B-Versand':
- const b2bVersand = await this.availabilityService
- .getB2bDeliveryAvailability({
- item: itemData,
- quantity: item.quantity,
- })
- .toPromise();
-
- availability = b2bVersand;
- break;
- }
-
- await this.updateItemInShoppingCart({
- processId,
- update: { availability },
- shoppingCartItemId: item.id,
- }).toPromise();
-
- return availability;
- }
-
- /**
- * Check if the availability of all items is valid
- * @param param0 Process Id
- * @returns true if the availability of all items is valid
- */
- validateOlaStatus({ processId, interval }: { processId: number; interval?: number }): Observable {
- return rxjsInterval(interval ?? this.olaExpiration / 10).pipe(
- startWith(0),
- switchMap(() =>
- this.store.select(DomainCheckoutSelectors.selectCheckoutEntityByProcessId, { processId }).pipe(
- map((entity) => {
- const now = Date.now();
- if (!entity || !entity.shoppingCart || !entity.shoppingCart.items) {
- return;
- }
-
- const itemAvailabilityTimestamp = entity.itemAvailabilityTimestamp ?? {};
- const shoppingCart = entity.shoppingCart;
-
- const timestamps = shoppingCart.items
- ?.map((i) => i.data)
- ?.filter((item) => !!item?.features?.orderType)
- ?.map((item) => {
- const orderType = item.features.orderType;
-
- let timestamp = itemAvailabilityTimestamp[`${item.id}_${orderType}`];
-
- if (timestamp) {
- return timestamp;
- }
-
- if (orderType.endsWith('Versand')) {
- timestamp =
- itemAvailabilityTimestamp[`${item.id}_Versand`] ??
- itemAvailabilityTimestamp[`${item.id}_DIG-Versand`] ??
- itemAvailabilityTimestamp[`${item.id}_B2B-Versand`];
- }
-
- return timestamp;
- })
- ?.filter((timestamp) => !!timestamp);
-
- if (timestamps?.length > 0) {
- const oldestTimestamp = Math.min(...timestamps);
- const expirationTimestamp = oldestTimestamp + this.olaExpiration;
- return expirationTimestamp > now;
- }
-
- return false;
- }),
- ),
- ),
- distinctUntilChanged(),
- );
- }
-
- validateAvailabilities({ processId }: { processId: number }): Observable {
- return this.getShoppingCart({ processId }).pipe(
- map((shoppingCart) => {
- const items = shoppingCart?.items?.map((item) => item.data) || [];
- return items.every((i) => this.availabilityService.isAvailable({ availability: i.availability }));
- }),
- );
- }
-
- checkoutIsValid({ processId }: { processId: number }): Observable {
- const olaStatus$ = this.validateOlaStatus({ processId, interval: 250 });
-
- const availabilities$ = this.validateAvailabilities({ processId });
-
- return combineLatest([olaStatus$, availabilities$]).pipe(
- map(([olaStatus, availabilities]) => olaStatus && availabilities),
- );
- }
-
- completeCheckout({ processId }: { processId: number }): Observable {
- const refreshShoppingCart$ = this.getShoppingCart({ processId, latest: true }).pipe(first());
- const refreshCheckout$ = this.getCheckout({ processId, refresh: true }).pipe(first());
-
- const itemOrderOptions$ = this.getShoppingCart({ processId }).pipe(
- first(),
- map((shoppingCart) => {
- const shoppingCartItems = shoppingCart?.items?.map((item) => item.data) || [];
-
- const hasTakeAway = shoppingCartItems.some((item) => item.features.orderType === 'Rรผcklage');
- const hasPickUp = shoppingCartItems.some((item) => item.features.orderType === 'Abholung');
- const hasDownload = shoppingCartItems.some((item) => item.features.orderType === 'Download');
- const hasDelivery = shoppingCartItems.some((item) => item.features.orderType === 'Versand');
- const hasDigDelivery = shoppingCartItems.some((item) => item.features.orderType === 'DIG-Versand');
- const hasB2BDelivery = shoppingCartItems.some((item) => item.features.orderType === 'B2B-Versand');
-
- return {
- hasTakeAway,
- hasPickUp,
- hasDownload,
- hasDelivery,
- hasDigDelivery,
- hasB2BDelivery,
- };
- }),
- shareReplay(),
- );
-
- const customerTypes$ = this.getCustomerFeatures({ processId }).pipe(
- first(),
- map((features) => {
- const isOnline = !!features?.webshop;
- const isGuest = !!features?.guest;
- const isB2B = !!features?.b2b;
- const hasCustomerCard = !!features?.p4mUser;
- const isStaff = !!features?.staff;
-
- return { isOnline: isOnline, isGuest, isB2B, hasCustomerCard, isStaff };
- }),
- );
-
- const setSpecialComment$ = this.getSpecialComment({ processId }).pipe(
- first(),
- mergeMap((specialComment) => {
- if (specialComment) {
- return this.setSpecialCommentOnItem({ processId, specialComment });
- }
- return of(specialComment);
- }),
- );
-
- const shippingAddressDestination$ = this.getCheckout({ processId }).pipe(
- first(),
- map((checkout) => checkout?.destinations?.filter((dest) => dest.data.target === 2 || dest.data.target === 16)),
- shareReplay(),
- );
-
- const setBuyer$ = this.getBuyer({ processId }).pipe(
- first(),
- mergeMap((buyer) => this._setBuyer({ processId, buyer })),
- );
-
- const setNotificationChannels$ = this.getNotificationChannels({ processId }).pipe(
- first(),
- mergeMap((notificationChannels) => this._setNotificationChannels({ processId, notificationChannels })),
- );
-
- const setPayer$ = combineLatest([itemOrderOptions$, customerTypes$]).pipe(
- first(),
- mergeMap(([itemOrderOptions, customerTypes]) => {
- if (
- customerTypes.isB2B ||
- itemOrderOptions.hasB2BDelivery ||
- itemOrderOptions.hasDelivery ||
- itemOrderOptions.hasDigDelivery ||
- itemOrderOptions.hasDownload
- ) {
- return this.getPayer({ processId }).pipe(first());
- }
- return of(undefined);
- }),
- mergeMap((payer) => (payer ? this._setPayer({ processId, payer }) : of(undefined))),
- );
-
- const updateDestination$ = itemOrderOptions$.pipe(
- withLatestFrom(this.getCustomerFeatures({ processId })),
- mergeMap(([{ hasDownload, hasDelivery, hasDigDelivery, hasB2BDelivery }, customerFeatures]) => {
- const needsUpdate = hasDownload || hasDelivery || hasDigDelivery || hasB2BDelivery;
- return needsUpdate ? this.setDestinationForCustomer({ processId, customerFeatures }) : of(undefined);
- }),
- );
-
- const checkAvailabilities$ = this.checkAvailabilities({ processId });
-
- const updateAvailabilities$ = this.updateAvailabilities({ processId });
-
- const setPaymentType$ = itemOrderOptions$.pipe(
- mergeMap(({ hasDownload, hasDelivery, hasDigDelivery, hasB2BDelivery }) => {
- const paymentType =
- hasDownload || hasDelivery || hasDigDelivery || hasB2BDelivery ? 128 /* Rechnung */ : 4; /* Bar */
- return this.setPayment({ processId, paymentType });
- }),
- shareReplay(),
- );
-
- const setDestination$ = combineLatest([
- this.getCheckout({ processId }).pipe(first()),
- shippingAddressDestination$,
- this.getShippingAddress({ processId }).pipe(first()),
- ]).pipe(
- mergeMap(([checkout, destinations, shippingAddress]) => {
- const obs: Observable[] = [];
- if (destinations?.length > 0) {
- destinations.forEach((destination) => {
- const updatedDestination: DestinationDTO = { ...destination.data, shippingAddress: { ...shippingAddress } };
- obs.push(
- this.storeCheckoutService.StoreCheckoutUpdateDestination({
- checkoutId: checkout.id,
- destinationId: destination.id,
- destinationDTO: updatedDestination,
- }),
- );
- });
- return concat(...obs).pipe(bufferCount(destinations?.length));
- }
- return of(destinations);
- }),
- shareReplay(),
- );
-
- const completeOrder$ = this.getCheckout({ processId }).pipe(
- first(),
- mergeMap((checkout) =>
- this.orderCheckoutService
- .OrderCheckoutCreateOrderPOST({
- checkoutId: checkout.id,
- })
- .pipe(
- catchError((error) => {
- if (error instanceof HttpErrorResponse) {
- if (error.status === 409) {
- this.store.dispatch(DomainCheckoutActions.setOrders({ orders: error.error.result }));
- }
- return throwError(error);
- }
- }),
- map((response) => {
- this.store.dispatch(DomainCheckoutActions.setOrders({ orders: response.result }));
- return response.result;
- }),
- ),
- ),
- );
-
- return of(undefined)
- .pipe(
- mergeMap((_) => updateDestination$.pipe(tap(console.log.bind(window, 'updateDestination$')))),
- mergeMap((_) => refreshShoppingCart$.pipe(tap(console.log.bind(window, 'refreshShoppingCart$')))),
- mergeMap((_) => setSpecialComment$.pipe(tap(console.log.bind(window, 'setSpecialComment$')))),
- mergeMap((_) => refreshCheckout$.pipe(tap(console.log.bind(window, 'refreshCheckout$')))),
- mergeMap((_) => checkAvailabilities$.pipe(tap(console.log.bind(window, 'checkAvailabilities$')))),
- mergeMap((_) => updateAvailabilities$.pipe(tap(console.log.bind(window, 'updateAvailabilities$')))),
- )
- .pipe(
- mergeMap((_) => setBuyer$.pipe(tap(console.log.bind(window, 'setBuyer$')))),
- mergeMap((_) => setNotificationChannels$.pipe(tap(console.log.bind(window, 'setNotificationChannels$')))),
- mergeMap((_) => setPayer$.pipe(tap(console.log.bind(window, 'setPayer$')))),
- mergeMap((_) => setPaymentType$.pipe(tap(console.log.bind(window, 'setPaymentType$')))),
- mergeMap((_) => setDestination$.pipe(tap(console.log.bind(window, 'setDestination$')))),
- mergeMap((_) => completeOrder$.pipe(tap(console.log.bind(window, 'completeOrder$')))),
- );
- }
-
- completeKulturpassOrder({
- processId,
- orderItemSubsetId,
- }: {
- processId: number;
- orderItemSubsetId: number;
- }): Observable {
- const refreshShoppingCart$ = this.getShoppingCart({ processId, latest: true }).pipe(first());
- const refreshCheckout$ = this.getCheckout({ processId, refresh: true }).pipe(first());
-
- const setBuyer$ = this.getBuyer({ processId }).pipe(
- first(),
- mergeMap((buyer) => this._setBuyer({ processId, buyer })),
- );
-
- const setPayer$ = this.getPayer({ processId }).pipe(
- first(),
- mergeMap((payer) => this._setPayer({ processId, payer })),
- );
-
- const checkAvailabilities$ = this.checkAvailabilities({ processId });
-
- const updateAvailabilities$ = this.updateAvailabilities({ processId });
-
- return refreshShoppingCart$.pipe(
- mergeMap((_) => refreshCheckout$),
- mergeMap((_) => checkAvailabilities$),
- mergeMap((_) => updateAvailabilities$),
- mergeMap((_) => setBuyer$),
- mergeMap((_) => setPayer$),
- mergeMap((checkout) =>
- this.orderCheckoutService.OrderCheckoutCreateKulturPassOrder({
- payload: {
- checkoutId: checkout.id,
- orderItemSubsetId: String(orderItemSubsetId),
- },
- }),
- ),
- );
- }
-
- updateDestination({
- processId,
- destinationId,
- destination,
- }: {
- processId: number;
- destinationId: number;
- destination: DestinationDTO;
- }): Observable {
- return this.getCheckout({ processId }).pipe(
- first(),
- mergeMap((checkout) =>
- this.storeCheckoutService
- .StoreCheckoutUpdateDestination({
- destinationId,
- checkoutId: checkout.id,
- destinationDTO: destination,
- })
- .pipe(
- map((response) => response.result),
- tap((destination) =>
- this.store.dispatch(
- DomainCheckoutActions.setCheckoutDestination({
- processId,
- destination,
- }),
- ),
- ),
- ),
- ),
- );
- }
-
- //#endregion
-
- //#region Common
-
- // Fix fรผr Ticket #4619 Versand Artikel im Warenkob -> keine รnderung bei Kundendaten erfassen
- // Auskommentiert, da dieser Aufruf oftmals mit gleichen Parametern aufgerufen wird (ohne ausgewรคhlten Kunden nur ein leeres Objekt bei customerFeatures)
- // memorize macht keinen deepCompare von Objekten und denkt hier, dass immer der gleiche Return Wert zurรผckkommt, allerdings ist das hier oft nicht der Fall
- // und der Decorator memorized dann fรคlschlicherweise
- // @memorize()
- canSetCustomer({
- processId,
- customerFeatures,
- }: {
- processId: number;
- customerFeatures?: { [key: string]: string };
- }): Observable<{ ok?: boolean; filter?: { [key: string]: string }; message?: string; create?: InputDTO }> {
- return this.getShoppingCart({ processId })
- .pipe(
- first(),
- mergeMap((shoppingCart) =>
- this._shoppingCartService
- .StoreCheckoutShoppingCartCanAddBuyer({
- shoppingCartId: shoppingCart.id,
- payload: { customerFeatures },
- })
- .pipe(
- map((response) => ({
- ok: response.result.ok,
- filter: response.result.queryToken?.filter || {},
- message: response.message,
- create: response.result.create,
- })),
- ),
- ),
- )
- .pipe(shareReplay(1));
- }
-
- setNotificationChannels({
- processId,
- notificationChannels,
- }: {
- processId: number;
- notificationChannels: NotificationChannel;
- }): void {
- this.store.dispatch(DomainCheckoutActions.setNotificationChannels({ processId, notificationChannels }));
- }
-
- getNotificationChannels({ processId }: { processId: number }): Observable {
- return this.store.select(DomainCheckoutSelectors.selectNotificationChannels, { processId });
- }
-
- setBuyerCommunicationDetails({
- processId,
- mobile,
- email,
- }: {
- processId: number;
- mobile?: string;
- email?: string;
- }): void {
- this.store.dispatch(DomainCheckoutActions.setBuyerCommunicationDetails({ processId, mobile, email }));
- }
-
- getBuyerCommunicationDetails({ processId }: { processId: number }): Observable {
- return this.store.select(DomainCheckoutSelectors.selectBuyerCommunicationDetails, { processId });
- }
-
- getSetableCustomerTypes(processId: number): Observable<{ [key: string]: boolean }> {
- return this.canSetCustomer({ processId, customerFeatures: undefined }).pipe(
- map((res) => {
- let setableTypes: { [key: string]: boolean } = {
- store: false,
- guest: false,
- webshop: false,
- b2b: false,
- };
-
- res.create?.options?.values?.forEach((option) => {
- setableTypes[option.value] = option.enabled !== false;
- });
-
- // if (Object.keys(res.filter).length === 0) {
- // return setableTypes;
- // }
-
- // const customerTypes = res.filter?.customertype?.split(';') || [];
- // const customerAttributes = res.filter?.customerattributes?.split(';') || [];
-
- // const typesAndAttributes = [...customerTypes, ...customerAttributes];
- // if (typesAndAttributes.includes('webshop') && !typesAndAttributes.includes('!guest')) {
- // typesAndAttributes.push('guest');
- // }
-
- // for (const key in setableTypes) {
- // if (Object.prototype.hasOwnProperty.call(setableTypes, key)) {
- // if (typesAndAttributes.includes(key)) {
- // setableTypes[key] = true;
- // } else if (typesAndAttributes.includes(`!${key}`)) {
- // setableTypes[key] = false;
- // } else {
- // setableTypes[key] = false;
- // }
- // }
- // }
-
- return setableTypes;
- }),
- );
- }
-
- @memorize()
- getBranches(): Observable {
- return this._branchService
- .StoreCheckoutBranchGetBranches({
- take: 999,
- })
- .pipe(
- map((r) => {
- return r.result.filter(
- (branch) =>
- branch.status === 1 &&
- branch.branchType === 1 &&
- branch.isOnline === true &&
- branch.isShippingEnabled === true,
- );
- }),
- shareReplay(),
- );
- }
-
- reorder(orderId: number, orderItemId: number, orderItemSubsetId: number, data: ReorderValues) {
- return this.orderCheckoutService
- .OrderCheckoutReorder({ orderId, orderItemId, orderItemSubsetId, data })
- .pipe(map((response) => response.result));
- }
-
- setOlaErrors({ processId, errorIds }: { processId: number; errorIds: number[] }) {
- this.store.dispatch(
- DomainCheckoutActions.setOlaError({
- processId,
- olaErrorIds: errorIds,
- }),
- );
- }
-
- getCustomerFeatures({ processId }: { processId: number }): Observable<{ [key: string]: string }> {
- return this.store.select(DomainCheckoutSelectors.selectCustomerFeaturesByProcessId, { processId });
- }
-
- setShippingAddress({ processId, shippingAddress }: { processId: number; shippingAddress: ShippingAddressDTO }) {
- this.store.dispatch(DomainCheckoutActions.setShippingAddress({ processId, shippingAddress }));
- }
-
- getShippingAddress({ processId }: { processId: number }): Observable {
- return this.store.select(DomainCheckoutSelectors.selectShippingAddressByProcessId, { processId });
- }
-
- removeProcess({ processId }: { processId: number }) {
- this.store.dispatch(DomainCheckoutActions.removeCheckoutWithProcessId({ processId }));
- }
-
- setCustomer({ processId, customerDto }: { processId: number; customerDto: CustomerDTO }) {
- this.store.dispatch(DomainCheckoutActions.setCustomer({ processId, customer: customerDto }));
- }
-
- getCustomer({ processId }: { processId: number }): Observable {
- return this.store.select(DomainCheckoutSelectors.selectCustomerByProcessId, { processId });
- }
-
- setPayer({ processId, payer }: { processId: number; payer: PayerDTO }) {
- this.store.dispatch(DomainCheckoutActions.setPayer({ processId, payer }));
- }
-
- getPayer({ processId }: { processId: number }): Observable {
- return this.store.select(DomainCheckoutSelectors.selectPayerByProcessId, { processId });
- }
-
- setBuyer({ processId, buyer }: { processId: number; buyer: BuyerDTO }) {
- this.store.dispatch(DomainCheckoutActions.setBuyer({ processId, buyer }));
- }
-
- getBuyer({ processId }: { processId: number }): Observable {
- return this.store.select(DomainCheckoutSelectors.selectBuyerByProcessId, { processId });
- }
-
- getOrders(): Observable {
- return this.store.select(DomainCheckoutSelectors.selectOrders);
- }
-
- updateOrderItem(item: DisplayOrderItemDTO) {
- this.store.dispatch(DomainCheckoutActions.updateOrderItem({ item }));
- }
-
- removeAllOrders() {
- this.store.dispatch(DomainCheckoutActions.removeAllOrders());
- }
-
- setSpecialComment({ processId, agentComment }: { processId: number; agentComment: string }) {
- this.store.dispatch(DomainCheckoutActions.setSpecialComment({ processId, agentComment }));
- }
-
- getSpecialComment({ processId }: { processId: number }) {
- return this.store.select(DomainCheckoutSelectors.selectSpecialComment, { processId });
- }
- //#endregion
-
- //#region Common
-
- private updateProcessCount(processId: number, count: number) {
- this.applicationService.patchProcessData(processId, { count });
- }
- //#endregion
-}
+import { inject, Injectable } from '@angular/core';
+import { Store } from '@ngrx/store';
+import {
+ AddToShoppingCartDTO,
+ AvailabilityDTO,
+ BranchDTO,
+ BuyerDTO,
+ BuyerResult,
+ CheckoutDTO,
+ CommunicationDetailsDTO,
+ DestinationDTO,
+ NotificationChannel,
+ OLAAvailabilityDTO,
+ PayerDTO,
+ PaymentDTO,
+ PaymentType,
+ ResponseArgsOfDestinationDTO,
+ ShippingAddressDTO,
+ ShoppingCartDTO,
+ StoreCheckoutService,
+ UpdateShoppingCartItemDTO,
+ InputDTO,
+ ItemPayload,
+ StoreCheckoutShoppingCartService,
+ StoreCheckoutPaymentService,
+ StoreCheckoutBuyerService,
+ StoreCheckoutPayerService,
+ StoreCheckoutBranchService,
+ ItemsResult,
+ KulturPassService,
+ ProductDTO,
+ KulturPassResult,
+} from '@generated/swagger/checkout-api';
+import {
+ DisplayOrderDTO,
+ DisplayOrderItemDTO,
+ OrderCheckoutService,
+ ReorderValues,
+ ResponseArgsOfValueTupleOfIEnumerableOfDisplayOrderDTOAndIEnumerableOfKeyValueDTOOfStringAndString,
+} from '@generated/swagger/oms-api';
+import { isNullOrUndefined, memorize } from '@utils/common';
+import {
+ combineLatest,
+ Observable,
+ of,
+ concat,
+ isObservable,
+ throwError,
+ interval as rxjsInterval,
+ firstValueFrom,
+} from 'rxjs';
+import {
+ bufferCount,
+ catchError,
+ distinctUntilChanged,
+ filter,
+ first,
+ map,
+ mergeMap,
+ shareReplay,
+ switchMap,
+ tap,
+ withLatestFrom,
+ startWith,
+} from 'rxjs/operators';
+
+import * as DomainCheckoutSelectors from './store/domain-checkout.selectors';
+import * as DomainCheckoutActions from './store/domain-checkout.actions';
+import { DomainAvailabilityService, ItemData } from '@domain/availability';
+import { HttpErrorResponse } from '@angular/common/http';
+import { ApplicationService } from '@core/application';
+import { CustomerDTO } from '@generated/swagger/crm-api';
+import { Config } from '@core/config';
+import parseDuration from 'parse-duration';
+import { CheckoutMetadataService } from '@isa/checkout/data-access';
+
+@Injectable()
+export class DomainCheckoutService {
+ #checkoutMetadataService = inject(CheckoutMetadataService);
+
+ get olaExpiration() {
+ const exp = this._config.get('@domain/checkout.olaExpiration') ?? '5m';
+ return parseDuration(exp);
+ }
+
+ constructor(
+ private store: Store,
+ private _config: Config,
+ private applicationService: ApplicationService,
+ private storeCheckoutService: StoreCheckoutService,
+ private orderCheckoutService: OrderCheckoutService,
+ private availabilityService: DomainAvailabilityService,
+ private _shoppingCartService: StoreCheckoutShoppingCartService,
+ private _paymentService: StoreCheckoutPaymentService,
+ private _buyerService: StoreCheckoutBuyerService,
+ private _payerService: StoreCheckoutPayerService,
+ private _branchService: StoreCheckoutBranchService,
+ private _kulturpassService: KulturPassService,
+ ) {}
+
+ //#region shoppingcart
+ @memorize()
+ getShoppingCart({
+ processId,
+ latest,
+ }: {
+ processId: number;
+ latest?: boolean;
+ }): Observable {
+ let _latest = latest;
+ return this.store
+ .select(DomainCheckoutSelectors.selectShoppingCartByProcessId, {
+ processId,
+ })
+ .pipe(
+ filter((cart) => {
+ if (isNullOrUndefined(cart)) {
+ this.createShoppingCart({ processId }).subscribe();
+ return false;
+ } else if (cart && _latest) {
+ console.log('Reloading shopping cart from API');
+ _latest = false;
+ this._shoppingCartService
+ .StoreCheckoutShoppingCartGetShoppingCart({
+ shoppingCartId: cart.id,
+ })
+ .pipe(
+ map((response) => response.result),
+ tap((shoppingCart) => {
+ this.updateProcessCount(processId, shoppingCart);
+ this.store.dispatch(
+ DomainCheckoutActions.setShoppingCart({
+ processId,
+ shoppingCart,
+ }),
+ );
+ }),
+ )
+ .subscribe();
+ return false;
+ }
+ return true;
+ }),
+ );
+ }
+
+ async reloadShoppingCart({ processId }: { processId: number }) {
+ const shoppingCart = await firstValueFrom(
+ this.store.select(DomainCheckoutSelectors.selectShoppingCartByProcessId, {
+ processId,
+ }),
+ );
+ if (!shoppingCart) {
+ return;
+ }
+ const cart = await firstValueFrom(
+ this._shoppingCartService.StoreCheckoutShoppingCartGetShoppingCart({
+ shoppingCartId: shoppingCart.id,
+ }),
+ );
+
+ this.updateProcessCount(processId, cart.result);
+ this.store.dispatch(
+ DomainCheckoutActions.setShoppingCart({
+ processId,
+ shoppingCart: cart.result,
+ }),
+ );
+ }
+
+ createShoppingCart({
+ processId,
+ }: {
+ processId: number;
+ }): Observable {
+ return this._shoppingCartService
+ .StoreCheckoutShoppingCartCreateShoppingCart()
+ .pipe(
+ map((response) => response.result),
+ tap((shoppingCart) => {
+ this.#checkoutMetadataService.setShoppingCartId(
+ processId,
+ shoppingCart.id,
+ );
+ this.store.dispatch(
+ DomainCheckoutActions.setShoppingCart({
+ processId,
+ shoppingCart,
+ }),
+ );
+ }),
+ );
+ }
+
+ addItemToShoppingCart({
+ processId,
+ items,
+ }: {
+ processId: number;
+ items: AddToShoppingCartDTO[];
+ }): Observable {
+ return this.getShoppingCart({ processId }).pipe(
+ first(),
+ mergeMap((cart) =>
+ this._shoppingCartService
+ .StoreCheckoutShoppingCartAddItemToShoppingCart({
+ items,
+ shoppingCartId: cart.id,
+ })
+ .pipe(
+ map((response) => response.result),
+ tap((shoppingCart) => {
+ this.updateProcessCount(processId, shoppingCart);
+ this.store.dispatch(
+ DomainCheckoutActions.setShoppingCart({
+ processId,
+ shoppingCart,
+ }),
+ );
+ }),
+ ),
+ ),
+ );
+ }
+
+ setDestinationForCustomer({
+ processId,
+ customerFeatures,
+ }: {
+ processId: number;
+ customerFeatures: { [key: string]: string };
+ }): Observable {
+ return this.getShoppingCart({ processId }).pipe(
+ first(),
+ mergeMap((shoppingCart) =>
+ this._shoppingCartService
+ .StoreCheckoutShoppingCartSetLogisticianOnDestinationsByBuyer({
+ shoppingCartId: shoppingCart?.id,
+ payload: { customerFeatures },
+ })
+ .pipe(map((response) => response.result)),
+ ),
+ );
+ }
+
+ canAddDestination({
+ processId,
+ destinationDTO,
+ }: {
+ processId: number;
+ destinationDTO: DestinationDTO;
+ }) {
+ return this.getShoppingCart({ processId }).pipe(
+ first(),
+ mergeMap((cart) =>
+ this._shoppingCartService.StoreCheckoutShoppingCartCanAddDestination({
+ shoppingCartId: cart.id,
+ payload: destinationDTO,
+ }),
+ ),
+ map((response) => {
+ if (response.result?.ok) {
+ return true;
+ }
+ return (
+ Object.values(response.invalidProperties).join('; ') ||
+ response.message
+ );
+ }),
+ );
+ }
+
+ canAddItem({
+ processId,
+ availability,
+ orderType,
+ }: {
+ processId: number;
+ availability: OLAAvailabilityDTO;
+ orderType: string;
+ }): Observable {
+ return this.getShoppingCart({ processId }).pipe(
+ first(),
+ withLatestFrom(
+ this.store.select(
+ DomainCheckoutSelectors.selectCustomerFeaturesByProcessId,
+ { processId },
+ ),
+ ),
+ mergeMap(([shoppingCart, customerFeatures]) =>
+ this._shoppingCartService
+ .StoreCheckoutShoppingCartCanAddItem({
+ shoppingCartId: shoppingCart?.id,
+ payload: {
+ customerFeatures,
+ availabilities: [availability],
+ orderType,
+ },
+ })
+ .pipe(
+ map((response) => {
+ if (response.result.ok) {
+ return true;
+ }
+ return response.message;
+ }),
+ ),
+ ),
+ );
+ }
+
+ canAddItemsKulturpass(payload: ProductDTO[]): Observable {
+ return this._kulturpassService
+ .KulturPassCanAddForKulturPass({ payload })
+ .pipe(map((response) => response?.result));
+ }
+
+ canAddItems({
+ processId,
+ payload,
+ orderType,
+ }: {
+ processId: number;
+ payload: ItemPayload[];
+ orderType: string;
+ }): Observable {
+ return this.getShoppingCart({ processId }).pipe(
+ first(),
+ withLatestFrom(
+ this.store.select(
+ DomainCheckoutSelectors.selectCustomerFeaturesByProcessId,
+ { processId },
+ ),
+ ),
+ mergeMap(([shoppingCart, customerFeatures]) => {
+ payload = payload?.map((p) => {
+ return {
+ ...p,
+ customerFeatures,
+ orderType,
+ };
+ });
+ return this._shoppingCartService
+ .StoreCheckoutShoppingCartCanAddItems({
+ shoppingCartId: shoppingCart.id,
+ payload,
+ })
+ .pipe(
+ map((response) => {
+ // TODO: remove this when the API is fixed
+ return response.result as unknown as ItemsResult[];
+ }),
+ );
+ }),
+ );
+ }
+
+ updateShoppingCartItemAvailability({
+ shoppingCartId,
+ shoppingCartItemId,
+ availability,
+ }: {
+ shoppingCartId: number;
+ shoppingCartItemId: number;
+ availability: AvailabilityDTO;
+ }) {
+ return this._shoppingCartService
+ .StoreCheckoutShoppingCartUpdateShoppingCartItemAvailability({
+ shoppingCartId,
+ shoppingCartItemId,
+ availability,
+ })
+ .pipe(
+ map((response) => response.result),
+ tap((shoppingCart) => {
+ this.store.dispatch(
+ DomainCheckoutActions.addShoppingCartItemAvailabilityToHistoryByShoppingCartId(
+ {
+ shoppingCartId,
+ availability,
+ shoppingCartItemId,
+ },
+ ),
+ );
+ }),
+ );
+ }
+
+ updateItemInShoppingCart({
+ processId,
+ shoppingCartItemId,
+ update,
+ }: {
+ processId: number;
+ shoppingCartItemId: number;
+ update: UpdateShoppingCartItemDTO;
+ }): Observable {
+ return this.getShoppingCart({ processId, latest: true }).pipe(
+ first(),
+ mergeMap((shoppingCart) =>
+ this._shoppingCartService
+ .StoreCheckoutShoppingCartUpdateShoppingCartItem({
+ shoppingCartId: shoppingCart.id,
+ shoppingCartItemId,
+ values: update,
+ })
+ .pipe(
+ map((response) => response.result),
+ tap((shoppingCart) => {
+ this.store.dispatch(
+ DomainCheckoutActions.setShoppingCart({
+ processId,
+ shoppingCart,
+ }),
+ );
+
+ if (update.availability) {
+ this.store.dispatch(
+ DomainCheckoutActions.addShoppingCartItemAvailabilityToHistory(
+ {
+ processId,
+ availability: update.availability,
+ shoppingCartItemId,
+ },
+ ),
+ );
+ }
+
+ this.updateProcessCount(processId, shoppingCart);
+ }),
+ ),
+ ),
+ );
+ }
+
+ //#endregion
+
+ //#region Checkout
+
+ getCheckout({
+ processId,
+ refresh,
+ }: {
+ processId: number;
+ refresh?: boolean;
+ }): Observable {
+ let _refresh = refresh;
+ return this.store
+ .select(DomainCheckoutSelectors.selectCheckoutByProcessId, { processId })
+ .pipe(
+ filter((checkout) => {
+ if (isNullOrUndefined(checkout) || _refresh) {
+ _refresh = false;
+ this.createCheckout({ processId }).subscribe();
+ return false;
+ }
+ return true;
+ }),
+ );
+ }
+
+ createCheckout({ processId }: { processId: number }) {
+ return this.getShoppingCart({ processId }).pipe(
+ first(),
+ mergeMap((shoppingCart) =>
+ this.storeCheckoutService
+ .StoreCheckoutCreateOrRefreshCheckout({
+ shoppingCartId: shoppingCart?.id,
+ })
+ .pipe(
+ map((response) => response.result),
+ tap((checkout) =>
+ this.store.dispatch(
+ DomainCheckoutActions.setCheckout({ processId, checkout }),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ /* @internal */
+ _setNotificationChannels({
+ processId,
+ notificationChannels,
+ }: {
+ processId: number;
+ notificationChannels: NotificationChannel;
+ }): Observable {
+ return this.getCheckout({ processId }).pipe(
+ first(),
+ mergeMap((checkout) =>
+ this.storeCheckoutService
+ .StoreCheckoutSetNotificationChannels({
+ checkoutId: checkout.id,
+ notificationChannel: notificationChannels,
+ })
+ .pipe(
+ map((response) => response.result),
+ tap((checkout) =>
+ this.store.dispatch(
+ DomainCheckoutActions.setCheckout({ processId, checkout }),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ getPayment({ processId }: { processId: number }): Observable {
+ return this.getCheckout({ processId }).pipe(
+ first(),
+ mergeMap((checkout) =>
+ this._paymentService
+ .StoreCheckoutPaymentGetCheckoutPayment({
+ checkoutId: checkout.id,
+ })
+ .pipe(map((response) => response.result)),
+ ),
+ );
+ }
+
+ getOlaErrors({ processId }: { processId: number }): Observable {
+ return this.store.select(
+ DomainCheckoutSelectors.selectOlaErrorsByProcessId,
+ { processId },
+ );
+ }
+
+ setPayment({
+ processId,
+ paymentType,
+ }: {
+ processId: number;
+ paymentType: PaymentType;
+ }): Observable {
+ return this.getCheckout({ processId }).pipe(
+ first(),
+ mergeMap((checkout) =>
+ this._paymentService
+ .StoreCheckoutPaymentSetPaymentType({
+ checkoutId: checkout?.id,
+ paymentType,
+ })
+ .pipe(
+ map((response) => response.result),
+ tap((checkout) =>
+ this.store.dispatch(
+ DomainCheckoutActions.setCheckout({ processId, checkout }),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ _setBuyer({
+ processId,
+ buyer,
+ }: {
+ processId: number;
+ buyer: BuyerDTO;
+ }): Observable {
+ return this.getCheckout({ processId }).pipe(
+ first(),
+ mergeMap((checkout) => {
+ console.log('checkout', checkout, processId);
+ return this._buyerService
+ .StoreCheckoutBuyerSetBuyerPOST({
+ checkoutId: checkout?.id,
+ buyerDTO: buyer,
+ })
+ .pipe(
+ map((response) => response.result),
+ tap((checkout) =>
+ this.store.dispatch(
+ DomainCheckoutActions.setCheckout({ processId, checkout }),
+ ),
+ ),
+ );
+ }),
+ );
+ }
+
+ _setPayer({
+ processId,
+ payer,
+ }: {
+ processId: number;
+ payer: PayerDTO;
+ }): Observable {
+ return this.getCheckout({ processId }).pipe(
+ first(),
+ mergeMap((checkout) =>
+ this._payerService
+ .StoreCheckoutPayerSetPayerPOST({
+ checkoutId: checkout?.id,
+ payerDTO: payer,
+ })
+ .pipe(
+ map((response) => response.result),
+ tap((checkout) =>
+ this.store.dispatch(
+ DomainCheckoutActions.setCheckout({ processId, checkout }),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ setSpecialCommentOnItem({
+ processId,
+ specialComment,
+ }: {
+ processId: number;
+ specialComment: string;
+ }) {
+ const shoppingCart$ = this.getShoppingCart({ processId }).pipe(first());
+
+ return shoppingCart$.pipe(
+ mergeMap((cart) =>
+ concat(
+ ...cart.items.map((item) =>
+ this._shoppingCartService.StoreCheckoutShoppingCartUpdateShoppingCartItem(
+ {
+ shoppingCartId: cart.id,
+ shoppingCartItemId: item.id,
+ values: { specialComment },
+ },
+ ),
+ ),
+ ).pipe(bufferCount(cart.items?.length)),
+ ),
+ );
+ }
+
+ checkAvailabilities({ processId }: { processId: number }): Observable {
+ const shoppingCart$ = this.getShoppingCart({ processId }).pipe(first());
+ const itemsToCheck$ = shoppingCart$.pipe(
+ map((cart) =>
+ cart?.items?.filter(
+ (item) =>
+ item?.data?.features?.orderType === 'Download' &&
+ !item.data.availability.lastRequest,
+ ),
+ ),
+ );
+
+ return itemsToCheck$.pipe(
+ withLatestFrom(shoppingCart$),
+ switchMap(async ([items, cart]) => {
+ const errorIds = [];
+
+ for (const item of items) {
+ const availability = await this.availabilityService
+ .getDownloadAvailability({
+ item: {
+ ean: item.data.product.ean,
+ itemId: Number(item.data.product.catalogProductNumber),
+ price: item.data.availability.price,
+ },
+ })
+ .toPromise();
+
+ if (
+ !availability ||
+ !this.availabilityService.isAvailable({ availability })
+ ) {
+ errorIds.push(item.id);
+ } else {
+ await this.updateShoppingCartItemAvailability({
+ shoppingCartId: cart.id,
+ shoppingCartItemId: item.id,
+ availability: {
+ ...availability,
+ lastRequest: new Date().toISOString(),
+ },
+ }).toPromise();
+ }
+ }
+
+ this.setOlaErrors({ processId, errorIds });
+
+ if (errorIds.length > 0) {
+ throw throwError(new Error(`Artikel nicht verfรผgbar`));
+ } else {
+ return of(undefined);
+ }
+ }),
+ );
+ }
+
+ updateAvailabilities({ processId }: { processId: number }): Observable {
+ const shoppingCart$ = this.getShoppingCart({ processId }).pipe(first());
+ const itemsToUpdate$ = shoppingCart$.pipe(
+ map((cart) =>
+ cart?.items?.filter(
+ (item) =>
+ item?.data?.features?.orderType === 'DIG-Versand' ||
+ item?.data?.features?.orderType === 'B2B-Versand',
+ ),
+ ),
+ );
+
+ return itemsToUpdate$.pipe(
+ mergeMap((itemsToUpdate) => {
+ if (!(itemsToUpdate?.length > 0)) {
+ return of(undefined);
+ }
+
+ return concat(
+ ...itemsToUpdate.map(async (itemToUpdate) => {
+ const orderType = itemToUpdate?.data?.features?.orderType;
+ let availability$: Observable;
+ if (orderType === 'DIG-Versand') {
+ availability$ =
+ this.availabilityService.getDigDeliveryAvailability({
+ item: {
+ ean: itemToUpdate.data.product.ean,
+ itemId: Number(
+ itemToUpdate.data.product.catalogProductNumber,
+ ),
+ price: itemToUpdate.data.availability.price,
+ },
+ quantity: itemToUpdate.data.quantity,
+ });
+ } else if (orderType === 'B2B-Versand') {
+ const branch = await this.applicationService
+ .getSelectedBranch$(processId)
+ .pipe(first())
+ .toPromise();
+ availability$ =
+ this.availabilityService.getB2bDeliveryAvailability({
+ item: {
+ ean: itemToUpdate.data.product.ean,
+ itemId: Number(
+ itemToUpdate.data.product.catalogProductNumber,
+ ),
+ price: itemToUpdate.data.availability.price,
+ },
+ quantity: itemToUpdate.data.quantity,
+ branch,
+ });
+ }
+
+ if (!isObservable(availability$)) {
+ return of(undefined);
+ }
+
+ return availability$.pipe(
+ mergeMap((availability) => {
+ let updatedAvailability = availability;
+ // Bei Preisupdate der Versandoptionen soll immer der Preis genommen werden, der im Warenkorb steht
+ if (
+ orderType === 'DIG-Versand' ||
+ orderType === 'B2B-Versand'
+ ) {
+ const itemPrice = itemToUpdate.data.availability.price;
+ updatedAvailability = {
+ ...availability,
+ price: itemPrice,
+ };
+ }
+ return this.updateItemInShoppingCart({
+ processId,
+ shoppingCartItemId: itemToUpdate.id,
+ update: {
+ availability: updatedAvailability,
+ },
+ });
+ }),
+ );
+ }),
+ ).pipe(bufferCount(itemsToUpdate.length));
+ }),
+ );
+ }
+
+ async refreshAvailability({
+ processId,
+ shoppingCartItemId,
+ }: {
+ processId: number;
+ shoppingCartItemId: number;
+ }): Promise {
+ const shoppingCart = await this.getShoppingCart({ processId })
+ .pipe(first())
+ .toPromise();
+ const item = shoppingCart?.items.find(
+ (item) => item.id === shoppingCartItemId,
+ )?.data;
+
+ if (!item) {
+ return;
+ }
+
+ const itemData: ItemData = {
+ ean: item.product.ean,
+ itemId: Number(item.product.catalogProductNumber),
+ price: item.availability.price,
+ };
+
+ let availability: AvailabilityDTO;
+
+ switch (item.features.orderType) {
+ case 'Abholung': {
+ const abholung = await this.availabilityService
+ .getPickUpAvailability({
+ item: itemData,
+ branch: item.destination?.data?.targetBranch?.data,
+ quantity: item.quantity,
+ })
+ .toPromise();
+ availability = abholung[0];
+ break;
+ }
+ case 'Rรผcklage': {
+ const ruecklage = await this.availabilityService
+ .getTakeAwayAvailability({
+ item: itemData,
+ quantity: item.quantity,
+ branch: item.destination?.data?.targetBranch?.data,
+ })
+ .toPromise();
+ availability = ruecklage;
+ break;
+ }
+ case 'Download': {
+ const download = await this.availabilityService
+ .getDownloadAvailability({
+ item: itemData,
+ })
+ .toPromise();
+
+ availability = download;
+ break;
+ }
+ case 'Versand': {
+ const versand = await this.availabilityService
+ .getDeliveryAvailability({
+ item: itemData,
+ quantity: item.quantity,
+ })
+ .toPromise();
+
+ availability = versand;
+ break;
+ }
+ case 'DIG-Versand': {
+ const digVersand = await this.availabilityService
+ .getDigDeliveryAvailability({
+ item: itemData,
+ quantity: item.quantity,
+ })
+ .toPromise();
+
+ availability = digVersand;
+ break;
+ }
+ case 'B2B-Versand': {
+ const b2bVersand = await this.availabilityService
+ .getB2bDeliveryAvailability({
+ item: itemData,
+ quantity: item.quantity,
+ })
+ .toPromise();
+
+ availability = b2bVersand;
+ break;
+ }
+ }
+
+ await this.updateItemInShoppingCart({
+ processId,
+ update: { availability },
+ shoppingCartItemId: item.id,
+ }).toPromise();
+
+ return availability;
+ }
+
+ /**
+ * Check if the availability of all items is valid
+ * @param param0 Process Id
+ * @returns true if the availability of all items is valid
+ */
+ validateOlaStatus({
+ processId,
+ interval,
+ }: {
+ processId: number;
+ interval?: number;
+ }): Observable {
+ return rxjsInterval(interval ?? this.olaExpiration / 10).pipe(
+ startWith(0),
+ switchMap(() =>
+ this.store
+ .select(DomainCheckoutSelectors.selectCheckoutEntityByProcessId, {
+ processId,
+ })
+ .pipe(
+ map((entity) => {
+ const now = Date.now();
+ if (
+ !entity ||
+ !entity.shoppingCart ||
+ !entity.shoppingCart.items
+ ) {
+ return;
+ }
+
+ const itemAvailabilityTimestamp =
+ entity.itemAvailabilityTimestamp ?? {};
+ const shoppingCart = entity.shoppingCart;
+
+ const timestamps = shoppingCart.items
+ ?.map((i) => i.data)
+ ?.filter((item) => !!item?.features?.orderType)
+ ?.map((item) => {
+ const orderType = item.features.orderType;
+
+ let timestamp =
+ itemAvailabilityTimestamp[`${item.id}_${orderType}`];
+
+ if (timestamp) {
+ return timestamp;
+ }
+
+ if (orderType.endsWith('Versand')) {
+ timestamp =
+ itemAvailabilityTimestamp[`${item.id}_Versand`] ??
+ itemAvailabilityTimestamp[`${item.id}_DIG-Versand`] ??
+ itemAvailabilityTimestamp[`${item.id}_B2B-Versand`];
+ }
+
+ return timestamp;
+ })
+ ?.filter((timestamp) => !!timestamp);
+
+ if (timestamps?.length > 0) {
+ const oldestTimestamp = Math.min(...timestamps);
+ const expirationTimestamp =
+ oldestTimestamp + this.olaExpiration;
+ return expirationTimestamp > now;
+ }
+
+ return false;
+ }),
+ ),
+ ),
+ distinctUntilChanged(),
+ );
+ }
+
+ validateAvailabilities({
+ processId,
+ }: {
+ processId: number;
+ }): Observable {
+ return this.getShoppingCart({ processId }).pipe(
+ map((shoppingCart) => {
+ const items = shoppingCart?.items?.map((item) => item.data) || [];
+ return items.every((i) =>
+ this.availabilityService.isAvailable({
+ availability: i.availability,
+ }),
+ );
+ }),
+ );
+ }
+
+ checkoutIsValid({ processId }: { processId: number }): Observable {
+ const olaStatus$ = this.validateOlaStatus({ processId, interval: 250 });
+
+ const availabilities$ = this.validateAvailabilities({ processId });
+
+ return combineLatest([olaStatus$, availabilities$]).pipe(
+ map(([olaStatus, availabilities]) => olaStatus && availabilities),
+ );
+ }
+
+ completeCheckout({
+ processId,
+ }: {
+ processId: number;
+ }): Observable {
+ const refreshShoppingCart$ = this.getShoppingCart({
+ processId,
+ latest: true,
+ }).pipe(first());
+ const refreshCheckout$ = this.getCheckout({
+ processId,
+ refresh: true,
+ }).pipe(first());
+
+ const itemOrderOptions$ = this.getShoppingCart({ processId }).pipe(
+ first(),
+ map((shoppingCart) => {
+ const shoppingCartItems =
+ shoppingCart?.items?.map((item) => item.data) || [];
+
+ const hasTakeAway = shoppingCartItems.some(
+ (item) => item.features.orderType === 'Rรผcklage',
+ );
+ const hasPickUp = shoppingCartItems.some(
+ (item) => item.features.orderType === 'Abholung',
+ );
+ const hasDownload = shoppingCartItems.some(
+ (item) => item.features.orderType === 'Download',
+ );
+ const hasDelivery = shoppingCartItems.some(
+ (item) => item.features.orderType === 'Versand',
+ );
+ const hasDigDelivery = shoppingCartItems.some(
+ (item) => item.features.orderType === 'DIG-Versand',
+ );
+ const hasB2BDelivery = shoppingCartItems.some(
+ (item) => item.features.orderType === 'B2B-Versand',
+ );
+
+ return {
+ hasTakeAway,
+ hasPickUp,
+ hasDownload,
+ hasDelivery,
+ hasDigDelivery,
+ hasB2BDelivery,
+ };
+ }),
+ shareReplay(),
+ );
+
+ const customerTypes$ = this.getCustomerFeatures({ processId }).pipe(
+ first(),
+ map((features) => {
+ const isOnline = !!features?.webshop;
+ const isGuest = !!features?.guest;
+ const isB2B = !!features?.b2b;
+ const hasCustomerCard = !!features?.p4mUser;
+ const isStaff = !!features?.staff;
+
+ return { isOnline: isOnline, isGuest, isB2B, hasCustomerCard, isStaff };
+ }),
+ );
+
+ const setSpecialComment$ = this.getSpecialComment({ processId }).pipe(
+ first(),
+ mergeMap((specialComment) => {
+ if (specialComment) {
+ return this.setSpecialCommentOnItem({ processId, specialComment });
+ }
+ return of(specialComment);
+ }),
+ );
+
+ const shippingAddressDestination$ = this.getCheckout({ processId }).pipe(
+ first(),
+ map((checkout) =>
+ checkout?.destinations?.filter(
+ (dest) => dest.data.target === 2 || dest.data.target === 16,
+ ),
+ ),
+ shareReplay(),
+ );
+
+ const setBuyer$ = this.getBuyer({ processId }).pipe(
+ first(),
+ mergeMap((buyer) => this._setBuyer({ processId, buyer })),
+ );
+
+ const setNotificationChannels$ = this.getNotificationChannels({
+ processId,
+ }).pipe(
+ first(),
+ mergeMap((notificationChannels) =>
+ this._setNotificationChannels({ processId, notificationChannels }),
+ ),
+ );
+
+ const setPayer$ = combineLatest([itemOrderOptions$, customerTypes$]).pipe(
+ first(),
+ mergeMap(([itemOrderOptions, customerTypes]) => {
+ if (
+ customerTypes.isB2B ||
+ itemOrderOptions.hasB2BDelivery ||
+ itemOrderOptions.hasDelivery ||
+ itemOrderOptions.hasDigDelivery ||
+ itemOrderOptions.hasDownload
+ ) {
+ return this.getPayer({ processId }).pipe(first());
+ }
+ return of(undefined);
+ }),
+ mergeMap((payer) =>
+ payer ? this._setPayer({ processId, payer }) : of(undefined),
+ ),
+ );
+
+ const updateDestination$ = itemOrderOptions$.pipe(
+ withLatestFrom(this.getCustomerFeatures({ processId })),
+ mergeMap(
+ ([
+ { hasDownload, hasDelivery, hasDigDelivery, hasB2BDelivery },
+ customerFeatures,
+ ]) => {
+ const needsUpdate =
+ hasDownload || hasDelivery || hasDigDelivery || hasB2BDelivery;
+ return needsUpdate
+ ? this.setDestinationForCustomer({ processId, customerFeatures })
+ : of(undefined);
+ },
+ ),
+ );
+
+ const checkAvailabilities$ = this.checkAvailabilities({ processId });
+
+ const updateAvailabilities$ = this.updateAvailabilities({ processId });
+
+ const setPaymentType$ = itemOrderOptions$.pipe(
+ mergeMap(
+ ({ hasDownload, hasDelivery, hasDigDelivery, hasB2BDelivery }) => {
+ const paymentType =
+ hasDownload || hasDelivery || hasDigDelivery || hasB2BDelivery
+ ? 128 /* Rechnung */
+ : 4; /* Bar */
+ return this.setPayment({ processId, paymentType });
+ },
+ ),
+ shareReplay(),
+ );
+
+ const setDestination$ = combineLatest([
+ this.getCheckout({ processId }).pipe(first()),
+ shippingAddressDestination$,
+ this.getShippingAddress({ processId }).pipe(first()),
+ ]).pipe(
+ mergeMap(([checkout, destinations, shippingAddress]) => {
+ const obs: Observable[] = [];
+ if (destinations?.length > 0) {
+ destinations.forEach((destination) => {
+ const updatedDestination: DestinationDTO = {
+ ...destination.data,
+ shippingAddress: { ...shippingAddress },
+ };
+ obs.push(
+ this.storeCheckoutService.StoreCheckoutUpdateDestination({
+ checkoutId: checkout.id,
+ destinationId: destination.id,
+ destinationDTO: updatedDestination,
+ }),
+ );
+ });
+ return concat(...obs).pipe(bufferCount(destinations?.length));
+ }
+ return of(destinations);
+ }),
+ shareReplay(),
+ );
+
+ const completeOrder$ = this.getCheckout({ processId }).pipe(
+ first(),
+ mergeMap((checkout) =>
+ this.orderCheckoutService
+ .OrderCheckoutCreateOrderPOST({
+ checkoutId: checkout.id,
+ })
+ .pipe(
+ catchError((error) => {
+ if (error instanceof HttpErrorResponse) {
+ if (error.status === 409) {
+ this.store.dispatch(
+ DomainCheckoutActions.setOrders({
+ orders: error.error.result,
+ }),
+ );
+ }
+ return throwError(error);
+ }
+ }),
+ map((response) => {
+ this.store.dispatch(
+ DomainCheckoutActions.setOrders({ orders: response.result }),
+ );
+ return response.result;
+ }),
+ ),
+ ),
+ );
+
+ return of(undefined)
+ .pipe(
+ mergeMap((_) =>
+ updateDestination$.pipe(
+ tap(console.log.bind(window, 'updateDestination$')),
+ ),
+ ),
+ mergeMap((_) =>
+ refreshShoppingCart$.pipe(
+ tap(console.log.bind(window, 'refreshShoppingCart$')),
+ ),
+ ),
+ mergeMap((_) =>
+ setSpecialComment$.pipe(
+ tap(console.log.bind(window, 'setSpecialComment$')),
+ ),
+ ),
+ mergeMap((_) =>
+ refreshCheckout$.pipe(
+ tap(console.log.bind(window, 'refreshCheckout$')),
+ ),
+ ),
+ mergeMap((_) =>
+ checkAvailabilities$.pipe(
+ tap(console.log.bind(window, 'checkAvailabilities$')),
+ ),
+ ),
+ mergeMap((_) =>
+ updateAvailabilities$.pipe(
+ tap(console.log.bind(window, 'updateAvailabilities$')),
+ ),
+ ),
+ )
+ .pipe(
+ mergeMap((_) =>
+ setBuyer$.pipe(tap(console.log.bind(window, 'setBuyer$'))),
+ ),
+ mergeMap((_) =>
+ setNotificationChannels$.pipe(
+ tap(console.log.bind(window, 'setNotificationChannels$')),
+ ),
+ ),
+ mergeMap((_) =>
+ setPayer$.pipe(tap(console.log.bind(window, 'setPayer$'))),
+ ),
+ mergeMap((_) =>
+ setPaymentType$.pipe(
+ tap(console.log.bind(window, 'setPaymentType$')),
+ ),
+ ),
+ mergeMap((_) =>
+ setDestination$.pipe(
+ tap(console.log.bind(window, 'setDestination$')),
+ ),
+ ),
+ mergeMap((_) =>
+ completeOrder$.pipe(tap(console.log.bind(window, 'completeOrder$'))),
+ ),
+ );
+ }
+
+ completeKulturpassOrder({
+ processId,
+ orderItemSubsetId,
+ }: {
+ processId: number;
+ orderItemSubsetId: number;
+ }): Observable {
+ const refreshShoppingCart$ = this.getShoppingCart({
+ processId,
+ latest: true,
+ }).pipe(first());
+ const refreshCheckout$ = this.getCheckout({
+ processId,
+ refresh: true,
+ }).pipe(first());
+
+ const setBuyer$ = this.getBuyer({ processId }).pipe(
+ first(),
+ mergeMap((buyer) => this._setBuyer({ processId, buyer })),
+ );
+
+ const setPayer$ = this.getPayer({ processId }).pipe(
+ first(),
+ mergeMap((payer) => this._setPayer({ processId, payer })),
+ );
+
+ const checkAvailabilities$ = this.checkAvailabilities({ processId });
+
+ const updateAvailabilities$ = this.updateAvailabilities({ processId });
+
+ return refreshShoppingCart$.pipe(
+ mergeMap((_) => refreshCheckout$),
+ mergeMap((_) => checkAvailabilities$),
+ mergeMap((_) => updateAvailabilities$),
+ mergeMap((_) => setBuyer$),
+ mergeMap((_) => setPayer$),
+ mergeMap((checkout) =>
+ this.orderCheckoutService.OrderCheckoutCreateKulturPassOrder({
+ payload: {
+ checkoutId: checkout.id,
+ orderItemSubsetId: String(orderItemSubsetId),
+ },
+ }),
+ ),
+ );
+ }
+
+ updateDestination({
+ processId,
+ destinationId,
+ destination,
+ }: {
+ processId: number;
+ destinationId: number;
+ destination: DestinationDTO;
+ }): Observable {
+ return this.getCheckout({ processId }).pipe(
+ first(),
+ mergeMap((checkout) =>
+ this.storeCheckoutService
+ .StoreCheckoutUpdateDestination({
+ destinationId,
+ checkoutId: checkout.id,
+ destinationDTO: destination,
+ })
+ .pipe(
+ map((response) => response.result),
+ tap((destination) =>
+ this.store.dispatch(
+ DomainCheckoutActions.setCheckoutDestination({
+ processId,
+ destination,
+ }),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ //#endregion
+
+ //#region Common
+
+ // Fix fรผr Ticket #4619 Versand Artikel im Warenkob -> keine รnderung bei Kundendaten erfassen
+ // Auskommentiert, da dieser Aufruf oftmals mit gleichen Parametern aufgerufen wird (ohne ausgewรคhlten Kunden nur ein leeres Objekt bei customerFeatures)
+ // memorize macht keinen deepCompare von Objekten und denkt hier, dass immer der gleiche Return Wert zurรผckkommt, allerdings ist das hier oft nicht der Fall
+ // und der Decorator memorized dann fรคlschlicherweise
+ // @memorize()
+ canSetCustomer({
+ processId,
+ customerFeatures,
+ }: {
+ processId: number;
+ customerFeatures?: { [key: string]: string };
+ }): Observable<{
+ ok?: boolean;
+ filter?: { [key: string]: string };
+ message?: string;
+ create?: InputDTO;
+ }> {
+ return this.getShoppingCart({ processId })
+ .pipe(
+ first(),
+ mergeMap((shoppingCart) =>
+ this._shoppingCartService
+ .StoreCheckoutShoppingCartCanAddBuyer({
+ shoppingCartId: shoppingCart.id,
+ payload: { customerFeatures },
+ })
+ .pipe(
+ map((response) => ({
+ ok: response.result.ok,
+ filter: response.result.queryToken?.filter || {},
+ message: response.message,
+ create: response.result.create,
+ })),
+ ),
+ ),
+ )
+ .pipe(shareReplay(1));
+ }
+
+ setNotificationChannels({
+ processId,
+ notificationChannels,
+ }: {
+ processId: number;
+ notificationChannels: NotificationChannel;
+ }): void {
+ this.store.dispatch(
+ DomainCheckoutActions.setNotificationChannels({
+ processId,
+ notificationChannels,
+ }),
+ );
+ }
+
+ getNotificationChannels({
+ processId,
+ }: {
+ processId: number;
+ }): Observable {
+ return this.store.select(
+ DomainCheckoutSelectors.selectNotificationChannels,
+ { processId },
+ );
+ }
+
+ setBuyerCommunicationDetails({
+ processId,
+ mobile,
+ email,
+ }: {
+ processId: number;
+ mobile?: string;
+ email?: string;
+ }): void {
+ this.store.dispatch(
+ DomainCheckoutActions.setBuyerCommunicationDetails({
+ processId,
+ mobile,
+ email,
+ }),
+ );
+ }
+
+ getBuyerCommunicationDetails({
+ processId,
+ }: {
+ processId: number;
+ }): Observable {
+ return this.store.select(
+ DomainCheckoutSelectors.selectBuyerCommunicationDetails,
+ { processId },
+ );
+ }
+
+ getSetableCustomerTypes(
+ processId: number,
+ ): Observable<{ [key: string]: boolean }> {
+ return this.canSetCustomer({ processId, customerFeatures: undefined }).pipe(
+ map((res) => {
+ let setableTypes: { [key: string]: boolean } = {
+ store: false,
+ guest: false,
+ webshop: false,
+ b2b: false,
+ };
+
+ res.create?.options?.values?.forEach((option) => {
+ setableTypes[option.value] = option.enabled !== false;
+ });
+
+ // if (Object.keys(res.filter).length === 0) {
+ // return setableTypes;
+ // }
+
+ // const customerTypes = res.filter?.customertype?.split(';') || [];
+ // const customerAttributes = res.filter?.customerattributes?.split(';') || [];
+
+ // const typesAndAttributes = [...customerTypes, ...customerAttributes];
+ // if (typesAndAttributes.includes('webshop') && !typesAndAttributes.includes('!guest')) {
+ // typesAndAttributes.push('guest');
+ // }
+
+ // for (const key in setableTypes) {
+ // if (Object.prototype.hasOwnProperty.call(setableTypes, key)) {
+ // if (typesAndAttributes.includes(key)) {
+ // setableTypes[key] = true;
+ // } else if (typesAndAttributes.includes(`!${key}`)) {
+ // setableTypes[key] = false;
+ // } else {
+ // setableTypes[key] = false;
+ // }
+ // }
+ // }
+
+ return setableTypes;
+ }),
+ );
+ }
+
+ @memorize()
+ getBranches(): Observable {
+ return this._branchService
+ .StoreCheckoutBranchGetBranches({
+ take: 999,
+ })
+ .pipe(
+ map((r) => {
+ return r.result.filter(
+ (branch) =>
+ branch.status === 1 &&
+ branch.branchType === 1 &&
+ branch.isOnline === true &&
+ branch.isShippingEnabled === true,
+ );
+ }),
+ shareReplay(),
+ );
+ }
+
+ reorder(
+ orderId: number,
+ orderItemId: number,
+ orderItemSubsetId: number,
+ data: ReorderValues,
+ ) {
+ return this.orderCheckoutService
+ .OrderCheckoutReorder({ orderId, orderItemId, orderItemSubsetId, data })
+ .pipe(map((response) => response.result));
+ }
+
+ setOlaErrors({
+ processId,
+ errorIds,
+ }: {
+ processId: number;
+ errorIds: number[];
+ }) {
+ this.store.dispatch(
+ DomainCheckoutActions.setOlaError({
+ processId,
+ olaErrorIds: errorIds,
+ }),
+ );
+ }
+
+ getCustomerFeatures({
+ processId,
+ }: {
+ processId: number;
+ }): Observable<{ [key: string]: string }> {
+ return this.store.select(
+ DomainCheckoutSelectors.selectCustomerFeaturesByProcessId,
+ { processId },
+ );
+ }
+
+ setShippingAddress({
+ processId,
+ shippingAddress,
+ }: {
+ processId: number;
+ shippingAddress: ShippingAddressDTO;
+ }) {
+ this.store.dispatch(
+ DomainCheckoutActions.setShippingAddress({ processId, shippingAddress }),
+ );
+ }
+
+ getShippingAddress({
+ processId,
+ }: {
+ processId: number;
+ }): Observable {
+ return this.store.select(
+ DomainCheckoutSelectors.selectShippingAddressByProcessId,
+ { processId },
+ );
+ }
+
+ removeProcess({ processId }: { processId: number }) {
+ this.store.dispatch(
+ DomainCheckoutActions.removeCheckoutWithProcessId({ processId }),
+ );
+ }
+
+ setCustomer({
+ processId,
+ customerDto,
+ }: {
+ processId: number;
+ customerDto: CustomerDTO;
+ }) {
+ this.store.dispatch(
+ DomainCheckoutActions.setCustomer({ processId, customer: customerDto }),
+ );
+ }
+
+ getCustomer({ processId }: { processId: number }): Observable {
+ return this.store.select(
+ DomainCheckoutSelectors.selectCustomerByProcessId,
+ { processId },
+ );
+ }
+
+ setPayer({ processId, payer }: { processId: number; payer: PayerDTO }) {
+ this.store.dispatch(DomainCheckoutActions.setPayer({ processId, payer }));
+ }
+
+ getPayer({ processId }: { processId: number }): Observable {
+ return this.store.select(DomainCheckoutSelectors.selectPayerByProcessId, {
+ processId,
+ });
+ }
+
+ setBuyer({ processId, buyer }: { processId: number; buyer: BuyerDTO }) {
+ this.store.dispatch(DomainCheckoutActions.setBuyer({ processId, buyer }));
+ }
+
+ getBuyer({ processId }: { processId: number }): Observable {
+ return this.store.select(DomainCheckoutSelectors.selectBuyerByProcessId, {
+ processId,
+ });
+ }
+
+ getOrders(): Observable {
+ return this.store.select(DomainCheckoutSelectors.selectOrders);
+ }
+
+ updateOrderItem(item: DisplayOrderItemDTO) {
+ this.store.dispatch(DomainCheckoutActions.updateOrderItem({ item }));
+ }
+
+ removeAllOrders() {
+ this.store.dispatch(DomainCheckoutActions.removeAllOrders());
+ }
+
+ setSpecialComment({
+ processId,
+ agentComment,
+ }: {
+ processId: number;
+ agentComment: string;
+ }) {
+ this.store.dispatch(
+ DomainCheckoutActions.setSpecialComment({ processId, agentComment }),
+ );
+ }
+
+ getSpecialComment({ processId }: { processId: number }) {
+ return this.store.select(DomainCheckoutSelectors.selectSpecialComment, {
+ processId,
+ });
+ }
+ //#endregion
+
+ //#region Common
+
+ async updateProcessCount(processId: number, shoppingCart: ShoppingCartDTO) {
+ this.applicationService.patchProcessData(processId, {
+ count: shoppingCart.items?.length ?? 0,
+ });
+ }
+ //#endregion
+}
diff --git a/apps/isa-app/src/modal/kulturpass-order/kulturpass-order-modal.store.ts b/apps/isa-app/src/modal/kulturpass-order/kulturpass-order-modal.store.ts
index 4297492b9..397013b60 100644
--- a/apps/isa-app/src/modal/kulturpass-order/kulturpass-order-modal.store.ts
+++ b/apps/isa-app/src/modal/kulturpass-order/kulturpass-order-modal.store.ts
@@ -12,7 +12,13 @@ import {
ShoppingCartItemDTO,
} from '@generated/swagger/checkout-api';
import { DomainCheckoutService } from '@domain/checkout';
-import { catchError, mergeMap, switchMap, tap, withLatestFrom } from 'rxjs/operators';
+import {
+ catchError,
+ mergeMap,
+ switchMap,
+ tap,
+ withLatestFrom,
+} from 'rxjs/operators';
import {
BranchService,
DisplayOrderDTO,
@@ -40,7 +46,10 @@ export interface KulturpassOrderModalState {
}
@Injectable()
-export class KulturpassOrderModalStore extends ComponentStore implements OnStoreInit {
+export class KulturpassOrderModalStore
+ extends ComponentStore
+ implements OnStoreInit
+{
private _checkoutService = inject(DomainCheckoutService);
private _branchService = inject(BranchService);
private _authService = inject(AuthService);
@@ -87,23 +96,33 @@ export class KulturpassOrderModalStore extends ComponentStore state.order);
- readonly updateCheckout = this.updater((state, checkout: CheckoutDTO) => ({ ...state, checkout }));
+ readonly updateCheckout = this.updater((state, checkout: CheckoutDTO) => ({
+ ...state,
+ checkout,
+ }));
- readonly updateOrder = this.updater((state, order: OrderDTO) => ({ ...state, order }));
+ readonly updateOrder = this.updater((state, order: OrderDTO) => ({
+ ...state,
+ order,
+ }));
readonly fetchShoppingCart$ = this.select((state) => state.fetchShoppingCart);
- readonly updateFetchShoppingCart = this.updater((state, fetchShoppingCart: boolean) => ({
- ...state,
- fetchShoppingCart,
- }));
+ readonly updateFetchShoppingCart = this.updater(
+ (state, fetchShoppingCart: boolean) => ({
+ ...state,
+ fetchShoppingCart,
+ }),
+ );
readonly ordering$ = this.select((state) => state.ordering);
loadBranch = this.effect(($) =>
$.pipe(
switchMap(() =>
- this._branchService.BranchGetBranches({}).pipe(tapResponse(this.handleBranchResponse, this.handleBranchError)),
+ this._branchService
+ .BranchGetBranches({})
+ .pipe(tapResponse(this.handleBranchResponse, this.handleBranchError)),
),
),
);
@@ -111,31 +130,45 @@ export class KulturpassOrderModalStore extends ComponentStore {
const branchNumber = this._authService.getClaimByKey('branch_no');
- this.patchState({ branch: res.result.find((b) => b.branchNumber === branchNumber) });
+ this.patchState({
+ branch: res.result.find((b) => b.branchNumber === branchNumber),
+ });
};
handleBranchError = (err) => {
this._modal.error('Fehler beim Laden der Filiale', err);
};
- createShoppingCart = this.effect((orderItemListItem$: Observable) =>
- orderItemListItem$.pipe(
- tap((orderItemListItem) => {
- this.patchState({ orderItemListItem });
- this.updateFetchShoppingCart(true);
- }),
- switchMap((orderItemListItem) =>
- this._checkoutService
- .getShoppingCart({ processId: this.processId })
- .pipe(tapResponse(this.handleCreateShoppingCartResponse, this.handleCreateShoppingCartError)),
+ createShoppingCart = this.effect(
+ (orderItemListItem$: Observable) =>
+ orderItemListItem$.pipe(
+ tap((orderItemListItem) => {
+ this.patchState({ orderItemListItem });
+ this.updateFetchShoppingCart(true);
+ }),
+ switchMap((orderItemListItem) =>
+ this._checkoutService
+ .getShoppingCart({ processId: this.processId })
+ .pipe(
+ tapResponse(
+ this.handleCreateShoppingCartResponse,
+ this.handleCreateShoppingCartError,
+ ),
+ ),
+ ),
),
- ),
);
handleCreateShoppingCartResponse = (res: ShoppingCartDTO) => {
this.patchState({ shoppingCart: res });
- this._checkoutService.setBuyer({ processId: this.processId, buyer: this.order.buyer });
- this._checkoutService.setPayer({ processId: this.processId, payer: this.order.billing?.data });
+ this._checkoutService.setBuyer({
+ processId: this.processId,
+ buyer: this.order.buyer,
+ });
+ this._checkoutService.setPayer({
+ processId: this.processId,
+ payer: this.order.billing?.data,
+ });
this.updateFetchShoppingCart(false);
};
@@ -154,7 +187,9 @@ export class KulturpassOrderModalStore extends ComponentStore {};
+ onOrderSuccess = (
+ displayOrder: DisplayOrderDTO,
+ action: KeyValueDTOOfStringAndString[],
+ ) => {};
handleOrderError = (err: any) => {
this._modal.error('Fehler beim Bestellen', err);
@@ -215,8 +258,9 @@ export class KulturpassOrderModalStore extends ComponentStore getCatalogProductNumber(i?.data) === catalogProductNumber)?.data
- ?.quantity ?? 0
+ this.shoppingCart?.items?.find(
+ (i) => getCatalogProductNumber(i?.data) === catalogProductNumber,
+ )?.data?.quantity ?? 0
);
}
@@ -227,7 +271,11 @@ export class KulturpassOrderModalStore extends ComponentStore this.handleCanAddItemResponse({ item, result: results?.find((_) => true) }),
+ (results) =>
+ this.handleCanAddItemResponse({
+ item,
+ result: results?.find((_) => true),
+ }),
this.handleCanAddItemError,
),
),
@@ -235,14 +283,23 @@ export class KulturpassOrderModalStore extends ComponentStore {
+ handleCanAddItemResponse = ({
+ item,
+ result,
+ }: {
+ item: ItemDTO;
+ result: KulturPassResult;
+ }) => {
if (result?.canAdd) {
this.addItemToShoppingCart(item);
} else {
this._modal.open({
content: UiMessageModalComponent,
title: 'Artikel nicht fรถrderfรคhig',
- data: { message: result?.message, closeAction: 'ohne Artikel fortfahren' },
+ data: {
+ message: result?.message,
+ closeAction: 'ohne Artikel fortfahren',
+ },
});
}
};
@@ -254,14 +311,18 @@ export class KulturpassOrderModalStore extends ComponentStore) =>
item$.pipe(
mergeMap((item) => {
- const takeAwayAvailability$ = this._availabilityService.getTakeAwayAvailability({
- item: {
- ean: item.product.ean,
- itemId: item.id,
- price: item.catalogAvailability.price,
- },
- quantity: this.itemQuantityByCatalogProductNumber(getCatalogProductNumber(item)) + 1,
- });
+ const takeAwayAvailability$ =
+ this._availabilityService.getTakeAwayAvailability({
+ item: {
+ ean: item.product.ean,
+ itemId: item.id,
+ price: item.catalogAvailability.price,
+ },
+ quantity:
+ this.itemQuantityByCatalogProductNumber(
+ getCatalogProductNumber(item),
+ ) + 1,
+ });
const deliveryAvailability$ = this._availabilityService
.getDeliveryAvailability({
@@ -270,7 +331,10 @@ export class KulturpassOrderModalStore extends ComponentStore {
@@ -279,7 +343,10 @@ export class KulturpassOrderModalStore extends ComponentStore
- ([takeAwayAvailability, deliveryAvailability]: [AvailabilityDTO, AvailabilityDTO]) => {
+ ([takeAwayAvailability, deliveryAvailability]: [
+ AvailabilityDTO,
+ AvailabilityDTO,
+ ]) => {
let isPriceMaintained = item?.catalogAvailability?.priceMaintained;
let onlinePrice = -1;
if (deliveryAvailability) {
- isPriceMaintained = isPriceMaintained ?? deliveryAvailability['priceMaintained'] ?? false;
+ isPriceMaintained =
+ isPriceMaintained ?? deliveryAvailability['priceMaintained'] ?? false;
onlinePrice = deliveryAvailability?.price?.value?.value ?? -1;
}
// Preis und priceMaintained werden immer erst vom Katalog genommen. Bei nicht Verfรผgbarkeit greifen die anderen Availabilities
const offlinePrice =
- item?.catalogAvailability?.price?.value?.value ?? takeAwayAvailability?.price?.value?.value ?? -1;
+ item?.catalogAvailability?.price?.value?.value ??
+ takeAwayAvailability?.price?.value?.value ??
+ -1;
const availability = takeAwayAvailability;
- availability.price = item?.catalogAvailability?.price ?? takeAwayAvailability?.price;
+ availability.price =
+ item?.catalogAvailability?.price ?? takeAwayAvailability?.price;
/**
* Onlinepreis ist niedliger als der Offlinepreis
@@ -314,7 +388,11 @@ export class KulturpassOrderModalStore extends ComponentStore {
- return { ...state, availabilities: { ...state.availabilities, [data.catalogProductNumber]: data.availability } };
- });
+ setAvailability = this.updater(
+ (
+ state,
+ data: { catalogProductNumber: string; availability: AvailabilityDTO },
+ ) => {
+ return {
+ ...state,
+ availabilities: {
+ ...state.availabilities,
+ [data.catalogProductNumber]: data.availability,
+ },
+ };
+ },
+ );
getAvailability(catalogProductNumber: string): AvailabilityDTO | undefined {
return this.get((state) => state.availabilities[catalogProductNumber]);
}
- getAvailability$(catalogProductNumber: string): Observable {
+ getAvailability$(
+ catalogProductNumber: string,
+ ): Observable {
return this.select((state) => state.availabilities[catalogProductNumber]);
}
}
diff --git a/apps/isa-app/src/modal/purchase-options/constants.ts b/apps/isa-app/src/modal/purchase-options/constants.ts
index b1d18e917..a657eb1e9 100644
--- a/apps/isa-app/src/modal/purchase-options/constants.ts
+++ b/apps/isa-app/src/modal/purchase-options/constants.ts
@@ -1,33 +1,48 @@
-import { ItemType, PriceDTO, PriceValueDTO, VATValueDTO } from '@generated/swagger/checkout-api';
-import { OrderType, PurchaseOption } from './store';
-
-export const PURCHASE_OPTIONS: PurchaseOption[] = [
- 'in-store',
- 'pickup',
- 'delivery',
- 'dig-delivery',
- 'b2b-delivery',
- 'download',
-];
-
-export const DELIVERY_PURCHASE_OPTIONS: PurchaseOption[] = ['delivery', 'dig-delivery', 'b2b-delivery'];
-
-export const PURCHASE_OPTION_TO_ORDER_TYPE: { [purchaseOption: string]: OrderType } = {
- 'in-store': 'Rรผcklage',
- pickup: 'Abholung',
- delivery: 'Versand',
- 'dig-delivery': 'Versand',
- 'b2b-delivery': 'Versand',
-};
-
-export const GIFT_CARD_TYPE = 66560 as ItemType;
-
-export const DEFAULT_PRICE_DTO: PriceDTO = { value: { value: undefined }, vat: { vatType: 0 } };
-
-export const DEFAULT_PRICE_VALUE: PriceValueDTO = { value: 0, currency: 'EUR' };
-
-export const DEFAULT_VAT_VALUE: VATValueDTO = { value: 0 };
-
-export const GIFT_CARD_MAX_PRICE = 200;
-
-export const PRICE_PATTERN = /^\d+(,\d{1,2})?$/;
+import {
+ ItemType,
+ PriceDTO,
+ PriceValueDTO,
+ VATValueDTO,
+} from '@generated/swagger/checkout-api';
+import { PurchaseOption } from './store';
+import { OrderType } from '@isa/checkout/data-access';
+
+export const PURCHASE_OPTIONS: PurchaseOption[] = [
+ 'in-store',
+ 'pickup',
+ 'delivery',
+ 'dig-delivery',
+ 'b2b-delivery',
+ 'download',
+];
+
+export const DELIVERY_PURCHASE_OPTIONS: PurchaseOption[] = [
+ 'delivery',
+ 'dig-delivery',
+ 'b2b-delivery',
+];
+
+export const PURCHASE_OPTION_TO_ORDER_TYPE: {
+ [purchaseOption: string]: OrderType;
+} = {
+ 'in-store': 'Rรผcklage',
+ 'pickup': 'Abholung',
+ 'delivery': 'Versand',
+ 'dig-delivery': 'Versand',
+ 'b2b-delivery': 'Versand',
+};
+
+export const GIFT_CARD_TYPE = 66560 as ItemType;
+
+export const DEFAULT_PRICE_DTO: PriceDTO = {
+ value: { value: undefined },
+ vat: { vatType: 0 },
+};
+
+export const DEFAULT_PRICE_VALUE: PriceValueDTO = { value: 0, currency: 'EUR' };
+
+export const DEFAULT_VAT_VALUE: VATValueDTO = { value: 0 };
+
+export const GIFT_CARD_MAX_PRICE = 200;
+
+export const PRICE_PATTERN = /^\d+(,\d{1,2})?$/;
diff --git a/apps/isa-app/src/modal/purchase-options/purchase-options-list-item/purchase-options-list-item.component.html b/apps/isa-app/src/modal/purchase-options/purchase-options-list-item/purchase-options-list-item.component.html
index ee19a4520..c0fb6593b 100644
--- a/apps/isa-app/src/modal/purchase-options/purchase-options-list-item/purchase-options-list-item.component.html
+++ b/apps/isa-app/src/modal/purchase-options/purchase-options-list-item/purchase-options-list-item.component.html
@@ -1,185 +1,268 @@
-
-
-
-
-
-
- {{ product?.contributors }}
-
-
- {{ product?.name }}
-
-
-
- {{ product?.formatDetail }}
-
-
- {{ product?.manufacturer }}
- @if (product?.manufacturer && product?.ean) {
- |
- }
- {{ product?.ean }}
-
-
- {{ product?.volume }}
- @if (product?.volume && product?.publicationDate) {
- |
- }
- {{ product?.publicationDate | date: 'dd. MMMM yyyy' }}
-
-
- @if ((availabilities$ | async)?.length) {
-
Verfรผgbar als
- }
- @for (availability of availabilities$ | async; track availability) {
-
-
- @switch (availability.purchaseOption) {
- @case ('delivery') {
-
- {{ availability.data.estimatedDelivery?.start | date: 'EE dd.MM.' }}
- -
- {{ availability.data.estimatedDelivery?.stop | date: 'EE dd.MM.' }}
- }
- @case ('dig-delivery') {
-
- {{ availability.data.estimatedDelivery?.start | date: 'EE dd.MM.' }}
- -
- {{ availability.data.estimatedDelivery?.stop | date: 'EE dd.MM.' }}
- }
- @case ('b2b-delivery') {
-
- {{ availability.data.estimatedShippingDate | date: 'dd. MMMM yyyy' }}
- }
- @case ('pickup') {
-
- {{ availability.data.estimatedShippingDate | date: 'dd. MMMM yyyy' }}
-
- {{ availability.data?.orderDeadline | orderDeadline }}
-
- }
- @case ('in-store') {
-
- {{ availability.data.inStock }}x
- @if (isEVT) {
- ab {{ isEVT | date: 'dd. MMMM yyyy' }}
- } @else {
- ab sofort
- }
- }
- @case ('download') {
-
- Download
- }
- }
-
-
- }
-
-
-
-
-
- @if (canEditVat$ | async) {
-
- @for (vat of vats$ | async; track vat) {
-
- }
-
- }
- @if (canEditPrice$ | async) {
-
-
- @if (priceFormControl?.invalid && priceFormControl?.dirty) {
-
- }
-
-
- EUR
- Preis ist ungรผltig
- Preis ist ungรผltig
- Preis ist ungรผltig
- Preis ist ungรผltig
-
- } @else {
- {{ priceValue$ | async | currency: 'EUR' : 'code' }}
- }
-
-
- Tragen Sie hier den
-
- Gutscheinbetrag ein.
-
-
-
-
-
- @if ((canAddResult$ | async)?.canAdd) {
-
- }
-
-
- @if (canAddResult$ | async; as canAddResult) {
- @if (!canAddResult.canAdd) {
-
- {{ canAddResult.message }}
-
- }
- }
-
- @if (showMaxAvailableQuantity$ | async) {
-
- {{ (availability$ | async)?.inStock }} Exemplare sofort lieferbar
-
- }
- @if (showNotAvailable$ | async) {
-
Derzeit nicht bestellbar
- }
-
-
-
+
+
+
+
+
+
+ {{ product?.contributors }}
+
+
+ {{ product?.name }}
+
+
+
+ {{ product?.formatDetail }}
+
+
+ {{ product?.manufacturer }}
+ @if (product?.manufacturer && product?.ean) {
+ |
+ }
+ {{ product?.ean }}
+
+
+ {{ product?.volume }}
+ @if (product?.volume && product?.publicationDate) {
+ |
+ }
+ {{ product?.publicationDate | date: 'dd. MMMM yyyy' }}
+
+
+ @if ((availabilities$ | async)?.length) {
+
Verfรผgbar als
+ }
+ @for (availability of availabilities$ | async; track availability) {
+
+
+ @switch (availability.purchaseOption) {
+ @case ('delivery') {
+
+ {{
+ availability.data.estimatedDelivery?.start | date: 'EE dd.MM.'
+ }}
+ -
+ {{
+ availability.data.estimatedDelivery?.stop | date: 'EE dd.MM.'
+ }}
+ }
+ @case ('dig-delivery') {
+
+ {{
+ availability.data.estimatedDelivery?.start | date: 'EE dd.MM.'
+ }}
+ -
+ {{
+ availability.data.estimatedDelivery?.stop | date: 'EE dd.MM.'
+ }}
+ }
+ @case ('b2b-delivery') {
+
+ {{
+ availability.data.estimatedShippingDate
+ | date: 'dd. MMMM yyyy'
+ }}
+ }
+ @case ('pickup') {
+
+ {{
+ availability.data.estimatedShippingDate
+ | date: 'dd. MMMM yyyy'
+ }}
+
+ {{ availability.data?.orderDeadline | orderDeadline }}
+
+ }
+ @case ('in-store') {
+
+ {{ availability.data.inStock }}x
+ @if (isEVT) {
+ ab {{ isEVT | date: 'dd. MMMM yyyy' }}
+ } @else {
+ ab sofort
+ }
+ }
+ @case ('download') {
+
+ Download
+ }
+ }
+
+
+ }
+
+
+
+
+
+ @if (showRedemptionPoints()) {
+ Einlรถsen fรผr:
+ {{
+ redemptionPoints() * quantityFormControl.value
+ }}
+ Lesepunkte
+ } @else {
+ @if (canEditVat$ | async) {
+
+ @for (vat of vats$ | async; track vat) {
+
+ }
+
+ }
+ @if (canEditPrice$ | async) {
+
+
+ @if (priceFormControl?.invalid && priceFormControl?.dirty) {
+
+ }
+
+
+ EUR
+ Preis ist ungรผltig
+ Preis ist ungรผltig
+ Preis ist ungรผltig
+ Preis ist ungรผltig
+
+ } @else {
+ {{ priceValue$ | async | currency: 'EUR' : 'code' }}
+ }
+ }
+
+ Tragen Sie hier den
+
+ Gutscheinbetrag ein.
+
+
+
+
+
+ @if ((canAddResult$ | async)?.canAdd) {
+
+ }
+
+
+ @if (canAddResult$ | async; as canAddResult) {
+ @if (!canAddResult.canAdd) {
+
+ {{ canAddResult.message }}
+
+ }
+ }
+
+ @if (showMaxAvailableQuantity$ | async) {
+
+ {{ (availability$ | async)?.inStock }} Exemplare sofort lieferbar
+
+ }
+ @if (showNotAvailable$ | async) {
+
Derzeit nicht bestellbar
+ }
+
+
+
+@if (showLowStockMessage()) {
+
+
+
Geringer Bestand - Artikel holen vor Abschluss
+
+}
diff --git a/apps/isa-app/src/modal/purchase-options/purchase-options-list-item/purchase-options-list-item.component.ts b/apps/isa-app/src/modal/purchase-options/purchase-options-list-item/purchase-options-list-item.component.ts
index 68e76960e..ab6f61d40 100644
--- a/apps/isa-app/src/modal/purchase-options/purchase-options-list-item/purchase-options-list-item.component.ts
+++ b/apps/isa-app/src/modal/purchase-options/purchase-options-list-item/purchase-options-list-item.component.ts
@@ -1,349 +1,467 @@
-import { CommonModule } from '@angular/common';
-import { Component, ChangeDetectionStrategy, Input, OnInit, OnDestroy, OnChanges, SimpleChanges } from '@angular/core';
-import { FormControl, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
-import { ProductImageModule } from '@cdn/product-image';
-import { InputControlModule } from '@shared/components/input-control';
-import { ElementLifecycleModule } from '@shared/directives/element-lifecycle';
-import { UiCommonModule, UiOverlayTriggerDirective } from '@ui/common';
-import { UiQuantityDropdownModule } from '@ui/quantity-dropdown';
-import { UiSpinnerModule } from '@ui/spinner';
-import { UiTooltipModule } from '@ui/tooltip';
-import { combineLatest, ReplaySubject, Subscription } from 'rxjs';
-import { IconComponent } from '@shared/components/icon';
-import { map, take, shareReplay, startWith, switchMap, withLatestFrom } from 'rxjs/operators';
-import { GIFT_CARD_MAX_PRICE, PRICE_PATTERN } from '../constants';
-import { Item, PurchaseOptionsStore, isItemDTO, isShoppingCartItemDTO } from '../store';
-import { OrderDeadlinePipeModule } from '@shared/pipes/order-deadline';
-import { UiSelectModule } from '@ui/select';
-import { KeyValueDTOOfStringAndString } from '@generated/swagger/cat-search-api';
-import { ScaleContentComponent } from '@shared/components/scale-content';
-import moment from 'moment';
-
-@Component({
- selector: 'shared-purchase-options-list-item',
- templateUrl: 'purchase-options-list-item.component.html',
- styleUrls: ['purchase-options-list-item.component.css'],
- changeDetection: ChangeDetectionStrategy.OnPush,
- imports: [
- CommonModule,
- UiQuantityDropdownModule,
- UiSelectModule,
- ProductImageModule,
- IconComponent,
- UiSpinnerModule,
- ReactiveFormsModule,
- InputControlModule,
- FormsModule,
- ElementLifecycleModule,
- UiTooltipModule,
- UiCommonModule,
- ScaleContentComponent,
- OrderDeadlinePipeModule,
- ],
- host: { class: 'shared-purchase-options-list-item' },
-})
-export class PurchaseOptionsListItemComponent implements OnInit, OnDestroy, OnChanges {
- private _subscriptions = new Subscription();
-
- private _itemSubject = new ReplaySubject- (1);
-
- @Input() item: Item;
-
- get item$() {
- return this._itemSubject.asObservable();
- }
-
- get product() {
- return this.item.product;
- }
-
- quantityFormControl = new FormControl
(null);
-
- private readonly _giftCardValidators = [
- Validators.required,
- Validators.min(1),
- Validators.max(GIFT_CARD_MAX_PRICE),
- Validators.pattern(PRICE_PATTERN),
- ];
-
- private readonly _defaultValidators = [
- Validators.required,
- Validators.min(0.01),
- Validators.max(999.99),
- Validators.pattern(PRICE_PATTERN),
- ];
-
- priceFormControl = new FormControl(null);
-
- manualVatFormControl = new FormControl('', [Validators.required]);
-
- selectedFormControl = new FormControl(false);
-
- availabilities$ = this.item$.pipe(switchMap((item) => this._store.getAvailabilitiesForItem$(item.id)));
-
- availability$ = combineLatest([this.item$, this._store.purchaseOption$]).pipe(
- switchMap(([item, purchaseOption]) => this._store.getAvailabilityWithPurchaseOption$(item.id, purchaseOption)),
- map((availability) => availability?.data),
- );
-
- price$ = this.item$.pipe(switchMap((item) => this._store.getPrice$(item.id)));
-
- priceValue$ = this.price$.pipe(map((price) => price?.value?.value));
-
- // Ticket #4074 analog zu Ticket #2244
- // take(2) um die Response des Katalogpreises und danach um die Response der OLAs abzuwarten
- // Logik gilt ausschlieรlich fรผr Archivartikel
- setManualPrice$ = this.price$.pipe(
- take(2),
- map((price) => {
- // Logik nur beim Hinzufรผgen รผber Kaufoptionen, da รผber รndern im Warenkorb die Info fehlt ob das jeweilige ShoppingCartItem ein Archivartikel ist oder nicht
- const features = this.item?.features as KeyValueDTOOfStringAndString[];
- if (!!features && Array.isArray(features)) {
- const isArchive = !!features?.find((feature) => feature?.enabled === true && feature?.key === 'ARC');
- return isArchive ? !price?.value?.value || price?.vat === undefined : false;
- }
- return false;
- }),
- );
-
- vats$ = this._store.vats$.pipe(shareReplay());
-
- priceVat$ = this.price$.pipe(map((price) => price?.vat?.vatType));
-
- canAddResult$ = this.item$.pipe(
- switchMap((item) => this._store.getCanAddResultForItemAndCurrentPurchaseOption$(item.id)),
- );
-
- canEditPrice$ = this.item$.pipe(
- switchMap((item) => combineLatest([this.canAddResult$, this._store.getCanEditPrice$(item.id)])),
- map(([canAddResult, canEditPrice]) => canAddResult?.canAdd && canEditPrice),
- );
-
- canEditVat$ = this.item$.pipe(
- switchMap((item) => combineLatest([this.canAddResult$, this._store.getCanEditVat$(item.id)])),
- map(([canAddResult, canEditVat]) => canAddResult?.canAdd && canEditVat),
- );
-
- isGiftCard$ = this.item$.pipe(switchMap((item) => this._store.getIsGiftCard$(item.id)));
-
- maxSelectableQuantity$ = combineLatest([this._store.purchaseOption$, this.availability$]).pipe(
- map(([purchaseOption, availability]) => {
- if (purchaseOption === 'in-store') {
- return availability?.inStock;
- }
-
- return 999;
- }),
- startWith(999),
- );
-
- showMaxAvailableQuantity$ = combineLatest([this._store.purchaseOption$, this.availability$, this.item$]).pipe(
- map(([purchaseOption, availability, item]) => {
- if (purchaseOption === 'pickup' && availability?.inStock < item.quantity) {
- return true;
- }
-
- return false;
- }),
- );
-
- fetchingAvailabilities$ = this.item$
- .pipe(switchMap((item) => this._store.getFetchingAvailabilitiesForItem$(item.id)))
- .pipe(map((fetchingAvailabilities) => fetchingAvailabilities.length > 0));
-
- showNotAvailable$ = combineLatest([this.availabilities$, this.fetchingAvailabilities$]).pipe(
- map(([availabilities, fetchingAvailabilities]) => {
- if (fetchingAvailabilities) {
- return false;
- }
-
- if (availabilities.length === 0) {
- return true;
- }
-
- return false;
- }),
- );
-
- // Ticket #4813 Artikeldetailseite // EVT-Datum bei der Kaufoption Rรผcklage anzeigen
- get isEVT() {
- // Einstieg รผber Kaufoptionen - Hier wird die Katalogavailability verwendet die am ItemDTO hรคngt
- if (isItemDTO(this.item, this._store.type)) {
- const firstDayOfSale = this.item?.catalogAvailability?.firstDayOfSale;
- return this.firstDayOfSaleBiggerThanToday(firstDayOfSale);
- }
-
- // Einstieg รผber Warenkorb - Da wir hier ein ShoppingCartItemDTO haben werden hier die Katalogdaten neu gefetched und eine Katalogavailability drangehรคngt
- if (isShoppingCartItemDTO(this.item, this._store.type)) {
- const catalogAvailabilities = this._store.availabilities?.filter(
- (availability) => availability?.purchaseOption === 'catalog',
- );
- // #4813 Fix: Hier muss als Kriterium auf EAN statt itemId verglichen werden, denn ein ShoppingCartItemDTO (this.item) hat eine andere ItemId wie das ItemDTO (availability.itemId)
- const firstDayOfSale = catalogAvailabilities?.find(
- (availability) => this.item?.product?.ean === availability?.ean,
- )?.data?.firstDayOfSale;
- return this.firstDayOfSaleBiggerThanToday(firstDayOfSale);
- }
-
- return undefined;
- }
-
- constructor(private _store: PurchaseOptionsStore) {}
-
- firstDayOfSaleBiggerThanToday(firstDayOfSale: string): Date {
- if (!!firstDayOfSale && moment(firstDayOfSale)?.isAfter(moment())) {
- return moment(firstDayOfSale).toDate();
- }
- return undefined;
- }
-
- onPriceInputInit(target: HTMLElement, overlayTrigger: UiOverlayTriggerDirective) {
- if (this._store.getIsGiftCard(this.item.id)) {
- overlayTrigger.open();
- }
-
- target?.focus();
- }
-
- // Wichtig fรผr das korrekte Setzen des Preises an das Item fรผr den Endpoint request
- parsePrice(value: string) {
- if (PRICE_PATTERN.test(value)) {
- return parseFloat(value.replace(',', '.'));
- }
- }
-
- stringifyPrice(value: number) {
- if (!value) return '';
-
- const price = value.toFixed(2).replace('.', ',');
- if (price.includes(',')) {
- const [integer, decimal] = price.split(',');
- return `${integer},${decimal.padEnd(2, '0')}`;
- }
-
- return price;
- }
-
- ngOnInit(): void {
- this.initPriceValidatorSubscription();
- this.initQuantitySubscription();
- this.initPriceSubscription();
- this.initVatSubscription();
- this.initSelectedSubscription();
- }
-
- ngOnChanges({ item }: SimpleChanges) {
- if (item) {
- this._itemSubject.next(this.item);
- }
- }
-
- ngOnDestroy(): void {
- this._itemSubject.complete();
- this._subscriptions.unsubscribe();
- }
-
- initPriceValidatorSubscription() {
- const sub = this.item$.pipe(switchMap((item) => this._store.getIsGiftCard$(item.id))).subscribe((isGiftCard) => {
- if (isGiftCard) {
- this.priceFormControl.setValidators(this._giftCardValidators);
- } else {
- this.priceFormControl.setValidators(this._defaultValidators);
- }
- });
-
- this._subscriptions.add(sub);
- }
-
- initQuantitySubscription() {
- const sub = this.item$.subscribe((item) => {
- if (this.quantityFormControl.value !== item.quantity) {
- this.quantityFormControl.setValue(item.quantity);
- }
- });
-
- const valueChangesSub = this.quantityFormControl.valueChanges.subscribe((quantity) => {
- if (this.item.quantity !== quantity) {
- this._store.setItemQuantity(this.item.id, quantity);
- }
- });
-
- this._subscriptions.add(sub);
- this._subscriptions.add(valueChangesSub);
- }
-
- initPriceSubscription() {
- const sub = combineLatest([this.canEditPrice$, this.price$]).subscribe(([canEditPrice, price]) => {
- if (!canEditPrice) {
- return;
- }
-
- const priceStr = this.stringifyPrice(price?.value?.value);
- if (priceStr === '') return;
-
- if (this.parsePrice(this.priceFormControl.value) !== price?.value?.value) {
- this.priceFormControl.setValue(priceStr);
- }
- });
-
- const valueChangesSub = combineLatest([this.canEditPrice$, this.priceFormControl.valueChanges]).subscribe(
- ([canEditPrice, value]) => {
- if (!canEditPrice) {
- return;
- }
-
- const price = this._store.getPrice(this.item.id);
- const parsedPrice = this.parsePrice(value);
-
- if (!parsedPrice) {
- this._store.setPrice(this.item.id, null);
- return;
- }
-
- if (price[this.item.id] !== parsedPrice) {
- this._store.setPrice(this.item.id, this.parsePrice(value));
- }
- },
- );
- this._subscriptions.add(sub);
- this._subscriptions.add(valueChangesSub);
- }
-
- initVatSubscription() {
- const valueChangesSub = this.manualVatFormControl.valueChanges
- .pipe(withLatestFrom(this.vats$))
- .subscribe(([formVatType, vats]) => {
- const price = this._store.getPrice(this.item.id);
-
- const vat = vats.find((vat) => vat?.vatType === Number(formVatType));
-
- if (!vat) {
- this._store.setVat(this.item.id, null);
- return;
- }
-
- if (price[this.item.id]?.vat?.vatType !== vat?.vatType) {
- this._store.setVat(this.item.id, vat);
- }
- });
- this._subscriptions.add(valueChangesSub);
- }
-
- initSelectedSubscription() {
- const sub = this.item$
- .pipe(switchMap((item) => this._store.selectedItemIds$.pipe(map((ids) => ids.includes(item.id)))))
- .subscribe((selected) => {
- if (this.selectedFormControl.value !== selected) {
- this.selectedFormControl.setValue(selected);
- }
- });
- const valueChangesSub = this.selectedFormControl.valueChanges.subscribe((selected) => {
- const current = this._store.selectedItemIds.includes(this.item.id);
- if (current !== selected) {
- this._store.setSelectedItem(this.item.id, selected);
- }
- });
- this._subscriptions.add(sub);
- this._subscriptions.add(valueChangesSub);
- }
-}
+import { CommonModule } from '@angular/common';
+import {
+ Component,
+ ChangeDetectionStrategy,
+ OnInit,
+ OnDestroy,
+ OnChanges,
+ SimpleChanges,
+ computed,
+ input,
+} from '@angular/core';
+import {
+ FormControl,
+ FormsModule,
+ ReactiveFormsModule,
+ Validators,
+} from '@angular/forms';
+import { ProductImageModule } from '@cdn/product-image';
+import { InputControlModule } from '@shared/components/input-control';
+import { ElementLifecycleModule } from '@shared/directives/element-lifecycle';
+import { UiCommonModule, UiOverlayTriggerDirective } from '@ui/common';
+import { UiQuantityDropdownModule } from '@ui/quantity-dropdown';
+import { UiSpinnerModule } from '@ui/spinner';
+import { UiTooltipModule } from '@ui/tooltip';
+import { combineLatest, ReplaySubject, Subscription } from 'rxjs';
+import { IconComponent } from '@shared/components/icon';
+import {
+ map,
+ take,
+ shareReplay,
+ startWith,
+ switchMap,
+ withLatestFrom,
+} from 'rxjs/operators';
+import { GIFT_CARD_MAX_PRICE, PRICE_PATTERN } from '../constants';
+import {
+ Item,
+ PurchaseOptionsStore,
+ isItemDTO,
+ isShoppingCartItemDTO,
+} from '../store';
+import { OrderDeadlinePipeModule } from '@shared/pipes/order-deadline';
+import { UiSelectModule } from '@ui/select';
+import { KeyValueDTOOfStringAndString } from '@generated/swagger/cat-search-api';
+import { ScaleContentComponent } from '@shared/components/scale-content';
+import moment from 'moment';
+import { toSignal } from '@angular/core/rxjs-interop';
+import { NgIcon, provideIcons } from '@ng-icons/core';
+import { isaOtherInfo } from '@isa/icons';
+
+@Component({
+ selector: 'shared-purchase-options-list-item',
+ templateUrl: 'purchase-options-list-item.component.html',
+ styleUrls: ['purchase-options-list-item.component.css'],
+ changeDetection: ChangeDetectionStrategy.OnPush,
+ imports: [
+ CommonModule,
+ UiQuantityDropdownModule,
+ UiSelectModule,
+ ProductImageModule,
+ IconComponent,
+ UiSpinnerModule,
+ ReactiveFormsModule,
+ InputControlModule,
+ FormsModule,
+ ElementLifecycleModule,
+ UiTooltipModule,
+ UiCommonModule,
+ ScaleContentComponent,
+ OrderDeadlinePipeModule,
+ NgIcon,
+ ],
+ host: { class: 'shared-purchase-options-list-item' },
+ providers: [provideIcons({ isaOtherInfo })],
+})
+export class PurchaseOptionsListItemComponent
+ implements OnInit, OnDestroy, OnChanges
+{
+ private _subscriptions = new Subscription();
+
+ private _itemSubject = new ReplaySubject- (1);
+
+ item = input.required
- ();
+
+ get item$() {
+ return this._itemSubject.asObservable();
+ }
+
+ get product() {
+ return this.item().product;
+ }
+
+ redemptionPoints = computed(() => {
+ const item = this.item();
+ if (isShoppingCartItemDTO(item, this._store.type)) {
+ return item.loyalty?.value;
+ }
+
+ return item.redemptionPoints;
+ });
+
+ showRedemptionPoints = toSignal(this._store.useRedemptionPoints$);
+
+ quantityFormControl = new FormControl
(null);
+
+ private readonly _giftCardValidators = [
+ Validators.required,
+ Validators.min(1),
+ Validators.max(GIFT_CARD_MAX_PRICE),
+ Validators.pattern(PRICE_PATTERN),
+ ];
+
+ private readonly _defaultValidators = [
+ Validators.required,
+ Validators.min(0.01),
+ Validators.max(999.99),
+ Validators.pattern(PRICE_PATTERN),
+ ];
+
+ priceFormControl = new FormControl(null);
+
+ manualVatFormControl = new FormControl('', [Validators.required]);
+
+ selectedFormControl = new FormControl(false);
+
+ availabilities$ = this.item$.pipe(
+ switchMap((item) => this._store.getAvailabilitiesForItem$(item.id)),
+ );
+
+ availability$ = combineLatest([this.item$, this._store.purchaseOption$]).pipe(
+ switchMap(([item, purchaseOption]) =>
+ this._store.getAvailabilityWithPurchaseOption$(item.id, purchaseOption),
+ ),
+ map((availability) => availability?.data),
+ );
+
+ availability = toSignal(this.availability$);
+
+ price$ = this.item$.pipe(switchMap((item) => this._store.getPrice$(item.id)));
+
+ priceValue$ = this.price$.pipe(map((price) => price?.value?.value));
+
+ // Ticket #4074 analog zu Ticket #2244
+ // take(2) um die Response des Katalogpreises und danach um die Response der OLAs abzuwarten
+ // Logik gilt ausschlieรlich fรผr Archivartikel
+ setManualPrice$ = this.price$.pipe(
+ take(2),
+ map((price) => {
+ // Logik nur beim Hinzufรผgen รผber Kaufoptionen, da รผber รndern im Warenkorb die Info fehlt ob das jeweilige ShoppingCartItem ein Archivartikel ist oder nicht
+ const features = this.item().features as KeyValueDTOOfStringAndString[];
+ if (!!features && Array.isArray(features)) {
+ const isArchive = !!features?.find(
+ (feature) => feature?.enabled === true && feature?.key === 'ARC',
+ );
+ return isArchive
+ ? !price?.value?.value || price?.vat === undefined
+ : false;
+ }
+ return false;
+ }),
+ );
+
+ vats$ = this._store.vats$.pipe(shareReplay());
+
+ priceVat$ = this.price$.pipe(map((price) => price?.vat?.vatType));
+
+ canAddResult$ = this.item$.pipe(
+ switchMap((item) =>
+ this._store.getCanAddResultForItemAndCurrentPurchaseOption$(item.id),
+ ),
+ );
+
+ canEditPrice$ = this.item$.pipe(
+ switchMap((item) =>
+ combineLatest([
+ this.canAddResult$,
+ this._store.getCanEditPrice$(item.id),
+ ]),
+ ),
+ map(([canAddResult, canEditPrice]) => canAddResult?.canAdd && canEditPrice),
+ );
+
+ canEditVat$ = this.item$.pipe(
+ switchMap((item) =>
+ combineLatest([this.canAddResult$, this._store.getCanEditVat$(item.id)]),
+ ),
+ map(([canAddResult, canEditVat]) => canAddResult?.canAdd && canEditVat),
+ );
+
+ isGiftCard$ = this.item$.pipe(
+ switchMap((item) => this._store.getIsGiftCard$(item.id)),
+ );
+
+ maxSelectableQuantity$ = combineLatest([
+ this._store.purchaseOption$,
+ this.availability$,
+ ]).pipe(
+ map(([purchaseOption, availability]) => {
+ if (purchaseOption === 'in-store') {
+ return availability?.inStock;
+ }
+
+ return 999;
+ }),
+ startWith(999),
+ );
+
+ showMaxAvailableQuantity$ = combineLatest([
+ this._store.purchaseOption$,
+ this.availability$,
+ this.item$,
+ ]).pipe(
+ map(([purchaseOption, availability, item]) => {
+ if (
+ purchaseOption === 'pickup' &&
+ availability?.inStock < item.quantity
+ ) {
+ return true;
+ }
+
+ return false;
+ }),
+ );
+
+ fetchingAvailabilities$ = this.item$
+ .pipe(
+ switchMap((item) =>
+ this._store.getFetchingAvailabilitiesForItem$(item.id),
+ ),
+ )
+ .pipe(map((fetchingAvailabilities) => fetchingAvailabilities.length > 0));
+
+ showNotAvailable$ = combineLatest([
+ this.availabilities$,
+ this.fetchingAvailabilities$,
+ ]).pipe(
+ map(([availabilities, fetchingAvailabilities]) => {
+ if (fetchingAvailabilities) {
+ return false;
+ }
+
+ if (availabilities.length === 0) {
+ return true;
+ }
+
+ return false;
+ }),
+ );
+
+ // Ticket #4813 Artikeldetailseite // EVT-Datum bei der Kaufoption Rรผcklage anzeigen
+ get isEVT() {
+ // Einstieg รผber Kaufoptionen - Hier wird die Katalogavailability verwendet die am ItemDTO hรคngt
+ if (isItemDTO(this.item, this._store.type)) {
+ const firstDayOfSale = this.item?.catalogAvailability?.firstDayOfSale;
+ return this.firstDayOfSaleBiggerThanToday(firstDayOfSale);
+ }
+
+ // Einstieg รผber Warenkorb - Da wir hier ein ShoppingCartItemDTO haben werden hier die Katalogdaten neu gefetched und eine Katalogavailability drangehรคngt
+ if (isShoppingCartItemDTO(this.item, this._store.type)) {
+ const catalogAvailabilities = this._store.availabilities?.filter(
+ (availability) => availability?.purchaseOption === 'catalog',
+ );
+ // #4813 Fix: Hier muss als Kriterium auf EAN statt itemId verglichen werden, denn ein ShoppingCartItemDTO (this.item) hat eine andere ItemId wie das ItemDTO (availability.itemId)
+ const firstDayOfSale = catalogAvailabilities?.find(
+ (availability) => this.item().product?.ean === availability?.ean,
+ )?.data?.firstDayOfSale;
+ return this.firstDayOfSaleBiggerThanToday(firstDayOfSale);
+ }
+
+ return undefined;
+ }
+
+ useRedemptionPoints = toSignal(this._store.useRedemptionPoints$);
+
+ purchaseOption = toSignal(this._store.purchaseOption$);
+
+ isReservePurchaseOption = computed(() => {
+ return this.purchaseOption() === 'in-store';
+ });
+
+ showLowStockMessage = computed(() => {
+ return (
+ this.useRedemptionPoints() &&
+ this.isReservePurchaseOption() &&
+ (!this.availability() || this.availability().inStock < 2)
+ );
+ });
+
+ constructor(private _store: PurchaseOptionsStore) {}
+
+ firstDayOfSaleBiggerThanToday(firstDayOfSale: string): Date {
+ if (!!firstDayOfSale && moment(firstDayOfSale)?.isAfter(moment())) {
+ return moment(firstDayOfSale).toDate();
+ }
+ return undefined;
+ }
+
+ onPriceInputInit(
+ target: HTMLElement,
+ overlayTrigger: UiOverlayTriggerDirective,
+ ) {
+ if (this._store.getIsGiftCard(this.item().id)) {
+ overlayTrigger.open();
+ }
+
+ target?.focus();
+ }
+
+ // Wichtig fรผr das korrekte Setzen des Preises an das Item fรผr den Endpoint request
+ parsePrice(value: string) {
+ if (PRICE_PATTERN.test(value)) {
+ return parseFloat(value.replace(',', '.'));
+ }
+ }
+
+ stringifyPrice(value: number) {
+ if (!value) return '';
+
+ const price = value.toFixed(2).replace('.', ',');
+ if (price.includes(',')) {
+ const [integer, decimal] = price.split(',');
+ return `${integer},${decimal.padEnd(2, '0')}`;
+ }
+
+ return price;
+ }
+
+ ngOnInit(): void {
+ this.initPriceValidatorSubscription();
+ this.initQuantitySubscription();
+ this.initPriceSubscription();
+ this.initVatSubscription();
+ this.initSelectedSubscription();
+ }
+
+ ngOnChanges({ item }: SimpleChanges) {
+ if (item) {
+ this._itemSubject.next(this.item());
+ }
+ }
+
+ ngOnDestroy(): void {
+ this._itemSubject.complete();
+ this._subscriptions.unsubscribe();
+ }
+
+ initPriceValidatorSubscription() {
+ const sub = this.item$
+ .pipe(switchMap((item) => this._store.getIsGiftCard$(item.id)))
+ .subscribe((isGiftCard) => {
+ if (isGiftCard) {
+ this.priceFormControl.setValidators(this._giftCardValidators);
+ } else {
+ this.priceFormControl.setValidators(this._defaultValidators);
+ }
+ });
+
+ this._subscriptions.add(sub);
+ }
+
+ initQuantitySubscription() {
+ const sub = this.item$.subscribe((item) => {
+ if (this.quantityFormControl.value !== item.quantity) {
+ this.quantityFormControl.setValue(item.quantity);
+ }
+ });
+
+ const valueChangesSub = this.quantityFormControl.valueChanges.subscribe(
+ (quantity) => {
+ if (this.item().quantity !== quantity) {
+ this._store.setItemQuantity(this.item().id, quantity);
+ }
+ },
+ );
+
+ this._subscriptions.add(sub);
+ this._subscriptions.add(valueChangesSub);
+ }
+
+ initPriceSubscription() {
+ const sub = combineLatest([this.canEditPrice$, this.price$]).subscribe(
+ ([canEditPrice, price]) => {
+ if (!canEditPrice) {
+ return;
+ }
+
+ const priceStr = this.stringifyPrice(price?.value?.value);
+ if (priceStr === '') return;
+
+ if (
+ this.parsePrice(this.priceFormControl.value) !== price?.value?.value
+ ) {
+ this.priceFormControl.setValue(priceStr);
+ }
+ },
+ );
+
+ const valueChangesSub = combineLatest([
+ this.canEditPrice$,
+ this.priceFormControl.valueChanges,
+ ]).subscribe(([canEditPrice, value]) => {
+ if (!canEditPrice) {
+ return;
+ }
+
+ const price = this._store.getPrice(this.item().id);
+ const parsedPrice = this.parsePrice(value);
+
+ if (!parsedPrice) {
+ this._store.setPrice(this.item().id, null);
+ return;
+ }
+
+ if (price[this.item().id] !== parsedPrice) {
+ this._store.setPrice(this.item().id, this.parsePrice(value));
+ }
+ });
+ this._subscriptions.add(sub);
+ this._subscriptions.add(valueChangesSub);
+ }
+
+ initVatSubscription() {
+ const valueChangesSub = this.manualVatFormControl.valueChanges
+ .pipe(withLatestFrom(this.vats$))
+ .subscribe(([formVatType, vats]) => {
+ const price = this._store.getPrice(this.item().id);
+
+ const vat = vats.find((vat) => vat?.vatType === Number(formVatType));
+
+ if (!vat) {
+ this._store.setVat(this.item().id, null);
+ return;
+ }
+
+ if (price[this.item().id]?.vat?.vatType !== vat?.vatType) {
+ this._store.setVat(this.item().id, vat);
+ }
+ });
+ this._subscriptions.add(valueChangesSub);
+ }
+
+ initSelectedSubscription() {
+ const sub = this.item$
+ .pipe(
+ switchMap((item) =>
+ this._store.selectedItemIds$.pipe(
+ map((ids) => ids.includes(item.id)),
+ ),
+ ),
+ )
+ .subscribe((selected) => {
+ if (this.selectedFormControl.value !== selected) {
+ this.selectedFormControl.setValue(selected);
+ }
+ });
+ const valueChangesSub = this.selectedFormControl.valueChanges.subscribe(
+ (selected) => {
+ const current = this._store.selectedItemIds.includes(this.item().id);
+ if (current !== selected) {
+ this._store.setSelectedItem(this.item().id, selected);
+ }
+ },
+ );
+ this._subscriptions.add(sub);
+ this._subscriptions.add(valueChangesSub);
+ }
+}
diff --git a/apps/isa-app/src/modal/purchase-options/purchase-options-modal.component.ts b/apps/isa-app/src/modal/purchase-options/purchase-options-modal.component.ts
index 4fa991796..467339710 100644
--- a/apps/isa-app/src/modal/purchase-options/purchase-options-modal.component.ts
+++ b/apps/isa-app/src/modal/purchase-options/purchase-options-modal.component.ts
@@ -1,145 +1,181 @@
-import { Component, ChangeDetectionStrategy, OnInit, OnDestroy, TrackByFunction, HostBinding } from '@angular/core';
-import { UiModalRef } from '@ui/modal';
-import { PurchaseOptionsModalData } from './purchase-options-modal.data';
-
-import { PurchaseOptionsListHeaderComponent } from './purchase-options-list-header';
-import { PurchaseOptionsListItemComponent } from './purchase-options-list-item';
-import { CommonModule } from '@angular/common';
-import { Subject, zip } from 'rxjs';
-import {
- DeliveryPurchaseOptionTileComponent,
- DownloadPurchaseOptionTileComponent,
- InStorePurchaseOptionTileComponent,
- PickupPurchaseOptionTileComponent,
-} from './purchase-options-tile';
-import { isGiftCard, Item, PurchaseOption, PurchaseOptionsStore } from './store';
-import { delay, map, shareReplay, skip, switchMap, takeUntil, tap } from 'rxjs/operators';
-import { KeyValueDTOOfStringAndString } from '@generated/swagger/cat-search-api';
-import { provideComponentStore } from '@ngrx/component-store';
-
-@Component({
- selector: 'shared-purchase-options-modal',
- templateUrl: 'purchase-options-modal.component.html',
- styleUrls: ['purchase-options-modal.component.css'],
- changeDetection: ChangeDetectionStrategy.OnPush,
- providers: [provideComponentStore(PurchaseOptionsStore)],
- imports: [
- CommonModule,
- PurchaseOptionsListHeaderComponent,
- PurchaseOptionsListItemComponent,
- DeliveryPurchaseOptionTileComponent,
- InStorePurchaseOptionTileComponent,
- PickupPurchaseOptionTileComponent,
- DownloadPurchaseOptionTileComponent,
- ],
-})
-export class PurchaseOptionsModalComponent implements OnInit, OnDestroy {
- get type() {
- return this._uiModalRef.data.type;
- }
-
- @HostBinding('attr.data-loading')
- get fetchingData() {
- return this.store.fetchingAvailabilities.length > 0;
- }
-
- items$ = this.store.items$;
-
- hasPrice$ = this.items$.pipe(
- switchMap((items) =>
- items.map((item) => {
- let isArchive = false;
- const features = item?.features as KeyValueDTOOfStringAndString[];
- // Ticket #4074 analog zu Ticket #2244
- // Ob Archivartikel kann nur รผber Kaufoptionen herausgefunden werden, nicht รผber รndern im Warenkorb da am ShoppingCartItem das Archivartikel Feature fehlt
- if (!!features && Array.isArray(features)) {
- isArchive = !!features?.find((feature) => feature?.enabled === true && feature?.key === 'ARC');
- }
- return zip(
- this.store
- ?.getPrice$(item?.id)
- .pipe(
- map((price) =>
- isArchive
- ? !!price?.value?.value && price?.vat !== undefined && price?.vat?.value !== undefined
- : !!price?.value?.value,
- ),
- ),
- );
- }),
- ),
- switchMap((hasPrices) => hasPrices),
- map((hasPrices) => {
- const containsItemWithNoPrice = hasPrices?.filter((hasPrice) => hasPrice === false) ?? [];
- return containsItemWithNoPrice?.length === 0;
- }),
- );
-
- purchasingOptions$ = this.store.getPurchaseOptionsInAvailabilities$;
-
- isDownloadOnly$ = this.purchasingOptions$.pipe(
- map((purchasingOptions) => purchasingOptions.length === 1 && purchasingOptions[0] === 'download'),
- );
-
- isGiftCardOnly$ = this.store.items$.pipe(map((items) => items.every((item) => isGiftCard(item, this.store.type))));
-
- hasDownload$ = this.purchasingOptions$.pipe(map((purchasingOptions) => purchasingOptions.includes('download')));
-
- canContinue$ = this.store.canContinue$;
-
- private _onDestroy$ = new Subject();
-
- saving = false;
-
- constructor(
- private _uiModalRef: UiModalRef,
- public store: PurchaseOptionsStore,
- ) {
- this.store.initialize(this._uiModalRef.data);
- }
-
- ngOnInit(): void {
- this.items$.pipe(takeUntil(this._onDestroy$), skip(1), delay(100)).subscribe((items) => {
- if (items.length === 0) {
- this._uiModalRef.close();
- return;
- }
-
- if (this._uiModalRef.data?.preSelectOption?.option) {
- this.store.setPurchaseOption(this._uiModalRef.data?.preSelectOption?.option);
- }
- });
- }
-
- ngOnDestroy(): void {
- this._onDestroy$.next();
- this._onDestroy$.complete();
- }
-
- itemTrackBy: TrackByFunction- = (_, item) => item.id;
-
- showOption(option: PurchaseOption): boolean {
- return this._uiModalRef.data?.preSelectOption?.showOptionOnly
- ? this._uiModalRef.data?.preSelectOption?.option === option
- : true;
- }
-
- async save(action: string) {
- if (this.saving) {
- return;
- }
- this.saving = true;
-
- try {
- await this.store.save();
-
- if (this.store.items.length === 0) {
- this._uiModalRef.close(action);
- }
- } catch (error) {
- console.error(error);
- }
-
- this.saving = false;
- }
-}
+import {
+ Component,
+ ChangeDetectionStrategy,
+ OnInit,
+ OnDestroy,
+ TrackByFunction,
+ HostBinding,
+} from '@angular/core';
+import { UiModalRef } from '@ui/modal';
+import { PurchaseOptionsModalContext } from './purchase-options-modal.data';
+
+import { PurchaseOptionsListHeaderComponent } from './purchase-options-list-header';
+import { PurchaseOptionsListItemComponent } from './purchase-options-list-item';
+import { CommonModule } from '@angular/common';
+import { Subject, zip } from 'rxjs';
+import {
+ DeliveryPurchaseOptionTileComponent,
+ DownloadPurchaseOptionTileComponent,
+ InStorePurchaseOptionTileComponent,
+ PickupPurchaseOptionTileComponent,
+} from './purchase-options-tile';
+import {
+ isGiftCard,
+ Item,
+ PurchaseOption,
+ PurchaseOptionsStore,
+} from './store';
+import {
+ delay,
+ map,
+ shareReplay,
+ skip,
+ switchMap,
+ takeUntil,
+ tap,
+} from 'rxjs/operators';
+import { KeyValueDTOOfStringAndString } from '@generated/swagger/cat-search-api';
+import { provideComponentStore } from '@ngrx/component-store';
+
+@Component({
+ selector: 'shared-purchase-options-modal',
+ templateUrl: 'purchase-options-modal.component.html',
+ styleUrls: ['purchase-options-modal.component.css'],
+ changeDetection: ChangeDetectionStrategy.OnPush,
+ providers: [provideComponentStore(PurchaseOptionsStore)],
+ imports: [
+ CommonModule,
+ PurchaseOptionsListHeaderComponent,
+ PurchaseOptionsListItemComponent,
+ DeliveryPurchaseOptionTileComponent,
+ InStorePurchaseOptionTileComponent,
+ PickupPurchaseOptionTileComponent,
+ DownloadPurchaseOptionTileComponent,
+ ],
+})
+export class PurchaseOptionsModalComponent implements OnInit, OnDestroy {
+ get type() {
+ return this._uiModalRef.data.type;
+ }
+
+ @HostBinding('attr.data-loading')
+ get fetchingData() {
+ return this.store.fetchingAvailabilities.length > 0;
+ }
+
+ items$ = this.store.items$;
+
+ hasPrice$ = this.items$.pipe(
+ switchMap((items) =>
+ items.map((item) => {
+ let isArchive = false;
+ const features = item?.features as KeyValueDTOOfStringAndString[];
+ // Ticket #4074 analog zu Ticket #2244
+ // Ob Archivartikel kann nur รผber Kaufoptionen herausgefunden werden, nicht รผber รndern im Warenkorb da am ShoppingCartItem das Archivartikel Feature fehlt
+ if (!!features && Array.isArray(features)) {
+ isArchive = !!features?.find(
+ (feature) => feature?.enabled === true && feature?.key === 'ARC',
+ );
+ }
+ return zip(
+ this.store
+ ?.getPrice$(item?.id)
+ .pipe(
+ map((price) =>
+ isArchive
+ ? !!price?.value?.value &&
+ price?.vat !== undefined &&
+ price?.vat?.value !== undefined
+ : !!price?.value?.value,
+ ),
+ ),
+ );
+ }),
+ ),
+ switchMap((hasPrices) => hasPrices),
+ map((hasPrices) => {
+ const containsItemWithNoPrice =
+ hasPrices?.filter((hasPrice) => hasPrice === false) ?? [];
+ return containsItemWithNoPrice?.length === 0;
+ }),
+ );
+
+ purchasingOptions$ = this.store.getPurchaseOptionsInAvailabilities$;
+
+ isDownloadOnly$ = this.purchasingOptions$.pipe(
+ map(
+ (purchasingOptions) =>
+ purchasingOptions.length === 1 && purchasingOptions[0] === 'download',
+ ),
+ );
+
+ isGiftCardOnly$ = this.store.items$.pipe(
+ map((items) => items.every((item) => isGiftCard(item, this.store.type))),
+ );
+
+ hasDownload$ = this.purchasingOptions$.pipe(
+ map((purchasingOptions) => purchasingOptions.includes('download')),
+ );
+
+ canContinue$ = this.store.canContinue$;
+
+ private _onDestroy$ = new Subject
();
+
+ saving = false;
+
+ constructor(
+ private _uiModalRef: UiModalRef,
+ public store: PurchaseOptionsStore,
+ ) {
+ this.store.initialize(this._uiModalRef.data);
+ }
+
+ ngOnInit(): void {
+ this.items$
+ .pipe(takeUntil(this._onDestroy$), skip(1), delay(100))
+ .subscribe((items) => {
+ if (items.length === 0) {
+ this._uiModalRef.close();
+ return;
+ }
+
+ if (this._uiModalRef.data?.preSelectOption?.option) {
+ this.store.setPurchaseOption(
+ this._uiModalRef.data?.preSelectOption?.option,
+ );
+ }
+ });
+ }
+
+ ngOnDestroy(): void {
+ this._onDestroy$.next();
+ this._onDestroy$.complete();
+ }
+
+ itemTrackBy: TrackByFunction- = (_, item) => item.id;
+
+ showOption(option: PurchaseOption): boolean {
+ return this._uiModalRef.data?.preSelectOption?.showOptionOnly
+ ? this._uiModalRef.data?.preSelectOption?.option === option
+ : true;
+ }
+
+ async save(action: string) {
+ if (this.saving) {
+ return;
+ }
+ this.saving = true;
+
+ try {
+ await this.store.save();
+
+ if (this.store.items.length === 0) {
+ this._uiModalRef.close(action);
+ }
+ } catch (error) {
+ console.error(error);
+ }
+
+ this.saving = false;
+ }
+}
diff --git a/apps/isa-app/src/modal/purchase-options/purchase-options-modal.data.ts b/apps/isa-app/src/modal/purchase-options/purchase-options-modal.data.ts
index d2b25aa31..e27b429e1 100644
--- a/apps/isa-app/src/modal/purchase-options/purchase-options-modal.data.ts
+++ b/apps/isa-app/src/modal/purchase-options/purchase-options-modal.data.ts
@@ -1,12 +1,30 @@
-import { ItemDTO } from '@generated/swagger/cat-search-api';
-import { ShoppingCartItemDTO, BranchDTO } from '@generated/swagger/checkout-api';
-import { ActionType, PurchaseOption } from './store';
-
-export interface PurchaseOptionsModalData {
- processId: number;
- type: ActionType;
- items: Array
;
- pickupBranch?: BranchDTO;
- inStoreBranch?: BranchDTO;
- preSelectOption?: { option: PurchaseOption; showOptionOnly?: boolean };
-}
+import { ItemDTO } from '@generated/swagger/cat-search-api';
+import {
+ ShoppingCartItemDTO,
+ BranchDTO,
+} from '@generated/swagger/checkout-api';
+import { Customer } from '@isa/crm/data-access';
+import { ActionType, PurchaseOption } from './store';
+
+export interface PurchaseOptionsModalData {
+ tabId: number;
+ shoppingCartId: number;
+ type: ActionType;
+ useRedemptionPoints?: boolean;
+ items: Array;
+ pickupBranch?: BranchDTO;
+ inStoreBranch?: BranchDTO;
+ preSelectOption?: { option: PurchaseOption; showOptionOnly?: boolean };
+}
+
+export interface PurchaseOptionsModalContext {
+ shoppingCartId: number;
+ type: ActionType;
+ useRedemptionPoints: boolean;
+ items: Array;
+ selectedCustomer?: Customer;
+ selectedBranch?: BranchDTO;
+ pickupBranch?: BranchDTO;
+ inStoreBranch?: BranchDTO;
+ preSelectOption?: { option: PurchaseOption; showOptionOnly?: boolean };
+}
diff --git a/apps/isa-app/src/modal/purchase-options/purchase-options-modal.service.ts b/apps/isa-app/src/modal/purchase-options/purchase-options-modal.service.ts
index b8865a56f..99a305b95 100644
--- a/apps/isa-app/src/modal/purchase-options/purchase-options-modal.service.ts
+++ b/apps/isa-app/src/modal/purchase-options/purchase-options-modal.service.ts
@@ -1,16 +1,49 @@
-import { Injectable } from '@angular/core';
-import { UiModalRef, UiModalService } from '@ui/modal';
-import { PurchaseOptionsModalComponent } from './purchase-options-modal.component';
-import { PurchaseOptionsModalData } from './purchase-options-modal.data';
-
-@Injectable({ providedIn: 'root' })
-export class PurchaseOptionsModalService {
- constructor(private _uiModal: UiModalService) {}
-
- open(data: PurchaseOptionsModalData): UiModalRef {
- return this._uiModal.open({
- content: PurchaseOptionsModalComponent,
- data,
- });
- }
-}
+import { Injectable, inject } from '@angular/core';
+import { UiModalRef, UiModalService } from '@ui/modal';
+import { PurchaseOptionsModalComponent } from './purchase-options-modal.component';
+import {
+ PurchaseOptionsModalData,
+ PurchaseOptionsModalContext,
+} from './purchase-options-modal.data';
+import {
+ CustomerFacade,
+ Customer,
+ CrmTabMetadataService,
+} from '@isa/crm/data-access';
+
+@Injectable({ providedIn: 'root' })
+export class PurchaseOptionsModalService {
+ #uiModal = inject(UiModalService);
+ #crmTabMetadataService = inject(CrmTabMetadataService);
+ #customerFacade = inject(CustomerFacade);
+
+ async open(
+ data: PurchaseOptionsModalData,
+ ): Promise> {
+ const context: PurchaseOptionsModalContext = {
+ useRedemptionPoints: !!data.useRedemptionPoints,
+ ...data,
+ };
+
+ context.selectedCustomer = await this.#getSelectedCustomer(data);
+
+ return this.#uiModal.open({
+ content: PurchaseOptionsModalComponent,
+ data: context,
+ });
+ }
+
+ #getSelectedCustomer({
+ tabId,
+ }: {
+ tabId: number;
+ }): Promise {
+ const customerId = this.#crmTabMetadataService.selectedCustomerId(tabId);
+
+ if (!customerId) {
+ return Promise.resolve(undefined);
+ }
+
+ return this.#customerFacade.fetchCustomer({ customerId });
+ }
+}
diff --git a/apps/isa-app/src/modal/purchase-options/store/purchase-options.helpers.ts b/apps/isa-app/src/modal/purchase-options/store/purchase-options.helpers.ts
index 284afdf9d..bae16254d 100644
--- a/apps/isa-app/src/modal/purchase-options/store/purchase-options.helpers.ts
+++ b/apps/isa-app/src/modal/purchase-options/store/purchase-options.helpers.ts
@@ -1,158 +1,180 @@
-import { PriceDTO } from '@generated/swagger/availability-api';
-import { ItemDTO } from '@generated/swagger/cat-search-api';
-import { AvailabilityDTO, OLAAvailabilityDTO, ShoppingCartItemDTO } from '@generated/swagger/checkout-api';
-import { GIFT_CARD_TYPE } from '../constants';
-import {
- ActionType,
- Item,
- ItemData,
- ItemPayloadWithSourceId,
- OrderType,
- PurchaseOption,
-} from './purchase-options.types';
-
-export function isItemDTO(item: any, type: ActionType): item is ItemDTO {
- return type === 'add';
-}
-
-export function isItemDTOArray(items: any, type: ActionType): items is ItemDTO[] {
- return type === 'add';
-}
-
-export function isShoppingCartItemDTO(item: any, type: ActionType): item is ShoppingCartItemDTO {
- return type === 'update';
-}
-
-export function isShoppingCartItemDTOArray(items: any, type: ActionType): items is ShoppingCartItemDTO[] {
- return type === 'update';
-}
-
-export function mapToItemData(item: Item, type: ActionType): ItemData {
- const price: PriceDTO = {};
-
- if (isItemDTO(item, type)) {
- price.value = item?.catalogAvailability?.price?.value ?? {};
- price.vat = item?.catalogAvailability?.price?.vat ?? {};
-
- return {
- ean: item.product.ean,
- itemId: item.id,
- price,
- sourceId: item.id,
- quantity: item.quantity ?? 1,
- };
- } else {
- price.value = item?.unitPrice?.value ?? {};
- price.vat = item?.unitPrice?.vat ?? {};
-
- return {
- ean: item.product.ean,
- itemId: Number(item.product.catalogProductNumber),
- price,
- sourceId: item.id,
- quantity: item.quantity ?? 1,
- };
- }
-}
-
-export function isDownload(item: Item): boolean {
- return item.product.format === 'DL' || item.product.format === 'EB';
-}
-
-export function isGiftCard(item: Item, type: ActionType): boolean {
- if (isItemDTO(item, type)) {
- return item?.type === GIFT_CARD_TYPE;
- } else {
- return item?.itemType === GIFT_CARD_TYPE;
- }
-}
-
-export function isArchive(item: Item, type: ActionType): boolean {
- if (isItemDTO(item, type)) {
- return item?.features?.some((f) => f.key === 'ARC');
- } else {
- return !!item?.features?.['ARC'];
- }
-}
-
-export function mapToItemPayload({
- item,
- quantity,
- availability,
- type,
-}: {
- item: ItemDTO | ShoppingCartItemDTO;
- quantity: number;
- availability: AvailabilityDTO;
- type: ActionType;
-}): ItemPayloadWithSourceId {
- return {
- availabilities: [mapToOlaAvailability({ item, quantity, availability, type })],
- id: String(getCatalogId(item, type)),
- sourceId: item.id,
- };
-}
-
-export function getCatalogId(item: ItemDTO | ShoppingCartItemDTO, type: ActionType): number | string {
- return isItemDTO(item, type) ? item.id : item.product.catalogProductNumber;
-}
-
-export function mapToOlaAvailability({
- availability,
- item,
- quantity,
- type,
-}: {
- availability: AvailabilityDTO;
- item: ItemDTO | ShoppingCartItemDTO;
- quantity: number;
- type: ActionType;
-}): OLAAvailabilityDTO {
- return {
- status: availability?.availabilityType,
- at: availability?.estimatedShippingDate,
- ean: item?.product?.ean,
- itemId: Number(getCatalogId(item, type)),
- format: item?.product?.format,
- isPrebooked: availability?.isPrebooked,
- logisticianId: availability?.logistician?.id,
- price: availability?.price,
- qty: quantity,
- ssc: availability?.ssc,
- sscText: availability?.sscText,
- supplierId: availability?.supplier?.id,
- supplierProductNumber: availability?.supplierProductNumber,
- };
-}
-
-export function getOrderTypeForPurchaseOption(purchaseOption: PurchaseOption): OrderType | undefined {
- switch (purchaseOption) {
- case 'delivery':
- case 'dig-delivery':
- case 'b2b-delivery':
- return 'Versand';
- case 'pickup':
- return 'Abholung';
- case 'in-store':
- return 'Rรผcklage';
- case 'download':
- return 'Download';
- default:
- return undefined;
- }
-}
-
-export function getPurchaseOptionForOrderType(orderType: OrderType): PurchaseOption | undefined {
- switch (orderType) {
- case 'Versand':
- return 'delivery';
- case 'Abholung':
- return 'pickup';
- case 'Rรผcklage':
- return 'in-store';
- case 'Download':
- return 'download';
- default:
- return undefined;
- }
-}
+import { PriceDTO } from '@generated/swagger/availability-api';
+import { ItemDTO } from '@generated/swagger/cat-search-api';
+import {
+ AvailabilityDTO,
+ OLAAvailabilityDTO,
+ ShoppingCartItemDTO,
+} from '@generated/swagger/checkout-api';
+import { GIFT_CARD_TYPE } from '../constants';
+import {
+ ActionType,
+ Item,
+ ItemData,
+ ItemPayloadWithSourceId,
+ PurchaseOption,
+} from './purchase-options.types';
+import { OrderType } from '@isa/checkout/data-access';
+
+export function isItemDTO(item: any, type: ActionType): item is ItemDTO {
+ return type === 'add';
+}
+
+export function isItemDTOArray(
+ items: any,
+ type: ActionType,
+): items is ItemDTO[] {
+ return type === 'add';
+}
+
+export function isShoppingCartItemDTO(
+ item: any,
+ type: ActionType,
+): item is ShoppingCartItemDTO {
+ return type === 'update';
+}
+
+export function isShoppingCartItemDTOArray(
+ items: any,
+ type: ActionType,
+): items is ShoppingCartItemDTO[] {
+ return type === 'update';
+}
+
+export function mapToItemData(item: Item, type: ActionType): ItemData {
+ const price: PriceDTO = {};
+
+ if (isItemDTO(item, type)) {
+ price.value = item?.catalogAvailability?.price?.value ?? {};
+ price.vat = item?.catalogAvailability?.price?.vat ?? {};
+
+ return {
+ ean: item.product.ean,
+ itemId: item.id,
+ price,
+ sourceId: item.id,
+ quantity: item.quantity ?? 1,
+ };
+ } else {
+ price.value = item?.unitPrice?.value ?? {};
+ price.vat = item?.unitPrice?.vat ?? {};
+
+ return {
+ ean: item.product.ean,
+ itemId: Number(item.product.catalogProductNumber),
+ price,
+ sourceId: item.id,
+ quantity: item.quantity ?? 1,
+ };
+ }
+}
+
+export function isDownload(item: Item): boolean {
+ return item.product.format === 'DL' || item.product.format === 'EB';
+}
+
+export function isGiftCard(item: Item, type: ActionType): boolean {
+ if (isItemDTO(item, type)) {
+ return item?.type === GIFT_CARD_TYPE;
+ } else {
+ return item?.itemType === GIFT_CARD_TYPE;
+ }
+}
+
+export function isArchive(item: Item, type: ActionType): boolean {
+ if (isItemDTO(item, type)) {
+ return item?.features?.some((f) => f.key === 'ARC');
+ } else {
+ return !!item?.features?.['ARC'];
+ }
+}
+
+export function mapToItemPayload({
+ item,
+ quantity,
+ availability,
+ type,
+}: {
+ item: ItemDTO | ShoppingCartItemDTO;
+ quantity: number;
+ availability: AvailabilityDTO;
+ type: ActionType;
+}): ItemPayloadWithSourceId {
+ return {
+ availabilities: [
+ mapToOlaAvailability({ item, quantity, availability, type }),
+ ],
+ id: String(getCatalogId(item, type)),
+ sourceId: item.id,
+ };
+}
+
+export function getCatalogId(
+ item: ItemDTO | ShoppingCartItemDTO,
+ type: ActionType,
+): number | string {
+ return isItemDTO(item, type) ? item.id : item.product.catalogProductNumber;
+}
+
+export function mapToOlaAvailability({
+ availability,
+ item,
+ quantity,
+ type,
+}: {
+ availability: AvailabilityDTO;
+ item: ItemDTO | ShoppingCartItemDTO;
+ quantity: number;
+ type: ActionType;
+}): OLAAvailabilityDTO {
+ return {
+ status: availability?.availabilityType,
+ at: availability?.estimatedShippingDate,
+ ean: item?.product?.ean,
+ itemId: Number(getCatalogId(item, type)),
+ format: item?.product?.format,
+ isPrebooked: availability?.isPrebooked,
+ logisticianId: availability?.logistician?.id,
+ price: availability?.price,
+ qty: quantity,
+ ssc: availability?.ssc,
+ sscText: availability?.sscText,
+ supplierId: availability?.supplier?.id,
+ supplierProductNumber: availability?.supplierProductNumber,
+ };
+}
+
+export function getOrderTypeForPurchaseOption(
+ purchaseOption: PurchaseOption,
+): OrderType | undefined {
+ switch (purchaseOption) {
+ case 'delivery':
+ case 'dig-delivery':
+ case 'b2b-delivery':
+ return 'Versand';
+ case 'pickup':
+ return 'Abholung';
+ case 'in-store':
+ return 'Rรผcklage';
+ case 'download':
+ return 'Download';
+ default:
+ return undefined;
+ }
+}
+
+export function getPurchaseOptionForOrderType(
+ orderType: OrderType,
+): PurchaseOption | undefined {
+ switch (orderType) {
+ case 'Versand':
+ return 'delivery';
+ case 'Abholung':
+ return 'pickup';
+ case 'Rรผcklage':
+ return 'in-store';
+ case 'Download':
+ return 'download';
+ default:
+ return undefined;
+ }
+}
diff --git a/apps/isa-app/src/modal/purchase-options/store/purchase-options.selectors.ts b/apps/isa-app/src/modal/purchase-options/store/purchase-options.selectors.ts
index c76e90904..fe99dfe83 100644
--- a/apps/isa-app/src/modal/purchase-options/store/purchase-options.selectors.ts
+++ b/apps/isa-app/src/modal/purchase-options/store/purchase-options.selectors.ts
@@ -1,561 +1,689 @@
-import { PriceDTO, PriceValueDTO } from '@generated/swagger/checkout-api';
-import {
- DEFAULT_PRICE_DTO,
- DEFAULT_PRICE_VALUE,
- GIFT_CARD_MAX_PRICE,
- GIFT_CARD_TYPE,
- PURCHASE_OPTIONS,
-} from '../constants';
-import { isArchive, isGiftCard, isItemDTO } from './purchase-options.helpers';
-import { PurchaseOptionsState } from './purchase-options.state';
-import {
- ActionType,
- Availability,
- Branch,
- CanAdd,
- FetchingAvailability,
- Item,
- PurchaseOption,
-} from './purchase-options.types';
-
-export function getType(state: PurchaseOptionsState): ActionType {
- return state.type;
-}
-
-export function getProcessId(state: PurchaseOptionsState): number {
- return state.processId;
-}
-
-export function getItems(state: PurchaseOptionsState): Item[] {
- return state.items;
-}
-
-export function getPurchaseOption(state: PurchaseOptionsState): PurchaseOption {
- const options = getPurchaseOptionsInAvailabilities(state);
-
- if (options.length === 1) {
- return options[0];
- }
-
- if (state.purchaseOption) {
- return state.purchaseOption;
- }
-
- // #4380 Abholung als Standard wenn mรถglich und keine Auswahl getroffen wurde
- if (options.includes('pickup')) {
- return 'pickup';
- }
-
- return undefined;
-}
-
-export function getSelectedItemIds(state: PurchaseOptionsState): number[] {
- let selectedItemIds = state.selectedItemIds;
-
- if (selectedItemIds.length === 0 && state.items.length === 1) {
- selectedItemIds = state.items.map((item) => item.id);
- }
- const purchaseOption = getPurchaseOption(state);
- selectedItemIds = selectedItemIds.filter((id) => getCanAddForItemWithPurchaseOption(id, purchaseOption)(state));
- return selectedItemIds;
-}
-
-export function getDefaultBranch(state: PurchaseOptionsState): Branch {
- if (state.defaultBranch?.isOrderingEnabled === false) {
- return undefined;
- }
- return state.defaultBranch;
-}
-
-export function getPickupBranch(state: PurchaseOptionsState): Branch {
- const branch = state.pickupBranch || getDefaultBranch(state);
-
- if (branch?.branchType === 1) {
- return branch;
- }
-
- return undefined;
-}
-
-export function getInStoreBranch(state: PurchaseOptionsState): Branch {
- const branch = state.inStoreBranch || getDefaultBranch(state);
-
- if (branch?.branchType === 1) {
- return branch;
- }
-
- return undefined;
-}
-
-export function getAvailabilities(state: PurchaseOptionsState): Availability[] {
- return state.availabilities;
-}
-
-export function getPrices(state: PurchaseOptionsState): { [itemId: number]: PriceDTO } {
- return state.prices;
-}
-
-export function getCanAddResults(state: PurchaseOptionsState): CanAdd[] {
- return state.canAddResults;
-}
-
-export function getCanAddForItemWithPurchaseOption(
- itemId: number,
- purchaseOption: PurchaseOption,
-): (state: PurchaseOptionsState) => CanAdd {
- return (state: PurchaseOptionsState) => {
- const canAddResults = getCanAddResults(state);
- return canAddResults.find((ca) => ca.canAdd && ca.itemId === itemId && ca.purchaseOption === purchaseOption);
- };
-}
-
-export function getPurchasingOptions(state: PurchaseOptionsState): PurchaseOption[] {
- const availabilities = getAvailabilities(state);
- const purchaseOptions = availabilities.map((availability) => availability.purchaseOption);
- return Array.from(new Set(purchaseOptions)).sort((a, b) => PURCHASE_OPTIONS.indexOf(a) - PURCHASE_OPTIONS.indexOf(b));
-}
-
-export function getPurchaseOptionsInAvailabilities(state: PurchaseOptionsState): PurchaseOption[] {
- const availabilities = getAvailabilities(state);
- let purchaseOptions = availabilities.map((availability) => availability.purchaseOption);
-
- purchaseOptions = Array.from(new Set(purchaseOptions));
-
- // if 'delivery' is not present but 'dig-delivery' or 'b2b-delivery' is present, add 'delivery' to the list
- if (
- !purchaseOptions.includes('delivery') &&
- (purchaseOptions.includes('dig-delivery') || purchaseOptions.includes('b2b-delivery'))
- ) {
- purchaseOptions.push('delivery');
- }
-
- // if remove 'dig-delivery' and 'b2b-delivery' and 'catalog' as 'catalog' is not a purchase option but is needed for other data (Needed for #4813 and Bugfix for #4710)
- purchaseOptions = purchaseOptions.filter(
- (purchaseOption) =>
- purchaseOption !== 'dig-delivery' && purchaseOption !== 'b2b-delivery' && purchaseOption !== 'catalog',
- );
-
- return purchaseOptions.sort((a, b) => PURCHASE_OPTIONS.indexOf(a) - PURCHASE_OPTIONS.indexOf(b));
-}
-
-export function getFetchingAvailabilities(state: PurchaseOptionsState): Array {
- return state.fetchingAvailabilities;
-}
-
-export function getFetchingAvailabilitiesForItem(
- itemId: number,
-): (state: PurchaseOptionsState) => Array {
- return (state: PurchaseOptionsState) => {
- const fetchingAvailabilities = getFetchingAvailabilities(state);
- return fetchingAvailabilities.filter((fa) => fa.itemId === itemId);
- };
-}
-
-export function getItemsThatHaveAnAvailabilityForPurchaseOption(
- purchaseOption: PurchaseOption,
-): (state: PurchaseOptionsState) => Item[] {
- return (state) => {
- const availabilities = getAvailabilities(state);
- const items = getItems(state);
-
- const itemIds = availabilities
- .filter((availability) => {
- if (purchaseOption === 'delivery') {
- return (
- availability.purchaseOption === purchaseOption ||
- availability.purchaseOption === 'dig-delivery' ||
- availability.purchaseOption === 'b2b-delivery'
- );
- }
- return availability.purchaseOption === purchaseOption;
- })
- .map((availability) => availability.itemId);
- return items.filter((item) => itemIds.includes(item.id));
- };
-}
-
-export function getItemsThatHaveAnAvailabilityAndCanAddForPurchaseOption(purchaseOption: PurchaseOption) {
- return (state: PurchaseOptionsState): Item[] => {
- const items = getItemsThatHaveAnAvailabilityForPurchaseOption(purchaseOption)(state);
-
- const canAddResults = getCanAddResults(state);
-
- return items.filter((item) =>
- canAddResults.some(
- (canAdd) => canAdd.itemId === item.id && canAdd.purchaseOption === purchaseOption && canAdd.canAdd,
- ),
- );
- };
-}
-
-export function getItemsForList(state: PurchaseOptionsState): Item[] {
- const purchaseOption = getPurchaseOption(state);
- const items = getItems(state);
-
- if (purchaseOption == undefined) {
- return items;
- }
-
- const availabilities = getAvailabilities(state);
-
- const itemIds = availabilities
- .filter((availability) => {
- if (purchaseOption === 'delivery') {
- return (
- availability.purchaseOption === purchaseOption ||
- availability.purchaseOption === 'dig-delivery' ||
- availability.purchaseOption === 'b2b-delivery'
- );
- }
- return availability.purchaseOption === purchaseOption;
- })
- .map((availability) => availability.itemId);
- return items.filter((item) => itemIds.includes(item.id));
-}
-
-export function getAvailabilitiesForItem(
- itemId: number,
- allDeliveryAvailabilities?: boolean,
-): (state: PurchaseOptionsState) => Availability[] {
- return (state) => {
- let availabilities = getAvailabilities(state);
- availabilities = availabilities.filter((availability) => availability.itemId === itemId);
-
- // if 'delivery', 'dig-delivery' and 'b2b-delivery' are present remove 'dig-delivery' and 'b2b-delivery'
- if (
- !allDeliveryAvailabilities &&
- availabilities.some((availability) => availability.purchaseOption === 'delivery')
- ) {
- availabilities = availabilities.filter(
- (availability) =>
- availability.purchaseOption !== 'dig-delivery' && availability.purchaseOption !== 'b2b-delivery',
- );
- }
- const optionsOrder = PURCHASE_OPTIONS;
-
- return availabilities.sort(
- (a, b) => optionsOrder.indexOf(a.purchaseOption) - optionsOrder.indexOf(b.purchaseOption),
- );
- };
-}
-
-export function getCanEditPrice(itemId: number): (state: PurchaseOptionsState) => boolean {
- return (state) => {
- const item = getItems(state).find((item) => item.id === itemId);
-
- if (isGiftCard(item, getType(state))) {
- return true;
- }
-
- const purchaseOption = getPurchaseOption(state);
-
- if (isArchive(item, getType(state)) && !getAvailabilityPriceForPurchaseOption(itemId, purchaseOption)(state)) {
- return true;
- }
-
- return false;
- };
-}
-
-export function getCanEditVat(itemId: number): (state: PurchaseOptionsState) => boolean {
- return (state) => {
- const item = getItems(state).find((item) => item.id === itemId);
- const purchaseOption = getPurchaseOption(state);
-
- if (isArchive(item, getType(state)) && !getAvailabilityPriceForPurchaseOption(itemId, purchaseOption)(state)) {
- return true;
- }
-
- return false;
- };
-}
-
-export function getIsGiftCard(itemId: number): (state: PurchaseOptionsState) => boolean {
- return (state) => {
- const item = getItems(state).find((item) => item.id === itemId);
- return isGiftCard(item, getType(state));
- };
-}
-
-export function getAvailabilityPriceForPurchaseOption(
- itemId: number,
- purchaseOption: PurchaseOption,
-): (state: PurchaseOptionsState) => (PriceDTO & { fromCatalogue?: boolean }) | undefined {
- return (state) => {
- const item = getItems(state).find((item) => item.id === itemId);
- const type = getType(state);
- let availabilities = getAvailabilitiesForItem(itemId)(state);
-
- let availability = availabilities.find((availability) => availability.purchaseOption === purchaseOption);
-
- /**
- * Wenn Abholung oder Versand, dann den gรผnstigeren Preis nehmen wenn priceMaintained false ist
- * Genauere Infos https://dev.azure.com/hugendubel/ISA/_wiki/wikis/ISA.wiki/186/Anzeige-Preise
- * 18.01.24 #4611 Preis // Preisunterschiede im Warenkorb
- */
- if (purchaseOption === 'delivery' || purchaseOption === 'pickup') {
- let deliveryAvailability = availabilities.find((availability) => availability.purchaseOption === 'delivery');
- const digAvailability = availabilities.find((availability) => availability.purchaseOption === 'dig-delivery');
- const b2bAvailability = availabilities.find((availability) => availability.purchaseOption === 'b2b-delivery');
-
- if (purchaseOption === 'delivery') {
- if (isDigCustomer(state)) {
- deliveryAvailability = digAvailability ?? deliveryAvailability;
- } else if (isB2bCustomer(state)) {
- deliveryAvailability = b2bAvailability ?? deliveryAvailability;
- }
- }
-
- deliveryAvailability = deliveryAvailability ?? digAvailability ?? b2bAvailability;
-
- if (purchaseOption === 'delivery') {
- availability = deliveryAvailability ?? availability;
- }
-
- // Wennn Artkkel nicht Preisgebinden ist, dann den gรผnstigeren Preis nehmen wenn priceMaintained false ist
- if (!availability?.data?.priceMaintained) {
- const pickupAvailability = availabilities.find((availability) => availability.purchaseOption === 'pickup');
- const catalogAvailability = availabilities.find((availability) => availability.purchaseOption === 'catalog');
-
- const availabilityHasInvalidPrice = !(availability?.data?.price?.value?.value > 0);
- const pickupAvailabilityHasInvalidPrice = !(pickupAvailability?.data?.price?.value?.value > 0);
- const catalogAvailabilityHasInvalidPrice = !(catalogAvailability?.data?.price?.value?.value > 0);
-
- // Early exit wenn Rรผcklagepreis und Versandpreis nicht vorhanden sind, dann auf den Katalogpreis zurรผckgreifen
- if (availabilityHasInvalidPrice && pickupAvailabilityHasInvalidPrice) {
- return catalogAvailabilityHasInvalidPrice ? DEFAULT_PRICE_DTO : catalogAvailability?.data?.price;
- }
-
- // Wenn beide Preise vorhanden sind, dann den gรผnstigeren Preis nehmen
- if (!availabilityHasInvalidPrice && !pickupAvailabilityHasInvalidPrice) {
- // Wenn beide Preise gleich sind dann nehme den Preis fรผr die ausgeรคhlte Option
- if (deliveryAvailability?.data?.price?.value?.value === pickupAvailability?.data?.price?.value?.value) {
- return availability?.data?.price;
- }
-
- return deliveryAvailability?.data?.price?.value?.value > pickupAvailability?.data?.price?.value?.value
- ? pickupAvailability?.data?.price
- : deliveryAvailability?.data?.price;
- }
-
- // Wenn nur der Versandpreis vorhanden ist, dann diesen nehmen
- if (!availabilityHasInvalidPrice && pickupAvailabilityHasInvalidPrice) {
- return deliveryAvailability?.data?.price;
- }
-
- // Wenn nur der Rรผcklagepreis vorhanden ist, dann diesen nehmen
- if (availabilityHasInvalidPrice && !pickupAvailabilityHasInvalidPrice) {
- return pickupAvailability?.data?.price;
- }
- }
-
- // #4760 Fehler bei Abholpreisberechnung in Filiale Darmstadt Ernst-Ludwig-Straรe (negativ Preis im Warenkorb)
- // รberprรผfen ob der Preis ungรผltig ist und der Versandpreis vorhanden ist
- // Wenn ja, dann den Versandpreis nehmen
- if (!(availability?.data?.price?.value?.value > 0)) {
- if (deliveryAvailability?.data?.price?.value?.value > 0) {
- const deliveryPrice = deliveryAvailability?.data?.price;
- availability.data.price = deliveryPrice;
- } else {
- // Wenn der Versandpreis auch ungรผltig ist, dann den Katalogpreis nehmen
- const catalogAvailability = availabilities.find((availability) => availability.purchaseOption === 'catalog');
- return catalogAvailability?.data?.price ?? DEFAULT_PRICE_DTO;
- }
- }
- }
-
- if (availability && availability.data.price?.value?.value && availability.data.price) {
- return availability.data.price;
- }
-
- if (isItemDTO(item, type)) {
- return item?.catalogAvailability?.price;
- } else {
- return item?.unitPrice;
- }
- };
-}
-
-export function getPriceForPurchaseOption(
- itemId: number,
- purchaseOption: PurchaseOption,
-): (state: PurchaseOptionsState) => PriceDTO {
- return (state) => {
- if (getCanEditPrice(itemId)(state)) {
- const price = getPrices(state)[itemId];
- if (price) {
- return price;
- }
- }
-
- return getAvailabilityPriceForPurchaseOption(itemId, purchaseOption)(state) ?? DEFAULT_PRICE_DTO;
- };
-}
-
-export function getQuantityForItem(itemId: number): (state: PurchaseOptionsState) => number {
- return (state) => {
- const item = getItems(state).find((item) => item.id === itemId);
- const quantity = item?.quantity;
- return quantity ?? 1;
- };
-}
-
-export function getCanAddResultForItemAndCurrentPurchaseOption(
- itemId: number,
-): (state: PurchaseOptionsState) => CanAdd {
- return (state) => {
- const fetchingAvailabilities = getFetchingAvailabilitiesForItem(itemId)(state);
- const purchaseOption = getPurchaseOption(state);
- if (fetchingAvailabilities.length > 0) {
- return { canAdd: false, itemId, purchaseOption };
- }
-
- const availability = getAvailabilityWithPurchaseOption(itemId, purchaseOption)(state);
-
- if (purchaseOption === 'in-store') {
- const quantity = getQuantityForItem(itemId)(state);
- if (quantity > availability?.data?.inStock) {
- return { canAdd: false, itemId, purchaseOption };
- }
- }
-
- const canAddResults = getCanAddResults(state);
-
- return canAddResults.find(
- (canAddResult) => canAddResult.itemId === itemId && canAddResult.purchaseOption === purchaseOption,
- );
- };
-}
-
-export function getAvailabilityWithPurchaseOption(
- itemId: number,
- purchaseOption: PurchaseOption,
-): (state: PurchaseOptionsState) => Availability {
- return (state) => {
- let availabilities = getAvailabilitiesForItem(itemId, true)(state);
-
- let availability = availabilities.find((availability) => availability.purchaseOption === purchaseOption);
- if (purchaseOption === 'delivery') {
- const digAvailability = availabilities.find((availability) => availability.purchaseOption === 'dig-delivery');
- const b2bAvailability = availabilities.find((availability) => availability.purchaseOption === 'b2b-delivery');
-
- if (!(digAvailability && b2bAvailability)) {
- availability = digAvailability ?? b2bAvailability;
- }
- }
- return availability;
- };
-}
-
-export function getCanAddResultWithPurchaseOption(
- itemId: number,
- purchaseOption: PurchaseOption,
-): (state: PurchaseOptionsState) => CanAdd {
- return (state) => {
- const canAddResults = getCanAddResults(state);
- return canAddResults.find(
- (canAddResult) => canAddResult.itemId === itemId && canAddResult.purchaseOption === purchaseOption,
- );
- };
-}
-
-export function canContinue(state: PurchaseOptionsState): boolean {
- const purchaseOption = getPurchaseOption(state);
-
- if (purchaseOption === undefined) {
- return false;
- }
-
- if (purchaseOption === 'pickup' && getPickupBranch(state) === undefined) {
- return false;
- }
-
- if (purchaseOption === 'in-store' && getInStoreBranch(state) === undefined) {
- return false;
- }
-
- if (
- (purchaseOption === 'delivery' || purchaseOption === 'b2b-delivery' || purchaseOption === 'dig-delivery') &&
- isGuestWithoutAccountCustomer(state)
- ) {
- return false;
- }
-
- const items = getItems(state);
-
- if (items.length === 0) {
- return false;
- }
-
- const actionType = getType(state);
-
- for (let item of items) {
- if (isGiftCard(item, actionType)) {
- const price = getPriceForPurchaseOption(item.id, purchaseOption)(state);
- if (!(price?.value?.value > 0 && price?.value?.value <= GIFT_CARD_MAX_PRICE)) {
- return false;
- }
- } else if (isArchive(item, actionType) && !getAvailabilityPriceForPurchaseOption(item.id, purchaseOption)(state)) {
- const price = getPriceForPurchaseOption(item.id, purchaseOption)(state);
- const hasPrice = price?.value?.value > 0;
- const hasVat = price?.vat?.vatType > 0;
- if (!(hasPrice && hasVat)) {
- return false;
- }
- }
- }
-
- const selectedItemIds = getSelectedItemIds(state);
-
- if (selectedItemIds.length === 0) {
- return false;
- }
-
- const selectedItems = items.filter((item) => selectedItemIds.includes(item.id));
-
- if (selectedItems.length === 0) {
- return false;
- }
-
- for (const item of selectedItems) {
- if (item.quantity > 0) {
- return true;
- }
-
- const price = getPriceForPurchaseOption(item.id, purchaseOption)(state);
-
- if (price === undefined) {
- return false;
- }
-
- if (price?.value?.value > 0 && !(price?.vat?.value >= 0)) {
- return false;
- }
-
- let availability = getAvailabilityWithPurchaseOption(item.id, purchaseOption)(state);
-
- if (availability === undefined) {
- return false;
- }
-
- const canAddResult = getCanAddResultWithPurchaseOption(item.id, purchaseOption)(state);
-
- if (canAddResult === undefined || !canAddResult.canAdd) {
- return false;
- }
- }
-
- return true;
-}
-
-export function isDigCustomer(state: PurchaseOptionsState): boolean {
- return !!state.customerFeatures['webshop'];
-}
-
-export function isB2bCustomer(state: PurchaseOptionsState): boolean {
- return !!state.customerFeatures['b2b'];
-}
-
-export function isGuestWithoutAccountCustomer(state: PurchaseOptionsState): boolean {
- return !!state.customerFeatures['guest'] && !!state.customerFeatures['d-no-account'];
-}
+import { PriceDTO } from '@generated/swagger/checkout-api';
+import {
+ DEFAULT_PRICE_DTO,
+ GIFT_CARD_MAX_PRICE,
+ PURCHASE_OPTIONS,
+} from '../constants';
+import { isArchive, isGiftCard, isItemDTO } from './purchase-options.helpers';
+import { PurchaseOptionsState } from './purchase-options.state';
+import {
+ ActionType,
+ Availability,
+ Branch,
+ CanAdd,
+ FetchingAvailability,
+ Item,
+ PurchaseOption,
+} from './purchase-options.types';
+
+export function getType(state: PurchaseOptionsState): ActionType {
+ return state.type;
+}
+
+export function getUseRedemptionPoints(state: PurchaseOptionsState): boolean {
+ return state.useRedemptionPoints;
+}
+
+export function getShoppingCartId(state: PurchaseOptionsState): number {
+ return state.shoppingCartId;
+}
+
+export function getItems(state: PurchaseOptionsState): Item[] {
+ return state.items;
+}
+
+export function getPurchaseOption(state: PurchaseOptionsState): PurchaseOption {
+ const options = getPurchaseOptionsInAvailabilities(state);
+
+ if (options.length === 1) {
+ return options[0];
+ }
+
+ if (state.purchaseOption) {
+ return state.purchaseOption;
+ }
+
+ // #4380 Abholung als Standard wenn mรถglich und keine Auswahl getroffen wurde
+ if (options.includes('pickup')) {
+ return 'pickup';
+ }
+
+ return undefined;
+}
+
+export function getSelectedItemIds(state: PurchaseOptionsState): number[] {
+ let selectedItemIds = state.selectedItemIds;
+
+ if (selectedItemIds.length === 0 && state.items.length === 1) {
+ selectedItemIds = state.items.map((item) => item.id);
+ }
+ const purchaseOption = getPurchaseOption(state);
+ selectedItemIds = selectedItemIds.filter((id) =>
+ getCanAddForItemWithPurchaseOption(id, purchaseOption)(state),
+ );
+ return selectedItemIds;
+}
+
+export function getDefaultBranch(state: PurchaseOptionsState): Branch {
+ if (state.defaultBranch?.isOrderingEnabled === false) {
+ return undefined;
+ }
+ return state.defaultBranch;
+}
+
+export function getPickupBranch(state: PurchaseOptionsState): Branch {
+ const branch = state.pickupBranch || getDefaultBranch(state);
+
+ if (branch?.branchType === 1) {
+ return branch;
+ }
+
+ return undefined;
+}
+
+export function getInStoreBranch(state: PurchaseOptionsState): Branch {
+ const branch = state.inStoreBranch || getDefaultBranch(state);
+
+ if (branch?.branchType === 1) {
+ return branch;
+ }
+
+ return undefined;
+}
+
+export function getAvailabilities(state: PurchaseOptionsState): Availability[] {
+ return state.availabilities;
+}
+
+export function getPrices(state: PurchaseOptionsState): {
+ [itemId: number]: PriceDTO;
+} {
+ return state.prices;
+}
+
+export function getCanAddResults(state: PurchaseOptionsState): CanAdd[] {
+ return state.canAddResults;
+}
+
+export function getCanAddForItemWithPurchaseOption(
+ itemId: number,
+ purchaseOption: PurchaseOption,
+): (state: PurchaseOptionsState) => CanAdd {
+ return (state: PurchaseOptionsState) => {
+ const canAddResults = getCanAddResults(state);
+ return canAddResults.find(
+ (ca) =>
+ ca.canAdd &&
+ ca.itemId === itemId &&
+ ca.purchaseOption === purchaseOption,
+ );
+ };
+}
+
+export function getPurchasingOptions(
+ state: PurchaseOptionsState,
+): PurchaseOption[] {
+ const availabilities = getAvailabilities(state);
+ const purchaseOptions = availabilities.map(
+ (availability) => availability.purchaseOption,
+ );
+ return Array.from(new Set(purchaseOptions)).sort(
+ (a, b) => PURCHASE_OPTIONS.indexOf(a) - PURCHASE_OPTIONS.indexOf(b),
+ );
+}
+
+export function getPurchaseOptionsInAvailabilities(
+ state: PurchaseOptionsState,
+): PurchaseOption[] {
+ const availabilities = getAvailabilities(state);
+ let purchaseOptions = availabilities.map(
+ (availability) => availability.purchaseOption,
+ );
+
+ purchaseOptions = Array.from(new Set(purchaseOptions));
+
+ // if 'delivery' is not present but 'dig-delivery' or 'b2b-delivery' is present, add 'delivery' to the list
+ if (
+ !purchaseOptions.includes('delivery') &&
+ (purchaseOptions.includes('dig-delivery') ||
+ purchaseOptions.includes('b2b-delivery'))
+ ) {
+ purchaseOptions.push('delivery');
+ }
+
+ // if remove 'dig-delivery' and 'b2b-delivery' and 'catalog' as 'catalog' is not a purchase option but is needed for other data (Needed for #4813 and Bugfix for #4710)
+ purchaseOptions = purchaseOptions.filter(
+ (purchaseOption) =>
+ purchaseOption !== 'dig-delivery' &&
+ purchaseOption !== 'b2b-delivery' &&
+ purchaseOption !== 'catalog',
+ );
+
+ return purchaseOptions.sort(
+ (a, b) => PURCHASE_OPTIONS.indexOf(a) - PURCHASE_OPTIONS.indexOf(b),
+ );
+}
+
+export function getFetchingAvailabilities(
+ state: PurchaseOptionsState,
+): Array {
+ return state.fetchingAvailabilities;
+}
+
+export function getFetchingAvailabilitiesForItem(
+ itemId: number,
+): (state: PurchaseOptionsState) => Array {
+ return (state: PurchaseOptionsState) => {
+ const fetchingAvailabilities = getFetchingAvailabilities(state);
+ return fetchingAvailabilities.filter((fa) => fa.itemId === itemId);
+ };
+}
+
+export function getItemsThatHaveAnAvailabilityForPurchaseOption(
+ purchaseOption: PurchaseOption,
+): (state: PurchaseOptionsState) => Item[] {
+ return (state) => {
+ const availabilities = getAvailabilities(state);
+ const items = getItems(state);
+
+ const itemIds = availabilities
+ .filter((availability) => {
+ if (purchaseOption === 'delivery') {
+ return (
+ availability.purchaseOption === purchaseOption ||
+ availability.purchaseOption === 'dig-delivery' ||
+ availability.purchaseOption === 'b2b-delivery'
+ );
+ }
+ return availability.purchaseOption === purchaseOption;
+ })
+ .map((availability) => availability.itemId);
+ return items.filter((item) => itemIds.includes(item.id));
+ };
+}
+
+export function getItemsThatHaveAnAvailabilityAndCanAddForPurchaseOption(
+ purchaseOption: PurchaseOption,
+) {
+ return (state: PurchaseOptionsState): Item[] => {
+ const items =
+ getItemsThatHaveAnAvailabilityForPurchaseOption(purchaseOption)(state);
+
+ const canAddResults = getCanAddResults(state);
+
+ return items.filter((item) =>
+ canAddResults.some(
+ (canAdd) =>
+ canAdd.itemId === item.id &&
+ canAdd.purchaseOption === purchaseOption &&
+ canAdd.canAdd,
+ ),
+ );
+ };
+}
+
+export function getItemsForList(state: PurchaseOptionsState): Item[] {
+ const purchaseOption = getPurchaseOption(state);
+ const items = getItems(state);
+
+ if (purchaseOption == undefined) {
+ return items;
+ }
+
+ const availabilities = getAvailabilities(state);
+
+ const itemIds = availabilities
+ .filter((availability) => {
+ if (purchaseOption === 'delivery') {
+ return (
+ availability.purchaseOption === purchaseOption ||
+ availability.purchaseOption === 'dig-delivery' ||
+ availability.purchaseOption === 'b2b-delivery'
+ );
+ }
+ return availability.purchaseOption === purchaseOption;
+ })
+ .map((availability) => availability.itemId);
+ return items.filter((item) => itemIds.includes(item.id));
+}
+
+export function getAvailabilitiesForItem(
+ itemId: number,
+ allDeliveryAvailabilities?: boolean,
+): (state: PurchaseOptionsState) => Availability[] {
+ return (state) => {
+ let availabilities = getAvailabilities(state);
+ availabilities = availabilities.filter(
+ (availability) => availability.itemId === itemId,
+ );
+
+ // if 'delivery', 'dig-delivery' and 'b2b-delivery' are present remove 'dig-delivery' and 'b2b-delivery'
+ if (
+ !allDeliveryAvailabilities &&
+ availabilities.some(
+ (availability) => availability.purchaseOption === 'delivery',
+ )
+ ) {
+ availabilities = availabilities.filter(
+ (availability) =>
+ availability.purchaseOption !== 'dig-delivery' &&
+ availability.purchaseOption !== 'b2b-delivery',
+ );
+ }
+ const optionsOrder = PURCHASE_OPTIONS;
+
+ return availabilities.sort(
+ (a, b) =>
+ optionsOrder.indexOf(a.purchaseOption) -
+ optionsOrder.indexOf(b.purchaseOption),
+ );
+ };
+}
+
+export function getCanEditPrice(
+ itemId: number,
+): (state: PurchaseOptionsState) => boolean {
+ return (state) => {
+ const item = getItems(state).find((item) => item.id === itemId);
+
+ if (isGiftCard(item, getType(state))) {
+ return true;
+ }
+
+ const purchaseOption = getPurchaseOption(state);
+
+ if (
+ isArchive(item, getType(state)) &&
+ !getAvailabilityPriceForPurchaseOption(itemId, purchaseOption)(state)
+ ) {
+ return true;
+ }
+
+ return false;
+ };
+}
+
+export function getCanEditVat(
+ itemId: number,
+): (state: PurchaseOptionsState) => boolean {
+ return (state) => {
+ const item = getItems(state).find((item) => item.id === itemId);
+ const purchaseOption = getPurchaseOption(state);
+
+ if (
+ isArchive(item, getType(state)) &&
+ !getAvailabilityPriceForPurchaseOption(itemId, purchaseOption)(state)
+ ) {
+ return true;
+ }
+
+ return false;
+ };
+}
+
+export function getIsGiftCard(
+ itemId: number,
+): (state: PurchaseOptionsState) => boolean {
+ return (state) => {
+ const item = getItems(state).find((item) => item.id === itemId);
+ return isGiftCard(item, getType(state));
+ };
+}
+
+export function getAvailabilityPriceForPurchaseOption(
+ itemId: number,
+ purchaseOption: PurchaseOption,
+): (
+ state: PurchaseOptionsState,
+) => (PriceDTO & { fromCatalogue?: boolean }) | undefined {
+ return (state) => {
+ const item = getItems(state).find((item) => item.id === itemId);
+ const type = getType(state);
+ const availabilities = getAvailabilitiesForItem(itemId)(state);
+
+ let availability = availabilities.find(
+ (availability) => availability.purchaseOption === purchaseOption,
+ );
+
+ /**
+ * Wenn Abholung oder Versand, dann den gรผnstigeren Preis nehmen wenn priceMaintained false ist
+ * Genauere Infos https://dev.azure.com/hugendubel/ISA/_wiki/wikis/ISA.wiki/186/Anzeige-Preise
+ * 18.01.24 #4611 Preis // Preisunterschiede im Warenkorb
+ */
+ if (purchaseOption === 'delivery' || purchaseOption === 'pickup') {
+ let deliveryAvailability = availabilities.find(
+ (availability) => availability.purchaseOption === 'delivery',
+ );
+ const digAvailability = availabilities.find(
+ (availability) => availability.purchaseOption === 'dig-delivery',
+ );
+ const b2bAvailability = availabilities.find(
+ (availability) => availability.purchaseOption === 'b2b-delivery',
+ );
+
+ if (purchaseOption === 'delivery') {
+ if (isDigCustomer(state)) {
+ deliveryAvailability = digAvailability ?? deliveryAvailability;
+ } else if (isB2bCustomer(state)) {
+ deliveryAvailability = b2bAvailability ?? deliveryAvailability;
+ }
+ }
+
+ deliveryAvailability =
+ deliveryAvailability ?? digAvailability ?? b2bAvailability;
+
+ if (purchaseOption === 'delivery') {
+ availability = deliveryAvailability ?? availability;
+ }
+
+ // Wennn Artkkel nicht Preisgebinden ist, dann den gรผnstigeren Preis nehmen wenn priceMaintained false ist
+ if (!availability?.data?.priceMaintained) {
+ const pickupAvailability = availabilities.find(
+ (availability) => availability.purchaseOption === 'pickup',
+ );
+ const catalogAvailability = availabilities.find(
+ (availability) => availability.purchaseOption === 'catalog',
+ );
+
+ const availabilityHasInvalidPrice = !(
+ availability?.data?.price?.value?.value > 0
+ );
+ const pickupAvailabilityHasInvalidPrice = !(
+ pickupAvailability?.data?.price?.value?.value > 0
+ );
+ const catalogAvailabilityHasInvalidPrice = !(
+ catalogAvailability?.data?.price?.value?.value > 0
+ );
+
+ // Early exit wenn Rรผcklagepreis und Versandpreis nicht vorhanden sind, dann auf den Katalogpreis zurรผckgreifen
+ if (availabilityHasInvalidPrice && pickupAvailabilityHasInvalidPrice) {
+ return catalogAvailabilityHasInvalidPrice
+ ? DEFAULT_PRICE_DTO
+ : catalogAvailability?.data?.price;
+ }
+
+ // Wenn beide Preise vorhanden sind, dann den gรผnstigeren Preis nehmen
+ if (
+ !availabilityHasInvalidPrice &&
+ !pickupAvailabilityHasInvalidPrice
+ ) {
+ // Wenn beide Preise gleich sind dann nehme den Preis fรผr die ausgeรคhlte Option
+ if (
+ deliveryAvailability?.data?.price?.value?.value ===
+ pickupAvailability?.data?.price?.value?.value
+ ) {
+ return availability?.data?.price;
+ }
+
+ return deliveryAvailability?.data?.price?.value?.value >
+ pickupAvailability?.data?.price?.value?.value
+ ? pickupAvailability?.data?.price
+ : deliveryAvailability?.data?.price;
+ }
+
+ // Wenn nur der Versandpreis vorhanden ist, dann diesen nehmen
+ if (!availabilityHasInvalidPrice && pickupAvailabilityHasInvalidPrice) {
+ return deliveryAvailability?.data?.price;
+ }
+
+ // Wenn nur der Rรผcklagepreis vorhanden ist, dann diesen nehmen
+ if (availabilityHasInvalidPrice && !pickupAvailabilityHasInvalidPrice) {
+ return pickupAvailability?.data?.price;
+ }
+ }
+
+ // #4760 Fehler bei Abholpreisberechnung in Filiale Darmstadt Ernst-Ludwig-Straรe (negativ Preis im Warenkorb)
+ // รberprรผfen ob der Preis ungรผltig ist und der Versandpreis vorhanden ist
+ // Wenn ja, dann den Versandpreis nehmen
+ if (!(availability?.data?.price?.value?.value > 0)) {
+ if (deliveryAvailability?.data?.price?.value?.value > 0) {
+ const deliveryPrice = deliveryAvailability?.data?.price;
+ availability.data.price = deliveryPrice;
+ } else {
+ // Wenn der Versandpreis auch ungรผltig ist, dann den Katalogpreis nehmen
+ const catalogAvailability = availabilities.find(
+ (availability) => availability.purchaseOption === 'catalog',
+ );
+ return catalogAvailability?.data?.price ?? DEFAULT_PRICE_DTO;
+ }
+ }
+ }
+
+ if (
+ availability &&
+ availability.data.price?.value?.value &&
+ availability.data.price
+ ) {
+ return availability.data.price;
+ }
+
+ if (isItemDTO(item, type)) {
+ return item?.catalogAvailability?.price;
+ } else {
+ return item?.unitPrice;
+ }
+ };
+}
+
+export function getPriceForPurchaseOption(
+ itemId: number,
+ purchaseOption: PurchaseOption,
+): (state: PurchaseOptionsState) => PriceDTO {
+ return (state) => {
+ if (getCanEditPrice(itemId)(state)) {
+ const price = getPrices(state)[itemId];
+ if (price) {
+ return price;
+ }
+ }
+
+ return (
+ getAvailabilityPriceForPurchaseOption(itemId, purchaseOption)(state) ??
+ DEFAULT_PRICE_DTO
+ );
+ };
+}
+
+export function getQuantityForItem(
+ itemId: number,
+): (state: PurchaseOptionsState) => number {
+ return (state) => {
+ const item = getItems(state).find((item) => item.id === itemId);
+ const quantity = item?.quantity;
+ return quantity ?? 1;
+ };
+}
+
+export function getCanAddResultForItemAndCurrentPurchaseOption(
+ itemId: number,
+): (state: PurchaseOptionsState) => CanAdd {
+ return (state) => {
+ const fetchingAvailabilities =
+ getFetchingAvailabilitiesForItem(itemId)(state);
+ const purchaseOption = getPurchaseOption(state);
+ if (fetchingAvailabilities.length > 0) {
+ return { canAdd: false, itemId, purchaseOption };
+ }
+
+ const availability = getAvailabilityWithPurchaseOption(
+ itemId,
+ purchaseOption,
+ )(state);
+
+ if (purchaseOption === 'in-store') {
+ const quantity = getQuantityForItem(itemId)(state);
+ if (quantity > availability?.data?.inStock) {
+ return { canAdd: false, itemId, purchaseOption };
+ }
+ }
+
+ const canAddResults = getCanAddResults(state);
+
+ return canAddResults.find(
+ (canAddResult) =>
+ canAddResult.itemId === itemId &&
+ canAddResult.purchaseOption === purchaseOption,
+ );
+ };
+}
+
+export function getAvailabilityWithPurchaseOption(
+ itemId: number,
+ purchaseOption: PurchaseOption,
+): (state: PurchaseOptionsState) => Availability {
+ return (state) => {
+ const availabilities = getAvailabilitiesForItem(itemId, true)(state);
+
+ let availability = availabilities.find(
+ (availability) => availability.purchaseOption === purchaseOption,
+ );
+ if (purchaseOption === 'delivery') {
+ const digAvailability = availabilities.find(
+ (availability) => availability.purchaseOption === 'dig-delivery',
+ );
+ const b2bAvailability = availabilities.find(
+ (availability) => availability.purchaseOption === 'b2b-delivery',
+ );
+
+ if (!(digAvailability && b2bAvailability)) {
+ availability = digAvailability ?? b2bAvailability;
+ }
+ }
+ return availability;
+ };
+}
+
+export function getCanAddResultWithPurchaseOption(
+ itemId: number,
+ purchaseOption: PurchaseOption,
+): (state: PurchaseOptionsState) => CanAdd {
+ return (state) => {
+ const canAddResults = getCanAddResults(state);
+ return canAddResults.find(
+ (canAddResult) =>
+ canAddResult.itemId === itemId &&
+ canAddResult.purchaseOption === purchaseOption,
+ );
+ };
+}
+
+export function canContinue(state: PurchaseOptionsState): boolean {
+ const purchaseOption = getPurchaseOption(state);
+
+ if (purchaseOption === undefined) {
+ return false;
+ }
+
+ if (purchaseOption === 'pickup' && getPickupBranch(state) === undefined) {
+ return false;
+ }
+
+ if (purchaseOption === 'in-store' && getInStoreBranch(state) === undefined) {
+ return false;
+ }
+
+ if (
+ (purchaseOption === 'delivery' ||
+ purchaseOption === 'b2b-delivery' ||
+ purchaseOption === 'dig-delivery') &&
+ isGuestWithoutAccountCustomer(state)
+ ) {
+ return false;
+ }
+
+ const items = getItems(state);
+
+ if (items.length === 0) {
+ return false;
+ }
+
+ const actionType = getType(state);
+
+ for (const item of items) {
+ if (isGiftCard(item, actionType)) {
+ const price = getPriceForPurchaseOption(item.id, purchaseOption)(state);
+ if (
+ !(price?.value?.value > 0 && price?.value?.value <= GIFT_CARD_MAX_PRICE)
+ ) {
+ return false;
+ }
+ } else if (
+ isArchive(item, actionType) &&
+ !getAvailabilityPriceForPurchaseOption(item.id, purchaseOption)(state)
+ ) {
+ const price = getPriceForPurchaseOption(item.id, purchaseOption)(state);
+ const hasPrice = price?.value?.value > 0;
+ const hasVat = price?.vat?.vatType > 0;
+ if (!(hasPrice && hasVat)) {
+ return false;
+ }
+ }
+ }
+
+ const selectedItemIds = getSelectedItemIds(state);
+
+ if (selectedItemIds.length === 0) {
+ return false;
+ }
+
+ const selectedItems = items.filter((item) =>
+ selectedItemIds.includes(item.id),
+ );
+
+ if (selectedItems.length === 0) {
+ return false;
+ }
+
+ for (const item of selectedItems) {
+ if (item.quantity > 0) {
+ return true;
+ }
+
+ const price = getPriceForPurchaseOption(item.id, purchaseOption)(state);
+
+ if (price === undefined) {
+ return false;
+ }
+
+ if (price?.value?.value > 0 && !(price?.vat?.value >= 0)) {
+ return false;
+ }
+
+ const availability = getAvailabilityWithPurchaseOption(
+ item.id,
+ purchaseOption,
+ )(state);
+
+ if (availability === undefined) {
+ return false;
+ }
+
+ const canAddResult = getCanAddResultWithPurchaseOption(
+ item.id,
+ purchaseOption,
+ )(state);
+
+ if (canAddResult === undefined || !canAddResult.canAdd) {
+ return false;
+ }
+ }
+
+ return true;
+}
+
+export function isDigCustomer(state: PurchaseOptionsState): boolean {
+ return !!state.customerFeatures['webshop'];
+}
+
+export function isB2bCustomer(state: PurchaseOptionsState): boolean {
+ return !!state.customerFeatures['b2b'];
+}
+
+export function isGuestWithoutAccountCustomer(
+ state: PurchaseOptionsState,
+): boolean {
+ return (
+ !!state.customerFeatures['guest'] &&
+ !!state.customerFeatures['d-no-account']
+ );
+}
diff --git a/apps/isa-app/src/modal/purchase-options/store/purchase-options.service.ts b/apps/isa-app/src/modal/purchase-options/store/purchase-options.service.ts
index 42ccf3da3..bb9445c51 100644
--- a/apps/isa-app/src/modal/purchase-options/store/purchase-options.service.ts
+++ b/apps/isa-app/src/modal/purchase-options/store/purchase-options.service.ts
@@ -1,178 +1,240 @@
-import { Injectable } from '@angular/core';
-import { DomainAvailabilityService } from '@domain/availability';
-import { DomainCheckoutService } from '@domain/checkout';
-import {
- AddToShoppingCartDTO,
- AvailabilityDTO,
- EntityDTOContainerOfDestinationDTO,
- ItemPayload,
- ItemsResult,
- ShoppingCartDTO,
- UpdateShoppingCartItemDTO,
-} from '@generated/swagger/checkout-api';
-import { Observable } from 'rxjs';
-import { map, shareReplay, take } from 'rxjs/operators';
-import { Branch, ItemData } from './purchase-options.types';
-import { memorize } from '@utils/common';
-import { AuthService } from '@core/auth';
-import { ApplicationService } from '@core/application';
-import { DomainOmsService } from '@domain/oms';
-
-@Injectable({ providedIn: 'root' })
-export class PurchaseOptionsService {
- constructor(
- private _availabilityService: DomainAvailabilityService,
- private _checkoutService: DomainCheckoutService,
- private _omsService: DomainOmsService,
- private _auth: AuthService,
- private _app: ApplicationService,
- ) {}
-
- getVats$() {
- return this._omsService.getVATs();
- }
-
- getSelectedBranchForProcess(processId: number): Observable {
- return this._app.getSelectedBranch$(processId).pipe(take(1), shareReplay(1));
- }
-
- getCustomerFeatures(processId: number): Observable> {
- return this._checkoutService.getCustomerFeatures({ processId }).pipe(take(1), shareReplay(1));
- }
-
- @memorize()
- fetchDefaultBranch(): Observable {
- return this.getBranch({ branchNumber: this._auth.getClaimByKey('branch_no') }).pipe(take(1), shareReplay(1));
- }
-
- fetchPickupAvailability(item: ItemData, quantity: number, branch: Branch): Observable {
- return this._availabilityService
- .getPickUpAvailability({
- branch,
- quantity,
- item,
- })
- .pipe(map((res) => (Array.isArray(res) ? res[0] : undefined)));
- }
-
- fetchInStoreAvailability(item: ItemData, quantity: number, branch: Branch): Observable {
- return this._availabilityService.getTakeAwayAvailability({
- item,
- quantity,
- branch,
- });
- }
-
- fetchDeliveryAvailability(item: ItemData, quantity: number): Observable {
- return this._availabilityService.getDeliveryAvailability({
- item,
- quantity,
- });
- }
-
- fetchDigDeliveryAvailability(item: ItemData, quantity: number): Observable {
- return this._availabilityService.getDigDeliveryAvailability({
- item,
- quantity,
- });
- }
-
- fetchB2bDeliveryAvailability(item: ItemData, quantity: number): Observable {
- return this._availabilityService.getB2bDeliveryAvailability({
- item,
- quantity,
- });
- }
-
- fetchDownloadAvailability(item: ItemData): Observable {
- return this._availabilityService.getDownloadAvailability({
- item,
- });
- }
-
- isAvailable(availability: AvailabilityDTO): boolean {
- return this._availabilityService.isAvailable({ availability });
- }
-
- fetchCanAdd(processId: number, orderType: string, payload: ItemPayload[]): Observable {
- return this._checkoutService.canAddItems({
- processId,
- orderType,
- payload,
- });
- }
-
- removeItemFromShoppingCart(processId: number, shoppingCartItemId: number): Promise {
- return this._checkoutService
- .updateItemInShoppingCart({
- processId,
- shoppingCartItemId,
- update: {
- availability: null,
- quantity: 0,
- },
- })
- .toPromise();
- }
-
- getInStoreDestination(branch: Branch): EntityDTOContainerOfDestinationDTO {
- return {
- data: { target: 1, targetBranch: { id: branch.id } },
- };
- }
-
- getPickupDestination(branch: Branch): EntityDTOContainerOfDestinationDTO {
- return {
- data: { target: 1, targetBranch: { id: branch.id } },
- };
- }
-
- getDeliveryDestination(availability: AvailabilityDTO): EntityDTOContainerOfDestinationDTO {
- return {
- data: { target: 2, logistician: availability?.logistician },
- };
- }
-
- getDownloadDestination(availability: AvailabilityDTO): EntityDTOContainerOfDestinationDTO {
- return {
- data: { target: 16, logistician: availability?.logistician },
- };
- }
-
- addItemToShoppingCart(processId: number, items: AddToShoppingCartDTO[]) {
- return this._checkoutService.addItemToShoppingCart({
- processId,
- items,
- });
- }
-
- updateItemInShoppingCart(processId: number, shoppingCartItemId: number, payload: UpdateShoppingCartItemDTO) {
- return this._checkoutService.updateItemInShoppingCart({
- processId,
- shoppingCartItemId,
- update: payload,
- });
- }
-
- @memorize({ comparer: (_) => true })
- getBranches(): Observable {
- return this._availabilityService.getBranches().pipe(
- map((branches) => {
- return branches.filter((branch) => branch.isShippingEnabled == true);
- }),
- shareReplay(1),
- );
- }
-
- getBranch(params: { id: number }): Observable;
- getBranch(params: { branchNumber: string }): Observable;
- getBranch(params: { id: number; branchNumber: string }): Observable;
- getBranch(params: { id?: number; branchNumber?: string }): Observable {
- return this.getBranches().pipe(
- map((branches) => {
- const branch = branches.find((branch) => branch.id == params.id || branch.branchNumber == params.branchNumber);
- return branch;
- }),
- );
- }
-}
+import { inject, Injectable } from '@angular/core';
+import { DomainAvailabilityService } from '@domain/availability';
+import { DomainCheckoutService } from '@domain/checkout';
+import {
+ AddToShoppingCartDTO,
+ AvailabilityDTO,
+ EntityDTOContainerOfDestinationDTO,
+ ItemPayload,
+ ItemsResult,
+ ShoppingCartDTO,
+ UpdateShoppingCartItemDTO,
+} from '@generated/swagger/checkout-api';
+import { Observable } from 'rxjs';
+import { map, shareReplay, take } from 'rxjs/operators';
+import { Branch, ItemData } from './purchase-options.types';
+import { memorize } from '@utils/common';
+import { AuthService } from '@core/auth';
+import { ApplicationService } from '@core/application';
+import { DomainOmsService } from '@domain/oms';
+import { OrderType, PurchaseOptionsFacade } from '@isa/checkout/data-access';
+
+@Injectable({ providedIn: 'root' })
+export class PurchaseOptionsService {
+ #purchaseOptionsFacade = inject(PurchaseOptionsFacade);
+
+ constructor(
+ private _availabilityService: DomainAvailabilityService,
+ private _checkoutService: DomainCheckoutService,
+ private _omsService: DomainOmsService,
+ private _auth: AuthService,
+ private _app: ApplicationService,
+ ) {}
+
+ getVats$() {
+ return this._omsService.getVATs();
+ }
+
+ getSelectedBranchForProcess(processId: number): Observable {
+ return this._app
+ .getSelectedBranch$(processId)
+ .pipe(take(1), shareReplay(1));
+ }
+
+ getCustomerFeatures(processId: number): Observable> {
+ return this._checkoutService
+ .getCustomerFeatures({ processId })
+ .pipe(take(1), shareReplay(1));
+ }
+
+ @memorize()
+ fetchDefaultBranch(): Observable {
+ return this.getBranch({
+ branchNumber: this._auth.getClaimByKey('branch_no'),
+ }).pipe(take(1), shareReplay(1));
+ }
+
+ fetchPickupAvailability(
+ item: ItemData,
+ quantity: number,
+ branch: Branch,
+ ): Observable {
+ return this._availabilityService
+ .getPickUpAvailability({
+ branch,
+ quantity,
+ item,
+ })
+ .pipe(map((res) => (Array.isArray(res) ? res[0] : undefined)));
+ }
+
+ fetchInStoreAvailability(
+ item: ItemData,
+ quantity: number,
+ branch: Branch,
+ ): Observable {
+ return this._availabilityService.getTakeAwayAvailability({
+ item,
+ quantity,
+ branch,
+ });
+ }
+
+ fetchDeliveryAvailability(
+ item: ItemData,
+ quantity: number,
+ ): Observable {
+ return this._availabilityService.getDeliveryAvailability({
+ item,
+ quantity,
+ });
+ }
+
+ fetchDigDeliveryAvailability(
+ item: ItemData,
+ quantity: number,
+ ): Observable {
+ return this._availabilityService.getDigDeliveryAvailability({
+ item,
+ quantity,
+ });
+ }
+
+ fetchB2bDeliveryAvailability(
+ item: ItemData,
+ quantity: number,
+ ): Observable {
+ return this._availabilityService.getB2bDeliveryAvailability({
+ item,
+ quantity,
+ });
+ }
+
+ fetchDownloadAvailability(item: ItemData): Observable {
+ return this._availabilityService.getDownloadAvailability({
+ item,
+ });
+ }
+
+ isAvailable(availability: AvailabilityDTO): boolean {
+ return this._availabilityService.isAvailable({ availability });
+ }
+
+ fetchCanAdd(
+ shoppingCartId: number,
+ orderType: OrderType,
+ payload: ItemPayload[],
+ customerFeatures: Record,
+ ): Promise {
+ return this.#purchaseOptionsFacade.canAddItems({
+ shoppingCartId,
+ payload: payload.map((p) => ({
+ ...p,
+ customerFeatures: customerFeatures,
+ orderType: orderType,
+ })),
+ });
+ }
+
+ removeItemFromShoppingCart(
+ shoppingCartId: number,
+ shoppingCartItemId: number,
+ ): Promise {
+ const shoppingCart = this.#purchaseOptionsFacade.removeItem({
+ shoppingCartId,
+ shoppingCartItemId,
+ });
+
+ return shoppingCart;
+ }
+
+ getInStoreDestination(branch: Branch): EntityDTOContainerOfDestinationDTO {
+ return {
+ data: { target: 1, targetBranch: { id: branch.id } },
+ };
+ }
+
+ getPickupDestination(branch: Branch): EntityDTOContainerOfDestinationDTO {
+ return {
+ data: { target: 1, targetBranch: { id: branch.id } },
+ };
+ }
+
+ getDeliveryDestination(
+ availability: AvailabilityDTO,
+ ): EntityDTOContainerOfDestinationDTO {
+ return {
+ data: { target: 2, logistician: availability?.logistician },
+ };
+ }
+
+ getDownloadDestination(
+ availability: AvailabilityDTO,
+ ): EntityDTOContainerOfDestinationDTO {
+ return {
+ data: { target: 16, logistician: availability?.logistician },
+ };
+ }
+
+ async addItemToShoppingCart(
+ shoppingCartId: number,
+ items: AddToShoppingCartDTO[],
+ ) {
+ const shoppingCart = await this.#purchaseOptionsFacade.addItem({
+ shoppingCartId,
+ items,
+ });
+ console.log('added item to cart', { shoppingCart });
+ this._checkoutService.updateProcessCount(
+ this._app.activatedProcessId,
+ shoppingCart,
+ );
+ return shoppingCart;
+ }
+
+ async updateItemInShoppingCart(
+ shoppingCartId: number,
+ shoppingCartItemId: number,
+ payload: UpdateShoppingCartItemDTO,
+ ) {
+ const shoppingCart = await this.#purchaseOptionsFacade.updateItem({
+ shoppingCartId,
+ shoppingCartItemId,
+ values: payload,
+ });
+ console.log('updated item in cart', { shoppingCart });
+ this._checkoutService.updateProcessCount(
+ this._app.activatedProcessId,
+ shoppingCart,
+ );
+ }
+
+ @memorize({ comparer: (_) => true })
+ getBranches(): Observable {
+ return this._availabilityService.getBranches().pipe(
+ map((branches) => {
+ return branches.filter((branch) => branch.isShippingEnabled == true);
+ }),
+ shareReplay(1),
+ );
+ }
+
+ getBranch(params: { id: number }): Observable;
+ getBranch(params: { branchNumber: string }): Observable;
+ getBranch(params: { id: number; branchNumber: string }): Observable;
+ getBranch(params: {
+ id?: number;
+ branchNumber?: string;
+ }): Observable {
+ return this.getBranches().pipe(
+ map((branches) => {
+ const branch = branches.find(
+ (branch) =>
+ branch.id == params.id ||
+ branch.branchNumber == params.branchNumber,
+ );
+ return branch;
+ }),
+ );
+ }
+}
diff --git a/apps/isa-app/src/modal/purchase-options/store/purchase-options.state.ts b/apps/isa-app/src/modal/purchase-options/store/purchase-options.state.ts
index 72786f89c..50e7315e5 100644
--- a/apps/isa-app/src/modal/purchase-options/store/purchase-options.state.ts
+++ b/apps/isa-app/src/modal/purchase-options/store/purchase-options.state.ts
@@ -1,38 +1,40 @@
-import { PriceDTO } from '@generated/swagger/checkout-api';
-import {
- ActionType,
- Availability,
- Branch,
- CanAdd,
- FetchingAvailability,
- Item,
- PurchaseOption,
-} from './purchase-options.types';
-
-export interface PurchaseOptionsState {
- type: ActionType;
-
- processId: number;
-
- items: Item[];
-
- availabilities: Availability[];
-
- canAddResults: CanAdd[];
-
- purchaseOption: PurchaseOption;
-
- selectedItemIds: number[];
-
- prices: { [itemId: number]: PriceDTO };
-
- defaultBranch: Branch;
-
- pickupBranch: Branch;
-
- inStoreBranch: Branch;
-
- customerFeatures: Record;
-
- fetchingAvailabilities: Array;
-}
+import { PriceDTO } from '@generated/swagger/checkout-api';
+import {
+ ActionType,
+ Availability,
+ Branch,
+ CanAdd,
+ FetchingAvailability,
+ Item,
+ PurchaseOption,
+} from './purchase-options.types';
+
+export interface PurchaseOptionsState {
+ shoppingCartId: number;
+
+ type: ActionType;
+
+ items: Item[];
+
+ availabilities: Availability[];
+
+ canAddResults: CanAdd[];
+
+ purchaseOption: PurchaseOption;
+
+ selectedItemIds: number[];
+
+ prices: { [itemId: number]: PriceDTO };
+
+ defaultBranch: Branch;
+
+ pickupBranch: Branch;
+
+ inStoreBranch: Branch;
+
+ customerFeatures: Record;
+
+ fetchingAvailabilities: Array;
+
+ useRedemptionPoints: boolean;
+}
diff --git a/apps/isa-app/src/modal/purchase-options/store/purchase-options.store.ts b/apps/isa-app/src/modal/purchase-options/store/purchase-options.store.ts
index aeb9e16b5..a337c7e2c 100644
--- a/apps/isa-app/src/modal/purchase-options/store/purchase-options.store.ts
+++ b/apps/isa-app/src/modal/purchase-options/store/purchase-options.store.ts
@@ -1,883 +1,1149 @@
-import { Injectable } from '@angular/core';
-import { ComponentStore } from '@ngrx/component-store';
-import { PurchaseOptionsModalData } from '../purchase-options-modal.data';
-import { PurchaseOptionsService } from './purchase-options.service';
-import { PurchaseOptionsState } from './purchase-options.state';
-import {
- Availability,
- Branch,
- CanAdd,
- FetchingAvailability,
- Item,
- ItemData,
- ItemPayloadWithSourceId,
- OrderType,
- PurchaseOption,
-} from './purchase-options.types';
-import * as Selectors from './purchase-options.selectors';
-import {
- getPurchaseOptionForOrderType,
- isDownload,
- isGiftCard,
- isItemDTO,
- isShoppingCartItemDTO,
- mapToItemData,
- mapToItemPayload,
-} from './purchase-options.helpers';
-import { Observable } from 'rxjs';
-import { first, switchMap } from 'rxjs/operators';
-import { DEFAULT_PRICE_DTO, DEFAULT_PRICE_VALUE, DEFAULT_VAT_VALUE } from '../constants';
-import {
- AddToShoppingCartDTO,
- EntityDTOContainerOfDestinationDTO,
- UpdateShoppingCartItemDTO,
-} from '@generated/swagger/checkout-api';
-import { uniqueId } from 'lodash';
-import { VATDTO } from '@generated/swagger/oms-api';
-import { DomainCatalogService } from '@domain/catalog';
-import { ItemDTO } from '@generated/swagger/cat-search-api';
-
-@Injectable()
-export class PurchaseOptionsStore extends ComponentStore {
- get type() {
- return this.get(Selectors.getType);
- }
-
- type$ = this.select(Selectors.getType);
-
- get processId() {
- return this.get(Selectors.getProcessId);
- }
-
- processId$ = this.select(Selectors.getProcessId);
-
- get items() {
- return this.get(Selectors.getItems);
- }
-
- items$ = this.select(Selectors.getItems);
-
- get purchaseOption() {
- return this.get(Selectors.getPurchaseOption);
- }
-
- purchaseOption$ = this.select(Selectors.getPurchaseOption);
-
- get availabilities() {
- return this.get(Selectors.getAvailabilities);
- }
-
- availabilities$ = this.select(Selectors.getAvailabilities);
-
- get defaultBranch() {
- return this.get(Selectors.getDefaultBranch);
- }
-
- defaultBranch$ = this.select(Selectors.getDefaultBranch);
-
- get pickupBranch() {
- return this.get(Selectors.getPickupBranch);
- }
-
- pickupBranch$ = this.select(Selectors.getPickupBranch);
-
- get inStoreBranch() {
- return this.get(Selectors.getInStoreBranch);
- }
-
- inStoreBranch$ = this.select(Selectors.getInStoreBranch);
-
- get purchasingOptions() {
- return this.get(Selectors.getPurchasingOptions);
- }
-
- purchasingOptions$ = this.select(Selectors.getPurchasingOptions);
-
- get selectedItemIds() {
- return this.get(Selectors.getSelectedItemIds);
- }
-
- selectedItemIds$ = this.select(Selectors.getSelectedItemIds);
-
- get purchaseOptionsInAvailabilities(): PurchaseOption[] {
- return this.get(Selectors.getPurchaseOptionsInAvailabilities);
- }
-
- getPurchaseOptionsInAvailabilities$ = this.select(Selectors.getPurchaseOptionsInAvailabilities);
-
- get itemsForList() {
- return this.get(Selectors.getItemsForList);
- }
-
- itemsForList$ = this.select(Selectors.getItemsForList);
-
- get prices() {
- return this.get(Selectors.getPrices);
- }
-
- prices$ = this.select(Selectors.getPrices);
-
- get canAddResults() {
- return this.get(Selectors.getCanAddResults);
- }
-
- canAddResults$ = this.select(Selectors.getCanAddResults);
-
- get canContinue() {
- return this.get(Selectors.canContinue);
- }
-
- canContinue$ = this.select(Selectors.canContinue);
-
- get fetchingAvailabilities() {
- return this.get(Selectors.getFetchingAvailabilities);
- }
-
- fetchingAvailabilities$ = this.select(Selectors.getFetchingAvailabilities);
-
- get vats$() {
- return this._service.getVats$();
- }
-
- constructor(
- private _service: PurchaseOptionsService,
- private _catalogService: DomainCatalogService,
- ) {
- super({
- defaultBranch: undefined,
- inStoreBranch: undefined,
- items: [],
- pickupBranch: undefined,
- processId: undefined,
- purchaseOption: undefined,
- selectedItemIds: [],
- type: undefined,
- availabilities: [],
- prices: {},
- canAddResults: [],
- customerFeatures: {},
- fetchingAvailabilities: [],
- });
- }
-
- addFetchingAvailability = this.updater((state, fetchState: FetchingAvailability) => {
- return {
- ...state,
- fetchingAvailabilities: [...state.fetchingAvailabilities, fetchState],
- };
- });
-
- removeFetchingAvailability = this.updater((state, fetchState: FetchingAvailability) => {
- return {
- ...state,
- fetchingAvailabilities: state.fetchingAvailabilities.filter((f) => f.id !== fetchState.id),
- };
- });
-
- async initialize({ items, processId, type, inStoreBranch, pickupBranch }: PurchaseOptionsModalData) {
- const selectedBranch = await this._service.getSelectedBranchForProcess(processId).toPromise();
- const defaultBranch = await this._service.fetchDefaultBranch().toPromise();
- const customerFeatures = await this._service.getCustomerFeatures(processId).toPromise();
-
- this.patchState({
- processId: processId,
- type: type,
- items: items.map((item) => ({ ...item, quantity: item['quantity'] ?? 1 })),
- defaultBranch: selectedBranch ?? defaultBranch,
- pickupBranch: pickupBranch ?? selectedBranch,
- inStoreBranch: inStoreBranch ?? selectedBranch,
- customerFeatures,
- });
-
- await this._loadAvailabilities();
- await this._loadCanAdd();
- this.selectSelectableItems();
- }
-
- // #region Private funtions for loading and setting Branches and Availabilities
-
- private async _loadAvailabilities() {
- const items = this.items;
-
- const promises: Promise[] = [];
-
- this._loadCatalogueAvailability();
-
- items.forEach((item) => {
- const itemData = mapToItemData(item, this.type);
- if (isDownload(item)) {
- promises.push(this._loadDownloadAvailability(itemData));
- } else {
- if (!isGiftCard(item, this.type)) {
- promises.push(this._loadPickupAvailability(itemData));
- promises.push(this._loadInStoreAvailability(itemData));
- promises.push(this._loadDeliveryAvailability(itemData));
- promises.push(this._loadDigDeliveryAvailability(itemData));
- }
- promises.push(this._loadB2bDeliveryAvailability(itemData));
- }
- });
-
- await Promise.all(promises);
- }
-
- private async loadItemAvailability(itemId: number) {
- const item = this.items.find((item) => item.id === itemId);
-
- const promises: Promise[] = [];
-
- const purchaseOption = this.purchaseOption;
-
- if (!item) return Promise.resolve();
-
- const itemData = mapToItemData(item, this.type);
-
- if (purchaseOption === 'in-store' || purchaseOption === undefined) {
- promises.push(this._loadInStoreAvailability(itemData));
- }
-
- if (purchaseOption === 'pickup' || purchaseOption === undefined) {
- promises.push(this._loadPickupAvailability(itemData));
- }
-
- if (purchaseOption === 'delivery' || purchaseOption === undefined) {
- promises.push(this._loadDeliveryAvailability(itemData));
- promises.push(this._loadDigDeliveryAvailability(itemData));
- promises.push(this._loadB2bDeliveryAvailability(itemData));
- }
-
- await Promise.all(promises);
- }
-
- private async _loadCatalogueAvailability() {
- const items = this.items;
- if (this.type === 'update') {
- const items = await this._catalogService
- .searchByEans({ eans: this.items.map((item) => item.product.ean) })
- .toPromise();
- if (items.result.length > 0) await this._addCatalogueAvailabilities(items.result);
- } else {
- await this._addCatalogueAvailabilities(items as ItemDTO[]);
- }
- }
-
- // #4813 - Function updated - "this.updater" didn't work, so "this.patchState" gets used instead
- // Added firstDayOfSale for catalogAvailability via ShoppingCart Route
- private async _addCatalogueAvailabilities(items: ItemDTO[]) {
- const currentAvailabilities = await this.availabilities$.pipe(first()).toPromise();
- const availabilities = [...currentAvailabilities];
- items.forEach((item) => {
- const catalogAvailability = item.catalogAvailability;
- availabilities.push({
- purchaseOption: 'catalog',
- itemId: item.id,
- ean: item.product.ean, // Hier brauchen wir zusรคtzlich die EAN - siehe purchase-options-list-item.component.ts: "get isEVT()"
- data: { price: catalogAvailability?.price, firstDayOfSale: catalogAvailability?.firstDayOfSale },
- });
- });
-
- this.patchState({
- availabilities,
- });
- }
-
- private async _loadPickupAvailability(itemData: ItemData) {
- const branch = this.pickupBranch;
- if (!branch) return Promise.resolve();
-
- const id = uniqueId('availability_');
- try {
- this.addFetchingAvailability({ id, itemId: itemData.sourceId, purchaseOption: 'pickup' });
- const res = await this._service.fetchPickupAvailability(itemData, itemData.quantity, branch).toPromise();
-
- const availability: Availability = {
- itemId: itemData.sourceId,
- purchaseOption: 'pickup',
- data: res,
- };
-
- this._checkAndSetAvailability(availability);
- } catch (err) {
- console.error('_loadPickupAvailability', err);
- }
-
- this.removeFetchingAvailability({ id, itemId: itemData.sourceId, purchaseOption: 'pickup' });
- }
-
- private async _loadInStoreAvailability(itemData: ItemData) {
- const branch = this.inStoreBranch;
- if (!branch) return Promise.resolve();
-
- const id = uniqueId('availability_');
- try {
- this.addFetchingAvailability({ id, itemId: itemData.sourceId, purchaseOption: 'in-store' });
- const res = await this._service.fetchInStoreAvailability(itemData, itemData.quantity, branch).toPromise();
-
- const availability: Availability = {
- itemId: itemData.sourceId,
- purchaseOption: 'in-store',
- data: res,
- };
-
- this._checkAndSetAvailability(availability);
- } catch (err) {
- console.error('_loadInStoreAvailability', err);
- }
-
- this.removeFetchingAvailability({ id, itemId: itemData.sourceId, purchaseOption: 'in-store' });
- }
-
- private async _loadDeliveryAvailability(itemData: ItemData) {
- const id = uniqueId('availability_');
- try {
- this.addFetchingAvailability({ id, itemId: itemData.sourceId, purchaseOption: 'delivery' });
- const res = await this._service.fetchDeliveryAvailability(itemData, itemData.quantity).toPromise();
- const availability: Availability = {
- itemId: itemData.sourceId,
- purchaseOption: 'delivery',
- data: res,
- };
-
- this._checkAndSetAvailability(availability);
- } catch (error) {
- console.error('_loadDeliveryAvailability', error);
- }
-
- this.removeFetchingAvailability({ id, itemId: itemData.sourceId, purchaseOption: 'delivery' });
- }
-
- private async _loadDigDeliveryAvailability(itemData: ItemData) {
- const id = uniqueId('availability_');
- try {
- this.addFetchingAvailability({ id, itemId: itemData.sourceId, purchaseOption: 'dig-delivery' });
- const res = await this._service.fetchDigDeliveryAvailability(itemData, itemData.quantity).toPromise();
-
- const availability: Availability = {
- itemId: itemData.sourceId,
- purchaseOption: 'dig-delivery',
- data: res,
- };
-
- this._checkAndSetAvailability(availability);
- } catch (error) {
- console.error('_loadDigDeliveryAvailability', error);
- }
-
- this.removeFetchingAvailability({ id, itemId: itemData.sourceId, purchaseOption: 'dig-delivery' });
- }
-
- private async _loadB2bDeliveryAvailability(itemData: ItemData) {
- const id = uniqueId('availability_');
- try {
- this.addFetchingAvailability({ id, itemId: itemData.sourceId, purchaseOption: 'b2b-delivery' });
- const res = await this._service.fetchB2bDeliveryAvailability(itemData, itemData.quantity).toPromise();
-
- const availability: Availability = {
- itemId: itemData.sourceId,
- purchaseOption: 'b2b-delivery',
- data: res,
- };
-
- this._checkAndSetAvailability(availability);
- } catch (error) {
- console.error('_loadB2bDeliveryAvailability', error);
- }
-
- this.removeFetchingAvailability({ id, itemId: itemData.sourceId, purchaseOption: 'b2b-delivery' });
- }
-
- private async _loadDownloadAvailability(itemData: ItemData) {
- const id = uniqueId('availability_');
- try {
- this.addFetchingAvailability({ id, itemId: itemData.sourceId, purchaseOption: 'download' });
- const res = await this._service.fetchDownloadAvailability(itemData).toPromise();
-
- const availability: Availability = {
- itemId: itemData.sourceId,
- purchaseOption: 'download',
- data: res,
- };
-
- this._checkAndSetAvailability(availability);
- } catch (error) {
- console.error('_loadDownloadAvailability', error);
- }
-
- this.removeFetchingAvailability({ id, itemId: itemData.sourceId, purchaseOption: 'download' });
- }
-
- private _checkAndSetAvailability(availability: Availability) {
- if (this._service.isAvailable(availability.data)) {
- const availabilities = this.availabilities;
-
- const index = availabilities.findIndex(
- (a) => a.itemId === availability.itemId && a.purchaseOption === availability.purchaseOption,
- );
-
- if (index > -1) {
- availabilities[index] = availability;
- } else {
- availabilities.push(availability);
- }
-
- this.patchState({ availabilities });
- } else {
- let availabilities = this.availabilities.filter(
- (a) => !(a.itemId === availability.itemId && a.purchaseOption === availability.purchaseOption),
- );
- this.patchState({ availabilities });
- }
- }
-
- private _addCanAddResult(canAdd: CanAdd) {
- let canAddResults = this.canAddResults;
- canAddResults = canAddResults.filter(
- (c) => !(c.itemId === canAdd.itemId && c.purchaseOption === canAdd.purchaseOption),
- );
- canAddResults.push(canAdd);
- this.patchState({ canAddResults });
- }
-
- private async _loadCanAdd() {
- const payloads: Record = {
- Abholung: [],
- Rรผcklage: [],
- Versand: [],
- Download: [],
- };
-
- this.patchState({ canAddResults: [] });
-
- this.items.forEach((item) => {
- // Get Rรผcklage availability
- const inStoreAvailability = this.availabilities.find(
- (a) => a.itemId === item.id && a.purchaseOption === 'in-store',
- );
- if (inStoreAvailability) {
- payloads['Rรผcklage'].push(
- mapToItemPayload({
- item,
- availability: inStoreAvailability.data,
- quantity: item.quantity ?? 1,
- type: this.type,
- }),
- );
- }
-
- // Get Versand availability
- let deliveryAvailability = this.availabilities.find(
- (a) => a.itemId === item.id && a.purchaseOption === 'delivery',
- );
- const digDeliveryAvailability = this.availabilities.find(
- (a) => a.itemId === item.id && a.purchaseOption === 'dig-delivery',
- );
- const b2bDeliveryAvailability = this.availabilities.find(
- (a) => a.itemId === item.id && a.purchaseOption === 'b2b-delivery',
- );
- deliveryAvailability = deliveryAvailability || digDeliveryAvailability || b2bDeliveryAvailability;
- if (deliveryAvailability) {
- payloads['Versand'].push(
- mapToItemPayload({
- item,
- availability: deliveryAvailability.data,
- quantity: item.quantity ?? 1,
- type: this.type,
- }),
- );
- }
-
- // Get Abholung availability
- let pickupAvailability = this.availabilities.find((a) => a.itemId === item.id && a.purchaseOption === 'pickup');
- if (pickupAvailability) {
- payloads['Abholung'].push(
- mapToItemPayload({
- item,
- availability: pickupAvailability.data,
- quantity: item.quantity ?? 1,
- type: this.type,
- }),
- );
- }
-
- // Get Download availability
- const downloadAvailability = this.availabilities.find(
- (a) => a.itemId === item.id && a.purchaseOption === 'download',
- );
- if (downloadAvailability) {
- payloads['Download'].push(
- mapToItemPayload({
- item,
- availability: downloadAvailability.data,
- quantity: item.quantity ?? 1,
- type: this.type,
- }),
- );
- }
- });
-
- for (const key in payloads) {
- const itemPayloads = payloads[key];
- if (itemPayloads.length > 0) {
- try {
- const res = await this._service.fetchCanAdd(this.processId, key, itemPayloads).toPromise();
- res.forEach((canAdd) => {
- const item = itemPayloads.find((i) => i.id === canAdd.id);
- this._addCanAddResult({
- canAdd: canAdd.status === 0,
- itemId: item.sourceId,
- purchaseOption: getPurchaseOptionForOrderType(key as OrderType),
- message: canAdd.message,
- });
- });
- } catch (error) {
- console.error('_loadCanAdd', error);
- }
- }
- }
- }
-
- // #endregion
-
- setPurchaseOption(purchaseOption: PurchaseOption) {
- if (purchaseOption !== this.purchaseOption) {
- this.patchState({ purchaseOption });
- }
- }
-
- setSelectedItem(itemId: number, value: boolean) {
- const selectedItemIds = this.selectedItemIds;
- if (value && !selectedItemIds.includes(itemId)) {
- this.patchState({ selectedItemIds: [...selectedItemIds, itemId] });
- } else if (!value && selectedItemIds.includes(itemId)) {
- this.patchState({ selectedItemIds: selectedItemIds.filter((id) => id !== itemId) });
- }
- }
-
- selectSelectableItems() {
- const items = this.items.filter((i) => this.canAddItem(i.id));
-
- this.patchState({ selectedItemIds: items.map((item) => item.id) });
- }
-
- canAddItem(itemId: number): boolean {
- const purchaseOption = this.purchaseOption;
- const canAdd = this.canAddResults.find((c) => c.itemId === itemId && c.purchaseOption === purchaseOption);
-
- if (canAdd) {
- return canAdd.canAdd;
- }
-
- return false;
- }
-
- resetSelectedItems() {
- this.patchState({ selectedItemIds: [] });
- }
-
- getItemsThatHaveAnAvailabilityForPurchaseOption(purchaseOption: PurchaseOption): Item[] {
- return this.get(Selectors.getItemsThatHaveAnAvailabilityForPurchaseOption(purchaseOption));
- }
-
- getItemsThatHaveAnAvailabilityForPurchaseOption$(purchaseOption: PurchaseOption): Observable- {
- return this.select(Selectors.getItemsThatHaveAnAvailabilityForPurchaseOption(purchaseOption));
- }
-
- getItemsThatHaveAnAvailabilityAndCanAddForPurchaseOption(purchaseOption: PurchaseOption): Item[] {
- return this.get(Selectors.getItemsThatHaveAnAvailabilityAndCanAddForPurchaseOption(purchaseOption));
- }
-
- getItemsThatHaveAnAvailabilityAndCanAddForPurchaseOption$(purchaseOption: PurchaseOption): Observable
- {
- return this.select(Selectors.getItemsThatHaveAnAvailabilityAndCanAddForPurchaseOption(purchaseOption));
- }
-
- getAvailabilitiesForItem(itemId: number): Availability[] {
- return this.get(Selectors.getAvailabilitiesForItem(itemId));
- }
-
- getAvailabilitiesForItem$(itemId: number): Observable
{
- return this.select(Selectors.getAvailabilitiesForItem(itemId));
- }
-
- setInStoreBranch(branch: Branch | undefined) {
- if (this.inStoreBranch !== branch) {
- this.patchState({ inStoreBranch: branch });
-
- if (this.inStoreBranch) {
- const promises = this.items.map((item) => {
- const itemData = mapToItemData(item, this.type);
- return this._loadInStoreAvailability(itemData);
- });
-
- Promise.all(promises).then(() => {
- this._loadCanAdd();
- });
- }
- }
- }
-
- setPickupBranch(branch: Branch | undefined) {
- if (this.pickupBranch !== branch) {
- this.patchState({ pickupBranch: branch });
-
- if (this.pickupBranch) {
- const promises = this.items.map((item) => {
- const itemData = mapToItemData(item, this.type);
- return this._loadPickupAvailability(itemData);
- });
-
- Promise.all(promises).then(() => {
- this._loadCanAdd();
- });
- }
- }
- }
-
- async removeItem(itemId: number, removeFromShoppingCart: boolean) {
- const item = this.items.find((i) => i.id === itemId);
-
- if (removeFromShoppingCart && isShoppingCartItemDTO(item, this.type)) {
- this.removeItemFromShoppingCart(item);
- }
-
- const items = this.items.filter((i) => i.id !== itemId);
- this.setSelectedItem(itemId, false);
- this.patchState({ items });
- }
-
- async removeItemFromShoppingCart(item: Item) {
- try {
- await this._service.removeItemFromShoppingCart(this.processId, item.id);
- } catch (error) {
- console.error('removeItem', error);
- }
- }
-
- setItemQuantity(itemId: number, quantity: number) {
- const items = this.items;
- if (quantity <= 0) {
- this.removeItem(itemId, true);
- return;
- }
-
- const index = items.findIndex((item) => item.id === itemId);
- if (index > -1 && items[index].quantity !== quantity) {
- items[index].quantity = quantity;
- this.patchState({ items });
- }
-
- this.loadItemAvailability(itemId).then(() => {
- this._loadCanAdd();
- });
- }
-
- getIsGiftCard(itemId: number) {
- return this.get(Selectors.getIsGiftCard(itemId));
- }
-
- getPrice(itemId: number) {
- return this.getPriceForPurchaseOption(itemId, this.purchaseOption);
- }
-
- getPrice$(itemId: number) {
- return this.purchaseOption$.pipe(switchMap((po) => this.getPriceForPurchaseOption$(itemId, po)));
- }
-
- getPriceForPurchaseOption(itemId: number, purchaseOption: PurchaseOption) {
- return this.get(Selectors.getPriceForPurchaseOption(itemId, purchaseOption));
- }
-
- getPriceForPurchaseOption$(itemId: number, purchaseOption: PurchaseOption) {
- return this.select(Selectors.getPriceForPurchaseOption(itemId, purchaseOption));
- }
-
- getCanEditPrice(itemId: number) {
- return this.get(Selectors.getCanEditPrice(itemId));
- }
-
- getCanEditPrice$(itemId: number) {
- return this.select(Selectors.getCanEditPrice(itemId));
- }
-
- getCanEditVat(itemId: number) {
- return this.get(Selectors.getCanEditVat(itemId));
- }
-
- getCanEditVat$(itemId: number) {
- return this.select(Selectors.getCanEditVat(itemId));
- }
-
- getIsGiftCard$(itemId: number) {
- return this.select(Selectors.getIsGiftCard(itemId));
- }
-
- setPrice(itemId: number, value: number, manually: boolean = false) {
- const prices = this.prices;
- let price = prices[itemId];
-
- if (price?.value?.value !== value) {
- if (!price) {
- price = {
- ...DEFAULT_PRICE_DTO,
- value: { ...DEFAULT_PRICE_VALUE, value },
- vat: manually ? price?.vat : { ...DEFAULT_VAT_VALUE, ...price?.vat },
- };
- } else {
- price = { ...price, value: { ...price.value, value }, vat: price?.vat };
- }
-
- this.patchState({ prices: { ...prices, [itemId]: price } });
- }
- }
-
- setVat(itemId: number, vat: VATDTO) {
- const prices = this.prices;
- let price = prices[itemId];
- if (price?.vat?.vatType !== vat?.vatType) {
- if (!price) {
- price = {
- ...DEFAULT_PRICE_DTO,
- value: { ...DEFAULT_PRICE_VALUE, ...price?.value },
- vat: { ...DEFAULT_VAT_VALUE, ...vat },
- };
- } else {
- price = { ...price, value: price.value, vat: { ...price.vat, ...vat } };
- }
-
- this.patchState({ prices: { ...prices, [itemId]: price } });
- }
- }
-
- getCanAddResultForItemAndCurrentPurchaseOption(itemId: number) {
- return this.get(Selectors.getCanAddResultForItemAndCurrentPurchaseOption(itemId));
- }
-
- getCanAddResultForItemAndCurrentPurchaseOption$(itemId: number) {
- return this.select(Selectors.getCanAddResultForItemAndCurrentPurchaseOption(itemId));
- }
-
- getAvailabilityWithPurchaseOption(itemId: number, purchaseOption: PurchaseOption) {
- return this.get(Selectors.getAvailabilityWithPurchaseOption(itemId, purchaseOption));
- }
-
- getAvailabilityWithPurchaseOption$(itemId: number, purchaseOption: PurchaseOption) {
- return this.select(Selectors.getAvailabilityWithPurchaseOption(itemId, purchaseOption));
- }
-
- getCanAddResultWithPurchaseOption(itemId: number, purchaseOption: PurchaseOption) {
- return this.get(Selectors.getCanAddResultWithPurchaseOption(itemId, purchaseOption));
- }
-
- getCanAddResultWithPurchaseOption$(itemId: number, purchaseOption: PurchaseOption) {
- return this.select(Selectors.getCanAddResultWithPurchaseOption(itemId, purchaseOption));
- }
-
- addItemsToShoppingCart() {
- if (!this.canContinue || this.type !== 'add') {
- return;
- }
- }
-
- getAddToShoppingCartDTOForItem(itemId: number, purchaseOption: PurchaseOption): AddToShoppingCartDTO {
- const item = this.items.find((i) => i.id === itemId);
- const price = this.getPriceForPurchaseOption(itemId, this.purchaseOption);
- const availability = this.getAvailabilityWithPurchaseOption(itemId, purchaseOption);
-
- if (!isItemDTO(item, this.type)) {
- throw new Error('Invalid item');
- }
-
- let destination: EntityDTOContainerOfDestinationDTO;
- if (purchaseOption === 'delivery') {
- destination = this._service.getDeliveryDestination(availability.data);
- } else if (purchaseOption === 'pickup') {
- destination = this._service.getPickupDestination(this.pickupBranch);
- } else if (purchaseOption === 'in-store') {
- destination = this._service.getInStoreDestination(this.inStoreBranch);
- } else if (purchaseOption === 'download') {
- destination = this._service.getDownloadDestination(availability.data);
- }
-
- return {
- quantity: item.quantity,
- availability: { ...availability.data, price },
- destination,
- itemType: item.type,
- product: { ...item.product, catalogProductNumber: item?.product?.catalogProductNumber ?? String(item.id) },
- promotion: { points: item.promoPoints },
- // retailPrice: {
- // value: price.value.value,
- // currency: price.value.currency,
- // vatType: price.vat.vatType,
- // },
- // shopItemId: item.id ?? +item.product.catalogProductNumber,
- };
- }
-
- getUpdateShoppingCartItemDTOForItem(itemId: number, purchaseOption: PurchaseOption): UpdateShoppingCartItemDTO {
- const item = this.items.find((i) => i.id === itemId);
- const price = this.getPriceForPurchaseOption(itemId, this.purchaseOption);
- const availability = this.getAvailabilityWithPurchaseOption(itemId, purchaseOption);
-
- if (!isShoppingCartItemDTO(item, this.type)) {
- throw new Error('Invalid item');
- }
-
- let destination: EntityDTOContainerOfDestinationDTO;
- if (purchaseOption === 'delivery') {
- destination = this._service.getDeliveryDestination(availability.data);
- } else if (purchaseOption === 'pickup') {
- destination = this._service.getPickupDestination(this.pickupBranch);
- } else if (purchaseOption === 'in-store') {
- destination = this._service.getInStoreDestination(this.inStoreBranch);
- } else if (purchaseOption === 'download') {
- destination = this._service.getDownloadDestination(availability.data);
- }
-
- return {
- quantity: item.quantity,
- availability: { ...availability.data, price },
- destination,
- // retailPrice: {
- // value: price.value.value,
- // currency: price.value.currency,
- // vatType: price.vat.vatType,
- // },
- };
- }
-
- async save() {
- if (!this.canContinue) {
- return;
- }
- const type = this.type;
- const purchaseOption = this.purchaseOption;
-
- if (type === 'add') {
- const payloads = this.selectedItemIds.map((itemId) =>
- this.getAddToShoppingCartDTOForItem(itemId, purchaseOption),
- );
- await this._service.addItemToShoppingCart(this.processId, payloads).toPromise();
- } else if (type === 'update') {
- const payloads = this.selectedItemIds.map((itemId) =>
- this.getUpdateShoppingCartItemDTOForItem(itemId, purchaseOption),
- );
-
- for (const itemId of this.selectedItemIds) {
- const item = this.items.find((i) => i.id === itemId);
- const payload = this.getUpdateShoppingCartItemDTOForItem(itemId, purchaseOption);
- await this._service.updateItemInShoppingCart(this.processId, item.id, payload).toPromise();
- }
- } else {
- throw new Error('Invalid type');
- }
-
- this.selectedItemIds.forEach((itemId) => {
- this.removeItem(itemId, false);
- this.resetSelectedItems();
- });
- }
-
- getFetchingAvailabilitiesForItem$(itemId: number) {
- return this.select(Selectors.getFetchingAvailabilitiesForItem(itemId));
- }
-}
+import { Injectable } from '@angular/core';
+import { ComponentStore } from '@ngrx/component-store';
+import { logger } from '@isa/core/logging';
+import { PurchaseOptionsModalContext } from '../purchase-options-modal.data';
+import { PurchaseOptionsService } from './purchase-options.service';
+import { PurchaseOptionsState } from './purchase-options.state';
+import {
+ Availability,
+ Branch,
+ CanAdd,
+ FetchingAvailability,
+ Item,
+ ItemData,
+ ItemPayloadWithSourceId,
+ PurchaseOption,
+} from './purchase-options.types';
+import * as Selectors from './purchase-options.selectors';
+import {
+ getPurchaseOptionForOrderType,
+ isDownload,
+ isGiftCard,
+ isItemDTO,
+ isShoppingCartItemDTO,
+ mapToItemData,
+ mapToItemPayload,
+} from './purchase-options.helpers';
+import { Observable } from 'rxjs';
+import { first, switchMap } from 'rxjs/operators';
+import {
+ DEFAULT_PRICE_DTO,
+ DEFAULT_PRICE_VALUE,
+ DEFAULT_VAT_VALUE,
+} from '../constants';
+import {
+ AddToShoppingCartDTO,
+ EntityDTOContainerOfDestinationDTO,
+ UpdateShoppingCartItemDTO,
+} from '@generated/swagger/checkout-api';
+import { uniqueId } from 'lodash';
+import { VATDTO } from '@generated/swagger/oms-api';
+import { DomainCatalogService } from '@domain/catalog';
+import { ItemDTO } from '@generated/swagger/cat-search-api';
+import { Loyalty, OrderType, Promotion } from '@isa/checkout/data-access';
+
+@Injectable()
+export class PurchaseOptionsStore extends ComponentStore {
+ get type() {
+ return this.get(Selectors.getType);
+ }
+
+ type$ = this.select(Selectors.getType);
+
+ get useRedemptionPoints() {
+ return this.get(Selectors.getUseRedemptionPoints);
+ }
+
+ useRedemptionPoints$ = this.select(Selectors.getUseRedemptionPoints);
+
+ get shoppingCartId() {
+ return this.get(Selectors.getShoppingCartId);
+ }
+
+ shoppingCartId$ = this.select(Selectors.getShoppingCartId);
+
+ get customerFeatures() {
+ return this.get((s) => s.customerFeatures) ?? {};
+ }
+
+ get items() {
+ return this.get(Selectors.getItems);
+ }
+
+ items$ = this.select(Selectors.getItems);
+
+ get purchaseOption() {
+ return this.get(Selectors.getPurchaseOption);
+ }
+
+ purchaseOption$ = this.select(Selectors.getPurchaseOption);
+
+ get availabilities() {
+ return this.get(Selectors.getAvailabilities);
+ }
+
+ availabilities$ = this.select(Selectors.getAvailabilities);
+
+ get defaultBranch() {
+ return this.get(Selectors.getDefaultBranch);
+ }
+
+ defaultBranch$ = this.select(Selectors.getDefaultBranch);
+
+ get pickupBranch() {
+ return this.get(Selectors.getPickupBranch);
+ }
+
+ pickupBranch$ = this.select(Selectors.getPickupBranch);
+
+ get inStoreBranch() {
+ return this.get(Selectors.getInStoreBranch);
+ }
+
+ inStoreBranch$ = this.select(Selectors.getInStoreBranch);
+
+ get purchasingOptions() {
+ return this.get(Selectors.getPurchasingOptions);
+ }
+
+ purchasingOptions$ = this.select(Selectors.getPurchasingOptions);
+
+ get selectedItemIds() {
+ return this.get(Selectors.getSelectedItemIds);
+ }
+
+ selectedItemIds$ = this.select(Selectors.getSelectedItemIds);
+
+ get purchaseOptionsInAvailabilities(): PurchaseOption[] {
+ return this.get(Selectors.getPurchaseOptionsInAvailabilities);
+ }
+
+ getPurchaseOptionsInAvailabilities$ = this.select(
+ Selectors.getPurchaseOptionsInAvailabilities,
+ );
+
+ get itemsForList() {
+ return this.get(Selectors.getItemsForList);
+ }
+
+ itemsForList$ = this.select(Selectors.getItemsForList);
+
+ get prices() {
+ return this.get(Selectors.getPrices);
+ }
+
+ prices$ = this.select(Selectors.getPrices);
+
+ get canAddResults() {
+ return this.get(Selectors.getCanAddResults);
+ }
+
+ canAddResults$ = this.select(Selectors.getCanAddResults);
+
+ get canContinue() {
+ return this.get(Selectors.canContinue);
+ }
+
+ canContinue$ = this.select(Selectors.canContinue);
+
+ get fetchingAvailabilities() {
+ return this.get(Selectors.getFetchingAvailabilities);
+ }
+
+ fetchingAvailabilities$ = this.select(Selectors.getFetchingAvailabilities);
+
+ get vats$() {
+ return this._service.getVats$();
+ }
+
+ #logger = logger(() => ({
+ class: 'PurchaseOptionsStore',
+ module: 'purchase-options',
+ importMetaUrl: import.meta.url,
+ }));
+
+ constructor(
+ private _service: PurchaseOptionsService,
+ private _catalogService: DomainCatalogService,
+ ) {
+ super({
+ shoppingCartId: undefined,
+ defaultBranch: undefined,
+ inStoreBranch: undefined,
+ items: [],
+ pickupBranch: undefined,
+ purchaseOption: undefined,
+ selectedItemIds: [],
+ type: undefined,
+ availabilities: [],
+ prices: {},
+ canAddResults: [],
+ customerFeatures: {},
+ fetchingAvailabilities: [],
+ useRedemptionPoints: false,
+ });
+ }
+
+ addFetchingAvailability = this.updater(
+ (state, fetchState: FetchingAvailability) => {
+ return {
+ ...state,
+ fetchingAvailabilities: [...state.fetchingAvailabilities, fetchState],
+ };
+ },
+ );
+
+ removeFetchingAvailability = this.updater(
+ (state, fetchState: FetchingAvailability) => {
+ return {
+ ...state,
+ fetchingAvailabilities: state.fetchingAvailabilities.filter(
+ (f) => f.id !== fetchState.id,
+ ),
+ };
+ },
+ );
+
+ async initialize({
+ items,
+ shoppingCartId,
+ selectedBranch,
+ selectedCustomer,
+ type,
+ inStoreBranch,
+ pickupBranch,
+ useRedemptionPoints: showRedemptionPoints,
+ }: PurchaseOptionsModalContext) {
+ const defaultBranch = await this._service.fetchDefaultBranch().toPromise();
+
+ const customerFeatures =
+ selectedCustomer?.features.reduce(
+ (acc, feature) => {
+ acc[feature.key] = feature.value;
+ return acc;
+ },
+ {} as Record,
+ ) ?? {};
+
+ this.patchState({
+ type: type,
+ shoppingCartId,
+ useRedemptionPoints: showRedemptionPoints,
+ items: items.map((item) => ({
+ ...item,
+ quantity: item['quantity'] ?? 1,
+ })),
+ defaultBranch: selectedBranch ?? defaultBranch,
+ pickupBranch: pickupBranch ?? selectedBranch,
+ inStoreBranch: inStoreBranch ?? selectedBranch,
+ customerFeatures,
+ });
+
+ await this._loadAvailabilities();
+ await this._loadCanAdd();
+ this.selectSelectableItems();
+ }
+
+ // #region Private funtions for loading and setting Branches and Availabilities
+
+ private async _loadAvailabilities() {
+ const items = this.items;
+
+ const promises: Promise[] = [];
+
+ this._loadCatalogueAvailability();
+
+ items.forEach((item) => {
+ const itemData = mapToItemData(item, this.type);
+ if (isDownload(item)) {
+ promises.push(this._loadDownloadAvailability(itemData));
+ } else {
+ if (!isGiftCard(item, this.type)) {
+ promises.push(this._loadPickupAvailability(itemData));
+ promises.push(this._loadInStoreAvailability(itemData));
+ promises.push(this._loadDeliveryAvailability(itemData));
+ promises.push(this._loadDigDeliveryAvailability(itemData));
+ }
+ promises.push(this._loadB2bDeliveryAvailability(itemData));
+ }
+ });
+
+ await Promise.all(promises);
+ }
+
+ private async loadItemAvailability(itemId: number) {
+ const item = this.items.find((item) => item.id === itemId);
+
+ const promises: Promise[] = [];
+
+ const purchaseOption = this.purchaseOption;
+
+ if (!item) return Promise.resolve();
+
+ const itemData = mapToItemData(item, this.type);
+
+ if (purchaseOption === 'in-store' || purchaseOption === undefined) {
+ promises.push(this._loadInStoreAvailability(itemData));
+ }
+
+ if (purchaseOption === 'pickup' || purchaseOption === undefined) {
+ promises.push(this._loadPickupAvailability(itemData));
+ }
+
+ if (purchaseOption === 'delivery' || purchaseOption === undefined) {
+ promises.push(this._loadDeliveryAvailability(itemData));
+ promises.push(this._loadDigDeliveryAvailability(itemData));
+ promises.push(this._loadB2bDeliveryAvailability(itemData));
+ }
+
+ await Promise.all(promises);
+ }
+
+ private async _loadCatalogueAvailability() {
+ const items = this.items;
+ if (this.type === 'update') {
+ const items = await this._catalogService
+ .searchByEans({ eans: this.items.map((item) => item.product.ean) })
+ .toPromise();
+ if (items.result.length > 0)
+ await this._addCatalogueAvailabilities(items.result);
+ } else {
+ await this._addCatalogueAvailabilities(items as ItemDTO[]);
+ }
+ }
+
+ // #4813 - Function updated - "this.updater" didn't work, so "this.patchState" gets used instead
+ // Added firstDayOfSale for catalogAvailability via ShoppingCart Route
+ private async _addCatalogueAvailabilities(items: ItemDTO[]) {
+ const currentAvailabilities = await this.availabilities$
+ .pipe(first())
+ .toPromise();
+ const availabilities = [...currentAvailabilities];
+ items.forEach((item) => {
+ const catalogAvailability = item.catalogAvailability;
+ availabilities.push({
+ purchaseOption: 'catalog',
+ itemId: item.id,
+ ean: item.product.ean, // Hier brauchen wir zusรคtzlich die EAN - siehe purchase-options-list-item.component.ts: "get isEVT()"
+ data: {
+ price: catalogAvailability?.price,
+ firstDayOfSale: catalogAvailability?.firstDayOfSale,
+ },
+ });
+ });
+
+ this.patchState({
+ availabilities,
+ });
+ }
+
+ private async _loadPickupAvailability(itemData: ItemData) {
+ const branch = this.pickupBranch;
+ if (!branch) return Promise.resolve();
+
+ const id = uniqueId('availability_');
+ try {
+ this.addFetchingAvailability({
+ id,
+ itemId: itemData.sourceId,
+ purchaseOption: 'pickup',
+ });
+ const res = await this._service
+ .fetchPickupAvailability(itemData, itemData.quantity, branch)
+ .toPromise();
+
+ const availability: Availability = {
+ itemId: itemData.sourceId,
+ purchaseOption: 'pickup',
+ data: res,
+ };
+
+ this._checkAndSetAvailability(availability);
+ } catch (err) {
+ this.#logger.error('Failed to load pickup availability', err, () => ({
+ itemId: itemData.sourceId,
+ quantity: itemData.quantity,
+ branchId: branch?.id,
+ }));
+ }
+
+ this.removeFetchingAvailability({
+ id,
+ itemId: itemData.sourceId,
+ purchaseOption: 'pickup',
+ });
+ }
+
+ private async _loadInStoreAvailability(itemData: ItemData) {
+ const branch = this.inStoreBranch;
+ if (!branch) return Promise.resolve();
+
+ const id = uniqueId('availability_');
+ try {
+ this.addFetchingAvailability({
+ id,
+ itemId: itemData.sourceId,
+ purchaseOption: 'in-store',
+ });
+ const res = await this._service
+ .fetchInStoreAvailability(itemData, itemData.quantity, branch)
+ .toPromise();
+
+ const availability: Availability = {
+ itemId: itemData.sourceId,
+ purchaseOption: 'in-store',
+ data: res,
+ };
+
+ this._checkAndSetAvailability(availability);
+ } catch (err) {
+ this.#logger.error('Failed to load in-store availability', err, () => ({
+ itemId: itemData.sourceId,
+ quantity: itemData.quantity,
+ branchId: branch?.id,
+ }));
+ }
+
+ this.removeFetchingAvailability({
+ id,
+ itemId: itemData.sourceId,
+ purchaseOption: 'in-store',
+ });
+ }
+
+ private async _loadDeliveryAvailability(itemData: ItemData) {
+ const id = uniqueId('availability_');
+ try {
+ this.addFetchingAvailability({
+ id,
+ itemId: itemData.sourceId,
+ purchaseOption: 'delivery',
+ });
+ const res = await this._service
+ .fetchDeliveryAvailability(itemData, itemData.quantity)
+ .toPromise();
+ const availability: Availability = {
+ itemId: itemData.sourceId,
+ purchaseOption: 'delivery',
+ data: res,
+ };
+
+ this._checkAndSetAvailability(availability);
+ } catch (error) {
+ this.#logger.error('Failed to load delivery availability', error, () => ({
+ itemId: itemData.sourceId,
+ quantity: itemData.quantity,
+ }));
+ }
+
+ this.removeFetchingAvailability({
+ id,
+ itemId: itemData.sourceId,
+ purchaseOption: 'delivery',
+ });
+ }
+
+ private async _loadDigDeliveryAvailability(itemData: ItemData) {
+ const id = uniqueId('availability_');
+ try {
+ this.addFetchingAvailability({
+ id,
+ itemId: itemData.sourceId,
+ purchaseOption: 'dig-delivery',
+ });
+ const res = await this._service
+ .fetchDigDeliveryAvailability(itemData, itemData.quantity)
+ .toPromise();
+
+ const availability: Availability = {
+ itemId: itemData.sourceId,
+ purchaseOption: 'dig-delivery',
+ data: res,
+ };
+
+ this._checkAndSetAvailability(availability);
+ } catch (error) {
+ this.#logger.error(
+ 'Failed to load digital delivery availability',
+ error,
+ () => ({
+ itemId: itemData.sourceId,
+ quantity: itemData.quantity,
+ }),
+ );
+ }
+
+ this.removeFetchingAvailability({
+ id,
+ itemId: itemData.sourceId,
+ purchaseOption: 'dig-delivery',
+ });
+ }
+
+ private async _loadB2bDeliveryAvailability(itemData: ItemData) {
+ const id = uniqueId('availability_');
+ try {
+ this.addFetchingAvailability({
+ id,
+ itemId: itemData.sourceId,
+ purchaseOption: 'b2b-delivery',
+ });
+ const res = await this._service
+ .fetchB2bDeliveryAvailability(itemData, itemData.quantity)
+ .toPromise();
+
+ const availability: Availability = {
+ itemId: itemData.sourceId,
+ purchaseOption: 'b2b-delivery',
+ data: res,
+ };
+
+ this._checkAndSetAvailability(availability);
+ } catch (error) {
+ this.#logger.error(
+ 'Failed to load B2B delivery availability',
+ error,
+ () => ({
+ itemId: itemData.sourceId,
+ quantity: itemData.quantity,
+ }),
+ );
+ }
+
+ this.removeFetchingAvailability({
+ id,
+ itemId: itemData.sourceId,
+ purchaseOption: 'b2b-delivery',
+ });
+ }
+
+ private async _loadDownloadAvailability(itemData: ItemData) {
+ const id = uniqueId('availability_');
+ try {
+ this.addFetchingAvailability({
+ id,
+ itemId: itemData.sourceId,
+ purchaseOption: 'download',
+ });
+ const res = await this._service
+ .fetchDownloadAvailability(itemData)
+ .toPromise();
+
+ const availability: Availability = {
+ itemId: itemData.sourceId,
+ purchaseOption: 'download',
+ data: res,
+ };
+
+ this._checkAndSetAvailability(availability);
+ } catch (error) {
+ this.#logger.error('Failed to load download availability', error, () => ({
+ itemId: itemData.sourceId,
+ }));
+ }
+
+ this.removeFetchingAvailability({
+ id,
+ itemId: itemData.sourceId,
+ purchaseOption: 'download',
+ });
+ }
+
+ private _checkAndSetAvailability(availability: Availability) {
+ if (this._service.isAvailable(availability.data)) {
+ const availabilities = this.availabilities;
+
+ const index = availabilities.findIndex(
+ (a) =>
+ a.itemId === availability.itemId &&
+ a.purchaseOption === availability.purchaseOption,
+ );
+
+ if (index > -1) {
+ availabilities[index] = availability;
+ } else {
+ availabilities.push(availability);
+ }
+
+ this.patchState({ availabilities });
+ } else {
+ const availabilities = this.availabilities.filter(
+ (a) =>
+ !(
+ a.itemId === availability.itemId &&
+ a.purchaseOption === availability.purchaseOption
+ ),
+ );
+ this.patchState({ availabilities });
+ }
+ }
+
+ private _addCanAddResult(canAdd: CanAdd) {
+ let canAddResults = this.canAddResults;
+ canAddResults = canAddResults.filter(
+ (c) =>
+ !(
+ c.itemId === canAdd.itemId &&
+ c.purchaseOption === canAdd.purchaseOption
+ ),
+ );
+ canAddResults.push(canAdd);
+ this.patchState({ canAddResults });
+ }
+
+ private async _loadCanAdd() {
+ const payloads: Record = {
+ Abholung: [],
+ Rรผcklage: [],
+ Versand: [],
+ Download: [],
+ };
+
+ this.patchState({ canAddResults: [] });
+
+ this.items.forEach((item) => {
+ // Get Rรผcklage availability
+ const inStoreAvailability = this.availabilities.find(
+ (a) => a.itemId === item.id && a.purchaseOption === 'in-store',
+ );
+ if (inStoreAvailability) {
+ payloads['Rรผcklage'].push(
+ mapToItemPayload({
+ item,
+ availability: inStoreAvailability.data,
+ quantity: item.quantity ?? 1,
+ type: this.type,
+ }),
+ );
+ }
+
+ // Get Versand availability
+ let deliveryAvailability = this.availabilities.find(
+ (a) => a.itemId === item.id && a.purchaseOption === 'delivery',
+ );
+ const digDeliveryAvailability = this.availabilities.find(
+ (a) => a.itemId === item.id && a.purchaseOption === 'dig-delivery',
+ );
+ const b2bDeliveryAvailability = this.availabilities.find(
+ (a) => a.itemId === item.id && a.purchaseOption === 'b2b-delivery',
+ );
+ deliveryAvailability =
+ deliveryAvailability ||
+ digDeliveryAvailability ||
+ b2bDeliveryAvailability;
+ if (deliveryAvailability) {
+ payloads['Versand'].push(
+ mapToItemPayload({
+ item,
+ availability: deliveryAvailability.data,
+ quantity: item.quantity ?? 1,
+ type: this.type,
+ }),
+ );
+ }
+
+ // Get Abholung availability
+ const pickupAvailability = this.availabilities.find(
+ (a) => a.itemId === item.id && a.purchaseOption === 'pickup',
+ );
+ if (pickupAvailability) {
+ payloads['Abholung'].push(
+ mapToItemPayload({
+ item,
+ availability: pickupAvailability.data,
+ quantity: item.quantity ?? 1,
+ type: this.type,
+ }),
+ );
+ }
+
+ // Get Download availability
+ const downloadAvailability = this.availabilities.find(
+ (a) => a.itemId === item.id && a.purchaseOption === 'download',
+ );
+ if (downloadAvailability) {
+ payloads['Download'].push(
+ mapToItemPayload({
+ item,
+ availability: downloadAvailability.data,
+ quantity: item.quantity ?? 1,
+ type: this.type,
+ }),
+ );
+ }
+ });
+
+ for (const key in payloads) {
+ const itemPayloads = payloads[key];
+ if (itemPayloads.length > 0) {
+ try {
+ const res = await this._service.fetchCanAdd(
+ this.shoppingCartId,
+ key as OrderType,
+ itemPayloads,
+ this.customerFeatures,
+ );
+ res.forEach((canAdd) => {
+ const item = itemPayloads.find((i) => i.id === canAdd.id);
+ this._addCanAddResult({
+ canAdd: canAdd.status === 0,
+ itemId: item.sourceId,
+ purchaseOption: getPurchaseOptionForOrderType(key as OrderType),
+ message: canAdd.message,
+ });
+ });
+ } catch (error) {
+ this.#logger.error('Failed to load canAdd results', error, () => ({
+ orderType: key,
+ shoppingCartId: this.shoppingCartId,
+ itemCount: itemPayloads.length,
+ }));
+ }
+ }
+ }
+ }
+
+ // #endregion
+
+ setPurchaseOption(purchaseOption: PurchaseOption) {
+ if (purchaseOption !== this.purchaseOption) {
+ this.patchState({ purchaseOption });
+ }
+ }
+
+ setSelectedItem(itemId: number, value: boolean) {
+ const selectedItemIds = this.selectedItemIds;
+ if (value && !selectedItemIds.includes(itemId)) {
+ this.patchState({ selectedItemIds: [...selectedItemIds, itemId] });
+ } else if (!value && selectedItemIds.includes(itemId)) {
+ this.patchState({
+ selectedItemIds: selectedItemIds.filter((id) => id !== itemId),
+ });
+ }
+ }
+
+ selectSelectableItems() {
+ const items = this.items.filter((i) => this.canAddItem(i.id));
+
+ this.patchState({ selectedItemIds: items.map((item) => item.id) });
+ }
+
+ canAddItem(itemId: number): boolean {
+ const purchaseOption = this.purchaseOption;
+ const canAdd = this.canAddResults.find(
+ (c) => c.itemId === itemId && c.purchaseOption === purchaseOption,
+ );
+
+ if (canAdd) {
+ return canAdd.canAdd;
+ }
+
+ return false;
+ }
+
+ resetSelectedItems() {
+ this.patchState({ selectedItemIds: [] });
+ }
+
+ getItemsThatHaveAnAvailabilityForPurchaseOption(
+ purchaseOption: PurchaseOption,
+ ): Item[] {
+ return this.get(
+ Selectors.getItemsThatHaveAnAvailabilityForPurchaseOption(purchaseOption),
+ );
+ }
+
+ getItemsThatHaveAnAvailabilityForPurchaseOption$(
+ purchaseOption: PurchaseOption,
+ ): Observable- {
+ return this.select(
+ Selectors.getItemsThatHaveAnAvailabilityForPurchaseOption(purchaseOption),
+ );
+ }
+
+ getItemsThatHaveAnAvailabilityAndCanAddForPurchaseOption(
+ purchaseOption: PurchaseOption,
+ ): Item[] {
+ return this.get(
+ Selectors.getItemsThatHaveAnAvailabilityAndCanAddForPurchaseOption(
+ purchaseOption,
+ ),
+ );
+ }
+
+ getItemsThatHaveAnAvailabilityAndCanAddForPurchaseOption$(
+ purchaseOption: PurchaseOption,
+ ): Observable
- {
+ return this.select(
+ Selectors.getItemsThatHaveAnAvailabilityAndCanAddForPurchaseOption(
+ purchaseOption,
+ ),
+ );
+ }
+
+ getAvailabilitiesForItem(itemId: number): Availability[] {
+ return this.get(Selectors.getAvailabilitiesForItem(itemId));
+ }
+
+ getAvailabilitiesForItem$(itemId: number): Observable
{
+ return this.select(Selectors.getAvailabilitiesForItem(itemId));
+ }
+
+ setInStoreBranch(branch: Branch | undefined) {
+ if (this.inStoreBranch !== branch) {
+ this.patchState({ inStoreBranch: branch });
+
+ if (this.inStoreBranch) {
+ const promises = this.items.map((item) => {
+ const itemData = mapToItemData(item, this.type);
+ return this._loadInStoreAvailability(itemData);
+ });
+
+ Promise.all(promises).then(() => {
+ this._loadCanAdd();
+ });
+ }
+ }
+ }
+
+ setPickupBranch(branch: Branch | undefined) {
+ if (this.pickupBranch !== branch) {
+ this.patchState({ pickupBranch: branch });
+
+ if (this.pickupBranch) {
+ const promises = this.items.map((item) => {
+ const itemData = mapToItemData(item, this.type);
+ return this._loadPickupAvailability(itemData);
+ });
+
+ Promise.all(promises).then(() => {
+ this._loadCanAdd();
+ });
+ }
+ }
+ }
+
+ async removeItem(itemId: number, removeFromShoppingCart: boolean) {
+ const item = this.items.find((i) => i.id === itemId);
+
+ if (removeFromShoppingCart && isShoppingCartItemDTO(item, this.type)) {
+ this.removeItemFromShoppingCart(item);
+ }
+
+ const items = this.items.filter((i) => i.id !== itemId);
+ this.setSelectedItem(itemId, false);
+ this.patchState({ items });
+ }
+
+ async removeItemFromShoppingCart(item: Item) {
+ try {
+ await this._service.removeItemFromShoppingCart(
+ this.shoppingCartId,
+ item.id,
+ );
+ } catch (error) {
+ this.#logger.error(
+ 'Failed to remove item from shopping cart',
+ error,
+ () => ({
+ shoppingCartId: this.shoppingCartId,
+ itemId: item.id,
+ }),
+ );
+ }
+ }
+
+ setItemQuantity(itemId: number, quantity: number) {
+ const items = this.items;
+ if (quantity <= 0) {
+ this.removeItem(itemId, true);
+ return;
+ }
+
+ const index = items.findIndex((item) => item.id === itemId);
+ if (index > -1 && items[index].quantity !== quantity) {
+ items[index].quantity = quantity;
+ this.patchState({ items });
+ }
+
+ this.loadItemAvailability(itemId).then(() => {
+ this._loadCanAdd();
+ });
+ }
+
+ getIsGiftCard(itemId: number) {
+ return this.get(Selectors.getIsGiftCard(itemId));
+ }
+
+ getPrice(itemId: number) {
+ return this.getPriceForPurchaseOption(itemId, this.purchaseOption);
+ }
+
+ getPrice$(itemId: number) {
+ return this.purchaseOption$.pipe(
+ switchMap((po) => this.getPriceForPurchaseOption$(itemId, po)),
+ );
+ }
+
+ getPriceForPurchaseOption(itemId: number, purchaseOption: PurchaseOption) {
+ return this.get(
+ Selectors.getPriceForPurchaseOption(itemId, purchaseOption),
+ );
+ }
+
+ getPriceForPurchaseOption$(itemId: number, purchaseOption: PurchaseOption) {
+ return this.select(
+ Selectors.getPriceForPurchaseOption(itemId, purchaseOption),
+ );
+ }
+
+ getCanEditPrice(itemId: number) {
+ return this.get(Selectors.getCanEditPrice(itemId));
+ }
+
+ getCanEditPrice$(itemId: number) {
+ return this.select(Selectors.getCanEditPrice(itemId));
+ }
+
+ getCanEditVat(itemId: number) {
+ return this.get(Selectors.getCanEditVat(itemId));
+ }
+
+ getCanEditVat$(itemId: number) {
+ return this.select(Selectors.getCanEditVat(itemId));
+ }
+
+ getIsGiftCard$(itemId: number) {
+ return this.select(Selectors.getIsGiftCard(itemId));
+ }
+
+ setPrice(itemId: number, value: number, manually = false) {
+ const prices = this.prices;
+ let price = prices[itemId];
+
+ if (price?.value?.value !== value) {
+ if (!price) {
+ price = {
+ ...DEFAULT_PRICE_DTO,
+ value: { ...DEFAULT_PRICE_VALUE, value },
+ vat: manually ? price?.vat : { ...DEFAULT_VAT_VALUE, ...price?.vat },
+ };
+ } else {
+ price = { ...price, value: { ...price.value, value }, vat: price?.vat };
+ }
+
+ this.patchState({ prices: { ...prices, [itemId]: price } });
+ }
+ }
+
+ setVat(itemId: number, vat: VATDTO) {
+ const prices = this.prices;
+ let price = prices[itemId];
+ if (price?.vat?.vatType !== vat?.vatType) {
+ if (!price) {
+ price = {
+ ...DEFAULT_PRICE_DTO,
+ value: { ...DEFAULT_PRICE_VALUE, ...price?.value },
+ vat: { ...DEFAULT_VAT_VALUE, ...vat },
+ };
+ } else {
+ price = { ...price, value: price.value, vat: { ...price.vat, ...vat } };
+ }
+
+ this.patchState({ prices: { ...prices, [itemId]: price } });
+ }
+ }
+
+ getCanAddResultForItemAndCurrentPurchaseOption(itemId: number) {
+ return this.get(
+ Selectors.getCanAddResultForItemAndCurrentPurchaseOption(itemId),
+ );
+ }
+
+ getCanAddResultForItemAndCurrentPurchaseOption$(itemId: number) {
+ return this.select(
+ Selectors.getCanAddResultForItemAndCurrentPurchaseOption(itemId),
+ );
+ }
+
+ getAvailabilityWithPurchaseOption(
+ itemId: number,
+ purchaseOption: PurchaseOption,
+ ) {
+ return this.get(
+ Selectors.getAvailabilityWithPurchaseOption(itemId, purchaseOption),
+ );
+ }
+
+ getAvailabilityWithPurchaseOption$(
+ itemId: number,
+ purchaseOption: PurchaseOption,
+ ) {
+ return this.select(
+ Selectors.getAvailabilityWithPurchaseOption(itemId, purchaseOption),
+ );
+ }
+
+ getCanAddResultWithPurchaseOption(
+ itemId: number,
+ purchaseOption: PurchaseOption,
+ ) {
+ return this.get(
+ Selectors.getCanAddResultWithPurchaseOption(itemId, purchaseOption),
+ );
+ }
+
+ getCanAddResultWithPurchaseOption$(
+ itemId: number,
+ purchaseOption: PurchaseOption,
+ ) {
+ return this.select(
+ Selectors.getCanAddResultWithPurchaseOption(itemId, purchaseOption),
+ );
+ }
+
+ addItemsToShoppingCart() {
+ if (!this.canContinue || this.type !== 'add') {
+ return;
+ }
+ }
+
+ getAddToShoppingCartDTOForItem(
+ itemId: number,
+ purchaseOption: PurchaseOption,
+ ): AddToShoppingCartDTO {
+ const item = this.items.find((i) => i.id === itemId);
+
+ if (!isItemDTO(item, this.type)) {
+ throw new Error('Invalid item');
+ }
+
+ const price = this.getPriceForPurchaseOption(itemId, this.purchaseOption);
+ const availability = this.getAvailabilityWithPurchaseOption(
+ itemId,
+ purchaseOption,
+ );
+
+ 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 = undefined;
+ // Set loyalty points from item
+ loyalty = { value: redemptionPoints };
+ // Set price to 0
+ price.value.value = 0;
+ }
+
+ let destination: EntityDTOContainerOfDestinationDTO;
+ if (purchaseOption === 'delivery') {
+ destination = this._service.getDeliveryDestination(availability.data);
+ } else if (purchaseOption === 'pickup') {
+ destination = this._service.getPickupDestination(this.pickupBranch);
+ } else if (purchaseOption === 'in-store') {
+ destination = this._service.getInStoreDestination(this.inStoreBranch);
+ } else if (purchaseOption === 'download') {
+ destination = this._service.getDownloadDestination(availability.data);
+ }
+
+ return {
+ quantity: item.quantity,
+ availability: { ...availability.data, price },
+ destination,
+ itemType: item.type,
+ product: {
+ ...item.product,
+ catalogProductNumber:
+ item?.product?.catalogProductNumber ?? String(item.id),
+ },
+ promotion,
+ loyalty,
+ };
+ }
+
+ getUpdateShoppingCartItemDTOForItem(
+ itemId: number,
+ purchaseOption: PurchaseOption,
+ ): UpdateShoppingCartItemDTO {
+ const item = this.items.find((i) => i.id === itemId);
+
+ if (!isShoppingCartItemDTO(item, this.type)) {
+ throw new Error('Invalid item');
+ }
+ const price = this.getPriceForPurchaseOption(itemId, this.purchaseOption);
+ const availability = this.getAvailabilityWithPurchaseOption(
+ itemId,
+ purchaseOption,
+ );
+
+ // If loyalty points is set we know it is a redemption item
+ // we need to make sure we don't update the price
+ if (this.useRedemptionPoints) {
+ price.value.value = 0;
+ }
+
+ let destination: EntityDTOContainerOfDestinationDTO;
+ if (purchaseOption === 'delivery') {
+ destination = this._service.getDeliveryDestination(availability.data);
+ } else if (purchaseOption === 'pickup') {
+ destination = this._service.getPickupDestination(this.pickupBranch);
+ } else if (purchaseOption === 'in-store') {
+ destination = this._service.getInStoreDestination(this.inStoreBranch);
+ } else if (purchaseOption === 'download') {
+ destination = this._service.getDownloadDestination(availability.data);
+ }
+
+ return {
+ quantity: item.quantity,
+ availability: { ...availability.data, price },
+ destination,
+ };
+ }
+
+ async save() {
+ if (!this.canContinue) {
+ return;
+ }
+ const type = this.type;
+ const purchaseOption = this.purchaseOption;
+
+ if (type === 'add') {
+ const payloads = this.selectedItemIds.map((itemId) =>
+ this.getAddToShoppingCartDTOForItem(itemId, purchaseOption),
+ );
+ await this._service.addItemToShoppingCart(this.shoppingCartId, payloads);
+ } else if (type === 'update') {
+ this.selectedItemIds.map((itemId) =>
+ this.getUpdateShoppingCartItemDTOForItem(itemId, purchaseOption),
+ );
+
+ for (const itemId of this.selectedItemIds) {
+ const item = this.items.find((i) => i.id === itemId);
+ const payload = this.getUpdateShoppingCartItemDTOForItem(
+ itemId,
+ purchaseOption,
+ );
+ await this._service.updateItemInShoppingCart(
+ this.shoppingCartId,
+ item.id,
+ payload,
+ );
+ }
+ } else {
+ throw new Error('Invalid type');
+ }
+
+ this.selectedItemIds.forEach((itemId) => {
+ this.removeItem(itemId, false);
+ this.resetSelectedItems();
+ });
+ }
+
+ getFetchingAvailabilitiesForItem$(itemId: number) {
+ return this.select(Selectors.getFetchingAvailabilitiesForItem(itemId));
+ }
+}
diff --git a/apps/isa-app/src/modal/purchase-options/store/purchase-options.types.ts b/apps/isa-app/src/modal/purchase-options/store/purchase-options.types.ts
index 25bb55ab7..aba04c949 100644
--- a/apps/isa-app/src/modal/purchase-options/store/purchase-options.types.ts
+++ b/apps/isa-app/src/modal/purchase-options/store/purchase-options.types.ts
@@ -1,37 +1,56 @@
-import { ItemData as AvailabilityItemData } from '@domain/availability';
-import { ItemDTO } from '@generated/swagger/cat-search-api';
-import { AvailabilityDTO, BranchDTO, ItemPayload, ShoppingCartItemDTO } from '@generated/swagger/checkout-api';
-
-export type ActionType = 'add' | 'update';
-
-export type PurchaseOption =
- | 'delivery'
- | 'dig-delivery'
- | 'b2b-delivery'
- | 'pickup'
- | 'in-store'
- | 'download'
- | 'catalog';
-
-export type OrderType = 'Rรผcklage' | 'Abholung' | 'Versand' | 'Download';
-
-export type ItemDTOWithQuantity = ItemDTO & { quantity?: number };
-
-export type Item = ItemDTOWithQuantity | ShoppingCartItemDTO;
-
-export type Branch = BranchDTO;
-
-export type Availability = {
- itemId: number;
- purchaseOption: PurchaseOption;
- data: AvailabilityDTO & { priceMaintained?: boolean; orderDeadline?: string; firstDayOfSale?: string };
- ean?: string;
-};
-
-export type ItemData = AvailabilityItemData & { sourceId: number; quantity: number };
-
-export type ItemPayloadWithSourceId = ItemPayload & { sourceId: number };
-
-export type CanAdd = { itemId: number; purchaseOption: PurchaseOption; canAdd: boolean; message?: string };
-
-export type FetchingAvailability = { id: string; itemId: number; purchaseOption?: PurchaseOption };
+import { ItemData as AvailabilityItemData } from '@domain/availability';
+import { ItemDTO } from '@generated/swagger/cat-search-api';
+import {
+ AvailabilityDTO,
+ BranchDTO,
+ ItemPayload,
+ ShoppingCartItemDTO,
+} from '@generated/swagger/checkout-api';
+
+export type ActionType = 'add' | 'update';
+
+export type PurchaseOption =
+ | 'delivery'
+ | 'dig-delivery'
+ | 'b2b-delivery'
+ | 'pickup'
+ | 'in-store'
+ | 'download'
+ | 'catalog';
+
+export type ItemDTOWithQuantity = ItemDTO & { quantity?: number };
+
+export type Item = ItemDTOWithQuantity | ShoppingCartItemDTO;
+
+export type Branch = BranchDTO;
+
+export type Availability = {
+ itemId: number;
+ purchaseOption: PurchaseOption;
+ data: AvailabilityDTO & {
+ priceMaintained?: boolean;
+ orderDeadline?: string;
+ firstDayOfSale?: string;
+ };
+ ean?: string;
+};
+
+export type ItemData = AvailabilityItemData & {
+ sourceId: number;
+ quantity: number;
+};
+
+export type ItemPayloadWithSourceId = ItemPayload & { sourceId: number };
+
+export type CanAdd = {
+ itemId: number;
+ purchaseOption: PurchaseOption;
+ canAdd: boolean;
+ message?: string;
+};
+
+export type FetchingAvailability = {
+ id: string;
+ itemId: number;
+ purchaseOption?: PurchaseOption;
+};
diff --git a/apps/isa-app/src/page/catalog/article-details/article-details.component.ts b/apps/isa-app/src/page/catalog/article-details/article-details.component.ts
index 47380ecbf..0fe446ffe 100644
--- a/apps/isa-app/src/page/catalog/article-details/article-details.component.ts
+++ b/apps/isa-app/src/page/catalog/article-details/article-details.component.ts
@@ -1,522 +1,669 @@
-import { Component, ChangeDetectionStrategy, OnInit, OnDestroy, ElementRef, ViewChild, inject } from '@angular/core';
-import { ActivatedRoute, Router } from '@angular/router';
-import { ApplicationService } from '@core/application';
-import { DomainPrinterService } from '@domain/printer';
-import { ItemDTO as PrinterItemDTO } from '@generated/swagger/print-api';
-import { PrintModalComponent, PrintModalData } from '@modal/printer';
-import { BranchDTO } from '@generated/swagger/checkout-api';
-import { UiModalService } from '@ui/modal';
-import { ModalReviewsComponent } from '@modal/reviews';
-import { BehaviorSubject, combineLatest, Subscription } from 'rxjs';
-import { debounceTime, filter, first, map, shareReplay, switchMap, tap, withLatestFrom } from 'rxjs/operators';
-import { ArticleDetailsStore } from './article-details.store';
-import { ModalImagesComponent } from '@modal/images';
-import { ProductImageService } from '@cdn/product-image';
-import { ModalAvailabilitiesComponent } from '@modal/availabilities';
-import { slideYAnimation } from './slide.animation';
-import { BreadcrumbService } from '@core/breadcrumb';
-import { ItemDTO } from '@generated/swagger/cat-search-api';
-import { DateAdapter } from '@ui/common';
-import { DatePipe } from '@angular/common';
-import { PurchaseOptionsModalService } from '@modal/purchase-options';
-import { EnvironmentService } from '@core/environment';
-import {
- CheckoutNavigationService,
- ProductCatalogNavigationService,
- CustomerSearchNavigation,
-} from '@shared/services/navigation';
-import { DomainCheckoutService } from '@domain/checkout';
-import { Store } from '@ngrx/store';
-import moment, { Moment } from 'moment';
-
-@Component({
- selector: 'page-article-details',
- templateUrl: 'article-details.component.html',
- styleUrls: ['article-details.component.scss'],
- changeDetection: ChangeDetectionStrategy.Default,
- providers: [ArticleDetailsStore, DatePipe],
- animations: [slideYAnimation],
- standalone: false,
-})
-export class ArticleDetailsComponent implements OnInit, OnDestroy {
- private _customerSearchNavigation = inject(CustomerSearchNavigation);
-
- private readonly subscriptions = new Subscription();
- showRecommendations: boolean;
-
- imageLoaded$ = new BehaviorSubject(false);
-
- fetchingAvailabilities$ = combineLatest([
- this.store.fetchingDeliveryAvailability$,
- this.store.fetchingDeliveryB2BAvailability$,
- this.store.fetchingDeliveryDigAvailability$,
- this.store.fetchingDownloadAvailability$,
- this.store.fetchingPickUpAvailability$,
- this.store.fetchingTakeAwayAvailability$,
- ]).pipe(map((values) => values.some((v) => v)));
-
- isAvailable$ = combineLatest([
- this.store.isDeliveryAvailabilityAvailable$,
- this.store.isDeliveryDigAvailabilityAvailable$,
- this.store.isDeliveryB2BAvailabilityAvailable$,
- this.store.isPickUpAvailabilityAvailable$,
- this.store.isTakeAwayAvailabilityAvailable$,
- this.store.isDownloadAvailabilityAvailable$,
- ]).pipe(
- map((values) => values.some((v) => v)),
- shareReplay(),
- );
-
- showDeliveryTruck$ = combineLatest([
- this.store.isDeliveryAvailabilityAvailable$,
- this.store.isDeliveryDigAvailabilityAvailable$,
- ]).pipe(map(([delivery, digDelivery]) => delivery || digDelivery));
-
- showDeliveryB2BTruck$ = combineLatest([
- this.store.isDeliveryDigAvailabilityAvailable$,
- this.store.isDeliveryB2BAvailabilityAvailable$,
- ]).pipe(map(([digDelivery, b2bDelivery]) => b2bDelivery && !digDelivery));
-
- customerFeatures$ = this.applicationService.activatedProcessId$.pipe(
- switchMap((processId) => this._domainCheckoutService.getCustomerFeatures({ processId })),
- );
-
- showSubscriptionBadge$ = this.store.item$.pipe(map((item) => item?.features?.find((i) => i.key === 'PFO')));
-
- hasPromotionFeature$ = this.store.item$.pipe(map((item) => !!item?.features?.find((i) => i.key === 'Promotion')));
- promotionPoints$ = this.store.item$.pipe(map((item) => item?.redemptionPoints));
-
- showPromotionBadge$ = combineLatest([this.hasPromotionFeature$, this.promotionPoints$]).pipe(
- map(([hasPromotionFeature, promotionPoints]) => hasPromotionFeature && promotionPoints > 0),
- );
-
- showArchivBadge$ = this.store.item$.pipe(map((item) => item?.features?.find((i) => i.key === 'ARC')));
-
- isBadgeVisible$ = combineLatest([this.showSubscriptionBadge$, this.showPromotionBadge$, this.showArchivBadge$]).pipe(
- map(
- ([showSubscriptionBadge, showPromotionBadge, showArchivBadge]) =>
- showSubscriptionBadge || showPromotionBadge || showArchivBadge,
- ),
- );
-
- contributors$ = this.store.item$.pipe(map((item) => item?.product?.contributors?.split(';').map((m) => m.trim())));
-
- /**
- * Observable that emits the formatted publication date of an item.
- *
- * This observable filters the items to ensure they have a valid publication date,
- * then maps the item to the appropriate date format. It considers both the
- * `firstDayOfSale` and `publicationDate` fields, choosing the later of the two
- * if both are valid. If neither date is valid, it returns an empty string.
- *
- * The date is formatted as 'DD. MMMM YYYY'.
- *
- * Cases:
- * - If both `firstDayOfSale` and `publicationDate` are valid, the later date is taken.
- * - If only `firstDayOfSale` is valid, it is taken.
- * - If only `publicationDate` is valid, it is taken.
- * - If neither date is valid, an empty string is returned.
- *
- * @observable
- * @returns {Observable} Formatted publication date or an empty string.
- */
- publicationDate$ = this.store.item$.pipe(
- filter((item) => !!item?.product?.publicationDate),
- map((item) => {
- const firstDayOfSale = item.catalogAvailability?.firstDayOfSale
- ? moment(item.catalogAvailability.firstDayOfSale)
- : null;
- const publicationDate = item.product?.publicationDate ? moment(item.product.publicationDate) : null;
-
- if (!firstDayOfSale && !publicationDate) {
- return '';
- }
-
- const validDates = [firstDayOfSale, publicationDate].filter((date) => date?.isValid());
- const latestDate = validDates.length ? moment.max(validDates) : null;
-
- return latestDate ? latestDate.format('DD. MMMM YYYY') : '';
- }),
- );
-
- selectedBranchId$ = this.applicationService.activatedProcessId$.pipe(
- switchMap((processId) => this.applicationService.getSelectedBranch$(processId)),
- );
-
- get isTablet$() {
- return this._environment.matchTablet$;
- }
-
- get resultsPath() {
- return this._navigationService.getArticleSearchResultsPath(this.applicationService.activatedProcessId).path;
- }
-
- showMore: boolean = false;
-
- @ViewChild('detailsContainer', { read: ElementRef, static: false })
- detailsContainer: ElementRef;
-
- get detailsContainerNative(): HTMLElement {
- return this.detailsContainer?.nativeElement;
- }
-
- stockTooltipText$ = combineLatest([this.store.defaultBranch$, this.selectedBranchId$]).pipe(
- map(([defaultBranch, selectedBranch]) => {
- if (defaultBranch?.branchType !== 4 && selectedBranch && defaultBranch.id !== selectedBranch?.id) {
- return 'Sie sehen den Bestand einer anderen Filiale.';
- }
- return '';
- }),
- );
-
- priceMaintained$ = combineLatest([
- this.store.takeAwayAvailability$,
- this.store.pickUpAvailability$,
- this.store.deliveryAvailability$,
- this.store.deliveryDigAvailability$,
- this.store.deliveryB2BAvailability$,
- this.store.downloadAvailability$,
- ]).pipe(
- map((availabilities) => {
- return availabilities?.some((availability) => (availability as any)?.priceMaintained) ?? false;
- }),
- );
-
- price$ = combineLatest([
- this.store.item$,
- this.store.takeAwayAvailability$,
- this.store.pickUpAvailability$,
- this.store.deliveryAvailability$,
- this.store.deliveryDigAvailability$,
- this.store.deliveryB2BAvailability$,
- this.store.downloadAvailability$,
- ]).pipe(
- map(([item, takeAway, pickUp, delivery, deliveryDig, deliveryB2B, download]) => {
- const hasPickupOrTakeaway = takeAway?.inStock || pickUp?.inStock;
-
- if (hasPickupOrTakeaway && item?.catalogAvailability?.price?.value?.value) {
- return item?.catalogAvailability?.price;
- }
-
- if (takeAway?.price?.value?.value && takeAway?.inStock) {
- return takeAway.price;
- }
-
- if (delivery?.price?.value?.value) {
- return delivery.price;
- }
-
- if (deliveryDig?.price?.value?.value) {
- return deliveryDig.price;
- }
-
- if (deliveryB2B?.price?.value?.value) {
- return deliveryB2B.price;
- }
-
- if (download?.price?.value?.value) {
- return download.price;
- }
-
- return null;
- }),
- );
-
- constructor(
- public readonly applicationService: ApplicationService,
- private activatedRoute: ActivatedRoute,
- public readonly store: ArticleDetailsStore,
- private domainPrinterService: DomainPrinterService,
- private uiModal: UiModalService,
- private productImageService: ProductImageService,
- private breadcrumb: BreadcrumbService,
- private _dateAdapter: DateAdapter,
- private _datePipe: DatePipe,
- private _purchaseOptionsModalService: PurchaseOptionsModalService,
- private _navigationService: ProductCatalogNavigationService,
- private _checkoutNavigationService: CheckoutNavigationService,
- private _environment: EnvironmentService,
- private _router: Router,
- private _domainCheckoutService: DomainCheckoutService,
- private _store: Store,
- ) {}
-
- ngOnInit() {
- const processIdSubscription = this.activatedRoute.parent.params
- .pipe(
- debounceTime(0),
- switchMap((params) =>
- this.applicationService
- .getSelectedBranch$(Number(params.processId))
- .pipe(map((selectedBranch) => ({ params, selectedBranch }))),
- ),
- )
- .subscribe(({ params, selectedBranch }) => {
- const processId = Number(params.processId);
- const processChanged = processId !== this.store.processId;
- const branchChanged = selectedBranch?.id !== this.store?.branch?.id;
-
- if (processChanged) {
- this.store.setProcessId(processId);
- }
-
- if (branchChanged) {
- this.store.setBranch(selectedBranch);
- }
- });
-
- const id$ = this.activatedRoute.params.pipe(
- tap((_) => (this.showRecommendations = false)),
- map((params) => Number(params?.id) || undefined),
- filter((f) => !!f),
- );
-
- const ean$ = this.activatedRoute.params.pipe(
- tap((_) => (this.showRecommendations = false)),
- map((params) => params?.ean || undefined),
- filter((f) => !!f),
- );
-
- const more$ = this.activatedRoute.params.subscribe(() => (this.showMore = false));
-
- this.subscriptions.add(processIdSubscription);
- this.subscriptions.add(more$);
- this.subscriptions.add(this.store.loadDefaultBranch());
- this.subscriptions.add(this.store.loadItemById(id$));
- this.subscriptions.add(this.store.loadItemByEan(ean$));
- this.subscriptions.add(
- this.store.item$
- .pipe(
- withLatestFrom(this.isTablet$),
- filter(([item, isTablet]) => !!item),
- )
- .subscribe(([item, isTablet]) => (isTablet ? this.updateBreadcrumb(item) : this.updateBreadcrumbDesktop(item))),
- );
- }
-
- ngOnDestroy() {
- this.subscriptions.unsubscribe();
- }
-
- getDetailsPath(ean?: string) {
- return this._navigationService.getArticleDetailsPathByEan({
- processId: this.applicationService.activatedProcessId,
- ean,
- }).path;
- }
-
- async updateBreadcrumb(item: ItemDTO) {
- const crumbs = await this.breadcrumb
- .getBreadcrumbsByKeyAndTags$(this.applicationService.activatedProcessId, ['catalog', 'details', `${item.id}`])
- .pipe(first())
- .toPromise();
-
- for (const crumb of crumbs) {
- await this.breadcrumb.removeBreadcrumbsAfter(crumb.id);
- }
-
- this.breadcrumb.addBreadcrumbIfNotExists({
- key: this.applicationService.activatedProcessId,
- name: item.product?.name,
- path: this._navigationService.getArticleDetailsPath({
- processId: this.applicationService.activatedProcessId,
- itemId: item.id,
- }).path,
- params: this.activatedRoute.snapshot.queryParams,
- tags: ['catalog', 'details', `${item.id}`],
- section: 'customer',
- });
- }
-
- async showTooltip() {
- const text = await this.stockTooltipText$.pipe(first()).toPromise();
- if (!text) {
- // Show Tooltip attached to branch selector dropdown
- this._store.dispatch({ type: 'OPEN_TOOLTIP_NO_BRANCH_SELECTED' });
- }
- }
-
- async updateBreadcrumbDesktop(item: ItemDTO) {
- const crumbs = await this.breadcrumb
- .getBreadcrumbsByKeyAndTags$(this.applicationService.activatedProcessId, ['catalog', 'details'])
- .pipe(first())
- .toPromise();
-
- if (crumbs.length === 0) {
- this.breadcrumb.addBreadcrumbIfNotExists({
- key: this.applicationService.activatedProcessId,
- name: item.product?.name,
- path: this._navigationService.getArticleDetailsPath({
- processId: this.applicationService.activatedProcessId,
- itemId: item.id,
- }).path,
- params: this.activatedRoute.snapshot.queryParams,
- tags: ['catalog', 'details', `${item.id}`],
- section: 'customer',
- });
- } else {
- const crumb = crumbs.find((_) => true);
- this.breadcrumb.patchBreadcrumb(crumb.id, {
- key: this.applicationService.activatedProcessId,
- name: item.product?.name,
- path: this._navigationService.getArticleDetailsPath({
- processId: this.applicationService.activatedProcessId,
- itemId: item.id,
- }).path,
- params: this.activatedRoute.snapshot.queryParams,
- tags: ['catalog', 'details', `${item.id}`],
- section: 'customer',
- });
- }
- }
-
- async print() {
- const item = await this.store.item$.pipe(first()).toPromise();
- this.uiModal.open({
- content: PrintModalComponent,
- data: {
- printerType: 'Label',
- // TODO: remove item: item as PrinterItemDTO when the backend is fixed
- print: (printer) =>
- this.domainPrinterService.printProduct({ item: item as PrinterItemDTO, printer }).toPromise(),
- } as PrintModalData,
- config: {
- panelClass: [],
- showScrollbarY: false,
- },
- });
- }
-
- async showReviews() {
- const item = await this.store.item$.pipe(first()).toPromise();
-
- this.uiModal.open({
- content: ModalReviewsComponent,
- title: `${item.reviews?.length} Rezensionen`,
- data: item.reviews,
- });
- }
-
- async showAvailabilities() {
- const item = await this.store.item$.pipe(first()).toPromise();
- const modal = this.uiModal.open({
- content: ModalAvailabilitiesComponent,
- title: 'Bestรคnde in anderen Filialen',
- data: {
- item,
- },
- });
-
- this.subscriptions.add(
- modal.afterClosed$.subscribe((result) => {
- if (result?.data) {
- this.showPurchasingModal(result.data);
- }
- }),
- );
- }
-
- async showImages() {
- const item = await this.store.item$.pipe(first()).toPromise();
- const images = item.images ? [...item.images] : [];
-
- images.unshift({
- url: this.productImageService.getImageUrl({
- imageId: item.imageId,
- width: 400,
- height: 655,
- }),
- thumbUrl: this.productImageService.getImageUrl({
- imageId: item.imageId,
- width: 43,
- height: 69,
- }),
- });
-
- this.uiModal.open({
- content: ModalImagesComponent,
- title: item.product.name,
- data: {
- images,
- },
- });
- }
-
- async showPurchasingModal(selectedBranch?: BranchDTO) {
- const item = await this.store.item$.pipe(first()).toPromise();
-
- this._purchaseOptionsModalService
- .open({
- type: 'add',
- processId: this.applicationService.activatedProcessId,
- items: [item],
- pickupBranch: selectedBranch,
- inStoreBranch: selectedBranch,
- preSelectOption: selectedBranch ? { option: 'in-store', showOptionOnly: true } : undefined,
- })
- .afterClosed$.subscribe(async (result) => {
- if (result?.data === 'continue') {
- const customer = await this._domainCheckoutService
- .getBuyer({ processId: this.applicationService.activatedProcessId })
- .pipe(first())
- .toPromise();
- if (customer) {
- await this.navigateToShoppingCart();
- } else {
- await this.navigateToCustomerSearch();
- }
- } else if (result?.data === 'continue-shopping') {
- this.navigateToResultList();
- }
- });
- }
-
- async navigateToShoppingCart() {
- await this._checkoutNavigationService.getCheckoutReviewPath(this.applicationService.activatedProcessId).navigate();
- }
-
- async navigateToCustomerSearch() {
- const nav = this._customerSearchNavigation.defaultRoute({ processId: this.applicationService.activatedProcessId });
- try {
- const response = await this.customerFeatures$
- .pipe(
- first(),
- switchMap((customerFeatures) => {
- return this._domainCheckoutService.canSetCustomer({
- processId: this.applicationService.activatedProcessId,
- customerFeatures,
- });
- }),
- )
- .toPromise();
- this._router.navigate(nav.path, {
- queryParams: { filter_customertype: response.filter.customertype },
- });
- } catch (error) {
- this._router.navigate(nav.path);
- }
- }
-
- async navigateToResultList() {
- const processId = this.applicationService.activatedProcessId;
- let crumbs = await this.breadcrumb
- .getBreadcrumbsByKeyAndTags$(this.applicationService.activatedProcessId, ['catalog', 'details'])
- .pipe(first())
- .toPromise();
-
- const crumb = crumbs[crumbs.length - 1];
- if (crumb) {
- await this._navigationService.getArticleSearchResultsPath(processId, { queryParams: crumb.params }).navigate();
- } else {
- await this._navigationService.getArticleSearchBasePath(processId).navigate();
- }
- }
-
- scrollTop(div: HTMLDivElement) {
- this.detailsContainerNative?.scrollTo({ top: 0, behavior: 'smooth' });
- }
-
- loadImage() {
- this.imageLoaded$.next(true);
- }
-}
+import {
+ Component,
+ ChangeDetectionStrategy,
+ OnInit,
+ OnDestroy,
+ ElementRef,
+ ViewChild,
+ inject,
+} from '@angular/core';
+import { ActivatedRoute, Router } from '@angular/router';
+import { ApplicationService } from '@core/application';
+import { DomainPrinterService } from '@domain/printer';
+import { ItemDTO as PrinterItemDTO } from '@generated/swagger/print-api';
+import { PrintModalComponent, PrintModalData } from '@modal/printer';
+import { BranchDTO } from '@generated/swagger/checkout-api';
+import { UiModalService } from '@ui/modal';
+import { ModalReviewsComponent } from '@modal/reviews';
+import {
+ BehaviorSubject,
+ combineLatest,
+ firstValueFrom,
+ Subscription,
+} from 'rxjs';
+import {
+ debounceTime,
+ filter,
+ first,
+ map,
+ shareReplay,
+ switchMap,
+ tap,
+ withLatestFrom,
+} from 'rxjs/operators';
+import { ArticleDetailsStore } from './article-details.store';
+import { ModalImagesComponent } from '@modal/images';
+import { ProductImageService } from '@cdn/product-image';
+import { ModalAvailabilitiesComponent } from '@modal/availabilities';
+import { slideYAnimation } from './slide.animation';
+import { BreadcrumbService } from '@core/breadcrumb';
+import { ItemDTO } from '@generated/swagger/cat-search-api';
+import { DateAdapter } from '@ui/common';
+import { DatePipe } from '@angular/common';
+import { PurchaseOptionsModalService } from '@modal/purchase-options';
+import { EnvironmentService } from '@core/environment';
+import {
+ CheckoutNavigationService,
+ ProductCatalogNavigationService,
+ CustomerSearchNavigation,
+} from '@shared/services/navigation';
+import { DomainCheckoutService } from '@domain/checkout';
+import { Store } from '@ngrx/store';
+import moment, { Moment } from 'moment';
+import {
+ NavigateAfterRewardSelection,
+ RewardSelectionPopUpService,
+} from '@isa/checkout/shared/reward-selection-dialog';
+
+import { injectConfirmationDialog, injectFeedbackDialog } from '@isa/ui/dialog';
+
+@Component({
+ selector: 'page-article-details',
+ templateUrl: 'article-details.component.html',
+ styleUrls: ['article-details.component.scss'],
+ changeDetection: ChangeDetectionStrategy.Default,
+ providers: [ArticleDetailsStore, DatePipe],
+ animations: [slideYAnimation],
+ standalone: false,
+})
+export class ArticleDetailsComponent implements OnInit, OnDestroy {
+ private _rewardSelectionPopUpService = inject(RewardSelectionPopUpService);
+ private _customerSearchNavigation = inject(CustomerSearchNavigation);
+
+ private readonly subscriptions = new Subscription();
+ showRecommendations: boolean;
+
+ imageLoaded$ = new BehaviorSubject(false);
+
+ fetchingAvailabilities$ = combineLatest([
+ this.store.fetchingDeliveryAvailability$,
+ this.store.fetchingDeliveryB2BAvailability$,
+ this.store.fetchingDeliveryDigAvailability$,
+ this.store.fetchingDownloadAvailability$,
+ this.store.fetchingPickUpAvailability$,
+ this.store.fetchingTakeAwayAvailability$,
+ ]).pipe(map((values) => values.some((v) => v)));
+
+ isAvailable$ = combineLatest([
+ this.store.isDeliveryAvailabilityAvailable$,
+ this.store.isDeliveryDigAvailabilityAvailable$,
+ this.store.isDeliveryB2BAvailabilityAvailable$,
+ this.store.isPickUpAvailabilityAvailable$,
+ this.store.isTakeAwayAvailabilityAvailable$,
+ this.store.isDownloadAvailabilityAvailable$,
+ ]).pipe(
+ map((values) => values.some((v) => v)),
+ shareReplay(),
+ );
+
+ showDeliveryTruck$ = combineLatest([
+ this.store.isDeliveryAvailabilityAvailable$,
+ this.store.isDeliveryDigAvailabilityAvailable$,
+ ]).pipe(map(([delivery, digDelivery]) => delivery || digDelivery));
+
+ showDeliveryB2BTruck$ = combineLatest([
+ this.store.isDeliveryDigAvailabilityAvailable$,
+ this.store.isDeliveryB2BAvailabilityAvailable$,
+ ]).pipe(map(([digDelivery, b2bDelivery]) => b2bDelivery && !digDelivery));
+
+ customerFeatures$ = this.applicationService.activatedProcessId$.pipe(
+ switchMap((processId) =>
+ this._domainCheckoutService.getCustomerFeatures({ processId }),
+ ),
+ );
+
+ showSubscriptionBadge$ = this.store.item$.pipe(
+ map((item) => item?.features?.find((i) => i.key === 'PFO')),
+ );
+
+ hasPromotionFeature$ = this.store.item$.pipe(
+ map((item) => !!item?.features?.find((i) => i.key === 'Promotion')),
+ );
+ promotionPoints$ = this.store.item$.pipe(
+ map((item) => item?.redemptionPoints),
+ );
+
+ showPromotionBadge$ = combineLatest([
+ this.hasPromotionFeature$,
+ this.promotionPoints$,
+ ]).pipe(
+ map(
+ ([hasPromotionFeature, promotionPoints]) =>
+ hasPromotionFeature && promotionPoints > 0,
+ ),
+ );
+
+ showArchivBadge$ = this.store.item$.pipe(
+ map((item) => item?.features?.find((i) => i.key === 'ARC')),
+ );
+
+ isBadgeVisible$ = combineLatest([
+ this.showSubscriptionBadge$,
+ this.showPromotionBadge$,
+ this.showArchivBadge$,
+ ]).pipe(
+ map(
+ ([showSubscriptionBadge, showPromotionBadge, showArchivBadge]) =>
+ showSubscriptionBadge || showPromotionBadge || showArchivBadge,
+ ),
+ );
+
+ contributors$ = this.store.item$.pipe(
+ map((item) => item?.product?.contributors?.split(';').map((m) => m.trim())),
+ );
+
+ /**
+ * Observable that emits the formatted publication date of an item.
+ *
+ * This observable filters the items to ensure they have a valid publication date,
+ * then maps the item to the appropriate date format. It considers both the
+ * `firstDayOfSale` and `publicationDate` fields, choosing the later of the two
+ * if both are valid. If neither date is valid, it returns an empty string.
+ *
+ * The date is formatted as 'DD. MMMM YYYY'.
+ *
+ * Cases:
+ * - If both `firstDayOfSale` and `publicationDate` are valid, the later date is taken.
+ * - If only `firstDayOfSale` is valid, it is taken.
+ * - If only `publicationDate` is valid, it is taken.
+ * - If neither date is valid, an empty string is returned.
+ *
+ * @observable
+ * @returns {Observable} Formatted publication date or an empty string.
+ */
+ publicationDate$ = this.store.item$.pipe(
+ filter((item) => !!item?.product?.publicationDate),
+ map((item) => {
+ const firstDayOfSale = item.catalogAvailability?.firstDayOfSale
+ ? moment(item.catalogAvailability.firstDayOfSale)
+ : null;
+ const publicationDate = item.product?.publicationDate
+ ? moment(item.product.publicationDate)
+ : null;
+
+ if (!firstDayOfSale && !publicationDate) {
+ return '';
+ }
+
+ const validDates = [firstDayOfSale, publicationDate].filter((date) =>
+ date?.isValid(),
+ );
+ const latestDate = validDates.length ? moment.max(validDates) : null;
+
+ return latestDate ? latestDate.format('DD. MMMM YYYY') : '';
+ }),
+ );
+
+ selectedBranchId$ = this.applicationService.activatedProcessId$.pipe(
+ switchMap((processId) =>
+ this.applicationService.getSelectedBranch$(processId),
+ ),
+ );
+
+ get isTablet$() {
+ return this._environment.matchTablet$;
+ }
+
+ get resultsPath() {
+ return this._navigationService.getArticleSearchResultsPath(
+ this.applicationService.activatedProcessId,
+ ).path;
+ }
+
+ showMore: boolean = false;
+
+ @ViewChild('detailsContainer', { read: ElementRef, static: false })
+ detailsContainer: ElementRef;
+
+ get detailsContainerNative(): HTMLElement {
+ return this.detailsContainer?.nativeElement;
+ }
+
+ stockTooltipText$ = combineLatest([
+ this.store.defaultBranch$,
+ this.selectedBranchId$,
+ ]).pipe(
+ map(([defaultBranch, selectedBranch]) => {
+ if (
+ defaultBranch?.branchType !== 4 &&
+ selectedBranch &&
+ defaultBranch.id !== selectedBranch?.id
+ ) {
+ return 'Sie sehen den Bestand einer anderen Filiale.';
+ }
+ return '';
+ }),
+ );
+
+ priceMaintained$ = combineLatest([
+ this.store.takeAwayAvailability$,
+ this.store.pickUpAvailability$,
+ this.store.deliveryAvailability$,
+ this.store.deliveryDigAvailability$,
+ this.store.deliveryB2BAvailability$,
+ this.store.downloadAvailability$,
+ ]).pipe(
+ map((availabilities) => {
+ return (
+ availabilities?.some(
+ (availability) => (availability as any)?.priceMaintained,
+ ) ?? false
+ );
+ }),
+ );
+
+ price$ = combineLatest([
+ this.store.item$,
+ this.store.takeAwayAvailability$,
+ this.store.pickUpAvailability$,
+ this.store.deliveryAvailability$,
+ this.store.deliveryDigAvailability$,
+ this.store.deliveryB2BAvailability$,
+ this.store.downloadAvailability$,
+ ]).pipe(
+ map(
+ ([
+ item,
+ takeAway,
+ pickUp,
+ delivery,
+ deliveryDig,
+ deliveryB2B,
+ download,
+ ]) => {
+ const hasPickupOrTakeaway = takeAway?.inStock || pickUp?.inStock;
+
+ if (
+ hasPickupOrTakeaway &&
+ item?.catalogAvailability?.price?.value?.value
+ ) {
+ return item?.catalogAvailability?.price;
+ }
+
+ if (takeAway?.price?.value?.value && takeAway?.inStock) {
+ return takeAway.price;
+ }
+
+ if (delivery?.price?.value?.value) {
+ return delivery.price;
+ }
+
+ if (deliveryDig?.price?.value?.value) {
+ return deliveryDig.price;
+ }
+
+ if (deliveryB2B?.price?.value?.value) {
+ return deliveryB2B.price;
+ }
+
+ if (download?.price?.value?.value) {
+ return download.price;
+ }
+
+ return null;
+ },
+ ),
+ );
+
+ constructor(
+ public readonly applicationService: ApplicationService,
+ private activatedRoute: ActivatedRoute,
+ public readonly store: ArticleDetailsStore,
+ private domainPrinterService: DomainPrinterService,
+ private uiModal: UiModalService,
+ private productImageService: ProductImageService,
+ private breadcrumb: BreadcrumbService,
+ private _dateAdapter: DateAdapter,
+ private _datePipe: DatePipe,
+ private _purchaseOptionsModalService: PurchaseOptionsModalService,
+ private _navigationService: ProductCatalogNavigationService,
+ private _checkoutNavigationService: CheckoutNavigationService,
+ private _environment: EnvironmentService,
+ private _router: Router,
+ private _domainCheckoutService: DomainCheckoutService,
+ private _store: Store,
+ ) {}
+
+ ngOnInit() {
+ const processIdSubscription = this.activatedRoute.parent.params
+ .pipe(
+ debounceTime(0),
+ switchMap((params) =>
+ this.applicationService
+ .getSelectedBranch$(Number(params.processId))
+ .pipe(map((selectedBranch) => ({ params, selectedBranch }))),
+ ),
+ )
+ .subscribe(({ params, selectedBranch }) => {
+ const processId = Number(params.processId);
+ const processChanged = processId !== this.store.processId;
+ const branchChanged = selectedBranch?.id !== this.store?.branch?.id;
+
+ if (processChanged) {
+ this.store.setProcessId(processId);
+ }
+
+ if (branchChanged) {
+ this.store.setBranch(selectedBranch);
+ }
+ });
+
+ const id$ = this.activatedRoute.params.pipe(
+ tap((_) => (this.showRecommendations = false)),
+ map((params) => Number(params?.id) || undefined),
+ filter((f) => !!f),
+ );
+
+ const ean$ = this.activatedRoute.params.pipe(
+ tap((_) => (this.showRecommendations = false)),
+ map((params) => params?.ean || undefined),
+ filter((f) => !!f),
+ );
+
+ const more$ = this.activatedRoute.params.subscribe(
+ () => (this.showMore = false),
+ );
+
+ this.subscriptions.add(processIdSubscription);
+ this.subscriptions.add(more$);
+ this.subscriptions.add(this.store.loadDefaultBranch());
+ this.subscriptions.add(this.store.loadItemById(id$));
+ this.subscriptions.add(this.store.loadItemByEan(ean$));
+ this.subscriptions.add(
+ this.store.item$
+ .pipe(
+ withLatestFrom(this.isTablet$),
+ filter(([item, isTablet]) => !!item),
+ )
+ .subscribe(([item, isTablet]) =>
+ isTablet
+ ? this.updateBreadcrumb(item)
+ : this.updateBreadcrumbDesktop(item),
+ ),
+ );
+ }
+
+ ngOnDestroy() {
+ this.subscriptions.unsubscribe();
+ }
+
+ getDetailsPath(ean?: string) {
+ return this._navigationService.getArticleDetailsPathByEan({
+ processId: this.applicationService.activatedProcessId,
+ ean,
+ }).path;
+ }
+
+ async updateBreadcrumb(item: ItemDTO) {
+ const crumbs = await this.breadcrumb
+ .getBreadcrumbsByKeyAndTags$(this.applicationService.activatedProcessId, [
+ 'catalog',
+ 'details',
+ `${item.id}`,
+ ])
+ .pipe(first())
+ .toPromise();
+
+ for (const crumb of crumbs) {
+ await this.breadcrumb.removeBreadcrumbsAfter(crumb.id);
+ }
+
+ this.breadcrumb.addBreadcrumbIfNotExists({
+ key: this.applicationService.activatedProcessId,
+ name: item.product?.name,
+ path: this._navigationService.getArticleDetailsPath({
+ processId: this.applicationService.activatedProcessId,
+ itemId: item.id,
+ }).path,
+ params: this.activatedRoute.snapshot.queryParams,
+ tags: ['catalog', 'details', `${item.id}`],
+ section: 'customer',
+ });
+ }
+
+ async showTooltip() {
+ const text = await this.stockTooltipText$.pipe(first()).toPromise();
+ if (!text) {
+ // Show Tooltip attached to branch selector dropdown
+ this._store.dispatch({ type: 'OPEN_TOOLTIP_NO_BRANCH_SELECTED' });
+ }
+ }
+
+ async updateBreadcrumbDesktop(item: ItemDTO) {
+ const crumbs = await this.breadcrumb
+ .getBreadcrumbsByKeyAndTags$(this.applicationService.activatedProcessId, [
+ 'catalog',
+ 'details',
+ ])
+ .pipe(first())
+ .toPromise();
+
+ if (crumbs.length === 0) {
+ this.breadcrumb.addBreadcrumbIfNotExists({
+ key: this.applicationService.activatedProcessId,
+ name: item.product?.name,
+ path: this._navigationService.getArticleDetailsPath({
+ processId: this.applicationService.activatedProcessId,
+ itemId: item.id,
+ }).path,
+ params: this.activatedRoute.snapshot.queryParams,
+ tags: ['catalog', 'details', `${item.id}`],
+ section: 'customer',
+ });
+ } else {
+ const crumb = crumbs.find((_) => true);
+ this.breadcrumb.patchBreadcrumb(crumb.id, {
+ key: this.applicationService.activatedProcessId,
+ name: item.product?.name,
+ path: this._navigationService.getArticleDetailsPath({
+ processId: this.applicationService.activatedProcessId,
+ itemId: item.id,
+ }).path,
+ params: this.activatedRoute.snapshot.queryParams,
+ tags: ['catalog', 'details', `${item.id}`],
+ section: 'customer',
+ });
+ }
+ }
+
+ async print() {
+ const item = await this.store.item$.pipe(first()).toPromise();
+ this.uiModal.open({
+ content: PrintModalComponent,
+ data: {
+ printerType: 'Label',
+ // TODO: remove item: item as PrinterItemDTO when the backend is fixed
+ print: (printer) =>
+ this.domainPrinterService
+ .printProduct({ item: item as PrinterItemDTO, printer })
+ .toPromise(),
+ } as PrintModalData,
+ config: {
+ panelClass: [],
+ showScrollbarY: false,
+ },
+ });
+ }
+
+ async showReviews() {
+ const item = await this.store.item$.pipe(first()).toPromise();
+
+ this.uiModal.open({
+ content: ModalReviewsComponent,
+ title: `${item.reviews?.length} Rezensionen`,
+ data: item.reviews,
+ });
+ }
+
+ async showAvailabilities() {
+ const item = await this.store.item$.pipe(first()).toPromise();
+ const modal = this.uiModal.open({
+ content: ModalAvailabilitiesComponent,
+ title: 'Bestรคnde in anderen Filialen',
+ data: {
+ item,
+ },
+ });
+
+ this.subscriptions.add(
+ modal.afterClosed$.subscribe((result) => {
+ if (result?.data) {
+ this.showPurchasingModal(result.data);
+ }
+ }),
+ );
+ }
+
+ async showImages() {
+ const item = await this.store.item$.pipe(first()).toPromise();
+ const images = item.images ? [...item.images] : [];
+
+ images.unshift({
+ url: this.productImageService.getImageUrl({
+ imageId: item.imageId,
+ width: 400,
+ height: 655,
+ }),
+ thumbUrl: this.productImageService.getImageUrl({
+ imageId: item.imageId,
+ width: 43,
+ height: 69,
+ }),
+ });
+
+ this.uiModal.open({
+ content: ModalImagesComponent,
+ title: item.product.name,
+ data: {
+ images,
+ },
+ });
+ }
+
+ async showPurchasingModal(selectedBranch?: BranchDTO) {
+ const processId = this.applicationService.activatedProcessId;
+ const item = await this.store.item$.pipe(first()).toPromise();
+ const shoppingCart = await firstValueFrom(
+ this._domainCheckoutService.getShoppingCart({
+ processId,
+ }),
+ );
+
+ const modalRef = await this._purchaseOptionsModalService.open({
+ type: 'add',
+ tabId: processId,
+ shoppingCartId: shoppingCart.id,
+ items: [item],
+ pickupBranch: selectedBranch,
+ inStoreBranch: selectedBranch,
+ preSelectOption: selectedBranch
+ ? { option: 'in-store', showOptionOnly: true }
+ : undefined,
+ });
+
+ modalRef.afterClosed$.subscribe(async (result) => {
+ if (result?.data === 'continue') {
+ const customer = await this._domainCheckoutService
+ .getBuyer({ processId })
+ .pipe(first())
+ .toPromise();
+ if (customer) {
+ await this.#rewardSelectionPopUpFlow(processId);
+ } else {
+ await this.navigateToCustomerSearch();
+ }
+ } else if (result?.data === 'continue-shopping') {
+ this.navigateToResultList();
+ }
+ });
+ }
+
+ async navigateToShoppingCart() {
+ await this._checkoutNavigationService
+ .getCheckoutReviewPath(this.applicationService.activatedProcessId)
+ .navigate();
+ }
+
+ async navigateToCustomerSearch() {
+ const nav = this._customerSearchNavigation.defaultRoute({
+ processId: this.applicationService.activatedProcessId,
+ });
+ try {
+ const response = await this.customerFeatures$
+ .pipe(
+ first(),
+ switchMap((customerFeatures) => {
+ return this._domainCheckoutService.canSetCustomer({
+ processId: this.applicationService.activatedProcessId,
+ customerFeatures,
+ });
+ }),
+ )
+ .toPromise();
+ this._router.navigate(nav.path, {
+ queryParams: { filter_customertype: response.filter.customertype },
+ });
+ } catch (error) {
+ this._router.navigate(nav.path);
+ }
+ }
+
+ async navigateToResultList() {
+ const processId = this.applicationService.activatedProcessId;
+ let crumbs = await this.breadcrumb
+ .getBreadcrumbsByKeyAndTags$(this.applicationService.activatedProcessId, [
+ 'catalog',
+ 'details',
+ ])
+ .pipe(first())
+ .toPromise();
+
+ const crumb = crumbs[crumbs.length - 1];
+ if (crumb) {
+ await this._navigationService
+ .getArticleSearchResultsPath(processId, { queryParams: crumb.params })
+ .navigate();
+ } else {
+ await this._navigationService
+ .getArticleSearchBasePath(processId)
+ .navigate();
+ }
+ }
+
+ scrollTop(div: HTMLDivElement) {
+ this.detailsContainerNative?.scrollTo({ top: 0, behavior: 'smooth' });
+ }
+
+ loadImage() {
+ this.imageLoaded$.next(true);
+ }
+
+ async #reloadShoppingCart(processId: number) {
+ await this._domainCheckoutService.reloadShoppingCart({ processId });
+ }
+
+ async #navigateToReward(processId: number) {
+ await this._router.navigate([`/${processId}`, 'reward', 'cart']);
+ }
+
+ async #rewardSelectionPopUpFlow(tabId: number) {
+ await this.#reloadShoppingCart(tabId);
+ const navigate: NavigateAfterRewardSelection =
+ await this._rewardSelectionPopUpService.popUp();
+ await this.#reloadShoppingCart(tabId);
+
+ switch (navigate) {
+ case NavigateAfterRewardSelection.CART:
+ await this.navigateToShoppingCart();
+ break;
+ case NavigateAfterRewardSelection.REWARD:
+ await this.#navigateToReward(tabId);
+ break;
+ case NavigateAfterRewardSelection.CATALOG:
+ await this.navigateToResultList();
+ break;
+ default:
+ break;
+ }
+ }
+}
diff --git a/apps/isa-app/src/page/catalog/article-details/article-details.module.ts b/apps/isa-app/src/page/catalog/article-details/article-details.module.ts
index a3888800f..6b26a29e8 100644
--- a/apps/isa-app/src/page/catalog/article-details/article-details.module.ts
+++ b/apps/isa-app/src/page/catalog/article-details/article-details.module.ts
@@ -15,6 +15,14 @@ import { IconModule } from '@shared/components/icon';
import { ArticleDetailsTextComponent } from './article-details-text/article-details-text.component';
import { IconBadgeComponent } from 'apps/isa-app/src/shared/components/icon/badge/icon-badge.component';
import { MatomoModule } from 'ngx-matomo-client';
+import {
+ SelectedRewardShoppingCartResource,
+ SelectedShoppingCartResource,
+} from '@isa/checkout/data-access';
+import {
+ RewardSelectionService,
+ RewardSelectionPopUpService,
+} from '@isa/checkout/shared/reward-selection-dialog';
@NgModule({
imports: [
@@ -35,5 +43,11 @@ import { MatomoModule } from 'ngx-matomo-client';
],
exports: [ArticleDetailsComponent, ArticleRecommendationsComponent],
declarations: [ArticleDetailsComponent, ArticleRecommendationsComponent],
+ providers: [
+ SelectedShoppingCartResource,
+ SelectedRewardShoppingCartResource,
+ RewardSelectionService,
+ RewardSelectionPopUpService,
+ ],
})
export class ArticleDetailsModule {}
diff --git a/apps/isa-app/src/page/catalog/article-search/search-results/search-results.component.ts b/apps/isa-app/src/page/catalog/article-search/search-results/search-results.component.ts
index 880204e23..3554dcf3b 100644
--- a/apps/isa-app/src/page/catalog/article-search/search-results/search-results.component.ts
+++ b/apps/isa-app/src/page/catalog/article-search/search-results/search-results.component.ts
@@ -22,12 +22,21 @@ import { UiErrorModalComponent, UiModalService } from '@ui/modal';
import { CacheService } from '@core/cache';
import { isEqual } from 'lodash';
import { BehaviorSubject, combineLatest, Subscription } from 'rxjs';
-import { debounceTime, first, map, switchMap, withLatestFrom } from 'rxjs/operators';
+import {
+ debounceTime,
+ first,
+ map,
+ switchMap,
+ withLatestFrom,
+} from 'rxjs/operators';
import { ArticleSearchService } from '../article-search.store';
import { AddedToCartModalComponent } from './added-to-cart-modal/added-to-cart-modal.component';
import { SearchResultItemComponent } from './search-result-item.component';
import { ProductCatalogNavigationService } from '@shared/services/navigation';
-import { Filter, FilterInputGroupMainComponent } from '@shared/components/filter';
+import {
+ Filter,
+ FilterInputGroupMainComponent,
+} from '@shared/components/filter';
import { DomainAvailabilityService, ItemData } from '@domain/availability';
import { asapScheduler } from 'rxjs';
import { ShellService } from '@shared/shell';
@@ -39,8 +48,11 @@ import { ShellService } from '@shared/shell';
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: false,
})
-export class ArticleSearchResultsComponent implements OnInit, OnDestroy, AfterViewInit {
- @ViewChildren(SearchResultItemComponent) listItems: QueryList;
+export class ArticleSearchResultsComponent
+ implements OnInit, OnDestroy, AfterViewInit
+{
+ @ViewChildren(SearchResultItemComponent)
+ listItems: QueryList;
@ViewChild(CdkVirtualScrollViewport, { static: false })
scrollContainer: CdkVirtualScrollViewport;
@@ -59,7 +71,9 @@ export class ArticleSearchResultsComponent implements OnInit, OnDestroy, AfterVi
selectedItems$ = combineLatest([this.results$, this.selectedItemIds$]).pipe(
map(([items, selectedItemIds]) => {
- return items?.filter((item) => selectedItemIds?.find((selectedItemId) => item.id === selectedItemId));
+ return items?.filter((item) =>
+ selectedItemIds?.find((selectedItemId) => item.id === selectedItemId),
+ );
}),
);
@@ -81,7 +95,10 @@ export class ArticleSearchResultsComponent implements OnInit, OnDestroy, AfterVi
return this._environment.matchDesktopLarge();
}
- hasFilter$ = combineLatest([this.searchService.filter$, this.searchService.defaultSettings$]).pipe(
+ hasFilter$ = combineLatest([
+ this.searchService.filter$,
+ this.searchService.defaultSettings$,
+ ]).pipe(
map(([filter, defaultFilter]) => {
const filterQueryParams = filter?.getQueryParams();
return !isEqual(
@@ -100,11 +117,15 @@ export class ArticleSearchResultsComponent implements OnInit, OnDestroy, AfterVi
}
get filterQueryParams() {
- return this.cleanupQueryParams(this.searchService?.filter?.getQueryParams());
+ return this.cleanupQueryParams(
+ this.searchService?.filter?.getQueryParams(),
+ );
}
get primaryOutletActive$() {
- return this._environment.matchDesktop$.pipe(map((matches) => matches && this.route.outlet === 'primary'));
+ return this._environment.matchDesktop$.pipe(
+ map((matches) => matches && this.route.outlet === 'primary'),
+ );
}
private readonly SCROLL_INDEX_TOKEN = 'CATALOG_RESULTS_LIST_SCROLL_INDEX';
@@ -129,28 +150,42 @@ export class ArticleSearchResultsComponent implements OnInit, OnDestroy, AfterVi
ngOnInit() {
this.subscriptions.add(
- combineLatest([this.application.activatedProcessId$, this.route.queryParams])
+ combineLatest([
+ this.application.activatedProcessId$,
+ this.route.queryParams,
+ ])
.pipe(
debounceTime(0),
switchMap(([processId, queryParams]) =>
- this.application
- .getSelectedBranch$(processId)
- .pipe(map((selectedBranch) => ({ processId, queryParams, selectedBranch }))),
+ this.application.getSelectedBranch$(processId).pipe(
+ map((selectedBranch) => ({
+ processId,
+ queryParams,
+ selectedBranch,
+ })),
+ ),
),
)
.subscribe(async ({ processId, queryParams, selectedBranch }) => {
const processChanged = processId !== this.searchService.processId;
- const branchChanged = selectedBranch?.id !== this.searchService?.selectedBranch?.id;
+ const branchChanged =
+ selectedBranch?.id !== this.searchService?.selectedBranch?.id;
if (processChanged) {
- if (!!this.searchService.processId && this.searchService.filter instanceof Filter) {
+ if (
+ !!this.searchService.processId &&
+ this.searchService.filter instanceof Filter
+ ) {
this.cacheCurrentData(
this.searchService.processId,
this.searchService.filter.getQueryParams(),
this.searchService?.selectedBranch?.id,
);
- this.updateBreadcrumbs(this.searchService.processId, this.searchService.filter.getQueryParams());
+ this.updateBreadcrumbs(
+ this.searchService.processId,
+ this.searchService.filter.getQueryParams(),
+ );
}
this.searchService.setProcess(processId);
}
@@ -169,9 +204,20 @@ export class ArticleSearchResultsComponent implements OnInit, OnDestroy, AfterVi
this.scrollToItem(await this._getScrollIndexFromCache());
}
- if (!isEqual(cleanQueryParams, this.cleanupQueryParams(this.searchService.filter.getQueryParams()))) {
+ if (
+ !isEqual(
+ cleanQueryParams,
+ this.cleanupQueryParams(
+ this.searchService.filter.getQueryParams(),
+ ),
+ )
+ ) {
await this.searchService.setDefaultFilter(queryParams);
- const data = await this.getCachedData(processId, queryParams, selectedBranch?.id);
+ const data = await this.getCachedData(
+ processId,
+ queryParams,
+ selectedBranch?.id,
+ );
if (data.items?.length > 0) {
this.searchService.setItems(data.items);
@@ -179,21 +225,29 @@ export class ArticleSearchResultsComponent implements OnInit, OnDestroy, AfterVi
}
if (
data.items?.length === 0 &&
- this.route?.parent?.children?.find((childRoute) => childRoute?.outlet === 'side')?.snapshot?.routeConfig
- ?.path !== 'filter'
+ this.route?.parent?.children?.find(
+ (childRoute) => childRoute?.outlet === 'side',
+ )?.snapshot?.routeConfig?.path !== 'filter'
) {
this.search({ clear: true });
} else {
- const selectedItemIds: Array = queryParams?.selected_item_ids?.split(',') ?? [];
+ const selectedItemIds: Array =
+ queryParams?.selected_item_ids?.split(',') ?? [];
for (const id of selectedItemIds) {
if (id) {
- this.searchService.setSelected({ selected: true, itemId: Number(id) });
+ this.searchService.setSelected({
+ selected: true,
+ itemId: Number(id),
+ });
}
}
}
}
- const process = await this.application.getProcessById$(processId).pipe(first()).toPromise();
+ const process = await this.application
+ .getProcessById$(processId)
+ .pipe(first())
+ .toPromise();
if (process) {
await this.updateBreadcrumbs(processId, queryParams);
await this.createBreadcrumb(processId, queryParams);
@@ -240,7 +294,10 @@ export class ArticleSearchResultsComponent implements OnInit, OnDestroy, AfterVi
})
.navigate();
}
- } else if (searchCompleted?.clear || this.route.outlet === 'primary') {
+ } else if (
+ searchCompleted?.clear ||
+ this.route.outlet === 'primary'
+ ) {
const ean = this.route?.snapshot?.params?.ean;
if (ean) {
@@ -253,7 +310,9 @@ export class ArticleSearchResultsComponent implements OnInit, OnDestroy, AfterVi
.navigate();
} else {
await this._navigationService
- .getArticleSearchResultsPath(processId, { queryParams: params })
+ .getArticleSearchResultsPath(processId, {
+ queryParams: params,
+ })
.navigate();
}
}
@@ -266,7 +325,9 @@ export class ArticleSearchResultsComponent implements OnInit, OnDestroy, AfterVi
this.searchService.searchStarted.subscribe(async (options) => {
if (!options?.clear) {
const queryParams = {
- ...this.cleanupQueryParams(this.searchService.filter.getQueryParams()),
+ ...this.cleanupQueryParams(
+ this.searchService.filter.getQueryParams(),
+ ),
main_qs: this.sharedFilterInputGroupMain?.uiInput?.value,
};
@@ -281,11 +342,19 @@ export class ArticleSearchResultsComponent implements OnInit, OnDestroy, AfterVi
}
private _addScrollIndexToCache(index: number): void {
- this.cache.set({ processId: this.getProcessId(), token: this.SCROLL_INDEX_TOKEN }, index);
+ this.cache.set(
+ { processId: this.getProcessId(), token: this.SCROLL_INDEX_TOKEN },
+ index,
+ );
}
private async _getScrollIndexFromCache(): Promise {
- return (await this.cache.get({ processId: this.getProcessId(), token: this.SCROLL_INDEX_TOKEN })) ?? 0;
+ return (
+ (await this.cache.get({
+ processId: this.getProcessId(),
+ token: this.SCROLL_INDEX_TOKEN,
+ })) ?? 0
+ );
}
async scrollToItem(i?: number) {
@@ -303,12 +372,14 @@ export class ArticleSearchResultsComponent implements OnInit, OnDestroy, AfterVi
}
scrolledIndexChange(index: number) {
- const completeListFetched = this.searchService.items.length === this.searchService.hits;
+ const completeListFetched =
+ this.searchService.items.length === this.searchService.hits;
if (
index &&
!completeListFetched &&
- this.searchService.items.length <= this.scrollContainer?.getRenderedRange()?.end
+ this.searchService.items.length <=
+ this.scrollContainer?.getRenderedRange()?.end
) {
this.search({ clear: false });
}
@@ -326,7 +397,10 @@ export class ArticleSearchResultsComponent implements OnInit, OnDestroy, AfterVi
this.searchService.filter.getQueryParams(),
this.searchService?.selectedBranch?.id,
);
- await this.updateBreadcrumbs(this.searchService.processId, this.searchService.filter.getQueryParams());
+ await this.updateBreadcrumbs(
+ this.searchService.processId,
+ this.searchService.filter.getQueryParams(),
+ );
this.unselectAll();
}
@@ -345,7 +419,15 @@ export class ArticleSearchResultsComponent implements OnInit, OnDestroy, AfterVi
return clean;
}
- search({ filter, clear = false, orderBy = false }: { filter?: Filter; clear?: boolean; orderBy?: boolean }) {
+ search({
+ filter,
+ clear = false,
+ orderBy = false,
+ }: {
+ filter?: Filter;
+ clear?: boolean;
+ orderBy?: boolean;
+ }) {
if (filter) {
this.sharedFilterInputGroupMain.cancelAutocomplete();
}
@@ -354,19 +436,28 @@ export class ArticleSearchResultsComponent implements OnInit, OnDestroy, AfterVi
}
getDetailsPath(itemId: number) {
- return this._navigationService.getArticleDetailsPath({ processId: this.application.activatedProcessId, itemId })
- .path;
+ return this._navigationService.getArticleDetailsPath({
+ processId: this.application.activatedProcessId,
+ itemId,
+ }).path;
}
async updateBreadcrumbs(
processId: number = this.searchService.processId,
- queryParams: Record = this.searchService.filter?.getQueryParams(),
+ queryParams: Record<
+ string,
+ string
+ > = this.searchService.filter?.getQueryParams(),
) {
const selected_item_ids = this.searchService?.selectedItemIds?.toString();
if (queryParams) {
const crumbs = await this.breadcrumb
- .getBreadcrumbsByKeyAndTags$(processId, ['catalog', 'filter', 'results'])
+ .getBreadcrumbsByKeyAndTags$(processId, [
+ 'catalog',
+ 'filter',
+ 'results',
+ ])
.pipe(first())
.toPromise();
@@ -382,13 +473,18 @@ export class ArticleSearchResultsComponent implements OnInit, OnDestroy, AfterVi
}
}
- async createBreadcrumb(processId: number, queryParams: Record) {
+ async createBreadcrumb(
+ processId: number,
+ queryParams: Record,
+ ) {
if (queryParams) {
const name = queryParams.main_qs ? queryParams.main_qs : 'Alle Artikel';
await this.breadcrumb.addBreadcrumbIfNotExists({
key: processId,
name,
- path: this._navigationService.getArticleSearchResultsPath(processId, { queryParams }).path,
+ path: this._navigationService.getArticleSearchResultsPath(processId, {
+ queryParams,
+ }).path,
params: queryParams,
section: 'customer',
tags: ['catalog', 'filter', 'results'],
@@ -405,8 +501,16 @@ export class ArticleSearchResultsComponent implements OnInit, OnDestroy, AfterVi
crumbs?.forEach((crumb) => this.breadcrumb.removeBreadcrumb(crumb.id));
}
- cacheCurrentData(processId: number, params: Record = {}, branchId: number) {
- const qparams = this.cleanupQueryParams({ ...params, processId: String(processId), branchId: String(branchId) });
+ cacheCurrentData(
+ processId: number,
+ params: Record = {},
+ branchId: number,
+ ) {
+ const qparams = this.cleanupQueryParams({
+ ...params,
+ processId: String(processId),
+ branchId: String(branchId),
+ });
this.cache.set(qparams, {
items: this.searchService.items,
@@ -414,8 +518,16 @@ export class ArticleSearchResultsComponent implements OnInit, OnDestroy, AfterVi
});
}
- async getCachedData(processId: number, params: Record = {}, branchId: number) {
- const qparams = this.cleanupQueryParams({ ...params, processId: String(processId), branchId: String(branchId) });
+ async getCachedData(
+ processId: number,
+ params: Record = {},
+ branchId: number,
+ ) {
+ const qparams = this.cleanupQueryParams({
+ ...params,
+ processId: String(processId),
+ branchId: String(branchId),
+ });
const cacheData = await this.cache.get<{
items: ItemDTO[];
hits: number;
@@ -452,7 +564,12 @@ export class ArticleSearchResultsComponent implements OnInit, OnDestroy, AfterVi
}
unselectAll() {
- this.listItems.forEach((listItem) => this.searchService.setSelected({ selected: false, itemId: listItem.item.id }));
+ this.listItems.forEach((listItem) =>
+ this.searchService.setSelected({
+ selected: false,
+ itemId: listItem.item.id,
+ }),
+ );
this.searchService.patchState({ selectedItemIds: [] });
}
@@ -474,39 +591,46 @@ export class ArticleSearchResultsComponent implements OnInit, OnDestroy, AfterVi
availability: {
availabilityType: item?.catalogAvailability?.status,
price: item?.catalogAvailability?.price,
- supplierProductNumber: item?.ids?.dig ? String(item?.ids?.dig) : item?.product?.supplierProductNumber,
+ supplierProductNumber: item?.ids?.dig
+ ? String(item?.ids?.dig)
+ : item?.product?.supplierProductNumber,
},
product: {
catalogProductNumber: String(item?.id),
...item?.product,
},
itemType: item?.type,
- promotion: { points: item?.promoPoints },
+ promotion: { value: item?.promoPoints },
};
}
async addItemsToCart(item?: ItemDTO) {
- const selectedItems = !item ? await this.selectedItems$.pipe(first()).toPromise() : [item];
+ const selectedItems = !item
+ ? await this.selectedItems$.pipe(first()).toPromise()
+ : [item];
const items: AddToShoppingCartDTO[] = [];
const canAddItemsPayload = [];
for (const item of selectedItems) {
- const isDownload = item?.product?.format === 'EB' || item?.product?.format === 'DL';
+ const isDownload =
+ item?.product?.format === 'EB' || item?.product?.format === 'DL';
const price = item?.catalogAvailability?.price;
const shoppingCartItem: AddToShoppingCartDTO = {
quantity: 1,
availability: {
availabilityType: item?.catalogAvailability?.status,
price,
- supplierProductNumber: item?.ids?.dig ? String(item.ids?.dig) : item?.product?.supplierProductNumber,
+ supplierProductNumber: item?.ids?.dig
+ ? String(item.ids?.dig)
+ : item?.product?.supplierProductNumber,
},
product: {
catalogProductNumber: String(item?.id),
...item?.product,
},
itemType: item.type,
- promotion: { points: item?.promoPoints },
+ promotion: { value: item?.promoPoints },
};
if (isDownload) {
@@ -519,9 +643,14 @@ export class ArticleSearchResultsComponent implements OnInit, OnDestroy, AfterVi
.getDownloadAvailability({ item: downloadItem })
.pipe(first())
.toPromise();
- shoppingCartItem.destination = { data: { target: 16, logistician: downloadAvailability?.logistician } };
+ shoppingCartItem.destination = {
+ data: { target: 16, logistician: downloadAvailability?.logistician },
+ };
if (downloadAvailability) {
- shoppingCartItem.availability = { ...shoppingCartItem.availability, ...downloadAvailability };
+ shoppingCartItem.availability = {
+ ...shoppingCartItem.availability,
+ ...downloadAvailability,
+ };
}
canAddItemsPayload.push({
availabilities: [{ ...item.catalogAvailability, format: 'DL' }],
@@ -546,7 +675,10 @@ export class ArticleSearchResultsComponent implements OnInit, OnDestroy, AfterVi
if (response) {
const cantAdd = (response as any)?.filter((r) => r.status >= 2);
if (cantAdd?.length > 0) {
- this.openModal({ itemLength: cantAdd.length, canAddMessage: cantAdd[0].message });
+ this.openModal({
+ itemLength: cantAdd.length,
+ canAddMessage: cantAdd[0].message,
+ });
return;
}
}
@@ -571,7 +703,15 @@ export class ArticleSearchResultsComponent implements OnInit, OnDestroy, AfterVi
}
}
- openModal({ itemLength, canAddMessage, error }: { itemLength: number; canAddMessage?: string; error?: Error }) {
+ openModal({
+ itemLength,
+ canAddMessage,
+ error,
+ }: {
+ itemLength: number;
+ canAddMessage?: string;
+ error?: Error;
+ }) {
const modal = this._uiModal.open({
title:
!error && !canAddMessage
diff --git a/apps/isa-app/src/page/checkout/checkout-dummy/checkout-dummy.store.ts b/apps/isa-app/src/page/checkout/checkout-dummy/checkout-dummy.store.ts
index 42ca8ab49..9980d21e0 100644
--- a/apps/isa-app/src/page/checkout/checkout-dummy/checkout-dummy.store.ts
+++ b/apps/isa-app/src/page/checkout/checkout-dummy/checkout-dummy.store.ts
@@ -114,15 +114,21 @@ export class CheckoutDummyStore extends ComponentStore {
readonly processId$ = this._application.activatedProcessId$;
- readonly customer$ = this.processId$.pipe(switchMap((processId) => this._checkoutService.getBuyer({ processId })));
+ readonly customer$ = this.processId$.pipe(
+ switchMap((processId) => this._checkoutService.getBuyer({ processId })),
+ );
readonly customerFeatures$ = this.processId$.pipe(
- switchMap((processId) => this._checkoutService.getCustomerFeatures({ processId })),
+ switchMap((processId) =>
+ this._checkoutService.getCustomerFeatures({ processId }),
+ ),
);
readonly customerFilter$ = this.customerFeatures$.pipe(
withLatestFrom(this.processId$),
- switchMap(([customerFeatures, processId]) => this._checkoutService.canSetCustomer({ processId, customerFeatures })),
+ switchMap(([customerFeatures, processId]) =>
+ this._checkoutService.canSetCustomer({ processId, customerFeatures }),
+ ),
map((res) => res.filter),
);
@@ -169,7 +175,11 @@ export class CheckoutDummyStore extends ComponentStore {
tapResponse(
(res) => {
const item = res.result[0];
- if (!!item && item?.product?.format !== 'EB' && item?.product?.format !== 'DL') {
+ if (
+ !!item &&
+ item?.product?.format !== 'EB' &&
+ item?.product?.format !== 'DL'
+ ) {
this.patchState({
item: res.result[0],
message: '',
@@ -229,12 +239,22 @@ export class CheckoutDummyStore extends ComponentStore {
updateCart = this.effect((cb$: Observable) =>
cb$.pipe(
tap((_) => this.patchState({ fetching: true })),
- withLatestFrom(this.processId$, this.addToCartItem$, this.shoppingCartItemId$),
+ withLatestFrom(
+ this.processId$,
+ this.addToCartItem$,
+ this.shoppingCartItemId$,
+ ),
switchMap(([cb, processId, newItem, shoppingCartItemId]) => {
const availability = newItem.availability;
const quantity = newItem.quantity;
const destination = newItem.destination;
- return this.updateCartRequest({ processId, shoppingCartItemId, availability, quantity, destination }).pipe(
+ return this.updateCartRequest({
+ processId,
+ shoppingCartItemId,
+ availability,
+ quantity,
+ destination,
+ }).pipe(
tapResponse(
(res) => {
this.patchState({
@@ -270,7 +290,10 @@ export class CheckoutDummyStore extends ComponentStore {
}
addToCartRequest(processId: number, newItem: AddToShoppingCartDTO) {
- return this._checkoutService.addItemToShoppingCart({ processId, items: [newItem] });
+ return this._checkoutService.addItemToShoppingCart({
+ processId,
+ items: [newItem],
+ });
}
updateCartRequest({
@@ -297,7 +320,11 @@ export class CheckoutDummyStore extends ComponentStore {
});
}
- async createAddToCartItem(control: UntypedFormGroup, branch: BranchDTO, update?: boolean) {
+ async createAddToCartItem(
+ control: UntypedFormGroup,
+ branch: BranchDTO,
+ update?: boolean,
+ ) {
let item: ItemDTO;
const quantity = Number(control.get('quantity').value);
const price = this._createPriceDTO(control);
@@ -305,7 +332,11 @@ export class CheckoutDummyStore extends ComponentStore {
// Check if item exists or ean inside the control changed in the meantime
if (!!this.item && this.item.product.ean === control.get('ean').value) {
item = this.item;
- promoPoints = await this._getPromoPoints({ itemId: item.id, quantity, price: price.value.value });
+ promoPoints = await this._getPromoPoints({
+ itemId: item.id,
+ quantity,
+ price: price.value.value,
+ });
} else {
item = undefined;
}
@@ -316,21 +347,33 @@ export class CheckoutDummyStore extends ComponentStore {
quantity,
availability,
product,
- promotion: item ? { points: promoPoints } : undefined,
+ promotion: item ? { value: promoPoints } : undefined,
destination: {
data: { target: 1, targetBranch: { id: branch?.id } },
},
- itemType: this.item?.type ?? this.get((s) => s.shoppingCartItem)?.itemType,
+ itemType:
+ this.item?.type ?? this.get((s) => s.shoppingCartItem)?.itemType,
};
if (update) {
const existingItem = this.get((s) => s.shoppingCartItem);
- this.patchState({ addToCartItem: newItem, shoppingCartItemId: existingItem?.id });
+ this.patchState({
+ addToCartItem: newItem,
+ shoppingCartItemId: existingItem?.id,
+ });
}
this.patchState({ addToCartItem: newItem });
}
- private async _getPromoPoints({ itemId, quantity, price }: { itemId: number; quantity: number; price: number }) {
+ private async _getPromoPoints({
+ itemId,
+ quantity,
+ price,
+ }: {
+ itemId: number;
+ quantity: number;
+ price: number;
+ }) {
let points: number;
try {
points = await this._catalogService
@@ -371,7 +414,13 @@ export class CheckoutDummyStore extends ComponentStore {
};
}
- private _createAvailabilityDTO({ price, control }: { price: PriceDTO; control: UntypedFormGroup }): AvailabilityDTO {
+ private _createAvailabilityDTO({
+ price,
+ control,
+ }: {
+ price: PriceDTO;
+ control: UntypedFormGroup;
+ }): AvailabilityDTO {
return {
availabilityType: 1024,
supplier: {
@@ -383,7 +432,13 @@ export class CheckoutDummyStore extends ComponentStore {
};
}
- private _createProductDTO({ item, control }: { item?: ItemDTO; control: UntypedFormGroup }): ProductDTO {
+ private _createProductDTO({
+ item,
+ control,
+ }: {
+ item?: ItemDTO;
+ control: UntypedFormGroup;
+ }): ProductDTO {
const formValues: Partial = {
ean: control.get('ean').value,
name: control.get('name').value,
diff --git a/apps/isa-app/src/page/checkout/checkout-review/checkout-review.component.html b/apps/isa-app/src/page/checkout/checkout-review/checkout-review.component.html
index 5ddca304d..bca0deef1 100644
--- a/apps/isa-app/src/page/checkout/checkout-review/checkout-review.component.html
+++ b/apps/isa-app/src/page/checkout/checkout-review/checkout-review.component.html
@@ -13,8 +13,12 @@
keinen Artikel hinzugefรผgt.
@@ -24,11 +28,22 @@
Drucken
-
+
@if (!(isDesktop$ | async)) {
}
- @for (group of groupedItems$ | async; track trackByGroupedItems($index, group); let lastGroup = $last) {
+ @for (
+ group of groupedItems$ | async;
+ track trackByGroupedItems($index, group);
+ let lastGroup = $last
+ ) {
@if (group?.orderType !== undefined) {
@@ -62,20 +88,44 @@
group.orderType === 'Versand' ||
group.orderType === 'B2B-Versand' ||
group.orderType === 'DIG-Versand'
- ) {
-
+ ) {
+
}
}
- @for (item of group.items; track trackByItemId(i, item); let lastItem = $last; let i = $index) {
- @if (group?.orderType !== undefined && (item.features?.orderType === 'Abholung' || item.features?.orderType === 'Rรผcklage')) {
+ @for (
+ item of group.items;
+ track trackByItemId(i, item);
+ let lastItem = $last;
+ let i = $index
+ ) {
+ @if (
+ group?.orderType !== undefined &&
+ (item.features?.orderType === 'Abholung' ||
+ item.features?.orderType === 'Rรผcklage')
+ ) {
@if (item?.destination?.data?.targetBranch?.data; as targetBranch) {
- @if (i === 0 || checkIfMultipleDestinationsForOrderTypeExist(targetBranch, group, i)) {
+ @if (
+ i === 0 ||
+ checkIfMultipleDestinationsForOrderTypeExist(
+ targetBranch,
+ group,
+ i
+ )
+ ) {
+ {{ targetBranch?.name }} |
+ {{ targetBranch | branchAddress }}
- {{ targetBranch?.name }} | {{ targetBranch | branchAddress }}
}
@@ -85,7 +135,9 @@
(changeItem)="changeItem($event)"
(changeDummyItem)="changeDummyItem($event)"
(changeQuantity)="updateItemQuantity($event)"
- [quantityError]="(quantityError$ | async)[item.product.catalogProductNumber]"
+ [quantityError]="
+ (quantityError$ | async)[item.product.catalogProductNumber]
+ "
[item]="item"
[orderType]="group?.orderType"
[loadingOnItemChangeById]="loadingOnItemChangeById$ | async"
@@ -109,7 +161,11 @@
}
- Zwischensumme {{ shoppingCart?.total?.value | currency: shoppingCart?.total?.currency : 'code' }}
+ Zwischensumme
+ {{
+ shoppingCart?.total?.value
+ | currency: shoppingCart?.total?.currency : 'code'
+ }}
ohne Versandkosten
@@ -119,11 +175,13 @@
(click)="order()"
[disabled]="
showOrderButtonSpinner ||
- ((primaryCtaLabel$ | async) === 'Bestellen' && !(checkNotificationChannelControl$ | async)) ||
+ ((primaryCtaLabel$ | async) === 'Bestellen' &&
+ !(checkNotificationChannelControl$ | async)) ||
notificationsControl?.invalid ||
- ((primaryCtaLabel$ | async) === 'Bestellen' && ((checkingOla$ | async) || (checkoutIsInValid$ | async)))
+ ((primaryCtaLabel$ | async) === 'Bestellen' &&
+ ((checkingOla$ | async) || (checkoutIsInValid$ | async)))
"
- >
+ >
{{ primaryCtaLabel$ | async }}
@@ -137,4 +195,3 @@
}
-
diff --git a/apps/isa-app/src/page/checkout/checkout-review/checkout-review.component.scss b/apps/isa-app/src/page/checkout/checkout-review/checkout-review.component.scss
index 18ef18b11..0a9d7de0d 100644
--- a/apps/isa-app/src/page/checkout/checkout-review/checkout-review.component.scss
+++ b/apps/isa-app/src/page/checkout/checkout-review/checkout-review.component.scss
@@ -72,8 +72,12 @@ button {
@apply text-lg;
}
+.header-container {
+ @apply flex flex-col items-center justify-center desktop-large:pb-10 -mt-2;
+}
+
.header {
- @apply text-center text-h2 desktop-large:pb-10 -mt-2;
+ @apply text-center text-h2;
}
hr {
diff --git a/apps/isa-app/src/page/checkout/checkout-review/checkout-review.component.ts b/apps/isa-app/src/page/checkout/checkout-review/checkout-review.component.ts
index 1667fb46c..a15763063 100644
--- a/apps/isa-app/src/page/checkout/checkout-review/checkout-review.component.ts
+++ b/apps/isa-app/src/page/checkout/checkout-review/checkout-review.component.ts
@@ -1,715 +1,738 @@
-import {
- Component,
- ChangeDetectionStrategy,
- ChangeDetectorRef,
- OnInit,
- OnDestroy,
- ViewChildren,
- QueryList,
- AfterViewInit,
- TrackByFunction,
- inject,
-} from "@angular/core";
-import { Router } from "@angular/router";
-import { ApplicationService } from "@core/application";
-import { DomainAvailabilityService } from "@domain/availability";
-import { DomainCheckoutService } from "@domain/checkout";
-import {
- AvailabilityDTO,
- BranchDTO,
- DestinationDTO,
- ShoppingCartItemDTO,
-} from "@generated/swagger/checkout-api";
-import { UiMessageModalComponent, UiModalService } from "@ui/modal";
-import { PrintModalData, PrintModalComponent } from "@modal/printer";
-import { delay, first, map, switchMap, takeUntil, tap } from "rxjs/operators";
-import {
- Subject,
- NEVER,
- combineLatest,
- BehaviorSubject,
- Subscription,
-} from "rxjs";
-import { DomainCatalogService } from "@domain/catalog";
-import { BreadcrumbService } from "@core/breadcrumb";
-import { DomainPrinterService } from "@domain/printer";
-import { CheckoutDummyComponent } from "../checkout-dummy/checkout-dummy.component";
-import { CheckoutDummyData } from "../checkout-dummy/checkout-dummy-data";
-import { PurchaseOptionsModalService } from "@modal/purchase-options";
-import {
- CheckoutNavigationService,
- ProductCatalogNavigationService,
-} from "@shared/services/navigation";
-import { EnvironmentService } from "@core/environment";
-import { CheckoutReviewStore } from "./checkout-review.store";
-import { ToasterService } from "@shared/shell";
-import { ShoppingCartItemComponent } from "./shopping-cart-item/shopping-cart-item.component";
-import { CustomerSearchNavigation } from "@shared/services/navigation";
-
-@Component({
- selector: "page-checkout-review",
- templateUrl: "checkout-review.component.html",
- styleUrls: ["checkout-review.component.scss"],
- changeDetection: ChangeDetectionStrategy.OnPush,
- standalone: false,
-})
-export class CheckoutReviewComponent
- implements OnInit, OnDestroy, AfterViewInit
-{
- private _onDestroy$ = new Subject();
-
- private _customerSearchNavigation = inject(CustomerSearchNavigation);
- checkingOla$ = new BehaviorSubject(false);
-
- payer$ = this._store.payer$;
-
- buyer$ = this._store.buyer$;
-
- shoppingCart$ = this._store.shoppingCart$;
-
- fetching$ = this._store.fetching$;
-
- notificationsControl = this._store.notificationsControl;
-
- shoppingCartItemsWithoutOrderType$ = this._store.shoppingCartItems$.pipe(
- takeUntil(this._store.orderCompleted),
- map((items) =>
- items?.filter((item) => item?.features?.orderType === undefined),
- ),
- );
-
- trackByGroupedItems: TrackByFunction<{
- orderType: string;
- destination: DestinationDTO;
- items: ShoppingCartItemDTO[];
- }> = (_, item) => item?.orderType + item?.destination?.id;
-
- groupedItems$ = this._store.shoppingCartItems$.pipe(
- takeUntil(this._store.orderCompleted),
- map((items) =>
- items.reduce(
- (grouped, item) => {
- const index = grouped.findIndex((g) =>
- item?.availability?.supplyChannel === "MANUALLY"
- ? g?.orderType === "Dummy"
- : item?.features?.orderType === "DIG-Versand"
- ? g?.orderType === "Versand"
- : g?.orderType === item?.features?.orderType,
- );
-
- let group = index !== -1 ? grouped[index] : undefined;
- if (!group) {
- group = {
- orderType:
- item?.availability?.supplyChannel === "MANUALLY"
- ? "Dummy"
- : item?.features?.orderType === "DIG-Versand"
- ? "Versand"
- : item?.features?.orderType,
- destination: item?.destination?.data,
- items: [],
- };
- }
-
- group.items = [...group.items, item]?.sort(
- (a, b) =>
- a.destination?.data?.targetBranch?.id -
- b.destination?.data?.targetBranch?.id ||
- a.product?.name.localeCompare(b.product?.name),
- );
-
- if (index !== -1) {
- grouped[index] = group;
- } else {
- grouped.push(group);
- }
-
- return [...grouped].sort((a, b) =>
- a?.orderType === undefined
- ? -1
- : b?.orderType === undefined
- ? 1
- : 0,
- );
- },
- [] as {
- orderType: string;
- destination: DestinationDTO;
- items: ShoppingCartItemDTO[];
- }[],
- ),
- ),
- );
-
- totalItemCount$ = this._store.shoppingCartItems$.pipe(
- takeUntil(this._store.orderCompleted),
- map((items) => items.reduce((total, item) => total + item.quantity, 0)),
- );
-
- totalReadingPoints$ = this._store.shoppingCartItems$.pipe(
- switchMap((displayOrders) => {
- if (displayOrders.length === 0) {
- return NEVER;
- }
- const items = displayOrders
- .map((i) => {
- if (i?.product?.catalogProductNumber) {
- return {
- id: Number(i.product?.catalogProductNumber),
- quantity: i.quantity,
- price: i.unitPrice?.value?.value,
- };
- }
- })
- .filter((item) => item !== undefined);
- if (items.length !== 0) {
- return this.domainCatalogService
- .getPromotionPoints({
- items,
- })
- .pipe(
- map((response) =>
- Object.values(response.result).reduce(
- (sum, points) => sum + points,
- 0,
- ),
- ),
- );
- } else {
- return NEVER;
- }
- }),
- );
-
- customerFeatures$ = this._store.customerFeatures$;
-
- checkNotificationChannelControl$ =
- this._store.checkNotificationChannelControl$;
-
- showQuantityControlSpinnerItemId: number;
- quantityError$ = new BehaviorSubject<{ [key: string]: string }>({});
-
- primaryCtaLabel$ = combineLatest([
- this.payer$,
- this.buyer$,
- this.shoppingCartItemsWithoutOrderType$,
- ]).pipe(
- map(([payer, buyer, shoppingCartItemsWithoutOrderType]) => {
- if (shoppingCartItemsWithoutOrderType?.length > 0) {
- return "Kaufoptionen";
- }
- if (!(payer || buyer)) {
- return "Weiter";
- }
- return "Bestellen";
- }),
- );
-
- primaryCtaDisabled$ = this.quantityError$.pipe(
- map((quantityError) => {
- for (const key in quantityError) {
- if (Object.prototype.hasOwnProperty.call(quantityError, key)) {
- return true;
- }
- }
- return this.showOrderButtonSpinner;
- }),
- );
-
- loadingOnItemChangeById$ = new Subject();
- loadingOnQuantityChangeById$ = new Subject();
- showOrderButtonSpinner: boolean;
-
- checkoutIsInValid$ = this.applicationService.activatedProcessId$.pipe(
- takeUntil(this._onDestroy$),
- switchMap((processId) =>
- this.domainCheckoutService.checkoutIsValid({ processId }),
- ),
- map((valid) => !valid),
- );
-
- get productSearchBasePath() {
- return this._productNavigationService.getArticleSearchBasePath(
- this.applicationService.activatedProcessId,
- ).path;
- }
-
- get isDesktop$() {
- return this._environmentService.matchDesktopLarge$;
- }
-
- @ViewChildren(ShoppingCartItemComponent)
- private _shoppingCartItems: QueryList;
-
- olaCheckSubscription: Subscription;
-
- trackByItemId: TrackByFunction = (_, item) => item?.id;
-
- constructor(
- private domainCheckoutService: DomainCheckoutService,
- public applicationService: ApplicationService,
- private availabilityService: DomainAvailabilityService,
- private uiModal: UiModalService,
- private router: Router,
- private cdr: ChangeDetectorRef,
- private domainCatalogService: DomainCatalogService,
- private breadcrumb: BreadcrumbService,
- private domainPrinterService: DomainPrinterService,
- private _purchaseOptionsModalService: PurchaseOptionsModalService,
- private _productNavigationService: ProductCatalogNavigationService,
- private _navigationService: CheckoutNavigationService,
- private _environmentService: EnvironmentService,
- private _store: CheckoutReviewStore,
- private _toaster: ToasterService,
- ) {}
-
- async ngOnInit() {
- this.applicationService.activatedProcessId$
- .pipe(takeUntil(this._onDestroy$))
- .subscribe((_) => {
- this._store.loadShoppingCart();
- });
-
- await this.removeBreadcrumbs();
- await this.updateBreadcrumb();
-
- window["Checkout"] = {
- refreshAvailabilities: this.refreshAvailabilities.bind(this),
- };
- }
-
- ngAfterViewInit() {
- this.registerOlaCechk();
- }
-
- ngOnDestroy(): void {
- this.resetControl();
- this._onDestroy$.next();
- this._onDestroy$.complete();
- this.checkingOla$.complete();
- this.quantityError$.complete();
- this.olaCheckSubscription?.unsubscribe();
- }
-
- registerOlaCechk() {
- this.olaCheckSubscription?.unsubscribe();
- this.olaCheckSubscription = this.applicationService.activatedProcessId$
- .pipe(
- delay(250),
- switchMap((processId) =>
- this.domainCheckoutService.validateOlaStatus({
- processId,
- }),
- ),
- )
- .subscribe((result) => {
- if (!result) {
- this.refreshAvailabilities();
- }
- });
- }
-
- checkIfMultipleDestinationsForOrderTypeExist(
- targetBranch: BranchDTO,
- group: { items: ShoppingCartItemDTO[] },
- i: number,
- ) {
- return i === 0
- ? false
- : targetBranch.id !==
- group.items[i - 1].destination?.data?.targetBranch?.data.id;
- }
-
- async refreshAvailabilities() {
- this.checkingOla$.next(true);
-
- for (const itemComp of this._shoppingCartItems.toArray()) {
- await itemComp.refreshAvailability();
- await new Promise((resolve) => setTimeout(resolve, 100));
- }
- this.checkingOla$.next(false);
- }
-
- async updateBreadcrumb() {
- await this.breadcrumb.addOrUpdateBreadcrumbIfNotExists({
- key: this.applicationService.activatedProcessId,
- name: "Warenkorb",
- path: this._navigationService.getCheckoutReviewPath(
- this.applicationService.activatedProcessId,
- ).path,
- tags: ["checkout", "cart"],
- section: "customer",
- });
- }
-
- async removeBreadcrumbs() {
- const checkoutDummyCrumbs = await this.breadcrumb
- .getBreadcrumbsByKeyAndTags$(this.applicationService.activatedProcessId, [
- "checkout",
- "cart",
- "dummy",
- ])
- .pipe(first())
- .toPromise();
- checkoutDummyCrumbs.forEach(async (crumb) => {
- await this.breadcrumb.removeBreadcrumb(crumb.id, true);
- });
- }
-
- resetControl() {
- this._store.notificationsControl = undefined;
- }
-
- openDummyModal({
- data,
- changeDataFromCart = false,
- }: {
- data?: CheckoutDummyData;
- changeDataFromCart?: boolean;
- }) {
- this.uiModal.open({
- content: CheckoutDummyComponent,
- data: { ...data, changeDataFromCart },
- });
- }
-
- changeDummyItem({
- shoppingCartItem,
- }: {
- shoppingCartItem: ShoppingCartItemDTO;
- }) {
- this.openDummyModal({ data: shoppingCartItem, changeDataFromCart: true });
- }
-
- async changeItem({
- shoppingCartItem,
- }: {
- shoppingCartItem: ShoppingCartItemDTO;
- }) {
- this._purchaseOptionsModalService.open({
- processId: this.applicationService.activatedProcessId,
- items: [shoppingCartItem],
- type: "update",
- });
- }
-
- async openPrintModal() {
- const shoppingCart = await this.shoppingCart$.pipe(first()).toPromise();
- this.uiModal.open({
- content: PrintModalComponent,
- data: {
- printerType: "Label",
- print: (printer) =>
- this.domainPrinterService
- .printCart({ cartId: shoppingCart.id, printer })
- .toPromise(),
- } as PrintModalData,
- config: {
- panelClass: [],
- showScrollbarY: false,
- },
- });
- }
-
- async updateItemQuantity({
- shoppingCartItem,
- quantity,
- }: {
- shoppingCartItem: ShoppingCartItemDTO;
- quantity: number;
- }) {
- if (quantity === shoppingCartItem.quantity) {
- return;
- }
-
- this.loadingOnQuantityChangeById$.next(shoppingCartItem.id);
-
- const shoppingCartItemPrice =
- shoppingCartItem?.availability?.price?.value?.value;
- const orderType = shoppingCartItem?.features?.orderType;
- let availability: AvailabilityDTO;
-
- if (quantity) {
- const branch = shoppingCartItem?.destination?.data?.targetBranch?.data;
-
- if (orderType) {
- switch (orderType) {
- case "Rรผcklage":
- availability = await this.availabilityService
- .getTakeAwayAvailability({
- item: {
- itemId: Number(shoppingCartItem.product.catalogProductNumber),
- ean: shoppingCartItem.product.ean,
- price: shoppingCartItem.availability.price,
- },
- quantity,
- branch,
- })
- .toPromise();
-
- // this.setQuantityError(shoppingCartItem, availability, availability?.inStock < quantity);
- break;
- case "Abholung":
- availability = await this.availabilityService
- .getPickUpAvailability({
- branch,
- item: {
- itemId: Number(shoppingCartItem.product.catalogProductNumber),
- ean: shoppingCartItem.product.ean,
- price: shoppingCartItem.availability.price,
- },
- quantity,
- })
- .pipe(map((av) => av[0]))
- .toPromise();
- break;
- case "Versand":
- availability = await this.availabilityService
- .getDeliveryAvailability({
- item: {
- itemId: Number(shoppingCartItem.product.catalogProductNumber),
- ean: shoppingCartItem.product.ean,
- price: shoppingCartItem.availability.price,
- },
- quantity,
- })
- .toPromise();
- break;
- case "DIG-Versand":
- availability = await this.availabilityService
- .getDigDeliveryAvailability({
- item: {
- itemId: Number(shoppingCartItem.product.catalogProductNumber),
- ean: shoppingCartItem.product.ean,
- price: shoppingCartItem.availability.price,
- },
- quantity,
- })
- .toPromise();
- break;
- case "B2B-Versand":
- availability = await this.availabilityService
- .getB2bDeliveryAvailability({
- item: {
- itemId: Number(shoppingCartItem.product.catalogProductNumber),
- ean: shoppingCartItem.product.ean,
- price: shoppingCartItem.availability.price,
- },
- quantity,
- })
- .toPromise();
- break;
- case "Download":
- availability = await this.availabilityService
- .getDownloadAvailability({
- item: {
- itemId: Number(shoppingCartItem.product.catalogProductNumber),
- ean: shoppingCartItem.product.ean,
- price: shoppingCartItem.availability.price,
- },
- })
- .toPromise();
- break;
- }
- }
- }
-
- if (quantity === 0) {
- await this.domainCheckoutService
- .updateItemInShoppingCart({
- processId: this.applicationService.activatedProcessId,
- shoppingCartItemId: shoppingCartItem.id,
- update: {
- quantity,
- availability: null,
- },
- })
- .toPromise();
- } else if (availability) {
- // Wenn das Ergebnis der Availability Abfrage keinen Preis zurรผckliefert (z.B. HFI Geschenkkarte), wird der Preis aus der
- // Availability vor der Abfrage verwendet
- const updateAvailability = availability?.price
- ? availability
- : { ...availability, price: shoppingCartItem.availability?.price };
-
- await this.domainCheckoutService
- .updateItemInShoppingCart({
- processId: this.applicationService.activatedProcessId,
- shoppingCartItemId: shoppingCartItem.id,
- update: {
- quantity,
- availability: this.compareDeliveryAndCatalogPrice(
- updateAvailability,
- orderType,
- shoppingCartItemPrice,
- ),
- },
- })
- .toPromise();
- } else {
- await this.domainCheckoutService
- .updateItemInShoppingCart({
- processId: this.applicationService.activatedProcessId,
- shoppingCartItemId: shoppingCartItem.id,
- update: {
- quantity,
- },
- })
- .toPromise();
- }
-
- this.loadingOnQuantityChangeById$.next(undefined);
- }
-
- // Bei unbekannten Kunden und DIG Bestellung findet ein Vergleich der Preise statt
- compareDeliveryAndCatalogPrice(
- availability: AvailabilityDTO,
- orderType: string,
- shoppingCartItemPrice: number,
- ) {
- if (
- ["Versand", "DIG-Versand"].includes(orderType) &&
- shoppingCartItemPrice < availability?.price?.value?.value
- ) {
- return {
- ...availability,
- price: {
- ...availability.price,
- value: {
- ...availability.price.value,
- value: shoppingCartItemPrice,
- },
- },
- };
- }
- return availability;
- }
-
- async navigateToCustomerSearch(processId: number) {
- const nav = this._customerSearchNavigation.defaultRoute({ processId });
-
- try {
- const response = await this.customerFeatures$
- .pipe(
- first(),
- switchMap((customerFeatures) => {
- return this.domainCheckoutService.canSetCustomer({
- processId,
- customerFeatures,
- });
- }),
- )
- .toPromise();
-
- this.router.navigate(nav.path, {
- queryParams: { filter_customertype: response.filter.customertype },
- });
- } catch (error) {
- this.router.navigate(nav.path);
- }
- }
-
- async showPurchasingListModal(shoppingCartItems: ShoppingCartItemDTO[]) {
- this._purchaseOptionsModalService.open({
- processId: this.applicationService.activatedProcessId,
- items: shoppingCartItems,
- type: "update",
- });
- }
-
- async changeAddress() {
- const processId = this.applicationService.activatedProcessId;
- const customer = await this.domainCheckoutService
- .getBuyer({ processId })
- .pipe(first())
- .toPromise();
- if (!customer) {
- this.navigateToCustomerSearch(processId);
- return;
- }
- const customerId = customer.source;
- const nav = this._customerSearchNavigation.detailsRoute({
- processId,
- customerId,
- });
- this.router.navigate(nav.path);
- }
-
- async order() {
- const shoppingCartItemsWithoutOrderType =
- await this.shoppingCartItemsWithoutOrderType$.pipe(first()).toPromise();
-
- if (shoppingCartItemsWithoutOrderType?.length > 0) {
- this.showPurchasingListModal(shoppingCartItemsWithoutOrderType);
- return;
- }
-
- const processId = this.applicationService.activatedProcessId;
- const customer = await this.domainCheckoutService
- .getBuyer({ processId })
- .pipe(first())
- .toPromise();
- if (!customer) {
- this.navigateToCustomerSearch(processId);
- } else {
- try {
- this.showOrderButtonSpinner = true;
- // Ticket #3287 Um nur E-Mail und SMS Benachrichtigungen zu setzen und um alle anderen Benachrichtigungskanรคle wie z.B. Brief zu deaktivieren
- await this._store.onNotificationChange();
- const orders = await this.domainCheckoutService
- .completeCheckout({ processId })
- .toPromise();
- const orderIds = orders.map((order) => order.id).join(",");
- this._store.orderCompleted.next();
- await this.patchProcess(processId);
- await this._navigationService
- .getCheckoutSummaryPath({ processId, orderIds })
- .navigate();
- } catch (error) {
- const response = error?.error;
- let message: string = response?.message ?? "";
-
- if (
- response?.invalidProperties &&
- Object.values(response?.invalidProperties)?.length
- ) {
- message += `\n${Object.values(response.invalidProperties).join("\n")}`;
- }
-
- if (message?.length) {
- this.uiModal.open({
- content: UiMessageModalComponent,
- title: "Hinweis",
- data: { message: message.trim() },
- });
- } else if (error) {
- this.uiModal.error("Fehler beim abschlieรen der Bestellung", error);
- }
-
- if (error.status === 409) {
- this._store.orderCompleted.next();
- await this.patchProcess(processId);
- await this._navigationService
- .getCheckoutSummaryPath({ processId })
- .navigate();
- }
- } finally {
- this.showOrderButtonSpinner = false;
- this.cdr.markForCheck();
- }
- }
- }
-
- async patchProcess(processId: number) {
- const process = await this.applicationService
- .getProcessById$(processId)
- .pipe(first())
- .toPromise();
- if (process) {
- this.applicationService.patchProcess(process.id, {
- name: `${process.name} Bestellbestรคtigung`,
- type: "cart-checkout",
- });
- }
- }
-}
+import {
+ Component,
+ ChangeDetectionStrategy,
+ ChangeDetectorRef,
+ OnInit,
+ OnDestroy,
+ ViewChildren,
+ QueryList,
+ AfterViewInit,
+ TrackByFunction,
+ inject,
+} from '@angular/core';
+import { Router } from '@angular/router';
+import { ApplicationService } from '@core/application';
+import { DomainAvailabilityService } from '@domain/availability';
+import { DomainCheckoutService } from '@domain/checkout';
+import {
+ AvailabilityDTO,
+ BranchDTO,
+ DestinationDTO,
+ ShoppingCartItemDTO,
+} from '@generated/swagger/checkout-api';
+import { UiMessageModalComponent, UiModalService } from '@ui/modal';
+import { PrintModalData, PrintModalComponent } from '@modal/printer';
+import { delay, first, map, switchMap, takeUntil, tap } from 'rxjs/operators';
+import {
+ Subject,
+ NEVER,
+ combineLatest,
+ BehaviorSubject,
+ Subscription,
+ firstValueFrom,
+} from 'rxjs';
+import { DomainCatalogService } from '@domain/catalog';
+import { BreadcrumbService } from '@core/breadcrumb';
+import { DomainPrinterService } from '@domain/printer';
+import { CheckoutDummyComponent } from '../checkout-dummy/checkout-dummy.component';
+import { CheckoutDummyData } from '../checkout-dummy/checkout-dummy-data';
+import { PurchaseOptionsModalService } from '@modal/purchase-options';
+import {
+ CheckoutNavigationService,
+ ProductCatalogNavigationService,
+} from '@shared/services/navigation';
+import { EnvironmentService } from '@core/environment';
+import { CheckoutReviewStore } from './checkout-review.store';
+import { ToasterService } from '@shared/shell';
+import { ShoppingCartItemComponent } from './shopping-cart-item/shopping-cart-item.component';
+import { CustomerSearchNavigation } from '@shared/services/navigation';
+
+@Component({
+ selector: 'page-checkout-review',
+ templateUrl: 'checkout-review.component.html',
+ styleUrls: ['checkout-review.component.scss'],
+ changeDetection: ChangeDetectionStrategy.OnPush,
+ standalone: false,
+})
+export class CheckoutReviewComponent
+ implements OnInit, OnDestroy, AfterViewInit
+{
+ #checkoutService = inject(DomainCheckoutService);
+
+ private _onDestroy$ = new Subject();
+
+ private _customerSearchNavigation = inject(CustomerSearchNavigation);
+ checkingOla$ = new BehaviorSubject(false);
+
+ payer$ = this._store.payer$;
+
+ buyer$ = this._store.buyer$;
+
+ shoppingCart$ = this._store.shoppingCart$;
+
+ fetching$ = this._store.fetching$;
+
+ notificationsControl = this._store.notificationsControl;
+
+ shoppingCartItemsWithoutOrderType$ = this._store.shoppingCartItems$.pipe(
+ takeUntil(this._store.orderCompleted),
+ map((items) =>
+ items?.filter((item) => item?.features?.orderType === undefined),
+ ),
+ );
+
+ trackByGroupedItems: TrackByFunction<{
+ orderType: string;
+ destination: DestinationDTO;
+ items: ShoppingCartItemDTO[];
+ }> = (_, item) => item?.orderType + item?.destination?.id;
+
+ groupedItems$ = this._store.shoppingCartItems$.pipe(
+ takeUntil(this._store.orderCompleted),
+ map((items) =>
+ items.reduce(
+ (grouped, item) => {
+ const index = grouped.findIndex((g) =>
+ item?.availability?.supplyChannel === 'MANUALLY'
+ ? g?.orderType === 'Dummy'
+ : item?.features?.orderType === 'DIG-Versand'
+ ? g?.orderType === 'Versand'
+ : g?.orderType === item?.features?.orderType,
+ );
+
+ let group = index !== -1 ? grouped[index] : undefined;
+ if (!group) {
+ group = {
+ orderType:
+ item?.availability?.supplyChannel === 'MANUALLY'
+ ? 'Dummy'
+ : item?.features?.orderType === 'DIG-Versand'
+ ? 'Versand'
+ : item?.features?.orderType,
+ destination: item?.destination?.data,
+ items: [],
+ };
+ }
+
+ group.items = [...group.items, item]?.sort(
+ (a, b) =>
+ a.destination?.data?.targetBranch?.id -
+ b.destination?.data?.targetBranch?.id ||
+ a.product?.name.localeCompare(b.product?.name),
+ );
+
+ if (index !== -1) {
+ grouped[index] = group;
+ } else {
+ grouped.push(group);
+ }
+
+ return [...grouped].sort((a, b) =>
+ a?.orderType === undefined
+ ? -1
+ : b?.orderType === undefined
+ ? 1
+ : 0,
+ );
+ },
+ [] as {
+ orderType: string;
+ destination: DestinationDTO;
+ items: ShoppingCartItemDTO[];
+ }[],
+ ),
+ ),
+ );
+
+ orderTypesExist$ = this.groupedItems$.pipe(
+ map((groups) => groups?.every((group) => group?.orderType !== undefined)),
+ );
+
+ totalItemCount$ = this._store.shoppingCartItems$.pipe(
+ takeUntil(this._store.orderCompleted),
+ map((items) => items.reduce((total, item) => total + item.quantity, 0)),
+ );
+
+ totalReadingPoints$ = this._store.shoppingCartItems$.pipe(
+ switchMap((displayOrders) => {
+ if (displayOrders.length === 0) {
+ return NEVER;
+ }
+ const items = displayOrders
+ .map((i) => {
+ if (i?.product?.catalogProductNumber) {
+ return {
+ id: Number(i.product?.catalogProductNumber),
+ quantity: i.quantity,
+ price: i.unitPrice?.value?.value,
+ };
+ }
+ })
+ .filter((item) => item !== undefined);
+ if (items.length !== 0) {
+ return this.domainCatalogService
+ .getPromotionPoints({
+ items,
+ })
+ .pipe(
+ map((response) =>
+ Object.values(response.result).reduce(
+ (sum, points) => sum + points,
+ 0,
+ ),
+ ),
+ );
+ } else {
+ return NEVER;
+ }
+ }),
+ );
+
+ customerFeatures$ = this._store.customerFeatures$;
+
+ checkNotificationChannelControl$ =
+ this._store.checkNotificationChannelControl$;
+
+ showQuantityControlSpinnerItemId: number;
+ quantityError$ = new BehaviorSubject<{ [key: string]: string }>({});
+
+ primaryCtaLabel$ = combineLatest([
+ this.payer$,
+ this.buyer$,
+ this.shoppingCartItemsWithoutOrderType$,
+ ]).pipe(
+ map(([payer, buyer, shoppingCartItemsWithoutOrderType]) => {
+ if (shoppingCartItemsWithoutOrderType?.length > 0) {
+ return 'Kaufoptionen';
+ }
+ if (!(payer || buyer)) {
+ return 'Weiter';
+ }
+ return 'Bestellen';
+ }),
+ );
+
+ primaryCtaDisabled$ = this.quantityError$.pipe(
+ map((quantityError) => {
+ for (const key in quantityError) {
+ if (Object.prototype.hasOwnProperty.call(quantityError, key)) {
+ return true;
+ }
+ }
+ return this.showOrderButtonSpinner;
+ }),
+ );
+
+ loadingOnItemChangeById$ = new Subject();
+ loadingOnQuantityChangeById$ = new Subject();
+ showOrderButtonSpinner: boolean;
+
+ checkoutIsInValid$ = this.applicationService.activatedProcessId$.pipe(
+ takeUntil(this._onDestroy$),
+ switchMap((processId) =>
+ this.domainCheckoutService.checkoutIsValid({ processId }),
+ ),
+ map((valid) => !valid),
+ );
+
+ get productSearchBasePath() {
+ return this._productNavigationService.getArticleSearchBasePath(
+ this.applicationService.activatedProcessId,
+ ).path;
+ }
+
+ get isDesktop$() {
+ return this._environmentService.matchDesktopLarge$;
+ }
+
+ @ViewChildren(ShoppingCartItemComponent)
+ private _shoppingCartItems: QueryList;
+
+ olaCheckSubscription: Subscription;
+
+ trackByItemId: TrackByFunction = (_, item) => item?.id;
+
+ constructor(
+ private domainCheckoutService: DomainCheckoutService,
+ public applicationService: ApplicationService,
+ private availabilityService: DomainAvailabilityService,
+ private uiModal: UiModalService,
+ private router: Router,
+ private cdr: ChangeDetectorRef,
+ private domainCatalogService: DomainCatalogService,
+ private breadcrumb: BreadcrumbService,
+ private domainPrinterService: DomainPrinterService,
+ private _purchaseOptionsModalService: PurchaseOptionsModalService,
+ private _productNavigationService: ProductCatalogNavigationService,
+ private _navigationService: CheckoutNavigationService,
+ private _environmentService: EnvironmentService,
+ private _store: CheckoutReviewStore,
+ private _toaster: ToasterService,
+ ) {}
+
+ async ngOnInit() {
+ this.applicationService.activatedProcessId$
+ .pipe(takeUntil(this._onDestroy$))
+ .subscribe((_) => {
+ this._store.loadShoppingCart();
+ });
+
+ await this.removeBreadcrumbs();
+ await this.updateBreadcrumb();
+
+ window['Checkout'] = {
+ refreshAvailabilities: this.refreshAvailabilities.bind(this),
+ };
+ }
+
+ ngAfterViewInit() {
+ this.registerOlaCechk();
+ }
+
+ ngOnDestroy(): void {
+ this.resetControl();
+ this._onDestroy$.next();
+ this._onDestroy$.complete();
+ this.checkingOla$.complete();
+ this.quantityError$.complete();
+ this.olaCheckSubscription?.unsubscribe();
+ }
+
+ registerOlaCechk() {
+ this.olaCheckSubscription?.unsubscribe();
+ this.olaCheckSubscription = this.applicationService.activatedProcessId$
+ .pipe(
+ delay(250),
+ switchMap((processId) =>
+ this.domainCheckoutService.validateOlaStatus({
+ processId,
+ }),
+ ),
+ )
+ .subscribe((result) => {
+ if (!result) {
+ this.refreshAvailabilities();
+ }
+ });
+ }
+
+ checkIfMultipleDestinationsForOrderTypeExist(
+ targetBranch: BranchDTO,
+ group: { items: ShoppingCartItemDTO[] },
+ i: number,
+ ) {
+ return i === 0
+ ? false
+ : targetBranch.id !==
+ group.items[i - 1].destination?.data?.targetBranch?.data.id;
+ }
+
+ async refreshAvailabilities() {
+ this.checkingOla$.next(true);
+
+ for (const itemComp of this._shoppingCartItems.toArray()) {
+ await itemComp.refreshAvailability();
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ }
+ this.checkingOla$.next(false);
+ }
+
+ async updateBreadcrumb() {
+ await this.breadcrumb.addOrUpdateBreadcrumbIfNotExists({
+ key: this.applicationService.activatedProcessId,
+ name: 'Warenkorb',
+ path: this._navigationService.getCheckoutReviewPath(
+ this.applicationService.activatedProcessId,
+ ).path,
+ tags: ['checkout', 'cart'],
+ section: 'customer',
+ });
+ }
+
+ async removeBreadcrumbs() {
+ const checkoutDummyCrumbs = await this.breadcrumb
+ .getBreadcrumbsByKeyAndTags$(this.applicationService.activatedProcessId, [
+ 'checkout',
+ 'cart',
+ 'dummy',
+ ])
+ .pipe(first())
+ .toPromise();
+ checkoutDummyCrumbs.forEach(async (crumb) => {
+ await this.breadcrumb.removeBreadcrumb(crumb.id, true);
+ });
+ }
+
+ resetControl() {
+ this._store.notificationsControl = undefined;
+ }
+
+ openDummyModal({
+ data,
+ changeDataFromCart = false,
+ }: {
+ data?: CheckoutDummyData;
+ changeDataFromCart?: boolean;
+ }) {
+ this.uiModal.open({
+ content: CheckoutDummyComponent,
+ data: { ...data, changeDataFromCart },
+ });
+ }
+
+ changeDummyItem({
+ shoppingCartItem,
+ }: {
+ shoppingCartItem: ShoppingCartItemDTO;
+ }) {
+ this.openDummyModal({ data: shoppingCartItem, changeDataFromCart: true });
+ }
+
+ async changeItem({
+ shoppingCartItem,
+ }: {
+ shoppingCartItem: ShoppingCartItemDTO;
+ }) {
+ const shoppingCart = await firstValueFrom(this.shoppingCart$);
+ const modalRef = await this._purchaseOptionsModalService.open({
+ tabId: this.applicationService.activatedProcessId,
+ shoppingCartId: shoppingCart.id,
+ items: [shoppingCartItem],
+ type: 'update',
+ });
+
+ await firstValueFrom(modalRef.afterClosed$);
+ // Reload Shopping Cart after modal is closed to get updated items
+ this.#checkoutService.reloadShoppingCart({
+ processId: this.applicationService.activatedProcessId,
+ });
+ }
+
+ async openPrintModal() {
+ const shoppingCart = await this.shoppingCart$.pipe(first()).toPromise();
+ this.uiModal.open({
+ content: PrintModalComponent,
+ data: {
+ printerType: 'Label',
+ print: (printer) =>
+ this.domainPrinterService
+ .printCart({ cartId: shoppingCart.id, printer })
+ .toPromise(),
+ } as PrintModalData,
+ config: {
+ panelClass: [],
+ showScrollbarY: false,
+ },
+ });
+ }
+
+ async updateItemQuantity({
+ shoppingCartItem,
+ quantity,
+ }: {
+ shoppingCartItem: ShoppingCartItemDTO;
+ quantity: number;
+ }) {
+ if (quantity === shoppingCartItem.quantity) {
+ return;
+ }
+
+ this.loadingOnQuantityChangeById$.next(shoppingCartItem.id);
+
+ const shoppingCartItemPrice =
+ shoppingCartItem?.availability?.price?.value?.value;
+ const orderType = shoppingCartItem?.features?.orderType;
+ let availability: AvailabilityDTO;
+
+ if (quantity) {
+ const branch = shoppingCartItem?.destination?.data?.targetBranch?.data;
+
+ if (orderType) {
+ switch (orderType) {
+ case 'Rรผcklage':
+ availability = await this.availabilityService
+ .getTakeAwayAvailability({
+ item: {
+ itemId: Number(shoppingCartItem.product.catalogProductNumber),
+ ean: shoppingCartItem.product.ean,
+ price: shoppingCartItem.availability.price,
+ },
+ quantity,
+ branch,
+ })
+ .toPromise();
+
+ // this.setQuantityError(shoppingCartItem, availability, availability?.inStock < quantity);
+ break;
+ case 'Abholung':
+ availability = await this.availabilityService
+ .getPickUpAvailability({
+ branch,
+ item: {
+ itemId: Number(shoppingCartItem.product.catalogProductNumber),
+ ean: shoppingCartItem.product.ean,
+ price: shoppingCartItem.availability.price,
+ },
+ quantity,
+ })
+ .pipe(map((av) => av[0]))
+ .toPromise();
+ break;
+ case 'Versand':
+ availability = await this.availabilityService
+ .getDeliveryAvailability({
+ item: {
+ itemId: Number(shoppingCartItem.product.catalogProductNumber),
+ ean: shoppingCartItem.product.ean,
+ price: shoppingCartItem.availability.price,
+ },
+ quantity,
+ })
+ .toPromise();
+ break;
+ case 'DIG-Versand':
+ availability = await this.availabilityService
+ .getDigDeliveryAvailability({
+ item: {
+ itemId: Number(shoppingCartItem.product.catalogProductNumber),
+ ean: shoppingCartItem.product.ean,
+ price: shoppingCartItem.availability.price,
+ },
+ quantity,
+ })
+ .toPromise();
+ break;
+ case 'B2B-Versand':
+ availability = await this.availabilityService
+ .getB2bDeliveryAvailability({
+ item: {
+ itemId: Number(shoppingCartItem.product.catalogProductNumber),
+ ean: shoppingCartItem.product.ean,
+ price: shoppingCartItem.availability.price,
+ },
+ quantity,
+ })
+ .toPromise();
+ break;
+ case 'Download':
+ availability = await this.availabilityService
+ .getDownloadAvailability({
+ item: {
+ itemId: Number(shoppingCartItem.product.catalogProductNumber),
+ ean: shoppingCartItem.product.ean,
+ price: shoppingCartItem.availability.price,
+ },
+ })
+ .toPromise();
+ break;
+ }
+ }
+ }
+
+ if (quantity === 0) {
+ await this.domainCheckoutService
+ .updateItemInShoppingCart({
+ processId: this.applicationService.activatedProcessId,
+ shoppingCartItemId: shoppingCartItem.id,
+ update: {
+ quantity,
+ availability: null,
+ },
+ })
+ .toPromise();
+ } else if (availability) {
+ // Wenn das Ergebnis der Availability Abfrage keinen Preis zurรผckliefert (z.B. HFI Geschenkkarte), wird der Preis aus der
+ // Availability vor der Abfrage verwendet
+ const updateAvailability = availability?.price
+ ? availability
+ : { ...availability, price: shoppingCartItem.availability?.price };
+
+ await this.domainCheckoutService
+ .updateItemInShoppingCart({
+ processId: this.applicationService.activatedProcessId,
+ shoppingCartItemId: shoppingCartItem.id,
+ update: {
+ quantity,
+ availability: this.compareDeliveryAndCatalogPrice(
+ updateAvailability,
+ orderType,
+ shoppingCartItemPrice,
+ ),
+ },
+ })
+ .toPromise();
+ } else {
+ await this.domainCheckoutService
+ .updateItemInShoppingCart({
+ processId: this.applicationService.activatedProcessId,
+ shoppingCartItemId: shoppingCartItem.id,
+ update: {
+ quantity,
+ },
+ })
+ .toPromise();
+ }
+
+ this.loadingOnQuantityChangeById$.next(undefined);
+ }
+
+ // Bei unbekannten Kunden und DIG Bestellung findet ein Vergleich der Preise statt
+ compareDeliveryAndCatalogPrice(
+ availability: AvailabilityDTO,
+ orderType: string,
+ shoppingCartItemPrice: number,
+ ) {
+ if (
+ ['Versand', 'DIG-Versand'].includes(orderType) &&
+ shoppingCartItemPrice < availability?.price?.value?.value
+ ) {
+ return {
+ ...availability,
+ price: {
+ ...availability.price,
+ value: {
+ ...availability.price.value,
+ value: shoppingCartItemPrice,
+ },
+ },
+ };
+ }
+ return availability;
+ }
+
+ async navigateToCustomerSearch(processId: number) {
+ const nav = this._customerSearchNavigation.defaultRoute({ processId });
+
+ try {
+ const response = await this.customerFeatures$
+ .pipe(
+ first(),
+ switchMap((customerFeatures) => {
+ return this.domainCheckoutService.canSetCustomer({
+ processId,
+ customerFeatures,
+ });
+ }),
+ )
+ .toPromise();
+
+ this.router.navigate(nav.path, {
+ queryParams: { filter_customertype: response.filter.customertype },
+ });
+ } catch (error) {
+ this.router.navigate(nav.path);
+ }
+ }
+
+ async showPurchasingListModal(shoppingCartItems: ShoppingCartItemDTO[]) {
+ const shoppingCart = await firstValueFrom(this.shoppingCart$);
+ const ref = await this._purchaseOptionsModalService.open({
+ tabId: this.applicationService.activatedProcessId,
+ shoppingCartId: shoppingCart.id,
+ items: shoppingCartItems,
+ type: 'update',
+ });
+
+ await firstValueFrom(ref.afterClosed$);
+ // Reload Shopping Cart after modal is closed to get updated items
+ this.#checkoutService.reloadShoppingCart({
+ processId: this.applicationService.activatedProcessId,
+ });
+ }
+
+ async changeAddress() {
+ const processId = this.applicationService.activatedProcessId;
+ const customer = await this.domainCheckoutService
+ .getBuyer({ processId })
+ .pipe(first())
+ .toPromise();
+ if (!customer) {
+ this.navigateToCustomerSearch(processId);
+ return;
+ }
+ const customerId = customer.source;
+ const nav = this._customerSearchNavigation.detailsRoute({
+ processId,
+ customerId,
+ });
+ this.router.navigate(nav.path);
+ }
+
+ async order() {
+ const shoppingCartItemsWithoutOrderType =
+ await this.shoppingCartItemsWithoutOrderType$.pipe(first()).toPromise();
+
+ if (shoppingCartItemsWithoutOrderType?.length > 0) {
+ this.showPurchasingListModal(shoppingCartItemsWithoutOrderType);
+ return;
+ }
+
+ const processId = this.applicationService.activatedProcessId;
+ const customer = await this.domainCheckoutService
+ .getBuyer({ processId })
+ .pipe(first())
+ .toPromise();
+ if (!customer) {
+ this.navigateToCustomerSearch(processId);
+ } else {
+ try {
+ this.showOrderButtonSpinner = true;
+ // Ticket #3287 Um nur E-Mail und SMS Benachrichtigungen zu setzen und um alle anderen Benachrichtigungskanรคle wie z.B. Brief zu deaktivieren
+ await this._store.onNotificationChange();
+ const orders = await this.domainCheckoutService
+ .completeCheckout({ processId })
+ .toPromise();
+ const orderIds = orders.map((order) => order.id).join(',');
+ this._store.orderCompleted.next();
+ await this.patchProcess(processId);
+ await this._navigationService
+ .getCheckoutSummaryPath({ processId, orderIds })
+ .navigate();
+ } catch (error) {
+ const response = error?.error;
+ let message: string = response?.message ?? '';
+
+ if (
+ response?.invalidProperties &&
+ Object.values(response?.invalidProperties)?.length
+ ) {
+ message += `\n${Object.values(response.invalidProperties).join('\n')}`;
+ }
+
+ if (message?.length) {
+ this.uiModal.open({
+ content: UiMessageModalComponent,
+ title: 'Hinweis',
+ data: { message: message.trim() },
+ });
+ } else if (error) {
+ this.uiModal.error('Fehler beim abschlieรen der Bestellung', error);
+ }
+
+ if (error.status === 409) {
+ this._store.orderCompleted.next();
+ await this.patchProcess(processId);
+ await this._navigationService
+ .getCheckoutSummaryPath({ processId })
+ .navigate();
+ }
+ } finally {
+ this.showOrderButtonSpinner = false;
+ this.cdr.markForCheck();
+ }
+ }
+ }
+
+ async patchProcess(processId: number) {
+ const process = await this.applicationService
+ .getProcessById$(processId)
+ .pipe(first())
+ .toPromise();
+ if (process) {
+ this.applicationService.patchProcess(process.id, {
+ name: `${process.name} Bestellbestรคtigung`,
+ type: 'cart-checkout',
+ });
+ }
+ }
+}
diff --git a/apps/isa-app/src/page/checkout/checkout-review/checkout-review.module.ts b/apps/isa-app/src/page/checkout/checkout-review/checkout-review.module.ts
index 9346aeb0c..240a6a5e9 100644
--- a/apps/isa-app/src/page/checkout/checkout-review/checkout-review.module.ts
+++ b/apps/isa-app/src/page/checkout/checkout-review/checkout-review.module.ts
@@ -19,7 +19,11 @@ import { CheckoutReviewDetailsComponent } from './details/checkout-review-detail
import { CheckoutReviewStore } from './checkout-review.store';
import { IconModule } from '@shared/components/icon';
import { TextFieldModule } from '@angular/cdk/text-field';
-import { LoaderComponent, SkeletonLoaderComponent } from '@shared/components/loader';
+import {
+ LoaderComponent,
+ SkeletonLoaderComponent,
+} from '@shared/components/loader';
+import { RewardSelectionTriggerComponent } from '@isa/checkout/shared/reward-selection-dialog';
@NgModule({
imports: [
@@ -40,6 +44,7 @@ import { LoaderComponent, SkeletonLoaderComponent } from '@shared/components/loa
TextFieldModule,
LoaderComponent,
SkeletonLoaderComponent,
+ RewardSelectionTriggerComponent,
],
exports: [CheckoutReviewComponent, CheckoutReviewDetailsComponent],
declarations: [
diff --git a/apps/isa-app/src/page/checkout/checkout-review/checkout-review.store.ts b/apps/isa-app/src/page/checkout/checkout-review/checkout-review.store.ts
index 341f47b8f..89aa91b89 100644
--- a/apps/isa-app/src/page/checkout/checkout-review/checkout-review.store.ts
+++ b/apps/isa-app/src/page/checkout/checkout-review/checkout-review.store.ts
@@ -1,185 +1,237 @@
-import { Injectable } from '@angular/core';
-import { UntypedFormGroup } from '@angular/forms';
-import { ApplicationService } from '@core/application';
-import { DomainCheckoutService } from '@domain/checkout';
-import { ComponentStore } from '@ngrx/component-store';
-import { tapResponse } from '@ngrx/operators';
-
-import { NotificationChannel, PayerDTO, ShoppingCartDTO, ShoppingCartItemDTO } from '@generated/swagger/checkout-api';
-import { UiErrorModalComponent, UiModalService } from '@ui/modal';
-import { BehaviorSubject, Subject } from 'rxjs';
-import { first, map, switchMap, takeUntil, tap, withLatestFrom } from 'rxjs/operators';
-
-export interface CheckoutReviewState {
- payer: PayerDTO;
- shoppingCart: ShoppingCartDTO;
- shoppingCartItems: ShoppingCartItemDTO[];
- fetching: boolean;
-}
-
-@Injectable()
-export class CheckoutReviewStore extends ComponentStore {
- orderCompleted = new Subject();
-
- get shoppingCart() {
- return this.get((s) => s.shoppingCart);
- }
- set shoppingCart(shoppingCart: ShoppingCartDTO) {
- this.patchState({ shoppingCart });
- }
- readonly shoppingCart$ = this.select((s) => s.shoppingCart);
-
- get shoppingCartItems() {
- return this.get((s) => s.shoppingCartItems);
- }
- set shoppingCartItems(shoppingCartItems: ShoppingCartItemDTO[]) {
- this.patchState({ shoppingCartItems });
- }
- readonly shoppingCartItems$ = this.select((s) => s.shoppingCartItems);
-
- get fetching() {
- return this.get((s) => s.fetching);
- }
- set fetching(fetching: boolean) {
- this.patchState({ fetching });
- }
- readonly fetching$ = this.select((s) => s.fetching);
-
- customerFeatures$ = this._application.activatedProcessId$.pipe(
- takeUntil(this.orderCompleted),
- switchMap((processId) => this._domainCheckoutService.getCustomerFeatures({ processId })),
- );
-
- payer$ = this._application.activatedProcessId$.pipe(
- takeUntil(this.orderCompleted),
- switchMap((processId) => this._domainCheckoutService.getPayer({ processId })),
- );
-
- buyer$ = this._application.activatedProcessId$.pipe(
- takeUntil(this.orderCompleted),
- switchMap((processId) => this._domainCheckoutService.getBuyer({ processId })),
- );
-
- showBillingAddress$ = this.shoppingCartItems$.pipe(
- withLatestFrom(this.customerFeatures$),
- map(
- ([items, customerFeatures]) =>
- items.some(
- (item) =>
- item.features?.orderType === 'Versand' ||
- item.features?.orderType === 'B2B-Versand' ||
- item.features?.orderType === 'DIG-Versand',
- ) || !!customerFeatures?.b2b,
- ),
- );
-
- checkNotificationChannelControl$ = new BehaviorSubject