Compare commits

...

131 Commits

Author SHA1 Message Date
Nino
353864e2f0 hotfix(customer-card-deactivate): Hotfix due to Keycard ISA Login Error 2025-10-24 11:18:25 +02:00
Nino Righi
1b6b726036 Merged PR 1975: hotfix(remission-list): prioritize reload trigger over exact search
hotfix(remission-list): prioritize reload trigger over exact search

Fix navigation issue where reload searches were incorrectly applying
exact search logic, causing filters to be cleared when they should
be preserved during navigation.

Changes:
- Update remission-list.resource.ts to check reload trigger before
  exact search conditions
- Ensure reload trigger always clears input but preserves other query
  parameters
- Prevent exact search from overriding reload behavior
- Add explanatory comment for reload priority logic

This ensures proper filter state management when users navigate
between remission lists, maintaining expected behavior for both
reload and exact search scenarios.

Ref: #5387
2025-10-21 12:08:06 +00:00
Nino Righi
4c56f394c5 Merged PR 1972: hotfix(remission-list-item, remission-list-empty-state): improve empty state...
hotfix(remission-list-item, remission-list-empty-state): improve empty state logic and cleanup selected items on destroy

Refactor empty state display conditions in remission-list-empty-state component
to correctly handle search term validation. Move hasValidSearchTerm check to
parent condition to prevent displaying empty states during active searches.

Add ngOnDestroy lifecycle hook to remission-list-item component to properly
clean up selected quantities from the store when items are removed from the list.
This prevents memory leaks and ensures the store state remains synchronized with
the displayed items.

Changes:
- Move hasValidSearchTerm check in displayEmptyState computed signal to improve
  empty state display logic
- Implement OnDestroy interface in RemissionListItemComponent
- Add removeItem call in ngOnDestroy to clean up store state
- Add corresponding unit tests for the cleanup behavior

Ref: #5387
2025-10-17 12:09:55 +00:00
Nino Righi
a086111ab5 Merged PR 1966: Adjustments for #5320, #5360, #5361
Adjustments for #5320, #5360, #5361
2025-10-06 19:02:45 +00:00
Nino Righi
15a4718e58 Merged PR 1965: feat(remission-list): improve item update handling and UI feedback
feat(remission-list): improve item update handling and UI feedback

Enhance the remission list item management by introducing a more robust
update mechanism that tracks both item removal and impediment updates.
Previously, the component only tracked deletion progress, but now it
handles both deletion and update scenarios, allowing for better state
management and user feedback.

Key changes:
- Replace simple inProgress boolean with UpdateItem interface containing
  inProgress state, itemId, and optional impediment
- Update local items signal directly when items are removed or updated,
  eliminating unnecessary API calls and improving performance
- Add visual highlight to "Remi Menge ändern" button when dialog is open
  using a border style for better accessibility
- Improve error handling by tracking specific item operations
- Ensure selected items are properly removed from store when deleted
  or updated

The new approach optimizes list reloads by only fetching data when
necessary and provides clearer visual feedback during item operations.

Unit Tests updated also

Ref: #5361
2025-10-06 08:41:47 +00:00
Nino Righi
40592b4477 Merged PR 1964: feat(shared-filter): add canApply input to filter input menu components
feat(shared-filter): add canApply input to filter input menu components

Add canApply input parameter to FilterInputMenuButtonComponent and FilterInputMenuComponent to control when filter actions can be applied. Update RemissionListDepartmentElementsComponent to use canApply flag and implement rollback functionality when filter menu is closed without applying changes.

- Add canApply input to FilterInputMenuButtonComponent with default false
- Pass canApply parameter through to FilterInputMenuComponent
- Update remission department filter to use canApply=true
- Implement rollbackFilterInput method for filter state management
- Change selectedDepartments to selectedDepartment for single selection
- Update capacity resource to work with single department selection

Ref: #5320
2025-10-06 08:41:22 +00:00
Nino Righi
d430f544f0 Merged PR 1963: feat(utils): add scroll-top button component
feat(utils): add scroll-top button component

Add a reusable ScrollTopButtonComponent that provides smooth scrolling
to the top of a page or specific element. The component automatically
shows/hides based on scroll position and respects user's reduced motion
preferences.

Key features:
- Supports both window and element-specific scrolling
- Configurable position with sensible defaults
- Accessibility compliant with proper aria-label
- Respects prefers-reduced-motion media query
- Debounced scroll event handling for performance

Integrate the component into remission list and search dialog
components to improve user navigation experience.

Ref: #5360
2025-10-06 08:41:08 +00:00
Nino Righi
62e586cfda Merged PR 1951: fix(remission-list): ensure list reload after search dialog closes
fix(remission-list): ensure list reload after search dialog closes

Move reloadListAndReturnData() call outside the conditional block
to guarantee data refresh regardless of dialog result. Previously,
the list would only reload when items were selected, causing stale
data when the dialog was cancelled or closed without selection.

Ref: #5342
2025-09-16 12:41:05 +00:00
Nino Righi
304f8a64e5 Merged PR 1949: feat(isa-app): migrate remission navigation to tab-based routing system
feat(isa-app): migrate remission navigation to tab-based routing system

Replace hardcoded /filiale/remission routes with dynamic tab-based paths
using TabService. This enables proper process isolation and multi-tab
support for remission workflows.

Changes include:
- Update notification component to use dynamic remission paths
- Migrate goods-in remission preview to tab-based navigation
- Refactor side menu to use new remission routing structure
- Remove legacy remission route from app routing module
- Add linkedSignal for reactive path generation

BREAKING CHANGE: Direct navigation to /filiale/remission is no longer supported.
Users must access remission through the new tab-based system.

Ref: #5323, #5324, #5325
2025-09-15 13:11:47 +00:00
Nino Righi
c672ae4012 Merged PR 1948: fix(remission-error): simplify error handling in remission components
fix(remission-error): simplify error handling in remission components

Refactor error handling to use consistent error message extraction pattern.
Remove dependency on ResponseArgsError type and streamline error processing
in both RemissionListComponent and RemissionReturnReceiptDetailsItemComponent.
Extract error handling logic into separate methods for better maintainability.

Ref: #5331
2025-09-12 10:15:13 +00:00
Nino Righi
fd693a4beb Merged PR 1947: #5331 Set correct Prototype
#5331 Set correct Prototype
2025-09-11 15:42:55 +00:00
Nino Righi
2c70339f23 Merged PR 1945: fix(remission-list): auto-select single search result when remission started
fix(remission-list): auto-select single search result when remission started

Enhance search result handling to automatically select items when only
one result is found during an active remission. This improves user
workflow by eliminating the extra click required to select obvious
single results.

- Add preselectRemissionItem method to handle automatic selection
- Update emptySearchResultEffect to handle single hit scenario
- Clear selected items at start of effect to prevent stale selections
- Only auto-select if item has available stock and can be remitted
- Improve effect documentation with detailed behavior explanation

Ref: #5338
2025-09-11 14:21:19 +00:00
Nino Righi
59f0cc7d43 Merged PR 1946: fix(remission-list, remission-return-receipt-details, libs-dialog): improve error handling with dedicated error dialog
fix(remission-list, remission-return-receipt-details, libs-dialog): improve error handling with dedicated error dialog

- Add RemissionResponseArgsErrorMessage constants for standardized error messages
- Create FeedbackErrorDialogComponent for consistent error display across the app
- Implement enhanced error handling in RemissionListComponent.handleRemitItemsError()
- Update RemissionReturnReceiptDetailsItemComponent to use new error dialog pattern
- Add injectFeedbackErrorDialog convenience function for easy error dialog injection
- Include comprehensive unit tests for new dialog component
- Replace generic error handling with specific ResponseArgsError handling
- Clear remission state when "AlreadyCompleted" error occurs

The new error dialog provides a standardized way to display backend error
messages to users with consistent styling and behavior. Error handling now
properly differentiates between different error types and takes appropriate
actions like clearing state for completed remissions.

Ref: #5331
2025-09-11 14:06:14 +00:00
Nino Righi
0ca58fe1bf Merged PR 1942: feat(remission-list, search-item-to-remit-dialog): simplify dialog flow by re...
feat(remission-list, search-item-to-remit-dialog): simplify dialog flow by removing conditional views

Refactor the search item to remit dialog to use a dedicated quantity and reason
dialog instead of conditional views within the main dialog. This change improves
user experience by providing clearer navigation and better separation of concerns.

Key changes:
- Remove item signal and conditional template logic from SearchItemToRemitDialogComponent
- Create new SelectRemiQuantityAndReasonDialogComponent for quantity/reason selection
- Update SearchItemToRemitComponent to open quantity dialog instead of setting item state
- Simplify dialog data interface by removing isDepartment property
- Improve stock filtering logic to show only items with available stock
- Fix import path for QuantityAndReason interface

This refactor eliminates complex state management within the dialog and provides
a more intuitive user flow with dedicated dialogs for each step.

Ref: #5326
2025-09-10 14:18:17 +00:00
Nino
8cf80a60a0 Merge branch 'develop' into release/4.1 2025-09-05 08:19:36 +02:00
Nino Righi
cffa7721bc Merged PR 1941: fix(oms-data-access): adjust tolino return eligibility logic for display damage
fix(oms-data-access): adjust tolino return eligibility logic for display damage

Update tolino return eligibility to check for display damage and refine
date range conditions. Returns are now only eligible if the receipt is
between 6-24 months old, the item was received damaged, and the display
is not damaged.

Ref: #5286
2025-09-04 15:12:44 +00:00
Nino Righi
066ab5d5be Merged PR 1940: feat(old-ui-tooltip): add pointer-events-auto to tooltip panel
feat(old-ui-tooltip): add pointer-events-auto to tooltip panel

Enable mouse interactions with tooltip content by adding pointer-events-auto
class to .ui-tooltip-panel. This allows users to interact with clickable
elements inside tooltips while maintaining proper tooltip positioning.

Ref: #5244
2025-09-04 14:11:49 +00:00
Nino Righi
3bbf79a3c3 Merged PR 1939: feat(remission-list, empty-state): add comprehensive empty state handling wit...
feat(remission-list, empty-state): add comprehensive empty state handling with new appearance types

Add dedicated empty state component for remission list with smart prioritization logic:
- Department selection required state (highest priority)
- All done state when list is processed and empty
- No search results state for filtered content

Enhance ui-empty-state component with new appearance types:
- AllDone: Trophy cup icon with animated steam effects
- SelectAction: Hand pointer with dropdown interface element
- Improved visual hierarchy and spacing for all states

Update remission list to use new empty state component with proper state detection
including search term validation, department filter checking, and reload detection.

Ref: #5317, #5290
2025-09-04 14:11:19 +00:00
Nino Righi
357485e32f Merged PR 1938: #5294 Small Adjustments
#5294 Small Adjustments
2025-09-04 14:10:55 +00:00
Nino Righi
39984342a6 Merged PR 1937: fix(ui-input-controls-dropdown): prevent multiple dropdowns from being open s...
fix(ui-input-controls-dropdown): prevent multiple dropdowns from being open simultaneously

Add DropdownService to manage global dropdown state and ensure only one
dropdown is open at any time. When a new dropdown opens, any previously
opened dropdown is automatically closed, improving user experience and
preventing UI conflicts.

Ref: #5298
2025-09-03 13:19:10 +00:00
Nino Righi
c52f18e979 Merged PR 1936: fix(remission): filter search results by stock availability and display stock...
fix(remission): filter search results by stock availability and display stock info

- Add stock resource integration to search item component
- Filter search results to only show items with available stock (> 0)
- Display current stock information in search result items
- Implement calculateAvailableStock utility for accurate stock calculation
- Add inStock input parameter to SearchItemToRemitComponent
- Create reusable instock.resource for stock data fetching

The search now only displays items that are actually available for remission,
improving user experience by preventing selection of out-of-stock items.

Ref: #5318
2025-09-03 13:18:47 +00:00
Nino Righi
e58ec93087 Merged PR 1935: fix(remission-list, remission-data-access): add impediment comment and remain...
fix(remission-list, remission-data-access): add impediment comment and remaining quantity handling for return suggestions

Add support for impedimentComment and remainingQuantity fields when adding return suggestion items. When quantity is less than available stock, automatically set impedimentComment to 'Restmenge' and calculate remainingQuantity as the difference between available stock and remitted quantity.

Changes:
- Add impedimentComment and remainingQuantity to AddReturnSuggestionItemSchema
- Update RemissionReturnReceiptService to handle new fields in addReturnSuggestionItem method
- Enhance RemissionListComponent to calculate and pass impediment data when remitting items
- Fix quantity calculation logic to properly handle partial remissions

Ref: #5322
2025-09-03 13:18:23 +00:00
Nino Righi
4e6204817d Merged PR 1934: feature(remission-list): temporarily disable remission-processed-hint component
feature(remission-list): temporarily disable remission-processed-hint component

Comment out remi-remission-processed-hint component in remission list template
and add TODO comments referencing the need to adjust code once ticket #5215
is implemented. This temporary fix prevents issues with the hint component
until the underlying changes are completed.

Ref: #5136
2025-09-03 13:16:35 +00:00
Nino Righi
c41355bcdf Merged PR 1933: fix(remission-data-access): replace hardcoded values with dynamic helper func...
fix(remission-data-access): replace hardcoded values with dynamic helper functions

Replace hardcoded assortment and retail price values in RemissionSearchService
with proper helper functions. Add getAssortmentFromItem and getRetailPriceFromItem
helpers to dynamically extract values from Item objects instead of using
static fallbacks.

Also fix potential undefined reference errors in remission list resource
by adding proper null checks for response merging operations.

Ref: #5321
2025-09-03 13:15:57 +00:00
Nino Righi
fa8e601660 Merged PR 1932: feat(remission): ensure package assignment before completing return receipts
feat(remission): ensure package assignment before completing return receipts

Add validation to check if a package is assigned to a return receipt before
allowing completion. When no package is assigned, automatically open the
package assignment dialog to let users scan/input a package number.

- Add hasAssignedPackage input to complete component and pass from parent
- Integrate RemissionStartService.assignPackage() in completion flow
- Add assignPackageOnly flag to conditionally hide step counter in dialog
- Update dialog data structure to support direct package assignment mode
- Enhance test coverage for new assignment scenarios

This ensures all completed return receipts have proper package tracking
and improves the user workflow by guiding them through required steps.

Ref: #5289
2025-09-03 13:15:32 +00:00
Nino Righi
708ec01704 Merged PR 1931: fix(remission-quantity-and-reason-item)
fix(remission-quantity-and-reason-item)
Ref: #5292
2025-09-02 15:20:44 +00:00
Nino Righi
332699ca74 Merged PR 1930: fix(remission-quantity-and-reason-item): correct quantity input binding and d...
fix(remission-quantity-and-reason-item): correct quantity input binding and default value

Fix quantity input field binding to use computed quantity signal instead of
direct quantityAndReason().quantity, ensuring proper display of undefined
values as empty field. Update initial quantity default from 1 to 0 to
prevent pre-filled values when creating new quantity/reason items.

Also improves placeholder text color contrast by changing from neutral-200
to neutral-500 for better accessibility.

Ref: #5292
2025-09-02 15:20:14 +00:00
Nino
3b0a63a53a fix(remission-data-access, remission-list, remission-add-item-flow): enforce mandatory list type for add-item flow
Remove addToDepartmentList method and ensure items added via search dialog
are always processed as mandatory remission items (ReturnItem) instead of
department suggestions (ReturnSuggestion). This prevents items from being
incorrectly added to department overflow lists when remission is already
started, maintaining data consistency in the WBS system.

Changes:
- Remove addToDepartmentList method from RemissionSearchService
- Update remitItems to use mandatory list type for add-item flow
- Simplify addToRemiList to only use mandatory remission endpoint
- Add addItemFlow parameter to control remission list type behavior

Refs: #4768, #5273, #5280
2025-09-02 14:40:26 +02:00
Nino Righi
327fdc745d Merged PR 1929: fix(remission-quantity-reason): correct dropdown placeholder and remove hardc...
fix(remission-quantity-reason): correct dropdown placeholder and remove hardcoded option

Change dropdown placeholder from "Rückgabegrund" to "Remigrund" for consistency
with application terminology. Remove hardcoded test option from reason dropdown
that was polluting the dropdown list. Extract initial item object to class
property for better maintainability and reusability.

Ref: #5293, #5299
2025-09-01 16:24:54 +00:00
Nino Righi
297ec9100d Merged PR 1928: fix(remission-filter-label): improve filter button label display and default text
fix(remission-filter-label): improve filter button label display and default text

Add default placeholder text "Abteilung auswählen" when no departments
are selected and implement dynamic label width to prevent text truncation.
The label now expands to full width when displaying placeholder text
and constrains to 8rem when showing selected values.

Ref: #5303
2025-09-01 16:24:23 +00:00
Nino Righi
298ab1acbe Merged PR 1927: fix(remission-data-access): remove automatic date defaulting in fetchRemissio...
fix(remission-data-access): remove automatic date defaulting in fetchRemissionReturnReceipts

Remove the automatic default of 7 days ago when no start date is provided
to the fetchRemissionReturnReceipts method. The service now passes the
start parameter directly to the API without modification, allowing the
API or schema to handle date defaults as intended.

This change improves the separation of concerns by moving date handling
logic out of the service layer and updates the corresponding test to
handle both defined and undefined start date scenarios.

Ref: #5256
2025-09-01 16:24:06 +00:00
Nino Righi
fe77a0ea8b Merged PR 1926: feat(libs-ui-dialog-feedback-dialog): add auto-close functionality with confi...
feat(libs-ui-dialog-feedback-dialog): add auto-close functionality with configurable delay

Implement automatic dialog closure after a configurable delay period.
The dialog now auto-closes by default after 1500ms, with options to
disable auto-close or customize the delay duration through the
FeedbackDialogData interface.

- Add autoClose and autoCloseDelay properties to FeedbackDialogData
- Implement auto-close logic using RxJS asapScheduler in constructor
- Add comprehensive test coverage for auto-close behavior
- Update JSDoc documentation for better clarity

Ref: #5297
2025-09-01 15:01:21 +00:00
Nino Righi
48f588f53b Merged PR 1925: fix(remission-shared-search-item-to-remit-dialog): display context-aware feed...
fix(remission-shared-search-item-to-remit-dialog): display context-aware feedback message

Update feedback dialog message to reflect the current remission state.
Shows "Wurde zum Warenbegleitschein hinzugefügt" when remission is already
started, otherwise shows "Wurde zur Remi Liste hinzugefügt".

This provides users with more accurate feedback about where their items
were added based on the current workflow state.

Ref: #5300
2025-09-01 15:00:54 +00:00
Nino Righi
7f4af304ac Merged PR 1924: feat(isa-app-shell): improve navigation link targeting for remission sub-routes
feat(isa-app-shell): improve navigation link targeting for remission sub-routes

Replace generic routerLinkActive with specific regex patterns for remission
navigation items to ensure accurate active state highlighting. This change:

- Uses sharedRegexRouterLinkActive for "Remission" sub-item to match specific routes
- Uses sharedRegexRouterLinkActive for "Warenbegleitscheine" sub-item
- Replaces broad routerLinkActive with precise regex patterns
- Ensures navigation accurately reflects current route state for remission workflows

The regex patterns specifically target `/[tabId]/remission/(mandatory|department)`
and `/[tabId]/remission/return-receipt` routes for better user experience.

Ref: #5304
2025-09-01 15:00:22 +00:00
Nino Righi
643b2b0e60 Merged PR 1923: feat(remission): remove Koerperlos remission list type
feat(remission): remove Koerperlos remission list type

Remove the 'Körperlose Remi' option from remission list types as it's no longer needed. This simplifies the remission type selection by:

- Removing Koerperlos from RemissionListType constant
- Eliminating disabled state logic in dropdown component
- Removing special handling in changeRemissionType method
- Fixing label text from 'Abteilungen' to 'Abteilung' for consistency

The dropdown now only shows the two active remission types: Pflichtremission and Abteilungsremission.

Ref: #5303
2025-09-01 14:59:57 +00:00
Nino Righi
cd1ff5f277 Merged PR 1922: feat(libs-shared-product-format): remove truncate class from format detail text
feat(libs-shared-product-format): remove truncate class from format detail text

Remove the 'truncate' class from the span element containing formatDetail()
to allow full text display without text clipping. This improves readability
when product format details contain longer descriptions.

Ref: #5301
2025-09-01 14:59:28 +00:00
Nino Righi
46c70cae3e Merged PR 1921: feat(remission-list-resource): remove client-side date sorting in favor of ba...
feat(remission-list-resource): remove client-side date sorting in favor of backend sorting

Remove commented-out date sorting logic from sortResponseResult function.
The sorting by creation date for Pflichtremission and by SORT number
for Abteilungsremission is now handled entirely by the backend,
eliminating the need for client-side date sorting operations.

This change improves performance by reducing client-side processing
and ensures consistent sorting behavior across the application.

Ref: #5295
2025-09-01 14:59:07 +00:00
Nino
2cb1f9ec99 chore(azure-pipelines): Version bump 4.1 2025-08-14 17:09:13 +02:00
Nino
d2dcf638e3 Merge tag '4.0-hotfix-release' 2025-08-14 16:47:48 +02:00
Nino
a4241cbd7a Merge branch 'release/4.0' 2025-08-14 16:40:46 +02:00
Nino Righi
dd3705f8bc Merged PR 1920: feat(remission-list): add navigation to default list and clear input on reload
feat(remission-list): add navigation to default list and clear input on reload

Add Router injection and injectTabId for navigation functionality.
Implement navigateToDefaultRemissionList method to redirect users
to the default remission list using the current activated tab ID.
Clear query input on reload trigger to prevent stale search results
from persisting across navigation.

Enhance emptySearchResultEffect to handle department list navigation
when no items are found and remission hasn't started yet.

Ref: #5273
2025-08-14 14:06:20 +00:00
Nino Righi
514715589b Merged PR 1919: feat(remission): add impediment management and UI enhancements for remission...
feat(remission): add impediment management and UI enhancements for remission list

Implement comprehensive impediment handling for return items and suggestions
with enhanced user interface components and improved data access layer.

Key additions:
- Add impediment update schema and validation for return items
- Implement RemissionReturnReceiptService with full CRUD operations
- Create RemissionListItemComponent with actions and selection capabilities
- Add ProductInfoComponent with responsive layout and labeling
- Enhance UI Dialog system with improved injection patterns and testing
- Add comprehensive test coverage for all new components and services
- Implement proper data attributes for E2E testing support

Technical improvements:
- Follow SOLID principles with clear separation of concerns
- Use OnPush change detection strategy for optimal performance
- Implement proper TypeScript typing with Zod schema validation
- Add comprehensive JSDoc documentation for all public APIs
- Use modern Angular signals and computed properties for state management

Refs: #5275, #5038
2025-08-14 14:05:01 +00:00
Nino Righi
0740273dbc Merged PR 1917: feat(remission-data-access): enhance stock calculation to handle zero predefi...
feat(remission-data-access): enhance stock calculation to handle zero predefined quantities

Improve calculateStockToRemit and getStockToRemit functions to properly distinguish
between undefined and zero predefined return quantities. When predefinedReturnQuantity
is undefined, the system now falls back to approximation calculation (availableStock
minus remainingQuantityInStock). When predefinedReturnQuantity is explicitly set to 0,
the system respects this backend-calculated value.

Add comprehensive test coverage for edge cases including:
- Zero predefined return quantities for both Pflicht and Abteilung types
- Negative approximation calculations (clamped to 0)
- Null/undefined remainingQuantityInStock handling
- Missing returnItem scenarios for Abteilung type

Ref: #5280
2025-08-13 13:39:18 +00:00
Nino Righi
bbb9c5d39c Merged PR 1918: feat(libs-ui-label, remission-shared-product, storybook): add UI label compon...
feat(libs-ui-label, remission-shared-product, storybook): add UI label component for remission tags

- Create new @isa/ui/label library with primary/secondary appearances
- Integrate label component into ProductInfoComponent to display remission tags (Prio 1, Prio 2, Pflicht)
- Add conditional rendering based on RemissionItemTags enum with proper appearance mapping
- Include comprehensive unit tests using Vitest and Angular Testing Utilities
- Add Storybook stories for both label component and updated product info component
- Import label styles in main tailwind.scss

Ref: #5268
2025-08-13 13:38:13 +00:00
Nino Righi
f0bd957a07 Merged PR 1914: Rückmerge Release/4.0 -> Develop
Rückmerge Release/4.0 -> Develop
2025-08-13 09:52:15 +00:00
Nino Righi
e4f289c67d Merged PR 1915: fix(remission-list-resource): only apply default sorting when no orderBy spec...
fix(remission-list-resource): only apply default sorting when no orderBy specified

Replace default sort mechanism to respect explicit orderBy from QueryToken.
Previously, the resource always applied manual sorting regardless of whether
explicit ordering was requested, causing conflicts with user-defined sorting.

Now checks if queryToken.orderBy exists and has items before applying the
default sort behavior (manually-added items first, then by created date).

Refs: #5276
2025-08-13 09:51:25 +00:00
Nino Righi
2af16d92ea Merged PR 1916: fix(remission-helpers, remission-list-item): fix predefinedReturnQuantity han...
fix(remission-helpers, remission-list-item): fix predefinedReturnQuantity handling and enhance stock validation

Fix issue where predefinedReturnQuantity value of 0 was being treated differently
from undefined in mandatory remission (Pflichtremission). Now both 0 and undefined
are handled consistently by changing the initial value to undefined and using
truthy check instead of strict undefined comparison.

Additionally enhance hasStockToRemit validation by requiring both availableStock
and stockToRemit to be greater than 0, preventing invalid remission states when
no stock is available.

Changes:
- Change predefinedReturnQuantity initial value from 0 to undefined in getStockToRemit
- Remove nullish coalescing operator that forced 0 default for predefinedReturnQuantity
- Update calculateStockToRemit to use truthy check (!predefinedReturnQuantity)
  instead of strict undefined comparison
- Enhance hasStockToRemit computed property to validate both availableStock > 0
  and stockToRemit > 0
- Add comprehensive test coverage for all hasStockToRemit edge cases including
  negative values and zero combinations

Ref: #5269
2025-08-13 09:50:18 +00:00
Nino Righi
99e8e7cfe0 Merged PR 1913: feat(remission): refactor return receipt details and extract shared actions
feat(remission): refactor return receipt details and extract shared actions

Refactor remission return receipt details to use return-based data flow
instead of individual receipt fetching. Extract reusable action components
for better code organization and consistency.

- Remove deprecated fetchRemissionReturnReceipt method and schema
- Add helper functions for extracting data from return objects
- Replace receipt-specific components with return-based equivalents
- Create shared return-receipt-actions library with reusable components
- Update components to use modern Angular patterns (signals, computed)
- Improve data flow consistency across remission features
- Add comprehensive test coverage for new components
- Update eager loading support in fetch return functionality

The new architecture provides better data consistency and reduces
code duplication by centralizing receipt actions and data extraction
logic into reusable components.

Refs: #5242, #5138, #5232, #5241
2025-08-12 13:32:57 +00:00
Nino Righi
ac728f2dd9 Merged PR 1912: hotfix(isa-app-ui/shared-searchbox): improve component initialization and met...
hotfix(isa-app-ui/shared-searchbox): improve component initialization and method safety

Enhance searchbox component reliability by addressing initialization
issues and improving method safety across both shared and ui implementations.

Key changes:
- Fix potential null reference errors in cancel search functionality
- Improve method parameter typing with explicit defaults
- Add proper initialization for ControlValueAccessor callbacks
- Enhance component property initialization with explicit types
- Add hintCleared output event for better hint management

These changes resolve runtime errors and improve type safety
for the searchbox components used throughout the application.

Refs: #5245
2025-08-07 17:55:25 +00:00
Nino
2e012a124a chore(package-lock): Update Package Lock JSON 2025-08-07 14:21:57 +02:00
Nino Righi
d22e320294 Merged PR 1910: feat(remission-list, ui-tooltip): add info tooltip with performance optimization
feat(remission-list, ui-tooltip): add info tooltip with performance optimization

Add tooltip to department capacity info button with enhanced trigger management.
Optimize department list fetching to only load when search input or department
filter is active, improving initial load performance.

- Add tooltip directive to info button showing capacity details
- Implement conditional department list fetching based on input/filter presence
- Enhance tooltip directive with improved trigger management and positioning
- Update tooltip component to use modern Angular control flow syntax
- Add proper show/hide logic with trigger-specific behavior

Refs: #5255
2025-08-06 16:02:27 +00:00
Nino Righi
a0f24aac17 Merged PR 1909: fix(remission-data-access, remission-product-stock-info): improve stock infor...
fix(remission-data-access, remission-product-stock-info): improve stock information display and data handling

Enhance product stock info component with proper loading states.

- Add stockFetching input to ProductStockInfoComponent for loading states
- Update remission list components to properly handle stock fetching state
- Enhance type safety and documentation for better maintainability

The RemissionSearchService now provides clear documentation for all
methods including fetchList, fetchQuerySettings, and capacity fetching
operations. The ProductStockInfoComponent now properly displays loading
states during stock data retrieval.

Ref: #5243
2025-08-06 16:01:10 +00:00
Nino Righi
7ae484fc83 Merged PR 1908: feat(remission-shared-dialog): add dynamic dropdown label for return reason s...
feat(remission-shared-dialog): add dynamic dropdown label for return reason selection

Implement computed property to show selected reason value or default placeholder
text in the dropdown label. This provides better UX by displaying the current
selection instead of a static label.

- Add dropdownLabel computed property that returns selected reason or fallback
- Update template to use dynamic label binding instead of hardcoded text
- Enhances user feedback when reason is selected vs. when no selection is made

Ref: #5253
2025-08-06 15:58:44 +00:00
Nino Righi
0dcb31973f Merged PR 1907: feat(remission-list-item, ui-dialog): enhance quantity dialog with original v...
feat(remission-list-item, ui-dialog): enhance quantity dialog with original value display

Add support for displaying original remission quantity in the quantity change dialog.
This provides better context for users when modifying remission quantities by showing
both the current input and the original calculated value.

Changes:
- Add subMessage and subMessageValue inputs to NumberInputComponent and dialog interfaces
- Update RemissionListItemActionsComponent to pass original quantity context to dialog
- Modify RemissionListItemComponent to track quantity differences and pass stockToRemit value
- Add selectedQuantityDiffersFromStockToRemit computed property for UI state management
- Update component templates to display contextual information in quantity dialogs

Ref: #5204
2025-08-06 15:58:10 +00:00
Nino Righi
c2f393d249 Merged PR 1911: hotfix(isa-app-store, core-storage): prevent caching of erroneous user state
hotfix(isa-app-store, core-storage): prevent caching of erroneous user state

Remove shareReplay(1) operator from user state observable to ensure
fresh state retrieval on each request. This prevents the system from
retaining and reusing failed or invalid state data across multiple
operations.

The current implementation now makes two API calls (GET + POST) per
set operation to guarantee the latest state is always used, trading
performance for reliability in error scenarios.

Refs: #5270, #5249
2025-08-06 15:47:49 +00:00
Nino Righi
2dbf7dda37 Merged PR 1906: feat(remission-data-access, remission-start-dialog): refactor remission workf...
feat(remission-data-access, remission-start-dialog): refactor remission workflow to use createRemission API

Replace the startRemission method with separate createRemission and assignPackage operations.
The new implementation improves error handling and provides better separation of concerns
between return creation and package assignment steps.

Key changes:
- Add CreateRemission interface to models with support for validation error properties
- Replace startRemission with createRemission method that handles return and receipt creation
- Update service methods to return ResponseArgs objects with proper error handling
- Enhance dialog components with reactive error handling using Angular effects
- Add comprehensive server-side validation error display in form controls
- Separate package assignment into dedicated step with individual loading states
- Improve test coverage with proper mocking of new service methods

The refactored workflow provides better user feedback for validation errors and maintains
the existing two-step process while improving maintainability and error handling.

Ref: #5251
2025-08-05 10:42:45 +00:00
Nino Righi
cce15a2137 Merged PR 1905: feat(remission-data-access, remission-list-item): add remission item source t...
feat(remission-data-access, remission-list-item): add remission item source tracking and delete functionality

Add comprehensive remission item source management with the ability to delete
manually added items from return receipts. Introduces new RemissionItemSource
model to track item origins and refactors remission list item components for
better action management.

Key changes:
- Add RemissionItemSource model with 'manually-added' and 'DisposalListModule' types
- Extend ReturnItem and ReturnSuggestion interfaces with source property
- Implement deleteReturnItem service method with comprehensive error handling
- Create RemissionListItemActionsComponent for managing item-specific actions
- Add conditional display logic for delete buttons based on item source
- Refactor RemissionListItemSelectComponent with hasStockToRemit input validation
- Add deleteRemissionListItemInProgress state management across components
- Include comprehensive test coverage for new delete functionality

This enhancement enables users to remove manually added items from remission
lists while preserving system-generated entries, improving workflow flexibility
and data integrity.

Ref: 5259
2025-08-04 11:31:05 +00:00
Nino Righi
14a5a67a1e Merged PR 1904: feat(utils-ean-validation, remission-list): add EAN validation library and im...
feat(utils-ean-validation, remission-list): add EAN validation library and implement exact search

Create new EAN validation utility library with validator function and isEan helper.
Implement exact search functionality for remission lists that bypasses filters
when scanning EAN codes or performing exact searches.

Changes:
- Add new utils/ean-validation library with EAN regex validation
- Export eanValidator for Angular reactive forms integration
- Export isEan utility function for EAN validation checks
- Configure library with Vitest for testing
- Update remission list resource to support exact search mode
- Clear filters and orderBy when performing EAN-based searches
- Add data attributes to product info component for E2E testing

Ref: #5128
2025-08-01 13:22:41 +00:00
Nino Righi
d7d535c10d Merged PR 1903: fix(remission-list, product-info, search-item-to-remit): improve responsive l...
fix(remission-list, product-info, search-item-to-remit): improve responsive layout and fix orientation logic

- Fix grid layout responsiveness in remission-list-item component by updating breakpoint conditions from mobileBreakpoint to desktopBreakpoint
- Correct product-info orientation logic to properly apply horizontal/vertical layouts based on breakpoint state
- Add consistent orientation handling to search-item-to-remit component with proper breakpoint detection
- Update CSS classes to use desktop-large breakpoint for better grid column management
- Add bottom margin to remission list container to prevent overlap with fixed action button
- Enhance test coverage for new computed properties and breakpoint-dependent behavior

Ref: #5239
2025-07-31 16:44:06 +00:00
Nino Righi
ad00899b6e Merged PR 1902: feat(shared-filter-inputs-checkbox-input): add bulk toggle functionality for...
feat(shared-filter-inputs-checkbox-input): add bulk toggle functionality for checkbox options

Replace individual option iteration with new toggleAllCheckboxOptions method
in FilterService. This improves performance and provides cleaner API for
selecting/deselecting all checkbox options at once. Updates component logic
to use the new bulk operation and fixes test expectations accordingly.

Ref: #5231
2025-07-31 16:42:37 +00:00
Nino Righi
0addf392b6 Merged PR 1901: hotfix(return-summary): disable navigation during return processing
hotfix(return-summary): disable navigation during return processing

Replace Router navigation with Location.back() for better UX and add
disabled states to prevent user actions during pending operations.

Changes:
- Replace navigateBack() method with direct Location.back() calls
- Add returnItemsAndPrintReciptPending input to ReturnSummaryItemComponent
- Disable edit and back buttons when return operation is pending
- Update parent component to pass pending state to child components
- Fix template binding to use computed pending status signal

This prevents users from navigating away during critical return
operations and provides consistent disabled states across the UI.

Ref: #5257
2025-07-31 16:41:59 +00:00
Michael Auer
1e84223076 ~ azure-pipelines.yml: DockerTagSourceBranch _ ==> - 2025-07-30 17:46:32 +02:00
Nino Righi
244984b6cf Merged PR 1900: feat(remission): add getStockToRemit helper and improve stock calculation logic
feat(remission): add getStockToRemit helper and improve stock calculation logic

Add new getStockToRemit helper function that handles different remission list types
(Pflicht and Abteilung) for calculating stock to remit. Refactor existing logic
to use the centralized helper instead of duplicated calculation code.

Changes:
- Add getStockToRemit function to handle RemissionListType-specific logic
- Update calculateStockToRemit to use strict undefined check for predefinedReturnQuantity
- Refactor RemissionListItemComponent to use getStockToRemit helper
- Update RemissionListComponent to use getStockToRemit for consistent calculations
- Add comprehensive test coverage for both helper functions

This centralizes stock calculation logic and ensures consistent behavior
across all remission components.

Ref: #5252
2025-07-30 12:00:08 +00:00
Lorenz Hilpert
b39abe630d Merged PR 1899: feat(empty-state): enhance empty state component with new appearance options...
feat(empty-state): enhance empty state component with new appearance options and integration in remission details

Related work items: #5232
2025-07-30 08:54:09 +00:00
Lorenz Hilpert
239ab52890 Merged PR 1898: chore: update dependencies to latest versions
chore: update dependencies to latest versions

- Upgraded @ngrx packages from 19.2.1 to ^20.0.0
- Upgraded ngx-matomo-client from ^7.0.1 to ^8.0.0
- Upgraded jest and related packages from 30.0.4 to ^29.7.0
2025-07-30 08:52:36 +00:00
Nino
4732656a0f chore(remission, navigation): update routing and remove unused helpers 2025-07-29 12:18:07 +02:00
Nino Righi
0da9800ca0 Merged PR 1897: #5236 #4771 Abteilungsremission
- feat(remission-list): Added Tooltip and Static Toolbar
- Merge branch 'develop' into feature/5236-Remission-Abteilungsremission-Offene-Punkte
- feat(remission-list, shared-filter, ui-input-controls): enhance department filtering and UI improvements
- Merge branch 'develop' into feature/5236-Remission-Abteilungsremission-Offene-Punkte
- Merge branch 'develop' into feature/5236-Remission-Abteilungsremission-Offene-Punkte
- feat(remission-list, remission-data-access): add department capacity display functionality

#5236 #4771 Abteilungsremission
2025-07-28 19:28:14 +00:00
Lorenz Hilpert
baf4a0dfbc Merge branch 'develop' of https://dev.azure.com/hugendubel/ISA/_git/ISA-Frontend into develop 2025-07-28 19:11:36 +02:00
Lorenz Hilpert
da5a42280a feat(remission): enhance quantity input handling and error validation
Refactor quantity input to use a direct input field instead of a toggle button.
Add validation to ensure quantity does not exceed 999 and display relevant error messages.
Improve overall user experience in the remission process.

Refs: #5253
2025-07-28 19:11:08 +02:00
Lorenz Hilpert
4d29189c8d Merged PR 1896: feat(filter): add maximum selection limits for checkbox filters
feat(filter): add maximum selection limits for checkbox filters

Implement a maxOptions property to limit the number of selections in checkbox filters.
This feature includes FIFO behavior for managing selections and hides the "Select All"
control when limits are set to prevent user confusion. Update related documentation
and components to reflect these changes.

Refs: #5250
2025-07-28 16:01:34 +00:00
Lorenz Hilpert
32bd3e26d2 Merged PR 1895: feat(app): provide default currency code as EUR
feat(app): provide default currency code as EUR

Refs: #5247 #5248
2025-07-28 12:00:38 +00:00
Lorenz Hilpert
6d26f7f6c0 Merged PR 1894: feat(filter): enhance search trigger handling and event emissions
feat(filter): enhance search trigger handling and event emissions

Refactor search components to emit specific search trigger types,
improving tracking of user interactions. Update relevant components
to handle 'input', 'filter', 'scan', and 'order-by' triggers,
ensuring consistent behavior across the filter system.

Refs: #5234
2025-07-28 08:54:15 +00:00
Lorenz Hilpert
72bcacefb6 Merged PR 1893: feat(remission): add remission processed hint component and update schemas
feat(remission): add remission processed hint component and update schemas

- Introduced RemissionProcessedHintComponent to display hints based on remission processing status.
- Updated fetch-remission-return-receipts schema to include parameters for completed returns.
- Refactored remission return receipt service to handle completed and incomplete returns separately.
- Adjusted remission list component to utilize the new hint component and updated data fetching logic.

Refs: #5240 #5136
2025-07-28 08:30:04 +00:00
Lorenz Hilpert
71e9a6da0e Merged PR 1892: refactor(return-receipt-list-item): restructure styles and remove unused imports
refactor(return-receipt-list-item): restructure styles and remove unused imports

Updated the SCSS to separate background styles for different states and removed the unused Receipt import from the component.

Refs: #5225
2025-07-28 08:26:54 +00:00
Lorenz Hilpert
b339a6d79f Merged PR 1891: feat: implement multi-level checkbox filter with hierarchical selection
feat: implement multi-level checkbox filter with hierarchical selection

- Add support for hierarchical checkbox options with parent-child relationships
- Implement automatic child selection/deselection when parent is toggled
- Add checkbox-input-control component for individual option management
- Add isCheckboxSelected helper for determining selection states
- Extend FilterService with setInputCheckboxOptionSelected method
- Update checkbox schemas to support nested option structures
- Add comprehensive test coverage for new multi-level functionality

Ref: #5231
2025-07-25 13:49:44 +00:00
Lorenz Hilpert
0b4aef5f6c chore: add nx.instructions.md to .gitignore 2025-07-25 10:37:44 +02:00
Nino Righi
c5182809ac Merged PR 1890: #5230 #5233 Remi Starten Feedback
- feat(remission-data-access,remission-list,remission-return-receipt-details): improve remission list UX and persist store state
- feat(remission-list, remission-data-access): implement resource-based receipt data fetching
- Merge branch 'develop' into feature/5230-Feedback-Remi-Starten
- feat(remission-data-access, remission-list, ui-dialog, remission-start-dialog): consolidate remission workflow and enhance dialog system
- feat(remission-list-item): extract selection logic into dedicated component
Refs: #5230 #5233
2025-07-24 21:22:02 +00:00
Lorenz Hilpert
f4b541c7c0 chore: update package.json to include overrides for jest-environment-jsdom and stylus 2025-07-23 17:40:37 +02:00
Lorenz Hilpert
afe6c6abcc chore: update package.json to override stylus version to 0.64.0 and ensure jsdom is set to 26.0.0 2025-07-23 17:29:37 +02:00
Lorenz Hilpert
3f233f9580 Merge tag '4.0' into develop
Finish Release 4.0 4.0
2025-07-23 17:02:32 +02:00
Lorenz Hilpert
6f9d4d9218 Merge branch 'release/4.0' 2025-07-23 16:35:08 +02:00
Lorenz Hilpert
4111663d8c feat: add mock for ScannerButtonComponent and update feedback dialog
- Created a mock for ScannerButtonComponent in test-mocks.ts to facilitate testing.
- Updated test-setup.ts to mock browser APIs for the test environment.
- Refactored SelectRemiQuantityAndReasonComponent to simplify addToRemiList logic and update feedback dialog usage.
- Modified feedback-dialog.component.html to safely access message data.
- Cleaned up package-lock.json by removing deprecated and unnecessary dependencies.
2025-07-22 15:06:25 +02:00
Lorenz Hilpert
2beeba5c92 fix: resolve critical security vulnerability in form-data
- Updated form-data from 4.0.3 to 4.0.4
- Fixes GHSA-fjxv-7rqg-78g4: unsafe random function usage for boundary selection
- Applied npm audit fix --force due to peer dependency conflicts
2025-07-21 23:11:54 +02:00
Lorenz Hilpert
edab1322c8 chore: migrate nx to latest 2025-07-21 22:35:11 +02:00
Lorenz Hilpert
59ce736faa feat(remission-return-receipt-list): rewrite unit tests with Angular Testing Utilities
- Replace Spectator with Angular's official TestBed and ComponentFixture
- Implement isolated test approach with proper AAA pattern
- Fix TypeScript errors related to Return interface type mismatches
- Add comprehensive edge case testing and error handling
- Create proper mock components for child dependencies
- Ensure all 47 tests pass with improved maintainability
2025-07-21 20:07:02 +02:00
Nino Righi
3cd6f4bd58 Merged PR 1889: feat(remission-data-access, remission-list, remission-start-card): add remission item selection and quantity update logic
- Introduce `addReturnItem` and `addReturnSuggestionItem` methods to `RemissionReturnReceiptService` with full schema validation and error handling
- Add models and schemas for receipt-return tuples and add-return-item/suggestion operations
- Refactor `RemissionStore` (formerly `RemissionSelectionStore`) to support selection, quantity updates, and clearing of remission items; update all usages to new store name and API
- Update `RemissionListItemComponent` to support item selection via checkbox and quantity dialog, following workspace UX and state management guidelines
- Enhance `RemissionListComponent` to handle selected items, batch remission, and error/success feedback using new store and service APIs
- Fix and extend tests for new store and service logic, ensuring coverage for selection, quantity, and remission flows
- Update remission start dialog and assign package number components for improved validation and loading state handling

Ref: #5221
2025-07-21 10:28:12 +00:00
Lorenz Hilpert
594acaa5f5 feat(button): add disabled state input to stateful button component 2025-07-21 08:39:33 +02:00
Lorenz Hilpert
76ff54dd3a Merged PR 1887: feat(navigation): add collapsible submenu for remission navigation #5223
feat(navigation): add collapsible submenu for remission navigation #5223

- Convert remission navigation to expandable submenu with arrow toggle
- Add 'list' route for remission with redirect from empty path
- Separate navigation items for Remission and Warenbegleitscheine
- Refactor side-menu component to use inject() pattern
- Add remissionExpanded signal to track submenu state
2025-07-18 06:40:24 +00:00
Lorenz Hilpert
598df7d5ed Merged PR 1888: fix: improve sorting of remission return receipts
fix: improve sorting of remission return receipts

- Refactor data fetching to use a single API call for all returns
- Apply sorting separately to completed and incomplete returns
- Fix template tracking to use index instead of potentially undefined ID
- Remove redundant API calls for incomplete returns

This ensures proper sorting of remission return receipts while maintaining
the separation between completed and incomplete items in the display order.

Ref: #5224
2025-07-18 06:39:44 +00:00
Lorenz Hilpert
442670bdd0 Merged PR 1885: Remi Add Flow - ohne offener Remi
Related work items: #5135
2025-07-17 13:53:36 +00:00
Lorenz Hilpert
b015e97e1f Merged PR 1886: feat: add unit tests for remission return receipt functionality
feat: add unit tests for remission return receipt functionality

- Add tests for 4 new RemissionReturnReceiptService methods:
  - removeReturnItemFromReturnReceipt()
  - completeReturnReceipt()
  - completeReturn()
  - completeReturnReceiptAndReturn()
- Update RemissionReturnReceiptDetailsCardComponent tests for itemCount -> positionCount
- Add tests for new inputs and remove functionality in RemissionReturnReceiptDetailsItemComponent
- Add tests for canRemoveItems and completeReturn in RemissionReturnReceiptDetailsComponent
- All tests focus on happy path scenarios and isolated functionality

Refs: #5138
2025-07-17 13:46:32 +00:00
Nino Righi
65ab3bfc0a Merged PR 1884: #5213
- feat(dialog-feedback-dialog, remission-list-item): add feedback dialog and remission list item components
- feat(remission-list-item): implement remission list item component
Refs: #5213
2025-07-15 11:26:03 +00:00
Lorenz Hilpert
e674378080 Merged PR 1883: fix(return-details): update email validation and improve error handling
fix(return-details): update email validation and improve error handling

Refs: #5211
2025-07-14 14:57:41 +00:00
Lorenz Hilpert
40c9d51dfc Merged PR 1881: Stateful Remi Button
#5203

Related work items: #5203
2025-07-14 11:57:03 +00:00
Nino Righi
5f74c6ddf8 Merged PR 1878: Refs: #4769, #5196
- feat(remission-shared-produt-shelf-meta-info): Intermediate commit.
- feat(remission-shared-product-shelf-meta-info): improve template structure and data attributes
- feat(remission-list-item): add product shelf meta info and improve E2E selectors

Refs: #4769, #5196
2025-07-11 19:53:56 +00:00
Lorenz Hilpert
a36d746fb8 Merged PR 1879: Warenbegleitschein Übersicht und Details
Related work items: #5137, #5138
2025-07-10 16:00:16 +00:00
Nino
f6b2b554bb Merge branch 'release/4.0' into develop 2025-07-10 14:31:03 +02:00
Nino
465df27858 Merge branch 'release/4.0' into develop 2025-07-10 14:16:29 +02:00
Nino Righi
7c907645dc Merged PR 1880: hotfix(oms-data-access): initial implementation of OMS data access layer
hotfix(oms-data-access): initial implementation of OMS data access layer

Introduce the foundational OMS data access module, including service scaffolding and integration points for future API communication. This establishes a clear separation of concerns for order management system data retrieval and manipulation, following project architecture guidelines.

Ref: #5210
2025-07-10 11:32:42 +00:00
Nino Righi
b7e7155577 Merged PR 1877: #4769, #5194 Remission List Item - StockInfos - ItemInfos
feat(remission-list, remission-shared-product-stock-info): implement product stock info display

Add product stock information to the remission list and shared product components.
This enhances user visibility into current stock levels directly within remission-related views,
improving workflow efficiency and reducing the need for context switching.

Ref: #4769, #5194
2025-07-02 14:23:04 +00:00
Lorenz Hilpert
b28c204f23 refactor(tabs): add metadata and navigation properties to Tab model 2025-07-01 12:00:12 +02:00
Lorenz Hilpert
e7a807cfbd refactor(tabs): enhance Tab interface with navigation and metadata 2025-07-01 11:46:30 +02:00
Lorenz Hilpert
344dc61a90 fix: resolve CSS cascade issue with UI components and Tailwind utilities
- Move UI component styles to @layer components in tailwind.scss
- Remove ui.scss and integrate imports directly into component layer
- Add SCSS files to Tailwind content config to prevent CSS class purging
- Update Angular project configuration to remove ui.scss references
- Ensure Tailwind utilities can override component styles properly

Refs: #5195
2025-06-30 23:01:58 +02:00
Lorenz Hilpert
8d063428fc Merge branch 'refactor/convert-buildable-libs-to-non-buildable' into develop
Resolved conflicts:
- .gitignore: Added .claude to ignored files
- nx.json: Kept HEAD version with extra eslint.config.js exclusion
- package.json: Merged dependencies, updated vitest to v3.1.1 for compatibility
- eslint config files: Fixed merge conflicts and accepted conversion from .mjs to .js
- Removed deleted files from refactor branch
- Regenerated package-lock.json with --legacy-peer-deps

Build and tests pass successfully.
2025-06-30 20:52:05 +02:00
Lorenz Hilpert
06b0c6264a chore: add .claude to .gitignore 2025-06-30 20:13:33 +02:00
Lorenz Hilpert
4fe633e973 chore: update package dependencies and remove unused shared imports in tsconfig 2025-06-30 20:13:19 +02:00
Lorenz Hilpert
2463a803ea Merged PR 1876: Fix Workspace Build Issues 2025-06-30 09:17:03 +00:00
Lorenz Hilpert
1663dcec73 test(search-item-to-remit-dialog): enhance unit tests for component behavior and signal integration 2025-06-30 11:00:00 +02:00
Lorenz Hilpert
827aa565c5 feat(tests): update test command to include tuiAutoExit and add unit tests for SearchItemToRemitDialogComponent 2025-06-27 17:34:13 +02:00
Lorenz Hilpert
39fc4ce1ce refactor(styles): update styles to use Tailwind CSS and clean up code 2025-06-27 16:45:47 +02:00
Lorenz Hilpert
4f4b072e25 refactor(sass): migrate @import to @use syntax
- Replace deprecated @import with modern @use in _components.scss
- Replace deprecated @import with modern @use in tailwind.scss
- Move @use statements before @tailwind directives per Sass requirements
- Eliminates all 5 Sass deprecation warnings from build
- Future-proofs codebase for Dart Sass 3.0.0
2025-06-27 16:42:49 +02:00
Lorenz Hilpert
9af4a72a76 fix: resolve build warnings and improve code quality
- Remove unused Angular component and pipe imports to eliminate TS-998113 warnings
- Fix Sass mixed declarations warnings by reordering CSS properties
- Remove empty ngOnInit method from preview component
- Clean up unused imports across customer search and OMS components
- Move animation/transition properties above nested rules in SCSS files

Reduces build warnings significantly and improves code maintainability.
2025-06-27 16:19:18 +02:00
Lorenz Hilpert
7a44101e90 refactor: convert buildable libraries to non-buildable and migrate eslint configs
- Convert eslint.config.mjs files to eslint.config.js format across workspace
- Remove build targets from remission libraries (data-access, feature/remission-list, helpers, shared)
- Remove build target from icons library
- Delete ng-package.json and tsconfig.lib.prod.json files from buildable libraries
- Update tsconfig.lib.json configurations to remove bundler moduleResolution
- Clean up build artifacts and simplify library configurations
- Libraries now compile on-demand during application build instead of pre-compilation
2025-06-27 15:44:34 +02:00
Nino Righi
6fee35c756 Merged PR 1872: fix(isa-app-moment-locale): correct locale initialization for date formatting
fix(isa-app-moment-locale): correct locale initialization for date formatting

Ensures proper setup of moment.js locale in the ISA app to provide accurate date and time formatting for users. Addresses issues with incorrect or inconsistent locale application.

Ref: #5188
2025-06-25 08:35:43 +00:00
Nino Righi
c15077aa86 Merged PR 1870: fix(oms-return-search): fix display and logic issues in return search results
fix(oms-return-search): fix display and logic issues in return search results

Resolve display inconsistencies and correct logic in the return search result component to improve user experience and maintain alignment with design and business requirements.

Ref: #5009
2025-06-23 21:23:27 +00:00
Nino Righi
f051a97e53 Merged PR 1871: fix(ui-dropdown): improve dropdown usability and conditional rendering
fix(ui-dropdown): improve dropdown usability and conditional rendering

Refines the logic for displaying quantity and product category dropdowns in the return details order group item controls. Ensures dropdowns are only shown when appropriate and maintains accessibility and user experience.

Ref: #5189
2025-06-23 15:32:56 +00:00
Nino Righi
1b26a44a37 Merged PR 1869: fix(oms-task-list-item): address styling and layout issues in return task lis...
fix(oms-task-list-item): address styling and layout issues in return task list item

Improves SCSS for the return task list item component to ensure consistent appearance and resolve layout inconsistencies. Enhances maintainability and visual alignment with design standards.

Ref: #5191
2025-06-23 15:25:34 +00:00
Nino Righi
80b2508708 Merged PR 1868: fix(oms-return-search): resolve issues in return search result item rendering
fix(oms-return-search): resolve issues in return search result item rendering

Corrects rendering logic and improves template structure for the return search result item component. Ensures compliance with Angular control flow best practices and enhances maintainability.

Ref: #5190
2025-06-23 15:24:26 +00:00
Nino
e9affd2359 fix(return-details): Small Layout Fix, Refs: #5171 2025-06-17 16:52:03 +02:00
Nino
8f8b9153b0 Merge branch 'develop' into release/4.0 2025-06-17 16:45:37 +02:00
Lorenz Hilpert
9a4121e2bf fix(return-details): correct storage key retrieval in ReturnDetailsStore 2025-06-16 10:53:58 +02:00
Lorenz Hilpert
50b7f21394 Merge branch 'develop' into release/4.0 2025-06-12 21:12:08 +02:00
Lorenz Hilpert
a67375557d Merge branch 'develop' into release/4.0 2025-06-02 11:41:54 +02:00
Lorenz Hilpert
6e7c56fcb9 style(errors): standardize quotation marks in error exports 2025-05-28 21:32:41 +02:00
Lorenz Hilpert
05e257b922 Merge branch 'develop' into release/4.0 2025-05-13 18:52:00 +02:00
Lorenz Hilpert
d7d61915fa Merge branch 'develop' into release/4.0 2025-05-13 18:36:09 +02:00
Nino
d0220b6246 Merge branch 'develop' into release/4.0 2025-05-09 17:26:47 +02:00
Nino
32336ba5b4 Update index file return data-access 2025-05-09 12:13:25 +02:00
Nino
1f26d5285b Merge branch 'develop' into release/4.0 2025-05-09 12:12:19 +02:00
Michael Auer
be0bff0535 Cherry Pick: PR 1824: ISA-Frontend - Expliziter Pfad für Traefik IngressRoute
(cherry picked from commit c9b2762bbc)
2025-02-28 09:36:06 +01:00
Lorenz Hilpert
cb7391e66f Update version numbers in azure-pipelines.yml to 4.0 2025-02-10 10:43:23 +01:00
632 changed files with 44664 additions and 16728 deletions

View File

@@ -1,9 +0,0 @@
{
"permissions": {
"allow": [
"mcp__context7__resolve-library-id",
"mcp__context7__get-library-docs"
],
"deny": []
}
}

View File

@@ -4,6 +4,8 @@
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:

View File

@@ -1,40 +0,0 @@
---
applyTo: '**'
---
// This file is automatically generated by Nx Console
You are in an nx workspace using Nx 21.2.0 and npm as the package manager.
You have access to the Nx MCP server and the tools it provides. Use them. Follow these guidelines in order to best help the user:
# General Guidelines
- When answering questions, use the nx_workspace tool first to gain an understanding of the workspace architecture
- For questions around nx configuration, best practices or if you're unsure, use the nx_docs tool to get relevant, up-to-date docs!! Always use this instead of assuming things about nx configuration
- If the user needs help with an Nx configuration or project graph error, use the 'nx_workspace' tool to get any errors
- To help answer questions about the workspace structure or simply help with demonstrating how tasks depend on each other, use the 'nx_visualize_graph' tool
# Generation Guidelines
If the user wants to generate something, use the following flow:
- learn about the nx workspace and any specifics the user needs by using the 'nx_workspace' tool and the 'nx_project_details' tool if applicable
- get the available generators using the 'nx_generators' tool
- decide which generator to use. If no generators seem relevant, check the 'nx_available_plugins' tool to see if the user could install a plugin to help them
- get generator details using the 'nx_generator_schema' tool
- you may use the 'nx_docs' tool to learn more about a specific generator or technology if you're unsure
- decide which options to provide in order to best complete the user's request. Don't make any assumptions and keep the options minimalistic
- open the generator UI using the 'nx_open_generate_ui' tool
- wait for the user to finish the generator
- read the generator log file using the 'nx_read_generator_log' tool
- use the information provided in the log file to answer the user's question or continue with what they were doing
# Running Tasks Guidelines
If the user wants help with tasks or commands (which include keywords like "test", "build", "lint", or other similar actions), use the following flow:
- Use the 'nx_current_running_tasks_details' tool to get the list of tasks (this can include tasks that were completed, stopped or failed).
- If there are any tasks, ask the user if they would like help with a specific task then use the 'nx_current_running_task_output' tool to get the terminal output for that task/command
- Use the terminal output from 'nx_current_running_task_output' to see what's wrong and help the user fix their problem. Use the appropriate tools if necessary
- If the user would like to rerun the task or command, always use `nx run <taskId>` to rerun in the terminal. This will ensure that the task will run in the nx context and will be run the same way it originally executed
- If the task was marked as "continuous" do not offer to rerun the task. This task is already running and the user can see the output in the terminal. You can use 'nx_current_running_task_output' to get the output of the task to verify the output.

View File

@@ -2,8 +2,10 @@
## Framework and Tools
- Use **Jest** as the testing framework.
- For unit tests, utilize **Spectator** to simplify Angular component testing.
- **Vitest** is the recommended testing framework.
[Vitest Documentation (latest)](https://context7.com/vitest-dev/vitest/llms.txt?topic=getting+started)
- **Jest** and **Spectator** are **deprecated**.
Do not use them for new tests. Existing tests should be migrated to Vitest where possible.
## Guidelines
@@ -23,28 +25,31 @@
## Example Test Structure
```typescript
// Example using Jest and Spectator
import { createComponentFactory, Spectator } from '@ngneat/spectator';
// Example using Vitest (Jest and Spectator are deprecated)
import { describe, it, expect, beforeEach } from 'vitest';
import { render } from '@testing-library/angular';
import { MyComponent } from './my-component.component';
describe('MyComponent', () => {
let spectator: Spectator<MyComponent>;
const createComponent = createComponentFactory(MyComponent);
let component: MyComponent;
beforeEach(() => {
spectator = createComponent();
beforeEach(async () => {
const { fixture } = await render(MyComponent);
component = fixture.componentInstance;
});
it('should display the correct title', () => {
it('should display the correct title', async () => {
// Arrange
const expectedTitle = 'Hello World';
// Act
spectator.component.title = expectedTitle;
spectator.detectChanges();
component.title = expectedTitle;
// If using Angular, trigger change detection:
// fixture.detectChanges();
// Assert
expect(spectator.query('h1')).toHaveText(expectedTitle);
const compiled = fixture.nativeElement as HTMLElement;
expect(compiled.querySelector('h1')?.textContent).toBe(expectedTitle);
});
it('should handle error cases gracefully', () => {
@@ -52,15 +57,17 @@ describe('MyComponent', () => {
const invalidInput = null;
// Act
spectator.component.input = invalidInput;
component.input = invalidInput;
// Assert
expect(() => spectator.component.processInput()).toThrowError('Invalid input');
expect(() => component.processInput()).toThrowError('Invalid input');
});
});
```
## Additional Resources
- [Jest Documentation](https://jestjs.io/docs/getting-started)
- [Spectator Documentation](https://ngneat.github.io/spectator/)
- [Vitest Documentation (latest)](https://context7.com/vitest-dev/vitest/llms.txt?topic=getting+started)
- [Vitest Official Guide](https://vitest.dev/guide/)
- [Testing Library for Angular](https://testing-library.com/docs/angular-testing-library/intro/)
- **Jest** and **Spectator** documentation are deprecated

147
.gitignore vendored
View File

@@ -1,70 +1,77 @@
# See http://help.github.com/ignore-files/ for more about ignoring files.
.matomo
junit.xml
# compiled output
/dist
/tmp
/out-tsc
/
# dependencies
/node_modules
# profiling files
chrome-profiler-events.json
speed-measure-plugin.json
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*
# misc
/.angular/cache
/.sass-cache
/connect.lock
/coverage
/testresults
/libpeerconnection.log
npm-debug.log
yarn-error.log
yarn.lock
testem.log
/typings
# System Files
.DS_Store
Thumbs.db
libs/swagger/src/lib/*
*storybook.log
.nx/cache
.nx/workspace-data
.angular
storybook-static
.cursor\rules\nx-rules.mdc
.github\instructions\nx.instructions.md
.cursor/rules/nx-rules.mdc
.github/instructions/nx.instructions.md
vite.config.*.timestamp*
# See http://help.github.com/ignore-files/ for more about ignoring files.
.matomo
junit.xml
# compiled output
/dist
/tmp
/out-tsc
/
# dependencies
/node_modules
# profiling files
chrome-profiler-events.json
speed-measure-plugin.json
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*
# misc
/.angular/cache
/.sass-cache
/connect.lock
/coverage
/testresults
/libpeerconnection.log
npm-debug.log
yarn-error.log
yarn.lock
testem.log
/typings
# System Files
.DS_Store
Thumbs.db
libs/swagger/src/lib/*
*storybook.log
.nx/cache
.nx/workspace-data
.angular
.claude
storybook-static
.cursor\rules\nx-rules.mdc
.github\instructions\nx.instructions.md
.cursor/rules/nx-rules.mdc
.github/instructions/nx.instructions.md
vite.config.*.timestamp*
vitest.config.*.timestamp*
.mcp.json
.memory.json
nx.instructions.md

View File

@@ -1,7 +1,7 @@
{
"*.ts": "npx eslint --fix --config eslint.config.mjs",
"*.tsx": "npx eslint --fix --config eslint.config.mjs",
"*.js": "npx eslint --fix --config eslint.config.mjs",
"*.jsx": "npx eslint --fix --config eslint.config.mjs",
"*.html": "npx eslint --fix --config eslint.config.mjs"
}
{
"*.ts": "npx eslint --fix --config eslint.config.js",
"*.tsx": "npx eslint --fix --config eslint.config.js",
"*.js": "npx eslint --fix --config eslint.config.js",
"*.jsx": "npx eslint --fix --config eslint.config.js",
"*.html": "npx eslint --fix --config eslint.config.js"
}

View File

@@ -8,7 +8,7 @@ WORKDIR /app
COPY . .
RUN umask 0022
RUN npm version ${SEMVERSION}
RUN npm install --foreground-scripts --legacy-peer-deps
RUN npm install --foreground-scripts
RUN if [ "${IS_PRODUCTION}" = "true" ] ; then npm run-script build-prod ; else npm run-script build ; fi
# stage final

View File

@@ -1,55 +1,55 @@
import nx from '@nx/eslint-plugin';
import baseConfig from '../../eslint.config.mjs';
export default [
...baseConfig,
...nx.configs['flat/angular'],
...nx.configs['flat/angular-template'],
{
files: ['**/*.ts'],
rules: {
'@angular-eslint/directive-selector': [
'error',
{
type: 'attribute',
prefix: 'app',
style: 'camelCase',
},
],
'@angular-eslint/component-selector': [
'error',
{
type: 'element',
prefix: 'app',
style: 'kebab-case',
},
],
},
},
{
files: ['**/*.ts'],
rules: {
'@typescript-eslint/no-unused-expressions': 'warn',
'prefer-const': 'warn',
'@angular-eslint/contextual-lifecycle': 'warn',
'@typescript-eslint/no-explicit-any': 'warn',
'@angular-eslint/no-empty-lifecycle-method': 'warn',
'@typescript-eslint/no-inferrable-types': 'warn',
'@angular-eslint/component-selector': 'warn',
'@angular-eslint/prefer-standalone': 'warn',
'@typescript-eslint/no-inferrable-types': 'warn',
'no-empty-function': 'warn',
'@typescript-eslint/no-empty-function': 'warn',
'@typescript-eslint/no-unused-vars': 'warn',
'@angular-eslint/directive-selector': 'warn',
},
},
{
files: ['**/*.html'],
// Override or add rules here
rules: {
'@angular-eslint/template/elements-content': 'warn',
'@angular-eslint/template/no-autofocus': 'warn',
},
},
];
const nx = require('@nx/eslint-plugin');
const baseConfig = require('../../eslint.config.js');
module.exports = [
...baseConfig,
...nx.configs['flat/angular'],
...nx.configs['flat/angular-template'],
{
files: ['**/*.ts'],
rules: {
'@angular-eslint/directive-selector': [
'error',
{
type: 'attribute',
prefix: 'app',
style: 'camelCase',
},
],
'@angular-eslint/component-selector': [
'error',
{
type: 'element',
prefix: 'app',
style: 'kebab-case',
},
],
},
},
{
files: ['**/*.ts'],
rules: {
'@typescript-eslint/no-unused-expressions': 'warn',
'prefer-const': 'warn',
'@angular-eslint/contextual-lifecycle': 'warn',
'@typescript-eslint/no-explicit-any': 'warn',
'@angular-eslint/no-empty-lifecycle-method': 'warn',
'@typescript-eslint/no-inferrable-types': 'warn',
'@angular-eslint/component-selector': 'warn',
'@angular-eslint/prefer-standalone': 'warn',
'@typescript-eslint/no-inferrable-types': 'warn',
'no-empty-function': 'warn',
'@typescript-eslint/no-empty-function': 'warn',
'@typescript-eslint/no-unused-vars': 'warn',
'@angular-eslint/directive-selector': 'warn',
},
},
{
files: ['**/*.html'],
// Override or add rules here
rules: {
'@angular-eslint/template/elements-content': 'warn',
'@angular-eslint/template/no-autofocus': 'warn',
},
},
];

View File

@@ -38,7 +38,7 @@
],
"styles": [
"@angular/cdk/overlay-prebuilt.css",
"apps/isa-app/src/ui.scss",
"apps/isa-app/src/tailwind.scss",
"apps/isa-app/src/styles.scss"
],
"scripts": []
@@ -128,7 +128,7 @@
],
"styles": [
"@angular/cdk/overlay-prebuilt.css",
"apps/isa-app/src/ui.scss",
"apps/isa-app/src/tailwind.scss",
"apps/isa-app/src/styles.scss"
]
},
@@ -148,7 +148,7 @@
"compodoc": false,
"styles": [
"@angular/cdk/overlay-prebuilt.css",
"apps/isa-app/src/ui.scss",
"apps/isa-app/src/tailwind.scss",
"apps/isa-app/src/styles.scss"
]
},

View File

@@ -1,214 +1,231 @@
import { isDevMode, NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import {
CanActivateCartGuard,
CanActivateCartWithProcessIdGuard,
CanActivateCustomerGuard,
CanActivateCustomerOrdersGuard,
CanActivateCustomerOrdersWithProcessIdGuard,
CanActivateCustomerWithProcessIdGuard,
CanActivateGoodsInGuard,
CanActivateProductGuard,
CanActivateProductWithProcessIdGuard,
CanActivateRemissionGuard,
CanActivateTaskCalendarGuard,
IsAuthenticatedGuard,
} from './guards';
import { CanActivateAssortmentGuard } from './guards/can-activate-assortment.guard';
import { CanActivatePackageInspectionGuard } from './guards/can-activate-package-inspection.guard';
import { MainComponent } from './main.component';
import { PreviewComponent } from './preview';
import {
BranchSectionResolver,
CustomerSectionResolver,
ProcessIdResolver,
} from './resolvers';
import { TokenLoginComponent, TokenLoginModule } from './token-login';
import { ProcessIdGuard } from './guards/process-id.guard';
import {
ActivateProcessIdGuard,
ActivateProcessIdWithConfigKeyGuard,
} from './guards/activate-process-id.guard';
import { MatomoRouteData } from 'ngx-matomo-client';
import { tabResolverFn } from '@isa/core/tabs';
import { provideScrollPositionRestoration } from '@isa/utils/scroll-position';
const routes: Routes = [
{ path: '', redirectTo: 'kunde/dashboard', pathMatch: 'full' },
{
path: 'login',
children: [
{ path: ':token', component: TokenLoginComponent },
{ path: '**', redirectTo: 'kunde', pathMatch: 'full' },
],
},
{
path: '',
canActivate: [IsAuthenticatedGuard],
children: [
{
path: 'kunde',
component: MainComponent,
children: [
{
path: 'dashboard',
loadChildren: () =>
import('@page/dashboard').then((m) => m.DashboardModule),
data: {
matomo: {
title: 'Dashboard',
} as MatomoRouteData,
},
},
{
path: 'product',
loadChildren: () =>
import('@page/catalog').then((m) => m.PageCatalogModule),
canActivate: [CanActivateProductGuard],
},
{
path: ':processId/product',
loadChildren: () =>
import('@page/catalog').then((m) => m.PageCatalogModule),
canActivate: [CanActivateProductWithProcessIdGuard],
resolve: { processId: ProcessIdResolver },
},
{
path: 'order',
loadChildren: () =>
import('@page/customer-order').then((m) => m.CustomerOrderModule),
canActivate: [CanActivateCustomerOrdersGuard],
},
{
path: ':processId/order',
loadChildren: () =>
import('@page/customer-order').then((m) => m.CustomerOrderModule),
canActivate: [CanActivateCustomerOrdersWithProcessIdGuard],
resolve: { processId: ProcessIdResolver },
},
{
path: 'customer',
loadChildren: () =>
import('@page/customer').then((m) => m.CustomerModule),
canActivate: [CanActivateCustomerGuard],
},
{
path: ':processId/customer',
loadChildren: () =>
import('@page/customer').then((m) => m.CustomerModule),
canActivate: [CanActivateCustomerWithProcessIdGuard],
resolve: { processId: ProcessIdResolver },
},
{
path: 'cart',
loadChildren: () =>
import('@page/checkout').then((m) => m.PageCheckoutModule),
canActivate: [CanActivateCartGuard],
},
{
path: ':processId/cart',
loadChildren: () =>
import('@page/checkout').then((m) => m.PageCheckoutModule),
canActivate: [CanActivateCartWithProcessIdGuard],
},
{
path: 'pickup-shelf',
canActivate: [ProcessIdGuard],
// NOTE: This is a workaround for the canActivate guard not being called
loadChildren: () =>
import('@page/pickup-shelf').then((m) => m.PickupShelfOutModule),
},
{
path: ':processId/pickup-shelf',
canActivate: [ActivateProcessIdGuard],
loadChildren: () =>
import('@page/pickup-shelf').then((m) => m.PickupShelfOutModule),
},
{ path: '**', redirectTo: 'dashboard', pathMatch: 'full' },
],
resolve: { section: CustomerSectionResolver },
},
{
path: 'filiale',
component: MainComponent,
children: [
{
path: 'task-calendar',
loadChildren: () =>
import('@page/task-calendar').then(
(m) => m.PageTaskCalendarModule,
),
canActivate: [CanActivateTaskCalendarGuard],
},
{
path: 'pickup-shelf',
canActivate: [ActivateProcessIdWithConfigKeyGuard('pickupShelf')],
// NOTE: This is a workaround for the canActivate guard not being called
loadChildren: () =>
import('@page/pickup-shelf').then((m) => m.PickupShelfInModule),
},
{
path: 'goods/in',
loadChildren: () =>
import('@page/goods-in').then((m) => m.GoodsInModule),
canActivate: [CanActivateGoodsInGuard],
},
{
path: 'remission',
loadChildren: () =>
import('@page/remission').then((m) => m.PageRemissionModule),
canActivate: [CanActivateRemissionGuard],
},
{
path: 'package-inspection',
loadChildren: () =>
import('@page/package-inspection').then(
(m) => m.PackageInspectionModule,
),
canActivate: [CanActivatePackageInspectionGuard],
},
{
path: 'assortment',
loadChildren: () =>
import('@page/assortment').then((m) => m.AssortmentModule),
canActivate: [CanActivateAssortmentGuard],
},
{ path: '**', redirectTo: 'task-calendar', pathMatch: 'full' },
],
resolve: { section: BranchSectionResolver },
},
],
},
{
path: ':tabId',
component: MainComponent,
resolve: { process: tabResolverFn, tab: tabResolverFn },
canActivate: [IsAuthenticatedGuard],
children: [
{
path: 'return',
loadChildren: () =>
import('@isa/oms/feature/return-search').then((m) => m.routes),
},
{
path: 'remission',
loadChildren: () =>
import('@isa/remission/feature/remission-list').then((m) => m.routes),
},
],
},
];
if (isDevMode()) {
routes.unshift({
path: 'preview',
component: PreviewComponent,
});
}
@NgModule({
imports: [RouterModule.forRoot(routes), TokenLoginModule],
exports: [RouterModule],
providers: [provideScrollPositionRestoration()],
})
export class AppRoutingModule {}
import { isDevMode, NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import {
CanActivateCartGuard,
CanActivateCartWithProcessIdGuard,
CanActivateCustomerGuard,
CanActivateCustomerOrdersGuard,
CanActivateCustomerOrdersWithProcessIdGuard,
CanActivateCustomerWithProcessIdGuard,
CanActivateGoodsInGuard,
CanActivateProductGuard,
CanActivateProductWithProcessIdGuard,
CanActivateRemissionGuard,
CanActivateTaskCalendarGuard,
IsAuthenticatedGuard,
} from './guards';
import { CanActivateAssortmentGuard } from './guards/can-activate-assortment.guard';
import { CanActivatePackageInspectionGuard } from './guards/can-activate-package-inspection.guard';
import { MainComponent } from './main.component';
import { PreviewComponent } from './preview';
import {
BranchSectionResolver,
CustomerSectionResolver,
ProcessIdResolver,
} from './resolvers';
import { TokenLoginComponent, TokenLoginModule } from './token-login';
import { ProcessIdGuard } from './guards/process-id.guard';
import {
ActivateProcessIdGuard,
ActivateProcessIdWithConfigKeyGuard,
} from './guards/activate-process-id.guard';
import { MatomoRouteData } from 'ngx-matomo-client';
import { tabResolverFn } from '@isa/core/tabs';
import { provideScrollPositionRestoration } from '@isa/utils/scroll-position';
const routes: Routes = [
{ path: '', redirectTo: 'kunde/dashboard', pathMatch: 'full' },
{
path: 'login',
children: [
{ path: ':token', component: TokenLoginComponent },
{ path: '**', redirectTo: 'kunde', pathMatch: 'full' },
],
},
{
path: '',
canActivate: [IsAuthenticatedGuard],
children: [
{
path: 'kunde',
component: MainComponent,
children: [
{
path: 'dashboard',
loadChildren: () =>
import('@page/dashboard').then((m) => m.DashboardModule),
data: {
matomo: {
title: 'Dashboard',
} as MatomoRouteData,
},
},
{
path: 'product',
loadChildren: () =>
import('@page/catalog').then((m) => m.PageCatalogModule),
canActivate: [CanActivateProductGuard],
},
{
path: ':processId/product',
loadChildren: () =>
import('@page/catalog').then((m) => m.PageCatalogModule),
canActivate: [CanActivateProductWithProcessIdGuard],
resolve: { processId: ProcessIdResolver },
},
{
path: 'order',
loadChildren: () =>
import('@page/customer-order').then((m) => m.CustomerOrderModule),
canActivate: [CanActivateCustomerOrdersGuard],
},
{
path: ':processId/order',
loadChildren: () =>
import('@page/customer-order').then((m) => m.CustomerOrderModule),
canActivate: [CanActivateCustomerOrdersWithProcessIdGuard],
resolve: { processId: ProcessIdResolver },
},
{
path: 'customer',
loadChildren: () =>
import('@page/customer').then((m) => m.CustomerModule),
canActivate: [CanActivateCustomerGuard],
},
{
path: ':processId/customer',
loadChildren: () =>
import('@page/customer').then((m) => m.CustomerModule),
canActivate: [CanActivateCustomerWithProcessIdGuard],
resolve: { processId: ProcessIdResolver },
},
{
path: 'cart',
loadChildren: () =>
import('@page/checkout').then((m) => m.PageCheckoutModule),
canActivate: [CanActivateCartGuard],
},
{
path: ':processId/cart',
loadChildren: () =>
import('@page/checkout').then((m) => m.PageCheckoutModule),
canActivate: [CanActivateCartWithProcessIdGuard],
},
{
path: 'pickup-shelf',
canActivate: [ProcessIdGuard],
// NOTE: This is a workaround for the canActivate guard not being called
loadChildren: () =>
import('@page/pickup-shelf').then((m) => m.PickupShelfOutModule),
},
{
path: ':processId/pickup-shelf',
canActivate: [ActivateProcessIdGuard],
loadChildren: () =>
import('@page/pickup-shelf').then((m) => m.PickupShelfOutModule),
},
{ path: '**', redirectTo: 'dashboard', pathMatch: 'full' },
],
resolve: { section: CustomerSectionResolver },
},
{
path: 'filiale',
component: MainComponent,
children: [
{
path: 'task-calendar',
loadChildren: () =>
import('@page/task-calendar').then(
(m) => m.PageTaskCalendarModule,
),
canActivate: [CanActivateTaskCalendarGuard],
},
{
path: 'pickup-shelf',
canActivate: [ActivateProcessIdWithConfigKeyGuard('pickupShelf')],
// NOTE: This is a workaround for the canActivate guard not being called
loadChildren: () =>
import('@page/pickup-shelf').then((m) => m.PickupShelfInModule),
},
{
path: 'goods/in',
loadChildren: () =>
import('@page/goods-in').then((m) => m.GoodsInModule),
canActivate: [CanActivateGoodsInGuard],
},
// {
// path: 'remission',
// loadChildren: () =>
// import('@page/remission').then((m) => m.PageRemissionModule),
// canActivate: [CanActivateRemissionGuard],
// },
{
path: 'package-inspection',
loadChildren: () =>
import('@page/package-inspection').then(
(m) => m.PackageInspectionModule,
),
canActivate: [CanActivatePackageInspectionGuard],
},
{
path: 'assortment',
loadChildren: () =>
import('@page/assortment').then((m) => m.AssortmentModule),
canActivate: [CanActivateAssortmentGuard],
},
{ path: '**', redirectTo: 'task-calendar', pathMatch: 'full' },
],
resolve: { section: BranchSectionResolver },
},
],
},
{
path: ':tabId',
component: MainComponent,
resolve: { process: tabResolverFn, tab: tabResolverFn },
canActivate: [IsAuthenticatedGuard],
children: [
{
path: 'return',
loadChildren: () =>
import('@isa/oms/feature/return-search').then((m) => m.routes),
},
{
path: 'remission',
children: [
{
path: 'return-receipt',
loadChildren: () =>
import(
'@isa/remission/feature/remission-return-receipt-list'
).then((m) => m.routes),
},
{
path: '',
loadChildren: () =>
import('@isa/remission/feature/remission-list').then(
(m) => m.routes,
),
},
],
},
],
},
];
if (isDevMode()) {
routes.unshift({
path: 'preview',
component: PreviewComponent,
});
}
@NgModule({
imports: [
RouterModule.forRoot(routes, { bindToComponentInputs: true }),
TokenLoginModule,
],
exports: [RouterModule],
providers: [provideScrollPositionRestoration()],
})
export class AppRoutingModule {}

View File

@@ -4,6 +4,7 @@ import {
withInterceptorsFromDi,
} from '@angular/common/http';
import {
DEFAULT_CURRENCY_CODE,
ErrorHandler,
Injector,
LOCALE_ID,
@@ -228,6 +229,10 @@ export function _notificationsHubOptionsFactory(
withRouteData(),
),
provideLogging(withLogLevel(LogLevel.Debug), withSink(ConsoleLogSink)),
{
provide: DEFAULT_CURRENCY_CODE,
useValue: 'EUR',
},
],
})
export class AppModule {}

View File

@@ -1,7 +1,6 @@
import { Platform, PlatformModule } from '@angular/cdk/platform';
import { CommonModule } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { BranchSelectorComponent } from '@shared/components/branch-selector';
import { Component } from '@angular/core';
import { BranchDTO } from '@generated/swagger/checkout-api';
import { BehaviorSubject } from 'rxjs';
@@ -9,9 +8,9 @@ import { BehaviorSubject } from 'rxjs';
selector: 'app-preview',
templateUrl: 'preview.component.html',
styleUrls: ['preview.component.css'],
imports: [CommonModule, BranchSelectorComponent, PlatformModule],
imports: [CommonModule, PlatformModule],
})
export class PreviewComponent implements OnInit {
export class PreviewComponent {
selectedBranch$ = new BehaviorSubject<BranchDTO>({});
get appVersion() {
@@ -24,7 +23,7 @@ export class PreviewComponent implements OnInit {
get navigator() {
const nav = {};
for (let i in window.navigator) nav[i] = navigator[i];
for (const i in window.navigator) nav[i] = navigator[i];
return nav;
}
@@ -51,8 +50,6 @@ export class PreviewComponent implements OnInit {
constructor(private readonly _platform: Platform) {}
ngOnInit() {}
setNewBranch(branch: BranchDTO) {
this.selectedBranch$.next(branch);
}

View File

@@ -1,11 +1,16 @@
import { HttpErrorResponse } from '@angular/common/http';
import { ErrorHandler, Injectable } from '@angular/core';
import { AuthService } from '@core/auth';
import { DialogModel, UiDialogModalComponent, UiErrorModalComponent, UiModalService } from '@ui/modal';
import { IsaLogProvider } from './isa.log-provider';
import { LogLevel } from '@core/logger';
import { HttpErrorResponse } from "@angular/common/http";
import { ErrorHandler, Injectable } from "@angular/core";
import { AuthService } from "@core/auth";
import {
DialogModel,
UiDialogModalComponent,
UiErrorModalComponent,
UiModalService,
} from "@ui/modal";
import { IsaLogProvider } from "./isa.log-provider";
import { LogLevel } from "@core/logger";
@Injectable({ providedIn: 'root' })
@Injectable({ providedIn: "root" })
export class IsaErrorHandler implements ErrorHandler {
constructor(
private _modal: UiModalService,
@@ -17,7 +22,7 @@ export class IsaErrorHandler implements ErrorHandler {
console.error(error);
// Bei Klick auf Abbrechen auf der Login Seite erneut zur Login Seite weiterleiten
if (error?.type === 'token_error') {
if (error?.type === "token_error") {
this._authService.login();
return;
}
@@ -26,11 +31,14 @@ export class IsaErrorHandler implements ErrorHandler {
await this._modal
.open({
content: UiDialogModalComponent,
title: 'Sitzung abgelaufen',
title: "Sitzung abgelaufen",
data: {
handleCommand: false,
content: 'Sie waren zu lange nicht in der ISA aktiv. Bitte melden Sie sich erneut an',
actions: [{ command: 'CLOSE', selected: true, label: 'Erneut anmelden' }],
content:
"Sie waren zu lange nicht in der ISA aktiv. Bitte melden Sie sich erneut an",
actions: [
{ command: "CLOSE", selected: true, label: "Erneut anmelden" },
],
} as DialogModel,
})
.afterClosed$.toPromise();
@@ -39,7 +47,11 @@ export class IsaErrorHandler implements ErrorHandler {
return;
}
this._isaLogProvider.log(LogLevel.ERROR, 'Client Error', error);
try {
this._isaLogProvider.log(LogLevel.ERROR, "Client Error", error);
} catch (logError) {
console.error("Error logging to IsaLogProvider:", logError);
}
// this._modal.open({
// content: UiErrorModalComponent,

View File

@@ -1,28 +1,36 @@
import { Injectable, Injector } from '@angular/core';
import { LogLevel, LogProvider } from '@core/logger';
import { UserStateService } from '@generated/swagger/isa-api';
import { environment } from '../../environments/environment';
import { Injectable } from "@angular/core";
import { LogLevel, LogProvider } from "@core/logger";
import { UserStateService } from "@generated/swagger/isa-api";
import { environment } from "../../environments/environment";
@Injectable({ providedIn: 'root' })
@Injectable({ providedIn: "root" })
export class IsaLogProvider implements LogProvider {
static InfoService: UserStateService | undefined;
constructor() {}
log(logLevel: LogLevel, message: string, error: Error, ...optionalParams: any[]): void {
if (!environment.production && (logLevel === LogLevel.WARN || logLevel === LogLevel.ERROR)) {
IsaLogProvider.InfoService?.UserStateSaveLog({
logType: logLevel,
message: message,
content: JSON.stringify({
error: error?.name,
message: error?.message,
stack: error?.stack,
data: optionalParams,
}),
})
.toPromise()
.catch(() => {});
log(
logLevel: LogLevel,
message: string,
error: Error,
...optionalParams: any[]
): void {
try {
if (
!environment.production &&
(logLevel === LogLevel.WARN || logLevel === LogLevel.ERROR)
) {
IsaLogProvider.InfoService?.UserStateSaveLog({
logType: logLevel,
message: message,
content: JSON.stringify({
error: error?.name,
message: error?.message,
stack: error?.stack,
data: optionalParams,
}),
}).toPromise();
}
} catch (error) {
console.error("Error logging to InfoService:", error);
}
}
}

View File

@@ -1,18 +1,18 @@
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';
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' })
@Injectable({ providedIn: "root" })
export class RootStateService {
static LOCAL_STORAGE_KEY = 'ISA_APP_INITIALSTATE';
static LOCAL_STORAGE_KEY = "ISA_APP_INITIALSTATE";
#storage = injectStorage(UserStorageProvider);
@@ -29,14 +29,17 @@ export class RootStateService {
);
}
window['clearUserState'] = () => {
window["clearUserState"] = () => {
this.clear();
};
}
async init() {
await this.load();
this._store.dispatch({ type: 'HYDRATE', payload: RootStateService.LoadFromLocalStorage() });
this._store.dispatch({
type: "HYDRATE",
payload: RootStateService.LoadFromLocalStorage(),
});
this.initSave();
}
@@ -50,14 +53,10 @@ export class RootStateService {
const data = {
...state,
version: packageInfo.version,
sub: this._authService.getClaimByKey('sub'),
sub: this._authService.getClaimByKey("sub"),
};
RootStateService.SaveToLocalStorageRaw(JSON.stringify(data));
return this.#storage.set('state', {
...state,
version: packageInfo.version,
sub: this._authService.getClaimByKey('sub'),
});
return this.#storage.set("state", data);
}),
)
.subscribe();
@@ -68,7 +67,7 @@ export class RootStateService {
*/
async load(): Promise<boolean> {
try {
const res = await this.#storage.get('state');
const res = await this.#storage.get("state");
const storageContent = RootStateService.LoadFromLocalStorageRaw();
@@ -88,7 +87,7 @@ export class RootStateService {
async clear() {
try {
this._cancelSave.next();
await this.#storage.clear('state');
await this.#storage.clear("state");
await new Promise((resolve) => setTimeout(resolve, 100));
RootStateService.RemoveFromLocalStorage();
await new Promise((resolve) => setTimeout(resolve, 100));
@@ -112,7 +111,7 @@ export class RootStateService {
try {
return JSON.parse(raw);
} catch (error) {
console.error('Error parsing local storage:', error);
console.error("Error parsing local storage:", error);
this.RemoveFromLocalStorage();
}
}

View File

@@ -1,5 +1,4 @@
import { Injectable } from '@angular/core';
import { LogLevel } from './log-level';
import { LogLevel } from "./log-level";
export interface LogProvider {
log(logLevel: LogLevel, message: string, ...optionalParams: any[]): void;

View File

@@ -1,5 +1,9 @@
import { Injectable } from '@angular/core';
import { ItemDTO, ListResponseArgsOfItemDTO, SearchService } from '@generated/swagger/cat-search-api';
import {
ItemDTO,
ListResponseArgsOfItemDTO,
SearchService,
} from '@generated/swagger/cat-search-api';
import {
RemiService,
StockService,
@@ -18,7 +22,11 @@ import { memorize } from '@utils/common';
import { Observable, of, throwError } from 'rxjs';
import { catchError, map, shareReplay, switchMap } from 'rxjs/operators';
import { RemissionListItem } from './defs';
import { fromItemDto, mapFromReturnItemDTO, mapFromReturnSuggestionDTO } from './mappings';
import {
fromItemDto,
mapFromReturnItemDTO,
mapFromReturnSuggestionDTO,
} from './mappings';
import { Logger } from '@core/logger';
import { RemissionPlacementType } from '@domain/remission';
@@ -204,7 +212,10 @@ export class DomainRemissionService {
);
}
getStockInformation(items: RemissionListItem[], recalculate: boolean = false) {
getStockInformation(
items: RemissionListItem[],
recalculate: boolean = false,
) {
return this.getCurrentStock().pipe(
switchMap((stock) =>
this._stockService
@@ -218,7 +229,8 @@ export class DomainRemissionService {
map((res) => {
const o = items.map((item) => {
const stockInfo = res?.result?.find(
(stockInfo) => stockInfo.itemId === +item.dto.product.catalogProductNumber,
(stockInfo) =>
stockInfo.itemId === +item.dto.product.catalogProductNumber,
);
if (!stockInfo) {
@@ -231,7 +243,8 @@ export class DomainRemissionService {
return { ...item, ...defaultStockData };
}
const availableStock = stockInfo.inStock - stockInfo.removedFromStock;
const availableStock =
stockInfo.inStock - stockInfo.removedFromStock;
const inStock = availableStock < 0 ? 0 : availableStock;
let { remainingQuantity, remissionQuantity } = item;
@@ -249,7 +262,12 @@ export class DomainRemissionService {
}
}
return { ...item, remainingQuantity, remissionQuantity, inStock };
return {
...item,
remainingQuantity,
remissionQuantity,
inStock,
};
});
return o;
@@ -259,7 +277,10 @@ export class DomainRemissionService {
);
}
getRequiredCapacities(params: { departments?: string[]; supplierId: number }) {
getRequiredCapacities(params: {
departments?: string[];
supplierId: number;
}) {
return this.getCurrentStock().pipe(
switchMap((stock) =>
this._remiService
@@ -301,13 +322,18 @@ export class DomainRemissionService {
);
}
canAddReturnItem(item: ReturnItemDTO): Observable<BatchResponseArgsOfReturnItemDTOAndReturnItemDTO> {
canAddReturnItem(
item: ReturnItemDTO,
): Observable<BatchResponseArgsOfReturnItemDTOAndReturnItemDTO> {
return this._remiService.RemiCanAddReturnItem({
data: [item],
});
}
async createReturn(supplierId: number, returnGroup?: string): Promise<ReturnDTO> {
async createReturn(
supplierId: number,
returnGroup?: string,
): Promise<ReturnDTO> {
const response = await this._returnService
.ReturnCreateReturn({
data: {
@@ -343,7 +369,10 @@ export class DomainRemissionService {
.toPromise();
}
getReturns(params: { start?: Date; returncompleted: boolean }): Observable<ReturnDTO[]> {
getReturns(params: {
start?: Date;
returncompleted: boolean;
}): Observable<ReturnDTO[]> {
const queryToken: ReturnQueryTokenDTO = {
start: params.start?.toISOString(),
filter: {
@@ -360,13 +389,20 @@ export class DomainRemissionService {
});
return this.getCurrentStock().pipe(
switchMap((stock) => this._returnService.ReturnQueryReturns({ stockId: stock.id, queryToken })),
switchMap((stock) =>
this._returnService.ReturnQueryReturns({
stockId: stock.id,
queryToken,
}),
),
map((res) => res.result),
);
}
getReturn(returnId: number): Observable<ReturnDTO> {
return this._returnService.ReturnGetReturn({ returnId, eagerLoading: 3 }).pipe(map((res) => res.result));
return this._returnService
.ReturnGetReturn({ returnId, eagerLoading: 3 })
.pipe(map((res) => res.result));
}
async deleteReturn(returnId: number) {
@@ -393,7 +429,11 @@ export class DomainRemissionService {
inStock: number;
}) {
return this._returnService
.ReturnAddReturnItem({ returnId, receiptId, data: { returnItemId, quantity, placementType, inStock } })
.ReturnAddReturnItem({
returnId,
receiptId,
data: { returnItemId, quantity, placementType, inStock },
})
.pipe(map((r) => r.result));
}
@@ -420,7 +460,14 @@ export class DomainRemissionService {
.ReturnAddReturnSuggestion({
returnId,
receiptId,
data: { returnSuggestionId, quantity, placementType, inStock, impedimentComment, remainingQuantity },
data: {
returnSuggestionId,
quantity,
placementType,
inStock,
impedimentComment,
remainingQuantity,
},
})
.pipe(map((r) => r.result));
}
@@ -438,18 +485,28 @@ export class DomainRemissionService {
receiptId: number;
receiptItemId: number;
}) {
return this._returnService.ReturnRemoveReturnItem({ returnId, receiptItemId, receiptId });
return this._returnService.ReturnRemoveReturnItem({
returnId,
receiptItemId,
receiptId,
});
}
returnImpediment(itemId: number) {
return this._returnService
.ReturnReturnItemImpediment({ itemId, data: { comment: 'Produkt nicht gefunden' } })
.ReturnReturnItemImpediment({
itemId,
data: { comment: 'Produkt nicht gefunden' },
})
.pipe(map((r) => r.result));
}
returnSuggestion(itemId: number) {
return this._returnService
.ReturnReturnSuggestionImpediment({ itemId, data: { comment: 'Produkt nicht gefunden' } })
.ReturnReturnSuggestionImpediment({
itemId,
data: { comment: 'Produkt nicht gefunden' },
})
.pipe(map((r) => r.result));
}
@@ -459,7 +516,10 @@ export class DomainRemissionService {
* @param receiptNumber Receipt number
* @returns ReceiptDTO
*/
async createReceipt(returnDTO: ReturnDTO, receiptNumber?: string): Promise<ReceiptDTO> {
async createReceipt(
returnDTO: ReturnDTO,
receiptNumber?: string,
): Promise<ReceiptDTO> {
const stock = await this._getStock();
const response = await this._returnService
@@ -510,7 +570,10 @@ export class DomainRemissionService {
return receipt;
}
async completeReceipt(returnId: number, receiptId: number): Promise<ReceiptDTO> {
async completeReceipt(
returnId: number,
receiptId: number,
): Promise<ReceiptDTO> {
const res = await this._returnService
.ReturnFinalizeReceipt({
returnId,

View File

@@ -1,21 +1,22 @@
import { enableProdMode, isDevMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { CONFIG_DATA } from '@isa/core/config';
import { setDefaultOptions } from 'date-fns';
import { de } from 'date-fns/locale';
import * as moment from 'moment';
import { enableProdMode, isDevMode } from "@angular/core";
import { platformBrowserDynamic } from "@angular/platform-browser-dynamic";
import { CONFIG_DATA } from "@isa/core/config";
import { setDefaultOptions } from "date-fns";
import { de } from "date-fns/locale";
import * as moment from "moment";
import "moment/locale/de";
setDefaultOptions({ locale: de });
moment.locale('de');
moment.locale("de");
import { AppModule } from './app/app.module';
import { AppModule } from "./app/app.module";
if (!isDevMode()) {
enableProdMode();
}
async function bootstrap() {
const configRes = await fetch('/config/config.json');
const configRes = await fetch("/config/config.json");
const config = await configRes.json();

View File

@@ -1,10 +1,18 @@
<div class="notification-list scroll-bar">
@for (notification of notifications; track notification) {
<modal-notifications-list-item [item]="notification" (itemSelected)="itemSelected($event)"></modal-notifications-list-item>
<modal-notifications-list-item
[item]="notification"
(itemSelected)="itemSelected($event)"
></modal-notifications-list-item>
<hr />
}
</div>
<div class="actions">
<a class="cta-primary" [routerLink]="['/filiale/remission/create']" (click)="navigated.emit()">Zur Remission</a>
<a
class="cta-primary"
[routerLink]="remissionPath()"
(click)="navigated.emit()"
>Zur Remission</a
>
</div>

View File

@@ -1,8 +1,17 @@
import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output, inject } from '@angular/core';
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',
@@ -11,7 +20,10 @@ import { MessageBoardItemDTO } from '@hub/notifications';
standalone: false,
})
export class ModalNotificationsRemissionGroupComponent {
private _pickupShelfInNavigationService = inject(PickupShelfInNavigationService);
tabService = inject(TabService);
private _pickupShelfInNavigationService = inject(
PickupShelfInNavigationService,
);
@Input()
notifications: MessageBoardItemDTO[];
@@ -19,11 +31,19 @@ export class ModalNotificationsRemissionGroupComponent {
@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);
const queryParams = UiFilter.getQueryParamsFromQueryTokenDTO(
item.queryToken,
);
this._router.navigate(defaultNav.path, {
queryParams: {
...defaultNav.queryParams,

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,30 +117,35 @@ 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.p4mUser !== this.p4mUser || initial.customerType !== this.customerType) {
// this.setValue({ customerType: this.customerType, p4mUser: this.p4mUser });
// }
return result;
}),
@@ -224,42 +235,53 @@ 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 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,9 +1,9 @@
@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
class="rounded-full ml-4 h-8 w-8 text-xl text-center border-2 border-solid border-brand text-brand">i</span> -->
<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>
<p class="description">
Um Sie als Kunde beim nächsten
@@ -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

@@ -7,7 +7,6 @@ import { UiSelectModule } from '@ui/select';
import { UiIconModule } from '@ui/icon';
import { FormGroup, ReactiveFormsModule } from '@angular/forms';
import { RouterLink } from '@angular/router';
import { UiDateInputDirective } from '@ui/input';
import { validateCompanyOrPersonalInfoRequired } from '../../validators/gender-b2b-validator';
@Component({
@@ -23,7 +22,6 @@ import { validateCompanyOrPersonalInfoRequired } from '../../validators/gender-b
UiIconModule,
ReactiveFormsModule,
RouterLink,
UiDateInputDirective,
],
})
export class CustomerDataEditB2BComponent extends CustomerDataEditComponent {

View File

@@ -1,12 +1,11 @@
import { Component, ChangeDetectionStrategy, OnInit, OnDestroy, inject } from '@angular/core';
import { CustomerSearchStore } from '../store';
import { ActivatedRoute, RouterLink } from '@angular/router';
import { ActivatedRoute } from '@angular/router';
import { Subject, combineLatest, of } from 'rxjs';
import { catchError, map, share, switchMap } from 'rxjs/operators';
import { CrmCustomerService } from '@domain/crm';
import { KundenkarteComponent } from '../../components/kundenkarte';
import { AsyncPipe } from '@angular/common';
import { IconComponent } from '@shared/components/icon';
import { CustomerSearchNavigation } from '@shared/services/navigation';
import { BonusCardInfoDTO } from '@generated/swagger/crm-api';
import { CustomerMenuComponent } from '../../components/customer-menu';
@@ -17,7 +16,7 @@ import { CustomerMenuComponent } from '../../components/customer-menu';
styleUrls: ['kundenkarte-main-view.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush,
host: { class: 'page-customer-kundenkarte-main-view' },
imports: [CustomerMenuComponent, KundenkarteComponent, AsyncPipe, IconComponent, RouterLink],
imports: [CustomerMenuComponent, KundenkarteComponent, AsyncPipe],
})
export class KundenkarteMainViewComponent implements OnInit, OnDestroy {
private _store = inject(CustomerSearchStore);

View File

@@ -19,7 +19,7 @@ import { AddressPipe } from '@shared/pipes/customer';
import { IconComponent } from '@shared/components/icon';
import { CustomerSearchNavigation } from '@shared/services/navigation';
import { CustomerOrderItemListItemComponent } from './order-item-list-item/order-item-list-item.component';
import { GroupByPipe, groupBy } from '@ui/common';
import { groupBy } from '@ui/common';
import { EnvironmentService } from '@core/environment';
@Component({
@@ -40,7 +40,6 @@ import { EnvironmentService } from '@core/environment';
RouterLink,
CustomerOrderItemListItemComponent,
NgFor,
GroupByPipe,
NgSwitch,
NgSwitchCase,
NgSwitchDefault,

View File

@@ -2,9 +2,7 @@ import { AsyncPipe, CurrencyPipe, DatePipe } from '@angular/common';
import { Component, ChangeDetectionStrategy, Input, OnDestroy, OnInit, inject } from '@angular/core';
import { ActivatedRoute, RouterLink } from '@angular/router';
import { ProductImagePipe } from '@cdn/product-image';
import { IconComponent } from '@shared/components/icon';
import { BranchNamePipe, ResolveBranchPipe } from '@shared/pipes/branch';
import { OrderItemProcessingStatusPipe, OrderProcessingStatusPipe } from '@shared/pipes/order';
import { OrderItemProcessingStatusPipe } from '@shared/pipes/order';
import { OrderItemDTO } from '@generated/swagger/oms-api';
import { BehaviorSubject, Subject, combineLatest } from 'rxjs';
import { map, takeUntil } from 'rxjs/operators';
@@ -21,16 +19,12 @@ import { PaymentTypePipe } from '@shared/pipes/customer';
imports: [
AsyncPipe,
DatePipe,
OrderProcessingStatusPipe,
ProductImagePipe,
ResolveBranchPipe,
BranchNamePipe,
CurrencyPipe,
IconComponent,
RouterLink,
PaymentTypePipe,
OrderItemProcessingStatusPipe
],
],
})
export class CustomerOrderItemListItemComponent implements OnInit, OnDestroy {
private _activatedRoute = inject(ActivatedRoute);

View File

@@ -4,8 +4,6 @@ import { map } from 'rxjs/operators';
import { CustomerNamePipe } from '@shared/pipes/customer';
import { AsyncPipe } from '@angular/common';
import { ProductImagePipe } from '@cdn/product-image';
import { CustomerSearchNavigation } from '@shared/services/navigation';
import { RouterLink, RouterLinkActive } from '@angular/router';
import { OrderItemProcessingStatusPipe } from '@shared/pipes/order';
@Component({
@@ -18,8 +16,6 @@ import { OrderItemProcessingStatusPipe } from '@shared/pipes/order';
CustomerNamePipe,
AsyncPipe,
ProductImagePipe,
RouterLink,
RouterLinkActive,
OrderItemProcessingStatusPipe
],
})

View File

@@ -1,6 +1,6 @@
import { AsyncPipe, CurrencyPipe, DatePipe } from '@angular/common';
import { Component, ChangeDetectionStrategy, Input, inject } from '@angular/core';
import { OrderDestinationPipe, OrderProcessingStatusPipe } from '@shared/pipes/order';
import { OrderProcessingStatusPipe } from '@shared/pipes/order';
import { AddressPipe } from '@shared/pipes/customer';
import { OrderListItemDTO } from '@generated/swagger/oms-api';
@@ -19,7 +19,6 @@ import { RouterLink } from '@angular/router';
imports: [
DatePipe,
OrderProcessingStatusPipe,
OrderDestinationPipe,
CurrencyPipe,
AddressPipe,
AsyncPipe,

View File

@@ -4,8 +4,6 @@ import { Subject, combineLatest } from 'rxjs';
import { distinctUntilChanged, map, takeUntil } from 'rxjs/operators';
import { AsyncPipe } from '@angular/common';
import { CustomerSearchNavigation } from '@shared/services/navigation';
import { RouterLink } from '@angular/router';
import { IconComponent } from '@shared/components/icon';
import { LoaderComponent } from '@shared/components/loader';
import { CustomerOrderListItemComponent } from './order-list-item/order-list-item.component';
import { CustomerMenuComponent } from '../../components/customer-menu';
@@ -19,8 +17,6 @@ import { CustomerMenuComponent } from '../../components/customer-menu';
imports: [
CustomerMenuComponent,
AsyncPipe,
RouterLink,
IconComponent,
LoaderComponent,
CustomerOrderListItemComponent
],

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

@@ -16,13 +16,34 @@
[deltaEnd]="150"
[itemLength]="itemLength$ | async"
[containerHeight]="24.5"
>
@for (bueryNumberGroup of items$ | async | groupBy: byBuyerNumberFn; track bueryNumberGroup) {
>
@for (
bueryNumberGroup of items$ | async | groupBy: byBuyerNumberFn;
track bueryNumberGroup
) {
<shared-goods-in-out-order-group>
@for (orderNumberGroup of bueryNumberGroup.items | groupBy: byOrderNumberFn; track orderNumberGroup; let lastOrderNumber = $last) {
@for (processingStatusGroup of orderNumberGroup.items | groupBy: byProcessingStatusFn; track processingStatusGroup; let lastProcessingStatus = $last) {
@for (compartmentCodeGroup of processingStatusGroup.items | groupBy: byCompartmentCodeFn; track compartmentCodeGroup; let lastCompartmentCode = $last) {
@for (item of compartmentCodeGroup.items; track item; let firstItem = $first) {
@for (
orderNumberGroup of bueryNumberGroup.items | groupBy: byOrderNumberFn;
track orderNumberGroup;
let lastOrderNumber = $last
) {
@for (
processingStatusGroup of orderNumberGroup.items
| groupBy: byProcessingStatusFn;
track processingStatusGroup;
let lastProcessingStatus = $last
) {
@for (
compartmentCodeGroup of processingStatusGroup.items
| groupBy: byCompartmentCodeFn;
track compartmentCodeGroup;
let lastCompartmentCode = $last
) {
@for (
item of compartmentCodeGroup.items;
track item;
let firstItem = $first
) {
<shared-goods-in-out-order-group-item
[item]="item"
[showCompartmentCode]="firstItem"
@@ -49,7 +70,6 @@
<div class="empty-message">Es sind im Moment keine Artikel vorhanden</div>
}
<div class="actions">
@if (actions$ | async; as actions) {
@for (action of actions; track action) {
@@ -57,19 +77,27 @@
[disabled]="(changeActionLoader$ | async) || (loading$ | async)"
class="cta-action cta-action-primary"
(click)="handleAction(action)"
>
<ui-spinner
[show]="(changeActionLoader$ | async) || (loading$ | async)"
>{{ action.label }}</ui-spinner
>
<ui-spinner [show]="(changeActionLoader$ | async) || (loading$ | async)">{{ action.label }}</ui-spinner>
</button>
}
}
@if (listEmpty$ | async) {
<a class="cta-action cta-action-secondary" [routerLink]="['/filiale', 'goods', 'in']">
<a
class="cta-action cta-action-secondary"
[routerLink]="['/filiale', 'goods', 'in']"
>
Zur Bestellpostensuche
</a>
}
@if (listEmpty$ | async) {
<a class="cta-action cta-action-primary" [routerLink]="['/filiale', 'remission']">Zur Remission</a>
<a class="cta-action cta-action-primary" [routerLink]="remissionPath()"
>Zur Remission</a
>
}
</div>

View File

@@ -1,7 +1,18 @@
import { ChangeDetectionStrategy, Component, OnDestroy, OnInit, ViewChild, inject } from '@angular/core';
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 {
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';
@@ -11,6 +22,7 @@ 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',
@@ -21,8 +33,12 @@ import { CacheService } from '@core/cache';
standalone: false,
})
export class GoodsInRemissionPreviewComponent implements OnInit, OnDestroy {
private _pickupShelfInNavigationService = inject(PickupShelfInNavigationService);
@ViewChild(UiScrollContainerComponent) scrollContainer: UiScrollContainerComponent;
tabService = inject(TabService);
private _pickupShelfInNavigationService = inject(
PickupShelfInNavigationService,
);
@ViewChild(UiScrollContainerComponent)
scrollContainer: UiScrollContainerComponent;
items$ = this._store.results$;
@@ -50,10 +66,18 @@ export class GoodsInRemissionPreviewComponent implements OnInit, OnDestroy {
byProcessingStatusFn = (item: OrderItemListItemDTO) => item.processingStatus;
byCompartmentCodeFn = (item: OrderItemListItemDTO) =>
item.compartmentInfo ? `${item.compartmentCode}_${item.compartmentInfo}` : item.compartmentCode;
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,
@@ -78,12 +102,18 @@ export class GoodsInRemissionPreviewComponent implements OnInit, OnDestroy {
}
private _removeScrollPositionFromCache(): void {
this._cache.delete({ processId: this._config.get('process.ids.goodsIn'), token: this.SCROLL_POSITION_TOKEN });
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 },
{
processId: this._config.get('process.ids.goodsIn'),
token: this.SCROLL_POSITION_TOKEN,
},
this.scrollContainer?.scrollPos,
);
}
@@ -108,7 +138,10 @@ export class GoodsInRemissionPreviewComponent implements OnInit, OnDestroy {
async updateBreadcrumb() {
const crumbs = await this._breadcrumb
.getBreadcrumbsByKeyAndTags$(this._config.get('process.ids.goodsIn'), ['goods-in', 'preview'])
.getBreadcrumbsByKeyAndTags$(this._config.get('process.ids.goodsIn'), [
'goods-in',
'preview',
])
.pipe(first())
.toPromise();
for (const crumb of crumbs) {
@@ -120,12 +153,15 @@ export class GoodsInRemissionPreviewComponent implements OnInit, OnDestroy {
async removeBreadcrumbs() {
let breadcrumbsToDelete = await this._breadcrumb
.getBreadcrumbsByKeyAndTags$(this._config.get('process.ids.goodsIn'), ['goods-in'])
.getBreadcrumbsByKeyAndTags$(this._config.get('process.ids.goodsIn'), [
'goods-in',
])
.pipe(first())
.toPromise();
breadcrumbsToDelete = breadcrumbsToDelete.filter(
(crumb) => !crumb.tags.includes('preview') && !crumb.tags.includes('main'),
(crumb) =>
!crumb.tags.includes('preview') && !crumb.tags.includes('main'),
);
breadcrumbsToDelete.forEach((crumb) => {
@@ -133,11 +169,17 @@ export class GoodsInRemissionPreviewComponent implements OnInit, OnDestroy {
});
const detailsCrumbs = await this._breadcrumb
.getBreadcrumbsByKeyAndTags$(this._config.get('process.ids.goodsIn'), ['goods-in', 'details'])
.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'])
.getBreadcrumbsByKeyAndTags$(this._config.get('process.ids.goodsIn'), [
'goods-in',
'edit',
])
.pipe(first())
.toPromise();
@@ -152,32 +194,44 @@ export class GoodsInRemissionPreviewComponent implements OnInit, OnDestroy {
initInitialSearch() {
if (this._store.hits === 0) {
this._store.searchResult$.pipe(takeUntil(this._onDestroy$)).subscribe(async (result) => {
await this.createBreadcrumb();
this._store.searchResult$
.pipe(takeUntil(this._onDestroy$))
.subscribe(async (result) => {
await this.createBreadcrumb();
this.scrollContainer?.scrollTo((await this._getScrollPositionFromCache()) ?? 0);
this._removeScrollPositionFromCache();
});
this.scrollContainer?.scrollTo(
(await this._getScrollPositionFromCache()) ?? 0,
);
this._removeScrollPositionFromCache();
});
}
this._store.search();
}
async navigateToRemission() {
await this._router.navigate(['/filiale/remission']);
await this._router.navigate(this.remissionPath());
}
navigateToDetails(orderItem: OrderItemListItemDTO) {
const nav = this._pickupShelfInNavigationService.detailRoute({ item: orderItem, side: false });
const nav = this._pickupShelfInNavigationService.detailRoute({
item: orderItem,
side: false,
});
this._router.navigate(nav.path, { queryParams: { ...nav.queryParams, view: 'remission' } });
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();
const response = await this._store
.createRemissionFromPreview()
.pipe(first())
.toPromise();
if (!response?.dialog) {
this._toast.open({

View File

@@ -1,4 +1,4 @@
import { CurrencyPipe, DatePipe } from '@angular/common';
import { DatePipe } from '@angular/common';
import { ChangeDetectionStrategy, Component, ElementRef, Input, inject } from '@angular/core';
import { RouterLink, RouterLinkActive } from '@angular/router';
import { NavigateOnClickDirective, ProductImageModule } from '@cdn/product-image';
@@ -25,7 +25,6 @@ import { MatomoModule } from 'ngx-matomo-client';
RouterLinkActive,
IconModule,
DatePipe,
CurrencyPipe,
ProductImageModule,
UiCommonModule,
PickupShelfProcessingStatusPipe,

View File

@@ -1 +1 @@
@import "./components/icon";
@use "./components/icon";

View File

@@ -16,20 +16,20 @@ import {
forwardRef,
Optional,
inject,
} from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { UiAutocompleteComponent } from '@ui/autocomplete';
import { UiFormControlDirective } from '@ui/form-control';
import { containsElement } from '@utils/common';
import { Subscription } from 'rxjs';
import { ScanAdapterService } from '@adapter/scan';
import { injectCancelSearch } from '@shared/services/cancel-subject';
import { EnvironmentService } from '@core/environment';
} from "@angular/core";
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from "@angular/forms";
import { UiAutocompleteComponent } from "@ui/autocomplete";
import { UiFormControlDirective } from "@ui/form-control";
import { containsElement } from "@utils/common";
import { Subscription } from "rxjs";
import { ScanAdapterService } from "@adapter/scan";
import { injectCancelSearch } from "@shared/services/cancel-subject";
import { EnvironmentService } from "@core/environment";
@Component({
selector: 'shared-searchbox',
templateUrl: 'searchbox.component.html',
styleUrls: ['searchbox.component.scss'],
selector: "shared-searchbox",
templateUrl: "searchbox.component.html",
styleUrls: ["searchbox.component.scss"],
providers: [
{
provide: NG_VALUE_ACCESSOR,
@@ -49,9 +49,9 @@ export class SearchboxComponent
cancelSearch = injectCancelSearch({ optional: true });
disabled: boolean;
type = 'text';
type = "text";
@ViewChild('input', { read: ElementRef, static: true })
@ViewChild("input", { read: ElementRef, static: true })
input: ElementRef;
@ContentChild(UiAutocompleteComponent)
@@ -61,9 +61,9 @@ export class SearchboxComponent
focusAfterViewInit = true;
@Input()
placeholder = '';
placeholder = "";
private _query = '';
private _query = "";
@Input()
get query() {
@@ -94,7 +94,7 @@ export class SearchboxComponent
scanner = false;
@Input()
hint = '';
hint = "";
@Input()
autocompleteValueSelector: (item: any) => string = (item: any) => item;
@@ -104,11 +104,11 @@ export class SearchboxComponent
}
clear(): void {
this.setQuery('');
this.setQuery("");
this.cancelSearch();
}
@HostBinding('class.autocomplete-opend')
@HostBinding("class.autocomplete-opend")
get autocompleteOpen() {
return this.autocomplete?.opend;
}
@@ -213,13 +213,13 @@ export class SearchboxComponent
}
clearHint() {
this.hint = '';
this.hint = "";
this.focused.emit(true);
this.cdr.markForCheck();
}
onKeyup(event: KeyboardEvent) {
if (event.key === 'Enter') {
if (event.key === "Enter") {
if (this.autocomplete?.opend && this.autocomplete?.activeItem) {
this.setQuery(this.autocomplete?.activeItem?.item);
this.autocomplete?.close();
@@ -227,7 +227,7 @@ export class SearchboxComponent
this.search.emit(this.query);
event.preventDefault();
} else if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
} else if (event.key === "ArrowUp" || event.key === "ArrowDown") {
this.handleArrowUpDownEvent(event);
}
}
@@ -242,7 +242,7 @@ export class SearchboxComponent
}
}
@HostListener('window:click', ['$event'])
@HostListener("window:click", ["$event"])
focusLost(event: MouseEvent) {
if (
this.autocomplete?.opend &&
@@ -256,9 +256,11 @@ export class SearchboxComponent
this.search.emit(this.query);
}
@HostListener('focusout', ['$event'])
@HostListener("focusout", ["$event"])
onBlur() {
this.onTouched();
if (typeof this.onTouched === "function") {
this.onTouched();
}
this.focused.emit(false);
this.cdr.markForCheck();
}

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,303 +1,338 @@
<div class="side-menu-group">
<span class="side-menu-group-label">Kunden</span>
<nav class="side-menu-group-nav">
<a
class="side-menu-group-item"
(click)="closeSideMenu(); resetBranch(); focusSearchBox()"
[routerLink]="productRoutePath$ | async"
sharedRegexRouterLinkActive="active"
sharedRegexRouterLinkActiveTest="^\/kunde\/\d*\/product"
(isActiveChange)="focusSearchBox()"
>
<div class="side-menu-group-item-icon">
<shared-icon icon="import-contacts"></shared-icon>
</div>
<span class="side-menu-group-item-label">Artikelsuche</span>
</a>
<div class="side-menu-group-sub-item-wrapper">
@if (customerSearchRoute$ | async; as customerSearchRoute) {
<a
class="side-menu-group-item"
(click)="closeSideMenu(); focusSearchBox()"
[routerLink]="customerSearchRoute.path"
[queryParams]="customerSearchRoute.queryParams"
sharedRegexRouterLinkActive="active"
sharedRegexRouterLinkActiveTest="^\/kunde\/\d*\/customer"
(isActiveChange)="customerActive($event); focusSearchBox()"
>
<span class="side-menu-group-item-icon">
<shared-icon icon="person"></shared-icon>
</span>
<span class="side-menu-group-item-label">Kunden</span>
<button
class="side-menu-group-arrow"
[class.side-menu-item-rotate]="customerExpanded"
(click)="
$event.stopPropagation();
$event.preventDefault();
customerExpanded = !customerExpanded
"
>
<shared-icon icon="keyboard-arrow-down"></shared-icon>
</button>
</a>
}
<div class="side-menu-group-sub-items" [class.hidden]="!customerExpanded">
@if (customerSearchRoute$ | async; as customerSearchRoute) {
<a
class="side-menu-group-item"
(click)="closeSideMenu(); focusSearchBox()"
[routerLink]="customerSearchRoute.path"
[queryParams]="customerSearchRoute.queryParams"
sharedRegexRouterLinkActive="active"
sharedRegexRouterLinkActiveTest="^\/kunde\/\d*\/customer\/(\(search|search)"
(isActiveChange)="focusSearchBox()"
>
<span class="side-menu-group-item-icon"></span>
<span class="side-menu-group-item-label">Suchen</span>
</a>
}
@if (customerCreateRoute$ | async; as customerCreateRoute) {
<a
class="side-menu-group-item"
(click)="closeSideMenu()"
[routerLink]="customerCreateRoute.path"
[queryParams]="customerCreateRoute.queryParams"
sharedRegexRouterLinkActive="active"
sharedRegexRouterLinkActiveTest="^\/kunde\/\d*\/customer\/(\(create|create)"
>
<span class="side-menu-group-item-icon"></span>
<span class="side-menu-group-item-label">Erfassen</span>
</a>
}
</div>
</div>
<a
*ifRole="'Store'"
class="side-menu-group-item"
(click)="closeSideMenu(); focusSearchBox()"
[routerLink]="pickUpShelfOutRoutePath$ | async"
sharedRegexRouterLinkActive="active"
sharedRegexRouterLinkActiveTest="^\/kunde\/\d*\/pickup-shelf"
(isActiveChange)="focusSearchBox()"
>
<span class="side-menu-group-item-icon">
<shared-icon icon="unarchive"></shared-icon>
</span>
<span class="side-menu-group-item-label">Warenausgabe</span>
</a>
<a
*ifRole="'Store'"
class="side-menu-group-item"
(click)="closeSideMenu(); focusSearchBox()"
[routerLink]="[
'/',
processService.activatedTab()?.id || processService.nextId(),
'return',
]"
(isActiveChange)="focusSearchBox()"
>
<span class="side-menu-group-item-icon w-[2.375rem] h-12">
<ng-icon name="isaNavigationReturn"></ng-icon>
</span>
<span class="side-menu-group-item-label">Retoure</span>
</a>
<a
*ifRole="'CallCenter'"
class="side-menu-group-item"
(click)="closeSideMenu(); resetBranch(); focusSearchBox()"
[routerLink]="customerOrdersRoutePath$ | async"
sharedRegexRouterLinkActive="active"
sharedRegexRouterLinkActiveTest="^\/kunde\/\d*\/order"
(isActiveChange)="focusSearchBox()"
>
<span class="side-menu-group-item-icon">
<shared-icon icon="deployed-code"></shared-icon>
</span>
<span class="side-menu-group-item-label">Bestellungen</span>
</a>
</nav>
</div>
<div class="side-menu-group" *ifRole="'Store'">
<span class="side-menu-group-label">Filiale</span>
<nav class="side-menu-group-nav">
@if (taskCalenderNavigation$ | async; as taskCalenderNavigation) {
<a
class="side-menu-group-item"
(click)="closeSideMenu(); focusSearchBox()"
[routerLink]="taskCalenderNavigation.path"
[queryParams]="taskCalenderNavigation.queryParams"
routerLinkActive="active"
(isActiveChange)="focusSearchBox()"
>
<span class="side-menu-group-item-icon">
<shared-icon icon="event-available"></shared-icon>
</span>
<span class="side-menu-group-item-label">Kalender</span>
</a>
}
@if (assortmentNavigation$ | async; as assortmentNavigation) {
<a
class="side-menu-group-item"
(click)="closeSideMenu()"
[routerLink]="assortmentNavigation.path"
[queryParams]="assortmentNavigation.queryParams"
routerLinkActive="active"
>
<span class="side-menu-group-item-icon">
<shared-icon icon="shape-outline"></shared-icon>
</span>
<span class="side-menu-group-item-label">Sortiment</span>
</a>
}
<div class="side-menu-group-sub-item-wrapper">
@if (pickUpShelfInRoutePath$ | async; as pickUpShelfInNavigation) {
<a
class="side-menu-group-item"
(click)="closeSideMenu(); focusSearchBox()"
[routerLink]="pickUpShelfInNavigation.path"
[queryParams]="pickUpShelfInNavigation.queryParams"
sharedRegexRouterLinkActive="active"
sharedRegexRouterLinkActiveTest="^\/filiale\/(pickup-shelf|goods\/in)"
(isActiveChange)="shelfActive($event); focusSearchBox()"
>
<span class="side-menu-group-item-icon">
<shared-icon icon="isa-abholfach"></shared-icon>
</span>
<span class="side-menu-group-item-label">Abholfach</span>
<button
class="side-menu-group-arrow"
[class.side-menu-item-rotate]="shelfExpanded"
(click)="
$event.stopPropagation();
$event.preventDefault();
shelfExpanded = !shelfExpanded
"
>
<shared-icon icon="keyboard-arrow-down"></shared-icon>
</button>
</a>
}
<div class="side-menu-group-sub-items" [class.hidden]="!shelfExpanded">
@if (pickUpShelfInRoutePath$ | async; as pickUpShelfInListNavigation) {
<a
class="side-menu-group-item"
(click)="closeSideMenu(); focusSearchBox()"
[routerLink]="pickUpShelfInListNavigation.path"
[queryParams]="pickUpShelfInListNavigation.queryParams"
[class.has-child-view]="currentShelfView$ | async"
sharedRegexRouterLinkActive="active"
[sharedRegexRouterLinkActiveTest]="'^\/filiale\/pickup-shelf'"
(isActiveChange)="shelfActive($event); focusSearchBox()"
>
<span class="side-menu-group-item-icon"></span>
<span class="side-menu-group-item-label">Einbuchen</span>
</a>
}
<a
class="side-menu-group-item"
(click)="closeSideMenu()"
[routerLink]="['/filiale', 'goods', 'in', 'reservation']"
[queryParams]="{ view: 'reservation' }"
[class.active-child]="(currentShelfView$ | async) === 'reservation'"
routerLinkActive="active"
(isActiveChange)="shelfActive($event)"
>
<span class="side-menu-group-item-icon"></span>
<span class="side-menu-group-item-label">Reservierung</span>
</a>
<a
class="side-menu-group-item"
(click)="closeSideMenu()"
[routerLink]="['/filiale', 'goods', 'in', 'cleanup']"
[queryParams]="{ view: 'cleanup' }"
[class.active-child]="(currentShelfView$ | async) === 'cleanup'"
routerLinkActive="active"
(isActiveChange)="shelfActive($event)"
>
<span class="side-menu-group-item-icon"></span>
<span class="side-menu-group-item-label">Ausräumen</span>
</a>
<a
class="side-menu-group-item"
(click)="closeSideMenu()"
[routerLink]="['/filiale', 'goods', 'in', 'preview']"
[queryParams]="{ view: 'remission' }"
[class.active-child]="(currentShelfView$ | async) === 'remission'"
routerLinkActive="active"
(isActiveChange)="shelfActive($event)"
>
<span class="side-menu-group-item-icon"></span>
<span class="side-menu-group-item-label">Remi-Vorschau</span>
</a>
<a
class="side-menu-group-item"
(click)="closeSideMenu()"
[routerLink]="['/filiale', 'goods', 'in', 'list']"
[queryParams]="{ view: 'wareneingangsliste' }"
[class.active-child]="
(currentShelfView$ | async) === 'wareneingangsliste'
"
routerLinkActive="active"
(isActiveChange)="shelfActive($event)"
>
<span class="side-menu-group-item-icon"></span>
<span class="side-menu-group-item-label">Fehlende</span>
</a>
</div>
</div>
@if (remissionNavigation$ | async; as remissionNavigation) {
<a
class="side-menu-group-item"
(click)="closeSideMenu()"
[routerLink]="remissionNavigation.path"
[queryParams]="remissionNavigation.queryParams"
routerLinkActive="active"
>
<span class="side-menu-group-item-icon">
<shared-icon icon="assignment-return"></shared-icon>
</span>
<span class="side-menu-group-item-label">Remission</span>
</a>
}
@if (packageInspectionNavigation$ | async; as packageInspectionNavigation) {
<a
class="side-menu-group-item"
(click)="closeSideMenu(); fetchAndOpenPackages()"
[routerLink]="packageInspectionNavigation.path"
[queryParams]="packageInspectionNavigation.queryParams"
routerLinkActive="active"
>
<span class="side-menu-group-item-icon">
<shared-icon icon="clipboard-check-outline"></shared-icon>
</span>
<span class="side-menu-group-item-label">Wareneingang</span>
</a>
}
<a
class="side-menu-group-item"
(click)="closeSideMenu(); focusSearchBox()"
[routerLink]="[
'/',
processService.activatedTab()?.id || processService.nextId(),
'remission',
]"
(isActiveChange)="focusSearchBox()"
>
<span class="side-menu-group-item-icon w-[2.375rem] h-12">
<ng-icon name="isaNavigationRemission2"></ng-icon>
</span>
<span class="side-menu-group-item-label">Remission</span>
</a>
</nav>
</div>
<div class="side-menu-group">
<span class="side-menu-group-label">Kunden</span>
<nav class="side-menu-group-nav">
<a
class="side-menu-group-item"
(click)="closeSideMenu(); resetBranch(); focusSearchBox()"
[routerLink]="productRoutePath$ | async"
sharedRegexRouterLinkActive="active"
sharedRegexRouterLinkActiveTest="^\/kunde\/\d*\/product"
(isActiveChange)="focusSearchBox()"
>
<div class="side-menu-group-item-icon">
<shared-icon icon="import-contacts"></shared-icon>
</div>
<span class="side-menu-group-item-label">Artikelsuche</span>
</a>
<div class="side-menu-group-sub-item-wrapper">
@if (customerSearchRoute$ | async; as customerSearchRoute) {
<a
class="side-menu-group-item"
(click)="closeSideMenu(); focusSearchBox()"
[routerLink]="customerSearchRoute.path"
[queryParams]="customerSearchRoute.queryParams"
sharedRegexRouterLinkActive="active"
sharedRegexRouterLinkActiveTest="^\/kunde\/\d*\/customer"
(isActiveChange)="customerActive($event); focusSearchBox()"
>
<span class="side-menu-group-item-icon">
<shared-icon icon="person"></shared-icon>
</span>
<span class="side-menu-group-item-label">Kunden</span>
<button
class="side-menu-group-arrow"
[class.side-menu-item-rotate]="customerExpanded"
(click)="
$event.stopPropagation();
$event.preventDefault();
customerExpanded = !customerExpanded
"
>
<shared-icon icon="keyboard-arrow-down"></shared-icon>
</button>
</a>
}
<div class="side-menu-group-sub-items" [class.hidden]="!customerExpanded">
@if (customerSearchRoute$ | async; as customerSearchRoute) {
<a
class="side-menu-group-item"
(click)="closeSideMenu(); focusSearchBox()"
[routerLink]="customerSearchRoute.path"
[queryParams]="customerSearchRoute.queryParams"
sharedRegexRouterLinkActive="active"
sharedRegexRouterLinkActiveTest="^\/kunde\/\d*\/customer\/(\(search|search)"
(isActiveChange)="focusSearchBox()"
>
<span class="side-menu-group-item-icon"></span>
<span class="side-menu-group-item-label">Suchen</span>
</a>
}
@if (customerCreateRoute$ | async; as customerCreateRoute) {
<a
class="side-menu-group-item"
(click)="closeSideMenu()"
[routerLink]="customerCreateRoute.path"
[queryParams]="customerCreateRoute.queryParams"
sharedRegexRouterLinkActive="active"
sharedRegexRouterLinkActiveTest="^\/kunde\/\d*\/customer\/(\(create|create)"
>
<span class="side-menu-group-item-icon"></span>
<span class="side-menu-group-item-label">Erfassen</span>
</a>
}
</div>
</div>
<a
*ifRole="'Store'"
class="side-menu-group-item"
(click)="closeSideMenu(); focusSearchBox()"
[routerLink]="pickUpShelfOutRoutePath$ | async"
sharedRegexRouterLinkActive="active"
sharedRegexRouterLinkActiveTest="^\/kunde\/\d*\/pickup-shelf"
(isActiveChange)="focusSearchBox()"
>
<span class="side-menu-group-item-icon">
<shared-icon icon="unarchive"></shared-icon>
</span>
<span class="side-menu-group-item-label">Warenausgabe</span>
</a>
<a
*ifRole="'Store'"
class="side-menu-group-item"
(click)="closeSideMenu(); focusSearchBox()"
[routerLink]="[
'/',
processService.activatedTab()?.id || processService.nextId(),
'return',
]"
(isActiveChange)="focusSearchBox()"
>
<span class="side-menu-group-item-icon w-[2.375rem] h-12">
<ng-icon name="isaNavigationReturn"></ng-icon>
</span>
<span class="side-menu-group-item-label">Retoure</span>
</a>
<a
*ifRole="'CallCenter'"
class="side-menu-group-item"
(click)="closeSideMenu(); resetBranch(); focusSearchBox()"
[routerLink]="customerOrdersRoutePath$ | async"
sharedRegexRouterLinkActive="active"
sharedRegexRouterLinkActiveTest="^\/kunde\/\d*\/order"
(isActiveChange)="focusSearchBox()"
>
<span class="side-menu-group-item-icon">
<shared-icon icon="deployed-code"></shared-icon>
</span>
<span class="side-menu-group-item-label">Bestellungen</span>
</a>
</nav>
</div>
<div class="side-menu-group" *ifRole="'Store'">
<span class="side-menu-group-label">Filiale</span>
<nav class="side-menu-group-nav">
@if (taskCalenderNavigation$ | async; as taskCalenderNavigation) {
<a
class="side-menu-group-item"
(click)="closeSideMenu(); focusSearchBox()"
[routerLink]="taskCalenderNavigation.path"
[queryParams]="taskCalenderNavigation.queryParams"
routerLinkActive="active"
(isActiveChange)="focusSearchBox()"
>
<span class="side-menu-group-item-icon">
<shared-icon icon="event-available"></shared-icon>
</span>
<span class="side-menu-group-item-label">Kalender</span>
</a>
}
@if (assortmentNavigation$ | async; as assortmentNavigation) {
<a
class="side-menu-group-item"
(click)="closeSideMenu()"
[routerLink]="assortmentNavigation.path"
[queryParams]="assortmentNavigation.queryParams"
routerLinkActive="active"
>
<span class="side-menu-group-item-icon">
<shared-icon icon="shape-outline"></shared-icon>
</span>
<span class="side-menu-group-item-label">Sortiment</span>
</a>
}
<div class="side-menu-group-sub-item-wrapper">
@if (pickUpShelfInRoutePath$ | async; as pickUpShelfInNavigation) {
<a
class="side-menu-group-item"
(click)="closeSideMenu(); focusSearchBox()"
[routerLink]="pickUpShelfInNavigation.path"
[queryParams]="pickUpShelfInNavigation.queryParams"
sharedRegexRouterLinkActive="active"
sharedRegexRouterLinkActiveTest="^\/filiale\/(pickup-shelf|goods\/in)"
(isActiveChange)="shelfActive($event); focusSearchBox()"
>
<span class="side-menu-group-item-icon">
<shared-icon icon="isa-abholfach"></shared-icon>
</span>
<span class="side-menu-group-item-label">Abholfach</span>
<button
class="side-menu-group-arrow"
[class.side-menu-item-rotate]="shelfExpanded"
(click)="
$event.stopPropagation();
$event.preventDefault();
shelfExpanded = !shelfExpanded
"
>
<shared-icon icon="keyboard-arrow-down"></shared-icon>
</button>
</a>
}
<div class="side-menu-group-sub-items" [class.hidden]="!shelfExpanded">
@if (pickUpShelfInRoutePath$ | async; as pickUpShelfInListNavigation) {
<a
class="side-menu-group-item"
(click)="closeSideMenu(); focusSearchBox()"
[routerLink]="pickUpShelfInListNavigation.path"
[queryParams]="pickUpShelfInListNavigation.queryParams"
[class.has-child-view]="currentShelfView$ | async"
sharedRegexRouterLinkActive="active"
[sharedRegexRouterLinkActiveTest]="'^\/filiale\/pickup-shelf'"
(isActiveChange)="shelfActive($event); focusSearchBox()"
>
<span class="side-menu-group-item-icon"></span>
<span class="side-menu-group-item-label">Einbuchen</span>
</a>
}
<a
class="side-menu-group-item"
(click)="closeSideMenu()"
[routerLink]="['/filiale', 'goods', 'in', 'reservation']"
[queryParams]="{ view: 'reservation' }"
[class.active-child]="(currentShelfView$ | async) === 'reservation'"
routerLinkActive="active"
(isActiveChange)="shelfActive($event)"
>
<span class="side-menu-group-item-icon"></span>
<span class="side-menu-group-item-label">Reservierung</span>
</a>
<a
class="side-menu-group-item"
(click)="closeSideMenu()"
[routerLink]="['/filiale', 'goods', 'in', 'cleanup']"
[queryParams]="{ view: 'cleanup' }"
[class.active-child]="(currentShelfView$ | async) === 'cleanup'"
routerLinkActive="active"
(isActiveChange)="shelfActive($event)"
>
<span class="side-menu-group-item-icon"></span>
<span class="side-menu-group-item-label">Ausräumen</span>
</a>
<a
class="side-menu-group-item"
(click)="closeSideMenu()"
[routerLink]="['/filiale', 'goods', 'in', 'preview']"
[queryParams]="{ view: 'remission' }"
[class.active-child]="(currentShelfView$ | async) === 'remission'"
routerLinkActive="active"
(isActiveChange)="shelfActive($event)"
>
<span class="side-menu-group-item-icon"></span>
<span class="side-menu-group-item-label">Remi-Vorschau</span>
</a>
<a
class="side-menu-group-item"
(click)="closeSideMenu()"
[routerLink]="['/filiale', 'goods', 'in', 'list']"
[queryParams]="{ view: 'wareneingangsliste' }"
[class.active-child]="
(currentShelfView$ | async) === 'wareneingangsliste'
"
routerLinkActive="active"
(isActiveChange)="shelfActive($event)"
>
<span class="side-menu-group-item-icon"></span>
<span class="side-menu-group-item-label">Fehlende</span>
</a>
</div>
</div>
<div class="side-menu-group-sub-item-wrapper">
<a
class="side-menu-group-item"
(click)="closeSideMenu(); focusSearchBox()"
[routerLink]="[
'/',
processService.activatedTab()?.id || processService.nextId(),
'remission',
]"
(isActiveChange)="focusSearchBox(); remissionExpanded.set($event)"
routerLinkActive="active"
#rlActive="routerLinkActive"
>
<span class="side-menu-group-item-icon w-[2.375rem] h-12">
<ng-icon name="isaNavigationRemission2" size="1.5rem"></ng-icon>
</span>
<span class="side-menu-group-item-label">Remission</span>
<button
class="side-menu-group-arrow"
[class.side-menu-item-rotate]="remissionExpanded()"
(click)="
$event.stopPropagation();
$event.preventDefault();
remissionExpanded.set(!remissionExpanded())
"
>
<shared-icon icon="keyboard-arrow-down"></shared-icon>
</button>
</a>
@if (remissionExpanded()) {
<div class="side-menu-group-sub-items">
<a
class="side-menu-group-item"
(click)="closeSideMenu(); focusSearchBox()"
[routerLink]="[
'/',
processService.activatedTab()?.id || processService.nextId(),
'remission',
]"
(isActiveChange)="focusSearchBox()"
sharedRegexRouterLinkActive="active"
sharedRegexRouterLinkActiveTest="^\/\d*\/remission\/(mandatory|department)"
>
<span class="side-menu-group-item-icon"> </span>
<span class="side-menu-group-item-label">Remission</span>
</a>
<a
class="side-menu-group-item"
(click)="closeSideMenu(); focusSearchBox()"
[routerLink]="[
'/',
processService.activatedTab()?.id || processService.nextId(),
'remission',
'return-receipt',
]"
(isActiveChange)="focusSearchBox()"
sharedRegexRouterLinkActive="active"
sharedRegexRouterLinkActiveTest="^\/\d*\/remission\/return-receipt"
>
<span class="side-menu-group-item-icon"> </span>
<span class="side-menu-group-item-label">Warenbegleitscheine</span>
</a>
</div>
}
</div>
@if (packageInspectionNavigation$ | async; as packageInspectionNavigation) {
<a
class="side-menu-group-item"
(click)="closeSideMenu(); fetchAndOpenPackages()"
[routerLink]="packageInspectionNavigation.path"
[queryParams]="packageInspectionNavigation.queryParams"
routerLinkActive="active"
>
<span class="side-menu-group-item-icon">
<shared-icon icon="clipboard-check-outline"></shared-icon>
</span>
<span class="side-menu-group-item-label">Wareneingang</span>
</a>
}
</nav>
</div>

View File

@@ -1,435 +1,426 @@
import {
Component,
ChangeDetectionStrategy,
Inject,
ChangeDetectorRef,
inject,
DOCUMENT,
} from '@angular/core';
import { AuthModule, AuthService } from '@core/auth';
import { StockService } from '@generated/swagger/wws-api';
import { first, map, retry, switchMap, take } from 'rxjs/operators';
import { ShellService } from '../shell.service';
import { ApplicationProcess, ApplicationService } from '@core/application';
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
import { EnvironmentService } from '@core/environment';
import { CommonModule } from '@angular/common';
import { Config } from '@core/config';
import { BreadcrumbService } from '@core/breadcrumb';
import { IconComponent } from '@shared/components/icon';
import { RegexRouterLinkActiveDirective } from '@shared/directives/router-link-active';
import { WrongDestinationModalService } from '@modal/wrong-destination';
import {
CustomerCreateNavigation,
CustomerOrdersNavigationService,
CustomerSearchNavigation,
PickupShelfInNavigationService,
PickUpShelfOutNavigationService,
ProductCatalogNavigationService,
} from '@shared/services/navigation';
import { TabService } from '@isa/core/tabs';
import { NgIconComponent, provideIcons } from '@ng-icons/core';
import { isaNavigationRemission2, isaNavigationReturn } from '@isa/icons';
@Component({
selector: 'shell-side-menu',
templateUrl: 'side-menu.component.html',
styleUrls: ['side-menu.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [
CommonModule,
NgIconComponent,
IconComponent,
RouterModule,
AuthModule,
RegexRouterLinkActiveDirective,
],
providers: [provideIcons({ isaNavigationReturn, isaNavigationRemission2 })],
})
export class ShellSideMenuComponent {
processService = inject(TabService);
branchKey$ = this._stockService.StockCurrentBranch().pipe(
retry(3),
map((x) => x.result.key),
);
section$ = this._app.getSection$();
processes$ = this.section$.pipe(
switchMap((section) => this._app.getProcesses$(section)),
);
processesCount$ = this.processes$.pipe(
map((processes) => processes?.length ?? 0),
);
activeProcess$ = this._app.activatedProcessId$.pipe(
switchMap((processId) => this._app.getProcessById$(processId)),
);
get isTablet() {
return this._environment.matchTablet();
}
customerBasePath$ = this.activeProcess$.pipe(
map((process) => {
if (
!!process &&
process.section === 'customer' &&
process.type !== 'cart-checkout'
) {
// Übernehme aktiven Prozess
return `/kunde/${process.id}`;
} else {
// Über Guards wird ein neuer Prozess erstellt
return '/kunde';
}
}),
);
customerSearchRoute$ = this.getLastActivatedCustomerProcessId$().pipe(
map((processId) => {
return this._customerSearchNavigation.defaultRoute({ processId });
}),
);
customerCreateRoute$ = this.getLastActivatedCustomerProcessId$().pipe(
map((processId) => {
return this._customerCreateNavigation.defaultRoute({ processId });
}),
);
pickUpShelfOutRoutePath$ = this.getLastActivatedCustomerProcessId$().pipe(
map((processId) => {
if (processId) {
// Übernehme aktiven Prozess
return this._pickUpShelfOutNavigation.defaultRoute({ processId }).path;
} else {
// Über Guards wird ein neuer Prozess erstellt
return this._pickUpShelfOutNavigation.defaultRoute({}).path;
}
}),
);
productRoutePath$ = this.getLastActivatedCustomerProcessId$().pipe(
map((processId) => {
if (processId) {
// Übernehme aktiven Prozess
return this._catalogNavigationService.getArticleSearchBasePath(
processId,
).path;
} else {
// Über Guards wird ein neuer Prozess erstellt
return this._catalogNavigationService.getArticleSearchBasePath().path;
}
}),
);
customerOrdersRoutePath$ = this.getLastActivatedCustomerProcessId$().pipe(
map((processId) => {
if (processId) {
// Übernehme aktiven Prozess
return this._customerOrdersNavigationService.getCustomerOrdersBasePath(
processId,
).path;
} else {
// Über Guards wird ein neuer Prozess erstellt
return this._customerOrdersNavigationService.getCustomerOrdersBasePath()
.path;
}
}),
);
taskCalenderNavigation$ = this.getLastNavigationByProcessId(
this._config.get('process.ids.taskCalendar'),
{
path: ['/filiale', 'task-calendar'],
queryParams: {},
},
'/filiale/task-calendar',
);
assortmentNavigation$ = this.getLastNavigationByProcessId(
this._config.get('process.ids.assortment'),
{
path: ['/filiale', 'assortment'],
queryParams: {},
},
);
pickUpShelfInRoutePath$ = this.getLastNavigationByProcessId(
this._config.get('process.ids.pickupShelf'),
this._pickUpShelfInNavigation.defaultRoute(),
'/filiale/pickup-shelf',
);
// #4478 - RD // Abholfach - Routing löst Suche aus
// pickUpShelfInListRoutePath$ = this.getLastNavigationByProcessId(
// this._config.get('process.ids.pickupShelf'),
// this._pickUpShelfInNavigation.listRoute()
// );
remissionNavigation$ = this.getLastNavigationByProcessId(
this._config.get('process.ids.remission'),
{
path: ['/filiale', 'remission'],
queryParams: {},
},
);
packageInspectionNavigation$ = this.getLastNavigationByProcessId(
this._config.get('process.ids.packageInspection'),
{
path: ['/filiale', 'package-inspection'],
queryParams: {},
},
);
get currentShelfView$() {
return this._route.queryParams.pipe(map((params) => params.view));
}
shelfExpanded = false;
customerExpanded = false;
constructor(
private _shellService: ShellService,
private _authService: AuthService,
private _stockService: StockService,
private _app: ApplicationService,
private _router: Router,
private _route: ActivatedRoute,
private readonly _wrongDestinationModalService: WrongDestinationModalService,
private _environment: EnvironmentService,
private _catalogNavigationService: ProductCatalogNavigationService,
private _customerOrdersNavigationService: CustomerOrdersNavigationService,
private _config: Config,
private _breadcrumbService: BreadcrumbService,
private _customerSearchNavigation: CustomerSearchNavigation,
private _customerCreateNavigation: CustomerCreateNavigation,
private _pickUpShelfOutNavigation: PickUpShelfOutNavigationService,
private _pickUpShelfInNavigation: PickupShelfInNavigationService,
private _cdr: ChangeDetectorRef,
@Inject(DOCUMENT) private readonly _document: Document,
) {}
customerActive(isActive: boolean) {
if (isActive) {
this.expandCustomer();
}
}
shelfActive(isActive: boolean) {
if (isActive) {
this.expandShelf();
}
}
expandCustomer() {
this.customerExpanded = true;
this._cdr.markForCheck();
}
expandShelf() {
this.shelfExpanded = true;
this._cdr.markForCheck();
}
getLastNavigationByProcessId(
id: number,
fallback?: { path: string[]; queryParams: unknown },
pathContainsString?: string,
) {
return this._breadcrumbService.getBreadcrumbByKey$(id)?.pipe(
map((breadcrumbs) => {
const lastCrumb = breadcrumbs
.filter((breadcrumb) => {
/**
* #4532 - Der optionale Filter wurde hinzugefügt Breadcrumbs mit fehlerhaften Pfad auszuschließen.
* Dieser Filter kann entfernt werden, sobald die Breadcrumbs korrekt gesetzt werden. Jedoch konnte man bisher nicht feststellen,
* woher die fehlerhaften Breadcrumbs kommen.
*/
if (!pathContainsString) {
// Wenn kein Filter gesetzt ist, dann wird der letzte Breadcrumb zurückgegeben
return true;
}
const pathStr = Array.isArray(breadcrumb.path)
? breadcrumb.path.join('/')
: breadcrumb.path;
return pathStr.includes(pathContainsString);
})
// eslint-disable-next-line no-prototype-builtins
.filter((breadcrumb) => !breadcrumb?.params?.hasOwnProperty('view'))
.filter((breadcrumb) => !breadcrumb?.tags?.includes('reservation'))
.filter((breadcrumb) => !breadcrumb?.tags?.includes('cleanup'))
.filter(
(breadcrumb) => !breadcrumb?.tags?.includes('wareneingangsliste'),
)
.filter((breadcrumb) => !breadcrumb?.tags?.includes('preview'))
.reduce((last, current) => {
if (!last) return current;
if (last.changed > current.changed) {
return last;
} else {
return current;
}
}, undefined);
if (!lastCrumb) {
return fallback;
}
// #4692 Return Fallback if Values contain undefined or null values, regardless if path is from type string or array
if (typeof lastCrumb?.path === 'string') {
if (
lastCrumb?.path?.includes('undefined') ||
lastCrumb?.path?.includes('null')
) {
return fallback;
}
} else {
const valuesToCheck = [];
// eslint-disable-next-line no-unsafe-optional-chaining
for (const value of lastCrumb?.path) {
if (
value?.outlets &&
value?.outlets?.primary &&
value?.outlets?.side
) {
valuesToCheck.push(
...Object.values(value?.outlets?.primary),
...Object.values(value?.outlets?.side),
);
} else {
valuesToCheck.push(value);
}
}
if (this.checkIfArrayContainsUndefinedOrNull(valuesToCheck)) {
return fallback;
}
}
return { path: lastCrumb.path, queryParams: lastCrumb.params };
}),
);
}
checkIfArrayContainsUndefinedOrNull(array: unknown[]) {
return (
array?.includes(undefined) ||
array?.includes('undefined') ||
array?.includes(null) ||
array?.includes('null')
);
}
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();
}),
);
}
closeSideMenu() {
this._shellService.closeSideMenu();
}
logout() {
this._authService.logout();
}
async resetBranch() {
const process = await this.activeProcess$.pipe(first()).toPromise();
if (process?.id) {
this._app.patchProcessData(process.id, { selectedBranch: undefined });
}
}
focusSearchBox() {
setTimeout(() => this._document.getElementById('searchbox')?.focus(), 0);
}
async createProcess() {
const process = await this.createCartProcess();
this.navigateToCatalog(process);
}
async createCartProcess() {
const nextProcessName = await this.getNextProcessName();
const process: ApplicationProcess = {
id: this.getNextProcessId(),
type: 'cart',
name: nextProcessName,
section: 'customer',
closeable: true,
};
this._app.createProcess(process);
return process;
}
async getNextProcessName() {
let processes = await this._app
.getProcesses$('customer')
.pipe(first())
.toPromise();
processes = processes.filter(
(x) => x.type === 'cart' && x.name.startsWith('Vorgang '),
);
const maxProcessNumber = processes.reduce((max, process) => {
const number = parseInt(process.name.replace('Vorgang ', ''), 10);
return number > max ? number : max;
}, 0);
return `Vorgang ${maxProcessNumber + 1}`;
}
getNextProcessId() {
return Date.now();
}
async navigateToCatalog(process: ApplicationProcess) {
await this._catalogNavigationService
.getArticleSearchBasePath(process.id)
.navigate();
}
navigateToDashboard() {
this._router.navigate(['/kunde', 'dashboard']);
}
async closeAllProcesses() {
const processes = await this.processes$.pipe(take(1)).toPromise();
processes.forEach((process) => this._app.removeProcess(process.id));
this.navigateToDashboard();
}
fetchAndOpenPackages = () =>
this._wrongDestinationModalService.fetchAndOpen();
}
import {
Component,
ChangeDetectionStrategy,
Inject,
ChangeDetectorRef,
inject,
DOCUMENT,
signal,
} from '@angular/core';
import { AuthModule, AuthService } from '@core/auth';
import { StockService } from '@generated/swagger/wws-api';
import { first, map, retry, switchMap, take } from 'rxjs/operators';
import { ShellService } from '../shell.service';
import { ApplicationProcess, ApplicationService } from '@core/application';
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
import { EnvironmentService } from '@core/environment';
import { CommonModule } from '@angular/common';
import { Config } from '@core/config';
import { BreadcrumbService } from '@core/breadcrumb';
import { IconComponent } from '@shared/components/icon';
import { RegexRouterLinkActiveDirective } from '@shared/directives/router-link-active';
import { WrongDestinationModalService } from '@modal/wrong-destination';
import {
CustomerCreateNavigation,
CustomerOrdersNavigationService,
CustomerSearchNavigation,
PickupShelfInNavigationService,
PickUpShelfOutNavigationService,
ProductCatalogNavigationService,
} from '@shared/services/navigation';
import { TabService } from '@isa/core/tabs';
import { NgIconComponent, provideIcons } from '@ng-icons/core';
import { isaNavigationRemission2, isaNavigationReturn } from '@isa/icons';
@Component({
selector: 'shell-side-menu',
templateUrl: 'side-menu.component.html',
styleUrls: ['side-menu.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [
CommonModule,
NgIconComponent,
IconComponent,
RouterModule,
AuthModule,
RegexRouterLinkActiveDirective,
],
providers: [provideIcons({ isaNavigationReturn, isaNavigationRemission2 })],
})
export class ShellSideMenuComponent {
#shellService = inject(ShellService);
#authService = inject(AuthService);
#stockService = inject(StockService);
#app = inject(ApplicationService);
#router = inject(Router);
#route = inject(ActivatedRoute);
#wrongDestinationModalService = inject(WrongDestinationModalService);
#environment = inject(EnvironmentService);
#catalogNavigationService = inject(ProductCatalogNavigationService);
#customerOrdersNavigationService = inject(CustomerOrdersNavigationService);
#config = inject(Config);
#breadcrumbService = inject(BreadcrumbService);
#customerSearchNavigation = inject(CustomerSearchNavigation);
#customerCreateNavigation = inject(CustomerCreateNavigation);
#pickUpShelfOutNavigation = inject(PickUpShelfOutNavigationService);
#pickUpShelfInNavigation = inject(PickupShelfInNavigationService);
#cdr = inject(ChangeDetectorRef);
#document = inject(DOCUMENT);
processService = inject(TabService);
branchKey$ = this.#stockService.StockCurrentBranch().pipe(
retry(3),
map((x) => x.result.key),
);
section$ = this.#app.getSection$();
processes$ = this.section$.pipe(
switchMap((section) => this.#app.getProcesses$(section)),
);
processesCount$ = this.processes$.pipe(
map((processes) => processes?.length ?? 0),
);
activeProcess$ = this.#app.activatedProcessId$.pipe(
switchMap((processId) => this.#app.getProcessById$(processId)),
);
get isTablet() {
return this.#environment.matchTablet();
}
customerBasePath$ = this.activeProcess$.pipe(
map((process) => {
if (
!!process &&
process.section === 'customer' &&
process.type !== 'cart-checkout'
) {
// Übernehme aktiven Prozess
return `/kunde/${process.id}`;
} else {
// Über Guards wird ein neuer Prozess erstellt
return '/kunde';
}
}),
);
customerSearchRoute$ = this.getLastActivatedCustomerProcessId$().pipe(
map((processId) => {
return this.#customerSearchNavigation.defaultRoute({ processId });
}),
);
customerCreateRoute$ = this.getLastActivatedCustomerProcessId$().pipe(
map((processId) => {
return this.#customerCreateNavigation.defaultRoute({ processId });
}),
);
pickUpShelfOutRoutePath$ = this.getLastActivatedCustomerProcessId$().pipe(
map((processId) => {
if (processId) {
// Übernehme aktiven Prozess
return this.#pickUpShelfOutNavigation.defaultRoute({ processId }).path;
} else {
// Über Guards wird ein neuer Prozess erstellt
return this.#pickUpShelfOutNavigation.defaultRoute({}).path;
}
}),
);
productRoutePath$ = this.getLastActivatedCustomerProcessId$().pipe(
map((processId) => {
if (processId) {
// Übernehme aktiven Prozess
return this.#catalogNavigationService.getArticleSearchBasePath(
processId,
).path;
} else {
// Über Guards wird ein neuer Prozess erstellt
return this.#catalogNavigationService.getArticleSearchBasePath().path;
}
}),
);
customerOrdersRoutePath$ = this.getLastActivatedCustomerProcessId$().pipe(
map((processId) => {
if (processId) {
// Übernehme aktiven Prozess
return this.#customerOrdersNavigationService.getCustomerOrdersBasePath(
processId,
).path;
} else {
// Über Guards wird ein neuer Prozess erstellt
return this.#customerOrdersNavigationService.getCustomerOrdersBasePath()
.path;
}
}),
);
taskCalenderNavigation$ = this.getLastNavigationByProcessId(
this.#config.get('process.ids.taskCalendar'),
{
path: ['/filiale', 'task-calendar'],
queryParams: {},
},
'/filiale/task-calendar',
);
assortmentNavigation$ = this.getLastNavigationByProcessId(
this.#config.get('process.ids.assortment'),
{
path: ['/filiale', 'assortment'],
queryParams: {},
},
);
pickUpShelfInRoutePath$ = this.getLastNavigationByProcessId(
this.#config.get('process.ids.pickupShelf'),
this.#pickUpShelfInNavigation.defaultRoute(),
'/filiale/pickup-shelf',
);
// #4478 - RD // Abholfach - Routing löst Suche aus
// pickUpShelfInListRoutePath$ = this.getLastNavigationByProcessId(
// this._config.get('process.ids.pickupShelf'),
// this._pickUpShelfInNavigation.listRoute()
// );
packageInspectionNavigation$ = this.getLastNavigationByProcessId(
this.#config.get('process.ids.packageInspection'),
{
path: ['/filiale', 'package-inspection'],
queryParams: {},
},
);
get currentShelfView$() {
return this.#route.queryParams.pipe(map((params) => params.view));
}
shelfExpanded = false;
customerExpanded = false;
remissionExpanded = signal(false);
customerActive(isActive: boolean) {
if (isActive) {
this.expandCustomer();
}
}
shelfActive(isActive: boolean) {
if (isActive) {
this.expandShelf();
}
}
expandCustomer() {
this.customerExpanded = true;
this.#cdr.markForCheck();
}
expandShelf() {
this.shelfExpanded = true;
this.#cdr.markForCheck();
}
getLastNavigationByProcessId(
id: number,
fallback?: { path: string[]; queryParams: unknown },
pathContainsString?: string,
) {
return this.#breadcrumbService.getBreadcrumbByKey$(id)?.pipe(
map((breadcrumbs) => {
const lastCrumb = breadcrumbs
.filter((breadcrumb) => {
/**
* #4532 - Der optionale Filter wurde hinzugefügt Breadcrumbs mit fehlerhaften Pfad auszuschließen.
* Dieser Filter kann entfernt werden, sobald die Breadcrumbs korrekt gesetzt werden. Jedoch konnte man bisher nicht feststellen,
* woher die fehlerhaften Breadcrumbs kommen.
*/
if (!pathContainsString) {
// Wenn kein Filter gesetzt ist, dann wird der letzte Breadcrumb zurückgegeben
return true;
}
const pathStr = Array.isArray(breadcrumb.path)
? breadcrumb.path.join('/')
: breadcrumb.path;
return pathStr.includes(pathContainsString);
})
// eslint-disable-next-line no-prototype-builtins
.filter((breadcrumb) => !breadcrumb?.params?.hasOwnProperty('view'))
.filter((breadcrumb) => !breadcrumb?.tags?.includes('reservation'))
.filter((breadcrumb) => !breadcrumb?.tags?.includes('cleanup'))
.filter(
(breadcrumb) => !breadcrumb?.tags?.includes('wareneingangsliste'),
)
.filter((breadcrumb) => !breadcrumb?.tags?.includes('preview'))
.reduce((last, current) => {
if (!last) return current;
if (last.changed > current.changed) {
return last;
} else {
return current;
}
}, undefined);
if (!lastCrumb) {
return fallback;
}
// #4692 Return Fallback if Values contain undefined or null values, regardless if path is from type string or array
if (typeof lastCrumb?.path === 'string') {
if (
lastCrumb?.path?.includes('undefined') ||
lastCrumb?.path?.includes('null')
) {
return fallback;
}
} else {
const valuesToCheck = [];
// eslint-disable-next-line no-unsafe-optional-chaining
for (const value of lastCrumb?.path) {
if (
value?.outlets &&
value?.outlets?.primary &&
value?.outlets?.side
) {
valuesToCheck.push(
...Object.values(value?.outlets?.primary),
...Object.values(value?.outlets?.side),
);
} else {
valuesToCheck.push(value);
}
}
if (this.checkIfArrayContainsUndefinedOrNull(valuesToCheck)) {
return fallback;
}
}
return { path: lastCrumb.path, queryParams: lastCrumb.params };
}),
);
}
checkIfArrayContainsUndefinedOrNull(array: unknown[]) {
return (
array?.includes(undefined) ||
array?.includes('undefined') ||
array?.includes(null) ||
array?.includes('null')
);
}
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();
}),
);
}
closeSideMenu() {
this.#shellService.closeSideMenu();
}
logout() {
this.#authService.logout();
}
async resetBranch() {
const process = await this.activeProcess$.pipe(first()).toPromise();
if (process?.id) {
this.#app.patchProcessData(process.id, { selectedBranch: undefined });
}
}
focusSearchBox() {
setTimeout(() => this.#document.getElementById('searchbox')?.focus(), 0);
}
async createProcess() {
const process = await this.createCartProcess();
this.navigateToCatalog(process);
}
async createCartProcess() {
const nextProcessName = await this.getNextProcessName();
const process: ApplicationProcess = {
id: this.getNextProcessId(),
type: 'cart',
name: nextProcessName,
section: 'customer',
closeable: true,
};
this.#app.createProcess(process);
return process;
}
async getNextProcessName() {
let processes = await this.#app
.getProcesses$('customer')
.pipe(first())
.toPromise();
processes = processes.filter(
(x) => x.type === 'cart' && x.name.startsWith('Vorgang '),
);
const maxProcessNumber = processes.reduce((max, process) => {
const number = parseInt(process.name.replace('Vorgang ', ''), 10);
return number > max ? number : max;
}, 0);
return `Vorgang ${maxProcessNumber + 1}`;
}
getNextProcessId() {
return Date.now();
}
async navigateToCatalog(process: ApplicationProcess) {
await this.#catalogNavigationService
.getArticleSearchBasePath(process.id)
.navigate();
}
navigateToDashboard() {
this.#router.navigate(['/kunde', 'dashboard']);
}
async closeAllProcesses() {
const processes = await this.processes$.pipe(take(1)).toPromise();
processes.forEach((process) => this.#app.removeProcess(process.id));
this.navigateToDashboard();
}
fetchAndOpenPackages = () =>
this.#wrongDestinationModalService.fetchAndOpen();
}

View File

@@ -1,97 +1,22 @@
/* You can add global styles to this file, and also import other style files */
@tailwind base;
@tailwind components;
@tailwind utilities;
@import "./scss/components";
/* Scanner Fullscreen Styles */
.full-screen-scanner {
max-width: 100vw !important;
max-height: 100vh !important;
width: 100vw !important;
height: 100vh !important;
.scanner-component {
width: 100%;
height: 100%;
}
}
/* Override CDK overlay container styles for scanner */
.cdk-overlay-container {
.full-screen-scanner {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: 0;
}
}
@import "./scss/root";
@import "./scss/customer";
@import "./scss/branch";
@layer base {
body {
@apply bg-background;
}
::-webkit-scrollbar {
width: 0; // remove scrollbar space
height: 0;
background: transparent; // optional: just make scrollbar invisible */
}
.desktop .scroll-bar::-webkit-scrollbar {
@apply w-3;
background-color: transparent;
}
.desktop .scroll-bar::-webkit-scrollbar-track {
// @apply my-4;
-webkit-box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.1);
border-radius: 10px;
background-color: white;
}
.desktop .scroll-bar::-webkit-scrollbar-thumb {
-webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
border-radius: 10px;
background-color: var(--scrollbar-color);
}
}
@keyframes load {
0% {
opacity: 0;
}
30% {
opacity: 0.5;
}
100% {
opacity: 0;
}
}
.skeleton {
@apply block bg-gray-300 h-6;
animation: load 1s ease-in-out infinite;
}
@layer components {
.input-control {
@apply rounded border border-solid border-[#AEB7C1] px-4 py-[1.125rem] outline-none;
}
// .input-control:focus,
// .input-control:not(:placeholder-shown) {
// @apply bg-white;
// }
.input-control.ng-touched.ng-invalid {
@apply border-brand;
}
}
.full-screen-scanner {
max-width: 100vw !important;
max-height: 100vh !important;
width: 100vw !important;
height: 100vh !important;
.scanner-component {
width: 100%;
height: 100%;
}
}
.cdk-overlay-container {
.full-screen-scanner {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: 0;
}
}

View File

@@ -0,0 +1,76 @@
@use "./scss/components";
@use "./scss/root";
@use "./scss/customer";
@use "./scss/branch";
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer components {
@import "../../../libs/ui/buttons/src/buttons.scss";
@import "../../../libs/ui/bullet-list/src/bullet-list.scss";
@import "../../../libs/ui/datepicker/src/datepicker.scss";
@import "../../../libs/ui/dialog/src/dialog.scss";
@import "../../../libs/ui/input-controls/src/input-controls.scss";
@import "../../../libs/ui/menu/src/menu.scss";
@import "../../../libs/ui/progress-bar/src/lib/progress-bar.scss";
@import "../../../libs/ui/search-bar/src/search-bar.scss";
@import "../../../libs/ui/skeleton-loader/src/skeleton-loader.scss";
@import "../../../libs/ui/tooltip/src/tooltip.scss";
@import "../../../libs/ui/label/src/label.scss";
.input-control {
@apply rounded border border-solid border-[#AEB7C1] px-4 py-[1.125rem] outline-none;
}
.input-control.ng-touched.ng-invalid {
@apply border-brand;
}
@keyframes load {
0% {
opacity: 0;
}
30% {
opacity: 0.5;
}
100% {
opacity: 0;
}
}
.skeleton {
@apply block bg-gray-300 h-6;
animation: load 1s ease-in-out infinite;
}
}
@layer base {
body {
@apply bg-background;
}
::-webkit-scrollbar {
width: 0;
height: 0;
background: transparent;
}
.desktop .scroll-bar::-webkit-scrollbar {
@apply w-3;
background-color: transparent;
}
.desktop .scroll-bar::-webkit-scrollbar-track {
-webkit-box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.1);
border-radius: 10px;
background-color: white;
}
.desktop .scroll-bar::-webkit-scrollbar-thumb {
-webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
border-radius: 10px;
background-color: var(--scrollbar-color);
}
}

View File

@@ -1,9 +0,0 @@
@use "../../../libs/ui/buttons/src/buttons.scss";
@use "../../../libs/ui/datepicker/src/datepicker.scss";
@use "../../../libs/ui/dialog/src/dialog.scss";
@use "../../../libs/ui/input-controls/src/input-controls.scss";
@use "../../../libs/ui/menu/src/menu.scss";
@use "../../../libs/ui/progress-bar/src/lib/progress-bar.scss";
@use "../../../libs/ui/search-bar/src/search-bar.scss";
@use "../../../libs/ui/skeleton-loader/src/skeleton-loader.scss";
@use "../../../libs/ui/tooltip/src/tooltip.scss";

View File

@@ -34,6 +34,7 @@
bottom: 30px !important;
right: 12px;
box-shadow: 0px 0px 20px 0px rgba(89, 100, 112, 0.5);
transition: all 100ms linear;
@screen desktop {
margin-left: 600px;
@@ -44,7 +45,6 @@
box-shadow: none;
}
transition: all 100ms linear;
&.up {
transform: rotate(-90deg);
}

View File

@@ -16,20 +16,20 @@ import {
forwardRef,
Optional,
inject,
} from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { UiAutocompleteComponent } from '@ui/autocomplete';
import { UiFormControlDirective } from '@ui/form-control';
import { Subscription } from 'rxjs';
import { ScanAdapterService } from '@adapter/scan';
import { injectCancelSearch } from '@shared/services/cancel-subject';
import { containsElement } from '@utils/common';
import { EnvironmentService } from '@core/environment';
} from "@angular/core";
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from "@angular/forms";
import { UiAutocompleteComponent } from "@ui/autocomplete";
import { UiFormControlDirective } from "@ui/form-control";
import { Subscription } from "rxjs";
import { ScanAdapterService } from "@adapter/scan";
import { injectCancelSearch } from "@shared/services/cancel-subject";
import { containsElement } from "@utils/common";
import { EnvironmentService } from "@core/environment";
@Component({
selector: 'ui-searchbox',
templateUrl: 'searchbox.component.html',
styleUrls: ['searchbox.component.scss'],
selector: "ui-searchbox",
templateUrl: "searchbox.component.html",
styleUrls: ["searchbox.component.scss"],
providers: [
{
provide: NG_VALUE_ACCESSOR,
@@ -49,9 +49,9 @@ export class UiSearchboxNextComponent
private readonly _cancelSearch = injectCancelSearch({ optional: true });
disabled: boolean;
type = 'text';
type = "text";
@ViewChild('input', { read: ElementRef, static: true })
@ViewChild("input", { read: ElementRef, static: true })
input: ElementRef;
@ContentChild(UiAutocompleteComponent)
@@ -61,9 +61,9 @@ export class UiSearchboxNextComponent
focusAfterViewInit: boolean = true;
@Input()
placeholder: string = '';
placeholder: string = "";
private _query = '';
private _query = "";
@Input()
get query() {
@@ -94,7 +94,7 @@ export class UiSearchboxNextComponent
scanner = false;
@Input()
hint: string = '';
hint: string = "";
@Output()
hintCleared = new EventEmitter<void>();
@@ -107,11 +107,11 @@ export class UiSearchboxNextComponent
}
clear(): void {
this.setQuery('');
this.setQuery("");
this._cancelSearch();
}
@HostBinding('class.autocomplete-opend')
@HostBinding("class.autocomplete-opend")
get autocompleteOpen() {
return this.autocomplete?.opend;
}
@@ -212,14 +212,14 @@ export class UiSearchboxNextComponent
}
clearHint() {
this.hint = '';
this.hint = "";
this.focused.emit(true);
this.hintCleared.emit();
this.cdr.markForCheck();
}
onKeyup(event: KeyboardEvent) {
if (event.key === 'Enter') {
if (event.key === "Enter") {
if (this.autocomplete?.opend && this.autocomplete?.activeItem) {
this.setQuery(this.autocomplete?.activeItem?.item);
this.autocomplete?.close();
@@ -227,7 +227,7 @@ export class UiSearchboxNextComponent
this.search.emit(this.query);
event.preventDefault();
} else if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
} else if (event.key === "ArrowUp" || event.key === "ArrowDown") {
this.handleArrowUpDownEvent(event);
}
}
@@ -235,12 +235,14 @@ export class UiSearchboxNextComponent
handleArrowUpDownEvent(event: KeyboardEvent) {
this.autocomplete?.handleKeyboardEvent(event);
if (this.autocomplete?.activeItem) {
const query = this.autocompleteValueSelector(this.autocomplete.activeItem.item);
const query = this.autocompleteValueSelector(
this.autocomplete.activeItem.item,
);
this.setQuery(query, false, false);
}
}
@HostListener('window:click', ['$event'])
@HostListener("window:click", ["$event"])
focusLost(event: MouseEvent) {
if (
this.autocomplete?.opend &&
@@ -254,9 +256,11 @@ export class UiSearchboxNextComponent
this.search.emit(this.query);
}
@HostListener('focusout', ['$event'])
@HostListener("focusout", ["$event"])
onBlur() {
this.onTouched();
if (typeof this.onTouched === "function") {
this.onTouched();
}
this.focused.emit(false);
this.cdr.markForCheck();
}

View File

@@ -17,6 +17,8 @@
}
.ui-tooltip-panel {
@apply pointer-events-auto;
.triangle {
width: 30px;
polygon {

View File

@@ -17,6 +17,7 @@ import { provideRouter } from '@angular/router';
type ProductInfoInputs = {
item: ProductInfoItem;
orientation: ProductInfoOrientation;
innerGridClass: string;
};
const meta: Meta<ProductInfoInputs> = {
@@ -50,8 +51,10 @@ const meta: Meta<ProductInfoInputs> = {
value: 19.99,
},
},
tag: 'Prio 2',
},
orientation: 'horizontal',
innerGridClass: 'grid-cols-[minmax(20rem,1fr),auto]',
},
argTypes: {
item: {
@@ -68,6 +71,16 @@ const meta: Meta<ProductInfoInputs> = {
},
},
},
innerGridClass: {
control: 'text',
description:
'Custom CSS classes for the inner grid layout. (Applies on vertical layout only)',
table: {
defaultValue: {
summary: 'grid-cols-[minmax(20rem,1fr),auto]',
},
},
},
},
render: (args) => ({
props: args,
@@ -95,6 +108,7 @@ export const Default: Story = {
value: 29.99,
},
},
tag: 'Prio 2',
},
},
};

View File

@@ -0,0 +1,66 @@
import { type Meta, type StoryObj, argsToTemplate } from '@storybook/angular';
import { ProductShelfMetaInfoComponent } from '@isa/remission/shared/product';
const meta: Meta<ProductShelfMetaInfoComponent> = {
component: ProductShelfMetaInfoComponent,
title: 'remission/shared/product/ProductShelfMetaInfoComponent',
args: {
department: 'Reise',
shelfLabel: 'Europa',
productGroupKey: '311',
productGroupValue: 'Romane TB',
assortment: 'Basissortiment|BPrämienartikel|n',
returnReason: 'Beschädigt',
},
argTypes: {
department: {
control: { type: 'text' },
description: 'The department of the product.',
defaultValue: undefined,
},
shelfLabel: {
control: { type: 'text' },
description: 'The shelf label of the product.',
defaultValue: undefined,
},
productGroupKey: {
control: { type: 'text' },
description: 'The key of the product group.',
defaultValue: undefined,
},
productGroupValue: {
control: { type: 'text' },
description: 'The value of the product group.',
defaultValue: undefined,
},
assortment: {
control: { type: 'text' },
description: 'The assortment of the product.',
defaultValue: undefined,
},
returnReason: {
control: { type: 'text' },
description: 'The reason for the return of the product.',
defaultValue: undefined,
},
},
render: (args) => ({
props: args,
template: `<remi-product-shelf-meta-info ${argsToTemplate(args)}></remi-product-shelf-meta-info>`,
}),
};
export default meta;
type Story = StoryObj<ProductShelfMetaInfoComponent>;
export const Default: Story = {
args: {
department: 'Reise',
shelfLabel: 'Europa',
productGroupKey: '311',
productGroupValue: 'Romane TB',
assortment: 'Basissortiment|BPrämienartikel|n',
returnReason: 'Beschädigt',
},
};

View File

@@ -1,50 +1,64 @@
import {
type Meta,
type StoryObj,
argsToTemplate,
moduleMetadata,
} from '@storybook/angular';
import { ProductStockInfoComponent } from '@isa/remission/shared/product';
import { provideProductImageUrl } from '@isa/shared/product-image';
import { provideProductRouterLinkBuilder } from '@isa/shared/product-router-link';
const meta: Meta<ProductStockInfoComponent> = {
component: ProductStockInfoComponent,
title: 'remission/shared/product/ProductStockInfoComponent',
decorators: [
moduleMetadata({
providers: [
provideProductImageUrl('https://produktbilder-test.paragon-data.net'),
provideProductRouterLinkBuilder((ean: string) => ean),
],
}),
],
args: {
stock: 100,
stockToRemit: 20,
},
argTypes: {
stock: {
control: { type: 'number' },
description: 'The current stock of the product.',
defaultValue: undefined,
},
stockToRemit: {
control: { type: 'number' },
description: 'The amount of stock to remit.',
defaultValue: undefined,
},
},
render: (args) => ({
props: args,
template: `<remi-product-stock-info ${argsToTemplate({ info: args })}></remi-product-stock-info>`,
}),
};
export default meta;
type Story = StoryObj<ProductStockInfoComponent>;
export const Default: Story = {
args: {},
};
import {
type Meta,
type StoryObj,
argsToTemplate,
moduleMetadata,
} from '@storybook/angular';
import { ProductStockInfoComponent } from '@isa/remission/shared/product';
import { provideProductImageUrl } from '@isa/shared/product-image';
import { provideProductRouterLinkBuilder } from '@isa/shared/product-router-link';
const meta: Meta<ProductStockInfoComponent> = {
component: ProductStockInfoComponent,
title: 'remission/shared/product/ProductStockInfoComponent',
decorators: [
moduleMetadata({
providers: [
provideProductImageUrl('https://produktbilder-test.paragon-data.net'),
provideProductRouterLinkBuilder((ean: string) => ean),
],
}),
],
args: {
availableStock: 92,
stockToRemit: 91,
targetStock: 1,
zob: 0,
},
argTypes: {
availableStock: {
control: { type: 'number' },
description: 'Total available stock for the product.',
},
stockToRemit: {
control: { type: 'number' },
description: 'Stock quantity to remit.',
},
targetStock: {
control: { type: 'number' },
description: 'Target stock level after remittance.',
},
zob: {
control: { type: 'number' },
description: 'Min Stock Category Management Information.',
defaultValue: 0,
},
},
render: (args) => ({
props: args,
template: `<remi-product-stock-info ${argsToTemplate(args)}></remi-product-stock-info>`,
}),
};
export default meta;
type Story = StoryObj<ProductStockInfoComponent>;
export const Default: Story = {
args: {
availableStock: 92,
stockToRemit: 91,
targetStock: 1,
zob: 0,
},
};

View File

@@ -1,10 +1,16 @@
import { argsToTemplate, type Meta, type StoryObj, moduleMetadata } from '@storybook/angular';
import { EmptyStateComponent } from '@isa/ui/empty-state';
import {
argsToTemplate,
type Meta,
type StoryObj,
moduleMetadata,
} from '@storybook/angular';
import { EmptyStateAppearance, EmptyStateComponent } from '@isa/ui/empty-state';
import { ButtonComponent } from '@isa/ui/buttons';
type EmptyStateComponentInputs = {
title: string;
description: string;
appearance: EmptyStateAppearance;
};
const meta: Meta<EmptyStateComponentInputs> = {
@@ -22,6 +28,10 @@ const meta: Meta<EmptyStateComponentInputs> = {
description: {
control: 'text',
},
appearance: {
control: 'select',
options: Object.values(EmptyStateAppearance),
},
},
render: (args) => ({
props: args,
@@ -40,5 +50,6 @@ export const Default: Story = {
args: {
title: 'Keine Suchergebnisse',
description: 'Suchen Sie nach einer Rechnungsnummer oder Kundennamen.',
appearance: EmptyStateAppearance.NoResults,
},
};

View File

@@ -31,7 +31,7 @@ const meta: Meta<ClientRowComponent> = {
</ui-item-row-data-value>
</ui-item-row-data-row>
<ui-item-row-data-row>
<ui-item-row-data-label>Rechnugsnr.</ui-item-row-data-label>
<ui-item-row-data-label>Beleg-Nr.</ui-item-row-data-label>
<ui-item-row-data-value>
<span class="isa-text-body-2-bold">
1234567890

View File

@@ -0,0 +1,39 @@
import { argsToTemplate, type Meta, type StoryObj } from '@storybook/angular';
import { Labeltype, LabelPriority, LabelComponent } from '@isa/ui/label';
type UiLabelInputs = {
type: Labeltype;
priority: LabelPriority;
};
const meta: Meta<UiLabelInputs> = {
component: LabelComponent,
title: 'ui/label/Label',
argTypes: {
type: {
control: { type: 'select' },
options: Object.values(Labeltype),
description: 'Determines the label type',
},
priority: {
control: { type: 'select' },
options: Object.values(LabelPriority),
description: 'Determines the label priority',
},
},
args: {
type: 'tag',
priority: 'high',
},
render: (args) => ({
props: args,
template: `<ui-label ${argsToTemplate(args)}>Prio 1</ui-label>`,
}),
};
export default meta;
type Story = StoryObj<LabelComponent>;
export const Default: Story = {
args: {},
};

View File

@@ -2,7 +2,8 @@
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../dist/out-tsc",
"types": []
"types": [],
"moduleResolution": "bundler"
},
"files": ["src/main.ts"],
"include": ["src/**/*.d.ts"],

View File

@@ -9,10 +9,10 @@ trigger:
variables:
# Major Version einstellen
- name: 'Major'
value: '3'
value: '4'
# Minor Version einstellen
- name: 'Minor'
value: '4'
value: '1'
- name: 'Patch'
value: "$[counter(format('{0}.{1}', variables['Major'], variables['Minor']),0)]"
- name: 'BuildUniqueID'
@@ -89,7 +89,7 @@ jobs:
condition: and(ne(variables['Build.SourceBranch'], 'refs/heads/integration'), ne(variables['Build.SourceBranch'], 'refs/heads/master'), not(startsWith(variables['Build.SourceBranch'], 'refs/heads/hotfix/')), not(startsWith(variables['Build.SourceBranch'], 'refs/heads/release/')))
variables:
- name: DockerTagSourceBranch
value: $[replace(variables['Build.SourceBranch'], '/', '_')]
value: $[replace(variables['Build.SourceBranch'], '/', '-')]
- name: 'DockerTag'
value: |
$(Build.BuildNumber)-$(Build.SourceVersion)

View File

File diff suppressed because it is too large Load Diff

View File

@@ -6,7 +6,11 @@ module.exports = [
...nx.configs['flat/typescript'],
...nx.configs['flat/javascript'],
{
ignores: ['**/dist'],
ignores: [
'**/dist',
'**/vite.config.*.timestamp*',
'**/vitest.config.*.timestamp*',
],
},
// {
// files: ['**/*.ts', '**/*.tsx', '**/*.js', '**/*.jsx'],

View File

@@ -1,58 +0,0 @@
import nx from '@nx/eslint-plugin';
import eslintConfigPrettier from 'eslint-config-prettier/flat';
import jsoncEslintParser from 'jsonc-eslint-parser';
export default [
...nx.configs['flat/base'],
...nx.configs['flat/typescript'],
...nx.configs['flat/javascript'],
{
ignores: ['**/dist', '**/generated'],
},
// Bis Module Boundaries gelöst sind, wird das Plugin nicht verwendet
// {
// files: ['**/*.ts', '**/*.tsx', '**/*.js', '**/*.jsx'],
// rules: {
// '@nx/enforce-module-boundaries': [
// 'error',
// {
// enforceBuildableLibDependency: true,
// allow: ['^.*/eslint(\\.base)?\\.config\\.[cm]?js$'],
// depConstraints: [
// {
// sourceTag: '*',
// onlyDependOnLibsWithTags: ['*'],
// },
// ],
// },
// ],
// },
// },
{
files: [
'**/*.ts',
'**/*.tsx',
'**/*.js',
'**/*.jsx',
'**/*.cjs',
'**/*.mjs',
],
// Override or add rules here
rules: {},
},
{
files: ['**/*.json'],
rules: {
'@nx/dependency-checks': [
'error',
{
ignoredFiles: ['{projectRoot}/eslint.config.{js,cjs,mjs}'],
},
],
},
languageOptions: {
parser: jsoncEslintParser,
},
},
eslintConfigPrettier,
];

View File

@@ -0,0 +1,40 @@
const nx = require('@nx/eslint-plugin');
const baseConfig = require('../../../eslint.config.js');
module.exports = [
...baseConfig,
...nx.configs['flat/angular'],
...nx.configs['flat/angular-template'],
{
files: ['**/*.ts'],
rules: {
'@angular-eslint/directive-selector': [
'error',
{
type: 'attribute',
prefix: 'lib',
style: 'camelCase',
},
],
'@angular-eslint/component-selector': [
'error',
{
type: 'element',
prefix: 'lib',
style: 'kebab-case',
},
],
},
},
{
files: ['**/*.html'],
// Override or add rules here
rules: {},
},
{
files: ['**/*.ts'],
rules: {
'@angular-eslint/prefer-standalone': 'off',
},
},
];

View File

@@ -0,0 +1,40 @@
const nx = require('@nx/eslint-plugin');
const baseConfig = require('../../../eslint.config.js');
module.exports = [
...baseConfig,
...nx.configs['flat/angular'],
...nx.configs['flat/angular-template'],
{
files: ['**/*.ts'],
rules: {
'@angular-eslint/directive-selector': [
'error',
{
type: 'attribute',
prefix: 'lib',
style: 'camelCase',
},
],
'@angular-eslint/component-selector': [
'error',
{
type: 'element',
prefix: 'lib',
style: 'kebab-case',
},
],
},
},
{
files: ['**/*.html'],
// Override or add rules here
rules: {},
},
{
files: ['**/*.ts'],
rules: {
'@angular-eslint/prefer-standalone': 'off',
},
},
];

View File

@@ -0,0 +1,40 @@
const nx = require('@nx/eslint-plugin');
const baseConfig = require('../../../eslint.config.js');
module.exports = [
...baseConfig,
...nx.configs['flat/angular'],
...nx.configs['flat/angular-template'],
{
files: ['**/*.ts'],
rules: {
'@angular-eslint/directive-selector': [
'error',
{
type: 'attribute',
prefix: 'lib',
style: 'camelCase',
},
],
'@angular-eslint/component-selector': [
'error',
{
type: 'element',
prefix: 'lib',
style: 'kebab-case',
},
],
},
},
{
files: ['**/*.html'],
// Override or add rules here
rules: {},
},
{
files: ['**/*.ts'],
rules: {
'@angular-eslint/prefer-standalone': 'off',
},
},
];

View File

@@ -0,0 +1,40 @@
const nx = require('@nx/eslint-plugin');
const baseConfig = require('../../../eslint.config.js');
module.exports = [
...baseConfig,
...nx.configs['flat/angular'],
...nx.configs['flat/angular-template'],
{
files: ['**/*.ts'],
rules: {
'@angular-eslint/directive-selector': [
'error',
{
type: 'attribute',
prefix: 'lib',
style: 'camelCase',
},
],
'@angular-eslint/component-selector': [
'error',
{
type: 'element',
prefix: 'lib',
style: 'kebab-case',
},
],
},
},
{
files: ['**/*.html'],
// Override or add rules here
rules: {},
},
{
files: ['**/*.ts'],
rules: {
'@angular-eslint/prefer-standalone': 'off',
},
},
];

View File

@@ -0,0 +1,40 @@
const nx = require('@nx/eslint-plugin');
const baseConfig = require('../../../eslint.config.js');
module.exports = [
...baseConfig,
...nx.configs['flat/angular'],
...nx.configs['flat/angular-template'],
{
files: ['**/*.ts'],
rules: {
'@angular-eslint/directive-selector': [
'error',
{
type: 'attribute',
prefix: 'lib',
style: 'camelCase',
},
],
'@angular-eslint/component-selector': [
'error',
{
type: 'element',
prefix: 'lib',
style: 'kebab-case',
},
],
},
},
{
files: ['**/*.html'],
// Override or add rules here
rules: {},
},
{
files: ['**/*.ts'],
rules: {
'@angular-eslint/prefer-standalone': 'off',
},
},
];

View File

@@ -1,34 +0,0 @@
import nx from '@nx/eslint-plugin';
import baseConfig from '../../../eslint.config.mjs';
export default [
...baseConfig,
...nx.configs['flat/angular'],
...nx.configs['flat/angular-template'],
{
files: ['**/*.ts'],
rules: {
'@angular-eslint/directive-selector': [
'error',
{
type: 'attribute',
prefix: 'lib',
style: 'camelCase',
},
],
'@angular-eslint/component-selector': [
'error',
{
type: 'element',
prefix: 'lib',
style: 'kebab-case',
},
],
},
},
{
files: ['**/*.html'],
// Override or add rules here
rules: {},
},
];

View File

@@ -0,0 +1,40 @@
const nx = require('@nx/eslint-plugin');
const baseConfig = require('../../../eslint.config.js');
module.exports = [
...baseConfig,
...nx.configs['flat/angular'],
...nx.configs['flat/angular-template'],
{
files: ['**/*.ts'],
rules: {
'@angular-eslint/directive-selector': [
'error',
{
type: 'attribute',
prefix: 'lib',
style: 'camelCase',
},
],
'@angular-eslint/component-selector': [
'error',
{
type: 'element',
prefix: 'lib',
style: 'kebab-case',
},
],
},
},
{
files: ['**/*.html'],
// Override or add rules here
rules: {},
},
{
files: ['**/*.ts'],
rules: {
'@angular-eslint/prefer-standalone': 'off',
},
},
];

View File

@@ -1,34 +0,0 @@
import nx from '@nx/eslint-plugin';
import baseConfig from '../../../eslint.config.mjs';
export default [
...baseConfig,
...nx.configs['flat/angular'],
...nx.configs['flat/angular-template'],
{
files: ['**/*.ts'],
rules: {
'@angular-eslint/directive-selector': [
'error',
{
type: 'attribute',
prefix: 'lib',
style: 'camelCase',
},
],
'@angular-eslint/component-selector': [
'error',
{
type: 'element',
prefix: 'lib',
style: 'kebab-case',
},
],
},
},
{
files: ['**/*.html'],
// Override or add rules here
rules: {},
},
];

View File

@@ -0,0 +1,40 @@
const nx = require('@nx/eslint-plugin');
const baseConfig = require('../../../eslint.config.js');
module.exports = [
...baseConfig,
...nx.configs['flat/angular'],
...nx.configs['flat/angular-template'],
{
files: ['**/*.ts'],
rules: {
'@angular-eslint/directive-selector': [
'error',
{
type: 'attribute',
prefix: 'lib',
style: 'camelCase',
},
],
'@angular-eslint/component-selector': [
'error',
{
type: 'element',
prefix: 'lib',
style: 'kebab-case',
},
],
},
},
{
files: ['**/*.html'],
// Override or add rules here
rules: {},
},
{
files: ['**/*.ts'],
rules: {
'@angular-eslint/prefer-standalone': 'off',
},
},
];

View File

@@ -1,34 +0,0 @@
import nx from '@nx/eslint-plugin';
import baseConfig from '../../../eslint.config.mjs';
export default [
...baseConfig,
...nx.configs['flat/angular'],
...nx.configs['flat/angular-template'],
{
files: ['**/*.ts'],
rules: {
'@angular-eslint/directive-selector': [
'error',
{
type: 'attribute',
prefix: 'lib',
style: 'camelCase',
},
],
'@angular-eslint/component-selector': [
'error',
{
type: 'element',
prefix: 'lib',
style: 'kebab-case',
},
],
},
},
{
files: ['**/*.html'],
// Override or add rules here
rules: {},
},
];

View File

@@ -0,0 +1,40 @@
const nx = require('@nx/eslint-plugin');
const baseConfig = require('../../../eslint.config.js');
module.exports = [
...baseConfig,
...nx.configs['flat/angular'],
...nx.configs['flat/angular-template'],
{
files: ['**/*.ts'],
rules: {
'@angular-eslint/directive-selector': [
'error',
{
type: 'attribute',
prefix: 'lib',
style: 'camelCase',
},
],
'@angular-eslint/component-selector': [
'error',
{
type: 'element',
prefix: 'lib',
style: 'kebab-case',
},
],
},
},
{
files: ['**/*.html'],
// Override or add rules here
rules: {},
},
{
files: ['**/*.ts'],
rules: {
'@angular-eslint/prefer-standalone': 'off',
},
},
];

View File

@@ -1,34 +0,0 @@
import nx from '@nx/eslint-plugin';
import baseConfig from '../../../eslint.config.mjs';
export default [
...baseConfig,
...nx.configs['flat/angular'],
...nx.configs['flat/angular-template'],
{
files: ['**/*.ts'],
rules: {
'@angular-eslint/directive-selector': [
'error',
{
type: 'attribute',
prefix: 'lib',
style: 'camelCase',
},
],
'@angular-eslint/component-selector': [
'error',
{
type: 'element',
prefix: 'lib',
style: 'kebab-case',
},
],
},
},
{
files: ['**/*.html'],
// Override or add rules here
rules: {},
},
];

View File

@@ -0,0 +1,40 @@
const nx = require('@nx/eslint-plugin');
const baseConfig = require('../../../eslint.config.js');
module.exports = [
...baseConfig,
...nx.configs['flat/angular'],
...nx.configs['flat/angular-template'],
{
files: ['**/*.ts'],
rules: {
'@angular-eslint/directive-selector': [
'error',
{
type: 'attribute',
prefix: 'lib',
style: 'camelCase',
},
],
'@angular-eslint/component-selector': [
'error',
{
type: 'element',
prefix: 'lib',
style: 'kebab-case',
},
],
},
},
{
files: ['**/*.html'],
// Override or add rules here
rules: {},
},
{
files: ['**/*.ts'],
rules: {
'@angular-eslint/prefer-standalone': 'off',
},
},
];

View File

@@ -1,34 +0,0 @@
import nx from '@nx/eslint-plugin';
import baseConfig from '../../../eslint.config.mjs';
export default [
...baseConfig,
...nx.configs['flat/angular'],
...nx.configs['flat/angular-template'],
{
files: ['**/*.ts'],
rules: {
'@angular-eslint/directive-selector': [
'error',
{
type: 'attribute',
prefix: 'lib',
style: 'camelCase',
},
],
'@angular-eslint/component-selector': [
'error',
{
type: 'element',
prefix: 'lib',
style: 'kebab-case',
},
],
},
},
{
files: ['**/*.html'],
// Override or add rules here
rules: {},
},
];

View File

@@ -0,0 +1,40 @@
const nx = require('@nx/eslint-plugin');
const baseConfig = require('../../../eslint.config.js');
module.exports = [
...baseConfig,
...nx.configs['flat/angular'],
...nx.configs['flat/angular-template'],
{
files: ['**/*.ts'],
rules: {
'@angular-eslint/directive-selector': [
'error',
{
type: 'attribute',
prefix: 'lib',
style: 'camelCase',
},
],
'@angular-eslint/component-selector': [
'error',
{
type: 'element',
prefix: 'lib',
style: 'kebab-case',
},
],
},
},
{
files: ['**/*.html'],
// Override or add rules here
rules: {},
},
{
files: ['**/*.ts'],
rules: {
'@angular-eslint/prefer-standalone': 'off',
},
},
];

View File

@@ -1,34 +0,0 @@
import nx from '@nx/eslint-plugin';
import baseConfig from '../../../eslint.config.mjs';
export default [
...baseConfig,
...nx.configs['flat/angular'],
...nx.configs['flat/angular-template'],
{
files: ['**/*.ts'],
rules: {
'@angular-eslint/directive-selector': [
'error',
{
type: 'attribute',
prefix: 'lib',
style: 'camelCase',
},
],
'@angular-eslint/component-selector': [
'error',
{
type: 'element',
prefix: 'lib',
style: 'kebab-case',
},
],
},
},
{
files: ['**/*.html'],
// Override or add rules here
rules: {},
},
];

View File

@@ -0,0 +1,40 @@
const nx = require('@nx/eslint-plugin');
const baseConfig = require('../../../eslint.config.js');
module.exports = [
...baseConfig,
...nx.configs['flat/angular'],
...nx.configs['flat/angular-template'],
{
files: ['**/*.ts'],
rules: {
'@angular-eslint/directive-selector': [
'error',
{
type: 'attribute',
prefix: 'lib',
style: 'camelCase',
},
],
'@angular-eslint/component-selector': [
'error',
{
type: 'element',
prefix: 'lib',
style: 'kebab-case',
},
],
},
},
{
files: ['**/*.html'],
// Override or add rules here
rules: {},
},
{
files: ['**/*.ts'],
rules: {
'@angular-eslint/prefer-standalone': 'off',
},
},
];

View File

@@ -1,34 +0,0 @@
import nx from '@nx/eslint-plugin';
import baseConfig from '../../../eslint.config.mjs';
export default [
...baseConfig,
...nx.configs['flat/angular'],
...nx.configs['flat/angular-template'],
{
files: ['**/*.ts'],
rules: {
'@angular-eslint/directive-selector': [
'error',
{
type: 'attribute',
prefix: 'lib',
style: 'camelCase',
},
],
'@angular-eslint/component-selector': [
'error',
{
type: 'element',
prefix: 'lib',
style: 'kebab-case',
},
],
},
},
{
files: ['**/*.html'],
// Override or add rules here
rules: {},
},
];

View File

@@ -0,0 +1,3 @@
export * from './models';
export * from './schemas';
export * from './services';

View File

@@ -0,0 +1,222 @@
import { TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { CatalougeSearchService } from './catalouge-search.service';
import { SearchService } from '@generated/swagger/cat-search-api';
import { Item } from '../models';
import { SearchByTermInput } from '../schemas/catalouge-search.schemas';
describe('CatalougeSearchService', () => {
let service: CatalougeSearchService;
let searchServiceSpy: jest.Mocked<SearchService>;
beforeEach(() => {
const searchServiceMock = {
SearchByEAN: jest.fn(),
SearchSearch: jest.fn(),
};
TestBed.configureTestingModule({
providers: [
CatalougeSearchService,
{ provide: SearchService, useValue: searchServiceMock },
],
});
service = TestBed.inject(CatalougeSearchService);
searchServiceSpy = TestBed.inject(SearchService) as jest.Mocked<SearchService>;
});
it('should be created', () => {
expect(service).toBeTruthy();
});
describe('searchByEans', () => {
it('should return items when search is successful', (done) => {
// Arrange
const mockItems: Item[] = [
{ id: 1, product: { name: 'Item 1' }, catalogAvailability: { available: true } } as unknown as Item,
{ id: 2, product: { name: 'Item 2' }, catalogAvailability: { available: true } } as unknown as Item,
];
const mockResponse = {
error: false,
result: mockItems,
};
searchServiceSpy.SearchByEAN.mockReturnValue(of(mockResponse));
// Act
service.searchByEans('123456789', '987654321').subscribe({
next: (result) => {
// Assert
expect(result).toEqual(mockItems);
expect(searchServiceSpy.SearchByEAN).toHaveBeenCalledWith(['123456789', '987654321']);
done();
},
error: done.fail,
});
});
it('should throw error when response has error', (done) => {
// Arrange
const mockResponse = {
error: true,
message: 'Search failed',
};
searchServiceSpy.SearchByEAN.mockReturnValue(of(mockResponse));
// Act
service.searchByEans('123456789').subscribe({
next: () => done.fail('Should have thrown error'),
error: (error) => {
// Assert
expect(error).toBeInstanceOf(Error);
expect(error.message).toBe('Search failed');
done();
},
});
});
it('should handle single EAN', (done) => {
// Arrange
const mockItems: Item[] = [{ id: 1, product: { name: 'Item 1' }, catalogAvailability: { available: true } } as unknown as Item];
const mockResponse = {
error: false,
result: mockItems,
};
searchServiceSpy.SearchByEAN.mockReturnValue(of(mockResponse));
// Act
service.searchByEans('123456789').subscribe({
next: (result) => {
// Assert
expect(result).toEqual(mockItems);
expect(searchServiceSpy.SearchByEAN).toHaveBeenCalledWith(['123456789']);
done();
},
error: done.fail,
});
});
it('should handle empty EAN array', (done) => {
// Arrange
const mockResponse = {
error: false,
result: [],
};
searchServiceSpy.SearchByEAN.mockReturnValue(of(mockResponse));
// Act
service.searchByEans().subscribe({
next: (result) => {
// Assert
expect(result).toEqual([]);
expect(searchServiceSpy.SearchByEAN).toHaveBeenCalledWith([]);
done();
},
error: done.fail,
});
});
});
describe('searchByTerm', () => {
it('should return search results when successful', async () => {
// Arrange
const mockItems: Item[] = [
{ id: 1, product: { name: 'Test Item' }, catalogAvailability: { available: true } } as unknown as Item,
];
const mockResponse = {
error: false,
result: mockItems,
total: 1,
};
searchServiceSpy.SearchSearch.mockReturnValue(of(mockResponse));
const params: SearchByTermInput = {
searchTerm: 'test',
skip: 0,
take: 10,
};
const abortController = new AbortController();
// Act
const result = await service.searchByTerm(params, abortController.signal);
// Assert
expect(result).toEqual(mockResponse);
expect(searchServiceSpy.SearchSearch).toHaveBeenCalledWith({
input: { qs: 'test' },
skip: 0,
take: 10,
doNotTrack: true,
});
});
it('should throw error when response has error', async () => {
// Arrange
const mockResponse = {
error: true,
message: 'Search failed',
};
searchServiceSpy.SearchSearch.mockReturnValue(of(mockResponse));
const params: SearchByTermInput = {
searchTerm: 'test',
skip: 0,
take: 10,
};
const abortController = new AbortController();
// Act & Assert
await expect(service.searchByTerm(params, abortController.signal))
.rejects
.toThrow('Search failed');
});
it('should handle abort signal', async () => {
// Arrange
const abortController = new AbortController();
const mockResponse = {
error: false,
result: [],
};
searchServiceSpy.SearchSearch.mockReturnValue(of(mockResponse));
const params: SearchByTermInput = {
searchTerm: 'test',
skip: 0,
take: 10,
};
// Act
const result = await service.searchByTerm(params, abortController.signal);
// Assert
expect(result).toEqual(mockResponse);
expect(searchServiceSpy.SearchSearch).toHaveBeenCalled();
});
it('should use default values when not provided', async () => {
// Arrange
const mockResponse = {
error: false,
result: [],
};
searchServiceSpy.SearchSearch.mockReturnValue(of(mockResponse));
const params: SearchByTermInput = {
searchTerm: 'test',
};
const abortController = new AbortController();
// Act
await service.searchByTerm(params, abortController.signal);
// Assert
expect(searchServiceSpy.SearchSearch).toHaveBeenCalledWith({
input: { qs: 'test' },
skip: 0,
take: 20,
doNotTrack: true,
});
});
});
});

View File

@@ -1,52 +1,53 @@
import { inject, Injectable } from '@angular/core';
import { SearchService } from '@generated/swagger/cat-search-api';
import { firstValueFrom, map, Observable } from 'rxjs';
import { takeUntilAborted } from '@isa/common/data-access';
import { Item } from '../models';
import {
SearchByTermInput,
SearchByTermSchema,
} from '../schemas/catalouge-search.schemas';
import { ListResponseArgs } from '@isa/common/data-access';
@Injectable({ providedIn: 'root' })
export class CatalougeSearchService {
#searchService = inject(SearchService);
searchByEans(...ean: string[]): Observable<Item[]> {
return this.#searchService.SearchByEAN(ean).pipe(
map((res) => {
if (res.error) {
throw new Error(res.message);
}
return res.result as Item[];
}),
);
}
async searchByTerm(
params: SearchByTermInput,
abortSignal: AbortSignal,
): Promise<ListResponseArgs<Item>> {
const { searchTerm, skip, take } = SearchByTermSchema.parse(params);
const req$ = this.#searchService
.SearchSearch({
filter: {
qs: searchTerm,
},
skip,
take,
})
.pipe(takeUntilAborted(abortSignal));
const res = await firstValueFrom(req$);
if (res.error) {
throw new Error(res.message);
}
return res as ListResponseArgs<Item>;
}
}
import { inject, Injectable } from '@angular/core';
import { SearchService } from '@generated/swagger/cat-search-api';
import { firstValueFrom, map, Observable } from 'rxjs';
import { takeUntilAborted } from '@isa/common/data-access';
import { Item } from '../models';
import {
SearchByTermInput,
SearchByTermSchema,
} from '../schemas/catalouge-search.schemas';
import { ListResponseArgs } from '@isa/common/data-access';
@Injectable({ providedIn: 'root' })
export class CatalougeSearchService {
#searchService = inject(SearchService);
searchByEans(...ean: string[]): Observable<Item[]> {
return this.#searchService.SearchByEAN(ean).pipe(
map((res) => {
if (res.error) {
throw new Error(res.message);
}
return res.result as Item[];
}),
);
}
async searchByTerm(
params: SearchByTermInput,
abortSignal: AbortSignal,
): Promise<ListResponseArgs<Item>> {
const { searchTerm, skip, take } = SearchByTermSchema.parse(params);
const req$ = this.#searchService
.SearchSearch({
input: {
qs: searchTerm,
},
skip,
take,
doNotTrack: true,
})
.pipe(takeUntilAborted(abortSignal));
const res = await firstValueFrom(req$);
if (res.error) {
throw new Error(res.message);
}
return res as ListResponseArgs<Item>;
}
}

View File

@@ -0,0 +1,34 @@
const nx = require('@nx/eslint-plugin');
const baseConfig = require('../../../eslint.config.js');
module.exports = [
...baseConfig,
...nx.configs['flat/angular'],
...nx.configs['flat/angular-template'],
{
files: ['**/*.ts'],
rules: {
'@angular-eslint/directive-selector': [
'error',
{
type: 'attribute',
prefix: 'common',
style: 'camelCase',
},
],
'@angular-eslint/component-selector': [
'error',
{
type: 'element',
prefix: 'common',
style: 'kebab-case',
},
],
},
},
{
files: ['**/*.html'],
// Override or add rules here
rules: {},
},
];

View File

@@ -44,5 +44,8 @@ export class DataAccessError<TCode extends string, TData = void> extends Error {
public readonly data: TData,
) {
super(message);
// Set the prototype explicitly to maintain the correct prototype chain
Object.setPrototypeOf(this, new.target.prototype);
this.name = this.constructor.name;
}
}

View File

@@ -1,2 +1,4 @@
export * from './errors';
export * from './models';
export * from './errors';
export * from './helpers';
export * from './models';
export * from './operators';

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