Merge branch 'release/4.2'

This commit is contained in:
Nino
2025-10-23 16:23:01 +02:00
220 changed files with 23299 additions and 11593 deletions

View File

@@ -1,23 +1,415 @@
# Mentor Instructions
## Introduction
You are Mentor, an AI assistant focused on ensuring code quality, strict adherence to best practices, and development efficiency. **Your core function is to enforce the coding standards and guidelines established in this workspace.** Your goal is to help me produce professional, maintainable, and high-performing code.
**Always get the latest official documentation for Angular, Nx, or any related technology before implementing or when answering questions or providing feedback. Use Context7:**
## Tone and Personality
Maintain a professional, objective, and direct tone consistently:
- **Guideline Enforcement & Error Correction:** When code deviates from guidelines or contains errors, provide precise, technical feedback. Clearly state the issue, cite the relevant guideline or principle, and explain the required correction for optimal, maintainable results.
- **Technical Consultation:** In discussions about architecture, best practices, or complex coding inquiries, remain formal and analytical. Provide clear, well-reasoned explanations and recommendations grounded in industry standards and the project's specific guidelines.
## Behavioral Guidelines
- **Actionable Feedback:** Prioritize constructive, actionable feedback aimed at improving code quality, maintainability, and adherence to standards. Avoid rewriting code; focus on explaining the necessary changes and their rationale based on guidelines.
- **Strict Guideline Adherence:** Base _all_ feedback, suggestions, and explanations rigorously on the guidelines documented within this workspace. Cite specific rules and principles consistently.
- **Demand Clarity:** If a query or code snippet lacks sufficient detail for a thorough, professional analysis, request clarification.
- **Professional Framing:** Frame all feedback objectively, focusing on the technical aspects and the importance of meeting project standards for long-term success.
- **Context-Specific Expertise:** Provide specific, context-aware advice tailored to the code or problem, always within the framework of our established guidelines.
- **Enforce Standards:** Actively enforce project preferences for Type safety, Clean Code principles, and thorough documentation, as mandated by the workspace guidelines.
## ISA Frontend AI Assistant Working Rules
Concise, project-specific guidance so an AI agent can be productive quickly. Focus on THESE patterns; avoid generic boilerplate.
### 1. Monorepo & Tooling
- Nx workspace (Angular 20 + Libraries under `libs/**`, main app `apps/isa-app`).
- Scripts (see `package.json`):
- Dev serve: `npm start` (=> `nx serve isa-app --ssl`).
- Library tests (exclude app): `npm test` (Jest + emerging Vitest). CI uses `npm run ci`.
- Build dev: `npm run build`; prod: `npm run build-prod`.
- Storybook: `npm run storybook`.
- Swagger codegen: `npm run generate:swagger` then `npm run fix:files:swagger`.
- Default branch in Nx: `develop` (`nx.json: defaultBase`). Use affected commands when adding libs.
- Node >=22, TS 5.8, ESLint flat config (`eslint.config.js`).
### 1.a Project Tree (Detailed Overview)
```
.
├─ apps/
│ └─ isa-app/ # Main Angular app (Jest). Legacy non-standalone root component pattern.
│ ├─ project.json # Build/serve/test targets
│ ├─ src/
│ │ ├─ main.ts / index.html # Angular bootstrap
│ │ ├─ app/main.component.ts # Root component (standalone:false)
│ │ ├─ environments/ # Environment files (prod replace)
│ │ ├─ assets/ # Static assets
│ │ └─ config/ # Runtime config JSON (read via Config service)
│ └─ .storybook/ # App Storybook config
├─ libs/ # All reusable code (grouped by domain / concern)
│ ├─ core/ # Cross-cutting infrastructure
│ │ ├─ logging/ # Logging service + providers + sinks
│ │ │ ├─ src/lib/logging.service.ts
│ │ │ ├─ src/lib/logging.providers.ts
│ │ │ └─ README.md # Full API & patterns
│ │ ├─ config/ # `Config` service (Zod validated lookup)
│ │ └─ storage/ # User-scoped storage + signal store feature (`withStorage`)
│ │ ├─ src/lib/signal-store-feature.ts
│ │ └─ src/lib/storage.ts
│ │
│ ├─ shared/ # Shared UI/services not domain specific
│ │ └─ scanner/ # Scandit integration (tokens, service, components, platform gating)
│ │ ├─ src/lib/scanner.service.ts
│ │ └─ src/lib/render-if-scanner-is-ready.directive.ts
│ │
│ ├─ remission/ # Remission domain features (newer pattern; Vitest)
│ │ ├─ feature/
│ │ │ ├─ remission-return-receipt-details/
│ │ │ │ ├─ vite.config.mts # Signals + Vitest example
│ │ │ │ └─ src/lib/resources/ # Resource factories (signals async pattern)
│ │ │ └─ remission-return-receipt-list/
│ │ └─ shared/ # Dialogs / shared remission UI pieces
│ │
│ ├─ common/ # Cross-domain utilities (decorators, print, data-access)
│ ├─ utils/ # Narrow utility libs (ean-validation, z-safe-parse, etc.)
│ ├─ ui/ # Generic UI components (presentational)
│ ├─ icons/ # Icon sets / wrappers
│ ├─ catalogue/ # Domain area (legacy Jest)
│ ├─ customer/ # Domain area (legacy Jest)
│ └─ oms/ # Domain area (legacy Jest)
├─ generated/swagger/ # Generated API clients (regen via scripts; do not hand edit)
├─ tools/ # Helper scripts (e.g. swagger fix script)
├─ testresults/ # JUnit XML (jest-junit). CI artifact pickup.
├─ coverage/ # Per-project coverage outputs
├─ tailwind-plugins/ # Custom Tailwind plugin modules used by `tailwind.config.js`
├─ vitest.workspace.ts # Glob enabling multi-lib Vitest detection
├─ nx.json / package.json # Workspace + scripts + defaultBase=develop
└─ eslint.config.js # Flat ESLint root config
```
Guidelines: create new code in the closest domain folder; expose public API via each lib `src/index.ts`; follow existing naming (`feature-name.type.ts`). Keep generated swagger untouched—extend via wrapper libs if needed.
### 1.b Import Path Aliases
Use existing TS path aliases (see `tsconfig.base.json`) instead of long relative paths:
Core / Cross-cutting:
- `@isa/core/logging`, `@isa/core/config`, `@isa/core/storage`, `@isa/core/tabs`, `@isa/core/notifications`
Domain & Features:
- Catalogue: `@isa/catalogue/data-access`
- Customer: `@isa/customer/data-access`
- OMS features: `@isa/oms/feature/return-details`, `.../return-process`, `.../return-review`, `.../return-search`, `.../return-summary`
- OMS shared: `@isa/oms/shared/product-info`, `@isa/oms/shared/task-list`
- Remission: `@isa/remission/data-access`, feature libs (`@isa/remission/feature/remission-return-receipt-details`, `...-list`) and shared (`@isa/remission/shared/remission-start-dialog`, `.../search-item-to-remit-dialog`, `.../return-receipt-actions`, `.../product`)
Shared / UI:
- Shared libs: `@isa/shared/scanner`, `@isa/shared/filter`, `@isa/shared/product-image`, `@isa/shared/product-router-link`, `@isa/shared/product-format`
- UI components: `@isa/ui/buttons`, `@isa/ui/dialog`, `@isa/ui/input-controls`, `@isa/ui/layout`, `@isa/ui/menu`, `@isa/ui/toolbar`, etc. (one alias per folder under `libs/ui/*`)
- Icons: `@isa/icons`
Utilities:
- `@isa/utils/ean-validation`, `@isa/utils/z-safe-parse`, `@isa/utils/scroll-position`
Generated Swagger Clients:
- `@generated/swagger/isa-api`, `@generated/swagger/oms-api`, `@generated/swagger/inventory-api`, etc. (one per subfolder). Never edit generated sources—wrap in a domain lib if extension needed.
App-local (only inside `apps/isa-app` context):
- Namespaced folders: `@adapter/*`, `@domain/*`, `@hub/*`, `@modal/*`, `@page/*`, `@shared/*` (and nested: `@shared/components/*`, `@shared/services/*`, etc.), `@ui/*`, `@utils/*`, `@swagger/*`.
Patterns:
- Always add new reusable code as a library then expose via an `@isa/...` alias; do not add new generic code under app-local aliases if it may be reused later.
- When introducing a new library ensure its `src/index.ts` re-exports only stable public surface; internal helpers stay un-exported.
- For new generated API groups, extend via thin wrappers in a domain `data-access` lib rather than patching generated code.
### 2. Testing Strategy
- Legacy tests: Jest (`@nx/jest:jest`). New feature libs (e.g. remission feature) use Vitest + Vite plugin (`vite.config.mts`).
- When adding a new library today prefer Vitest unless consistency with existing Jest-only area is required.
- Do NOT mix frameworks inside one lib. Check presence of `vite.config.*` to know it is Vitest-enabled.
- App (`isa-app`) still uses Jest.
### 3. Architecture & Cross-Cutting Services
- Core libraries underpin features: `@isa/core/logging`, `@isa/core/config`, `@isa/core/storage`.
- Feature domains grouped (e.g. `libs/remission/**`, `libs/shared/**`, `libs/common/**`). Keep domain-specific code there; UI-only pieces in `ui/` or `shared/`.
- Prefer standalone components but some legacy components set `standalone: false` (see `MainComponent`). Maintain existing pattern unless doing a focused migration.
### 4. Logging (Critical Pattern)
- Central logging via `@isa/core/logging` (files: `logging.service.ts`, `logging.providers.ts`).
- Configure once in app config using provider builders: `provideLogging(withLogLevel(...), withSink(ConsoleLogSink), withContext({...}))`.
- Use factory `logger(() => ({ dynamicContext }))` (see README) rather than injecting `LoggingService` directly unless extending framework code.
- Context hierarchy: global -> component (`provideLoggerContext`) -> instance (factory param) -> message (callback arg). Always pass context as lazy function `() => ({ ... })` for perf.
- Respect log level threshold; do not perform expensive serialization before calling (let sinks handle it or gate behind dev checks).
### 5. Configuration Access
- Use `Config` service (`@isa/core/config/src/lib/config.ts`). Fetch values with Zod schema: `config.get('licence.scandit', z.string())` (see `SCANDIT_LICENSE` token). Avoid deprecated untyped access.
### 6. Storage & State Persistence
- Storage abstraction: `injectStorage(SomeProvider)` wraps a `StorageProvider` (local/session/indexedDB/custom user storage) and prefixes keys with current authenticated user `sub` (OAuth `sub` fallback 'anonymous').
- When adding persisted signal stores, use `withStorage(storageKey, ProviderType)` feature (`signal-store-feature.ts`) to auto debounce-save (1s) + restore on init. Only pass plain serializable state.
### 7. Signals & State
- Internal state often via Angular signals & NgRx Signals (`@ngrx/signals`). Avoid manual subscriptions—prefer computed/signals and `rxMethod` for side effects.
- When persisting, ensure objects are JSON-safe; validation via Zod if deserializing external data.
#### 7.a NgRx Signals Deep Dive
Core building blocks we use:
- `signalStore(...)` + features: `withState`, `withComputed`, `withMethods`, `withHooks`, `withStorage` (custom feature in `core/storage`).
- `rxMethod` (from `@ngrx/signals/rxjs-interop`) to bridge imperative async flows (HTTP calls, debounce, switchMap) into store-driven mutations.
- `getState`, `patchState` for immutable, shallow merges; avoid manually mutating nested objects—spread + patch.
Patterns:
1. Store Shape: Keep initial state small & serializable (no class instances, functions, DOM nodes). Derive heavy or view-specific projections with `withComputed`.
2. Side Effects: Wrap fetch/update flows inside `rxMethod` pipes; ensure cancellation semantics (`switchMap`) to drop stale requests.
3. Persistence: Apply `withStorage(key, Provider)` last so hooks run after other features; persisted state must be plain JSON (no Dates—convert to ISO strings). Debounce already handled (1s) in `withStorage`—do NOT add another debounce upstream unless burst traffic is extreme.
4. Error Handling: Keep an `error` field in state for presentation; log via `logger()` at Warn/Error levels but do not store full Error object (serialize minimal fields: `message`, maybe `code`).
5. Loading Flags: Prefer a boolean `loading` OR a discriminated union `status: 'idle'|'loading'|'success'|'error'` for richer UI; avoid multiple booleans that can drift.
6. Computed Selectors: Name as `XComputed` or just semantic (e.g. `filteredItems`) using `computed(() => ...)` inside `withComputed`; never cause side-effects in a computed.
7. Resource Factory Pattern: For remote data needed in multiple components, create a factory function returning an object with `value`, `isLoading`, `error` signals plus a `reload()` method; see remission `resources/` directory.
Store Lifecycle Hooks:
- Use `withHooks({ onInit() { ... }, onDestroy() { ... } })` for restoration, websockets, or timers. Pair cleanups explicitly.
Persistence Feature (`withStorage`):
- Implementation: Debounced `storeState` rxMethod listens to any state change, saves hashed userscoped key (see `hash.utils.ts`). On init it calls `restoreState()`.
- Extending: If you need to blacklist transient fields from persistence, add a method wrapping `getState` and remove keys before `storage.set` (extend feature locally rather than editing shared code unless broadly needed).
Typical Store Template:
```ts
// feature-x.store.ts
import {
signalStore,
withState,
withComputed,
withMethods,
withHooks,
} from '@ngrx/signals';
import { rxMethod } from '@ngrx/signals/rxjs-interop';
import { debounceTime, switchMap, tap, catchError, of } from 'rxjs';
import { withStorage } from '@isa/core/storage';
import { logger } from '@isa/core/logging';
interface FeatureXState {
items: ReadonlyArray<Item>;
query: string;
loading: boolean;
error?: string;
}
const initialState: FeatureXState = { items: [], query: '', loading: false };
export const FeatureXStore = signalStore(
withState(initialState),
withProps((store, logger = logger(() => ({ store: 'FeatureX' }))) => ({
_logger: logger,
})),
withComputed(({ items, query }) => ({
filtered: computed(() => items().filter((i) => i.name.includes(query()))),
hasError: computed(() => !!query() && !items().length),
})),
withMethods((store) => ({
setQuery: (q: string) => patchState(store, { query: q }),
// rxMethod side effect to load items
loadItems: rxMethod<string | void>(
pipe(
debounceTime(150),
tap(() => patchState(store, { loading: true, error: undefined })),
switchMap(() =>
fetchItems(store.query()).pipe(
tap((items) => patchState(store, { items, loading: false })),
catchError((err) => {
store._logger.error('Load failed', err as Error, () => ({
query: store.query(),
}));
patchState(store, {
loading: false,
error: (err as Error).message,
});
return of([]);
}),
),
),
),
),
})),
withHooks((store) => ({
onInit() {
store.loadItems();
},
})),
withStorage('feature-x', LocalStorageProvider),
);
```
Testing Signal Stores (Vitest or Jest):
- Use `runInInjectionContext(TestBed.inject(Injector), () => FeatureXStore)` or instantiate via exported factory if provided.
- For async rxMethod flows, flush microtasks (`await vi.runAllTimersAsync()` if timers used) or rely on returned observable completion when you subscribe inside the test harness.
- Snapshot only primitive slices (avoid full object snapshots with volatile ordering).
Migration Tips:
- Converting legacy NgRx reducers: Start by lifting static initial state + selectors into `withState` + `withComputed`; replace effects with `rxMethod` maintaining cancellation semantics (`switchMap` mirrors effect flattening strategy).
- Keep action names only if externally observed (analytics, logging). Otherwise remove ceremony—call store methods directly.
Anti-Patterns to Avoid:
- Writing to signals inside a computed or inside another signal setter (causes cascading updates).
- Storing large unnormalized arrays and then repeatedly filtering/sorting in multiple components—centralize that in computed selectors.
- Persisting secrets or PII directly; hash keys already user-scoped but content still plain—sanitize if needed.
- Returning raw subscriptions from store methods; expose signals or idempotent methods only.
#### 7.b Prefer Signals over Observables (Practical Rules)
Default to signals for all in-memory UI & derived state; keep Observables only at I/O edges.
Use Observables for:
- HTTP / WebSocket / SignalR streams at the boundary.
- Timer / interval / external event sources.
- Interop with legacy NgRx store pieces not yet migrated.
Immediately convert inbound Observables to signals:
```ts
// Legacy service returning Observable<Item[]>
items$ = http.get<Item[]>(url);
// New pattern
const items = toSignal(http.get<Item[]>(url), { initialValue: [] });
```
Expose signals from stores & services:
```ts
// BAD (forces template async pipe + subscription mgmt)
getItems(): Observable<Item[]> { return this.http.get(...); }
// GOOD
items = toSignal(this.http.get<Item[]>(url), { initialValue: [] });
```
Bridge when needed:
```ts
// Signal -> Observable (rare):
const queryChanges$ = fromSignal(query, { requireSync: true });
// Observable -> Signal (preferred):
const data = toSignal(data$, { initialValue: undefined });
```
Side-effects: never subscribe manually—wrap in `rxMethod` (cancels stale work via `switchMap`).
```ts
loadData: rxMethod<void>(
pipe(
switchMap(() =>
this.api.fetch().pipe(tap((r) => patchState(store, { data: r }))),
),
),
);
```
Template usage: reference signals directly (`{{ item.name }}`) or in control flow; no `| async` needed.
Replacing combineLatest / map chains:
```ts
// Before (Observable)
vm$ = combineLatest([a$, b$]).pipe(map(([a, b]) => buildVm(a, b)));
// After (Signals)
const vm = computed(() => buildVm(a(), b()));
```
Debounce / throttle user input:
Keep raw form value as a signal; create an rxMethod for debounced fetch instead of debouncing inside a computed.
```ts
search = signal('');
runSearch: rxMethod<string>(
pipe(
debounceTime(300),
switchMap((term) =>
this.api
.search(term)
.pipe(tap((results) => patchState(store, { results }))),
),
),
);
effect(() => {
runSearch(this.search());
});
```
Avoid converting a signal back to an Observable just to use a single RxJS operator; prefer inline signal `computed` or small helper.
Migration heuristic:
1. Identify component `foo$` fields used only in template -> convert to signal via `toSignal`.
2. Collapse chains of `combineLatest` + `map` into `computed`.
3. Replace imperative `subscribe` side-effects with `rxMethod` + `patchState`.
4. Add persistence last via `withStorage` if state must survive reload.
Performance tip: heavy derived computations (sorting large arrays) belong in a memoized `computed`; if expensive & infrequently needed, gate behind another signal flag.
### 8. Scanner Integration (Scandit)
- Barcode scanning encapsulated in `@isa/shared/scanner` (`scanner.service.ts`). Use provided injection tokens for license & defaults (override via DI if needed). Service auto-configures once; `ready` signal triggers `configure()` lazily.
- Always catch and log errors with proper context; platform gating throws `PlatformNotSupportedError` which is downgraded to warn.
### 9. Styling
- Tailwind with custom semantic tokens (`tailwind.config.js`). Prefer design tokens like `text-isa-neutral-700`, spacing utilities with custom `px-*` scales rather than adhoc raw values.
- Global overlays rely on CDK classes; retain `@angular/cdk/overlay-prebuilt.css` in style arrays when creating new entrypoints or Storybook stories.
### 10. Library Conventions
- File naming: kebab-case; feature first then type (e.g. `return-receipt-list.component.ts`).
- Provide public API via each lib `src/index.ts`. Export only stable symbols; keep internal utilities in subfolders not re-exported.
- Add `project.json` with `test` & `lint` targets; for new Vitest libs include `vite.config.mts` and adjust `tsconfig.spec.json` references to vitest types.
### 11. Adding / Modifying Tests
- For Jest libs: standard `*.spec.ts` with `TestBed`. Spectator may appear in legacy code—do not introduce Spectator in new tests; use Angular Testing Utilities.
- For Vitest libs: ensure `vite.config.mts` includes `setupFiles`. Use `describe/it` from `vitest` and Angular TestBed (see remission resource spec for pattern of using `runInInjectionContext`).
- Prefer resource-style factories returning signals for async state (pattern in `createSupplierResource`).
### 12. Performance & Safety
- Logging: rely on lazy context function; avoid `JSON.stringify()` unless behind a dev guard.
- Storage: hashing keys (see `hash.utils.ts`) ensures stable key space; do not bypass if you need consistent per-user scoping.
- Scanner overlay: always clean up overlay + event listeners (follow existing `open` implementation for pattern).
### 13. CI / Coverage / Artifacts
- JUnit XML placed in `testresults/` (Jest configured with `jest-junit`). Keep filename stability for pipeline consumption; do not rename those outputs.
- Coverage output under `coverage/libs/...`; respect Nx caching—avoid side effects outside project roots.
### 14. When Unsure
- Search existing domain folder for analogous implementation (e.g. new feature under remission: inspect sibling feature libs for structure).
- Preserve existing DI token patterns instead of introducing new global singletons.
### 15. Quick Examples
```ts
// New feature logger usage
const log = logger(() => ({ feature: 'ReturnReceipt', action: 'init' }));
log.info('Mount');
// Persisting a signal store slice
export const FeatureStore = signalStore(
withState(initState),
withStorage('return:filters', LocalStorageProvider),
);
// Fetch config value safely
const apiBase = inject(Config).get('api.baseUrl', z.string().url());
```
---
Let me know if any area (e.g. auth flow, NgRx usage, Swagger generation details) needs deeper coverage and I can extend this file.

189
.github/prompts/plan.prompt.md vendored Normal file
View File

@@ -0,0 +1,189 @@
---
mode: agent
tools: ['edit', 'search', 'usages', 'vscodeAPI', 'problems', 'changes', 'fetch', 'githubRepo', 'Nx Mcp Server', 'context7']
description: Plan Mode - Research and create a detailed implementation plan before making any changes.
model: Gemini 2.5 Pro (copilot)
---
# Plan Mode
You are now operating in **Plan Mode** - a research and planning phase that ensures thorough analysis before implementation. Plan mode is **ALWAYS ACTIVE** when using this prompt. You must follow these strict guidelines for every request:
## Phase 1: Research & Analysis (MANDATORY)
### ALLOWED Operations:
- ✅ Read files using Read, Glob, Grep tools
- ✅ Search documentation and codebases
- ✅ Analyze existing patterns and structures
- ✅ Use WebFetch for documentation research
- ✅ List and explore project structure
- ✅ Use Nx/Angular/Context7 MCP tools for workspace analysis
- ✅ Review dependencies and configurations
### FORBIDDEN Operations:
-**NEVER** create, edit, or modify any files
-**NEVER** run commands that change system state
-**NEVER** make commits or push changes
-**NEVER** install packages or modify configurations
-**NEVER** run build/test commands during planning
## Phase 2: Plan Presentation (REQUIRED FORMAT)
After thorough research, present your plan using this exact structure:
```markdown
## 📋 Implementation Plan
### 🎯 Objective
[Clear statement of what will be accomplished]
### 🔍 Research Summary
- **Current State**: [What exists now]
- **Requirements**: [What needs to be built/changed]
- **Constraints**: [Limitations and considerations]
### 📁 Files to be Modified/Created
1. **File**: `path/to/file.ts`
- **Action**: Create/Modify/Delete
- **Purpose**: [Why this file needs changes]
- **Key Changes**: [Specific modifications planned]
2. **File**: `path/to/another-file.ts`
- **Action**: Create/Modify/Delete
- **Purpose**: [Why this file needs changes]
- **Key Changes**: [Specific modifications planned]
### 🏗️ Implementation Steps
1. **Step 1**: [Detailed description]
- Files affected: `file1.ts`, `file2.ts`
- Rationale: [Why this step is necessary]
2. **Step 2**: [Detailed description]
- Files affected: `file3.ts`
- Rationale: [Why this step is necessary]
3. **Step N**: [Continue numbering...]
### ⚠️ Risks & Considerations
- **Risk 1**: [Potential issue and mitigation]
- **Risk 2**: [Potential issue and mitigation]
### 🧪 Testing Strategy
- [How the changes will be tested]
- [Specific test files or approaches]
### 📚 Architecture Decisions
- **Pattern Used**: [Which architectural pattern will be followed]
- **Libraries/Dependencies**: [What will be used and why]
- **Integration Points**: [How this fits with existing code]
### ✅ Success Criteria
- [ ] Criterion 1
- [ ] Criterion 2
- [ ] All tests pass
- [ ] No lint errors
```
## Phase 3: Await Approval
After presenting the plan:
1. **STOP** all implementation activities
2. **WAIT** for explicit user approval
3. **DO NOT** proceed with any file changes
4. **RESPOND** to questions or plan modifications
5. **EXIT PLAN MODE** only when user explicitly says "execute", "implement", "go ahead", "approved", or similar approval language
## Phase 4: Implementation (After Exiting Plan Mode)
Once the user explicitly approves and you exit plan mode:
1. **PLAN MODE IS NOW DISABLED** - you can proceed with normal implementation
2. Use TodoWrite to create implementation todos
3. Follow the plan step-by-step
4. Update todos as you progress
5. Run tests and lint checks as specified
6. Provide progress updates
## Key Behavioral Rules
### Research Thoroughly
- Spend significant time understanding the codebase
- Look for existing patterns to follow
- Identify all dependencies and integration points
- Consider edge cases and error scenarios
### Be Comprehensive
- Plans should be detailed enough for another developer to implement
- Include all necessary file changes
- Consider testing, documentation, and deployment
- Address potential conflicts or breaking changes
### Show Your Work
- Explain reasoning behind architectural decisions
- Reference existing code patterns when applicable
- Cite documentation or best practices
- Provide alternatives when multiple approaches exist
### Safety First
- Never make changes during planning phase
- Always wait for explicit approval
- Flag potentially risky changes
- Suggest incremental implementation when complex
## Example Interactions
### Good Plan Mode Behavior:
```
User: "Add a dark mode toggle to the settings page"
Assistant: I'll research the current theming system and create a comprehensive plan for implementing dark mode.
[Extensive research using Read, Grep, Glob tools]
## 📋 Implementation Plan
[Follows complete format above]
Ready to proceed? Please approve this plan before I begin implementation.
```
### What NOT to do:
```
User: "Add a dark mode toggle"
Assistant: I'll add that right away!
[Immediately starts editing files - WRONG!]
```
# <<<<<<< HEAD
## Integration with Existing Copilot Instructions
This plan mode respects all existing project patterns:
- Follows Angular + Nx workspace conventions
- Uses existing import path aliases
- Respects testing strategy (Jest/Vitest)
- Follows NgRx Signals patterns
- Adheres to logging and configuration patterns
- Maintains library conventions and file naming
> > > > > > > develop
> > > > > > > Remember: **RESEARCH FIRST, PLAN THOROUGHLY, WAIT FOR APPROVAL, THEN IMPLEMENT**

1
.gitignore vendored
View File

@@ -75,3 +75,4 @@ vitest.config.*.timestamp*
.memory.json
nx.instructions.md
CLAUDE.md

192
.vscode/settings.json vendored
View File

@@ -1,92 +1,100 @@
{
"editor.accessibilitySupport": "off",
"typescript.tsdk": "node_modules/typescript/lib",
"exportall.config.exclude": [".test.", ".spec.", ".stories."],
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"eslint.validate": [
"json"
],
"[html]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[typescriptreact]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"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": [
{
"file": ".github/commit-instructions.md"
}
],
"github.copilot.chat.codeGeneration.instructions": [
{
"file": ".vscode/llms/angular.txt"
},
{
"file": "docs/tech-stack.md"
},
{
"file": "docs/guidelines/code-style.md"
},
{
"file": "docs/guidelines/project-structure.md"
},
{
"file": "docs/guidelines/state-management.md"
},
{
"file": "docs/guidelines/testing.md"
}
],
"github.copilot.chat.testGeneration.instructions": [
{
"file": ".github/testing-instructions.md"
},
{
"file": "docs/tech-stack.md"
},
{
"file": "docs/guidelines/code-style.md"
},
{
"file": "docs/guidelines/testing.md"
}
],
"github.copilot.chat.reviewSelection.instructions": [
{
"file": ".github/copilot-instructions.md"
},
{
"file": ".github/review-instructions.md"
},
{
"file": "docs/tech-stack.md"
},
{
"file": "docs/guidelines/code-style.md"
},
{
"file": "docs/guidelines/project-structure.md"
},
{
"file": "docs/guidelines/state-management.md"
},
{
"file": "docs/guidelines/testing.md"
}
],
"nxConsole.generateAiAgentRules": true,
"chat.mcp.enabled": true,
"chat.mcp.discovery.enabled": true
}
{
"editor.accessibilitySupport": "off",
"typescript.tsdk": "node_modules/typescript/lib",
"exportall.config.exclude": [".test.", ".spec.", ".stories."],
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"eslint.validate": [
"json"
],
"[html]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[typescriptreact]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[markdown]": {
"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": [
{
"file": ".github/commit-instructions.md"
}
],
"github.copilot.chat.codeGeneration.instructions": [
{
"file": ".vscode/llms/angular.txt"
},
{
"file": "docs/tech-stack.md"
},
{
"file": "docs/guidelines/code-style.md"
},
{
"file": "docs/guidelines/project-structure.md"
},
{
"file": "docs/guidelines/state-management.md"
},
{
"file": "docs/guidelines/testing.md"
}
],
"github.copilot.chat.testGeneration.instructions": [
{
"file": ".github/testing-instructions.md"
},
{
"file": "docs/tech-stack.md"
},
{
"file": "docs/guidelines/code-style.md"
},
{
"file": "docs/guidelines/testing.md"
}
],
"github.copilot.chat.reviewSelection.instructions": [
{
"file": ".github/copilot-instructions.md"
},
{
"file": ".github/review-instructions.md"
},
{
"file": "docs/tech-stack.md"
},
{
"file": "docs/guidelines/code-style.md"
},
{
"file": "docs/guidelines/project-structure.md"
},
{
"file": "docs/guidelines/state-management.md"
},
{
"file": "docs/guidelines/testing.md"
}
],
"nxConsole.generateAiAgentRules": true,
"chat.mcp.discovery.enabled": {
"claude-desktop": true,
"windsurf": true,
"cursor-global": true,
"cursor-workspace": true
},
"chat.mcp.access": "all"
}

148
CLAUDE.md Normal file
View File

@@ -0,0 +1,148 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## 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.
## Architecture
### Monorepo Structure
- **apps/isa-app**: Main Angular application
- **libs/**: Reusable libraries organized by domain and type
- **core/**: Core utilities (config, logging, storage, tabs)
- **common/**: Shared utilities (data-access, decorators, print)
- **ui/**: UI component libraries (buttons, dialogs, inputs, etc.)
- **shared/**: Shared domain components (filter, scanner, product components)
- **oms/**: Order Management System features and utilities
- **remission/**: Remission/returns management features
- **catalogue/**: Product catalogue functionality
- **utils/**: General utilities (validation, scroll position, parsing)
- **icons/**: Icon library
- **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/`
## Common Development Commands
### Build Commands
```bash
# Build the main application (development)
npx nx build isa-app --configuration=development
# Build for production
npx nx build isa-app --configuration=production
# 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 <project-name>: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 <project-name>:test --testFile=<path-to-test-file> --skip-cache
# Run tests with coverage
npx nx run <project-name>:test --code-coverage --skip-cache
# Run tests in watch mode
npx nx run <project-name>:test --watch
```
### Linting Commands
```bash
# Lint a specific project
npx nx lint <project-name>
# Example: npx nx lint remission-data-access
# Run linting for all projects
npx nx run-many -t lint
```
### Other Useful Commands
```bash
# Generate Swagger API clients
npm run generate:swagger
# Start Storybook
npx nx run isa-app:storybook
# Format code with Prettier
npm run prettier
# List all projects in the workspace
npx nx list
# Show project dependencies graph
npx nx graph
# Run affected tests (based on git changes)
npx nx affected:test
```
## 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
### Test File 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
## State Management
- **NgRx**: Store, Effects, Entity, Component Store, Signals
- **RxJS**: For reactive programming patterns
## Styling
- **Tailwind CSS**: Primary styling framework with custom configuration
- **SCSS**: For component-specific styles
- **Custom Tailwind plugins**: For buttons, inputs, menus, typography
## 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
## 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
## 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
## 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`
## 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

View File

@@ -7,8 +7,9 @@ LABEL build.uniqueid="${BuildUniqueID:-1}"
WORKDIR /app
COPY . .
RUN umask 0022
RUN npm install -g npm@11.6
RUN npm version ${SEMVERSION}
RUN npm install --foreground-scripts
RUN npm ci --foreground-scripts
RUN if [ "${IS_PRODUCTION}" = "true" ] ; then npm run-script build-prod ; else npm run-script build ; fi
# stage final

View File

@@ -1,5 +1,6 @@
import { isDevMode, NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { inject, isDevMode, NgModule } from '@angular/core';
import { Location } from '@angular/common';
import { RouterModule, Routes, Router } from '@angular/router';
import {
CanActivateCartGuard,
CanActivateCartWithProcessIdGuard,
@@ -30,7 +31,12 @@ import {
ActivateProcessIdWithConfigKeyGuard,
} from './guards/activate-process-id.guard';
import { MatomoRouteData } from 'ngx-matomo-client';
import { tabResolverFn } from '@isa/core/tabs';
import {
tabResolverFn,
TabService,
TabNavigationService,
processResolverFn,
} from '@isa/core/tabs';
import { provideScrollPositionRestoration } from '@isa/utils/scroll-position';
const routes: Routes = [
@@ -182,9 +188,14 @@ const routes: Routes = [
{
path: ':tabId',
component: MainComponent,
resolve: { process: tabResolverFn, tab: tabResolverFn },
resolve: { process: processResolverFn, tab: tabResolverFn },
canActivate: [IsAuthenticatedGuard],
children: [
{
path: 'reward',
loadChildren: () =>
import('@isa/checkout/feature/reward-catalog').then((m) => m.routes),
},
{
path: 'return',
loadChildren: () =>
@@ -222,10 +233,18 @@ if (isDevMode()) {
@NgModule({
imports: [
RouterModule.forRoot(routes, { bindToComponentInputs: true }),
RouterModule.forRoot(routes, {
bindToComponentInputs: true,
enableTracing: false,
}),
TokenLoginModule,
],
exports: [RouterModule],
providers: [provideScrollPositionRestoration()],
})
export class AppRoutingModule {}
export class AppRoutingModule {
constructor() {
// Loading TabNavigationService to ensure tab state is synced with tab location
inject(TabNavigationService);
}
}

View File

@@ -1,35 +1,34 @@
import { NgModule } from '@angular/core';
import { EffectsModule } from '@ngrx/effects';
import { ActionReducer, MetaReducer, StoreModule } from '@ngrx/store';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';
import packageInfo from 'packageJson';
import { environment } from '../environments/environment';
import { RootStateService } from './store/root-state.service';
import { rootReducer } from './store/root.reducer';
import { RootState } from './store/root.state';
export function storeInLocalStorage(reducer: ActionReducer<any>): ActionReducer<any> {
return function (state, action) {
if (action.type === 'HYDRATE') {
const initialState = RootStateService.LoadFromLocalStorage();
if (initialState?.version === packageInfo.version) {
return reducer(initialState, action);
}
}
return reducer(state, action);
};
}
export const metaReducers: MetaReducer<RootState>[] = !environment.production
? [storeInLocalStorage]
: [storeInLocalStorage];
@NgModule({
imports: [
StoreModule.forRoot(rootReducer, { metaReducers }),
EffectsModule.forRoot([]),
StoreDevtoolsModule.instrument({ name: 'ISA Ngrx Application Store', connectInZone: true }),
],
})
export class AppStoreModule {}
import { NgModule } from '@angular/core';
import { EffectsModule } from '@ngrx/effects';
import { ActionReducer, MetaReducer, StoreModule } from '@ngrx/store';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';
import { environment } from '../environments/environment';
import { rootReducer } from './store/root.reducer';
import { RootState } from './store/root.state';
export function storeInLocalStorage(
reducer: ActionReducer<any>,
): ActionReducer<any> {
return function (state, action) {
if (action.type === 'HYDRATE') {
return reducer(action['payload'], action);
}
return reducer(state, action);
};
}
export const metaReducers: MetaReducer<RootState>[] = !environment.production
? [storeInLocalStorage]
: [storeInLocalStorage];
@NgModule({
imports: [
StoreModule.forRoot(rootReducer, { metaReducers }),
EffectsModule.forRoot([]),
StoreDevtoolsModule.instrument({
name: 'ISA Ngrx Application Store',
connectInZone: true,
}),
],
})
export class AppStoreModule {}

View File

@@ -1,238 +1,263 @@
import {
HTTP_INTERCEPTORS,
provideHttpClient,
withInterceptorsFromDi,
} from '@angular/common/http';
import {
DEFAULT_CURRENCY_CODE,
ErrorHandler,
Injector,
LOCALE_ID,
NgModule,
inject,
provideAppInitializer,
} from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { PlatformModule } from '@angular/cdk/platform';
import { Config } from '@core/config';
import { AuthModule, AuthService, LoginStrategy } from '@core/auth';
import { CoreCommandModule } from '@core/command';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { CoreApplicationModule } from '@core/application';
import { AppStoreModule } from './app-store.module';
import { ServiceWorkerModule } from '@angular/service-worker';
import { environment } from '../environments/environment';
import { AppSwaggerModule } from './app-swagger.module';
import { AppDomainModule } from './app-domain.module';
import { UiModalModule } from '@ui/modal';
import {
NotificationsHubModule,
NOTIFICATIONS_HUB_OPTIONS,
} from '@hub/notifications';
import { SignalRHubOptions } from '@core/signalr';
import { CoreBreadcrumbModule } from '@core/breadcrumb';
import { UiCommonModule } from '@ui/common';
import { registerLocaleData } from '@angular/common';
import localeDe from '@angular/common/locales/de';
import localeDeExtra from '@angular/common/locales/extra/de';
import { HttpErrorInterceptor } from './interceptors';
import { CoreLoggerModule, LOG_PROVIDER } from '@core/logger';
import { IsaLogProvider } from './providers';
import { IsaErrorHandler } from './providers/isa.error-handler';
import {
ScanAdapterModule,
ScanAdapterService,
ScanditScanAdapterModule,
} from '@adapter/scan';
import { RootStateService } from './store/root-state.service';
import * as Commands from './commands';
import { PreviewComponent } from './preview';
import { NativeContainerService } from '@external/native-container';
import { ShellModule } from '@shared/shell';
import { MainComponent } from './main.component';
import { IconModule } from '@shared/components/icon';
import { NgIconsModule } from '@ng-icons/core';
import {
matClose,
matWifi,
matWifiOff,
} from '@ng-icons/material-icons/baseline';
import { NetworkStatusService } from './services/network-status.service';
import { firstValueFrom } from 'rxjs';
import { provideMatomo } from 'ngx-matomo-client';
import { withRouter, withRouteData } from 'ngx-matomo-client';
import {
provideLogging,
withLogLevel,
LogLevel,
withSink,
ConsoleLogSink,
} from '@isa/core/logging';
registerLocaleData(localeDe, localeDeExtra);
registerLocaleData(localeDe, 'de', localeDeExtra);
export function _appInitializerFactory(config: Config, injector: Injector) {
return async () => {
const statusElement = document.querySelector('#init-status');
const laoderElement = document.querySelector('#init-loader');
try {
let online = false;
const networkStatus = injector.get(NetworkStatusService);
while (!online) {
online = await firstValueFrom(networkStatus.online$);
if (!online) {
statusElement.innerHTML =
'<b>Warte auf Netzwerkverbindung (WLAN)</b><br><br>Bitte prüfen Sie die Netzwerkverbindung (WLAN).<br>Sobald eine Netzwerkverbindung besteht, wird die App automatisch neu geladen.';
await new Promise((resolve) => setTimeout(resolve, 250));
}
}
statusElement.innerHTML = 'Konfigurationen werden geladen...';
statusElement.innerHTML = 'Scanner wird initialisiert...';
const scanAdapter = injector.get(ScanAdapterService);
await scanAdapter.init();
statusElement.innerHTML = 'Authentifizierung wird geprüft...';
const auth = injector.get(AuthService);
try {
await auth.init();
} catch (error) {
statusElement.innerHTML = 'Authentifizierung wird durchgeführt...';
const strategy = injector.get(LoginStrategy);
await strategy.login();
}
statusElement.innerHTML = 'App wird initialisiert...';
const state = injector.get(RootStateService);
await state.init();
statusElement.innerHTML = 'Native Container wird initialisiert...';
const nativeContainer = injector.get(NativeContainerService);
await nativeContainer.init();
} catch (error) {
laoderElement.remove();
statusElement.classList.add('text-xl');
statusElement.innerHTML +=
'⚡<br><br><b>Fehler bei der Initialisierung</b><br><br>Bitte prüfen Sie die Netzwerkverbindung (WLAN).<br><br>';
const reload = document.createElement('button');
reload.classList.add(
'bg-brand',
'text-white',
'p-2',
'rounded',
'cursor-pointer',
);
reload.innerHTML = 'App neu laden';
reload.onclick = () => window.location.reload();
statusElement.appendChild(reload);
const preLabel = document.createElement('div');
preLabel.classList.add('mt-12');
preLabel.innerHTML = 'Fehlermeldung:';
statusElement.appendChild(preLabel);
const pre = document.createElement('pre');
pre.classList.add('mt-4', 'text-wrap');
pre.innerHTML = error.message;
statusElement.appendChild(pre);
console.error('Error during app initialization', error);
throw error;
}
};
}
export function _notificationsHubOptionsFactory(
config: Config,
auth: AuthService,
): SignalRHubOptions {
const options = { ...config.get('hubs').notifications };
options.httpOptions.accessTokenFactory = () => auth.getToken();
return options;
}
@NgModule({
declarations: [AppComponent, MainComponent],
bootstrap: [AppComponent],
imports: [
BrowserModule,
BrowserAnimationsModule,
ShellModule.forRoot(),
AppRoutingModule,
AppSwaggerModule,
AppDomainModule,
CoreBreadcrumbModule.forRoot(),
CoreCommandModule.forRoot(Object.values(Commands)),
CoreLoggerModule.forRoot(),
AppStoreModule,
PreviewComponent,
AuthModule.forRoot(),
CoreApplicationModule.forRoot(),
UiModalModule.forRoot(),
UiCommonModule.forRoot(),
NotificationsHubModule.forRoot(),
ServiceWorkerModule.register('ngsw-worker.js', {
enabled: environment.production,
registrationStrategy: 'registerWhenStable:30000',
}),
ScanAdapterModule.forRoot(),
ScanditScanAdapterModule.forRoot(),
PlatformModule,
IconModule.forRoot(),
NgIconsModule.withIcons({ matWifiOff, matClose, matWifi }),
],
providers: [
provideAppInitializer(() => {
const initializerFn = _appInitializerFactory(
inject(Config),
inject(Injector),
);
return initializerFn();
}),
{
provide: NOTIFICATIONS_HUB_OPTIONS,
useFactory: _notificationsHubOptionsFactory,
deps: [Config, AuthService],
},
{
provide: HTTP_INTERCEPTORS,
useClass: HttpErrorInterceptor,
multi: true,
},
{
provide: LOG_PROVIDER,
useClass: IsaLogProvider,
multi: true,
},
{
provide: ErrorHandler,
useClass: IsaErrorHandler,
},
{ provide: LOCALE_ID, useValue: 'de-DE' },
provideHttpClient(withInterceptorsFromDi()),
provideMatomo(
{ trackerUrl: 'https://matomo.paragon-data.net', siteId: '1' },
withRouter(),
withRouteData(),
),
provideLogging(withLogLevel(LogLevel.Debug), withSink(ConsoleLogSink)),
{
provide: DEFAULT_CURRENCY_CODE,
useValue: 'EUR',
},
],
})
export class AppModule {}
import { version } from '../../../../package.json';
import {
HTTP_INTERCEPTORS,
provideHttpClient,
withInterceptorsFromDi,
} from '@angular/common/http';
import {
DEFAULT_CURRENCY_CODE,
ErrorHandler,
Injector,
LOCALE_ID,
NgModule,
inject,
provideAppInitializer,
} from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { PlatformModule } from '@angular/cdk/platform';
import { Config } from '@core/config';
import { AuthModule, AuthService, LoginStrategy } from '@core/auth';
import { CoreCommandModule } from '@core/command';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import {
ApplicationService,
ApplicationServiceAdapter,
CoreApplicationModule,
} from '@core/application';
import { AppStoreModule } from './app-store.module';
import { ServiceWorkerModule } from '@angular/service-worker';
import { environment } from '../environments/environment';
import { AppSwaggerModule } from './app-swagger.module';
import { AppDomainModule } from './app-domain.module';
import { UiModalModule } from '@ui/modal';
import {
NotificationsHubModule,
NOTIFICATIONS_HUB_OPTIONS,
} from '@hub/notifications';
import { SignalRHubOptions } from '@core/signalr';
import { CoreBreadcrumbModule } from '@core/breadcrumb';
import { UiCommonModule } from '@ui/common';
import { registerLocaleData } from '@angular/common';
import localeDe from '@angular/common/locales/de';
import localeDeExtra from '@angular/common/locales/extra/de';
import { HttpErrorInterceptor } from './interceptors';
import { CoreLoggerModule, LOG_PROVIDER } from '@core/logger';
import { IsaLogProvider } from './providers';
import { IsaErrorHandler } from './providers/isa.error-handler';
import {
ScanAdapterModule,
ScanAdapterService,
ScanditScanAdapterModule,
} from '@adapter/scan';
import * as Commands from './commands';
import { PreviewComponent } from './preview';
import { NativeContainerService } from '@external/native-container';
import { ShellModule } from '@shared/shell';
import { MainComponent } from './main.component';
import { IconModule } from '@shared/components/icon';
import { NgIconsModule } from '@ng-icons/core';
import {
matClose,
matWifi,
matWifiOff,
} from '@ng-icons/material-icons/baseline';
import { NetworkStatusService } from './services/network-status.service';
import { debounceTime, firstValueFrom } from 'rxjs';
import { provideMatomo } from 'ngx-matomo-client';
import { withRouter, withRouteData } from 'ngx-matomo-client';
import {
provideLogging,
withLogLevel,
LogLevel,
withSink,
ConsoleLogSink,
} from '@isa/core/logging';
import { IDBStorageProvider, UserStorageProvider } from '@isa/core/storage';
import { Store } from '@ngrx/store';
registerLocaleData(localeDe, localeDeExtra);
registerLocaleData(localeDe, 'de', localeDeExtra);
export function _appInitializerFactory(config: Config, injector: Injector) {
return async () => {
const statusElement = document.querySelector('#init-status');
const laoderElement = document.querySelector('#init-loader');
try {
let online = false;
const networkStatus = injector.get(NetworkStatusService);
while (!online) {
online = await firstValueFrom(networkStatus.online$);
if (!online) {
statusElement.innerHTML =
'<b>Warte auf Netzwerkverbindung (WLAN)</b><br><br>Bitte prüfen Sie die Netzwerkverbindung (WLAN).<br>Sobald eine Netzwerkverbindung besteht, wird die App automatisch neu geladen.';
await new Promise((resolve) => setTimeout(resolve, 250));
}
}
statusElement.innerHTML = 'Konfigurationen werden geladen...';
statusElement.innerHTML = 'Scanner wird initialisiert...';
const scanAdapter = injector.get(ScanAdapterService);
await scanAdapter.init();
statusElement.innerHTML = 'Authentifizierung wird geprüft...';
const auth = injector.get(AuthService);
try {
await auth.init();
} catch (error) {
statusElement.innerHTML = 'Authentifizierung wird durchgeführt...';
const strategy = injector.get(LoginStrategy);
await strategy.login();
}
statusElement.innerHTML = 'Native Container wird initialisiert...';
const nativeContainer = injector.get(NativeContainerService);
await nativeContainer.init();
statusElement.innerHTML = 'Datenbank wird initialisiert...';
await injector.get(IDBStorageProvider).init();
statusElement.innerHTML = 'Benutzerzustand wird geladen...';
const userStorage = injector.get(UserStorageProvider);
await userStorage.init();
const store = injector.get(Store);
// Hydrate Ngrx Store
const state = userStorage.get('store');
if (state && state['version'] === version) {
store.dispatch({ type: 'HYDRATE', payload: userStorage.get('store') });
}
// Subscribe on Store changes and save to user storage
store.pipe(debounceTime(1000)).subscribe((state) => {
userStorage.set('store', state);
});
} catch (error) {
console.error('Error during app initialization', error);
laoderElement.remove();
statusElement.classList.add('text-xl');
statusElement.innerHTML +=
'⚡<br><br><b>Fehler bei der Initialisierung</b><br><br>Bitte prüfen Sie die Netzwerkverbindung (WLAN).<br><br>';
const reload = document.createElement('button');
reload.classList.add(
'bg-brand',
'text-white',
'p-2',
'rounded',
'cursor-pointer',
);
reload.innerHTML = 'App neu laden';
reload.onclick = () => window.location.reload();
statusElement.appendChild(reload);
const preLabel = document.createElement('div');
preLabel.classList.add('mt-12');
preLabel.innerHTML = 'Fehlermeldung:';
statusElement.appendChild(preLabel);
const pre = document.createElement('pre');
pre.classList.add('mt-4', 'text-wrap');
pre.innerHTML = error.message;
statusElement.appendChild(pre);
console.error('Error during app initialization', error);
throw error;
}
};
}
export function _notificationsHubOptionsFactory(
config: Config,
auth: AuthService,
): SignalRHubOptions {
const options = { ...config.get('hubs').notifications };
options.httpOptions.accessTokenFactory = () => auth.getToken();
return options;
}
@NgModule({
declarations: [AppComponent, MainComponent],
bootstrap: [AppComponent],
imports: [
BrowserModule,
BrowserAnimationsModule,
ShellModule.forRoot(),
AppRoutingModule,
AppSwaggerModule,
AppDomainModule,
CoreBreadcrumbModule.forRoot(),
CoreCommandModule.forRoot(Object.values(Commands)),
CoreLoggerModule.forRoot(),
AppStoreModule,
PreviewComponent,
AuthModule.forRoot(),
CoreApplicationModule.forRoot(),
UiModalModule.forRoot(),
UiCommonModule.forRoot(),
NotificationsHubModule.forRoot(),
ServiceWorkerModule.register('ngsw-worker.js', {
enabled: environment.production,
registrationStrategy: 'registerWhenStable:30000',
}),
ScanAdapterModule.forRoot(),
ScanditScanAdapterModule.forRoot(),
PlatformModule,
IconModule.forRoot(),
NgIconsModule.withIcons({ matWifiOff, matClose, matWifi }),
],
providers: [
provideAppInitializer(() => {
const initializerFn = _appInitializerFactory(
inject(Config),
inject(Injector),
);
return initializerFn();
}),
{
provide: NOTIFICATIONS_HUB_OPTIONS,
useFactory: _notificationsHubOptionsFactory,
deps: [Config, AuthService],
},
{
provide: HTTP_INTERCEPTORS,
useClass: HttpErrorInterceptor,
multi: true,
},
{
provide: LOG_PROVIDER,
useClass: IsaLogProvider,
multi: true,
},
{
provide: ErrorHandler,
useClass: IsaErrorHandler,
},
{
provide: ApplicationService,
useClass: ApplicationServiceAdapter,
},
{ provide: LOCALE_ID, useValue: 'de-DE' },
provideHttpClient(withInterceptorsFromDi()),
provideMatomo(
{ trackerUrl: 'https://matomo.paragon-data.net', siteId: '1' },
withRouter(),
withRouteData(),
),
provideLogging(withLogLevel(LogLevel.Debug), withSink(ConsoleLogSink)),
{
provide: DEFAULT_CURRENCY_CODE,
useValue: 'EUR',
},
],
})
export class AppModule {}

View File

@@ -1,67 +1,74 @@
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { ApplicationProcess, ApplicationService } from '@core/application';
import { BreadcrumbService } from '@core/breadcrumb';
import { first } from 'rxjs/operators';
@Injectable({ providedIn: 'root' })
export class CanActivateProductWithProcessIdGuard {
constructor(
private readonly _applicationService: ApplicationService,
private readonly _breadcrumbService: BreadcrumbService,
) {}
async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const process = await this._applicationService.getProcessById$(+route.params.processId).pipe(first()).toPromise();
// if (!(process?.type === 'cart')) {
// // TODO:
// // Anderer Prozesstyp mit gleicher Id - Was soll gemacht werden?
// return false;
// }
if (!process) {
const processes = await this._applicationService.getProcesses$('customer').pipe(first()).toPromise();
await this._applicationService.createProcess({
id: +route.params.processId,
type: 'cart',
section: 'customer',
name: `Vorgang ${this.processNumber(processes.filter((process) => process.type === 'cart'))}`,
});
}
await this.removeBreadcrumbWithSameProcessId(route);
this._applicationService.activateProcess(+route.params.processId);
return true;
}
// Fix #3292: Alle Breadcrumbs die nichts mit dem aktuellen Prozess zu tun haben, müssen removed werden
async removeBreadcrumbWithSameProcessId(route: ActivatedRouteSnapshot) {
const crumbs = await this._breadcrumbService.getBreadcrumbByKey$(+route.params.processId).pipe(first()).toPromise();
// Entferne alle Crumbs die nichts mit der Artikelsuche zu tun haben
if (crumbs.length > 1) {
const crumbsToRemove = crumbs.filter((crumb) => crumb.tags.find((tag) => tag === 'catalog') === undefined);
for (const crumb of crumbsToRemove) {
await this._breadcrumbService.removeBreadcrumb(crumb.id);
}
}
}
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[]) {
// Ticket #3272 Bei Klick auf "+" bzw. neuen Prozess hinzufügen soll der neue Tab immer die höchste Nummer haben (wie aktuell im Produktiv)
// ----------------------------------------------------------------------------------------------------------------------------------------
// 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, RouterStateSnapshot } from '@angular/router';
import { ApplicationProcess, ApplicationService } from '@core/application';
import { BreadcrumbService } from '@core/breadcrumb';
import { first } from 'rxjs/operators';
@Injectable({ providedIn: 'root' })
export class CanActivateProductWithProcessIdGuard {
constructor(
private readonly _applicationService: ApplicationService,
private readonly _breadcrumbService: BreadcrumbService,
) {}
async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const processId = +route.params.processId;
const process = await this._applicationService
.getProcessById$(processId)
.pipe(first())
.toPromise();
// if (!(process?.type === 'cart')) {
// // TODO:
// // Anderer Prozesstyp mit gleicher Id - Was soll gemacht werden?
// return false;
// }
if (!process) {
await this._applicationService.createCustomerProcess(processId);
}
await this.removeBreadcrumbWithSameProcessId(route);
this._applicationService.activateProcess(+route.params.processId);
return true;
}
// Fix #3292: Alle Breadcrumbs die nichts mit dem aktuellen Prozess zu tun haben, müssen removed werden
async removeBreadcrumbWithSameProcessId(route: ActivatedRouteSnapshot) {
const crumbs = await this._breadcrumbService
.getBreadcrumbByKey$(+route.params.processId)
.pipe(first())
.toPromise();
// Entferne alle Crumbs die nichts mit der Artikelsuche zu tun haben
if (crumbs.length > 1) {
const crumbsToRemove = crumbs.filter(
(crumb) => crumb.tags.find((tag) => tag === 'catalog') === undefined,
);
for (const crumb of crumbsToRemove) {
await this._breadcrumbService.removeBreadcrumb(crumb.id);
}
}
}
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[]) {
// Ticket #3272 Bei Klick auf "+" bzw. neuen Prozess hinzufügen soll der neue Tab immer die höchste Nummer haben (wie aktuell im Produktiv)
// ----------------------------------------------------------------------------------------------------------------------------------------
// for (let missingNumber = 1; missingNumber < Math.max(...processNumbers); missingNumber++) {
// if (!processNumbers.find((number) => number === missingNumber)) {
// return missingNumber;
// }
// }
return Math.max(...processNumbers) + 1;
}
}

View File

@@ -9,6 +9,9 @@ import {
} from "@ui/modal";
import { IsaLogProvider } from "./isa.log-provider";
import { LogLevel } from "@core/logger";
import { ZodError } from "zod";
import { extractZodErrorMessage } from "@isa/common/data-access";
import { firstValueFrom } from "rxjs";
@Injectable({ providedIn: "root" })
export class IsaErrorHandler implements ErrorHandler {
@@ -28,7 +31,7 @@ export class IsaErrorHandler implements ErrorHandler {
}
if (error instanceof HttpErrorResponse && error?.status === 401) {
await this._modal
await firstValueFrom(this._modal
.open({
content: UiDialogModalComponent,
title: "Sitzung abgelaufen",
@@ -41,12 +44,33 @@ export class IsaErrorHandler implements ErrorHandler {
],
} as DialogModel,
})
.afterClosed$.toPromise();
.afterClosed$);
this._authService.logout();
return;
}
// Handle Zod validation errors
if (error instanceof ZodError) {
const zodErrorMessage = extractZodErrorMessage(error);
await firstValueFrom(this._modal
.open({
content: UiDialogModalComponent,
title: "Validierungsfehler",
data: {
handleCommand: false,
content: `Die eingegebenen Daten sind ungültig:\n\n${zodErrorMessage}`,
actions: [
{ command: "CLOSE", selected: true, label: "OK" },
],
} as DialogModel,
})
.afterClosed$);
return;
}
try {
this._isaLogProvider.log(LogLevel.ERROR, "Client Error", error);
} catch (logError) {

View File

@@ -1,11 +1,12 @@
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class ProcessIdResolver {
resolve(route: ActivatedRouteSnapshot): Observable<number> | Promise<number> | number {
return route.params.processId;
}
}
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class ProcessIdResolver {
resolve(
route: ActivatedRouteSnapshot,
): Observable<number> | Promise<number> | number {
return route.params.processId;
}
}

View File

@@ -1,128 +0,0 @@
import { Injectable } from "@angular/core";
import { Logger, LogLevel } from "@core/logger";
import { Store } from "@ngrx/store";
import { debounceTime, switchMap, takeUntil } from "rxjs/operators";
import { RootState } from "./root.state";
import packageInfo from "packageJson";
import { environment } from "../../environments/environment";
import { Subject } from "rxjs";
import { AuthService } from "@core/auth";
import { injectStorage, UserStorageProvider } from "@isa/core/storage";
import { isEqual } from "lodash";
@Injectable({ providedIn: "root" })
export class RootStateService {
static LOCAL_STORAGE_KEY = "ISA_APP_INITIALSTATE";
#storage = injectStorage(UserStorageProvider);
private _cancelSave = new Subject<void>();
constructor(
private readonly _authService: AuthService,
private _logger: Logger,
private _store: Store,
) {
if (!environment.production) {
console.log(
'Die UserState kann in der Konsole mit der Funktion "clearUserState()" geleert werden.',
);
}
window["clearUserState"] = () => {
this.clear();
};
}
async init() {
await this.load();
this._store.dispatch({
type: "HYDRATE",
payload: RootStateService.LoadFromLocalStorage(),
});
this.initSave();
}
initSave() {
this._store
.select((state) => state)
.pipe(
takeUntil(this._cancelSave),
debounceTime(1000),
switchMap((state) => {
const data = {
...state,
version: packageInfo.version,
sub: this._authService.getClaimByKey("sub"),
};
RootStateService.SaveToLocalStorageRaw(JSON.stringify(data));
return this.#storage.set("state", data);
}),
)
.subscribe();
}
/**
* Loads the initial state from local storage and returns true/false if state was changed
*/
async load(): Promise<boolean> {
try {
const res = await this.#storage.get("state");
const storageContent = RootStateService.LoadFromLocalStorageRaw();
if (res) {
RootStateService.SaveToLocalStorageRaw(JSON.stringify(res));
}
if (!isEqual(res, storageContent)) {
return true;
}
} catch (error) {
this._logger.log(LogLevel.ERROR, error);
}
return false;
}
async clear() {
try {
this._cancelSave.next();
await this.#storage.clear("state");
await new Promise((resolve) => setTimeout(resolve, 100));
RootStateService.RemoveFromLocalStorage();
await new Promise((resolve) => setTimeout(resolve, 100));
window.location.reload();
} catch (error) {
this._logger.log(LogLevel.ERROR, error);
}
}
static SaveToLocalStorage(state: RootState) {
RootStateService.SaveToLocalStorageRaw(JSON.stringify(state));
}
static SaveToLocalStorageRaw(state: string) {
localStorage.setItem(RootStateService.LOCAL_STORAGE_KEY, state);
}
static LoadFromLocalStorage(): RootState {
const raw = RootStateService.LoadFromLocalStorageRaw();
if (raw) {
try {
return JSON.parse(raw);
} catch (error) {
console.error("Error parsing local storage:", error);
this.RemoveFromLocalStorage();
}
}
return undefined;
}
static LoadFromLocalStorageRaw(): string {
return localStorage.getItem(RootStateService.LOCAL_STORAGE_KEY);
}
static RemoveFromLocalStorage() {
localStorage.removeItem(RootStateService.LOCAL_STORAGE_KEY);
}
}

View File

@@ -0,0 +1,338 @@
import { inject, Injectable } from '@angular/core';
import { BehaviorSubject, Observable, of, firstValueFrom } from 'rxjs';
import { map, filter, withLatestFrom } from 'rxjs/operators';
import { BranchDTO } from '@generated/swagger/checkout-api';
import { isBoolean, isNumber } from '@utils/common';
import { ApplicationService } from './application.service';
import { TabService } from '@isa/core/tabs';
import { ApplicationProcess } from './defs/application-process';
import { Tab, TabMetadata } from '@isa/core/tabs';
import { toObservable } from '@angular/core/rxjs-interop';
import { Store } from '@ngrx/store';
import { removeProcess } from './store/application.actions';
/**
* Adapter service that bridges the old ApplicationService interface with the new TabService.
*
* This adapter allows existing code that depends on ApplicationService to work with the new
* TabService without requiring immediate code changes. It maps ApplicationProcess concepts
* to Tab entities, storing process-specific data in tab metadata.
*
* Key mappings:
* - ApplicationProcess.id <-> Tab.id
* - ApplicationProcess.name <-> Tab.name
* - ApplicationProcess metadata (section, type, etc.) <-> Tab.metadata with 'process_' prefix
* - ApplicationProcess.data <-> Tab.metadata with 'data_' prefix
*
* @example
* ```typescript
* // Inject the adapter instead of the original service
* constructor(private applicationService: ApplicationServiceAdapter) {}
*
* // Use the same API as before
* const process = await this.applicationService.createCustomerProcess();
* this.applicationService.activateProcess(process.id);
* ```
*/
@Injectable({ providedIn: 'root' })
export class ApplicationServiceAdapter extends ApplicationService {
#store = inject(Store);
#tabService = inject(TabService);
#activatedProcessId$ = toObservable(this.#tabService.activatedTabId);
#tabs$ = toObservable(this.#tabService.entities);
#processes$ = this.#tabs$.pipe(
map((tabs) => tabs.map((tab) => this.mapTabToProcess(tab))),
);
#section = new BehaviorSubject<'customer' | 'branch'>('customer');
readonly REGEX_PROCESS_NAME = /^Vorgang \d+$/;
get activatedProcessId() {
return this.#tabService.activatedTabId();
}
get activatedProcessId$() {
return this.#activatedProcessId$;
}
getProcesses$(
section?: 'customer' | 'branch',
): Observable<ApplicationProcess[]> {
return this.#processes$.pipe(
map((processes) =>
processes.filter((process) =>
section ? process.section === section : true,
),
),
);
}
getProcessById$(processId: number): Observable<ApplicationProcess> {
return this.#processes$.pipe(
map((processes) => processes.find((process) => process.id === processId)),
);
}
getSection$(): Observable<'customer' | 'branch'> {
return this.#section.asObservable();
}
getTitle$(): Observable<'Kundenbereich' | 'Filialbereich'> {
return this.getSection$().pipe(
map((section) =>
section === 'customer' ? 'Kundenbereich' : 'Filialbereich',
),
);
}
/** @deprecated */
getActivatedProcessId$(): Observable<number> {
return this.activatedProcessId$;
}
activateProcess(activatedProcessId: number): void {
this.#tabService.activateTab(activatedProcessId);
}
removeProcess(processId: number): void {
this.#tabService.removeTab(processId);
this.#store.dispatch(removeProcess({ processId }));
}
patchProcess(processId: number, changes: Partial<ApplicationProcess>): void {
const tabChanges: {
name?: string;
tags?: string[];
metadata?: Record<string, unknown>;
} = {};
if (changes.name) {
tabChanges.name = changes.name;
}
// Store other ApplicationProcess properties in metadata
const metadataKeys = [
'section',
'type',
'closeable',
'confirmClosing',
'created',
'activated',
'data',
];
metadataKeys.forEach((key) => {
if (tabChanges.metadata === undefined) {
tabChanges.metadata = {};
}
if (changes[key as keyof ApplicationProcess] !== undefined) {
tabChanges.metadata[`process_${key}`] =
changes[key as keyof ApplicationProcess];
}
});
// Apply the changes to the tab
this.#tabService.patchTab(processId, tabChanges);
}
patchProcessData(processId: number, data: Record<string, unknown>): void {
const currentProcess = this.#tabService.entityMap()[processId];
const currentData: TabMetadata =
(currentProcess?.metadata?.['process_data'] as TabMetadata) ?? {};
this.#tabService.patchTab(processId, {
metadata: { [`process_data`]: { ...currentData, ...data } },
});
}
getSelectedBranch$(): Observable<BranchDTO> {
return this.#processes$.pipe(
withLatestFrom(this.#activatedProcessId$),
map(([processes, activatedProcessId]) =>
processes.find((process) => process.id === activatedProcessId),
),
filter((process): process is ApplicationProcess => !!process),
map((process) => process.data?.selectedBranch as BranchDTO),
);
}
async createCustomerProcess(processId?: number): Promise<ApplicationProcess> {
const processes = await firstValueFrom(this.getProcesses$('customer'));
const processIds = processes
.filter((x) => this.REGEX_PROCESS_NAME.test(x.name))
.map((x) => +x.name.split(' ')[1]);
const maxId = processIds.length > 0 ? Math.max(...processIds) : 0;
const process: ApplicationProcess = {
id: processId ?? Date.now(),
type: 'cart',
name: `Vorgang ${maxId + 1}`,
section: 'customer',
closeable: true,
};
await this.createProcess(process);
return process;
}
/**
* Creates a new ApplicationProcess by first creating a Tab and then storing
* process-specific properties in the tab's metadata.
*
* @param process - The ApplicationProcess to create
* @throws {Error} If process ID already exists or is invalid
*/
async createProcess(process: ApplicationProcess): Promise<void> {
const existingProcess = this.#tabService.entityMap()[process.id];
if (existingProcess?.id === process?.id) {
throw new Error('Process Id existiert bereits');
}
if (!isNumber(process.id)) {
throw new Error('Process Id nicht gesetzt');
}
if (!isBoolean(process.closeable)) {
process.closeable = true;
}
if (!isBoolean(process.confirmClosing)) {
process.confirmClosing = true;
}
process.created = this.createTimestamp();
process.activated = 0;
// Create tab with process data and preserve the process ID
this.#tabService.addTab({
id: process.id,
name: process.name,
tags: [process.section, process.type].filter(Boolean),
metadata: {
process_section: process.section,
process_type: process.type,
process_closeable: process.closeable,
process_confirmClosing: process.confirmClosing,
process_created: process.created,
process_activated: process.activated,
process_data: process.data,
},
});
}
setSection(section: 'customer' | 'branch'): void {
this.#section.next(section);
}
getLastActivatedProcessWithSectionAndType$(
section: 'customer' | 'branch',
type: string,
): Observable<ApplicationProcess> {
return this.getProcesses$(section).pipe(
map((processes) =>
processes
?.filter((process) => process.type === type)
?.reduce((latest, current) => {
if (!latest) {
return current;
}
return latest?.activated > current?.activated ? latest : current;
}, undefined),
),
);
}
getLastActivatedProcessWithSection$(
section: 'customer' | 'branch',
): Observable<ApplicationProcess> {
return this.getProcesses$(section).pipe(
map((processes) =>
processes?.reduce((latest, current) => {
if (!latest) {
return current;
}
return latest?.activated > current?.activated ? latest : current;
}, undefined),
),
);
}
/**
* Maps Tab entities to ApplicationProcess objects by extracting process-specific
* metadata and combining it with tab properties.
*
* @param tab - The tab entity to convert
* @returns The corresponding ApplicationProcess object
*/
private mapTabToProcess(tab: Tab): ApplicationProcess {
return {
id: tab.id,
name: tab.name,
created:
this.getMetadataValue<number>(tab.metadata, 'process_created') ??
tab.createdAt,
activated:
this.getMetadataValue<number>(tab.metadata, 'process_activated') ??
tab.activatedAt ??
0,
section:
this.getMetadataValue<'customer' | 'branch'>(
tab.metadata,
'process_section',
) ?? 'customer',
type: this.getMetadataValue<string>(tab.metadata, 'process_type'),
closeable:
this.getMetadataValue<boolean>(tab.metadata, 'process_closeable') ??
true,
confirmClosing:
this.getMetadataValue<boolean>(
tab.metadata,
'process_confirmClosing',
) ?? true,
data: this.extractDataFromMetadata(tab.metadata),
};
}
/**
* Extracts ApplicationProcess data properties from tab metadata.
* Data properties are stored with a 'data_' prefix in tab metadata.
*
* @param metadata - The tab metadata object
* @returns The extracted data object or undefined if no data properties exist
*/
private extractDataFromMetadata(
metadata: TabMetadata,
): Record<string, unknown> | undefined {
// Return the complete data object stored under 'process_data'
const processData = metadata?.['process_data'];
if (
processData &&
typeof processData === 'object' &&
processData !== null
) {
return processData as Record<string, unknown>;
}
return undefined;
}
private getMetadataValue<T>(
metadata: TabMetadata,
key: string,
): T | undefined {
return metadata?.[key] as T | undefined;
}
private createTimestamp(): number {
return Date.now();
}
}

View File

@@ -1,4 +1,5 @@
export * from './application.module';
export * from './application.service';
export * from './application.service-adapter';
export * from './defs';
export * from './store';

View File

@@ -1,55 +1,55 @@
import {
ChangeDetectionStrategy,
Component,
EventEmitter,
Input,
Output,
inject,
linkedSignal,
} from '@angular/core';
import { Router } from '@angular/router';
import { PickupShelfInNavigationService } from '@shared/services/navigation';
import { UiFilter } from '@ui/filter';
import { MessageBoardItemDTO } from '@hub/notifications';
import { TabService } from '@isa/core/tabs';
@Component({
selector: 'modal-notifications-remission-group',
templateUrl: 'notifications-remission-group.component.html',
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: false,
})
export class ModalNotificationsRemissionGroupComponent {
tabService = inject(TabService);
private _pickupShelfInNavigationService = inject(
PickupShelfInNavigationService,
);
@Input()
notifications: MessageBoardItemDTO[];
@Output()
navigated = new EventEmitter<void>();
remissionPath = linkedSignal(() => [
'/',
this.tabService.activatedTab()?.id || this.tabService.nextId(),
'remission',
]);
constructor(private _router: Router) {}
itemSelected(item: MessageBoardItemDTO) {
const defaultNav = this._pickupShelfInNavigationService.listRoute();
const queryParams = UiFilter.getQueryParamsFromQueryTokenDTO(
item.queryToken,
);
this._router.navigate(defaultNav.path, {
queryParams: {
...defaultNav.queryParams,
...queryParams,
},
});
this.navigated.emit();
}
}
import {
ChangeDetectionStrategy,
Component,
EventEmitter,
Input,
Output,
inject,
linkedSignal,
} from '@angular/core';
import { Router } from '@angular/router';
import { PickupShelfInNavigationService } from '@shared/services/navigation';
import { UiFilter } from '@ui/filter';
import { MessageBoardItemDTO } from '@hub/notifications';
import { TabService } from '@isa/core/tabs';
@Component({
selector: 'modal-notifications-remission-group',
templateUrl: 'notifications-remission-group.component.html',
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: false,
})
export class ModalNotificationsRemissionGroupComponent {
tabService = inject(TabService);
private _pickupShelfInNavigationService = inject(
PickupShelfInNavigationService,
);
@Input()
notifications: MessageBoardItemDTO[];
@Output()
navigated = new EventEmitter<void>();
remissionPath = linkedSignal(() => [
'/',
this.tabService.activatedTab()?.id || Date.now(),
'remission',
]);
constructor(private _router: Router) {}
itemSelected(item: MessageBoardItemDTO) {
const defaultNav = this._pickupShelfInNavigationService.listRoute();
const queryParams = UiFilter.getQueryParamsFromQueryTokenDTO(
item.queryToken,
);
this._router.navigate(defaultNav.path, {
queryParams: {
...defaultNav.queryParams,
...queryParams,
},
});
this.navigated.emit();
}
}

View File

@@ -1,4 +1,4 @@
<ng-container *ifRole="'Store'">
<!-- <ng-container *ifRole="'Store'">
@if (customerType !== 'b2b') {
<shared-checkbox
[ngModel]="p4mUser"
@@ -8,15 +8,17 @@
Kundenkarte
</shared-checkbox>
}
</ng-container>
</ng-container> -->
@for (option of filteredOptions$ | async; track option) {
@if (option?.enabled !== false) {
<shared-checkbox
[ngModel]="option.value === customerType"
(ngModelChange)="setValue({ customerType: $event ? option.value : undefined })"
(ngModelChange)="
setValue({ customerType: $event ? option.value : undefined })
"
[disabled]="isOptionDisabled(option)"
[name]="option.value"
>
>
{{ option.label }}
</shared-checkbox>
}

View File

@@ -21,7 +21,13 @@ import { OptionDTO } from '@generated/swagger/checkout-api';
import { UiCheckboxComponent } from '@ui/checkbox';
import { first, isBoolean, isString } from 'lodash';
import { combineLatest, Observable, Subject } from 'rxjs';
import { distinctUntilChanged, filter, map, shareReplay, switchMap } from 'rxjs/operators';
import {
distinctUntilChanged,
filter,
map,
shareReplay,
switchMap,
} from 'rxjs/operators';
export interface CustomerTypeSelectorState {
processId: number;
@@ -58,18 +64,18 @@ export class CustomerTypeSelectorComponent
@Input()
get value() {
if (this.p4mUser) {
return `${this.customerType}-p4m`;
}
// if (this.p4mUser) {
// return `${this.customerType}-p4m`;
// }
return this.customerType;
}
set value(value: string) {
if (value.includes('-p4m')) {
this.p4mUser = true;
this.customerType = value.replace('-p4m', '');
} else {
this.customerType = value;
}
// if (value.includes('-p4m')) {
// this.p4mUser = true;
// this.customerType = value.replace('-p4m', '');
// } else {
this.customerType = value;
// }
}
@Output()
@@ -111,29 +117,36 @@ export class CustomerTypeSelectorComponent
get filteredOptions$() {
const options$ = this.select((s) => s.options).pipe(distinctUntilChanged());
const p4mUser$ = this.select((s) => s.p4mUser).pipe(distinctUntilChanged());
const customerType$ = this.select((s) => s.customerType).pipe(distinctUntilChanged());
const customerType$ = this.select((s) => s.customerType).pipe(
distinctUntilChanged(),
);
return combineLatest([options$, p4mUser$, customerType$]).pipe(
filter(([options]) => options?.length > 0),
map(([options, p4mUser, customerType]) => {
const initial = { p4mUser: this.p4mUser, customerType: this.customerType };
const initial = {
p4mUser: this.p4mUser,
customerType: this.customerType,
};
let result: OptionDTO[] = options;
if (p4mUser) {
result = result.filter((o) => o.value === 'store' || (o.value === 'webshop' && o.enabled !== false));
// if (p4mUser) {
// result = result.filter((o) => o.value === 'store' || (o.value === 'webshop' && o.enabled !== false));
result = result.map((o) => {
if (o.value === 'store') {
return { ...o, enabled: false };
}
return o;
});
}
// result = result.map((o) => {
// if (o.value === 'store') {
// return { ...o, enabled: false };
// }
// return o;
// });
// }
if (customerType === 'b2b' && this.p4mUser) {
this.p4mUser = false;
}
if (initial.p4mUser !== this.p4mUser || initial.customerType !== this.customerType) {
this.setValue({ customerType: this.customerType, p4mUser: this.p4mUser });
if (initial.customerType !== this.customerType) {
// if (initial.p4mUser !== this.p4mUser || initial.customerType !== this.customerType) {
// this.setValue({ customerType: this.customerType, p4mUser: this.p4mUser });
this.setValue({ customerType: this.customerType });
}
return result;
@@ -224,42 +237,51 @@ export class CustomerTypeSelectorComponent
if (typeof value === 'string') {
this.value = value;
} else {
if (isBoolean(value.p4mUser)) {
this.p4mUser = value.p4mUser;
}
// if (isBoolean(value.p4mUser)) {
// this.p4mUser = value.p4mUser;
// }
if (isString(value.customerType)) {
this.customerType = value.customerType;
} else if (this.p4mUser) {
// Implementierung wie im PBI #3467 beschrieben
// wenn customerType nicht gesetzt wird und p4mUser true ist,
// dann customerType auf store setzen.
// wenn dies nicht möglich ist da der Warenkob keinen store Kunden zulässt,
// dann customerType auf webshop setzen.
// wenn dies nicht möglich ist da der Warenkob keinen webshop Kunden zulässt,
// dann customerType auf den ersten verfügbaren setzen und p4mUser auf false setzen.
if (this.enabledOptions.some((o) => o.value === 'store')) {
this.customerType = 'store';
} else if (this.enabledOptions.some((o) => o.value === 'webshop')) {
this.customerType = 'webshop';
} else {
this.p4mUser = false;
const includesGuest = this.enabledOptions.some((o) => o.value === 'guest');
this.customerType = includesGuest ? 'guest' : first(this.enabledOptions)?.value;
}
} else {
}
// else if (this.p4mUser) {
// // Implementierung wie im PBI #3467 beschrieben
// // wenn customerType nicht gesetzt wird und p4mUser true ist,
// // dann customerType auf store setzen.
// // wenn dies nicht möglich ist da der Warenkob keinen store Kunden zulässt,
// // dann customerType auf webshop setzen.
// // wenn dies nicht möglich ist da der Warenkob keinen webshop Kunden zulässt,
// // dann customerType auf den ersten verfügbaren setzen und p4mUser auf false setzen.
// if (this.enabledOptions.some((o) => o.value === 'store')) {
// this.customerType = 'store';
// } else if (this.enabledOptions.some((o) => o.value === 'webshop')) {
// this.customerType = 'webshop';
// } else {
// this.p4mUser = false;
// const includesGuest = this.enabledOptions.some((o) => o.value === 'guest');
// this.customerType = includesGuest ? 'guest' : first(this.enabledOptions)?.value;
// }
// }
else {
// wenn customerType nicht gesetzt wird und p4mUser false ist,
// dann customerType auf den ersten verfügbaren setzen der nicht mit dem aktuellen customerType übereinstimmt.
this.customerType =
first(this.enabledOptions.filter((o) => o.value === this.customerType))?.value ?? this.customerType;
first(
this.enabledOptions.filter((o) => o.value === this.customerType),
)?.value ?? this.customerType;
}
}
if (this.customerType !== initial.customerType || this.p4mUser !== initial.p4mUser) {
if (
this.customerType !== initial.customerType ||
this.p4mUser !== initial.p4mUser
) {
this.onChange(this.value);
this.onTouched();
this.valueChanges.emit(this.value);
}
this.checkboxes?.find((c) => c.name === this.customerType)?.writeValue(true);
this.checkboxes
?.find((c) => c.name === this.customerType)
?.writeValue(true);
}
}

View File

@@ -7,6 +7,6 @@ export * from './interests';
export * from './name';
export * from './newsletter';
export * from './organisation';
export * from './p4m-number';
// export * from './p4m-number';
export * from './phone-numbers';
export * from './form-block';

View File

@@ -1,4 +1,4 @@
// start:ng42.barrel
export * from './p4m-number-form-block.component';
export * from './p4m-number-form-block.module';
// end:ng42.barrel
// // start:ng42.barrel
// export * from './p4m-number-form-block.component';
// export * from './p4m-number-form-block.module';
// // end:ng42.barrel

View File

@@ -1,4 +1,4 @@
<shared-form-control label="Kundenkartencode" class="flex-grow">
<!-- <shared-form-control label="Kundenkartencode" class="flex-grow">
<input
placeholder="Kundenkartencode"
class="input-control"
@@ -13,4 +13,4 @@
<button type="button" (click)="scan()">
<shared-icon icon="barcode-scan" [size]="32"></shared-icon>
</button>
}
} -->

View File

@@ -1,49 +1,49 @@
import { Component, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { UntypedFormControl, Validators } from '@angular/forms';
import { FormBlockControl } from '../form-block';
import { ScanAdapterService } from '@adapter/scan';
// import { Component, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
// import { UntypedFormControl, Validators } from '@angular/forms';
// import { FormBlockControl } from '../form-block';
// import { ScanAdapterService } from '@adapter/scan';
@Component({
selector: 'app-p4m-number-form-block',
templateUrl: 'p4m-number-form-block.component.html',
styleUrls: ['p4m-number-form-block.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: false,
})
export class P4mNumberFormBlockComponent extends FormBlockControl<string> {
get tabIndexEnd() {
return this.tabIndexStart;
}
// @Component({
// selector: 'app-p4m-number-form-block',
// templateUrl: 'p4m-number-form-block.component.html',
// styleUrls: ['p4m-number-form-block.component.scss'],
// changeDetection: ChangeDetectionStrategy.OnPush,
// standalone: false,
// })
// export class P4mNumberFormBlockComponent extends FormBlockControl<string> {
// get tabIndexEnd() {
// return this.tabIndexStart;
// }
constructor(
private scanAdapter: ScanAdapterService,
private changeDetectorRef: ChangeDetectorRef,
) {
super();
}
// constructor(
// private scanAdapter: ScanAdapterService,
// private changeDetectorRef: ChangeDetectorRef,
// ) {
// super();
// }
updateValidators(): void {
this.control.setValidators([...this.getValidatorFn()]);
this.control.setAsyncValidators(this.getAsyncValidatorFn());
this.control.updateValueAndValidity();
}
// updateValidators(): void {
// this.control.setValidators([...this.getValidatorFn()]);
// this.control.setAsyncValidators(this.getAsyncValidatorFn());
// this.control.updateValueAndValidity();
// }
initializeControl(data?: string): void {
this.control = new UntypedFormControl(data ?? '', [Validators.required], this.getAsyncValidatorFn());
}
// initializeControl(data?: string): void {
// this.control = new UntypedFormControl(data ?? '', [Validators.required], this.getAsyncValidatorFn());
// }
_patchValue(update: { previous: string; current: string }): void {
this.control.patchValue(update.current);
}
// _patchValue(update: { previous: string; current: string }): void {
// this.control.patchValue(update.current);
// }
scan() {
this.scanAdapter.scan().subscribe((result) => {
this.control.patchValue(result);
this.changeDetectorRef.markForCheck();
});
}
// scan() {
// this.scanAdapter.scan().subscribe((result) => {
// this.control.patchValue(result);
// this.changeDetectorRef.markForCheck();
// });
// }
canScan() {
return this.scanAdapter.isReady();
}
}
// canScan() {
// return this.scanAdapter.isReady();
// }
// }

View File

@@ -1,14 +1,14 @@
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
// import { NgModule } from '@angular/core';
// import { CommonModule } from '@angular/common';
import { P4mNumberFormBlockComponent } from './p4m-number-form-block.component';
import { ReactiveFormsModule } from '@angular/forms';
import { IconComponent } from '@shared/components/icon';
import { FormControlComponent } from '@shared/components/form-control';
// import { P4mNumberFormBlockComponent } from './p4m-number-form-block.component';
// import { ReactiveFormsModule } from '@angular/forms';
// import { IconComponent } from '@shared/components/icon';
// import { FormControlComponent } from '@shared/components/form-control';
@NgModule({
imports: [CommonModule, ReactiveFormsModule, FormControlComponent, IconComponent],
exports: [P4mNumberFormBlockComponent],
declarations: [P4mNumberFormBlockComponent],
})
export class P4mNumberFormBlockModule {}
// @NgModule({
// imports: [CommonModule, ReactiveFormsModule, FormControlComponent, IconComponent],
// exports: [P4mNumberFormBlockComponent],
// declarations: [P4mNumberFormBlockComponent],
// })
// export class P4mNumberFormBlockModule {}

View File

@@ -1,5 +1,12 @@
import { HttpErrorResponse } from '@angular/common/http';
import { ChangeDetectorRef, Directive, OnDestroy, OnInit, ViewChild, inject } from '@angular/core';
import {
ChangeDetectorRef,
Directive,
OnDestroy,
OnInit,
ViewChild,
inject,
} from '@angular/core';
import {
AbstractControl,
AsyncValidatorFn,
@@ -11,7 +18,12 @@ import {
import { ActivatedRoute, Router } from '@angular/router';
import { BreadcrumbService } from '@core/breadcrumb';
import { CrmCustomerService } from '@domain/crm';
import { AddressDTO, CustomerDTO, PayerDTO, ShippingAddressDTO } from '@generated/swagger/crm-api';
import {
AddressDTO,
CustomerDTO,
PayerDTO,
ShippingAddressDTO,
} from '@generated/swagger/crm-api';
import { UiErrorModalComponent, UiModalService } from '@ui/modal';
import { UiValidators } from '@ui/validators';
import { isNull } from 'lodash';
@@ -42,7 +54,10 @@ import {
mapCustomerInfoDtoToCustomerCreateFormData,
} from './customer-create-form-data';
import { AddressSelectionModalService } from '../modals';
import { CustomerCreateNavigation, CustomerSearchNavigation } from '@shared/services/navigation';
import {
CustomerCreateNavigation,
CustomerSearchNavigation,
} from '@shared/services/navigation';
@Directive()
export abstract class AbstractCreateCustomer implements OnInit, OnDestroy {
@@ -104,7 +119,12 @@ export abstract class AbstractCreateCustomer implements OnInit, OnDestroy {
);
this.processId$
.pipe(startWith(undefined), bufferCount(2, 1), takeUntil(this.onDestroy$), delay(100))
.pipe(
startWith(undefined),
bufferCount(2, 1),
takeUntil(this.onDestroy$),
delay(100),
)
.subscribe(async ([previous, current]) => {
if (previous === undefined) {
await this._initFormData();
@@ -155,7 +175,10 @@ export abstract class AbstractCreateCustomer implements OnInit, OnDestroy {
}
}
async addOrUpdateBreadcrumb(processId: number, formData: CustomerCreateFormData) {
async addOrUpdateBreadcrumb(
processId: number,
formData: CustomerCreateFormData,
) {
await this.breadcrumb.addOrUpdateBreadcrumbIfNotExists({
key: processId,
name: 'Kundendaten erfassen',
@@ -195,7 +218,10 @@ export abstract class AbstractCreateCustomer implements OnInit, OnDestroy {
console.log('customerTypeChanged', customerType);
}
addFormBlock(key: keyof CustomerCreateFormData, block: FormBlock<any, AbstractControl>) {
addFormBlock(
key: keyof CustomerCreateFormData,
block: FormBlock<any, AbstractControl>,
) {
this.form.addControl(key, block.control);
this.cdr.markForCheck();
}
@@ -232,7 +258,10 @@ export abstract class AbstractCreateCustomer implements OnInit, OnDestroy {
return true;
}
// Check Year + Month
else if (inputDate.getFullYear() === minBirthDate.getFullYear() && inputDate.getMonth() < minBirthDate.getMonth()) {
else if (
inputDate.getFullYear() === minBirthDate.getFullYear() &&
inputDate.getMonth() < minBirthDate.getMonth()
) {
return true;
}
// Check Year + Month + Day
@@ -279,70 +308,80 @@ export abstract class AbstractCreateCustomer implements OnInit, OnDestroy {
);
};
checkLoyalityCardValidator: AsyncValidatorFn = (control) => {
return of(control.value).pipe(
delay(500),
mergeMap((value) => {
const customerId = this.formData?._meta?.customerDto?.id ?? this.formData?._meta?.customerInfoDto?.id;
return this.customerService.checkLoyaltyCard({ loyaltyCardNumber: value, customerId }).pipe(
map((response) => {
if (response.error) {
throw response.message;
}
// checkLoyalityCardValidator: AsyncValidatorFn = (control) => {
// return of(control.value).pipe(
// delay(500),
// mergeMap((value) => {
// const customerId = this.formData?._meta?.customerDto?.id ?? this.formData?._meta?.customerInfoDto?.id;
// return this.customerService.checkLoyaltyCard({ loyaltyCardNumber: value, customerId }).pipe(
// map((response) => {
// if (response.error) {
// throw response.message;
// }
/**
* #4485 Kubi // Verhalten mit angelegte aber nicht verknüpfte Kundenkartencode in Kundensuche und Kundendaten erfassen ist nicht gleich
* Fall1: Kundenkarte hat Daten in point4more:
* Sobald Kundenkartencode in Feld "Kundenkartencode" reingegeben wird- werden die Daten von point4more in Formular "Kundendaten Erfassen" eingefügt und ersetzen (im Ganzen, nicht inkremental) die Daten in Felder, falls welche schon reingetippt werden.
* Fall2: Kundenkarte hat keine Daten in point4more:
* Sobald Kundenkartencode in Feld "Kundenkartencode" reingegeben wird- bleiben die Daten in Formular "Kundendaten Erfassen" in Felder, falls welche schon reingetippt werden.
*/
if (response.result && response.result.customer) {
const customer = response.result.customer;
const data = mapCustomerInfoDtoToCustomerCreateFormData(customer);
// /**
// * #4485 Kubi // Verhalten mit angelegte aber nicht verknüpfte Kundenkartencode in Kundensuche und Kundendaten erfassen ist nicht gleich
// * Fall1: Kundenkarte hat Daten in point4more:
// * Sobald Kundenkartencode in Feld "Kundenkartencode" reingegeben wird- werden die Daten von point4more in Formular "Kundendaten Erfassen" eingefügt und ersetzen (im Ganzen, nicht inkremental) die Daten in Felder, falls welche schon reingetippt werden.
// * Fall2: Kundenkarte hat keine Daten in point4more:
// * Sobald Kundenkartencode in Feld "Kundenkartencode" reingegeben wird- bleiben die Daten in Formular "Kundendaten Erfassen" in Felder, falls welche schon reingetippt werden.
// */
// if (response.result && response.result.customer) {
// const customer = response.result.customer;
// const data = mapCustomerInfoDtoToCustomerCreateFormData(customer);
if (data.name.firstName && data.name.lastName) {
// Fall1
this._formData.next(data);
} else {
// Fall2 Hier müssen die Metadaten gesetzt werden um eine verknüfung zur kundenkarte zu ermöglichen.
const current = this.formData;
current._meta = data._meta;
current.p4m = data.p4m;
}
}
// if (data.name.firstName && data.name.lastName) {
// // Fall1
// this._formData.next(data);
// } else {
// // Fall2 Hier müssen die Metadaten gesetzt werden um eine verknüfung zur kundenkarte zu ermöglichen.
// const current = this.formData;
// current._meta = data._meta;
// current.p4m = data.p4m;
// }
// }
return null;
}),
catchError((error) => {
if (error instanceof HttpErrorResponse) {
if (error?.error?.invalidProperties?.loyaltyCardNumber) {
return of({ invalid: error.error.invalidProperties.loyaltyCardNumber });
} else {
return of({ invalid: 'Kundenkartencode ist ungültig' });
}
}
}),
);
}),
tap(() => {
control.markAsTouched();
this.cdr.markForCheck();
}),
);
};
// return null;
// }),
// catchError((error) => {
// if (error instanceof HttpErrorResponse) {
// if (error?.error?.invalidProperties?.loyaltyCardNumber) {
// return of({ invalid: error.error.invalidProperties.loyaltyCardNumber });
// } else {
// return of({ invalid: 'Kundenkartencode ist ungültig' });
// }
// }
// }),
// );
// }),
// tap(() => {
// control.markAsTouched();
// this.cdr.markForCheck();
// }),
// );
// };
async navigateToCustomerDetails(customer: CustomerDTO) {
const processId = await this.processId$.pipe(first()).toPromise();
const route = this.customerSearchNavigation.detailsRoute({ processId, customerId: customer.id, customer });
const route = this.customerSearchNavigation.detailsRoute({
processId,
customerId: customer.id,
customer,
});
return this.router.navigate(route.path, { queryParams: route.urlTree.queryParams });
return this.router.navigate(route.path, {
queryParams: route.urlTree.queryParams,
});
}
async validateAddressData(address: AddressDTO): Promise<AddressDTO> {
const addressValidationResult = await this.addressVlidationModal.validateAddress(address);
const addressValidationResult =
await this.addressVlidationModal.validateAddress(address);
if (addressValidationResult !== undefined && (addressValidationResult as any) !== 'continue') {
if (
addressValidationResult !== undefined &&
(addressValidationResult as any) !== 'continue'
) {
address = addressValidationResult;
}
@@ -389,7 +428,9 @@ export abstract class AbstractCreateCustomer implements OnInit, OnDestroy {
} catch (error) {
this.form.enable();
setTimeout(() => {
this.addressFormBlock.setAddressValidationError(error.error.invalidProperties);
this.addressFormBlock.setAddressValidationError(
error.error.invalidProperties,
);
}, 10);
return;
@@ -397,7 +438,10 @@ export abstract class AbstractCreateCustomer implements OnInit, OnDestroy {
}
}
if (data.birthDate && isNull(UiValidators.date(new UntypedFormControl(data.birthDate)))) {
if (
data.birthDate &&
isNull(UiValidators.date(new UntypedFormControl(data.birthDate)))
) {
customer.dateOfBirth = data.birthDate;
}
@@ -406,11 +450,15 @@ export abstract class AbstractCreateCustomer implements OnInit, OnDestroy {
if (this.validateShippingAddress) {
try {
billingAddress.address = await this.validateAddressData(billingAddress.address);
billingAddress.address = await this.validateAddressData(
billingAddress.address,
);
} catch (error) {
this.form.enable();
setTimeout(() => {
this.addressFormBlock.setAddressValidationError(error.error.invalidProperties);
this.addressFormBlock.setAddressValidationError(
error.error.invalidProperties,
);
}, 10);
return;
@@ -426,15 +474,21 @@ export abstract class AbstractCreateCustomer implements OnInit, OnDestroy {
}
if (data.deviatingDeliveryAddress?.deviatingAddress) {
const shippingAddress = this.mapToShippingAddress(data.deviatingDeliveryAddress);
const shippingAddress = this.mapToShippingAddress(
data.deviatingDeliveryAddress,
);
if (this.validateShippingAddress) {
try {
shippingAddress.address = await this.validateAddressData(shippingAddress.address);
shippingAddress.address = await this.validateAddressData(
shippingAddress.address,
);
} catch (error) {
this.form.enable();
setTimeout(() => {
this.deviatingDeliveryAddressFormBlock.setAddressValidationError(error.error.invalidProperties);
this.deviatingDeliveryAddressFormBlock.setAddressValidationError(
error.error.invalidProperties,
);
}, 10);
return;
@@ -474,7 +528,13 @@ export abstract class AbstractCreateCustomer implements OnInit, OnDestroy {
};
}
mapToBillingAddress({ name, address, email, organisation, phoneNumbers }: DeviatingAddressFormBlockData): PayerDTO {
mapToBillingAddress({
name,
address,
email,
organisation,
phoneNumbers,
}: DeviatingAddressFormBlockData): PayerDTO {
return {
gender: name?.gender,
title: name?.title,

View File

@@ -1,10 +1,10 @@
import { NgModule } from '@angular/core';
import { CreateB2BCustomerModule } from './create-b2b-customer/create-b2b-customer.module';
import { CreateGuestCustomerModule } from './create-guest-customer';
import { CreateP4MCustomerModule } from './create-p4m-customer';
// import { CreateP4MCustomerModule } from './create-p4m-customer';
import { CreateStoreCustomerModule } from './create-store-customer/create-store-customer.module';
import { CreateWebshopCustomerModule } from './create-webshop-customer/create-webshop-customer.module';
import { UpdateP4MWebshopCustomerModule } from './update-p4m-webshop-customer';
// import { UpdateP4MWebshopCustomerModule } from './update-p4m-webshop-customer';
import { CreateCustomerComponent } from './create-customer.component';
@NgModule({
@@ -13,8 +13,8 @@ import { CreateCustomerComponent } from './create-customer.component';
CreateGuestCustomerModule,
CreateStoreCustomerModule,
CreateWebshopCustomerModule,
CreateP4MCustomerModule,
UpdateP4MWebshopCustomerModule,
// CreateP4MCustomerModule,
// UpdateP4MWebshopCustomerModule,
CreateCustomerComponent,
],
exports: [
@@ -22,8 +22,8 @@ import { CreateCustomerComponent } from './create-customer.component';
CreateGuestCustomerModule,
CreateStoreCustomerModule,
CreateWebshopCustomerModule,
CreateP4MCustomerModule,
UpdateP4MWebshopCustomerModule,
// CreateP4MCustomerModule,
// UpdateP4MWebshopCustomerModule,
CreateCustomerComponent,
],
})

View File

@@ -1,10 +1,10 @@
@if (formData$ | async; as data) {
<!-- @if (formData$ | async; as data) {
<form (keydown.enter)="$event.preventDefault()">
<h1 class="title flex flex-row items-center justify-center">
Kundendaten erfassen
<!-- <span
Kundendaten erfassen -->
<!-- <span
class="rounded-full ml-4 h-8 w-8 text-xl text-center border-2 border-solid border-brand text-brand">i</span> -->
</h1>
<!-- </h1>
<p class="description">
Um Sie als Kunde beim nächsten
<br />
@@ -135,4 +135,4 @@
</button>
</div>
</form>
}
} -->

View File

@@ -1,292 +1,292 @@
import { Component, ChangeDetectionStrategy, ViewChild, OnInit } from '@angular/core';
import { AsyncValidatorFn, ValidatorFn, Validators } from '@angular/forms';
import { Result } from '@domain/defs';
import { CustomerDTO, CustomerInfoDTO, KeyValueDTOOfStringAndString } from '@generated/swagger/crm-api';
import { UiErrorModalComponent, UiModalResult } from '@ui/modal';
import { NEVER, Observable, of } from 'rxjs';
import { catchError, distinctUntilChanged, first, map, switchMap, takeUntil, withLatestFrom } from 'rxjs/operators';
import {
AddressFormBlockComponent,
AddressFormBlockData,
DeviatingAddressFormBlockComponent,
} from '../../components/form-blocks';
import { NameFormBlockData } from '../../components/form-blocks/name/name-form-block-data';
import { WebshopCustomnerAlreadyExistsModalComponent, WebshopCustomnerAlreadyExistsModalData } from '../../modals';
import { validateEmail } from '../../validators/email-validator';
import { AbstractCreateCustomer } from '../abstract-create-customer';
import { encodeFormData, mapCustomerDtoToCustomerCreateFormData } from '../customer-create-form-data';
import { zipCodeValidator } from '../../validators/zip-code-validator';
// import { Component, ChangeDetectionStrategy, ViewChild, OnInit } from '@angular/core';
// import { AsyncValidatorFn, ValidatorFn, Validators } from '@angular/forms';
// import { Result } from '@domain/defs';
// import { CustomerDTO, CustomerInfoDTO, KeyValueDTOOfStringAndString } from '@generated/swagger/crm-api';
// import { UiErrorModalComponent, UiModalResult } from '@ui/modal';
// import { NEVER, Observable, of } from 'rxjs';
// import { catchError, distinctUntilChanged, first, map, switchMap, takeUntil, withLatestFrom } from 'rxjs/operators';
// import {
// AddressFormBlockComponent,
// AddressFormBlockData,
// DeviatingAddressFormBlockComponent,
// } from '../../components/form-blocks';
// import { NameFormBlockData } from '../../components/form-blocks/name/name-form-block-data';
// import { WebshopCustomnerAlreadyExistsModalComponent, WebshopCustomnerAlreadyExistsModalData } from '../../modals';
// import { validateEmail } from '../../validators/email-validator';
// import { AbstractCreateCustomer } from '../abstract-create-customer';
// import { encodeFormData, mapCustomerDtoToCustomerCreateFormData } from '../customer-create-form-data';
// import { zipCodeValidator } from '../../validators/zip-code-validator';
@Component({
selector: 'app-create-p4m-customer',
templateUrl: 'create-p4m-customer.component.html',
styleUrls: ['../create-customer.scss', 'create-p4m-customer.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: false,
})
export class CreateP4MCustomerComponent extends AbstractCreateCustomer implements OnInit {
validateAddress = true;
// @Component({
// selector: 'app-create-p4m-customer',
// templateUrl: 'create-p4m-customer.component.html',
// styleUrls: ['../create-customer.scss', 'create-p4m-customer.component.scss'],
// changeDetection: ChangeDetectionStrategy.OnPush,
// standalone: false,
// })
// export class CreateP4MCustomerComponent extends AbstractCreateCustomer implements OnInit {
// validateAddress = true;
validateShippingAddress = true;
// validateShippingAddress = true;
get _customerType() {
return this.activatedRoute.snapshot.data.customerType;
}
// get _customerType() {
// return this.activatedRoute.snapshot.data.customerType;
// }
get customerType() {
return `${this._customerType}-p4m`;
}
// get customerType() {
// return `${this._customerType}-p4m`;
// }
nameRequiredMarks: (keyof NameFormBlockData)[] = ['gender', 'firstName', 'lastName'];
// nameRequiredMarks: (keyof NameFormBlockData)[] = ['gender', 'firstName', 'lastName'];
nameValidationFns: Record<keyof NameFormBlockData, ValidatorFn[]> = {
firstName: [Validators.required],
lastName: [Validators.required],
gender: [Validators.required],
title: [],
};
// nameValidationFns: Record<keyof NameFormBlockData, ValidatorFn[]> = {
// firstName: [Validators.required],
// lastName: [Validators.required],
// gender: [Validators.required],
// title: [],
// };
emailRequiredMark: boolean;
// emailRequiredMark: boolean;
emailValidatorFn: ValidatorFn[];
// emailValidatorFn: ValidatorFn[];
asyncEmailVlaidtorFn: AsyncValidatorFn[];
// asyncEmailVlaidtorFn: AsyncValidatorFn[];
asyncLoyaltyCardValidatorFn: AsyncValidatorFn[];
// asyncLoyaltyCardValidatorFn: AsyncValidatorFn[];
shippingAddressRequiredMarks: (keyof AddressFormBlockData)[] = [
'street',
'streetNumber',
'zipCode',
'city',
'country',
];
// shippingAddressRequiredMarks: (keyof AddressFormBlockData)[] = [
// 'street',
// 'streetNumber',
// 'zipCode',
// 'city',
// 'country',
// ];
shippingAddressValidators: Record<string, ValidatorFn[]> = {
street: [Validators.required],
streetNumber: [Validators.required],
zipCode: [Validators.required, zipCodeValidator()],
city: [Validators.required],
country: [Validators.required],
};
// shippingAddressValidators: Record<string, ValidatorFn[]> = {
// street: [Validators.required],
// streetNumber: [Validators.required],
// zipCode: [Validators.required, zipCodeValidator()],
// city: [Validators.required],
// country: [Validators.required],
// };
addressRequiredMarks: (keyof AddressFormBlockData)[];
// addressRequiredMarks: (keyof AddressFormBlockData)[];
addressValidatorFns: Record<string, ValidatorFn[]>;
// addressValidatorFns: Record<string, ValidatorFn[]>;
@ViewChild(AddressFormBlockComponent, { static: false })
addressFormBlock: AddressFormBlockComponent;
// @ViewChild(AddressFormBlockComponent, { static: false })
// addressFormBlock: AddressFormBlockComponent;
@ViewChild(DeviatingAddressFormBlockComponent, { static: false })
deviatingDeliveryAddressFormBlock: DeviatingAddressFormBlockComponent;
// @ViewChild(DeviatingAddressFormBlockComponent, { static: false })
// deviatingDeliveryAddressFormBlock: DeviatingAddressFormBlockComponent;
agbValidatorFns = [Validators.requiredTrue];
// agbValidatorFns = [Validators.requiredTrue];
birthDateValidatorFns = [];
// birthDateValidatorFns = [];
existingCustomer$: Observable<CustomerInfoDTO | CustomerDTO | null>;
// existingCustomer$: Observable<CustomerInfoDTO | CustomerDTO | null>;
ngOnInit(): void {
super.ngOnInit();
this.initMarksAndValidators();
this.existingCustomer$ = this.customerExists$.pipe(
distinctUntilChanged(),
switchMap((exists) => {
if (exists) {
return this.fetchCustomerInfo();
}
return of(null);
}),
);
// ngOnInit(): void {
// super.ngOnInit();
// this.initMarksAndValidators();
// this.existingCustomer$ = this.customerExists$.pipe(
// distinctUntilChanged(),
// switchMap((exists) => {
// if (exists) {
// return this.fetchCustomerInfo();
// }
// return of(null);
// }),
// );
this.existingCustomer$
.pipe(
takeUntil(this.onDestroy$),
switchMap((info) => {
if (info) {
return this.customerService.getCustomer(info.id, 2).pipe(
map((res) => res.result),
catchError((err) => NEVER),
);
}
return NEVER;
}),
withLatestFrom(this.processId$),
)
.subscribe(([customer, processId]) => {
if (customer) {
this.modal
.open({
content: WebshopCustomnerAlreadyExistsModalComponent,
data: {
customer,
processId,
} as WebshopCustomnerAlreadyExistsModalData,
title: 'Es existiert bereits ein Onlinekonto mit dieser E-Mail-Adresse',
})
.afterClosed$.subscribe(async (result: UiModalResult<boolean>) => {
if (result.data) {
this.navigateToUpdatePage(customer);
} else {
this.formData.email = '';
this.cdr.markForCheck();
}
});
}
});
}
// this.existingCustomer$
// .pipe(
// takeUntil(this.onDestroy$),
// switchMap((info) => {
// if (info) {
// return this.customerService.getCustomer(info.id, 2).pipe(
// map((res) => res.result),
// catchError((err) => NEVER),
// );
// }
// return NEVER;
// }),
// withLatestFrom(this.processId$),
// )
// .subscribe(([customer, processId]) => {
// if (customer) {
// this.modal
// .open({
// content: WebshopCustomnerAlreadyExistsModalComponent,
// data: {
// customer,
// processId,
// } as WebshopCustomnerAlreadyExistsModalData,
// title: 'Es existiert bereits ein Onlinekonto mit dieser E-Mail-Adresse',
// })
// .afterClosed$.subscribe(async (result: UiModalResult<boolean>) => {
// if (result.data) {
// this.navigateToUpdatePage(customer);
// } else {
// this.formData.email = '';
// this.cdr.markForCheck();
// }
// });
// }
// });
// }
async navigateToUpdatePage(customer: CustomerDTO) {
const processId = await this.processId$.pipe(first()).toPromise();
this.router.navigate(['/kunde', processId, 'customer', 'create', 'webshop-p4m', 'update'], {
queryParams: {
formData: encodeFormData({
...mapCustomerDtoToCustomerCreateFormData(customer),
p4m: this.formData.p4m,
}),
},
});
}
// async navigateToUpdatePage(customer: CustomerDTO) {
// const processId = await this.processId$.pipe(first()).toPromise();
// this.router.navigate(['/kunde', processId, 'customer', 'create', 'webshop-p4m', 'update'], {
// queryParams: {
// formData: encodeFormData({
// ...mapCustomerDtoToCustomerCreateFormData(customer),
// p4m: this.formData.p4m,
// }),
// },
// });
// }
initMarksAndValidators() {
this.asyncLoyaltyCardValidatorFn = [this.checkLoyalityCardValidator];
this.birthDateValidatorFns = [Validators.required, this.minBirthDateValidator()];
if (this._customerType === 'webshop') {
this.emailRequiredMark = true;
this.emailValidatorFn = [Validators.required, Validators.email, validateEmail];
this.asyncEmailVlaidtorFn = [this.emailExistsValidator];
this.addressRequiredMarks = this.shippingAddressRequiredMarks;
this.addressValidatorFns = this.shippingAddressValidators;
} else {
this.emailRequiredMark = false;
this.emailValidatorFn = [Validators.email, validateEmail];
}
}
// initMarksAndValidators() {
// this.asyncLoyaltyCardValidatorFn = [this.checkLoyalityCardValidator];
// this.birthDateValidatorFns = [Validators.required, this.minBirthDateValidator()];
// if (this._customerType === 'webshop') {
// this.emailRequiredMark = true;
// this.emailValidatorFn = [Validators.required, Validators.email, validateEmail];
// this.asyncEmailVlaidtorFn = [this.emailExistsValidator];
// this.addressRequiredMarks = this.shippingAddressRequiredMarks;
// this.addressValidatorFns = this.shippingAddressValidators;
// } else {
// this.emailRequiredMark = false;
// this.emailValidatorFn = [Validators.email, validateEmail];
// }
// }
fetchCustomerInfo(): Observable<CustomerDTO | null> {
const email = this.formData.email;
return this.customerService.getOnlineCustomerByEmail(email).pipe(
map((result) => {
if (result) {
return result;
}
return null;
}),
catchError((err) => {
this.modal.open({
content: UiErrorModalComponent,
data: err,
});
return [null];
}),
);
}
// fetchCustomerInfo(): Observable<CustomerDTO | null> {
// const email = this.formData.email;
// return this.customerService.getOnlineCustomerByEmail(email).pipe(
// map((result) => {
// if (result) {
// return result;
// }
// return null;
// }),
// catchError((err) => {
// this.modal.open({
// content: UiErrorModalComponent,
// data: err,
// });
// return [null];
// }),
// );
// }
getInterests(): KeyValueDTOOfStringAndString[] {
const interests: KeyValueDTOOfStringAndString[] = [];
// getInterests(): KeyValueDTOOfStringAndString[] {
// const interests: KeyValueDTOOfStringAndString[] = [];
for (const key in this.formData.interests) {
if (this.formData.interests[key]) {
interests.push({ key, group: 'KUBI_INTERESSEN' });
}
}
// for (const key in this.formData.interests) {
// if (this.formData.interests[key]) {
// interests.push({ key, group: 'KUBI_INTERESSEN' });
// }
// }
return interests;
}
// return interests;
// }
getNewsletter(): KeyValueDTOOfStringAndString | undefined {
if (this.formData.newsletter) {
return { key: 'kubi_newsletter', group: 'KUBI_NEWSLETTER' };
}
}
// getNewsletter(): KeyValueDTOOfStringAndString | undefined {
// if (this.formData.newsletter) {
// return { key: 'kubi_newsletter', group: 'KUBI_NEWSLETTER' };
// }
// }
static MapCustomerInfoDtoToCustomerDto(customerInfoDto: CustomerInfoDTO): CustomerDTO {
return {
address: customerInfoDto.address,
agentComment: customerInfoDto.agentComment,
bonusCard: customerInfoDto.bonusCard,
campaignCode: customerInfoDto.campaignCode,
communicationDetails: customerInfoDto.communicationDetails,
createdInBranch: customerInfoDto.createdInBranch,
customerGroup: customerInfoDto.customerGroup,
customerNumber: customerInfoDto.customerNumber,
customerStatus: customerInfoDto.customerStatus,
customerType: customerInfoDto.customerType,
dateOfBirth: customerInfoDto.dateOfBirth,
features: customerInfoDto.features,
firstName: customerInfoDto.firstName,
lastName: customerInfoDto.lastName,
gender: customerInfoDto.gender,
hasOnlineAccount: customerInfoDto.hasOnlineAccount,
isGuestAccount: customerInfoDto.isGuestAccount,
label: customerInfoDto.label,
notificationChannels: customerInfoDto.notificationChannels,
organisation: customerInfoDto.organisation,
title: customerInfoDto.title,
id: customerInfoDto.id,
pId: customerInfoDto.pId,
};
}
// static MapCustomerInfoDtoToCustomerDto(customerInfoDto: CustomerInfoDTO): CustomerDTO {
// return {
// address: customerInfoDto.address,
// agentComment: customerInfoDto.agentComment,
// bonusCard: customerInfoDto.bonusCard,
// campaignCode: customerInfoDto.campaignCode,
// communicationDetails: customerInfoDto.communicationDetails,
// createdInBranch: customerInfoDto.createdInBranch,
// customerGroup: customerInfoDto.customerGroup,
// customerNumber: customerInfoDto.customerNumber,
// customerStatus: customerInfoDto.customerStatus,
// customerType: customerInfoDto.customerType,
// dateOfBirth: customerInfoDto.dateOfBirth,
// features: customerInfoDto.features,
// firstName: customerInfoDto.firstName,
// lastName: customerInfoDto.lastName,
// gender: customerInfoDto.gender,
// hasOnlineAccount: customerInfoDto.hasOnlineAccount,
// isGuestAccount: customerInfoDto.isGuestAccount,
// label: customerInfoDto.label,
// notificationChannels: customerInfoDto.notificationChannels,
// organisation: customerInfoDto.organisation,
// title: customerInfoDto.title,
// id: customerInfoDto.id,
// pId: customerInfoDto.pId,
// };
// }
async saveCustomer(customer: CustomerDTO): Promise<CustomerDTO> {
const isWebshop = this._customerType === 'webshop';
let res: Result<CustomerDTO>;
// async saveCustomer(customer: CustomerDTO): Promise<CustomerDTO> {
// const isWebshop = this._customerType === 'webshop';
// let res: Result<CustomerDTO>;
const { customerDto, customerInfoDto } = this.formData?._meta ?? {};
// const { customerDto, customerInfoDto } = this.formData?._meta ?? {};
if (customerDto) {
customer = { ...customerDto, ...customer };
} else if (customerInfoDto) {
customer = { ...CreateP4MCustomerComponent.MapCustomerInfoDtoToCustomerDto(customerInfoDto), ...customer };
}
// if (customerDto) {
// customer = { ...customerDto, ...customer };
// } else if (customerInfoDto) {
// customer = { ...CreateP4MCustomerComponent.MapCustomerInfoDtoToCustomerDto(customerInfoDto), ...customer };
// }
const p4mFeature = customer.features?.find((attr) => attr.key === 'p4mUser');
if (p4mFeature) {
p4mFeature.value = this.formData.p4m;
} else {
customer.features.push({
key: 'p4mUser',
value: this.formData.p4m,
});
}
// const p4mFeature = customer.features?.find((attr) => attr.key === 'p4mUser');
// if (p4mFeature) {
// p4mFeature.value = this.formData.p4m;
// } else {
// customer.features.push({
// key: 'p4mUser',
// value: this.formData.p4m,
// });
// }
const interests = this.getInterests();
// const interests = this.getInterests();
if (interests.length > 0) {
customer.features?.push(...interests);
// TODO: Klärung wie Interessen zukünftig gespeichert werden
// await this._loyaltyCardService
// .LoyaltyCardSaveInteressen({
// customerId: res.result.id,
// interessen: this.getInterests(),
// })
// .toPromise();
}
// if (interests.length > 0) {
// customer.features?.push(...interests);
// // TODO: Klärung wie Interessen zukünftig gespeichert werden
// // await this._loyaltyCardService
// // .LoyaltyCardSaveInteressen({
// // customerId: res.result.id,
// // interessen: this.getInterests(),
// // })
// // .toPromise();
// }
const newsletter = this.getNewsletter();
// const newsletter = this.getNewsletter();
if (newsletter) {
customer.features.push(newsletter);
} else {
customer.features = customer.features.filter(
(feature) => feature.key !== 'kubi_newsletter' && feature.group !== 'KUBI_NEWSLETTER',
);
}
// if (newsletter) {
// customer.features.push(newsletter);
// } else {
// customer.features = customer.features.filter(
// (feature) => feature.key !== 'kubi_newsletter' && feature.group !== 'KUBI_NEWSLETTER',
// );
// }
if (isWebshop) {
if (customer.id > 0) {
if (this.formData?._meta?.hasLocalityCard) {
res = await this.customerService.updateStoreP4MToWebshopP4M(customer);
} else {
res = await this.customerService.updateToP4MOnlineCustomer(customer);
}
} else {
res = await this.customerService.createOnlineCustomer(customer).toPromise();
}
} else {
res = await this.customerService.createStoreCustomer(customer).toPromise();
}
// if (isWebshop) {
// if (customer.id > 0) {
// if (this.formData?._meta?.hasLocalityCard) {
// res = await this.customerService.updateStoreP4MToWebshopP4M(customer);
// } else {
// res = await this.customerService.updateToP4MOnlineCustomer(customer);
// }
// } else {
// res = await this.customerService.createOnlineCustomer(customer).toPromise();
// }
// } else {
// res = await this.customerService.createStoreCustomer(customer).toPromise();
// }
return res.result;
}
}
// return res.result;
// }
// }

View File

@@ -1,45 +1,45 @@
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
// import { NgModule } from '@angular/core';
// import { CommonModule } from '@angular/common';
import { CreateP4MCustomerComponent } from './create-p4m-customer.component';
import {
AddressFormBlockModule,
BirthDateFormBlockModule,
InterestsFormBlockModule,
NameFormBlockModule,
OrganisationFormBlockModule,
P4mNumberFormBlockModule,
NewsletterFormBlockModule,
DeviatingAddressFormBlockComponentModule,
AcceptAGBFormBlockModule,
EmailFormBlockModule,
PhoneNumbersFormBlockModule,
} from '../../components/form-blocks';
import { CustomerTypeSelectorModule } from '../../components/customer-type-selector';
import { UiSpinnerModule } from '@ui/spinner';
import { UiIconModule } from '@ui/icon';
import { RouterModule } from '@angular/router';
// import { CreateP4MCustomerComponent } from './create-p4m-customer.component';
// import {
// AddressFormBlockModule,
// BirthDateFormBlockModule,
// InterestsFormBlockModule,
// NameFormBlockModule,
// OrganisationFormBlockModule,
// P4mNumberFormBlockModule,
// NewsletterFormBlockModule,
// DeviatingAddressFormBlockComponentModule,
// AcceptAGBFormBlockModule,
// EmailFormBlockModule,
// PhoneNumbersFormBlockModule,
// } from '../../components/form-blocks';
// import { CustomerTypeSelectorModule } from '../../components/customer-type-selector';
// import { UiSpinnerModule } from '@ui/spinner';
// import { UiIconModule } from '@ui/icon';
// import { RouterModule } from '@angular/router';
@NgModule({
imports: [
CommonModule,
CustomerTypeSelectorModule,
AddressFormBlockModule,
BirthDateFormBlockModule,
InterestsFormBlockModule,
NameFormBlockModule,
OrganisationFormBlockModule,
P4mNumberFormBlockModule,
NewsletterFormBlockModule,
DeviatingAddressFormBlockComponentModule,
AcceptAGBFormBlockModule,
EmailFormBlockModule,
PhoneNumbersFormBlockModule,
UiSpinnerModule,
UiIconModule,
RouterModule,
],
exports: [CreateP4MCustomerComponent],
declarations: [CreateP4MCustomerComponent],
})
export class CreateP4MCustomerModule {}
// @NgModule({
// imports: [
// CommonModule,
// CustomerTypeSelectorModule,
// AddressFormBlockModule,
// BirthDateFormBlockModule,
// InterestsFormBlockModule,
// NameFormBlockModule,
// OrganisationFormBlockModule,
// P4mNumberFormBlockModule,
// NewsletterFormBlockModule,
// DeviatingAddressFormBlockComponentModule,
// AcceptAGBFormBlockModule,
// EmailFormBlockModule,
// PhoneNumbersFormBlockModule,
// UiSpinnerModule,
// UiIconModule,
// RouterModule,
// ],
// exports: [CreateP4MCustomerComponent],
// declarations: [CreateP4MCustomerComponent],
// })
// export class CreateP4MCustomerModule {}

View File

@@ -1,2 +1,2 @@
export * from './create-p4m-customer.component';
export * from './create-p4m-customer.module';
// export * from './create-p4m-customer.component';
// export * from './create-p4m-customer.module';

View File

@@ -1,6 +1,6 @@
import { Component, ChangeDetectionStrategy, ViewChild } from '@angular/core';
import { ValidatorFn, Validators } from '@angular/forms';
import { CustomerDTO } from '@generated/swagger/crm-api';
import { CustomerDTO, CustomerInfoDTO } from '@generated/swagger/crm-api';
import { map } from 'rxjs/operators';
import {
AddressFormBlockComponent,
@@ -10,13 +10,16 @@ import {
import { NameFormBlockData } from '../../components/form-blocks/name/name-form-block-data';
import { validateEmail } from '../../validators/email-validator';
import { AbstractCreateCustomer } from '../abstract-create-customer';
import { CreateP4MCustomerComponent } from '../create-p4m-customer';
// import { CreateP4MCustomerComponent } from '../create-p4m-customer';
import { zipCodeValidator } from '../../validators/zip-code-validator';
@Component({
selector: 'app-create-webshop-customer',
templateUrl: 'create-webshop-customer.component.html',
styleUrls: ['../create-customer.scss', 'create-webshop-customer.component.scss'],
styleUrls: [
'../create-customer.scss',
'create-webshop-customer.component.scss',
],
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: false,
})
@@ -26,7 +29,11 @@ export class CreateWebshopCustomerComponent extends AbstractCreateCustomer {
validateAddress = true;
validateShippingAddress = true;
nameRequiredMarks: (keyof NameFormBlockData)[] = ['gender', 'firstName', 'lastName'];
nameRequiredMarks: (keyof NameFormBlockData)[] = [
'gender',
'firstName',
'lastName',
];
nameValidationFns: Record<keyof NameFormBlockData, ValidatorFn[]> = {
firstName: [Validators.required],
@@ -35,7 +42,13 @@ export class CreateWebshopCustomerComponent extends AbstractCreateCustomer {
title: [],
};
addressRequiredMarks: (keyof AddressFormBlockData)[] = ['street', 'streetNumber', 'zipCode', 'city', 'country'];
addressRequiredMarks: (keyof AddressFormBlockData)[] = [
'street',
'streetNumber',
'zipCode',
'city',
'country',
];
addressValidators: Record<string, ValidatorFn[]> = {
street: [Validators.required],
@@ -68,7 +81,11 @@ export class CreateWebshopCustomerComponent extends AbstractCreateCustomer {
if (customerDto) {
customer = { ...customerDto, ...customer };
} else if (customerInfoDto) {
customer = { ...CreateP4MCustomerComponent.MapCustomerInfoDtoToCustomerDto(customerInfoDto), ...customer };
customer = {
// ...CreateP4MCustomerComponent.MapCustomerInfoDtoToCustomerDto(customerInfoDto),
...this.mapCustomerInfoDtoToCustomerDto(customerInfoDto),
...customer,
};
}
const res = await this.customerService.updateToOnlineCustomer(customer);
@@ -80,4 +97,34 @@ export class CreateWebshopCustomerComponent extends AbstractCreateCustomer {
.toPromise();
}
}
mapCustomerInfoDtoToCustomerDto(
customerInfoDto: CustomerInfoDTO,
): CustomerDTO {
return {
address: customerInfoDto.address,
agentComment: customerInfoDto.agentComment,
bonusCard: customerInfoDto.bonusCard,
campaignCode: customerInfoDto.campaignCode,
communicationDetails: customerInfoDto.communicationDetails,
createdInBranch: customerInfoDto.createdInBranch,
customerGroup: customerInfoDto.customerGroup,
customerNumber: customerInfoDto.customerNumber,
customerStatus: customerInfoDto.customerStatus,
customerType: customerInfoDto.customerType,
dateOfBirth: customerInfoDto.dateOfBirth,
features: customerInfoDto.features,
firstName: customerInfoDto.firstName,
lastName: customerInfoDto.lastName,
gender: customerInfoDto.gender,
hasOnlineAccount: customerInfoDto.hasOnlineAccount,
isGuestAccount: customerInfoDto.isGuestAccount,
label: customerInfoDto.label,
notificationChannels: customerInfoDto.notificationChannels,
organisation: customerInfoDto.organisation,
title: customerInfoDto.title,
id: customerInfoDto.id,
pId: customerInfoDto.pId,
};
}
}

View File

@@ -1,7 +1,7 @@
import { CustomerDTO, Gender } from '@generated/swagger/crm-api';
export interface CreateCustomerQueryParams {
p4mNumber?: string;
// p4mNumber?: string;
customerId?: number;
gender?: Gender;
title?: string;

View File

@@ -1,6 +1,6 @@
export * from './create-b2b-customer';
export * from './create-guest-customer';
export * from './create-p4m-customer';
// export * from './create-p4m-customer';
export * from './create-store-customer';
export * from './create-webshop-customer';
export * from './defs';

View File

@@ -1,4 +1,4 @@
@if (formData$ | async; as data) {
<!-- @if (formData$ | async; as data) {
<form (keydown.enter)="$event.preventDefault()">
<h1 class="title flex flex-row items-center justify-center">Kundenkartendaten erfasen</h1>
<p class="description">Bitte erfassen Sie die Kundenkarte</p>
@@ -106,4 +106,4 @@
</button>
</div>
</form>
}
} -->

View File

@@ -1,156 +1,156 @@
import { Component, ChangeDetectionStrategy, OnInit } from '@angular/core';
import { AsyncValidatorFn, ValidatorFn, Validators } from '@angular/forms';
import { Result } from '@domain/defs';
import { CustomerDTO, KeyValueDTOOfStringAndString, PayerDTO } from '@generated/swagger/crm-api';
import { AddressFormBlockData } from '../../components/form-blocks';
import { NameFormBlockData } from '../../components/form-blocks/name/name-form-block-data';
import { AbstractCreateCustomer } from '../abstract-create-customer';
import { CreateP4MCustomerComponent } from '../create-p4m-customer';
// import { Component, ChangeDetectionStrategy, OnInit } from '@angular/core';
// import { AsyncValidatorFn, ValidatorFn, Validators } from '@angular/forms';
// import { Result } from '@domain/defs';
// import { CustomerDTO, KeyValueDTOOfStringAndString, PayerDTO } from '@generated/swagger/crm-api';
// import { AddressFormBlockData } from '../../components/form-blocks';
// import { NameFormBlockData } from '../../components/form-blocks/name/name-form-block-data';
// import { AbstractCreateCustomer } from '../abstract-create-customer';
// import { CreateP4MCustomerComponent } from '../create-p4m-customer';
@Component({
selector: 'page-update-p4m-webshop-customer',
templateUrl: 'update-p4m-webshop-customer.component.html',
styleUrls: ['../create-customer.scss', 'update-p4m-webshop-customer.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: false,
})
export class UpdateP4MWebshopCustomerComponent extends AbstractCreateCustomer implements OnInit {
customerType = 'webshop-p4m/update';
// @Component({
// selector: 'page-update-p4m-webshop-customer',
// templateUrl: 'update-p4m-webshop-customer.component.html',
// styleUrls: ['../create-customer.scss', 'update-p4m-webshop-customer.component.scss'],
// changeDetection: ChangeDetectionStrategy.OnPush,
// standalone: false,
// })
// export class UpdateP4MWebshopCustomerComponent extends AbstractCreateCustomer implements OnInit {
// customerType = 'webshop-p4m/update';
validateAddress = true;
// validateAddress = true;
validateShippingAddress = true;
// validateShippingAddress = true;
agbValidatorFns = [Validators.requiredTrue];
// agbValidatorFns = [Validators.requiredTrue];
birthDateValidatorFns = [Validators.required, this.minBirthDateValidator()];
// birthDateValidatorFns = [Validators.required, this.minBirthDateValidator()];
nameRequiredMarks: (keyof NameFormBlockData)[] = ['gender', 'firstName', 'lastName'];
// nameRequiredMarks: (keyof NameFormBlockData)[] = ['gender', 'firstName', 'lastName'];
nameValidationFns: Record<keyof NameFormBlockData, ValidatorFn[]> = {
firstName: [Validators.required],
lastName: [Validators.required],
gender: [Validators.required],
title: [],
};
// nameValidationFns: Record<keyof NameFormBlockData, ValidatorFn[]> = {
// firstName: [Validators.required],
// lastName: [Validators.required],
// gender: [Validators.required],
// title: [],
// };
addressRequiredMarks: (keyof AddressFormBlockData)[] = ['street', 'streetNumber', 'zipCode', 'city', 'country'];
// addressRequiredMarks: (keyof AddressFormBlockData)[] = ['street', 'streetNumber', 'zipCode', 'city', 'country'];
addressValidatorFns: Record<string, ValidatorFn[]> = {
street: [Validators.required],
streetNumber: [Validators.required],
zipCode: [Validators.required],
city: [Validators.required],
country: [Validators.required],
};
// addressValidatorFns: Record<string, ValidatorFn[]> = {
// street: [Validators.required],
// streetNumber: [Validators.required],
// zipCode: [Validators.required],
// city: [Validators.required],
// country: [Validators.required],
// };
asyncLoyaltyCardValidatorFn: AsyncValidatorFn[] = [this.checkLoyalityCardValidator];
// asyncLoyaltyCardValidatorFn: AsyncValidatorFn[] = [this.checkLoyalityCardValidator];
get billingAddress(): PayerDTO | undefined {
const payers = this.formData?._meta?.customerDto?.payers;
// get billingAddress(): PayerDTO | undefined {
// const payers = this.formData?._meta?.customerDto?.payers;
if (!payers || payers.length === 0) {
return undefined;
}
// if (!payers || payers.length === 0) {
// return undefined;
// }
// the default payer is the payer with the latest isDefault(Date) value
const defaultPayer = payers.reduce((prev, curr) =>
new Date(prev.isDefault) > new Date(curr.isDefault) ? prev : curr,
);
// // the default payer is the payer with the latest isDefault(Date) value
// const defaultPayer = payers.reduce((prev, curr) =>
// new Date(prev.isDefault) > new Date(curr.isDefault) ? prev : curr,
// );
return defaultPayer.payer.data;
}
// return defaultPayer.payer.data;
// }
get shippingAddress() {
const shippingAddresses = this.formData?._meta?.customerDto?.shippingAddresses;
// get shippingAddress() {
// const shippingAddresses = this.formData?._meta?.customerDto?.shippingAddresses;
if (!shippingAddresses || shippingAddresses.length === 0) {
return undefined;
}
// if (!shippingAddresses || shippingAddresses.length === 0) {
// return undefined;
// }
// the default shipping address is the shipping address with the latest isDefault(Date) value
const defaultShippingAddress = shippingAddresses.reduce((prev, curr) =>
new Date(prev.data.isDefault) > new Date(curr.data.isDefault) ? prev : curr,
);
// // the default shipping address is the shipping address with the latest isDefault(Date) value
// const defaultShippingAddress = shippingAddresses.reduce((prev, curr) =>
// new Date(prev.data.isDefault) > new Date(curr.data.isDefault) ? prev : curr,
// );
return defaultShippingAddress.data;
}
// return defaultShippingAddress.data;
// }
ngOnInit() {
super.ngOnInit();
}
// ngOnInit() {
// super.ngOnInit();
// }
getInterests(): KeyValueDTOOfStringAndString[] {
const interests: KeyValueDTOOfStringAndString[] = [];
// getInterests(): KeyValueDTOOfStringAndString[] {
// const interests: KeyValueDTOOfStringAndString[] = [];
for (const key in this.formData.interests) {
if (this.formData.interests[key]) {
interests.push({ key, group: 'KUBI_INTERESSEN' });
}
}
// for (const key in this.formData.interests) {
// if (this.formData.interests[key]) {
// interests.push({ key, group: 'KUBI_INTERESSEN' });
// }
// }
return interests;
}
// return interests;
// }
getNewsletter(): KeyValueDTOOfStringAndString | undefined {
if (this.formData.newsletter) {
return { key: 'kubi_newsletter', group: 'KUBI_NEWSLETTER' };
}
}
// getNewsletter(): KeyValueDTOOfStringAndString | undefined {
// if (this.formData.newsletter) {
// return { key: 'kubi_newsletter', group: 'KUBI_NEWSLETTER' };
// }
// }
async saveCustomer(customer: CustomerDTO): Promise<CustomerDTO> {
let res: Result<CustomerDTO>;
// async saveCustomer(customer: CustomerDTO): Promise<CustomerDTO> {
// let res: Result<CustomerDTO>;
const { customerDto, customerInfoDto } = this.formData?._meta ?? {};
// const { customerDto, customerInfoDto } = this.formData?._meta ?? {};
if (customerDto) {
customer = { ...customerDto, shippingAddresses: [], payers: [], ...customer };
// if (customerDto) {
// customer = { ...customerDto, shippingAddresses: [], payers: [], ...customer };
if (customerDto.shippingAddresses?.length) {
customer.shippingAddresses.unshift(...customerDto.shippingAddresses);
}
if (customerDto.payers?.length) {
customer.payers.unshift(...customerDto.payers);
}
} else if (customerInfoDto) {
customer = { ...CreateP4MCustomerComponent.MapCustomerInfoDtoToCustomerDto(customerInfoDto), ...customer };
}
// if (customerDto.shippingAddresses?.length) {
// customer.shippingAddresses.unshift(...customerDto.shippingAddresses);
// }
// if (customerDto.payers?.length) {
// customer.payers.unshift(...customerDto.payers);
// }
// } else if (customerInfoDto) {
// customer = { ...CreateP4MCustomerComponent.MapCustomerInfoDtoToCustomerDto(customerInfoDto), ...customer };
// }
const p4mFeature = customer.features?.find((attr) => attr.key === 'p4mUser');
if (p4mFeature) {
p4mFeature.value = this.formData.p4m;
} else {
customer.features.push({
key: 'p4mUser',
value: this.formData.p4m,
});
}
// const p4mFeature = customer.features?.find((attr) => attr.key === 'p4mUser');
// if (p4mFeature) {
// p4mFeature.value = this.formData.p4m;
// } else {
// customer.features.push({
// key: 'p4mUser',
// value: this.formData.p4m,
// });
// }
const interests = this.getInterests();
// const interests = this.getInterests();
if (interests.length > 0) {
customer.features?.push(...interests);
// TODO: Klärung wie Interessen zukünftig gespeichert werden
// await this._loyaltyCardService
// .LoyaltyCardSaveInteressen({
// customerId: res.result.id,
// interessen: this.getInterests(),
// })
// .toPromise();
}
// if (interests.length > 0) {
// customer.features?.push(...interests);
// // TODO: Klärung wie Interessen zukünftig gespeichert werden
// // await this._loyaltyCardService
// // .LoyaltyCardSaveInteressen({
// // customerId: res.result.id,
// // interessen: this.getInterests(),
// // })
// // .toPromise();
// }
const newsletter = this.getNewsletter();
// const newsletter = this.getNewsletter();
if (newsletter) {
customer.features.push(newsletter);
} else {
customer.features = customer.features.filter(
(feature) => feature.key !== 'kubi_newsletter' && feature.group !== 'KUBI_NEWSLETTER',
);
}
// if (newsletter) {
// customer.features.push(newsletter);
// } else {
// customer.features = customer.features.filter(
// (feature) => feature.key !== 'kubi_newsletter' && feature.group !== 'KUBI_NEWSLETTER',
// );
// }
res = await this.customerService.updateToP4MOnlineCustomer(customer);
// res = await this.customerService.updateToP4MOnlineCustomer(customer);
return res.result;
}
}
// return res.result;
// }
// }

View File

@@ -1,48 +1,48 @@
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
// import { NgModule } from '@angular/core';
// import { CommonModule } from '@angular/common';
import { UpdateP4MWebshopCustomerComponent } from './update-p4m-webshop-customer.component';
// import { UpdateP4MWebshopCustomerComponent } from './update-p4m-webshop-customer.component';
import {
AddressFormBlockModule,
BirthDateFormBlockModule,
InterestsFormBlockModule,
NameFormBlockModule,
OrganisationFormBlockModule,
P4mNumberFormBlockModule,
NewsletterFormBlockModule,
DeviatingAddressFormBlockComponentModule,
AcceptAGBFormBlockModule,
EmailFormBlockModule,
PhoneNumbersFormBlockModule,
} from '../../components/form-blocks';
import { UiFormControlModule } from '@ui/form-control';
import { UiInputModule } from '@ui/input';
import { CustomerPipesModule } from '@shared/pipes/customer';
import { CustomerTypeSelectorModule } from '../../components/customer-type-selector';
import { UiSpinnerModule } from '@ui/spinner';
// import {
// AddressFormBlockModule,
// BirthDateFormBlockModule,
// InterestsFormBlockModule,
// NameFormBlockModule,
// OrganisationFormBlockModule,
// P4mNumberFormBlockModule,
// NewsletterFormBlockModule,
// DeviatingAddressFormBlockComponentModule,
// AcceptAGBFormBlockModule,
// EmailFormBlockModule,
// PhoneNumbersFormBlockModule,
// } from '../../components/form-blocks';
// import { UiFormControlModule } from '@ui/form-control';
// import { UiInputModule } from '@ui/input';
// import { CustomerPipesModule } from '@shared/pipes/customer';
// import { CustomerTypeSelectorModule } from '../../components/customer-type-selector';
// import { UiSpinnerModule } from '@ui/spinner';
@NgModule({
imports: [
CommonModule,
CustomerTypeSelectorModule,
AddressFormBlockModule,
BirthDateFormBlockModule,
InterestsFormBlockModule,
NameFormBlockModule,
OrganisationFormBlockModule,
P4mNumberFormBlockModule,
NewsletterFormBlockModule,
DeviatingAddressFormBlockComponentModule,
AcceptAGBFormBlockModule,
EmailFormBlockModule,
PhoneNumbersFormBlockModule,
UiFormControlModule,
UiInputModule,
CustomerPipesModule,
UiSpinnerModule,
],
exports: [UpdateP4MWebshopCustomerComponent],
declarations: [UpdateP4MWebshopCustomerComponent],
})
export class UpdateP4MWebshopCustomerModule {}
// @NgModule({
// imports: [
// CommonModule,
// CustomerTypeSelectorModule,
// AddressFormBlockModule,
// BirthDateFormBlockModule,
// InterestsFormBlockModule,
// NameFormBlockModule,
// OrganisationFormBlockModule,
// P4mNumberFormBlockModule,
// NewsletterFormBlockModule,
// DeviatingAddressFormBlockComponentModule,
// AcceptAGBFormBlockModule,
// EmailFormBlockModule,
// PhoneNumbersFormBlockModule,
// UiFormControlModule,
// UiInputModule,
// CustomerPipesModule,
// UiSpinnerModule,
// ],
// exports: [UpdateP4MWebshopCustomerComponent],
// declarations: [UpdateP4MWebshopCustomerComponent],
// })
// export class UpdateP4MWebshopCustomerModule {}

View File

@@ -1,15 +1,33 @@
import { Component, ChangeDetectionStrategy, OnInit, OnDestroy, inject, effect, untracked } from '@angular/core';
import {
Component,
ChangeDetectionStrategy,
OnInit,
OnDestroy,
inject,
effect,
untracked,
} from '@angular/core';
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
import { BehaviorSubject, Subject, Subscription, fromEvent } from 'rxjs';
import {
BehaviorSubject,
Subject,
Subscription,
firstValueFrom,
fromEvent,
} from 'rxjs';
import { CustomerSearchStore } from './store/customer-search.store';
import { provideComponentStore } from '@ngrx/component-store';
import { Breadcrumb, BreadcrumbService } from '@core/breadcrumb';
import { delay, filter, first, switchMap, takeUntil } from 'rxjs/operators';
import { CustomerCreateNavigation, CustomerSearchNavigation } from '@shared/services/navigation';
import {
CustomerCreateNavigation,
CustomerSearchNavigation,
} from '@shared/services/navigation';
import { CustomerSearchMainAutocompleteProvider } from './providers/customer-search-main-autocomplete.provider';
import { FilterAutocompleteProvider } from '@shared/components/filter';
import { toSignal } from '@angular/core/rxjs-interop';
import { provideCancelSearchSubject } from '@shared/services/cancel-subject';
import { injectFeedbackErrorDialog } from '@isa/ui/dialog';
@Component({
selector: 'page-customer-search',
@@ -28,6 +46,7 @@ import { provideCancelSearchSubject } from '@shared/services/cancel-subject';
standalone: false,
})
export class CustomerSearchComponent implements OnInit, OnDestroy {
#errorFeedbackDialog = injectFeedbackErrorDialog();
private _store = inject(CustomerSearchStore);
private _activatedRoute = inject(ActivatedRoute);
private _router = inject(Router);
@@ -37,7 +56,11 @@ export class CustomerSearchComponent implements OnInit, OnDestroy {
private searchStore = inject(CustomerSearchStore);
keyEscPressed = toSignal(fromEvent(document, 'keydown').pipe(filter((e: KeyboardEvent) => e.key === 'Escape')));
keyEscPressed = toSignal(
fromEvent(document, 'keydown').pipe(
filter((e: KeyboardEvent) => e.key === 'Escape'),
),
);
get breadcrumb() {
let breadcrumb: string;
@@ -53,7 +76,9 @@ export class CustomerSearchComponent implements OnInit, OnDestroy {
private _breadcrumbs$ = this._store.processId$.pipe(
filter((id) => !!id),
switchMap((id) => this._breadcrumbService.getBreadcrumbsByKeyAndTag$(id, 'customer')),
switchMap((id) =>
this._breadcrumbService.getBreadcrumbsByKeyAndTag$(id, 'customer'),
),
);
side$ = new BehaviorSubject<string | undefined>(undefined);
@@ -97,53 +122,77 @@ export class CustomerSearchComponent implements OnInit, OnDestroy {
this.checkDetailsBreadcrumb();
});
this._eventsSubscription = this._router.events.pipe(takeUntil(this._onDestroy$)).subscribe((event) => {
if (event instanceof NavigationEnd) {
this.checkAndUpdateProcessId();
this.checkAndUpdateSide();
this.checkAndUpdateCustomerId();
this.checkBreadcrumbs();
}
});
this._store.customerListResponse$
this._eventsSubscription = this._router.events
.pipe(takeUntil(this._onDestroy$))
.subscribe(async ([response, filter, processId, restored, skipNavigation]) => {
if (this._store.processId === processId) {
if (skipNavigation) {
return;
}
if (response.hits === 1) {
// Navigate to details page
const customer = response.result[0];
if (customer.id < 0) {
// navigate to create customer
const route = this._createNavigation.upgradeCustomerRoute({ processId, customerInfo: customer });
await this._router.navigate(route.path, { queryParams: route.queryParams });
return;
} else {
const route = this._navigation.detailsRoute({ processId, customerId: customer.id });
await this._router.navigate(route.path, { queryParams: filter.getQueryParams() });
}
} else if (response.hits > 1) {
const route = this._navigation.listRoute({ processId, filter });
if (
(['details'].includes(this.breadcrumb) &&
response?.result?.some((c) => c.id === this._store.customerId)) ||
restored
) {
await this._router.navigate([], { queryParams: route.queryParams });
} else {
await this._router.navigate(route.path, { queryParams: route.queryParams });
}
}
.subscribe((event) => {
if (event instanceof NavigationEnd) {
this.checkAndUpdateProcessId();
this.checkAndUpdateSide();
this.checkAndUpdateCustomerId();
this.checkBreadcrumbs();
}
});
this._store.customerListResponse$
.pipe(takeUntil(this._onDestroy$))
.subscribe(
async ([response, filter, processId, restored, skipNavigation]) => {
if (this._store.processId === processId) {
if (skipNavigation) {
return;
}
if (response.hits === 1) {
// Navigate to details page
const customer = response.result[0];
if (customer.id < 0) {
// #5375 - Zusätzlich soll bei Kunden bei denen ein Upgrade möglich ist ein Dialog angezeigt werden, dass Kundenneuanlage mit Kundenkarte nicht möglich ist
await firstValueFrom(
this.#errorFeedbackDialog({
data: {
errorMessage:
'Kundenneuanlage mit Kundenkarte nicht möglich',
},
}).closed,
);
// navigate to create customer
// const route = this._createNavigation.upgradeCustomerRoute({ processId, customerInfo: customer });
// await this._router.navigate(route.path, { queryParams: route.queryParams });
return;
} else {
const route = this._navigation.detailsRoute({
processId,
customerId: customer.id,
});
await this._router.navigate(route.path, {
queryParams: filter.getQueryParams(),
});
}
} else if (response.hits > 1) {
const route = this._navigation.listRoute({ processId, filter });
if (
(['details'].includes(this.breadcrumb) &&
response?.result?.some(
(c) => c.id === this._store.customerId,
)) ||
restored
) {
await this._router.navigate([], {
queryParams: route.queryParams,
});
} else {
await this._router.navigate(route.path, {
queryParams: route.queryParams,
});
}
}
this.checkBreadcrumbs();
}
},
);
}
ngOnDestroy(): void {
@@ -169,7 +218,11 @@ export class CustomerSearchComponent implements OnInit, OnDestroy {
this._store.setProcessId(processId);
this._store.reset(this._activatedRoute.snapshot.queryParams);
if (!['main', 'filter'].some((s) => s === this.breadcrumb)) {
const skipNavigation = ['orders', 'order-details', 'order-details-history'].includes(this.breadcrumb);
const skipNavigation = [
'orders',
'order-details',
'order-details-history',
].includes(this.breadcrumb);
this._store.search({ skipNavigation });
}
}
@@ -229,7 +282,9 @@ export class CustomerSearchComponent implements OnInit, OnDestroy {
const mainBreadcrumb = await this.getMainBreadcrumb();
if (!mainBreadcrumb) {
const navigation = this._navigation.defaultRoute({ processId: this._store.processId });
const navigation = this._navigation.defaultRoute({
processId: this._store.processId,
});
const breadcrumb: Breadcrumb = {
key: this._store.processId,
tags: ['customer', 'search', 'main'],
@@ -242,14 +297,19 @@ export class CustomerSearchComponent implements OnInit, OnDestroy {
this._breadcrumbService.addBreadcrumb(breadcrumb);
} else {
this._breadcrumbService.patchBreadcrumb(mainBreadcrumb.id, {
params: { ...this.snapshot.queryParams, ...(mainBreadcrumb.params ?? {}) },
params: {
...this.snapshot.queryParams,
...(mainBreadcrumb.params ?? {}),
},
});
}
}
async getCreateCustomerBreadcrumb(): Promise<Breadcrumb | undefined> {
const breadcrumbs = await this.getBreadcrumbs();
return breadcrumbs.find((b) => b.tags.includes('create') && b.tags.includes('customer'));
return breadcrumbs.find(
(b) => b.tags.includes('create') && b.tags.includes('customer'),
);
}
async checkCreateCustomerBreadcrumb() {
@@ -262,7 +322,9 @@ export class CustomerSearchComponent implements OnInit, OnDestroy {
async getSearchBreadcrumb(): Promise<Breadcrumb | undefined> {
const breadcrumbs = await this.getBreadcrumbs();
return breadcrumbs.find((b) => b.tags.includes('list') && b.tags.includes('search'));
return breadcrumbs.find(
(b) => b.tags.includes('list') && b.tags.includes('search'),
);
}
async checkSearchBreadcrumb() {
@@ -288,7 +350,9 @@ export class CustomerSearchComponent implements OnInit, OnDestroy {
const name = this._store.queryParams?.main_qs || 'Suche';
if (!searchBreadcrumb) {
const navigation = this._navigation.listRoute({ processId: this._store.processId });
const navigation = this._navigation.listRoute({
processId: this._store.processId,
});
const breadcrumb: Breadcrumb = {
key: this._store.processId,
tags: ['customer', 'search', 'list'],
@@ -300,7 +364,10 @@ export class CustomerSearchComponent implements OnInit, OnDestroy {
this._breadcrumbService.addBreadcrumb(breadcrumb);
} else {
this._breadcrumbService.patchBreadcrumb(searchBreadcrumb.id, { params: this.snapshot.queryParams, name });
this._breadcrumbService.patchBreadcrumb(searchBreadcrumb.id, {
params: this.snapshot.queryParams,
name,
});
}
} else {
if (searchBreadcrumb) {
@@ -311,7 +378,9 @@ export class CustomerSearchComponent implements OnInit, OnDestroy {
async getDetailsBreadcrumb(): Promise<Breadcrumb | undefined> {
const breadcrumbs = await this.getBreadcrumbs();
return breadcrumbs.find((b) => b.tags.includes('details') && b.tags.includes('search'));
return breadcrumbs.find(
(b) => b.tags.includes('details') && b.tags.includes('search'),
);
}
async checkDetailsBreadcrumb() {
@@ -333,7 +402,8 @@ export class CustomerSearchComponent implements OnInit, OnDestroy {
].includes(this.breadcrumb)
) {
const customer = this._store.customer;
const fullName = `${customer?.firstName ?? ''} ${customer?.lastName ?? ''}`.trim();
const fullName =
`${customer?.firstName ?? ''} ${customer?.lastName ?? ''}`.trim();
if (!detailsBreadcrumb) {
const navigation = this._navigation.detailsRoute({
@@ -515,7 +585,10 @@ export class CustomerSearchComponent implements OnInit, OnDestroy {
async checkOrderDetailsBreadcrumb() {
const orderDetailsBreadcrumb = await this.getOrderDetailsBreadcrumb();
if (this.breadcrumb === 'order-details' || this.breadcrumb === 'order-details-history') {
if (
this.breadcrumb === 'order-details' ||
this.breadcrumb === 'order-details-history'
) {
if (!orderDetailsBreadcrumb) {
const navigation = this._navigation.orderDetialsRoute({
processId: this._store.processId,
@@ -546,7 +619,8 @@ export class CustomerSearchComponent implements OnInit, OnDestroy {
}
async checkOrderDetailsHistoryBreadcrumb() {
const orderDetailsHistoryBreadcrumb = await this.getOrderDetailsHistoryBreadcrumb();
const orderDetailsHistoryBreadcrumb =
await this.getOrderDetailsHistoryBreadcrumb();
if (this.breadcrumb === 'order-details-history') {
if (!orderDetailsHistoryBreadcrumb) {
@@ -569,7 +643,9 @@ export class CustomerSearchComponent implements OnInit, OnDestroy {
this._breadcrumbService.addBreadcrumb(breadcrumb);
}
} else if (orderDetailsHistoryBreadcrumb) {
this._breadcrumbService.removeBreadcrumb(orderDetailsHistoryBreadcrumb.id);
this._breadcrumbService.removeBreadcrumb(
orderDetailsHistoryBreadcrumb.id,
);
}
}

View File

@@ -1,5 +1,10 @@
import { inject, Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Params, Router, RouterStateSnapshot } from '@angular/router';
import {
ActivatedRouteSnapshot,
Params,
Router,
RouterStateSnapshot,
} from '@angular/router';
import { DomainCheckoutService } from '@domain/checkout';
import { CustomerCreateFormData, decodeFormData } from '../create-customer';
import { CustomerCreateNavigation } from '@shared/services/navigation';
@@ -9,7 +14,10 @@ export class CustomerCreateGuard {
private checkoutService = inject(DomainCheckoutService);
private customerCreateNavigation = inject(CustomerCreateNavigation);
async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
async canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot,
): Promise<boolean> {
// exit with true if canActivateChild will be called
if (route.firstChild) {
return true;
@@ -19,10 +27,15 @@ export class CustomerCreateGuard {
const processId = this.getProcessId(route);
const formData = this.getFormData(route);
const canActivateCustomerType = await this.setableCustomerTypes(processId, formData);
const canActivateCustomerType = await this.setableCustomerTypes(
processId,
formData,
);
if (canActivateCustomerType[customerType] !== true) {
customerType = Object.keys(canActivateCustomerType).find((key) => canActivateCustomerType[key]);
customerType = Object.keys(canActivateCustomerType).find(
(key) => canActivateCustomerType[key],
);
}
await this.navigate(processId, customerType, route.queryParams);
@@ -30,9 +43,14 @@ export class CustomerCreateGuard {
return true;
}
async canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
async canActivateChild(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot,
): Promise<boolean> {
const processId = this.getProcessId(route);
const customerType = route.routeConfig.path?.replace('create/', '')?.replace('/update', '');
const customerType = route.routeConfig.path
?.replace('create/', '')
?.replace('/update', '');
if (customerType === 'create-customer-main') {
return true;
@@ -40,29 +58,39 @@ export class CustomerCreateGuard {
const formData = this.getFormData(route);
const canActivateCustomerType = await this.setableCustomerTypes(processId, formData);
const canActivateCustomerType = await this.setableCustomerTypes(
processId,
formData,
);
if (canActivateCustomerType[customerType]) {
return true;
}
const activatableCustomerType = Object.keys(canActivateCustomerType)?.find((key) => canActivateCustomerType[key]);
const activatableCustomerType = Object.keys(canActivateCustomerType)?.find(
(key) => canActivateCustomerType[key],
);
await this.navigate(processId, activatableCustomerType, route.queryParams);
return false;
}
async setableCustomerTypes(processId: number, formData: CustomerCreateFormData): Promise<Record<string, boolean>> {
const res = await this.checkoutService.getSetableCustomerTypes(processId).toPromise();
async setableCustomerTypes(
processId: number,
formData: CustomerCreateFormData,
): Promise<Record<string, boolean>> {
const res = await this.checkoutService
.getSetableCustomerTypes(processId)
.toPromise();
if (res.store) {
res['store-p4m'] = true;
}
// if (res.store) {
// res['store-p4m'] = true;
// }
if (res.webshop) {
res['webshop-p4m'] = true;
}
// if (res.webshop) {
// res['webshop-p4m'] = true;
// }
if (formData?._meta) {
const customerType = formData._meta.customerType;
@@ -107,7 +135,11 @@ export class CustomerCreateGuard {
return {};
}
navigate(processId: number, customerType: string, queryParams: Params): Promise<boolean> {
navigate(
processId: number,
customerType: string,
queryParams: Params,
): Promise<boolean> {
const path = this.customerCreateNavigation.createCustomerRoute({
customerType,
processId,

View File

@@ -31,7 +31,9 @@ export class CantAddCustomerToCartModalComponent {
get option() {
return (
this.ref.data.upgradeableTo?.options.values.find((upgradeOption) =>
this.ref.data.required.options.values.some((requiredOption) => upgradeOption.key === requiredOption.key),
this.ref.data.required.options.values.some(
(requiredOption) => upgradeOption.key === requiredOption.key,
),
) || { value: this.queryParams }
);
}
@@ -39,7 +41,9 @@ export class CantAddCustomerToCartModalComponent {
get queryParams() {
let option = this.ref.data.required?.options.values.find((f) => f.selected);
if (!option) {
option = this.ref.data.required?.options.values.find((f) => (isBoolean(f.enabled) ? f.enabled : true));
option = this.ref.data.required?.options.values.find((f) =>
isBoolean(f.enabled) ? f.enabled : true,
);
}
return option ? { customertype: option.value } : {};
}
@@ -57,27 +61,29 @@ export class CantAddCustomerToCartModalComponent {
const queryParams: Record<string, string> = {};
if (customer) {
queryParams['formData'] = encodeFormData(mapCustomerDtoToCustomerCreateFormData(customer));
queryParams['formData'] = encodeFormData(
mapCustomerDtoToCustomerCreateFormData(customer),
);
}
if (option === 'webshop' && attributes.some((a) => a.key === 'p4mUser')) {
const nav = this.customerCreateNavigation.createCustomerRoute({
processId: this.applicationService.activatedProcessId,
customerType: 'webshop-p4m',
});
this.router.navigate(nav.path, {
queryParams: { ...nav.queryParams, ...queryParams },
});
} else {
const nav = this.customerCreateNavigation.createCustomerRoute({
processId: this.applicationService.activatedProcessId,
customerType: option as any,
});
// if (option === 'webshop' && attributes.some((a) => a.key === 'p4mUser')) {
// const nav = this.customerCreateNavigation.createCustomerRoute({
// processId: this.applicationService.activatedProcessId,
// customerType: 'webshop-p4m',
// });
// this.router.navigate(nav.path, {
// queryParams: { ...nav.queryParams, ...queryParams },
// });
// } else {
const nav = this.customerCreateNavigation.createCustomerRoute({
processId: this.applicationService.activatedProcessId,
customerType: option as any,
});
this.router.navigate(nav.path, {
queryParams: { ...nav.queryParams, ...queryParams },
});
}
this.router.navigate(nav.path, {
queryParams: { ...nav.queryParams, ...queryParams },
});
// }
this.ref.close();
}

View File

@@ -1,7 +1,11 @@
<div class="font-bold text-center border-t border-b border-solid border-disabled-customer -mx-4 py-4">
<div
class="font-bold text-center border-t border-b border-solid border-disabled-customer -mx-4 py-4"
>
{{ customer?.communicationDetails?.email }}
</div>
<div class="grid grid-flow-row gap-1 text-sm font-bold border-b border-solid border-disabled-customer -mx-4 py-4 px-14">
<div
class="grid grid-flow-row gap-1 text-sm font-bold border-b border-solid border-disabled-customer -mx-4 py-4 px-14"
>
@if (customer?.organisation?.name) {
<span>{{ customer?.organisation?.name }}</span>
}
@@ -16,23 +20,26 @@
</div>
<div class="grid grid-flow-col gap-4 justify-around mt-12">
<button class="border-2 border-solid border-brand rounded-full font-bold text-brand px-6 py-3 text-lg" (click)="close(false)">
<button
class="border-2 border-solid border-brand rounded-full font-bold text-brand px-6 py-3 text-lg"
(click)="close(false)"
>
neues Onlinekonto anlegen
</button>
@if (!isWebshopWithP4M) {
<button
class="border-2 border-solid border-brand rounded-full font-bold text-white px-6 py-3 text-lg bg-brand"
(click)="close(true)"
>
>
Daten übernehmen
</button>
}
@if (isWebshopWithP4M) {
<!-- @if (isWebshopWithP4M) {
<button
class="border-2 border-solid border-brand rounded-full font-bold text-white px-6 py-3 text-lg bg-brand"
(click)="selectCustomer()"
>
Datensatz auswählen
</button>
}
} -->
</div>

View File

@@ -9,11 +9,11 @@ import { CustomerCreateGuard } from './guards/customer-create.guard';
import {
CreateB2BCustomerComponent,
CreateGuestCustomerComponent,
CreateP4MCustomerComponent,
// CreateP4MCustomerComponent,
CreateStoreCustomerComponent,
CreateWebshopCustomerComponent,
} from './create-customer';
import { UpdateP4MWebshopCustomerComponent } from './create-customer/update-p4m-webshop-customer';
// import { UpdateP4MWebshopCustomerComponent } from './create-customer/update-p4m-webshop-customer';
import { CreateCustomerComponent } from './create-customer/create-customer.component';
import { CustomerDataEditB2BComponent } from './customer-search/edit-main-view/customer-data-edit-b2b.component';
import { CustomerDataEditB2CComponent } from './customer-search/edit-main-view/customer-data-edit-b2c.component';
@@ -40,8 +40,16 @@ export const routes: Routes = [
path: '',
component: CustomerSearchComponent,
children: [
{ path: 'search', component: CustomerMainViewComponent, data: { side: 'main', breadcrumb: 'main' } },
{ path: 'search/list', component: CustomerResultsMainViewComponent, data: { breadcrumb: 'search' } },
{
path: 'search',
component: CustomerMainViewComponent,
data: { side: 'main', breadcrumb: 'main' },
},
{
path: 'search/list',
component: CustomerResultsMainViewComponent,
data: { breadcrumb: 'search' },
},
{
path: 'search/filter',
component: CustomerFilterMainViewComponent,
@@ -80,7 +88,10 @@ export const routes: Routes = [
{
path: 'search/:customerId/orders/:orderId/:orderItemId/history',
component: CustomerOrderDetailsHistoryMainViewComponent,
data: { side: 'order-details', breadcrumb: 'order-details-history' },
data: {
side: 'order-details',
breadcrumb: 'order-details-history',
},
},
{
path: 'search/:customerId/edit/b2b',
@@ -140,13 +151,13 @@ export const routes: Routes = [
{ path: 'create/webshop', component: CreateWebshopCustomerComponent },
{ path: 'create/b2b', component: CreateB2BCustomerComponent },
{ path: 'create/guest', component: CreateGuestCustomerComponent },
{ path: 'create/webshop-p4m', component: CreateP4MCustomerComponent, data: { customerType: 'webshop' } },
{ path: 'create/store-p4m', component: CreateP4MCustomerComponent, data: { customerType: 'store' } },
{
path: 'create/webshop-p4m/update',
component: UpdateP4MWebshopCustomerComponent,
data: { customerType: 'webshop' },
},
// { path: 'create/webshop-p4m', component: CreateP4MCustomerComponent, data: { customerType: 'webshop' } },
// { path: 'create/store-p4m', component: CreateP4MCustomerComponent, data: { customerType: 'store' } },
// {
// path: 'create/webshop-p4m/update',
// component: UpdateP4MWebshopCustomerComponent,
// data: { customerType: 'webshop' },
// },
{
path: 'create-customer-main',
outlet: 'side',

View File

@@ -1,254 +1,254 @@
import {
ChangeDetectionStrategy,
Component,
OnDestroy,
OnInit,
ViewChild,
inject,
linkedSignal,
} from '@angular/core';
import { Router } from '@angular/router';
import { BreadcrumbService } from '@core/breadcrumb';
import {
KeyValueDTOOfStringAndString,
OrderItemListItemDTO,
} from '@generated/swagger/oms-api';
import { UiErrorModalComponent, UiModalService } from '@ui/modal';
import { UiScrollContainerComponent } from '@ui/scroll-container';
import { BehaviorSubject, combineLatest, Subject } from 'rxjs';
import { first, map, shareReplay, takeUntil } from 'rxjs/operators';
import { GoodsInRemissionPreviewStore } from './goods-in-remission-preview.store';
import { Config } from '@core/config';
import { ToasterService } from '@shared/shell';
import { PickupShelfInNavigationService } from '@shared/services/navigation';
import { CacheService } from '@core/cache';
import { TabService } from '@isa/core/tabs';
@Component({
selector: 'page-goods-in-remission-preview',
templateUrl: 'goods-in-remission-preview.component.html',
styleUrls: ['goods-in-remission-preview.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [GoodsInRemissionPreviewStore],
standalone: false,
})
export class GoodsInRemissionPreviewComponent implements OnInit, OnDestroy {
tabService = inject(TabService);
private _pickupShelfInNavigationService = inject(
PickupShelfInNavigationService,
);
@ViewChild(UiScrollContainerComponent)
scrollContainer: UiScrollContainerComponent;
items$ = this._store.results$;
itemLength$ = this.items$.pipe(map((items) => items?.length));
hits$ = this._store.hits$;
loading$ = this._store.fetching$.pipe(shareReplay());
changeActionLoader$ = new BehaviorSubject<boolean>(false);
listEmpty$ = combineLatest([this.loading$, this.hits$]).pipe(
map(([loading, hits]) => !loading && hits === 0),
shareReplay(),
);
actions$ = this.items$.pipe(map((items) => items[0]?.actions));
private _onDestroy$ = new Subject<void>();
byBuyerNumberFn = (item: OrderItemListItemDTO) => item.buyerNumber;
byOrderNumberFn = (item: OrderItemListItemDTO) => item.orderNumber;
byProcessingStatusFn = (item: OrderItemListItemDTO) => item.processingStatus;
byCompartmentCodeFn = (item: OrderItemListItemDTO) =>
item.compartmentInfo
? `${item.compartmentCode}_${item.compartmentInfo}`
: item.compartmentCode;
private readonly SCROLL_POSITION_TOKEN = 'REMISSION_PREVIEW_SCROLL_POSITION';
remissionPath = linkedSignal(() => [
'/',
this.tabService.activatedTab()?.id || this.tabService.nextId(),
'remission',
]);
constructor(
private _breadcrumb: BreadcrumbService,
private _store: GoodsInRemissionPreviewStore,
private _router: Router,
private _modal: UiModalService,
private _config: Config,
private _toast: ToasterService,
private _cache: CacheService,
) {}
ngOnInit(): void {
this.initInitialSearch();
this.createBreadcrumb();
this.removeBreadcrumbs();
}
ngOnDestroy(): void {
this._onDestroy$.next();
this._onDestroy$.complete();
this._addScrollPositionToCache();
this.updateBreadcrumb();
}
private _removeScrollPositionFromCache(): void {
this._cache.delete({
processId: this._config.get('process.ids.goodsIn'),
token: this.SCROLL_POSITION_TOKEN,
});
}
private _addScrollPositionToCache(): void {
this._cache.set<number>(
{
processId: this._config.get('process.ids.goodsIn'),
token: this.SCROLL_POSITION_TOKEN,
},
this.scrollContainer?.scrollPos,
);
}
private async _getScrollPositionFromCache(): Promise<number> {
return await this._cache.get<number>({
processId: this._config.get('process.ids.goodsIn'),
token: this.SCROLL_POSITION_TOKEN,
});
}
async createBreadcrumb() {
await this._breadcrumb.addOrUpdateBreadcrumbIfNotExists({
key: this._config.get('process.ids.goodsIn'),
name: 'Abholfachremissionsvorschau',
path: '/filiale/goods/in/preview',
section: 'branch',
params: { view: 'remission' },
tags: ['goods-in', 'preview'],
});
}
async updateBreadcrumb() {
const crumbs = await this._breadcrumb
.getBreadcrumbsByKeyAndTags$(this._config.get('process.ids.goodsIn'), [
'goods-in',
'preview',
])
.pipe(first())
.toPromise();
for (const crumb of crumbs) {
this._breadcrumb.patchBreadcrumb(crumb.id, {
name: crumb.name,
});
}
}
async removeBreadcrumbs() {
let breadcrumbsToDelete = await this._breadcrumb
.getBreadcrumbsByKeyAndTags$(this._config.get('process.ids.goodsIn'), [
'goods-in',
])
.pipe(first())
.toPromise();
breadcrumbsToDelete = breadcrumbsToDelete.filter(
(crumb) =>
!crumb.tags.includes('preview') && !crumb.tags.includes('main'),
);
breadcrumbsToDelete.forEach((crumb) => {
this._breadcrumb.removeBreadcrumb(crumb.id, true);
});
const detailsCrumbs = await this._breadcrumb
.getBreadcrumbsByKeyAndTags$(this._config.get('process.ids.goodsIn'), [
'goods-in',
'details',
])
.pipe(first())
.toPromise();
const editCrumbs = await this._breadcrumb
.getBreadcrumbsByKeyAndTags$(this._config.get('process.ids.goodsIn'), [
'goods-in',
'edit',
])
.pipe(first())
.toPromise();
detailsCrumbs.forEach((crumb) => {
this._breadcrumb.removeBreadcrumb(crumb.id, true);
});
editCrumbs.forEach((crumb) => {
this._breadcrumb.removeBreadcrumb(crumb.id, true);
});
}
initInitialSearch() {
if (this._store.hits === 0) {
this._store.searchResult$
.pipe(takeUntil(this._onDestroy$))
.subscribe(async (result) => {
await this.createBreadcrumb();
this.scrollContainer?.scrollTo(
(await this._getScrollPositionFromCache()) ?? 0,
);
this._removeScrollPositionFromCache();
});
}
this._store.search();
}
async navigateToRemission() {
await this._router.navigate(this.remissionPath());
}
navigateToDetails(orderItem: OrderItemListItemDTO) {
const nav = this._pickupShelfInNavigationService.detailRoute({
item: orderItem,
side: false,
});
this._router.navigate(nav.path, {
queryParams: { ...nav.queryParams, view: 'remission' },
});
}
async handleAction(action: KeyValueDTOOfStringAndString) {
this.changeActionLoader$.next(true);
try {
const response = await this._store
.createRemissionFromPreview()
.pipe(first())
.toPromise();
if (!response?.dialog) {
this._toast.open({
title: 'Abholfachremission',
message: response?.message,
});
}
await this.navigateToRemission();
} catch (error) {
this._modal.open({
content: UiErrorModalComponent,
data: error,
});
console.error(error);
}
this.changeActionLoader$.next(false);
}
}
import {
ChangeDetectionStrategy,
Component,
OnDestroy,
OnInit,
ViewChild,
inject,
linkedSignal,
} from '@angular/core';
import { Router } from '@angular/router';
import { BreadcrumbService } from '@core/breadcrumb';
import {
KeyValueDTOOfStringAndString,
OrderItemListItemDTO,
} from '@generated/swagger/oms-api';
import { UiErrorModalComponent, UiModalService } from '@ui/modal';
import { UiScrollContainerComponent } from '@ui/scroll-container';
import { BehaviorSubject, combineLatest, Subject } from 'rxjs';
import { first, map, shareReplay, takeUntil } from 'rxjs/operators';
import { GoodsInRemissionPreviewStore } from './goods-in-remission-preview.store';
import { Config } from '@core/config';
import { ToasterService } from '@shared/shell';
import { PickupShelfInNavigationService } from '@shared/services/navigation';
import { CacheService } from '@core/cache';
import { TabService } from '@isa/core/tabs';
@Component({
selector: 'page-goods-in-remission-preview',
templateUrl: 'goods-in-remission-preview.component.html',
styleUrls: ['goods-in-remission-preview.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [GoodsInRemissionPreviewStore],
standalone: false,
})
export class GoodsInRemissionPreviewComponent implements OnInit, OnDestroy {
tabService = inject(TabService);
private _pickupShelfInNavigationService = inject(
PickupShelfInNavigationService,
);
@ViewChild(UiScrollContainerComponent)
scrollContainer: UiScrollContainerComponent;
items$ = this._store.results$;
itemLength$ = this.items$.pipe(map((items) => items?.length));
hits$ = this._store.hits$;
loading$ = this._store.fetching$.pipe(shareReplay());
changeActionLoader$ = new BehaviorSubject<boolean>(false);
listEmpty$ = combineLatest([this.loading$, this.hits$]).pipe(
map(([loading, hits]) => !loading && hits === 0),
shareReplay(),
);
actions$ = this.items$.pipe(map((items) => items[0]?.actions));
private _onDestroy$ = new Subject<void>();
byBuyerNumberFn = (item: OrderItemListItemDTO) => item.buyerNumber;
byOrderNumberFn = (item: OrderItemListItemDTO) => item.orderNumber;
byProcessingStatusFn = (item: OrderItemListItemDTO) => item.processingStatus;
byCompartmentCodeFn = (item: OrderItemListItemDTO) =>
item.compartmentInfo
? `${item.compartmentCode}_${item.compartmentInfo}`
: item.compartmentCode;
private readonly SCROLL_POSITION_TOKEN = 'REMISSION_PREVIEW_SCROLL_POSITION';
remissionPath = linkedSignal(() => [
'/',
this.tabService.activatedTab()?.id || Date.now(),
'remission',
]);
constructor(
private _breadcrumb: BreadcrumbService,
private _store: GoodsInRemissionPreviewStore,
private _router: Router,
private _modal: UiModalService,
private _config: Config,
private _toast: ToasterService,
private _cache: CacheService,
) {}
ngOnInit(): void {
this.initInitialSearch();
this.createBreadcrumb();
this.removeBreadcrumbs();
}
ngOnDestroy(): void {
this._onDestroy$.next();
this._onDestroy$.complete();
this._addScrollPositionToCache();
this.updateBreadcrumb();
}
private _removeScrollPositionFromCache(): void {
this._cache.delete({
processId: this._config.get('process.ids.goodsIn'),
token: this.SCROLL_POSITION_TOKEN,
});
}
private _addScrollPositionToCache(): void {
this._cache.set<number>(
{
processId: this._config.get('process.ids.goodsIn'),
token: this.SCROLL_POSITION_TOKEN,
},
this.scrollContainer?.scrollPos,
);
}
private async _getScrollPositionFromCache(): Promise<number> {
return await this._cache.get<number>({
processId: this._config.get('process.ids.goodsIn'),
token: this.SCROLL_POSITION_TOKEN,
});
}
async createBreadcrumb() {
await this._breadcrumb.addOrUpdateBreadcrumbIfNotExists({
key: this._config.get('process.ids.goodsIn'),
name: 'Abholfachremissionsvorschau',
path: '/filiale/goods/in/preview',
section: 'branch',
params: { view: 'remission' },
tags: ['goods-in', 'preview'],
});
}
async updateBreadcrumb() {
const crumbs = await this._breadcrumb
.getBreadcrumbsByKeyAndTags$(this._config.get('process.ids.goodsIn'), [
'goods-in',
'preview',
])
.pipe(first())
.toPromise();
for (const crumb of crumbs) {
this._breadcrumb.patchBreadcrumb(crumb.id, {
name: crumb.name,
});
}
}
async removeBreadcrumbs() {
let breadcrumbsToDelete = await this._breadcrumb
.getBreadcrumbsByKeyAndTags$(this._config.get('process.ids.goodsIn'), [
'goods-in',
])
.pipe(first())
.toPromise();
breadcrumbsToDelete = breadcrumbsToDelete.filter(
(crumb) =>
!crumb.tags.includes('preview') && !crumb.tags.includes('main'),
);
breadcrumbsToDelete.forEach((crumb) => {
this._breadcrumb.removeBreadcrumb(crumb.id, true);
});
const detailsCrumbs = await this._breadcrumb
.getBreadcrumbsByKeyAndTags$(this._config.get('process.ids.goodsIn'), [
'goods-in',
'details',
])
.pipe(first())
.toPromise();
const editCrumbs = await this._breadcrumb
.getBreadcrumbsByKeyAndTags$(this._config.get('process.ids.goodsIn'), [
'goods-in',
'edit',
])
.pipe(first())
.toPromise();
detailsCrumbs.forEach((crumb) => {
this._breadcrumb.removeBreadcrumb(crumb.id, true);
});
editCrumbs.forEach((crumb) => {
this._breadcrumb.removeBreadcrumb(crumb.id, true);
});
}
initInitialSearch() {
if (this._store.hits === 0) {
this._store.searchResult$
.pipe(takeUntil(this._onDestroy$))
.subscribe(async (result) => {
await this.createBreadcrumb();
this.scrollContainer?.scrollTo(
(await this._getScrollPositionFromCache()) ?? 0,
);
this._removeScrollPositionFromCache();
});
}
this._store.search();
}
async navigateToRemission() {
await this._router.navigate(this.remissionPath());
}
navigateToDetails(orderItem: OrderItemListItemDTO) {
const nav = this._pickupShelfInNavigationService.detailRoute({
item: orderItem,
side: false,
});
this._router.navigate(nav.path, {
queryParams: { ...nav.queryParams, view: 'remission' },
});
}
async handleAction(action: KeyValueDTOOfStringAndString) {
this.changeActionLoader$.next(true);
try {
const response = await this._store
.createRemissionFromPreview()
.pipe(first())
.toPromise();
if (!response?.dialog) {
this._toast.open({
title: 'Abholfachremission',
message: response?.message,
});
}
await this.navigateToRemission();
} catch (error) {
this._modal.open({
content: UiErrorModalComponent,
data: error,
});
console.error(error);
}
this.changeActionLoader$.next(false);
}
}

View File

@@ -1,39 +1,60 @@
<div class="shared-branch-selector-input-container" (click)="branchInput.focus(); openComplete()">
<button (click)="onClose($event)" type="button" class="shared-branch-selector-input-icon p-2">
<shared-icon class="text-[#AEB7C1]" icon="magnify" [size]="32"></shared-icon>
</button>
<input
#branchInput
class="shared-branch-selector-input"
[class.shared-branch-selector-opend]="autocompleteComponent?.opend"
uiInput
type="text"
[placeholder]="placeholder"
[ngModel]="query$ | async"
(ngModelChange)="onQueryChange($event)"
(keyup)="onKeyup($event)"
/>
@if ((query$ | async)?.length > 0) {
<button class="shared-branch-selector-clear-input-icon pr-2" type="button" (click)="clear()">
<shared-icon class="text-[#1F466C]" icon="close" [size]="32"></shared-icon>
</button>
}
</div>
<ui-autocomplete class="shared-branch-selector-autocomplete z-modal w-full">
@if (autocompleteComponent?.opend) {
<hr class="ml-3 text-[#9CB1C6]" uiAutocompleteSeparator />
}
@if ((filteredBranches$ | async)?.length > 0) {
<p class="text-p2 p-4 font-normal" uiAutocompleteLabel>Filialvorschläge</p>
}
@for (branch of filteredBranches$ | async; track branch) {
<button
class="shared-branch-selector-autocomplete-option min-h-[44px]"
[class.shared-branch-selector-selected]="value && value.id === branch.id"
(click)="setBranch(branch)"
[uiAutocompleteItem]="branch"
>
<span class="text-lg font-semibold">{{ store.formatBranch(branch) }}</span>
</button>
}
</ui-autocomplete>
<div
class="shared-branch-selector-input-container"
(click)="branchInput.focus(); openComplete()"
>
<button
(click)="onClose($event)"
type="button"
class="shared-branch-selector-input-icon p-2"
>
<shared-icon
class="text-[#AEB7C1]"
icon="magnify"
[size]="32"
></shared-icon>
</button>
<input
#branchInput
class="shared-branch-selector-input"
[class.shared-branch-selector-opend]="autocompleteComponent?.opend"
uiInput
type="text"
[placeholder]="placeholder"
[ngModel]="query$ | async"
(ngModelChange)="onQueryChange($event)"
(keyup)="onKeyup($event)"
/>
@if ((query$ | async)?.length > 0) {
<button
class="shared-branch-selector-clear-input-icon pr-2"
type="button"
(click)="clear()"
>
<shared-icon
class="text-[#1F466C]"
icon="close"
[size]="32"
></shared-icon>
</button>
}
</div>
<ui-autocomplete class="shared-branch-selector-autocomplete z-modal w-full">
@if (autocompleteComponent?.opend) {
<hr class="ml-3 text-[#9CB1C6]" uiAutocompleteSeparator />
}
@if ((filteredBranches$ | async)?.length > 0) {
<p class="text-p2 p-4 font-normal" uiAutocompleteLabel>Filialvorschläge</p>
}
@for (branch of filteredBranches$ | async; track branch) {
<button
class="shared-branch-selector-autocomplete-option min-h-[44px]"
[class.shared-branch-selector-selected]="value && value.id === branch.id"
(click)="setBranch(branch)"
[uiAutocompleteItem]="branch"
>
<span class="text-lg font-semibold">{{
store.formatBranch(branch)
}}</span>
</button>
}
</ui-autocomplete>

View File

@@ -3,7 +3,10 @@ import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { CustomerInfoDTO } from '@generated/swagger/crm-api';
import { NavigationRoute } from './defs/navigation-route';
import { encodeFormData, mapCustomerInfoDtoToCustomerCreateFormData } from 'apps/isa-app/src/page/customer';
import {
encodeFormData,
mapCustomerInfoDtoToCustomerCreateFormData,
} from 'apps/isa-app/src/page/customer';
@Injectable({ providedIn: 'root' })
export class CustomerCreateNavigation {
@@ -33,7 +36,9 @@ export class CustomerCreateNavigation {
navigateToDefault(params: { processId: NumberInput }): Promise<boolean> {
const route = this.defaultRoute(params);
return this._router.navigate(route.path, { queryParams: route.queryParams });
return this._router.navigate(route.path, {
queryParams: route.queryParams,
});
}
createCustomerRoute(params: {
@@ -54,7 +59,9 @@ export class CustomerCreateNavigation {
];
let formData = params?.customerInfo
? encodeFormData(mapCustomerInfoDtoToCustomerCreateFormData(params.customerInfo))
? encodeFormData(
mapCustomerInfoDtoToCustomerCreateFormData(params.customerInfo),
)
: undefined;
const urlTree = this._router.createUrlTree(path, {
@@ -79,7 +86,9 @@ export class CustomerCreateNavigation {
processId: NumberInput;
customerInfo: CustomerInfoDTO;
}): NavigationRoute {
const formData = encodeFormData(mapCustomerInfoDtoToCustomerCreateFormData(customerInfo));
const formData = encodeFormData(
mapCustomerInfoDtoToCustomerCreateFormData(customerInfo),
);
const path = [
'/kunde',
coerceNumberProperty(processId),
@@ -88,14 +97,16 @@ export class CustomerCreateNavigation {
outlets: {
primary: [
'create',
customerInfo?.features?.find((feature) => feature.key === 'webshop') ? 'webshop-p4m' : 'store-p4m',
// customerInfo?.features?.find((feature) => feature.key === 'webshop') ? 'webshop-p4m' : 'store-p4m',
],
side: 'create-customer-main',
},
},
];
const urlTree = this._router.createUrlTree(path, { queryParams: { formData } });
const urlTree = this._router.createUrlTree(path, {
queryParams: { formData },
});
return {
path,

View File

@@ -1,31 +1,38 @@
<div
class="tab-wrapper flex flex-row items-center justify-between border-b-[0.188rem] border-solid h-14"
[class.border-surface]="!(isActive$ | async)"
[class.border-brand]="isActive$ | async"
>
<a
class="tab-link font-bold flex flex-row justify-center items-center whitespace-nowrap px-4 truncate max-w-[15rem] h-14"
[routerLink]="routerLink$ | async"
[queryParams]="queryParams$ | async"
(click)="scrollIntoView()"
>
<span class="truncate">
{{ process?.name }}
</span>
@if (process?.type !== 'cart-checkout') {
<button
type="button"
class="rounded-full px-3 h-[2.375rem] font-bold text-p1 flex flex-row items-center justify-between shopping-cart-count ml-4"
[class.active]="isActive$ | async"
[routerLink]="getCheckoutPath((process$ | async)?.id)"
(click)="$event?.preventDefault(); $event?.stopPropagation()"
>
<shared-icon icon="shopping-cart-bold" [size]="22"></shared-icon>
<span class="shopping-cart-count-label ml-2">{{ cartItemCount$ | async }}</span>
</button>
}
</a>
<button type="button" class="tab-close-btn -ml-4 h-12 w-12 grid justify-center items-center" (click)="close()">
<shared-icon icon="close" [size]="28"></shared-icon>
</button>
</div>
@if (process(); as p) {
<div
class="tab-wrapper flex flex-row items-center justify-between border-b-[0.188rem] border-solid h-14"
[class.border-surface]="!(isActive$ | async)"
[class.border-brand]="isActive$ | async"
>
<a
class="tab-link font-bold flex flex-row justify-center items-center whitespace-nowrap px-4 truncate max-w-[15rem] h-14"
[href]="currentLocationUrlTree()?.toString()"
(click)="navigateByUrl($event); scrollIntoView()"
>
<span class="truncate">
{{ p.name }}
</span>
@if (p.type === 'cart') {
<button
type="button"
class="rounded-full px-3 h-[2.375rem] font-bold text-p1 flex flex-row items-center justify-between shopping-cart-count ml-4"
[class.active]="isActive$ | async"
[routerLink]="getCheckoutPath((process$ | async)?.id)"
(click)="$event?.preventDefault(); $event?.stopPropagation()"
>
<shared-icon icon="shopping-cart-bold" [size]="22"></shared-icon>
<span class="shopping-cart-count-label ml-2">{{
cartItemCount$ | async
}}</span>
</button>
}
</a>
<button
type="button"
class="tab-close-btn -ml-4 h-12 w-12 grid justify-center items-center"
(click)="close()"
>
<shared-icon icon="close" [size]="28"></shared-icon>
</button>
</div>
}

View File

@@ -1,156 +1,208 @@
import {
Component,
ChangeDetectionStrategy,
Input,
OnDestroy,
OnInit,
OnChanges,
SimpleChanges,
EventEmitter,
Output,
ElementRef,
} from '@angular/core';
import { Router } from '@angular/router';
import { ApplicationProcess, ApplicationService } from '@core/application';
import { Breadcrumb, BreadcrumbService } from '@core/breadcrumb';
import { DomainCheckoutService } from '@domain/checkout';
import { CheckoutNavigationService } from '@shared/services/navigation';
import { BehaviorSubject, NEVER, Observable, combineLatest, isObservable } from 'rxjs';
import { first, map, switchMap, tap } from 'rxjs/operators';
@Component({
selector: 'shell-process-bar-item',
templateUrl: 'process-bar-item.component.html',
styleUrls: ['process-bar-item.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: false,
})
export class ShellProcessBarItemComponent implements OnInit, OnDestroy, OnChanges {
private _process$ = new BehaviorSubject<ApplicationProcess>(undefined);
process$ = this._process$.asObservable();
@Input()
process: ApplicationProcess;
@Output()
closed = new EventEmitter();
activatedProcessId$ = this._app.activatedProcessId$;
latestBreadcrumb$: Observable<Breadcrumb> = NEVER;
routerLink$: Observable<string[] | any[]> = NEVER;
queryParams$: Observable<object> = NEVER;
isActive$: Observable<boolean> = NEVER;
showCloseButton$: Observable<boolean> = NEVER;
cartItemCount$: Observable<number> = NEVER;
constructor(
private _breadcrumb: BreadcrumbService,
private _app: ApplicationService,
private _router: Router,
private _checkout: DomainCheckoutService,
private _checkoutNavigationService: CheckoutNavigationService,
public _elRef: ElementRef<HTMLElement>,
) {}
ngOnChanges({ process }: SimpleChanges): void {
if (process) {
this._process$.next(process.currentValue);
}
}
ngOnInit() {
this.initLatestBreadcrumb$();
this.initRouterLink$();
this.initQueryParams$();
this.initIsActive$();
this.initShowCloseButton$();
this.initCartItemCount$();
}
scrollIntoView() {
setTimeout(() => this._elRef.nativeElement.scrollIntoView({ behavior: 'smooth', block: 'center' }), 0);
}
getCheckoutPath(processId: number) {
return this._checkoutNavigationService.getCheckoutReviewPath(processId).path;
}
initLatestBreadcrumb$() {
this.latestBreadcrumb$ = this.process$.pipe(
switchMap((process) => this._breadcrumb.getLastActivatedBreadcrumbByKey$(process?.id)),
);
}
initRouterLink$() {
this.routerLink$ = this.latestBreadcrumb$.pipe(
map((breadcrumb) => (breadcrumb?.path instanceof Array ? breadcrumb.path : [breadcrumb?.path])),
);
}
initQueryParams$() {
this.queryParams$ = this.latestBreadcrumb$.pipe(map((breadcrumb) => breadcrumb?.params));
}
initIsActive$() {
if (isObservable(this.activatedProcessId$) && isObservable(this.process$)) {
this.isActive$ = combineLatest([this.activatedProcessId$, this.process$]).pipe(
map(([activatedId, process]) => process?.id === activatedId),
tap((isActive) => {
if (isActive) {
this.scrollIntoView();
}
}),
);
}
}
initShowCloseButton$() {
if (isObservable(this.isActive$) && isObservable(this.process$)) {
this.showCloseButton$ = this.process$.pipe(map((process) => process?.closeable));
}
}
initCartItemCount$() {
this.cartItemCount$ = this.process$.pipe(
switchMap((process) => this._checkout?.getShoppingCart({ processId: process?.id })),
map((cart) => cart?.items?.length ?? 0),
);
}
ngOnDestroy() {
this._process$.complete();
}
async close() {
const breadcrumb = await this.getLatestBreadcrumbForSection();
await this.navigate(breadcrumb);
this._app.removeProcess(this.process.id);
this.closed.emit();
}
getLatestBreadcrumbForSection(): Promise<Breadcrumb> {
return this._breadcrumb
.getLatestBreadcrumbForSection('customer', (c) => c.key !== this.process?.id)
.pipe(first())
.toPromise();
}
async navigate(breadcrumb?: Breadcrumb) {
if (breadcrumb) {
if (breadcrumb.path instanceof Array) {
await this._router.navigate(breadcrumb.path, { queryParams: breadcrumb.params });
} else {
await this._router.navigate([breadcrumb.path], { queryParams: breadcrumb.params });
}
} else {
await this._router.navigate(['/kunde/dashboard']);
}
}
}
import {
Component,
ChangeDetectionStrategy,
OnDestroy,
OnInit,
OnChanges,
SimpleChanges,
EventEmitter,
Output,
ElementRef,
inject,
computed,
input,
effect,
} from '@angular/core';
import { Router } from '@angular/router';
import { ApplicationProcess, ApplicationService } from '@core/application';
import { Breadcrumb } from '@core/breadcrumb';
import { DomainCheckoutService } from '@domain/checkout';
import { CheckoutNavigationService } from '@shared/services/navigation';
import {
BehaviorSubject,
NEVER,
Observable,
combineLatest,
isObservable,
} from 'rxjs';
import { map, switchMap, tap } from 'rxjs/operators';
import { TabService } from '@isa/core/tabs';
@Component({
selector: 'shell-process-bar-item',
templateUrl: 'process-bar-item.component.html',
styleUrls: ['process-bar-item.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: false,
})
export class ShellProcessBarItemComponent
implements OnInit, OnDestroy, OnChanges
{
#tabService = inject(TabService);
tab = computed(() => this.#tabService.entityMap()[this.process().id]);
private _process$ = new BehaviorSubject<ApplicationProcess>(undefined);
process$ = this._process$.asObservable();
process = input.required<ApplicationProcess>();
@Output()
closed = new EventEmitter();
showCart = computed(() => {
const tab = this.tab();
const pdata = tab.metadata?.process_data as { count?: number };
if (!pdata) {
return false;
}
return 'count' in pdata;
});
currentLocationUrlTree = computed(() => {
const tab = this.tab();
const current = tab.location.locations[tab.location.current];
if (current?.url) {
return this._router.parseUrl(current.url);
}
return null;
});
navigateByUrl(event: MouseEvent) {
event?.preventDefault();
this._router.navigateByUrl(this.currentLocationUrlTree());
}
activatedProcessId$ = this._app.activatedProcessId$;
latestBreadcrumb$: Observable<Breadcrumb> = NEVER;
routerLink$: Observable<string[] | any[]> = NEVER;
queryParams$: Observable<object> = NEVER;
isActive$: Observable<boolean> = NEVER;
showCloseButton$: Observable<boolean> = NEVER;
cartItemCount$: Observable<number> = NEVER;
constructor(
private _app: ApplicationService,
private _router: Router,
private _checkout: DomainCheckoutService,
private _checkoutNavigationService: CheckoutNavigationService,
public _elRef: ElementRef<HTMLElement>,
) {}
ngOnChanges({ process }: SimpleChanges): void {
if (process) {
this._process$.next(process.currentValue);
}
}
ngOnInit() {
this.initRouterLink$();
this.initQueryParams$();
this.initIsActive$();
this.initShowCloseButton$();
this.initCartItemCount$();
}
scrollIntoView() {
setTimeout(
() =>
this._elRef.nativeElement.scrollIntoView({
behavior: 'smooth',
block: 'center',
}),
0,
);
}
getCheckoutPath(processId: number) {
return this._checkoutNavigationService.getCheckoutReviewPath(processId)
.path;
}
initRouterLink$() {
this.routerLink$ = this.latestBreadcrumb$.pipe(
map((breadcrumb) =>
breadcrumb?.path instanceof Array
? breadcrumb.path
: [breadcrumb?.path],
),
);
}
initQueryParams$() {
this.queryParams$ = this.latestBreadcrumb$.pipe(
map((breadcrumb) => breadcrumb?.params),
);
}
initIsActive$() {
if (isObservable(this.activatedProcessId$) && isObservable(this.process$)) {
this.isActive$ = combineLatest([
this.activatedProcessId$,
this.process$,
]).pipe(
map(([activatedId, process]) => process?.id === activatedId),
tap((isActive) => {
if (isActive) {
this.scrollIntoView();
}
}),
);
}
}
initShowCloseButton$() {
if (isObservable(this.isActive$) && isObservable(this.process$)) {
this.showCloseButton$ = this.process$.pipe(
map((process) => process?.closeable),
);
}
}
initCartItemCount$() {
this.cartItemCount$ = this.process$.pipe(
switchMap((process) =>
this._checkout?.getShoppingCart({ processId: process?.id }),
),
map((cart) => cart?.items?.length ?? 0),
);
}
ngOnDestroy() {
this._process$.complete();
}
async close() {
await this.navigate();
this._app.removeProcess(this.process().id);
this.closed.emit();
}
async navigate(breadcrumb?: Breadcrumb) {
if (breadcrumb) {
if (breadcrumb.path instanceof Array) {
await this._router.navigate(breadcrumb.path, {
queryParams: breadcrumb.params,
});
} else {
await this._router.navigate([breadcrumb.path], {
queryParams: breadcrumb.params,
});
}
} else {
await this._router.navigate(['/kunde/dashboard']);
}
}
}

View File

@@ -1,187 +1,206 @@
import { coerceArray } from '@angular/cdk/coercion';
import { Component, ChangeDetectionStrategy, OnInit, ViewChild, ElementRef } from '@angular/core';
import { Router } from '@angular/router';
import { ApplicationProcess, ApplicationService } from '@core/application';
import { BreadcrumbService } from '@core/breadcrumb';
import { DomainCheckoutService } from '@domain/checkout';
import { injectOpenMessageModal } from '@modal/message';
import { CustomerOrdersNavigationService, ProductCatalogNavigationService } from '@shared/services/navigation';
import { NEVER, Observable, of } from 'rxjs';
import { delay, first, map, switchMap } from 'rxjs/operators';
@Component({
selector: 'shell-process-bar',
templateUrl: 'process-bar.component.html',
styleUrls: ['process-bar.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: false,
})
export class ShellProcessBarComponent implements OnInit {
@ViewChild('processContainer')
processContainer: ElementRef;
section$: Observable<'customer' | 'branch'> = NEVER;
processes$: Observable<ApplicationProcess[]> = NEVER;
showStartProcessText$: Observable<boolean> = NEVER;
hovered: boolean;
showScrollArrows: boolean;
showArrowLeft: boolean;
showArrowRight: boolean;
trackByFn = (_: number, process: ApplicationProcess) => process.id;
openMessageModal = injectOpenMessageModal();
constructor(
private _app: ApplicationService,
private _router: Router,
private _catalogNavigationService: ProductCatalogNavigationService,
private _customerOrderNavigationService: CustomerOrdersNavigationService,
private _checkoutService: DomainCheckoutService,
private _breadcrumb: BreadcrumbService,
) {}
ngOnInit() {
this.initSection$();
this.initProcesses$();
this.initShowStartProcessText$();
this.checkScrollArrowVisibility();
}
initSection$() {
this.section$ = of('customer');
}
initProcesses$() {
this.processes$ = this.section$.pipe(switchMap((section) => this._app.getProcesses$(section)));
}
initShowStartProcessText$() {
this.showStartProcessText$ = this.processes$.pipe(map((processes) => processes.length === 0));
}
async createProcess(target: string = 'product') {
const process = await this.createCartProcess();
this.navigateTo(target, process);
setTimeout(() => this.scrollToEnd(), 25);
}
static REGEX_PROCESS_NAME = /^Vorgang \d+$/;
async createCartProcess() {
return this._app.createCustomerProcess();
}
async navigateTo(target: string, process: ApplicationProcess) {
switch (target) {
case 'product':
await this._catalogNavigationService.getArticleSearchBasePath(process.id).navigate();
break;
case 'customer':
await this._router.navigate(['/kunde', process.id, 'customer', 'search']);
break;
case 'goods-out':
await this._router.navigate(['/kunde', process.id, 'goods', 'out']);
break;
case 'order':
await this._customerOrderNavigationService.getCustomerOrdersBasePath(process.id).navigate();
break;
default:
await this._router.navigate(['/kunde', process.id, target]);
break;
}
}
async closeAllProcesses() {
const processes = await this.processes$.pipe(first()).toPromise();
this.openMessageModal({
title: 'Vorgänge schließen',
message: `Sind Sie sich sicher, dass sie alle ${processes.length} Vorgänge schließen wollen?`,
actions: [
{ label: 'Abbrechen', value: false },
{
label: 'leere Warenkörbe',
value: true,
action: () => this.handleCloseEmptyCartProcesses(),
},
{
label: 'Ja, alle',
value: true,
primary: true,
action: () => this.handleCloseAllProcesses(),
},
],
});
this.checkScrollArrowVisibility();
}
async handleCloseEmptyCartProcesses() {
let processes = await this.processes$.pipe(first()).toPromise();
for (const process of processes) {
const cart = await this._checkoutService.getShoppingCart({ processId: process.id }).pipe(first()).toPromise();
if (cart?.items?.length === 0 || cart?.items === undefined) {
this._app.removeProcess(process?.id);
}
processes = await this.processes$.pipe(delay(1), first()).toPromise();
if (processes.length === 0) {
this._router.navigate(['/kunde', 'dashboard']);
} else {
const lastest = processes.reduce(
(prev, current) => (prev.activated > current.activated ? prev : current),
processes[0],
);
const crumb = await this._breadcrumb.getLastActivatedBreadcrumbByKey$(lastest.id).pipe(first()).toPromise();
if (crumb) {
this._router.navigate(coerceArray(crumb.path), { queryParams: crumb.params });
} else {
this._router.navigate(['/kunde', lastest.id, 'product']);
}
}
}
}
async handleCloseAllProcesses() {
const processes = await this.processes$.pipe(first()).toPromise();
processes.forEach((process) => this._app.removeProcess(process?.id));
this._router.navigate(['/kunde', 'dashboard']);
}
onMouseWheel(event: any) {
// Ermöglicht es, am Desktop die Prozessleiste mit dem Mausrad hoch/runter horizontal zu scrollen
if (event.deltaY > 0) {
this.processContainer.nativeElement.scrollLeft += 100;
} else {
this.processContainer.nativeElement.scrollLeft -= 100;
}
event.preventDefault();
}
scrollLeft() {
this.processContainer.nativeElement.scrollLeft -= 100;
}
scrollRight() {
this.processContainer.nativeElement.scrollLeft += 100;
}
scrollToEnd() {
this.processContainer.nativeElement.scrollLeft =
this.processContainer?.nativeElement?.scrollWidth + this.processContainer?.nativeElement?.scrollLeft;
}
checkScrollArrowVisibility() {
this.showScrollArrows = this.processContainer?.nativeElement?.scrollWidth > 0;
this.showArrowRight =
((this.processContainer?.nativeElement?.scrollWidth - this.processContainer?.nativeElement?.scrollLeft) | 0) <=
this.processContainer?.nativeElement?.offsetWidth;
this.showArrowLeft = this.processContainer?.nativeElement?.scrollLeft <= 0;
}
}
import { coerceArray } from '@angular/cdk/coercion';
import {
Component,
ChangeDetectionStrategy,
OnInit,
ViewChild,
ElementRef,
} from '@angular/core';
import { Router } from '@angular/router';
import { ApplicationProcess, ApplicationService } from '@core/application';
import { BreadcrumbService } from '@core/breadcrumb';
import { DomainCheckoutService } from '@domain/checkout';
import { injectOpenMessageModal } from '@modal/message';
import {
CustomerOrdersNavigationService,
ProductCatalogNavigationService,
} from '@shared/services/navigation';
import { NEVER, Observable, of } from 'rxjs';
import { delay, first, map, switchMap } from 'rxjs/operators';
@Component({
selector: 'shell-process-bar',
templateUrl: 'process-bar.component.html',
styleUrls: ['process-bar.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: false,
})
export class ShellProcessBarComponent implements OnInit {
@ViewChild('processContainer')
processContainer: ElementRef;
section$: Observable<'customer' | 'branch'> = NEVER;
processes$: Observable<ApplicationProcess[]> = NEVER;
showStartProcessText$: Observable<boolean> = NEVER;
hovered: boolean;
showScrollArrows: boolean;
showArrowLeft: boolean;
showArrowRight: boolean;
trackByFn = (_: number, process: ApplicationProcess) => process.id;
openMessageModal = injectOpenMessageModal();
constructor(
private _app: ApplicationService,
private _router: Router,
private _catalogNavigationService: ProductCatalogNavigationService,
private _customerOrderNavigationService: CustomerOrdersNavigationService,
private _checkoutService: DomainCheckoutService,
private _breadcrumb: BreadcrumbService,
) {}
ngOnInit() {
this.initSection$();
this.initProcesses$();
this.initShowStartProcessText$();
this.checkScrollArrowVisibility();
}
initSection$() {
this.section$ = of(undefined);
}
initProcesses$() {
this.processes$ = this.section$.pipe(
switchMap((section) => this._app.getProcesses$(section)),
map((processes) =>
processes.filter((process) => process.type === 'cart'),
),
);
}
initShowStartProcessText$() {
this.showStartProcessText$ = this.processes$.pipe(
map((processes) => processes.length === 0),
);
}
async createProcess(target = 'product') {
// const process = await this.createCartProcess();
this.navigateTo(target, Date.now());
setTimeout(() => this.scrollToEnd(), 25);
}
static REGEX_PROCESS_NAME = /^Vorgang \d+$/;
async createCartProcess() {
return this._app.createCustomerProcess();
}
async navigateTo(target: string, processId: number) {
switch (target) {
case 'product':
await this._catalogNavigationService
.getArticleSearchBasePath(processId)
.navigate();
break;
case 'customer':
await this._router.navigate([
'/kunde',
processId,
'customer',
'search',
]);
break;
case 'goods-out':
await this._router.navigate(['/kunde', processId, 'goods', 'out']);
break;
case 'order':
await this._customerOrderNavigationService
.getCustomerOrdersBasePath(processId)
.navigate();
break;
default:
await this._router.navigate(['/kunde', processId, target]);
break;
}
}
async closeAllProcesses() {
const processes = await this.processes$.pipe(first()).toPromise();
this.openMessageModal({
title: 'Vorgänge schließen',
message: `Sind Sie sich sicher, dass sie alle ${processes.length} Vorgänge schließen wollen?`,
actions: [
{ label: 'Abbrechen', value: false },
{
label: 'leere Warenkörbe',
value: true,
action: () => this.handleCloseEmptyCartProcesses(),
},
{
label: 'Ja, alle',
value: true,
primary: true,
action: () => this.handleCloseAllProcesses(),
},
],
});
this.checkScrollArrowVisibility();
}
async handleCloseEmptyCartProcesses() {
let processes = await this.processes$.pipe(first()).toPromise();
for (const process of processes) {
const cart = await this._checkoutService
.getShoppingCart({ processId: process.id })
.pipe(first())
.toPromise();
if (cart?.items?.length === 0 || cart?.items === undefined) {
this._app.removeProcess(process?.id);
}
processes = await this.processes$.pipe(delay(1), first()).toPromise();
this._router.navigate(['/kunde', 'dashboard']);
}
}
async handleCloseAllProcesses() {
const processes = await this.processes$.pipe(first()).toPromise();
processes.forEach((process) => this._app.removeProcess(process?.id));
this._router.navigate(['/kunde', 'dashboard']);
}
onMouseWheel(event: any) {
// Ermöglicht es, am Desktop die Prozessleiste mit dem Mausrad hoch/runter horizontal zu scrollen
if (event.deltaY > 0) {
this.processContainer.nativeElement.scrollLeft += 100;
} else {
this.processContainer.nativeElement.scrollLeft -= 100;
}
event.preventDefault();
}
scrollLeft() {
this.processContainer.nativeElement.scrollLeft -= 100;
}
scrollRight() {
this.processContainer.nativeElement.scrollLeft += 100;
}
scrollToEnd() {
this.processContainer.nativeElement.scrollLeft =
this.processContainer?.nativeElement?.scrollWidth +
this.processContainer?.nativeElement?.scrollLeft;
}
checkScrollArrowVisibility() {
this.showScrollArrows =
this.processContainer?.nativeElement?.scrollWidth > 0;
this.showArrowRight =
((this.processContainer?.nativeElement?.scrollWidth -
this.processContainer?.nativeElement?.scrollLeft) |
0) <=
this.processContainer?.nativeElement?.offsetWidth;
this.showArrowLeft = this.processContainer?.nativeElement?.scrollLeft <= 0;
}
}

View File

@@ -16,14 +16,16 @@
</a>
<div class="side-menu-group-sub-item-wrapper">
@if (customerSearchRoute$ | async; as customerSearchRoute) {
@if (
customerSearchRoute() || customerCreateRoute() || customerRewardRoute()
) {
<a
class="side-menu-group-item"
(click)="closeSideMenu(); focusSearchBox()"
[routerLink]="customerSearchRoute.path"
[queryParams]="customerSearchRoute.queryParams"
[routerLink]="customerSearchRoute().path"
[queryParams]="customerSearchRoute().queryParams"
sharedRegexRouterLinkActive="active"
sharedRegexRouterLinkActiveTest="^\/kunde\/\d*\/customer"
sharedRegexRouterLinkActiveTest="^(\/kunde\/\d*\/customer|\/\d*\/reward)"
(isActiveChange)="customerActive($event); focusSearchBox()"
>
<span class="side-menu-group-item-icon">
@@ -32,11 +34,11 @@
<span class="side-menu-group-item-label">Kunden</span>
<button
class="side-menu-group-arrow"
[class.side-menu-item-rotate]="customerExpanded"
[class.side-menu-item-rotate]="customerExpanded()"
(click)="
$event.stopPropagation();
$event.preventDefault();
customerExpanded = !customerExpanded
toggleCustomerExpanded()
"
>
<shared-icon icon="keyboard-arrow-down"></shared-icon>
@@ -44,13 +46,16 @@
</a>
}
<div class="side-menu-group-sub-items" [class.hidden]="!customerExpanded">
@if (customerSearchRoute$ | async; as customerSearchRoute) {
<div
class="side-menu-group-sub-items"
[class.hidden]="!customerExpanded()"
>
@if (customerSearchRoute() || customerRewardRoute()) {
<a
class="side-menu-group-item"
(click)="closeSideMenu(); focusSearchBox()"
[routerLink]="customerSearchRoute.path"
[queryParams]="customerSearchRoute.queryParams"
[routerLink]="customerSearchRoute().path"
[queryParams]="customerSearchRoute().queryParams"
sharedRegexRouterLinkActive="active"
sharedRegexRouterLinkActiveTest="^\/kunde\/\d*\/customer\/(\(search|search)"
(isActiveChange)="focusSearchBox()"
@@ -59,12 +64,12 @@
<span class="side-menu-group-item-label">Suchen</span>
</a>
}
@if (customerCreateRoute$ | async; as customerCreateRoute) {
@if (customerCreateRoute() || customerRewardRoute()) {
<a
class="side-menu-group-item"
(click)="closeSideMenu()"
[routerLink]="customerCreateRoute.path"
[queryParams]="customerCreateRoute.queryParams"
[routerLink]="customerCreateRoute().path"
[queryParams]="customerCreateRoute().queryParams"
sharedRegexRouterLinkActive="active"
sharedRegexRouterLinkActiveTest="^\/kunde\/\d*\/customer\/(\(create|create)"
>
@@ -72,6 +77,19 @@
<span class="side-menu-group-item-label">Erfassen</span>
</a>
}
<!-- @if (customerRewardRoute()) {
<a
class="side-menu-group-item"
(click)="closeSideMenu(); focusSearchBox()"
[routerLink]="customerRewardRoute()"
(isActiveChange)="focusSearchBox()"
sharedRegexRouterLinkActive="active"
sharedRegexRouterLinkActiveTest="^\/\d*\/reward"
>
<span class="side-menu-group-item-icon"> </span>
<span class="side-menu-group-item-label">Prämienshop</span>
</a>
} -->
</div>
</div>
@@ -93,11 +111,7 @@
*ifRole="'Store'"
class="side-menu-group-item"
(click)="closeSideMenu(); focusSearchBox()"
[routerLink]="[
'/',
processService.activatedTab()?.id || processService.nextId(),
'return',
]"
[routerLink]="['/', tabId(), 'return']"
(isActiveChange)="focusSearchBox()"
>
<span class="side-menu-group-item-icon w-[2.375rem] h-12">
@@ -258,11 +272,7 @@
<a
class="side-menu-group-item"
(click)="closeSideMenu(); focusSearchBox()"
[routerLink]="[
'/',
processService.activatedTab()?.id || processService.nextId(),
'remission',
]"
[routerLink]="['/', tabId(), 'remission']"
(isActiveChange)="focusSearchBox(); remissionExpanded.set($event)"
routerLinkActive="active"
#rlActive="routerLinkActive"
@@ -288,11 +298,7 @@
<a
class="side-menu-group-item"
(click)="closeSideMenu(); focusSearchBox()"
[routerLink]="[
'/',
processService.activatedTab()?.id || processService.nextId(),
'remission',
]"
[routerLink]="['/', tabId(), 'remission']"
(isActiveChange)="focusSearchBox()"
sharedRegexRouterLinkActive="active"
sharedRegexRouterLinkActiveTest="^\/\d*\/remission\/(mandatory|department)"
@@ -303,12 +309,7 @@
<a
class="side-menu-group-item"
(click)="closeSideMenu(); focusSearchBox()"
[routerLink]="[
'/',
processService.activatedTab()?.id || processService.nextId(),
'remission',
'return-receipt',
]"
[routerLink]="['/', tabId(), 'remission', 'return-receipt']"
(isActiveChange)="focusSearchBox()"
sharedRegexRouterLinkActive="active"
sharedRegexRouterLinkActiveTest="^\/\d*\/remission\/return-receipt"

View File

@@ -1,7 +1,7 @@
import {
Component,
ChangeDetectionStrategy,
Inject,
computed,
ChangeDetectorRef,
inject,
DOCUMENT,
@@ -29,10 +29,12 @@ import {
PickUpShelfOutNavigationService,
ProductCatalogNavigationService,
} from '@shared/services/navigation';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { TabService } from '@isa/core/tabs';
import { NgIconComponent, provideIcons } from '@ng-icons/core';
import { isaNavigationRemission2, isaNavigationReturn } from '@isa/icons';
import z from 'zod';
@Component({
selector: 'shell-side-menu',
@@ -68,7 +70,21 @@ export class ShellSideMenuComponent {
#pickUpShelfInNavigation = inject(PickupShelfInNavigationService);
#cdr = inject(ChangeDetectorRef);
#document = inject(DOCUMENT);
processService = inject(TabService);
tabService = inject(TabService);
staticTabIds = Object.values(
this.#config.get('process.ids', z.record(z.coerce.number())),
);
tabId = computed(() => {
const tabId = this.tabService.activatedTab()?.id;
if (this.staticTabIds.includes(tabId)) {
return this.nextId();
}
return tabId || this.nextId();
});
tabId$ = toObservable(this.tabId);
branchKey$ = this.#stockService.StockCurrentBranch().pipe(
retry(3),
@@ -93,6 +109,10 @@ export class ShellSideMenuComponent {
return this.#environment.matchTablet();
}
nextId() {
return Date.now();
}
customerBasePath$ = this.activeProcess$.pipe(
map((process) => {
if (
@@ -109,18 +129,28 @@ export class ShellSideMenuComponent {
}),
);
customerSearchRoute$ = this.getLastActivatedCustomerProcessId$().pipe(
map((processId) => {
return this.#customerSearchNavigation.defaultRoute({ processId });
}),
customerSearchRoute = toSignal(
this.getLastActivatedCustomerProcessId$().pipe(
map((processId) => {
return this.#customerSearchNavigation.defaultRoute({ processId });
}),
),
);
customerCreateRoute$ = this.getLastActivatedCustomerProcessId$().pipe(
map((processId) => {
return this.#customerCreateNavigation.defaultRoute({ processId });
}),
customerCreateRoute = toSignal(
this.getLastActivatedCustomerProcessId$().pipe(
map((processId) => {
return this.#customerCreateNavigation.defaultRoute({ processId });
}),
),
);
customerRewardRoute = computed(() => {
const routeName = 'reward';
const tabId = this.tabService.activatedTab()?.id;
return this.#router.createUrlTree(['/', tabId || this.nextId(), routeName]);
});
pickUpShelfOutRoutePath$ = this.getLastActivatedCustomerProcessId$().pipe(
map((processId) => {
if (processId) {
@@ -204,26 +234,25 @@ export class ShellSideMenuComponent {
}
shelfExpanded = false;
customerExpanded = false;
customerExpanded = signal(false);
remissionExpanded = signal(false);
customerActive(isActive: boolean) {
if (isActive) {
this.expandCustomer();
this.customerExpanded.set(true);
}
}
toggleCustomerExpanded() {
this.customerExpanded.set(!this.customerExpanded());
}
shelfActive(isActive: boolean) {
if (isActive) {
this.expandShelf();
}
}
expandCustomer() {
this.customerExpanded = true;
this.#cdr.markForCheck();
}
expandShelf() {
this.shelfExpanded = true;
this.#cdr.markForCheck();
@@ -322,23 +351,7 @@ export class ShellSideMenuComponent {
}
getLastActivatedCustomerProcessId$() {
return this.#app.getProcesses$('customer').pipe(
map((processes) => {
const lastCustomerProcess = processes
.filter((process) => process.type === 'cart')
.reduce((last, current) => {
if (!last) return current;
if (last.activated > current.activated) {
return last;
} else {
return current;
}
}, undefined);
return lastCustomerProcess?.id ?? Date.now();
}),
);
return this.tabId$;
}
closeSideMenu() {

View File

@@ -0,0 +1,59 @@
import {
argsToTemplate,
moduleMetadata,
type Meta,
type StoryObj,
} from '@storybook/angular';
import {
InlineInputComponent,
InputControlDirective,
} from '@isa/ui/input-controls';
const meta: Meta<InlineInputComponent> = {
component: InlineInputComponent,
title: 'ui/input-controls/InlineInput',
argTypes: {
size: { control: 'select', options: ['small', 'medium'] },
},
args: {
size: 'medium',
},
decorators: [
moduleMetadata({
imports: [InputControlDirective],
}),
],
render: (args) => ({
props: args,
template: `
<ui-inline-input ${argsToTemplate(args)}>
<input type="text" placeholder="Enter inline text" />
</ui-inline-input>
`,
}),
};
export default meta;
type Story = StoryObj<InlineInputComponent>;
export const Primary: Story = {
args: {
size: 'medium',
},
};
export const WithLabel: Story = {
args: {
size: 'medium',
},
render: (args) => ({
props: args,
template: `
<ui-inline-input ${argsToTemplate(args)}>
<label>Label</label>
<input type="text" placeholder="Enter inline text" />
</ui-inline-input>
`,
}),
};

View File

@@ -12,7 +12,7 @@ variables:
value: '4'
# Minor Version einstellen
- name: 'Minor'
value: '1'
value: '2'
- name: 'Patch'
value: "$[counter(format('{0}.{1}', variables['Major'], variables['Minor']),0)]"
- name: 'BuildUniqueID'

200
docs/architecture/README.md Normal file
View File

@@ -0,0 +1,200 @@
# Architecture Decision Records (ADRs)
## Overview
Architecture Decision Records (ADRs) are lightweight documents that capture important architectural decisions made during the development of the ISA-Frontend project. They provide context for why certain decisions were made, helping current and future team members understand the reasoning behind architectural choices.
## What are ADRs?
An Architecture Decision Record is a document that captures a single architectural decision and its rationale. The goal of an ADR is to document the architectural decisions that are being made so that:
- **Future team members** can understand why certain decisions were made
- **Current team members** can refer back to the reasoning behind decisions
- **Architectural evolution** can be tracked over time
- **Knowledge transfer** is facilitated during team changes
## ADR Structure
Each ADR follows a consistent structure based on our [TEMPLATE.md](./TEMPLATE.md) and includes:
- **Problem Statement**: What architectural challenge needs to be addressed
- **Decision**: The architectural decision made
- **Rationale**: Why this decision was chosen
- **Consequences**: Both positive and negative outcomes of the decision
- **Alternatives**: Other options that were considered
- **Implementation**: Technical details and examples
- **Status**: Current state of the decision (Draft, Approved, Superseded, etc.)
## Naming Convention
ADRs should follow this naming pattern:
```
NNNN-short-descriptive-title.md
```
Where:
- `NNNN` is a 4-digit sequential number (e.g., 0001, 0002, 0003...)
- `short-descriptive-title` uses kebab-case and briefly describes the decision
- `.md` indicates it's a Markdown file
### Examples:
- `0001-use-standalone-components.md`
- `0002-adopt-ngrx-signals.md`
- `0003-implement-micro-frontend-architecture.md`
- `0004-choose-vitest-over-jest.md`
## Process Guidelines
### 1. When to Create an ADR
Create an ADR when making decisions about:
- **Architecture patterns** (e.g., micro-frontends, monorepo structure)
- **Technology choices** (e.g., testing frameworks, state management)
- **Development practices** (e.g., code organization, build processes)
- **Technical standards** (e.g., coding conventions, performance requirements)
- **Infrastructure decisions** (e.g., deployment strategies, CI/CD processes)
### 2. ADR Lifecycle
```
Draft → Under Review → Approved → [Superseded/Deprecated]
```
- **Draft**: Initial version, being written
- **Under Review**: Shared with team for feedback and discussion
- **Approved**: Team has agreed and decision is implemented
- **Superseded**: Replaced by a newer ADR
- **Deprecated**: No longer applicable but kept for historical reference
### 3. Creation Process
1. **Identify the Need**: Recognize an architectural decision needs documentation
2. **Create from Template**: Copy [TEMPLATE.md](./TEMPLATE.md) to create new ADR
3. **Fill in Content**: Complete all sections with relevant information
4. **Set Status to Draft**: Mark the document as "Draft" initially
5. **Share for Review**: Present to team for discussion and feedback
6. **Iterate**: Update based on team input
7. **Approve**: Once consensus is reached, mark as "Approved"
8. **Implement**: Begin implementation of the architectural decision
### 4. Review Process
- **Author Review**: Self-review for completeness and clarity
- **Peer Review**: Share with relevant team members for technical review
- **Architecture Review**: Present in architecture meetings if significant
- **Final Approval**: Get sign-off from technical leads/architects
## Angular/Nx Specific Considerations
When writing ADRs for this project, consider these Angular/Nx specific aspects:
### Architecture Decisions
- **Library organization** in the monorepo structure
- **Dependency management** between applications and libraries
- **Feature module vs. standalone component** approaches
- **State management patterns** (NgRx, Signals, Services)
- **Routing strategies** for large applications
### Technical Decisions
- **Build optimization** strategies using Nx
- **Testing approaches** for different types of libraries
- **Code sharing patterns** across applications
- **Performance optimization** techniques
- **Bundle splitting** and lazy loading strategies
### Development Workflow
- **Nx executor usage** for custom tasks
- **Generator patterns** for code scaffolding
- **Linting and formatting** configurations
- **CI/CD pipeline** optimizations using Nx affected commands
## Template Usage
### Getting Started
1. Copy the [TEMPLATE.md](./TEMPLATE.md) file
2. Rename it following the naming convention
3. Replace placeholder text with actual content
4. Focus on the "why" not just the "what"
5. Include concrete examples and code snippets
6. Consider both immediate and long-term consequences
### Key Template Sections
- **Decision**: State the architectural decision clearly and concisely
- **Context**: Provide background information and constraints
- **Consequences**: Be honest about both benefits and drawbacks
- **Implementation**: Include practical examples relevant to Angular/Nx
- **Alternatives**: Show you considered other options
## Examples of Good ADRs
Here are some example titles that would make good ADRs for this project:
- **State Management**: "0001-adopt-ngrx-signals-for-component-state.md"
- **Testing Strategy**: "0002-use-angular-testing-utilities-over-spectator.md"
- **Code Organization**: "0003-implement-domain-driven-library-structure.md"
- **Performance**: "0004-implement-lazy-loading-for-feature-modules.md"
- **Build Process**: "0005-use-nx-cloud-for-distributed-task-execution.md"
## Best Practices
### Writing Effective ADRs
1. **Be Concise**: Keep it focused and to the point
2. **Be Specific**: Include concrete examples and implementation details
3. **Be Honest**: Document both pros and cons honestly
4. **Be Timely**: Write ADRs close to when decisions are made
5. **Be Collaborative**: Involve relevant team members in the process
### Maintenance
- **Review Regularly**: Check ADRs during architecture reviews
- **Update Status**: Keep status current as decisions evolve
- **Link Related ADRs**: Reference connected decisions
- **Archive Outdated**: Mark superseded ADRs appropriately
### Code Examples
When including code examples:
- Use actual project syntax and patterns
- Include both TypeScript and template examples where relevant
- Show before/after scenarios for changes
- Reference specific files in the codebase when possible
## Tools and Integration
### Recommended Tools
- **Markdown Editor**: Use any markdown-capable editor
- **Version Control**: All ADRs are tracked in Git
- **Review Process**: Use PR reviews for ADR approval
- **Documentation**: Link ADRs from relevant code comments
### Integration with Development
- Reference ADR numbers in commit messages when implementing decisions
- Include ADR links in PR descriptions for architectural changes
- Update ADRs when decisions need modification
- Use ADRs as reference during code reviews
## Getting Help
### Questions or Issues?
- **Team Discussions**: Bring up in team meetings or Slack
- **Architecture Review**: Present in architecture meetings
- **Documentation**: Update this README if process improvements are needed
### Resources
- [Architecture Decision Records (ADRs) - Michael Nygard](https://cognitect.com/blog/2011/11/15/documenting-architecture-decisions)
- [ADR GitHub Organization](https://adr.github.io/)
- [Nx Documentation](https://nx.dev/getting-started/intro)
- [Angular Architecture Guide](https://angular.dev/guide/architecture)
---
*This ADR system helps maintain architectural consistency and knowledge sharing across the ISA-Frontend project. Keep it updated and use it regularly for the best results.*

View File

@@ -0,0 +1,138 @@
# ADR NNNN: <short-descriptive-title>
| Field | Value |
|-------|-------|
| Status | Draft / Under Review / Approved / Superseded by ADR NNNN / Deprecated |
| Date | YYYY-MM-DD |
| Owners | <author(s)> |
| Participants | <key reviewers / stakeholders> |
| Related ADRs | NNNN (title), NNNN (title) |
| Tags | architecture, <domain>, <category> |
---
## Summary (Decision in One Sentence)
Concise statement of the architectural decision. Avoid rationale here—just the what.
## Context & Problem Statement
Describe the background and the problem this decision addresses.
- Business drivers / user needs
- Technical constraints (performance, security, scalability, compliance, legacy, regulatory)
- Current pain points / gaps
- Measurable goals / success criteria (e.g. reduce build time by 30%)
### Scope
What is in scope and explicitly out of scope for this decision.
## Decision
State the decision clearly (active voice). Include high-level approach or pattern selection, not implementation detail.
## Rationale
Why this option was selected:
- Alignment with strategic/technical direction
- Trade-offs considered
- Data, benchmarks, experiments, spikes
- Impact on developer experience / velocity
- Long-term maintainability & extensibility
## Alternatives Considered
| Alternative | Summary | Pros | Cons | Reason Not Chosen |
|-------------|---------|------|------|-------------------|
| Option A | | | | |
| Option B | | | | |
| Option C | | | | |
Add deeper detail below if needed:
### Option A <name>
### Option B <name>
### Option C <name>
## Consequences
### Positive
-
### Negative / Risks / Debt Introduced
-
### Neutral / Open Questions
-
## Implementation Plan
High-level rollout strategy. Break into phases if applicable.
1. Phase 0 Spike / Validation
2. Phase 1 Foundation / Infrastructure
3. Phase 2 Incremental Adoption / Migration
4. Phase 3 Hardening / Optimization
5. Phase 4 Decommission Legacy
### Tasks / Workstreams
- Infra / tooling changes
- Library additions (Nx generators, new libs under `libs/<domain>`)
- Refactors / migrations
- Testing strategy updates (Jest → Vitest, Signals adoption, etc.)
- Documentation & onboarding materials
### Acceptance Criteria
List objective criteria to mark implementation complete.
### Rollback Plan
How to revert safely if outcomes are negative.
## Architectural Impact
### Nx / Monorepo Layout
Describe changes to library boundaries, tags, dependency graph, affected projects.
### Module / Library Design
New or modified public APIs (`src/index.ts` changes, path aliases additions to `tsconfig.base.json`).
### State Management
Implications for Signals, NgRx, resource factories, persistence patterns (`withStorage`).
### Runtime & Performance
Bundle size, lazy loading, code splitting, caching, SSR/hydration considerations.
### Security & Compliance
AuthZ/AuthN, token handling, data residency, PII, secure storage.
### Observability & Logging
Logging contexts (`@isa/core/logging`), metrics, tracing hooks.
### DX / Tooling
Generators, lint rules, schematic updates, local dev flow.
## Detailed Design Elements
(Optional deeper technical articulation.)
- Sequence diagrams / component diagrams
- Data flow / async flow
- Error handling strategy
- Concurrency / cancellation (e.g. `rxMethod` + `switchMap` usage)
- Abstractions & extension points
## Code Examples
### Before
```ts
// Previous approach (simplified)
```
### After
```ts
// New approach (simplified)
```
### Migration Snippet
```ts
// Example incremental migration pattern
```
## Open Questions / Follow-Ups
- Unresolved design clarifications
- Dependent ADRs required
- External approvals needed
## Decision Review & Revalidation
When and how this ADR will be re-evaluated (date, trigger conditions, metrics thresholds).
## Status Log
| Date | Change | Author |
|------|--------|--------|
| YYYY-MM-DD | Created (Draft) | |
| YYYY-MM-DD | Approved | |
| YYYY-MM-DD | Superseded by ADR NNNN | |
## References
- Links to spike notes, benchmark results
- External articles, standards, RFCs
- Related code PRs / commits
---
> Document updates MUST reference this ADR number in commit messages: `ADR-NNNN:` prefix.
> Keep this document updated through all lifecycle stages.

View File

@@ -0,0 +1,350 @@
# ADR 0001: Implement `data-access` API Requests
| Field | Value |
|-------|-------|
| Status | Draft |
| Date | 29.09.2025 |
| Owners | Lorenz, Nino |
| Participants | N/A |
| Related ADRs | N/A |
| Tags | architecture, data-access, library, swagger |
---
## Summary (Decision in One Sentence)
Standardize all data-access libraries with a three-layer architecture: Zod schemas for validation, domain models extending generated DTOs, and services with consistent error handling and logging.
## Context & Problem Statement
Inconsistent patterns across data-access libraries (`catalogue`, `remission`, `crm`, `oms`) cause:
- High cognitive load when switching domains
- Duplicated validation and error handling code
- Mixed approaches to request cancellation and logging
- No standard for extending generated DTOs
**Goals:** Standardize structure, reduce boilerplate 40%, eliminate validation runtime errors, improve type safety.
**Constraints:** Must integrate with generated Swagger clients, support AbortSignal, align with `@isa/core/logging`.
**Scope:** Schema validation, model extensions, service patterns, standard exports.
## Decision
Implement a **three-layer architecture** for all data-access libraries:
1. **Schema Layer** (`schemas/`): Zod schemas for input validation and type inference
- Pattern: `<Operation>Schema` with `<Operation>` and `<Operation>Input` types
- Example: `SearchItemsSchema`, `SearchItems`, `SearchItemsInput`
2. **Model Layer** (`models/`): Domain-specific interfaces extending generated DTOs
- Pattern: `interface MyModel extends GeneratedDTO { ... }`
- Use `EntityContainer<T>` for lazy-loaded relationships
3. **Service Layer** (`services/`): Injectable services integrating Swagger clients
- Pattern: Async methods with AbortSignal support
- Standardized error handling with `ResponseArgsError`
- Structured logging via `@isa/core/logging`
**Standard exports structure:**
```typescript
// src/index.ts
export * from './lib/models';
export * from './lib/schemas';
export * from './lib/services';
// Optional: stores, helpers
```
## Rationale
**Why this approach:**
- **Type Safety**: Zod provides runtime validation + compile-time types with zero manual type definitions
- **Separation of Concerns**: Clear boundaries between validation, domain logic, and API integration
- **Consistency**: Identical patterns across all domains reduce cognitive load
- **Maintainability**: Changes to generated clients don't break domain-specific enhancements
- **Developer Experience**: Auto-completion, type inference, and standardized error handling improve velocity
**Evidence supporting this decision:**
- Analysis of 4 existing data-access libraries shows these patterns emerging naturally
- `RemissionReturnReceiptService` demonstrates successful integration with logging
- `EntityContainer<T>` pattern proven effective for relationship management
- Zod validation catches input errors before API calls, reducing backend load
## Consequences
**Positive:** Consistent patterns, runtime + compile-time type safety, clear maintainability, reusable utilities, structured debugging, optimized performance.
**Negative:** Migration effort for existing libs, learning curve for Zod, ~1-2ms validation overhead, extra abstraction layer.
**Open Questions:** User-facing error message conventions, testing standards.
## Detailed Design Elements
### Schema Validation Pattern
**Structure:**
```typescript
// Input validation schema
export const SearchByTermSchema = z.object({
searchTerm: z.string().min(1, 'Search term must not be empty'),
skip: z.number().int().min(0).default(0),
take: z.number().int().min(1).max(100).default(20),
});
// Type inference
export type SearchByTerm = z.infer<typeof SearchByTermSchema>;
export type SearchByTermInput = z.input<typeof SearchByTermSchema>;
```
### Model Extension Pattern
**Generated DTO Extension:**
```typescript
import { ProductDTO } from '@generated/swagger/cat-search-api';
export interface Product extends ProductDTO {
name: string;
contributors: string;
catalogProductNumber: string;
// Domain-specific enhancements
}
```
**Entity Container Pattern:**
```typescript
export interface Return extends ReturnDTO {
id: number;
receipts: EntityContainer<Receipt>[]; // Lazy-loaded relationships
}
```
### Service Implementation Pattern
**Standard service structure:**
```typescript
@Injectable({ providedIn: 'root' })
export class DomainService {
#apiService = inject(GeneratedApiService);
#logger = logger(() => ({ service: 'DomainService' }));
async fetchData(params: InputType, abortSignal?: AbortSignal): Promise<ResultType> {
const validated = ValidationSchema.parse(params);
let req$ = this.#apiService.operation(validated);
if (abortSignal) {
req$ = req$.pipe(takeUntilAborted(abortSignal));
}
const res = await firstValueFrom(req$);
if (res.error) {
this.#logger.error('Operation failed', new Error(res.message));
throw new ResponseArgsError(res);
}
return res.result as ResultType;
}
}
```
### Error Handling Strategy
1. **Input Validation**: Zod schemas validate and transform inputs
2. **API Error Handling**: Check `res.error` from generated clients
3. **Structured Logging**: Log errors with context via `@isa/core/logging`
4. **Error Propagation**: Throw `ResponseArgsError` for consistent handling
### Concurrency & Cancellation
- **AbortSignal Support**: All async operations accept optional AbortSignal
- **RxJS Integration**: Use `takeUntilAborted` operator for cancellation
- **Promise Pattern**: `firstValueFrom` prevents subscription memory leaks
- **Caching**: `@InFlight` decorator prevents duplicate concurrent requests
### Extension Points
- **Custom Decorators**: `@Cache`, `@InFlight`, `@CacheTimeToLive`
- **Schema Transformations**: Zod `.transform()` for data normalization
- **Model Inheritance**: Interface extension for domain-specific properties
- **Service Composition**: Services can depend on other domain services
## Code Examples
### Complete Data-Access Library Structure
See full examples in existing implementations:
- `libs/catalogue/data-access` - Basic patterns
- `libs/remission/data-access` - Advanced with EntityContainer
- `libs/crm/data-access` - Service examples
- `libs/oms/data-access` - Model extensions
**Quick Reference:**
```typescript
// libs/domain/data-access/src/lib/schemas/fetch-items.schema.ts
import { z } from 'zod';
export const FetchItemsSchema = z.object({
categoryId: z.string().min(1),
skip: z.number().int().min(0).default(0),
take: z.number().int().min(1).max(100).default(20),
filters: z.record(z.any()).default({}),
});
export type FetchItems = z.infer<typeof FetchItemsSchema>;
export type FetchItemsInput = z.input<typeof FetchItemsSchema>;
// libs/domain/data-access/src/lib/models/item.ts
import { ItemDTO } from '@generated/swagger/domain-api';
import { EntityContainer } from '@isa/common/data-access';
import { Category } from './category';
export interface Item extends ItemDTO {
id: number;
displayName: string;
category: EntityContainer<Category>;
// Domain-specific enhancements
isAvailable: boolean;
formattedPrice: string;
}
// Service
@Injectable({ providedIn: 'root' })
export class ItemService {
#itemService = inject(GeneratedItemService);
#logger = logger(() => ({ service: 'ItemService' }));
async fetchItems(
params: FetchItemsInput,
abortSignal?: AbortSignal
): Promise<Item[]> {
this.#logger.debug('Fetching items', () => ({ params }));
const { categoryId, skip, take, filters } = FetchItemsSchema.parse(params);
let req$ = this.#itemService.getItems({
categoryId,
queryToken: { skip, take, filter: filters }
});
if (abortSignal) {
req$ = req$.pipe(takeUntilAborted(abortSignal));
}
const res = await firstValueFrom(req$);
if (res.error) {
this.#logger.error('Failed to fetch items', new Error(res.message));
throw new ResponseArgsError(res);
}
this.#logger.info('Successfully fetched items', () => ({
count: res.result?.length || 0
}));
return res.result as Item[];
}
}
// libs/domain/data-access/src/index.ts
export * from './lib/models';
export * from './lib/schemas';
export * from './lib/services';
```
### Usage in Feature Components
```typescript
// feature component using the data-access library
import { Component, inject, signal } from '@angular/core';
import { ItemService, Item, FetchItemsInput } from '@isa/domain/data-access';
@Component({
selector: 'app-item-list',
template: `
@if (loading()) {
<div>Loading...</div>
} @else {
@for (item of items(); track item.id) {
<div>{{ item.displayName }}</div>
}
}
`
})
export class ItemListComponent {
#itemService = inject(ItemService);
items = signal<Item[]>([]);
loading = signal(false);
async loadItems(categoryId: string) {
this.loading.set(true);
try {
const params: FetchItemsInput = {
categoryId,
take: 50,
filters: { active: true }
};
const items = await this.#itemService.fetchItems(params);
this.items.set(items);
} catch (error) {
console.error('Failed to load items', error);
} finally {
this.loading.set(false);
}
}
}
```
### Migration Pattern for Existing Services
```typescript
// Before: Direct HTTP client usage
@Injectable()
export class LegacyItemService {
constructor(private http: HttpClient) {}
getItems(categoryId: string): Observable<any> {
return this.http.get(`/api/items?category=${categoryId}`);
}
}
// After: Standardized data-access pattern
@Injectable({ providedIn: 'root' })
export class ItemService {
#itemService = inject(GeneratedItemService);
#logger = logger(() => ({ service: 'ItemService' }));
async fetchItems(params: FetchItemsInput, abortSignal?: AbortSignal): Promise<Item[]> {
const validated = FetchItemsSchema.parse(params);
// ... standard implementation pattern
}
}
```
## Open Questions / Follow-Ups
- Unresolved design clarifications
- Dependent ADRs required
- External approvals needed
## Decision Review & Revalidation
When and how this ADR will be re-evaluated (date, trigger conditions, metrics thresholds).
## Status Log
| Date | Change | Author |
|------|--------|--------|
| 2025-10-02 | Condensed for readability | Lorenz, Nino |
| 2025-09-29 | Created (Draft) | Lorenz |
| 2025-09-25 | Analysis completed, comprehensive patterns documented | Lorenz, Nino |
## References
**Existing Implementation Examples:**
- `libs/catalogue/data-access` - Basic schema and service patterns
- `libs/remission/data-access` - Advanced patterns with EntityContainer and stores
- `libs/common/data-access` - Shared utilities and response types
- `generated/swagger/` - Generated API clients integration
**Key Dependencies:**
- [Zod](https://github.com/colinhacks/zod) - Schema validation library
- [ng-swagger-gen](https://github.com/cyclosproject/ng-swagger-gen) - OpenAPI client generation
- `@isa/core/logging` - Structured logging infrastructure
- `@isa/common/data-access` - Shared utilities and types
**Related Documentation:**
- ISA Frontend Copilot Instructions - Data-access patterns
- Tech Stack Documentation - Architecture overview
- Code Style Guidelines - TypeScript and Angular patterns
---
> Document updates MUST reference this ADR number in commit messages: `ADR-NNNN:` prefix.
> Keep this document updated through all lifecycle stages.

View File

@@ -1,128 +1,136 @@
# Tech Stack Documentation
## Core Technologies
### Frontend Framework
- **[Angular](https://angular.dev/overview)** (Latest Version)
- Modern web framework for building scalable single-page applications
- Leverages TypeScript for enhanced type safety and developer experience
### State Management
- **[NgRx](https://ngrx.io/docs)**
- Redux-inspired state management for Angular applications
- Provides predictable state container and powerful dev tools
- Used for managing complex application state and side effects
### Styling
- **[Tailwind CSS](https://tailwindcss.com/)**
- Utility-first CSS framework
- Enables rapid UI development with pre-built classes
- Highly customizable through configuration
## Development Tools
### Language
- **[TypeScript](https://www.typescriptlang.org/docs/handbook/intro.html)**
- Strongly typed programming language
- Provides enhanced IDE support and compile-time error checking
- Used throughout the entire application
### Runtime
- **[Node.js](https://nodejs.org/docs/latest-v22.x/api/index.html)**
- JavaScript runtime environment
- Used for development server and build tools
- Required for running npm scripts and development tools
### Testing Framework
- **[Jest](https://jestjs.io/docs/getting-started)**
- Primary testing framework
- Used for unit and integration tests
- Provides snapshot testing capabilities
- **[Spectator](https://ngneat.github.io/spectator/)**
- Angular testing utility library
- Simplifies component testing
- Reduces boilerplate in test files
### UI Development
- **[Storybook](https://storybook.js.org/docs/get-started/frameworks/angular)**
- UI component development environment
- Enables isolated component development
- Serves as living documentation for components
### Utilities
- **[date-fns](https://date-fns.org/docs/Getting-Started)**
- Modern JavaScript date utility library
- Used for consistent date formatting and manipulation
- Tree-shakeable to optimize bundle size
- **[Lodash](https://lodash.com/)**
- Utility library for common JavaScript tasks
- **[UUID](https://www.npmjs.com/package/uuid)**
- Generates unique identifiers
- **[Zod](https://github.com/colinhacks/zod)**
- TypeScript-first schema validation library
## Additional Technical Areas
### Authentication & Authorization
- **[angular-oauth2-oidc](https://github.com/manfredsteyer/angular-oauth2-oidc)**
- Simplifies implementing OAuth2 and OIDC authentication in Angular.
- **[angular-oauth2-oidc-jwks](https://github.com/manfredsteyer/angular-oauth2-oidc)**
- Adds JWKS support for secure token management.
### Real-Time Communication
- **[@microsoft/signalr](https://www.npmjs.com/package/@microsoft/signalr)**
- Provides real-time communication between client and server components.
### Barcode Scanning
- **[Scandit Web Data Capture Barcode](https://www.scandit.com/documentation/web/)**
- Robust barcode scanning capabilities integrated into the application.
- **[Scandit Web Data Capture Core](https://www.scandit.com/documentation/web/)**
- Core library supporting the barcode scanning features.
### Tooling
- **[Nx](https://nx.dev/)**
- Powerful monorepo tool for Angular and other frontend applications.
- **[Husky](https://typicode.github.io/husky/#/)**
- Manages Git hooks for consistent developer workflows.
- **[ESLint](https://eslint.org/) & [Prettier](https://prettier.io/)**
- Linting and formatting tools to maintain consistent code quality.
- **[Storybook](https://storybook.js.org/)**
- Isolated component development and living documentation environment.
## Development Environment Setup
1. **Required Software**
- Node.js (Latest LTS version)
- npm (comes with Node.js)
- Git
2. **IDE Recommendations**
- Visual Studio Code with following extensions:
- Angular Language Service
- ESLint
- Prettier
- Tailwind CSS IntelliSense
3. **Getting Started**
```bash
npm install # Install dependencies
npm run start # Start development server
npm run test # Run tests
npm run storybook # Start Storybook
```
# Tech Stack Documentation
## Core Technologies
### Frontend Framework
- **[Angular](https://angular.dev/overview)** (Latest Version)
- Modern web framework for building scalable single-page applications
- Leverages TypeScript for enhanced type safety and developer experience
### State Management
- **[NgRx](https://ngrx.io/docs)**
- Redux-inspired state management for Angular applications
- Provides predictable state container and powerful dev tools
- Used for managing complex application state and side effects
### Styling
- **[Tailwind CSS](https://tailwindcss.com/)**
- Utility-first CSS framework
- Enables rapid UI development with pre-built classes
- Highly customizable through configuration
## Development Tools
### Language
- **[TypeScript](https://www.typescriptlang.org/docs/handbook/intro.html)**
- Strongly typed programming language
- Provides enhanced IDE support and compile-time error checking
- Used throughout the entire application
### Runtime
- **[Node.js](https://nodejs.org/docs/latest-v22.x/api/index.html)**
- JavaScript runtime environment
- Used for development server and build tools
- Required for running npm scripts and development tools
### Testing Framework
- **[Jest](https://jestjs.io/docs/getting-started)**
- Primary testing framework
- Used for unit and integration tests
- Provides snapshot testing capabilities
- **[Spectator](https://ngneat.github.io/spectator/)**
- Angular testing utility library
- Simplifies component testing
- Reduces boilerplate in test files
### UI Development
- **[Storybook](https://storybook.js.org/docs/get-started/frameworks/angular)**
- UI component development environment
- Enables isolated component development
- Serves as living documentation for components
### Utilities
- **[date-fns](https://date-fns.org/docs/Getting-Started)**
- Modern JavaScript date utility library
- Used for consistent date formatting and manipulation
- Tree-shakeable to optimize bundle size
- **[Lodash](https://lodash.com/)**
- Utility library for common JavaScript tasks
- **[UUID](https://www.npmjs.com/package/uuid)**
- Generates unique identifiers
- **[Zod](https://github.com/colinhacks/zod)**
- TypeScript-first schema validation library
## Additional Technical Areas
### Authentication & Authorization
- **[angular-oauth2-oidc](https://github.com/manfredsteyer/angular-oauth2-oidc)**
- Simplifies implementing OAuth2 and OIDC authentication in Angular.
- **[angular-oauth2-oidc-jwks](https://github.com/manfredsteyer/angular-oauth2-oidc)**
- Adds JWKS support for secure token management.
### Real-Time Communication
- **[@microsoft/signalr](https://www.npmjs.com/package/@microsoft/signalr)**
- Provides real-time communication between client and server components.
### Barcode Scanning
- **[Scandit Web Data Capture Barcode](https://www.scandit.com/documentation/web/)**
- Robust barcode scanning capabilities integrated into the application.
- **[Scandit Web Data Capture Core](https://www.scandit.com/documentation/web/)**
- Core library supporting the barcode scanning features.
### Tooling
- **[Nx](https://nx.dev/)**
- Powerful monorepo tool for Angular and other frontend applications.
- **[Husky](https://typicode.github.io/husky/#/)**
- Manages Git hooks for consistent developer workflows.
- **[ESLint](https://eslint.org/) & [Prettier](https://prettier.io/)**
- Linting and formatting tools to maintain consistent code quality.
- **[Storybook](https://storybook.js.org/)**
- Isolated component development and living documentation environment.
## Domain Libraries
### Customer Relationship Management (CRM)
- **`@isa/crm/data-access`**
- Handles data access logic for customer-related features.
- Contains services for fetching and managing customer data.
## Development Environment Setup
1. **Required Software**
- Node.js (Latest LTS version)
- npm (comes with Node.js)
- Git
2. **IDE Recommendations**
- Visual Studio Code with following extensions:
- Angular Language Service
- ESLint
- Prettier
- Tailwind CSS IntelliSense
3. **Getting Started**
```bash
npm install # Install dependencies
npm run start # Start development server
npm run test # Run tests
npm run storybook # Start Storybook
```

View File

@@ -31,8 +31,9 @@ const PARAMETER_CODEC = new ParameterCodec();
export class BaseService {
constructor(
protected config: CatConfiguration,
protected http: HttpClient,
) {}
protected http: HttpClient
) {
}
private _rootUrl: string = '';
@@ -56,7 +57,7 @@ export class BaseService {
*/
protected newParams(): HttpParams {
return new HttpParams({
encoder: PARAMETER_CODEC,
encoder: PARAMETER_CODEC
});
}
}

View File

@@ -4,6 +4,7 @@
* Auocomplete-Ergebnis
*/
export interface AutocompleteDTO {
/**
* Anzeige / Bezeichner
*/

View File

@@ -5,6 +5,7 @@ import { CatalogType } from './catalog-type';
* Suchabfrage
*/
export interface AutocompleteTokenDTO {
/**
* Katalogbereich
*/
@@ -13,7 +14,7 @@ export interface AutocompleteTokenDTO {
/**
* Filter
*/
filter?: { [key: string]: string };
filter?: {[key: string]: string};
/**
* Eingabe

View File

@@ -7,6 +7,7 @@ import { AvailabilityType } from './availability-type';
* Verfügbarkeit
*/
export interface AvailabilityDTO {
/**
* Voraussichtliches Lieferdatum
*/

View File

@@ -1,2 +1,2 @@
/* tslint:disable */
export type AvailabilityType = 0 | 1 | 2 | 32 | 256 | 512 | 1024 | 2048 | 4096 | 8192 | 16384;
export type AvailabilityType = 0 | 1 | 2 | 32 | 256 | 512 | 1024 | 2048 | 4096 | 8192 | 16384;

View File

@@ -1,2 +1,2 @@
/* tslint:disable */
export type Avoirdupois = 0 | 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128 | 256 | 512 | 1024 | 2048 | 4096;
export type Avoirdupois = 0 | 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128 | 256 | 512 | 1024 | 2048 | 4096;

View File

@@ -3,4 +3,4 @@
/**
* Katalogbereich
*/
export type CatalogType = 0 | 1 | 2 | 4;
export type CatalogType = 0 | 1 | 2 | 4;

View File

@@ -1,2 +1,2 @@
/* tslint:disable */
export type CRUDA = 0 | 1 | 2 | 4 | 8 | 16;
export type CRUDA = 0 | 1 | 2 | 4 | 8 | 16;

View File

@@ -1,2 +1,2 @@
/* tslint:disable */
export type DialogContentType = 0 | 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128;
export type DialogContentType = 0 | 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128;

View File

@@ -1,2 +1,2 @@
/* tslint:disable */
export type DialogSettings = 0 | 1 | 2 | 4;
export type DialogSettings = 0 | 1 | 2 | 4;

View File

@@ -2,7 +2,7 @@
import { TouchedBase } from './touched-base';
import { CRUDA } from './cruda';
import { EntityStatus } from './entity-status';
export interface EntityDTO extends TouchedBase {
export interface EntityDTO extends TouchedBase{
changed?: string;
created?: string;
cruda?: CRUDA;

View File

@@ -1,2 +1,2 @@
/* tslint:disable */
export type EntityStatus = 0 | 1 | 2 | 4 | 8;
export type EntityStatus = 0 | 1 | 2 | 4 | 8;

View File

@@ -4,6 +4,7 @@
* Bild
*/
export interface ImageDTO {
/**
* Copyright
*/

View File

@@ -1,2 +1,2 @@
/* tslint:disable */
export type InputType = 0 | 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128 | 256 | 512 | 1024 | 2048 | 3072 | 4096 | 8192 | 12288;
export type InputType = 0 | 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128 | 256 | 512 | 1024 | 2048 | 3072 | 4096 | 8192 | 12288;

View File

@@ -11,7 +11,8 @@ import { StockInfoDTO } from './stock-info-dto';
import { Successor } from './successor';
import { TextDTO } from './text-dto';
import { ItemType } from './item-type';
export interface ItemDTO extends EntityDTO {
export interface ItemDTO extends EntityDTO{
/**
* Verfügbarkeit laut Katalog
*/
@@ -30,7 +31,7 @@ export interface ItemDTO extends EntityDTO {
/**
* Weitere Artikel-IDs
*/
ids?: { [key: string]: number };
ids?: {[key: string]: number};
/**
* Primary image / Id des Hauptbilds
@@ -45,7 +46,7 @@ export interface ItemDTO extends EntityDTO {
/**
* Markierungen (Lesezeichen) wie (BOD, Prämie)
*/
labels?: { [key: string]: string };
labels?: {[key: string]: string};
/**
* Produkt-Stammdaten

View File

@@ -3,4 +3,4 @@
/**
* Artikel-/Produkttyp
*/
export type ItemType = 0 | 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128 | 256 | 512 | 1024 | 2048 | 4096 | 8192 | 16384 | 32768 | 65536;
export type ItemType = 0 | 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128 | 256 | 512 | 1024 | 2048 | 4096 | 8192 | 16384 | 32768 | 65536;

View File

@@ -1,5 +1,6 @@
/* tslint:disable */
export interface LesepunkteRequest {
/**
* Artikel ID
*/

View File

@@ -1,6 +1,6 @@
/* tslint:disable */
import { ResponseArgsOfIEnumerableOfAutocompleteDTO } from './response-args-of-ienumerable-of-autocomplete-dto';
export interface ListResponseArgsOfAutocompleteDTO extends ResponseArgsOfIEnumerableOfAutocompleteDTO {
export interface ListResponseArgsOfAutocompleteDTO extends ResponseArgsOfIEnumerableOfAutocompleteDTO{
completed?: boolean;
hits?: number;
skip?: number;

View File

@@ -1,6 +1,6 @@
/* tslint:disable */
import { ResponseArgsOfIEnumerableOfItemDTO } from './response-args-of-ienumerable-of-item-dto';
export interface ListResponseArgsOfItemDTO extends ResponseArgsOfIEnumerableOfItemDTO {
export interface ListResponseArgsOfItemDTO extends ResponseArgsOfIEnumerableOfItemDTO{
completed?: boolean;
hits?: number;
skip?: number;

View File

@@ -2,7 +2,7 @@
import { TouchedBase } from './touched-base';
import { PriceValueDTO } from './price-value-dto';
import { VATValueDTO } from './vatvalue-dto';
export interface PriceDTO extends TouchedBase {
export interface PriceDTO extends TouchedBase{
value?: PriceValueDTO;
vat?: VATValueDTO;
}

View File

@@ -1,6 +1,6 @@
/* tslint:disable */
import { TouchedBase } from './touched-base';
export interface PriceValueDTO extends TouchedBase {
export interface PriceValueDTO extends TouchedBase{
currency?: string;
currencySymbol?: string;
value?: number;

View File

@@ -1,7 +1,7 @@
/* tslint:disable */
export interface ProblemDetails {
detail?: string;
extensions: { [key: string]: any };
extensions: {[key: string]: any};
instance?: string;
status?: number;
title?: string;

View File

@@ -2,7 +2,7 @@
import { TouchedBase } from './touched-base';
import { SizeOfString } from './size-of-string';
import { WeightOfAvoirdupois } from './weight-of-avoirdupois';
export interface ProductDTO extends TouchedBase {
export interface ProductDTO extends TouchedBase{
additionalName?: string;
catalogProductNumber?: string;
contributors?: string;

View File

@@ -1,7 +1,8 @@
/* tslint:disable */
import { QueryTokenDTO2 } from './query-token-dto2';
import { CatalogType } from './catalog-type';
export interface QueryTokenDTO extends QueryTokenDTO2 {
export interface QueryTokenDTO extends QueryTokenDTO2{
/**
* Katalogbereich
*/

View File

@@ -1,13 +1,13 @@
/* tslint:disable */
import { OrderByDTO } from './order-by-dto';
export interface QueryTokenDTO2 {
filter?: { [key: string]: string };
filter?: {[key: string]: string};
friendlyName?: string;
fuzzy?: number;
hitsOnly?: boolean;
ids?: Array<number>;
input?: { [key: string]: string };
options?: { [key: string]: string };
input?: {[key: string]: string};
options?: {[key: string]: string};
orderBy?: Array<OrderByDTO>;
skip?: number;
take?: number;

View File

@@ -1,5 +1,5 @@
/* tslint:disable */
import { ResponseArgs } from './response-args';
export interface ResponseArgsOfIDictionaryOfLongAndNullableInteger extends ResponseArgs {
result?: { [key: string]: number };
export interface ResponseArgsOfIDictionaryOfLongAndNullableInteger extends ResponseArgs{
result?: {[key: string]: number};
}

View File

@@ -1,6 +1,6 @@
/* tslint:disable */
import { ResponseArgs } from './response-args';
import { AutocompleteDTO } from './autocomplete-dto';
export interface ResponseArgsOfIEnumerableOfAutocompleteDTO extends ResponseArgs {
export interface ResponseArgsOfIEnumerableOfAutocompleteDTO extends ResponseArgs{
result?: Array<AutocompleteDTO>;
}

View File

@@ -1,6 +1,6 @@
/* tslint:disable */
import { ResponseArgs } from './response-args';
import { InputGroupDTO } from './input-group-dto';
export interface ResponseArgsOfIEnumerableOfInputGroupDTO extends ResponseArgs {
export interface ResponseArgsOfIEnumerableOfInputGroupDTO extends ResponseArgs{
result?: Array<InputGroupDTO>;
}

View File

@@ -1,6 +1,6 @@
/* tslint:disable */
import { ResponseArgs } from './response-args';
import { ItemDTO } from './item-dto';
export interface ResponseArgsOfIEnumerableOfItemDTO extends ResponseArgs {
export interface ResponseArgsOfIEnumerableOfItemDTO extends ResponseArgs{
result?: Array<ItemDTO>;
}

View File

@@ -1,6 +1,6 @@
/* tslint:disable */
import { ResponseArgs } from './response-args';
import { OrderByDTO } from './order-by-dto';
export interface ResponseArgsOfIEnumerableOfOrderByDTO extends ResponseArgs {
export interface ResponseArgsOfIEnumerableOfOrderByDTO extends ResponseArgs{
result?: Array<OrderByDTO>;
}

View File

@@ -1,6 +1,6 @@
/* tslint:disable */
import { ResponseArgs } from './response-args';
import { QueryTokenDTO } from './query-token-dto';
export interface ResponseArgsOfIEnumerableOfQueryTokenDTO extends ResponseArgs {
export interface ResponseArgsOfIEnumerableOfQueryTokenDTO extends ResponseArgs{
result?: Array<QueryTokenDTO>;
}

View File

@@ -1,6 +1,6 @@
/* tslint:disable */
import { ResponseArgs } from './response-args';
import { ItemDTO } from './item-dto';
export interface ResponseArgsOfItemDTO extends ResponseArgs {
export interface ResponseArgsOfItemDTO extends ResponseArgs{
result?: ItemDTO;
}

View File

@@ -1,6 +1,6 @@
/* tslint:disable */
import { ResponseArgs } from './response-args';
import { UISettingsDTO } from './uisettings-dto';
export interface ResponseArgsOfUISettingsDTO extends ResponseArgs {
export interface ResponseArgsOfUISettingsDTO extends ResponseArgs{
result?: UISettingsDTO;
}

View File

@@ -3,7 +3,7 @@ import { DialogOfString } from './dialog-of-string';
export interface ResponseArgs {
dialog?: DialogOfString;
error: boolean;
invalidProperties?: { [key: string]: string };
invalidProperties?: {[key: string]: string};
message?: string;
requestId?: number;
}

View File

@@ -1,5 +1,6 @@
/* tslint:disable */
export interface ReviewDTO {
/**
* Autor
*/

View File

@@ -4,6 +4,7 @@
* Regalinfo
*/
export interface ShelfInfoDTO {
/**
* Sortiment
*/

View File

@@ -3,4 +3,5 @@
/**
* Shop
*/
export interface ShopDTO {}
export interface ShopDTO {
}

View File

@@ -4,6 +4,7 @@
* Eigenchaften
*/
export interface SpecDTO {
/**
* PK
*/

View File

@@ -5,6 +5,7 @@ import { StockStatus } from './stock-status';
* Bestandsinformation
*/
export interface StockInfoDTO {
/**
* Filiale PK
*/

View File

@@ -3,4 +3,4 @@
/**
* Dispositionsstatus
*/
export type StockStatus = 0 | 1 | 2 | 3 | 4;
export type StockStatus = 0 | 1 | 2 | 3 | 4;

View File

@@ -1,6 +1,7 @@
/* tslint:disable */
import { ProductDTO } from './product-dto';
export interface Successor extends ProductDTO {
export interface Successor extends ProductDTO{
/**
* PK
*/

View File

@@ -1,5 +1,6 @@
/* tslint:disable */
export interface TextDTO {
/**
* PK
*/

View File

@@ -1,2 +1,3 @@
/* tslint:disable */
export interface TouchedBase {}
export interface TouchedBase {
}

View File

@@ -1,5 +1,5 @@
/* tslint:disable */
export interface TranslationDTO {
target?: string;
values?: { [key: string]: string };
values?: {[key: string]: string};
}

View File

@@ -1,7 +1,8 @@
/* tslint:disable */
import { QuerySettingsDTO } from './query-settings-dto';
import { TranslationDTO } from './translation-dto';
export interface UISettingsDTO extends QuerySettingsDTO {
export interface UISettingsDTO extends QuerySettingsDTO{
/**
* Url Template für Detail-Bild
*/

View File

@@ -1,2 +1,2 @@
/* tslint:disable */
export type VATType = 0 | 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128;
export type VATType = 0 | 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128;

Some files were not shown because too many files have changed in this diff Show More