Compare commits

..
Author SHA1 Message Date
Jeppe Bundgaard 3a78e523b2 Focus EAN PR Playwright mapping 2026-07-06 18:11:07 +02:00
Jeppe Bundgaard 7f68471b85 Add EAN to economic customer registration 2026-07-06 18:10:42 +02:00
90 changed files with 590 additions and 4315 deletions
+13 -240
View File
@@ -6,39 +6,6 @@ on:
branches:
- master
workflow_dispatch:
inputs:
mode:
description: "What to run for a manual dispatch."
required: true
type: choice
default: full
options:
- full
- targeted
- targeted-then-full
target_specs:
description: "Comma- or newline-separated Playwright spec paths under tests/e2e."
required: false
type: string
default: "tests/e2e/superuser-department-overview.spec.js"
target_projects:
description: "JSON array of Playwright projects for targeted mode."
required: false
type: string
default: '["chromium-desktop","chromium-mobile","chromium-tablet","webkit-mobile","webkit-desktop"]'
target_grep:
description: "Optional Playwright grep pattern for targeted mode."
required: false
type: string
default: ""
runner:
description: "Runner pool for this manually dispatched test run"
required: false
default: "self-hosted"
type: choice
options:
- self-hosted
- github-hosted
schedule:
- cron: "0 2 * * *"
@@ -46,22 +13,16 @@ permissions:
contents: read
concurrency:
group: frontend-tests-${{ github.workflow }}-${{ github.event_name }}-${{ github.event_name == 'workflow_dispatch' && github.run_id || github.head_ref || github.ref_name }}
group: frontend-tests-${{ github.workflow }}-${{ github.event_name }}-${{ github.head_ref || github.ref_name }}
cancel-in-progress: true
# Repository variables used as CI runner and credit controls:
# - FRONTEND_CI_STANDARD_RUNNER: JSON runs-on value for format/build/unit jobs.
# - FRONTEND_CI_E2E_RUNNER: JSON runs-on value for Playwright jobs.
# - FRONTEND_CI_PR_E2E_MAX_PARALLEL: numeric Playwright PR job parallelism.
# - FRONTEND_CI_FULL_E2E_MAX_PARALLEL: numeric full-suite job parallelism.
# GitHub-hosted example: ["ubuntu-22.04"], with PR parallelism 2 and full parallelism 1.
jobs:
format-tests:
runs-on: ${{ fromJSON(vars.FRONTEND_CI_STANDARD_RUNNER || '["self-hosted","Linux","X64","pleno","frontend"]') }}
# CI runs on the repository's self-hosted runner pool.
runs-on: [self-hosted, Linux, X64, pleno, frontend]
timeout-minutes: 15
steps:
- name: Repair self-hosted workspace permissions
if: ${{ contains(vars.FRONTEND_CI_STANDARD_RUNNER || 'self-hosted', 'self-hosted') }}
shell: bash
run: |
if [[ -d "$GITHUB_WORKSPACE" ]]; then
@@ -94,11 +55,10 @@ jobs:
build-and-unit:
needs: format-tests
runs-on: ${{ fromJSON(vars.FRONTEND_CI_STANDARD_RUNNER || '["self-hosted","Linux","X64","pleno","frontend"]') }}
runs-on: [self-hosted, Linux, X64, pleno, frontend]
timeout-minutes: 30
steps:
- name: Repair self-hosted workspace permissions
if: ${{ contains(vars.FRONTEND_CI_STANDARD_RUNNER || 'self-hosted', 'self-hosted') }}
shell: bash
run: |
if [[ -d "$GITHUB_WORKSPACE" ]]; then
@@ -137,195 +97,15 @@ jobs:
env:
VITEST_BATCH_SIZE: 5
e2e-targeted:
if: >
github.event_name == 'workflow_dispatch' &&
(inputs.mode == 'targeted' || inputs.mode == 'targeted-then-full')
needs: build-and-unit
name: E2E-targeted-${{ matrix.project }}
# Use GitHub-hosted runners to avoid self-hosted desktop contention and sleep/power events.
runs-on: ubuntu-24.04
timeout-minutes: 35
strategy:
fail-fast: false
matrix:
project: ${{ fromJSON(inputs.target_projects || '["chromium-desktop"]') }}
env:
MATRIX_PROJECT: ${{ matrix.project }}
PLAYWRIGHT_ARTIFACT_NAMESPACE: e2e-targeted-${{ matrix.project }}
PLAYWRIGHT_REPORTER_MODE: line-html
PLAYWRIGHT_WORKERS: 1
PLAYWRIGHT_VIDEO_MODE: on-first-retry
TARGET_GREP: ${{ inputs.target_grep }}
TARGET_SPECS: ${{ inputs.target_specs }}
RUN_ID: ${{ github.run_id }}
steps:
- name: Normalize workspace permissions
shell: bash
run: |
if [[ -d "$GITHUB_WORKSPACE" ]]; then
sudo -n chown -R "$(id -u):$(id -g)" "$GITHUB_WORKSPACE" 2>/dev/null || true
foreign_entry="$(find "$GITHUB_WORKSPACE" -mindepth 1 -maxdepth 2 ! -user "$(id -u)" -print -quit 2>/dev/null || true)"
if [[ -n "$foreign_entry" ]]; then
trash="$GITHUB_WORKSPACE/../_workspace-trash-$GITHUB_RUN_ID-$GITHUB_JOB"
rm -rf "$trash" 2>/dev/null || true
mv "$GITHUB_WORKSPACE" "$trash" 2>/dev/null || true
mkdir -p "$GITHUB_WORKSPACE"
fi
fi
- name: Checkout repository
uses: actions/checkout@v5
- name: Setup Node.js
uses: actions/setup-node@v5
with:
node-version: 22
- name: Run targeted Playwright specs in container
shell: bash
run: |
set -euo pipefail
case "$MATRIX_PROJECT" in
chromium-mobile) project_offset=1 ;;
chromium-desktop) project_offset=2 ;;
chromium-tablet) project_offset=3 ;;
webkit-mobile) project_offset=31 ;;
webkit-desktop) project_offset=32 ;;
webkit-tablet) project_offset=33 ;;
firefox-mobile) project_offset=61 ;;
firefox-desktop) project_offset=62 ;;
firefox-tablet) project_offset=63 ;;
*) echo "Unsupported Playwright project: $MATRIX_PROJECT" >&2; exit 1 ;;
esac
port_seed=$((20000 + (RUN_ID % 20000) + project_offset))
lock_root="${PLAYWRIGHT_PORT_LOCK_ROOT:-/tmp/pleno-playwright-port-locks}"
mkdir -p "$lock_root"
chmod 1777 "$lock_root" 2>/dev/null || true
find "$lock_root" -mindepth 1 -maxdepth 1 -type d -mmin +360 -exec rmdir {} \; 2>/dev/null || true
playwright_port_lock=""
playwright_dev_port=""
for ((candidate = port_seed; candidate < port_seed + 1000; candidate += 1)); do
lock_dir="${lock_root}/${candidate}.lock"
if ! mkdir "$lock_dir" 2>/dev/null; then
continue
fi
if ss -H -ltn "sport = :${candidate}" 2>/dev/null | grep -q .; then
rmdir "$lock_dir" || true
continue
fi
playwright_port_lock="$lock_dir"
playwright_dev_port="$candidate"
break
done
if [[ -z "$playwright_dev_port" ]]; then
echo "Unable to find a free Playwright dev-server port." >&2
exit 1
fi
trap 'if [[ -n "${playwright_port_lock:-}" ]]; then rmdir "$playwright_port_lock" 2>/dev/null || true; fi' EXIT
if docker info >/dev/null 2>&1; then
docker_cmd=(docker)
elif sudo -n docker info >/dev/null 2>&1; then
docker_cmd=(sudo docker)
else
echo "Docker is not available to the runner user, and sudo docker is not available." >&2
exit 1
fi
mkdir -p output/playwright
scripts/ci/runner-diagnostics.sh "before targeted Playwright ${MATRIX_PROJECT}" -- "${docker_cmd[@]}"
SYSTEMD_INHIBIT_REASON="Frontend targeted Playwright ${MATRIX_PROJECT}" \
scripts/ci/with-systemd-inhibit.sh "${docker_cmd[@]}" run --rm --ipc=host --network host \
--volume "$PWD:/source:ro" \
--volume "$PWD/output/playwright:/work/output/playwright" \
--workdir /work \
--env HOME=/tmp \
--env CI="${CI:-}" \
--env PLAYWRIGHT_ARTIFACT_NAMESPACE="$PLAYWRIGHT_ARTIFACT_NAMESPACE" \
--env PLAYWRIGHT_REPORTER_MODE="$PLAYWRIGHT_REPORTER_MODE" \
--env PLAYWRIGHT_WORKERS="$PLAYWRIGHT_WORKERS" \
--env PLAYWRIGHT_VIDEO_MODE="$PLAYWRIGHT_VIDEO_MODE" \
--env PLAYWRIGHT_DEV_PORT="$playwright_dev_port" \
--env MATRIX_PROJECT="$MATRIX_PROJECT" \
--env TARGET_GREP="$TARGET_GREP" \
--env TARGET_SPECS="$TARGET_SPECS" \
mcr.microsoft.com/playwright:v1.58.2-noble \
bash -lc '
set -euo pipefail
tar --exclude=./output/playwright -C /source -cf - . | tar -C /work -xf -
git config --global --add safe.directory /work
install_dependencies() {
local attempt
for attempt in 1 2 3; do
if npm ci --legacy-peer-deps --fetch-retries=5 --fetch-retry-mintimeout=20000 --fetch-retry-maxtimeout=120000; then
return 0
fi
if [[ "$attempt" == "3" ]]; then
return 1
fi
echo "npm ci failed on attempt ${attempt}; retrying..." >&2
sleep 20
done
}
install_dependencies
ulimit -n 16384 || true
mapfile -t spec_args < <(printf "%s\n" "$TARGET_SPECS" | tr "," "\n" | sed "s/^[[:space:]]*//;s/[[:space:]]*$//;/^$/d")
if [[ "${#spec_args[@]}" -eq 0 && -z "${TARGET_GREP:-}" ]]; then
echo "Provide at least one spec path or grep pattern." >&2
exit 1
fi
for spec_path in "${spec_args[@]}"; do
if [[ "$spec_path" == /* || "$spec_path" == *".."* || "$spec_path" != tests/e2e/* ]]; then
echo "Targeted spec must stay under tests/e2e: $spec_path" >&2
exit 1
fi
if [[ ! -f "$spec_path" ]]; then
echo "Targeted spec does not exist: $spec_path" >&2
exit 1
fi
done
args=("${spec_args[@]}")
if [[ -n "${TARGET_GREP:-}" ]]; then
args+=(--grep "$TARGET_GREP")
fi
args+=(--project="$MATRIX_PROJECT")
npx playwright test "${args[@]}"
'
- name: Runner diagnostics after Playwright failure
if: failure() || cancelled()
continue-on-error: true
run: scripts/ci/runner-diagnostics.sh "after targeted Playwright ${{ matrix.project }}"
- name: Upload Playwright report
if: failure() || cancelled()
continue-on-error: true
uses: actions/upload-artifact@v4
with:
name: playwright-report-targeted-${{ matrix.project }}
path: |
output/playwright/${{ env.PLAYWRIGHT_ARTIFACT_NAMESPACE }}-*
output/playwright/${{ env.PLAYWRIGHT_ARTIFACT_NAMESPACE }}
if-no-files-found: ignore
retention-days: 1
e2e-pr:
if: >
always() &&
github.event_name != 'schedule' &&
needs.build-and-unit.result == 'success' &&
!(github.event_name == 'workflow_dispatch' && inputs.mode == 'targeted') &&
(
github.event_name != 'workflow_dispatch' ||
inputs.mode == 'full' ||
needs.e2e-targeted.result == 'success'
)
needs: [build-and-unit, e2e-targeted]
if: github.event_name != 'schedule'
needs: build-and-unit
name: E2E-pr-${{ matrix.suite }}-${{ matrix.project }}
runs-on: ${{ fromJSON(vars.FRONTEND_CI_E2E_RUNNER || '["self-hosted","Linux","X64","pleno","frontend","docker"]') }}
runs-on: [self-hosted, Linux, X64, pleno, frontend, docker]
timeout-minutes: 45
strategy:
fail-fast: false
max-parallel: ${{ fromJSON(vars.FRONTEND_CI_PR_E2E_MAX_PARALLEL || '2') }}
max-parallel: 4
matrix:
suite: [core, changed]
project: [chromium-desktop, chromium-mobile]
@@ -336,7 +116,6 @@ jobs:
PLAYWRIGHT_VIDEO_MODE: on-first-retry
steps:
- name: Repair self-hosted workspace permissions
if: ${{ contains(vars.FRONTEND_CI_E2E_RUNNER || 'self-hosted', 'self-hosted') }}
shell: bash
run: |
if [[ -d "$GITHUB_WORKSPACE" ]]; then
@@ -459,6 +238,7 @@ jobs:
--env PLAYWRIGHT_WORKERS="$PLAYWRIGHT_WORKERS" \
--env PLAYWRIGHT_VIDEO_MODE="$PLAYWRIGHT_VIDEO_MODE" \
--env PLAYWRIGHT_DEV_PORT="$playwright_dev_port" \
--env PLAYWRIGHT_WORKERS="${PLAYWRIGHT_WORKERS:-1}" \
--env MATRIX_SUITE="$MATRIX_SUITE" \
--env MATRIX_PROJECT="$MATRIX_PROJECT" \
--env DIFF_BASE_REF="$DIFF_BASE_REF" \
@@ -512,21 +292,15 @@ jobs:
if: >
always() &&
(github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' || github.ref_name == github.event.repository.default_branch) &&
!(github.event_name == 'workflow_dispatch' && inputs.mode == 'targeted') &&
needs.build-and-unit.result == 'success' &&
(github.event_name == 'schedule' || needs.e2e-pr.result == 'success') &&
(
github.event_name != 'workflow_dispatch' ||
inputs.mode == 'full' ||
needs.e2e-targeted.result == 'success'
)
needs: [build-and-unit, e2e-pr, e2e-targeted]
(github.event_name == 'schedule' || needs.e2e-pr.result == 'success')
needs: [build-and-unit, e2e-pr]
name: E2E-full-${{ matrix.browser_label }}-${{ matrix.device }}-${{ matrix.role }}
runs-on: ${{ fromJSON(vars.FRONTEND_CI_E2E_RUNNER || '["self-hosted","Linux","X64","pleno","frontend","docker"]') }}
runs-on: [self-hosted, Linux, X64, pleno, frontend, docker]
timeout-minutes: 60
strategy:
fail-fast: false
max-parallel: ${{ fromJSON(vars.FRONTEND_CI_FULL_E2E_MAX_PARALLEL || '1') }}
max-parallel: 2
matrix:
browser: [chromium, webkit, firefox]
device: [mobile, desktop, tablet]
@@ -548,7 +322,6 @@ jobs:
PLAYWRIGHT_VIDEO_MODE: off
steps:
- name: Repair self-hosted workspace permissions
if: ${{ contains(vars.FRONTEND_CI_E2E_RUNNER || 'self-hosted', 'self-hosted') }}
shell: bash
run: |
if [[ -d "$GITHUB_WORKSPACE" ]]; then
+4 -20
View File
@@ -29,8 +29,8 @@ export const sourceMappings = [
projects: chromiumProjects,
},
{
name: "limited-backoffice",
patterns: [/^src\/views\/backoffice\//u, /^src\/services\/limitedBackoffice\.js$/u],
name: "backoffice",
patterns: [/^src\/views\/backoffice\//u],
specs: ["tests/e2e/limited-backoffice.spec.ts"],
projects: chromiumProjects,
},
@@ -43,12 +43,6 @@ export const sourceMappings = [
specs: ["tests/e2e/superuser-roles-permissions.spec.ts"],
projects: chromiumProjects,
},
{
name: "superuser-users",
patterns: [/^src\/views\/dashboards\/superUserDashboard\/user\//u],
specs: ["tests/e2e/superuser-users.spec.ts"],
projects: chromiumProjects,
},
{
name: "superuser-dashboard",
patterns: [
@@ -96,8 +90,8 @@ export const sourceMappings = [
{
name: "pos",
patterns: [
/(?:^|[/_.-])pos(?:[/_.-]|$)/iu,
/(?:^|\/)(?:POS|Pos)[A-Z][^/]*\.(?:vue|js|ts)$/u,
/\/pos[/-]/iu,
/POS/iu,
/^src\/assets\/pos\.css$/u,
/^src\/components\/displays\/boxes\/ProductBox\.vue$/u,
/^src\/features\/customer\/customerProductRules\.js$/u,
@@ -120,22 +114,12 @@ export const sourceMappings = [
{
name: "admin-department-notifications",
patterns: [
/^src\/views\/dashboards\/departmentDashboard\/modules\/notifications\/DepartmentNotifications\.vue$/u,
/^src\/components\/displays\/department\/notifications\//u,
/^src\/components\/displays\/pagination\/models\/DepartmentPos\/NotificationsPhonePagination\.vue$/u,
],
specs: ["tests/e2e/admin-department-notifications.spec.ts"],
projects: chromiumProjects,
},
{
name: "admin-daily-report",
patterns: [
/^src\/views\/dashboards\/departmentDashboard\/modules\/daily-report\//u,
/^src\/components\/session\/token\/SessionUser\/Objects\/DepartmentDailyReports\.vue$/u,
],
specs: ["tests/e2e/admin-daily-report.spec.ts"],
projects: chromiumProjects,
},
{
name: "limited-backoffice",
patterns: [/^src\/views\/backoffice\/LimitedBackoffice/u],
@@ -126,8 +126,6 @@ const dropdownRoot = ref(null);
const dropdownContent = ref(null);
const isDropdownOpen = ref(false);
const dropdownInstanceId = Math.random().toString(36).substring(2, 15);
const dropdownPlacement = ref("bottom");
const isDropdownPlacementLocked = ref(false);
const shouldOpenDropdownUp = ref(false);
const dropdownMaxHeight = ref(null);
const isDesktopFlyoutLayout = ref(false);
@@ -142,7 +140,6 @@ const previewRequestsInFlight = new Set();
const generatedObjectUrls = new Set();
let previewStateGeneration = 0;
let contentResizeObserver = null;
let dropdownLayoutUpdateId = 0;
const desktopFlyoutMinViewportWidth = 1400;
const desktopFlyoutRootPanelWidthRem = 15;
const desktopFlyoutSubmenuWidthRem = 17;
@@ -233,8 +230,6 @@ const dropdownContentStyle = computed(() => {
});
const resetDropdownLayout = () => {
dropdownPlacement.value = "bottom";
isDropdownPlacementLocked.value = false;
shouldOpenDropdownUp.value = false;
dropdownMaxHeight.value = null;
isFixedPosition.value = false;
@@ -296,35 +291,7 @@ const getViewportInsets = () => {
};
};
const getDropdownPlacementSpaces = (triggerRect, viewportInsets = getViewportInsets()) => ({
bottom: Math.max(window.innerHeight - triggerRect.bottom - viewportInsets.bottom, 0),
top: Math.max(triggerRect.top - viewportInsets.top, 0),
});
const resolveDropdownPlacement = (triggerRect, menuHeight, viewportInsets = getViewportInsets()) => {
const spaces = getDropdownPlacementSpaces(triggerRect, viewportInsets);
return menuHeight > spaces.bottom && spaces.top > spaces.bottom ? "top" : "bottom";
};
const getDropdownAvailableHeight = (triggerRect, viewportInsets = getViewportInsets()) => {
const spaces = getDropdownPlacementSpaces(triggerRect, viewportInsets);
return dropdownPlacement.value === "top" ? spaces.top : spaces.bottom;
};
const lockDropdownPlacement = (triggerRect, menuHeight, viewportInsets = getViewportInsets()) => {
if (!isDropdownPlacementLocked.value) {
dropdownPlacement.value = resolveDropdownPlacement(triggerRect, menuHeight, viewportInsets);
isDropdownPlacementLocked.value = true;
}
shouldOpenDropdownUp.value = dropdownPlacement.value === "top";
};
const updateDropdownLayout = async () => {
const updateId = ++dropdownLayoutUpdateId;
if (!isDropdownOpen.value || !dropdownRoot.value || !dropdownContent.value) {
resetDropdownLayout();
return;
@@ -332,41 +299,35 @@ const updateDropdownLayout = async () => {
await nextTick();
if (updateId !== dropdownLayoutUpdateId || !isDropdownOpen.value || !dropdownRoot.value || !dropdownContent.value) {
return;
}
const triggerElement = dropdownRoot.value.querySelector(".dropdown-trigger");
const triggerRect = (triggerElement ?? dropdownRoot.value).getBoundingClientRect();
syncDesktopFlyoutState(triggerRect);
syncDesktopFlyoutPosition();
await nextTick();
if (updateId !== dropdownLayoutUpdateId || !isDropdownOpen.value || !dropdownContent.value) {
if (!dropdownContent.value) {
return;
}
const viewportInsets = getViewportInsets();
const viewportTop = viewportInsets.top;
const viewportBottom = window.innerHeight - viewportInsets.bottom;
const spaceBelow = Math.max(window.innerHeight - triggerRect.bottom - viewportInsets.bottom, 0);
const spaceAbove = Math.max(triggerRect.top - viewportInsets.top, 0);
const menuHeight = Math.ceil(dropdownContent.value.scrollHeight);
lockDropdownPlacement(triggerRect, menuHeight, viewportInsets);
const availableHeight = getDropdownAvailableHeight(triggerRect, viewportInsets);
const openUpward = menuHeight > spaceBelow && spaceAbove > spaceBelow;
const availableHeight = openUpward ? spaceAbove : spaceBelow;
const nextMaxHeight = availableHeight > 0 && menuHeight > availableHeight ? Math.floor(availableHeight) : null;
shouldOpenDropdownUp.value = openUpward;
dropdownMaxHeight.value = nextMaxHeight;
await nextTick();
if (updateId !== dropdownLayoutUpdateId || !isDropdownOpen.value || !dropdownContent.value) {
return;
}
syncDesktopFlyoutPosition();
await nextTick();
if (updateId !== dropdownLayoutUpdateId || !isDropdownOpen.value || !dropdownContent.value) {
if (!dropdownContent.value) {
return;
}
@@ -381,12 +342,6 @@ const updateDropdownLayout = async () => {
const boundedHeight = Math.floor(renderedMenuRect.height - overflowAbove - overflowBelow);
dropdownMaxHeight.value = boundedHeight > 0 ? boundedHeight : 1;
await nextTick();
if (updateId !== dropdownLayoutUpdateId || !isDropdownOpen.value) {
return;
}
syncDesktopFlyoutPosition();
};
@@ -1510,7 +1465,7 @@ onMounted(() => {
contentResizeObserver = new ResizeObserver(() => {
if (isDropdownOpen.value) {
void updateDropdownLayout();
syncDesktopFlyoutPosition();
}
});
@@ -2444,7 +2399,7 @@ watch(
() => {
if (isDropdownOpen.value) {
void nextTick(() => {
void updateDropdownLayout();
syncDesktopFlyoutPosition();
});
}
}
@@ -2552,6 +2507,7 @@ const syncDesktopFlyoutPosition = () => {
const triggerRect = triggerEl.getBoundingClientRect();
const contentHeight = dropdownContentEl.scrollHeight;
const viewportHeight = window.innerHeight;
const viewportWidth = window.innerWidth;
const contentRect = dropdownContentEl.getBoundingClientRect();
@@ -2581,13 +2537,12 @@ const syncDesktopFlyoutPosition = () => {
const viewportInsets = getViewportInsets();
const viewportTop = viewportInsets.top;
const effectiveContentHeight = dropdownMaxHeight.value
? Math.min(contentHeight, dropdownMaxHeight.value)
: contentHeight;
const top =
dropdownPlacement.value === "top"
? Math.max(viewportTop, triggerRect.top - effectiveContentHeight)
: triggerRect.bottom;
const viewportBottom = viewportHeight - viewportInsets.bottom;
let top = triggerRect.bottom;
if (top + contentHeight > viewportBottom) {
top = Math.max(viewportTop, triggerRect.top - contentHeight);
}
const nextFixedStyles = {
top: `${top}px`,
@@ -2603,8 +2558,18 @@ const syncDesktopFlyoutPosition = () => {
fixedPositionStyles.value = nextFixedStyles;
}
} else {
if (dropdownContentEl.style.top !== "") {
dropdownContentEl.style.top = "";
const contentRect = dropdownContentEl.getBoundingClientRect();
const contentBottom = contentRect.top + contentRect.height;
if (contentBottom > viewportHeight) {
const nextTop = `${triggerRect.top - contentRect.height}px`;
if (dropdownContentEl.style.top !== nextTop) {
dropdownContentEl.style.top = nextTop;
}
} else {
if (dropdownContentEl.style.top !== "") {
dropdownContentEl.style.top = "";
}
}
}
};
@@ -24,24 +24,8 @@ const onCustomerChange = () => {
isCustomerSelected.value = false;
}
const parseFixedPriceValue = (value) => {
if (value === null || value === undefined || value === '') {
return null;
}
const parsed = Number.parseInt(String(value), 10);
return Number.isFinite(parsed) ? parsed : null;
}
const formatNumber = (value) => Number.isInteger(value) ? String(value) : value.toFixed(2);
const parseValue = (discount) => {
const fixedPrice = parseFixedPriceValue(discount.fixed_price);
if (fixedPrice !== null) {
return `${formatNumber(fixedPrice)} Kr.`;
}
let tmp_value = parseFloat(discount.percentage).toFixed(2);
const parseValue = (value) => {
let tmp_value = parseFloat(value).toFixed(2);
// Add the percentage sign
return `${tmp_value}%`;
}
@@ -94,7 +78,7 @@ watch(customer_id, onCustomerChange, { immediate: true });
<!--<span class="icon is-small mr-1">
<i class="fas fa-percent" aria-hidden="true"></i>
</span> -->
<span>{{ parseValue(discount) }}</span>
<span>{{ parseValue(discount.percentage) }}</span>
</div>
</div>
</div>
@@ -102,4 +86,4 @@ watch(customer_id, onCustomerChange, { immediate: true });
<style scoped>
</style>
</style>
@@ -29,8 +29,6 @@ const discount_product = ref(null);
const discount_category = ref(null);
// The global discount (if any)
const discount_global = ref(null);
// The fixed product price (if any)
const fixed_product_price = ref(null);
// Show the discounts dropdown
const showDiscountsDropdown = ref(false);
@@ -51,19 +49,6 @@ const hasGlobalDiscount = () => {
return discount_global.value > 0;
}
const hasFixedProductPrice = () => {
return fixed_product_price.value !== null;
}
const parseFixedPriceValue = (value) => {
if (value === null || value === undefined || value === '') {
return null;
}
const parsed = Number.parseInt(String(value), 10);
return Number.isFinite(parsed) ? parsed : null;
}
// Set the product discount
const setProductDiscount = (percentage) => {
// Check if the percentage is a number
@@ -98,16 +83,6 @@ const setGlobalDiscount = (percentage) => {
discount_global.value = percentage;
}
const setFixedProductPrice = (fixedPrice) => {
const parsedFixedPrice = parseFixedPriceValue(fixedPrice);
if (parsedFixedPrice === null) {
fixed_product_price.value = null;
return;
}
fixed_product_price.value = parsedFixedPrice;
}
// Debugging function
const getDiscountDebug = () => {
@@ -126,15 +101,9 @@ const getDiscountDebug = () => {
// Parse the customer discounts
const parseCustomerDiscounts = () => {
discount_product.value = null;
discount_category.value = null;
discount_global.value = null;
fixed_product_price.value = null;
const customerDiscounts = Array.isArray(props.customer_discounts) ? props.customer_discounts : [];
const tmp_discount_product = customerDiscounts.find((discount) => discount.product_or_category_id == props.product.id && Number(discount.is_category) === 0)
const tmp_discount_category = customerDiscounts.find((discount) => discount.product_or_category_id == props.product.category && Number(discount.is_category) === 1);
const tmp_discount_global = customerDiscounts.find((discount) => discount.id === 999999 && Number(discount.is_category) === 1);
const tmp_discount_product = props.customer_discounts.find((discount) => discount.product_or_category_id === props.product.id && !discount.is_category)
const tmp_discount_category = props.customer_discounts.find((discount) => discount.product_or_category_id === props.product.category && discount.is_category);
const tmp_discount_global = props.customer_discounts.find((discount) => discount.id === 999999 && discount.is_category);
//console.log("Product discount: ", tmp_discount_product);
//console.log("Category discount: ", tmp_discount_category);
@@ -143,7 +112,6 @@ const parseCustomerDiscounts = () => {
// Set the product discount
if (tmp_discount_product) {
setProductDiscount(tmp_discount_product.percentage);
setFixedProductPrice(tmp_discount_product.fixed_price);
}
// Set the category discount
if (tmp_discount_category) {
@@ -157,10 +125,6 @@ const parseCustomerDiscounts = () => {
// Get the best discount for the customer
const getBestDiscount = () => {
if (hasFixedProductPrice()) {
highestEligibleDiscount.value = 0;
return 0;
}
// Set the best discount to 0
let tmp_best_discount = 0;
// Check if the product discount is higher than the current best discount
@@ -218,32 +182,13 @@ watch(() => props.customer_discounts, () => {
<span
aria-haspopup="true"
aria-controls="dropdown-menu"
v-if="hasFixedProductPrice()"
class="tag is-success is-light is-text text-can-not-select"
>{{ fixed_product_price }} Kr.</span>
<span
aria-haspopup="true"
aria-controls="dropdown-menu"
v-else-if="highestEligibleDiscount > 0"
v-if="highestEligibleDiscount > 0"
class="tag is-warning is-light is-text text-can-not-select"
> -{{ highestEligibleDiscount }}%</span>
</div>
<div class="dropdown-menu" id="dropdown-menu" role="menu">
<div class="dropdown-content py-0">
<div class="list has-overflow-ellipsis" style="width: 340px">
<template v-if="hasFixedProductPrice()">
<a class="list-item">
<div class="list-item-content">
<div class="list-item-title">Fast pris</div>
</div>
<div class="list-item-controls list-item-controls-force-visible">
<div class="tags has-addons">
<span class="tag is-success is-light">{{ fixed_product_price }} Kr.</span>
</div>
</div>
</a>
</template>
<template v-else>
<!-- Best discount -->
<a class="list-item">
<div class="list-item-content">
@@ -294,7 +239,6 @@ watch(() => props.customer_discounts, () => {
</div>
</div>
</a>
</template>
</div>
</div>
</div>
@@ -310,4 +254,4 @@ watch(() => props.customer_discounts, () => {
.text-can-not-select {
user-select: none;
}
</style>
</style>
@@ -38,8 +38,7 @@ if (router.currentRoute.value.params.departmentId) {
<TableLabeledPagination :label="SessionUser.objects.department_notification_sms.meta.title">
<template #buttons="{ loadList }">
<button
class="button is-primary is-small"
data-testid="department-notification-sms-add-button"
class="button is-info is-small"
@click="SessionUser.objects.department_notification_sms.showCreateObjectForm(() => loadList(), {department: parseInt(router.currentRoute.value.params.departmentId)})"
>
<span class="icon is-small">
@@ -7,7 +7,7 @@ import {
productCategoryAllowed,
isProductRestricted,
setProductsCategory,
getUserProductPrice,
getUserProductDiscount,
showFakeCreateOrderItem,
department_id,
user_discounts,
@@ -555,9 +555,10 @@ const addPreviousOrderToCurrent = async (previousOrder) => {
continue;
}
const previousOrderProduct = getPreviousOrderProduct(orderItem) || { id: productId, price: getPreviousOrderProductPrice(orderItem) };
const previousOrderProduct = getPreviousOrderProduct(orderItem);
const discount = getUserProductDiscount(previousOrderProduct || {});
const basePrice = getPreviousOrderProductPrice(orderItem);
const discountedPrice = String(getUserProductPrice({ ...previousOrderProduct, price: basePrice }));
const discountedPrice = (basePrice - (basePrice * (discount / 100))).toFixed(0);
showFakeCreateOrderItem(productId, quantity, discountedPrice);
await createOrderItem(orderId, productId, quantity);
@@ -591,7 +592,9 @@ const getRecommendedProductPrice = (productId) => {
return '0';
}
return String(getUserProductPrice(product));
const discount = getUserProductDiscount(product);
const price = Number(product.price ?? 0);
return (price - (price * (discount / 100))).toFixed(0);
};
const isRecommendedProductCategoryAllowed = (productId) => {
@@ -1,25 +1,17 @@
<script setup>
const props = defineProps(['invoice_id'])
import { authenticatedRequest } from "@/components/session/authenticatedRequest.vue";
import LoadButtonWhileAwait from "@/components/request/LoadButtonWhileAwait.vue";
import { handleEconomicError } from "@/components/request/HandleEconomicError.vue";
import { computed } from "vue";
const props = defineProps(["invoice_id"]);
const hasInvoice = computed(() => {
return props.invoice_id !== null && props.invoice_id !== undefined && String(props.invoice_id).trim() !== "";
});
import { ref } from "vue";
const getOrderPDF = async () => {
if (!hasInvoice.value) {
return;
}
await authenticatedRequest("/invoices/pdf", "GET", {
id: props.invoice_id,
}).then((response) => {
await authenticatedRequest('/invoices/pdf?id=' + props.invoice_id,
'GET',{
}) .then((response) => {
// Open the PDF in a new tab
window.open(response.data.data.url, "_blank");
window.open(response.data.data.url, '_blank');
}).catch((error) => {
handleEconomicError(error);
});
@@ -27,17 +19,9 @@ const getOrderPDF = async () => {
</script>
<template>
<LoadButtonWhileAwait
class="is-dark"
:loadFunction="getOrderPDF"
:disabled="!hasInvoice"
actionKey="economic-invoice-pdf-download"
icon="fas fa-file-pdf"
>
Hent faktura PDF
</LoadButtonWhileAwait>
<LoadButtonWhileAwait class="is-dark" :loadFunction="getOrderPDF" icon="fas fa-file-pdf"> Hent faktura PDF </LoadButtonWhileAwait>
</template>
<style scoped>
</style>
</style>
@@ -164,21 +164,6 @@ const t = (key) => i18n.global.t(key);
}
);
},
setProductTarget: async ({ department_id, product_id, target_percentage }) => {
const normalizedTarget = target_percentage === null || target_percentage === undefined || target_percentage === ""
? null
: Number(target_percentage);
return authenticatedRequest(
"/departments/daily-reports/product-targets",
"PUT",
{
department_id: parseInt(department_id, 10),
product_id: parseInt(product_id, 10),
target_percentage: normalizedTarget,
}
);
},
createComplaint: async ({
department_id,
customer_number = null,
@@ -32,23 +32,6 @@ const normalizeDateTimeLocalValue = (value) => {
return `${datePart}T${timePart.slice(0, 5)}`;
};
const sanitizeQueryParams = (params = {}) => {
if (!params || typeof params !== 'object') {
return {};
}
return Object.fromEntries(
Object.entries(params).filter(([, value]) => value !== null && value !== undefined)
);
};
const buildQueryString = (params = {}) => {
const queryParams = sanitizeQueryParams(params);
const queryString = new URLSearchParams(queryParams).toString();
return queryString ? `?${queryString}` : '';
};
/**
* The Global Objects object, which contains global functions for objects.
*/
@@ -448,15 +431,20 @@ export const ObjectsGlobal = {
* @returns {Promise} The promise
*/
object: async (endpoint, id, optionsObject = {}) => {
const requestParams = typeof id === 'object' && id !== null
? sanitizeQueryParams(id)
: {id};
const cacheKey = JSON.stringify({endpoint, id: requestParams, optionsObject});
const cacheKey = JSON.stringify({endpoint, id, optionsObject});
if (ObjectsGlobal.cache.has(cacheKey)) {
return ObjectsGlobal.cache.get(cacheKey);
}
const requestEndpoint = `${endpoint}${buildQueryString(requestParams)}`;
let requestEndpoint = endpoint;
if (typeof id === 'object') {
// If the id is an object, we need to convert it to a query string
const params = new URLSearchParams(id).toString();
requestEndpoint = `${endpoint}?${params}`;
} else {
// If the id is a number, we can just append it to the endpoint
requestEndpoint = `${endpoint}?id=${id}`;
}
let options = ObjectsGlobal.requestOptions.applyOptions(optionsObject);
let promise;
if (options.authenticated) {
@@ -511,24 +499,23 @@ export const ObjectsGlobal = {
* @returns {Promise} The promise
*/
objects: async (endpoint, data = {}) => {
const requestData = sanitizeQueryParams(data);
if (requestData.filters && typeof requestData.filters === 'object') {
requestData.filters = Object.entries(requestData.filters).flatMap(([key, value]) => {
const cacheKey = JSON.stringify({endpoint, data});
if (ObjectsGlobal.cache.has(cacheKey)) {
return ObjectsGlobal.cache.get(cacheKey);
}
if (data.filters && typeof data.filters === 'object') {
data.filters = Object.entries(data.filters).flatMap(([key, value]) => {
if (Array.isArray(value)) {
return value.map(v => `${key}:${v}`);
}
return `${key}:${value}`;
}).join(',');
}
const cacheKey = JSON.stringify({endpoint, data: requestData});
if (ObjectsGlobal.cache.has(cacheKey)) {
return ObjectsGlobal.cache.get(cacheKey);
}
const promise = authenticatedRequest(
endpoint,
"GET",
requestData
data
).then((response) => {
return response.data.data;
}).catch((error) => {
@@ -8,17 +8,6 @@ import i18n from '@/i18n';
const t = (key) => i18n.global.t(key);
const normalizeProductQueryOptions = (options = {}) => {
const queryOptions = { ...options };
if (!Object.prototype.hasOwnProperty.call(queryOptions, "final_price")) {
queryOptions.final_price = false;
}
return Object.fromEntries(
Object.entries(queryOptions).filter(([, value]) => value !== null && value !== undefined)
);
};
/**
* Local products cache
* @type {ref<null>}
@@ -280,19 +269,19 @@ export const Products = {
},
},
get: {
all: async (options = {}) => {
return ObjectsGlobal.get.objects(Products.meta.endpoint, normalizeProductQueryOptions(options));
all: async (options = {department_id: null, customer_id: null, category_id: null, final_price: false}) => {
return ObjectsGlobal.get.objects(Products.meta.endpoint, {...options});
},
single: async (id, options = {}) => {
return ObjectsGlobal.get.object(Products.meta.endpoint, {id: id, ...normalizeProductQueryOptions(options)});
single: async (id, options = {department_id: null, customer_id: null, category_id: null, final_price: false}) => {
return ObjectsGlobal.get.object(Products.meta.endpoint, {id: id, ...options});
},
category: async (category_id, department_id, customer_id = null, final_price = false) => {
return ObjectsGlobal.get.object(Products.meta.endpoint, normalizeProductQueryOptions({
return ObjectsGlobal.get.object(Products.meta.endpoint, {
category: category_id,
department_id: department_id,
...(customer_id !== null ? {customer_id: customer_id} : {}),
...{final_price: final_price}
}));
});
},
},
delete: async (id) => {
@@ -335,4 +324,4 @@ export const Products = {
);
},
};
</script>
</script>
+3 -50
View File
@@ -1802,30 +1802,13 @@ export const getUserDiscounts = async () => {
});
};
const ensureUserDiscountsLoaded = () => {
/** Get user product discount */
export const getUserProductDiscount = (product, allowCategory = null, onlyCategory = null) => {
// Check if the user discounts are loaded
if (!has_user_discounts_loaded.value) {
has_user_discounts_loaded.value = true;
getUserDiscounts().then(() => {});
}
};
const isDirectCustomerProductDiscount = (discount, productId) => {
return discount?.product_or_category_id == productId && Number(discount?.is_category) === 0;
};
const parseFixedPriceValue = (value) => {
if (value === null || value === undefined || value === '') {
return null;
}
const parsed = Number.parseInt(String(value), 10);
return Number.isFinite(parsed) ? parsed : null;
};
/** Get user product discount */
export const getUserProductDiscount = (product, allowCategory = null, onlyCategory = null) => {
// Check if the user discounts are loaded
ensureUserDiscountsLoaded();
// Get the product's id
const productId = product.id;
@@ -1923,36 +1906,6 @@ export const getUserProductDiscount = (product, allowCategory = null, onlyCatego
return appliedDiscount;
};
export const getUserProductFixedPrice = (product) => {
ensureUserDiscountsLoaded();
const productId = product?.id;
if (productId === null || productId === undefined) {
return null;
}
const fixedPriceDiscount = (Array.isArray(user_discounts.value) ? user_discounts.value : []).find((discount) => (
isDirectCustomerProductDiscount(discount, productId) && parseFixedPriceValue(discount.fixed_price) !== null
));
return fixedPriceDiscount ? parseFixedPriceValue(fixedPriceDiscount.fixed_price) : null;
};
export const getUserProductPrice = (product) => {
const fixedPrice = getUserProductFixedPrice(product);
if (fixedPrice !== null) {
return fixedPrice;
}
const price = Number(product?.price ?? 0);
const discount = Number(getUserProductDiscount(product) || 0);
if (!Number.isFinite(price)) {
return 0;
}
return Number((price - (price * (discount / 100))).toFixed(0));
};
export const showFakeCreateOrderItem = (product, quantity, price) => {
order_items.value.push({
id: Math.floor(Math.random() * 1000),
@@ -189,7 +189,7 @@ const descriptionKeyOverrides: Partial<Record<EntityType, string[]>> = {
xlvask_customers: ['email', 'city', 'address', 'vatnumber'],
motorapi_lookups: ['endpoint', 'license_plate', 'result'],
fxratesapi_conversion_rates: ['base', 'target', 'endpoint', 'result'],
customer_discounts: ['customer_number', 'fixed_price', 'percentage'],
customer_discounts: ['customer_number', 'percentage'],
module_config: ['description', 'value'],
department_goals: ['criteria.type', 'criteria.progress_alert_frequency', 'criteria.progress_alert_destination']
};
@@ -251,7 +251,6 @@ const keyFieldOverrides: Partial<Record<EntityType, FieldSelector[]>> = {
),
customer_discounts: fieldList(
field('Discount', 'discount', 'percentage'),
field('Fixed price', 'fixed_price'),
field('Target', 'product_or_category_id', 'object_id'),
field('Category', 'is_category'),
field('Customer #', 'customer_number'),
-33
View File
@@ -1517,14 +1517,6 @@
"subtitle_suffix": "@:{'words.generated.salg'} @:{'words.generated.af'} produktet",
"title": "Produktsalg"
},
"product_targets": {
"cancel_aria": "Annuller mål",
"edit_aria": "Rediger målprocent",
"input_label": "Målprocent",
"save_aria": "Gem mål",
"save_error": "Målet kunne ikke gemmes.",
"validation_range": "Målprocenten skal være mellem 0 og 100."
},
"reports": {
"bookings": {
"completed_count": "@.capitalize:{'words.generated.antal'} @:{'words.generated.fuldførte'}",
@@ -5772,31 +5764,6 @@
"transaction_history": "@:{'templates.generated.compat.superuser.nav.orders'}"
},
"other": "@:{'templates.generated.compat.global.other'}",
"overview": {
"active_vehicles": "Aktive køretøjer",
"attributes": "Attributter",
"connected": "Forbundet",
"customer_management": "Kundestyring",
"customer_number_required": "Et kundenummer er påkrævet før kundeindstillinger kan administreres.",
"customer_rules": "Kunderegler",
"effective_access": "Effektiv adgang",
"loaded": "Indlæst",
"load_failed": "Brugerdata kunne ikke indlæses",
"loading_user": "Indlæser bruger",
"management_hub": "Administrationshub",
"missing": "Mangler",
"more_permissions": "+{count} flere tilladelser",
"no_subscription_transactions": "Der er ikke registreret vaskeabonnementstransaktioner for kunden.",
"not_invoiced": "Ikke faktureret",
"open_draft": "Åben kladde",
"open_vehicles": "Åbn køretøjer",
"price_overrides": "Prisoverstyringer",
"pricing": "Priser",
"subscription_invoicing": "Abonnementsfakturering",
"subtitle": "Overblik over kundedata, adgang, priser, køretøjer og abonnementsfakturering.",
"vehicles_load_failed": "Køretøjer kunne ikke indlæses.",
"workspace_shortcuts": "Arbejdsgange"
},
"permissions": "@.capitalize:{'words.generated.tilladelser'}",
"user_data": "@.capitalize:{'words.generated.brugerdata'}",
"user_id": "@.capitalize:{'words.generated.bruger'} @.upper:{'words.generated.id'}",
-55
View File
@@ -1628,14 +1628,6 @@
"subtitle_suffix": "Produktverk?@:{'words.generated.ufe'}",
"title": "@:{'templates.generated.compat.admin.daily_report.product_sales.subtitle_suffix'}"
},
"product_targets": {
"cancel_aria": "Ziel abbrechen",
"edit_aria": "Zielprozentsatz bearbeiten",
"input_label": "Zielprozentsatz",
"save_aria": "Ziel speichern",
"save_error": "Das Ziel konnte nicht gespeichert werden.",
"validation_range": "Der Zielprozentsatz muss zwischen 0 und 100 liegen."
},
"reports": {
"bookings": {
"completed_count": "@:{'words.generated.abgeschlossene'} @:{'words.generated.anzahl'}",
@@ -3595,13 +3587,6 @@
"opening_hours": {
"closed": "@:{'templates.generated.compat.global.closed'}"
},
"pricing": {
"custom_pricing_disabled": "Fallback aktiviert",
"custom_pricing_enabled": "Nur eigene Preise",
"custom_pricing_missing_price": "Fehlende Abteilungspreise werden zu 999999.",
"custom_pricing_only": "Keine Fallback-Preise",
"effective_department_price": "Effektiver Abteilungspreis"
},
"search_placeholder": "@.capitalize:{'words.generated.nach'} @:{'words.generated.abteilungsname'} @:{'words.generated.suchen'}",
"select_department": "@:{'templates.generated.compat.nav.select_department'}",
"subtitle": "@:{'words.generated.abteilungen'} @:{'words.generated.verwalten'}",
@@ -4441,7 +4426,6 @@
"departments": {
"columns": {
"archived": "Archiviert",
"custom_pricing_only": "@:{'templates.generated.compat.departments.pricing.custom_pricing_only'}",
"dimension": "Abmessung",
"economic_department": "@:{'templates.generated.compat.objects.economic_departments.single'}",
"latitude": "@:{'templates.generated.compat.departments.form.latitude'}",
@@ -5883,31 +5867,6 @@
"transaction_history": "@:{'templates.generated.compat.superuser.nav.orders'}"
},
"other": "@.capitalize:{'words.generated.andere'}",
"overview": {
"active_vehicles": "Aktive Fahrzeuge",
"attributes": "Attribute",
"connected": "Verbunden",
"customer_management": "Kundenverwaltung",
"customer_number_required": "Eine Kundennummer ist erforderlich, bevor Kundeneinstellungen verwaltet werden können.",
"customer_rules": "Kundenregeln",
"effective_access": "Effektiver Zugriff",
"loaded": "Geladen",
"load_failed": "Benutzerdaten konnten nicht geladen werden",
"loading_user": "Benutzer wird geladen",
"management_hub": "Verwaltung",
"missing": "Fehlt",
"more_permissions": "+{count} weitere Berechtigungen",
"no_subscription_transactions": "Für diesen Kunden sind keine Waschabonnement-Transaktionen registriert.",
"not_invoiced": "Nicht fakturiert",
"open_draft": "Offener Entwurf",
"open_vehicles": "Fahrzeuge öffnen",
"price_overrides": "Preisüberschreibungen",
"pricing": "Preise",
"subscription_invoicing": "Abonnementabrechnung",
"subtitle": "Überblick über Kundendaten, Zugriff, Preise, Fahrzeuge und Abonnementabrechnung.",
"vehicles_load_failed": "Fahrzeuge konnten nicht geladen werden.",
"workspace_shortcuts": "Arbeitsbereich"
},
"permissions": "Tilladelser",
"user_data": "Brugerdata",
"user_id": "@:{'words.generated.benutzer'}-@.upper:{'words.generated.id'}",
@@ -6114,20 +6073,6 @@
},
"vehicles": {
"add": "@:{'words.generated.fahrzeug'} @:{'words.generated.hinzuf'}?@:{'words.generated.gen'}",
"add_modal": {
"customer_label": "Kunde",
"customer_placeholder": "Nach Kundenname oder Kundennummer suchen",
"error": "Fahrzeug konnte nicht hinzugefuegt werden.",
"no_customer_results": "Keine Kunden gefunden",
"reference_placeholder": "Optionale Referenz",
"registration_placeholder": "Kennzeichen",
"selected_customer": "Ausgewaehlter Kunde",
"submit": "Fahrzeug hinzufuegen",
"title": "Fahrzeug hinzufuegen",
"type_load_error": "Fahrzeugtypen konnten nicht geladen werden.",
"type_placeholder": "Fahrzeugtyp auswaehlen",
"validation_error": "Kunde, Kennzeichen und Fahrzeugtyp auswaehlen."
},
"brand": "@:{'templates.generated.compat.admin.pos.make'}",
"color": "Farbe",
"delete_vehicle": "@:{'templates.generated.compat.vehicles.delete'}",
-33
View File
@@ -1349,14 +1349,6 @@
"subtitle_suffix": "@:{'words.generated.product'} @:{'words.generated.sales'}",
"title": "@.capitalize:{'words.generated.product'} @.capitalize:{'words.generated.sales'}"
},
"product_targets": {
"cancel_aria": "Cancel target",
"edit_aria": "Edit target percentage",
"input_label": "Target percentage",
"save_aria": "Save target",
"save_error": "The target could not be saved.",
"validation_range": "The target percentage must be between 0 and 100."
},
"reports": {
"bookings": {
"completed_count": "@.capitalize:{'words.generated.completed'} @:{'words.generated.count'}",
@@ -5604,31 +5596,6 @@
"transaction_history": "@.capitalize:{'words.generated.transaction'} @:{'words.generated.history'}"
},
"other": "@:{'templates.generated.compat.global.other'}",
"overview": {
"active_vehicles": "Active vehicles",
"attributes": "Attributes",
"connected": "Connected",
"customer_management": "Customer management",
"customer_number_required": "A customer number is required before customer settings can be managed.",
"customer_rules": "Customer rules",
"effective_access": "Effective access",
"loaded": "Loaded",
"load_failed": "User data could not be loaded",
"loading_user": "Loading user",
"management_hub": "Management hub",
"missing": "Missing",
"more_permissions": "+{count} more permissions",
"no_subscription_transactions": "No wash subscription transactions are registered for this customer.",
"not_invoiced": "Not invoiced",
"open_draft": "Open draft",
"open_vehicles": "Open vehicles",
"price_overrides": "Price overrides",
"pricing": "Pricing",
"subscription_invoicing": "Subscription invoicing",
"subtitle": "Overview of customer data, access, pricing, vehicles, and subscription invoicing.",
"vehicles_load_failed": "Vehicles could not be loaded.",
"workspace_shortcuts": "Workspace shortcuts"
},
"permissions": "@.capitalize:{'words.generated.permissions'}",
"user_data": "@.capitalize:{'words.generated.user'} @:{'words.generated.data'}",
"user_id": "@.capitalize:{'words.generated.user'} @.upper:{'words.generated.id'}",
+9 -42
View File
@@ -126,14 +126,6 @@
"subtitle_suffix": "@:{'templates.generated.compat.admin.daily_report.product_sales.subtitle_suffix'}",
"title": "@:{'templates.generated.compat.admin.daily_report.product_sales.title'}"
},
"product_targets": {
"cancel_aria": "@:{'templates.generated.compat.admin.daily_report.product_targets.cancel_aria'}",
"edit_aria": "@:{'templates.generated.compat.admin.daily_report.product_targets.edit_aria'}",
"input_label": "@:{'templates.generated.compat.admin.daily_report.product_targets.input_label'}",
"save_aria": "@:{'templates.generated.compat.admin.daily_report.product_targets.save_aria'}",
"save_error": "@:{'templates.generated.compat.admin.daily_report.product_targets.save_error'}",
"validation_range": "@:{'templates.generated.compat.admin.daily_report.product_targets.validation_range'}"
},
"reports": {
"avg_revenue": {
"label": "@:{'templates.generated.compat.department_reports.avg_revenue_per_wash'}",
@@ -4590,8 +4582,8 @@
"overview": "Overview",
"modules": "Modules",
"branding": "Profile & Branding",
"gateways": "@.capitalize:{'words.generated.gateways'}",
"stripe": "@:{'words.generated.stripe'}",
"gateways": "Gateways",
"stripe": "Stripe",
"pricing": "Pricing",
"categories": "Categories"
},
@@ -4634,7 +4626,7 @@
"department_id": "Department ID",
"economic_department_id": "Economic department",
"branding": "Branding",
"created_at": "@:common.created",
"created_at": "Created",
"updated_at": "Updated"
},
"hardware": {
@@ -4650,12 +4642,12 @@
"quick_links": {
"title": "Department tools",
"subtitle": "Open the focused setup areas for this department",
"modules": "@:superuser_dashboard.department_navigation.modules",
"branding": "@:superuser_dashboard.department_overview.profile.branding",
"gateways": "@:superuser_dashboard.department_navigation.gateways",
"stripe": "@:superuser_dashboard.department_navigation.stripe",
"pricing": "@:superuser_dashboard.department_navigation.pricing",
"categories": "@:superuser_dashboard.department_navigation.categories"
"modules": "Modules",
"branding": "Branding",
"gateways": "Gateways",
"stripe": "Stripe",
"pricing": "Pricing",
"categories": "Categories"
},
"errors": {
"invalid_department": "A valid department is required",
@@ -5640,31 +5632,6 @@
"transaction_history": "@:{'templates.generated.compat.user_admin.orders.transaction_history'}"
},
"other": "@:{'templates.generated.compat.user_admin.other'}",
"overview": {
"active_vehicles": "@:{'templates.generated.compat.user_admin.overview.active_vehicles'}",
"attributes": "@:{'templates.generated.compat.user_admin.overview.attributes'}",
"connected": "@:{'templates.generated.compat.user_admin.overview.connected'}",
"customer_management": "@:{'templates.generated.compat.user_admin.overview.customer_management'}",
"customer_number_required": "@:{'templates.generated.compat.user_admin.overview.customer_number_required'}",
"customer_rules": "@:{'templates.generated.compat.user_admin.overview.customer_rules'}",
"effective_access": "@:{'templates.generated.compat.user_admin.overview.effective_access'}",
"loaded": "@:{'templates.generated.compat.user_admin.overview.loaded'}",
"load_failed": "@:{'templates.generated.compat.user_admin.overview.load_failed'}",
"loading_user": "@:{'templates.generated.compat.user_admin.overview.loading_user'}",
"management_hub": "@:{'templates.generated.compat.user_admin.overview.management_hub'}",
"missing": "@:{'templates.generated.compat.user_admin.overview.missing'}",
"more_permissions": "@:{'templates.generated.compat.user_admin.overview.more_permissions'}",
"no_subscription_transactions": "@:{'templates.generated.compat.user_admin.overview.no_subscription_transactions'}",
"not_invoiced": "@:{'templates.generated.compat.user_admin.overview.not_invoiced'}",
"open_draft": "@:{'templates.generated.compat.user_admin.overview.open_draft'}",
"open_vehicles": "@:{'templates.generated.compat.user_admin.overview.open_vehicles'}",
"price_overrides": "@:{'templates.generated.compat.user_admin.overview.price_overrides'}",
"pricing": "@:{'templates.generated.compat.user_admin.overview.pricing'}",
"subscription_invoicing": "@:{'templates.generated.compat.user_admin.overview.subscription_invoicing'}",
"subtitle": "@:{'templates.generated.compat.user_admin.overview.subtitle'}",
"vehicles_load_failed": "@:{'templates.generated.compat.user_admin.overview.vehicles_load_failed'}",
"workspace_shortcuts": "@:{'templates.generated.compat.user_admin.overview.workspace_shortcuts'}"
},
"permissions": "@:{'templates.generated.compat.user_admin.permissions'}",
"subtitle": "@:user_admin.user_data",
"title": "@:{'templates.generated.compat.common.user'}",
-55
View File
@@ -1631,14 +1631,6 @@
"subtitle_suffix": "@:{'words.generated.produktsalg'}",
"title": "@.capitalize:{'words.generated.produktsalg'}"
},
"product_targets": {
"cancel_aria": "Avbryt mål",
"edit_aria": "Rediger målprosent",
"input_label": "Målprosent",
"save_aria": "Lagre mål",
"save_error": "Målet kunne ikke lagres.",
"validation_range": "Målprosenten må være mellom 0 og 100."
},
"reports": {
"bookings": {
"completed_count": "@.capitalize:{'words.generated.fullført'} @:{'words.generated.telling'}",
@@ -3598,13 +3590,6 @@
"opening_hours": {
"closed": "Stengt"
},
"pricing": {
"custom_pricing_disabled": "Fallback aktiv",
"custom_pricing_enabled": "Kun egendefinerte priser",
"custom_pricing_missing_price": "Manglende avdelingspriser blir 999999.",
"custom_pricing_only": "Ingen fallback-priser",
"effective_department_price": "Effektiv avdelingspris"
},
"search_placeholder": "@.capitalize:{'words.generated.søk'} @:{'words.generated.etter'} @:{'words.generated.avdelingsnavn'}",
"select_department": "@.capitalize:{'words.generated.velg'} @:{'words.replication.host_definite_suffix'} @:{'words.generated.avdeling'}",
"subtitle": "@.capitalize:{'words.generated.administrer'} @:{'words.generated.avdelinger'}",
@@ -4444,7 +4429,6 @@
"departments": {
"columns": {
"archived": "Arkivert",
"custom_pricing_only": "@:{'templates.generated.compat.departments.pricing.custom_pricing_only'}",
"dimension": "Dimensjon",
"economic_department": "@.upper:{'words.generated.e'}-@:{'words.generated.økonomisk'} @:{'words.generated.avdeling'}",
"latitude": "@:{'templates.generated.compat.departments.form.latitude'}",
@@ -5886,31 +5870,6 @@
"transaction_history": "@:{'templates.generated.compat.superuser.nav.orders'}"
},
"other": "@:{'templates.generated.compat.global.other'}",
"overview": {
"active_vehicles": "Aktive kjøretøy",
"attributes": "Attributter",
"connected": "Tilkoblet",
"customer_management": "Kundestyring",
"customer_number_required": "Et kundenummer kreves før kundeinnstillinger kan administreres.",
"customer_rules": "Kunderegler",
"effective_access": "Effektiv tilgang",
"loaded": "Lastet",
"load_failed": "Brukerdata kunne ikke lastes",
"loading_user": "Laster bruker",
"management_hub": "Administrasjon",
"missing": "Mangler",
"more_permissions": "+{count} flere tillatelser",
"no_subscription_transactions": "Ingen vaskeabonnementstransaksjoner er registrert for kunden.",
"not_invoiced": "Ikke fakturert",
"open_draft": "Åpent utkast",
"open_vehicles": "Åpne kjøretøy",
"price_overrides": "Prisoverstyringer",
"pricing": "Priser",
"subscription_invoicing": "Abonnementsfakturering",
"subtitle": "Oversikt over kundedata, tilgang, priser, kjøretøy og abonnementsfakturering.",
"vehicles_load_failed": "Kjøretøy kunne ikke lastes.",
"workspace_shortcuts": "Arbeidsområde"
},
"permissions": "@.capitalize:{'words.generated.tillatelser'}",
"user_data": "@.capitalize:{'words.generated.brukerdata'}",
"user_id": "@.capitalize:{'words.generated.bruker'}-@.upper:{'words.generated.id'}",
@@ -6117,20 +6076,6 @@
},
"vehicles": {
"add": "@:{'words.generated.lagg'} @:{'words.generated.till'} @:{'words.generated.fordon'}",
"add_modal": {
"customer_label": "Kunde",
"customer_placeholder": "Søk etter kundenavn eller kundenummer",
"error": "Kunne ikke legge til kjøretøy.",
"no_customer_results": "Ingen kunder funnet",
"reference_placeholder": "Valgfri referanse",
"registration_placeholder": "Registreringsnummer",
"selected_customer": "Valgt kunde",
"submit": "Legg til kjøretøy",
"title": "Legg til kjøretøy",
"type_load_error": "Kunne ikke laste kjøretøytyper.",
"type_placeholder": "Velg kjøretøytype",
"validation_error": "Velg kunde, registreringsnummer og kjøretøytype."
},
"brand": "Märke",
"color": "Färg",
"delete_vehicle": "@:{'templates.generated.compat.vehicles.delete'}",
-55
View File
@@ -1681,14 +1681,6 @@
"subtitle_suffix": "@:{'words.generated.produktforsaljning'}",
"title": "@.capitalize:{'words.generated.produktforsaljning'}"
},
"product_targets": {
"cancel_aria": "Avbryt mål",
"edit_aria": "Redigera målprocent",
"input_label": "Målprocent",
"save_aria": "Spara mål",
"save_error": "Målet kunde inte sparas.",
"validation_range": "Målprocenten måste vara mellan 0 och 100."
},
"reports": {
"bookings": {
"completed_count": "@.capitalize:{'words.generated.antal'} @:{'words.generated.slutforda'}",
@@ -3648,13 +3640,6 @@
"opening_hours": {
"closed": "Stengt"
},
"pricing": {
"custom_pricing_disabled": "Fallback aktiv",
"custom_pricing_enabled": "Endast egna priser",
"custom_pricing_missing_price": "Saknade avdelningspriser blir 999999.",
"custom_pricing_only": "Inga fallback-priser",
"effective_department_price": "Effektivt avdelningspris"
},
"search_placeholder": "@:{'words.generated.sok'} @:{'words.generated.efter'} @:{'words.generated.avdelningsnamn'}",
"select_department": "@:{'words.generated.velg'} @:{'words.replication.host_definite_suffix'} @:{'words.generated.avdeling'}",
"subtitle": "@:{'words.generated.administrer'} @:{'words.generated.avdelinger'}",
@@ -4494,7 +4479,6 @@
"departments": {
"columns": {
"archived": "Arkiverad",
"custom_pricing_only": "@:{'templates.generated.compat.departments.pricing.custom_pricing_only'}",
"dimension": "Dimension",
"economic_department": "@:{'templates.generated.compat.objects.economic_departments.single'}",
"latitude": "Latitude",
@@ -5936,31 +5920,6 @@
"transaction_history": "@:{'templates.generated.compat.superuser.nav.orders'}"
},
"other": "Andet",
"overview": {
"active_vehicles": "Aktiva fordon",
"attributes": "Attribut",
"connected": "Ansluten",
"customer_management": "Kundhantering",
"customer_number_required": "Ett kundnummer krävs innan kundinställningar kan hanteras.",
"customer_rules": "Kundregler",
"effective_access": "Effektiv åtkomst",
"loaded": "Inläst",
"load_failed": "Användardata kunde inte läsas in",
"loading_user": "Läser in användare",
"management_hub": "Administration",
"missing": "Saknas",
"more_permissions": "+{count} fler behörigheter",
"no_subscription_transactions": "Inga tvättabonnemangstransaktioner är registrerade för kunden.",
"not_invoiced": "Ej fakturerat",
"open_draft": "Öppet utkast",
"open_vehicles": "Öppna fordon",
"price_overrides": "Prisöverskrivningar",
"pricing": "Priser",
"subscription_invoicing": "Abonnemangsfakturering",
"subtitle": "Översikt över kunddata, åtkomst, priser, fordon och abonnemangsfakturering.",
"vehicles_load_failed": "Fordon kunde inte läsas in.",
"workspace_shortcuts": "Arbetsyta"
},
"permissions": "Tilladelser",
"user_data": "Brugerdata",
"user_id": "Användar-@.upper:{'words.generated.id'}",
@@ -6167,20 +6126,6 @@
},
"vehicles": {
"add": "@:{'words.generated.lagg'} @:{'words.generated.till'} @:{'words.generated.fordon'}",
"add_modal": {
"customer_label": "Kund",
"customer_placeholder": "Sök efter kundnamn eller kundnummer",
"error": "Det gick inte att lägga till fordon.",
"no_customer_results": "Inga kunder hittades",
"reference_placeholder": "Valfri referens",
"registration_placeholder": "Registreringsnummer",
"selected_customer": "Vald kund",
"submit": "Lägg till fordon",
"title": "Lägg till fordon",
"type_load_error": "Det gick inte att läsa in fordonstyper.",
"type_placeholder": "Välj fordonstyp",
"validation_error": "Välj kund, registreringsnummer och fordonstyp."
},
"brand": "Märke",
"color": "Färg",
"delete_vehicle": "@.capitalize:{'words.generated.ta'} @:{'words.generated.bort'} @:{'words.generated.fordon'}",
@@ -27,14 +27,6 @@
"subtitle_suffix": "@:{'terms.glossary.salg'} @:{'terms.glossary.af'} produktet",
"title": "Produktsalg"
},
"product_targets": {
"cancel_aria": "Annuller mål",
"edit_aria": "Rediger målprocent",
"input_label": "Målprocent",
"save_aria": "Gem mål",
"save_error": "Målet kunne ikke gemmes.",
"validation_range": "Målprocenten skal være mellem 0 og 100."
},
"reports": {
"bookings": {
"completed_count": "@.capitalize:{'terms.glossary.antal'} @:{'terms.glossary.fuldførte'}",
@@ -14,31 +14,6 @@
"transaction_history": "@:{'phrases.compat.superuser.nav.orders'}"
},
"other": "@:{'phrases.compat.global.other'}",
"overview": {
"active_vehicles": "Aktive køretøjer",
"attributes": "Attributter",
"connected": "Forbundet",
"customer_management": "Kundestyring",
"customer_number_required": "Et kundenummer er påkrævet før kundeindstillinger kan administreres.",
"customer_rules": "Kunderegler",
"effective_access": "Effektiv adgang",
"loaded": "Indlæst",
"load_failed": "Brugerdata kunne ikke indlæses",
"loading_user": "Indlæser bruger",
"management_hub": "Administrationshub",
"missing": "Mangler",
"more_permissions": "+{count} flere tilladelser",
"no_subscription_transactions": "Der er ikke registreret vaskeabonnementstransaktioner for kunden.",
"not_invoiced": "Ikke faktureret",
"open_draft": "Åben kladde",
"open_vehicles": "Åbn køretøjer",
"price_overrides": "Prisoverstyringer",
"pricing": "Priser",
"subscription_invoicing": "Abonnementsfakturering",
"subtitle": "Overblik over kundedata, adgang, priser, køretøjer og abonnementsfakturering.",
"vehicles_load_failed": "Køretøjer kunne ikke indlæses.",
"workspace_shortcuts": "Arbejdsgange"
},
"permissions": "@.capitalize:{'terms.glossary.tilladelser'}",
"user_data": "@.capitalize:{'terms.glossary.brugerdata'}",
"user_id": "@.capitalize:{'terms.glossary.bruger'} @.upper:{'terms.glossary.id'}",
@@ -27,14 +27,6 @@
"subtitle_suffix": "Produktverk?@:{'terms.glossary.ufe'}",
"title": "@:{'phrases.compat.admin.daily_report.product_sales.subtitle_suffix'}"
},
"product_targets": {
"cancel_aria": "Ziel abbrechen",
"edit_aria": "Zielprozentsatz bearbeiten",
"input_label": "Zielprozentsatz",
"save_aria": "Ziel speichern",
"save_error": "Das Ziel konnte nicht gespeichert werden.",
"validation_range": "Der Zielprozentsatz muss zwischen 0 und 100 liegen."
},
"reports": {
"bookings": {
"completed_count": "@:{'terms.glossary.abgeschlossene'} @:{'terms.glossary.anzahl'}",
@@ -21,13 +21,6 @@
"opening_hours": {
"closed": "@:{'phrases.compat.global.closed'}"
},
"pricing": {
"custom_pricing_disabled": "Fallback aktiviert",
"custom_pricing_enabled": "Nur eigene Preise",
"custom_pricing_missing_price": "Fehlende Abteilungspreise werden zu 999999.",
"custom_pricing_only": "Keine Fallback-Preise",
"effective_department_price": "Effektiver Abteilungspreis"
},
"search_placeholder": "@.capitalize:{'terms.glossary.nach'} @:{'terms.glossary.abteilungsname'} @:{'terms.glossary.suchen'}",
"select_department": "@:{'phrases.compat.nav.select_department'}",
"subtitle": "@:{'terms.glossary.abteilungen'} @:{'terms.glossary.verwalten'}",
@@ -140,7 +140,6 @@
"departments": {
"columns": {
"archived": "Archiviert",
"custom_pricing_only": "@:{'phrases.compat.departments.pricing.custom_pricing_only'}",
"dimension": "Abmessung",
"economic_department": "@:{'phrases.compat.objects.economic_departments.single'}",
"latitude": "@:{'phrases.compat.departments.form.latitude'}",
@@ -14,31 +14,6 @@
"transaction_history": "@:{'phrases.compat.superuser.nav.orders'}"
},
"other": "@.capitalize:{'terms.glossary.andere'}",
"overview": {
"active_vehicles": "Aktive Fahrzeuge",
"attributes": "Attribute",
"connected": "Verbunden",
"customer_management": "Kundenverwaltung",
"customer_number_required": "Eine Kundennummer ist erforderlich, bevor Kundeneinstellungen verwaltet werden können.",
"customer_rules": "Kundenregeln",
"effective_access": "Effektiver Zugriff",
"loaded": "Geladen",
"load_failed": "Benutzerdaten konnten nicht geladen werden",
"loading_user": "Benutzer wird geladen",
"management_hub": "Verwaltung",
"missing": "Fehlt",
"more_permissions": "+{count} weitere Berechtigungen",
"no_subscription_transactions": "Für diesen Kunden sind keine Waschabonnement-Transaktionen registriert.",
"not_invoiced": "Nicht fakturiert",
"open_draft": "Offener Entwurf",
"open_vehicles": "Fahrzeuge öffnen",
"price_overrides": "Preisüberschreibungen",
"pricing": "Preise",
"subscription_invoicing": "Abonnementabrechnung",
"subtitle": "Überblick über Kundendaten, Zugriff, Preise, Fahrzeuge und Abonnementabrechnung.",
"vehicles_load_failed": "Fahrzeuge konnten nicht geladen werden.",
"workspace_shortcuts": "Arbeitsbereich"
},
"permissions": "Tilladelser",
"user_data": "Brugerdata",
"user_id": "@:{'terms.glossary.benutzer'}-@.upper:{'terms.glossary.id'}",
@@ -2,20 +2,6 @@
"compat": {
"vehicles": {
"add": "@:{'terms.glossary.fahrzeug'} @:{'terms.glossary.hinzuf'}?@:{'terms.glossary.gen'}",
"add_modal": {
"customer_label": "Kunde",
"customer_placeholder": "Nach Kundenname oder Kundennummer suchen",
"error": "Fahrzeug konnte nicht hinzugefuegt werden.",
"no_customer_results": "Keine Kunden gefunden",
"reference_placeholder": "Optionale Referenz",
"registration_placeholder": "Kennzeichen",
"selected_customer": "Ausgewaehlter Kunde",
"submit": "Fahrzeug hinzufuegen",
"title": "Fahrzeug hinzufuegen",
"type_load_error": "Fahrzeugtypen konnten nicht geladen werden.",
"type_placeholder": "Fahrzeugtyp auswaehlen",
"validation_error": "Kunde, Kennzeichen und Fahrzeugtyp auswaehlen."
},
"brand": "@:{'phrases.compat.admin.pos.make'}",
"color": "Farbe",
"delete_vehicle": "@:{'phrases.compat.vehicles.delete'}",
@@ -27,14 +27,6 @@
"subtitle_suffix": "@:{'terms.glossary.product'} @:{'terms.glossary.sales'}",
"title": "@.capitalize:{'terms.glossary.product'} @.capitalize:{'terms.glossary.sales'}"
},
"product_targets": {
"cancel_aria": "Cancel target",
"edit_aria": "Edit target percentage",
"input_label": "Target percentage",
"save_aria": "Save target",
"save_error": "The target could not be saved.",
"validation_range": "The target percentage must be between 0 and 100."
},
"reports": {
"bookings": {
"completed_count": "@.capitalize:{'terms.glossary.completed'} @:{'terms.glossary.count'}",
@@ -14,31 +14,6 @@
"transaction_history": "@.capitalize:{'terms.glossary.transaction'} @:{'terms.glossary.history'}"
},
"other": "@:{'phrases.compat.global.other'}",
"overview": {
"active_vehicles": "Active vehicles",
"attributes": "Attributes",
"connected": "Connected",
"customer_management": "Customer management",
"customer_number_required": "A customer number is required before customer settings can be managed.",
"customer_rules": "Customer rules",
"effective_access": "Effective access",
"loaded": "Loaded",
"load_failed": "User data could not be loaded",
"loading_user": "Loading user",
"management_hub": "Management hub",
"missing": "Missing",
"more_permissions": "+{count} more permissions",
"no_subscription_transactions": "No wash subscription transactions are registered for this customer.",
"not_invoiced": "Not invoiced",
"open_draft": "Open draft",
"open_vehicles": "Open vehicles",
"price_overrides": "Price overrides",
"pricing": "Pricing",
"subscription_invoicing": "Subscription invoicing",
"subtitle": "Overview of customer data, access, pricing, vehicles, and subscription invoicing.",
"vehicles_load_failed": "Vehicles could not be loaded.",
"workspace_shortcuts": "Workspace shortcuts"
},
"permissions": "@.capitalize:{'terms.glossary.permissions'}",
"user_data": "@.capitalize:{'terms.glossary.user'} @:{'terms.glossary.data'}",
"user_id": "@.capitalize:{'terms.glossary.user'} @.upper:{'terms.glossary.id'}",
@@ -34,14 +34,6 @@
"subtitle_suffix": "@:{'phrases.compat.admin.daily_report.product_sales.subtitle_suffix'}",
"title": "@:{'phrases.compat.admin.daily_report.product_sales.title'}"
},
"product_targets": {
"cancel_aria": "@:{'phrases.compat.admin.daily_report.product_targets.cancel_aria'}",
"edit_aria": "@:{'phrases.compat.admin.daily_report.product_targets.edit_aria'}",
"input_label": "@:{'phrases.compat.admin.daily_report.product_targets.input_label'}",
"save_aria": "@:{'phrases.compat.admin.daily_report.product_targets.save_aria'}",
"save_error": "@:{'phrases.compat.admin.daily_report.product_targets.save_error'}",
"validation_range": "@:{'phrases.compat.admin.daily_report.product_targets.validation_range'}"
},
"reports": {
"avg_revenue": {
"label": "@:{'phrases.compat.department_reports.avg_revenue_per_wash'}",
@@ -44,8 +44,8 @@
"overview": "Overview",
"modules": "Modules",
"branding": "Profile & Branding",
"gateways": "@.capitalize:{'terms.glossary.gateways'}",
"stripe": "@:{'terms.glossary.stripe'}",
"gateways": "Gateways",
"stripe": "Stripe",
"pricing": "Pricing",
"categories": "Categories"
},
@@ -88,7 +88,7 @@
"department_id": "Department ID",
"economic_department_id": "Economic department",
"branding": "Branding",
"created_at": "@:common.created",
"created_at": "Created",
"updated_at": "Updated"
},
"hardware": {
@@ -104,12 +104,12 @@
"quick_links": {
"title": "Department tools",
"subtitle": "Open the focused setup areas for this department",
"modules": "@:superuser_dashboard.department_navigation.modules",
"branding": "@:superuser_dashboard.department_overview.profile.branding",
"gateways": "@:superuser_dashboard.department_navigation.gateways",
"stripe": "@:superuser_dashboard.department_navigation.stripe",
"pricing": "@:superuser_dashboard.department_navigation.pricing",
"categories": "@:superuser_dashboard.department_navigation.categories"
"modules": "Modules",
"branding": "Branding",
"gateways": "Gateways",
"stripe": "Stripe",
"pricing": "Pricing",
"categories": "Categories"
},
"errors": {
"invalid_department": "A valid department is required",
@@ -22,31 +22,6 @@
"transaction_history": "@:{'phrases.compat.user_admin.orders.transaction_history'}"
},
"other": "@:{'phrases.compat.user_admin.other'}",
"overview": {
"active_vehicles": "@:{'phrases.compat.user_admin.overview.active_vehicles'}",
"attributes": "@:{'phrases.compat.user_admin.overview.attributes'}",
"connected": "@:{'phrases.compat.user_admin.overview.connected'}",
"customer_management": "@:{'phrases.compat.user_admin.overview.customer_management'}",
"customer_number_required": "@:{'phrases.compat.user_admin.overview.customer_number_required'}",
"customer_rules": "@:{'phrases.compat.user_admin.overview.customer_rules'}",
"effective_access": "@:{'phrases.compat.user_admin.overview.effective_access'}",
"loaded": "@:{'phrases.compat.user_admin.overview.loaded'}",
"load_failed": "@:{'phrases.compat.user_admin.overview.load_failed'}",
"loading_user": "@:{'phrases.compat.user_admin.overview.loading_user'}",
"management_hub": "@:{'phrases.compat.user_admin.overview.management_hub'}",
"missing": "@:{'phrases.compat.user_admin.overview.missing'}",
"more_permissions": "@:{'phrases.compat.user_admin.overview.more_permissions'}",
"no_subscription_transactions": "@:{'phrases.compat.user_admin.overview.no_subscription_transactions'}",
"not_invoiced": "@:{'phrases.compat.user_admin.overview.not_invoiced'}",
"open_draft": "@:{'phrases.compat.user_admin.overview.open_draft'}",
"open_vehicles": "@:{'phrases.compat.user_admin.overview.open_vehicles'}",
"price_overrides": "@:{'phrases.compat.user_admin.overview.price_overrides'}",
"pricing": "@:{'phrases.compat.user_admin.overview.pricing'}",
"subscription_invoicing": "@:{'phrases.compat.user_admin.overview.subscription_invoicing'}",
"subtitle": "@:{'phrases.compat.user_admin.overview.subtitle'}",
"vehicles_load_failed": "@:{'phrases.compat.user_admin.overview.vehicles_load_failed'}",
"workspace_shortcuts": "@:{'phrases.compat.user_admin.overview.workspace_shortcuts'}"
},
"permissions": "@:{'phrases.compat.user_admin.permissions'}",
"subtitle": "@:user_admin.user_data",
"title": "@:{'phrases.compat.common.user'}",
@@ -27,14 +27,6 @@
"subtitle_suffix": "@:{'terms.glossary.produktsalg'}",
"title": "@.capitalize:{'terms.glossary.produktsalg'}"
},
"product_targets": {
"cancel_aria": "Avbryt mål",
"edit_aria": "Rediger målprosent",
"input_label": "Målprosent",
"save_aria": "Lagre mål",
"save_error": "Målet kunne ikke lagres.",
"validation_range": "Målprosenten må være mellom 0 og 100."
},
"reports": {
"bookings": {
"completed_count": "@.capitalize:{'terms.glossary.fullført'} @:{'terms.glossary.telling'}",
@@ -21,13 +21,6 @@
"opening_hours": {
"closed": "Stengt"
},
"pricing": {
"custom_pricing_disabled": "Fallback aktiv",
"custom_pricing_enabled": "Kun egendefinerte priser",
"custom_pricing_missing_price": "Manglende avdelingspriser blir 999999.",
"custom_pricing_only": "Ingen fallback-priser",
"effective_department_price": "Effektiv avdelingspris"
},
"search_placeholder": "@.capitalize:{'terms.glossary.søk'} @:{'terms.glossary.etter'} @:{'terms.glossary.avdelingsnavn'}",
"select_department": "@.capitalize:{'terms.glossary.velg'} @:{'terms.replication.host_definite_suffix'} @:{'terms.glossary.avdeling'}",
"subtitle": "@.capitalize:{'terms.glossary.administrer'} @:{'terms.glossary.avdelinger'}",
@@ -140,7 +140,6 @@
"departments": {
"columns": {
"archived": "Arkivert",
"custom_pricing_only": "@:{'phrases.compat.departments.pricing.custom_pricing_only'}",
"dimension": "Dimensjon",
"economic_department": "@.upper:{'terms.glossary.e'}-@:{'terms.glossary.økonomisk'} @:{'terms.glossary.avdeling'}",
"latitude": "@:{'phrases.compat.departments.form.latitude'}",
@@ -14,31 +14,6 @@
"transaction_history": "@:{'phrases.compat.superuser.nav.orders'}"
},
"other": "@:{'phrases.compat.global.other'}",
"overview": {
"active_vehicles": "Aktive kjøretøy",
"attributes": "Attributter",
"connected": "Tilkoblet",
"customer_management": "Kundestyring",
"customer_number_required": "Et kundenummer kreves før kundeinnstillinger kan administreres.",
"customer_rules": "Kunderegler",
"effective_access": "Effektiv tilgang",
"loaded": "Lastet",
"load_failed": "Brukerdata kunne ikke lastes",
"loading_user": "Laster bruker",
"management_hub": "Administrasjon",
"missing": "Mangler",
"more_permissions": "+{count} flere tillatelser",
"no_subscription_transactions": "Ingen vaskeabonnementstransaksjoner er registrert for kunden.",
"not_invoiced": "Ikke fakturert",
"open_draft": "Åpent utkast",
"open_vehicles": "Åpne kjøretøy",
"price_overrides": "Prisoverstyringer",
"pricing": "Priser",
"subscription_invoicing": "Abonnementsfakturering",
"subtitle": "Oversikt over kundedata, tilgang, priser, kjøretøy og abonnementsfakturering.",
"vehicles_load_failed": "Kjøretøy kunne ikke lastes.",
"workspace_shortcuts": "Arbeidsområde"
},
"permissions": "@.capitalize:{'terms.glossary.tillatelser'}",
"user_data": "@.capitalize:{'terms.glossary.brukerdata'}",
"user_id": "@.capitalize:{'terms.glossary.bruker'}-@.upper:{'terms.glossary.id'}",
@@ -2,20 +2,6 @@
"compat": {
"vehicles": {
"add": "@:{'terms.glossary.lagg'} @:{'terms.glossary.till'} @:{'terms.glossary.fordon'}",
"add_modal": {
"customer_label": "Kunde",
"customer_placeholder": "Søk etter kundenavn eller kundenummer",
"error": "Kunne ikke legge til kjøretøy.",
"no_customer_results": "Ingen kunder funnet",
"reference_placeholder": "Valgfri referanse",
"registration_placeholder": "Registreringsnummer",
"selected_customer": "Valgt kunde",
"submit": "Legg til kjøretøy",
"title": "Legg til kjøretøy",
"type_load_error": "Kunne ikke laste kjøretøytyper.",
"type_placeholder": "Velg kjøretøytype",
"validation_error": "Velg kunde, registreringsnummer og kjøretøytype."
},
"brand": "Märke",
"color": "Färg",
"delete_vehicle": "@:{'phrases.compat.vehicles.delete'}",
@@ -27,14 +27,6 @@
"subtitle_suffix": "@:{'terms.glossary.produktforsaljning'}",
"title": "@.capitalize:{'terms.glossary.produktforsaljning'}"
},
"product_targets": {
"cancel_aria": "Avbryt mål",
"edit_aria": "Redigera målprocent",
"input_label": "Målprocent",
"save_aria": "Spara mål",
"save_error": "Målet kunde inte sparas.",
"validation_range": "Målprocenten måste vara mellan 0 och 100."
},
"reports": {
"bookings": {
"completed_count": "@.capitalize:{'terms.glossary.antal'} @:{'terms.glossary.slutforda'}",
@@ -21,13 +21,6 @@
"opening_hours": {
"closed": "Stengt"
},
"pricing": {
"custom_pricing_disabled": "Fallback aktiv",
"custom_pricing_enabled": "Endast egna priser",
"custom_pricing_missing_price": "Saknade avdelningspriser blir 999999.",
"custom_pricing_only": "Inga fallback-priser",
"effective_department_price": "Effektivt avdelningspris"
},
"search_placeholder": "@:{'terms.glossary.sok'} @:{'terms.glossary.efter'} @:{'terms.glossary.avdelningsnamn'}",
"select_department": "@:{'terms.glossary.velg'} @:{'terms.replication.host_definite_suffix'} @:{'terms.glossary.avdeling'}",
"subtitle": "@:{'terms.glossary.administrer'} @:{'terms.glossary.avdelinger'}",
@@ -140,7 +140,6 @@
"departments": {
"columns": {
"archived": "Arkiverad",
"custom_pricing_only": "@:{'phrases.compat.departments.pricing.custom_pricing_only'}",
"dimension": "Dimension",
"economic_department": "@:{'phrases.compat.objects.economic_departments.single'}",
"latitude": "Latitude",
@@ -14,31 +14,6 @@
"transaction_history": "@:{'phrases.compat.superuser.nav.orders'}"
},
"other": "Andet",
"overview": {
"active_vehicles": "Aktiva fordon",
"attributes": "Attribut",
"connected": "Ansluten",
"customer_management": "Kundhantering",
"customer_number_required": "Ett kundnummer krävs innan kundinställningar kan hanteras.",
"customer_rules": "Kundregler",
"effective_access": "Effektiv åtkomst",
"loaded": "Inläst",
"load_failed": "Användardata kunde inte läsas in",
"loading_user": "Läser in användare",
"management_hub": "Administration",
"missing": "Saknas",
"more_permissions": "+{count} fler behörigheter",
"no_subscription_transactions": "Inga tvättabonnemangstransaktioner är registrerade för kunden.",
"not_invoiced": "Ej fakturerat",
"open_draft": "Öppet utkast",
"open_vehicles": "Öppna fordon",
"price_overrides": "Prisöverskrivningar",
"pricing": "Priser",
"subscription_invoicing": "Abonnemangsfakturering",
"subtitle": "Översikt över kunddata, åtkomst, priser, fordon och abonnemangsfakturering.",
"vehicles_load_failed": "Fordon kunde inte läsas in.",
"workspace_shortcuts": "Arbetsyta"
},
"permissions": "Tilladelser",
"user_data": "Brugerdata",
"user_id": "Användar-@.upper:{'terms.glossary.id'}",
@@ -2,20 +2,6 @@
"compat": {
"vehicles": {
"add": "@:{'terms.glossary.lagg'} @:{'terms.glossary.till'} @:{'terms.glossary.fordon'}",
"add_modal": {
"customer_label": "Kund",
"customer_placeholder": "Sök efter kundnamn eller kundnummer",
"error": "Det gick inte att lägga till fordon.",
"no_customer_results": "Inga kunder hittades",
"reference_placeholder": "Valfri referens",
"registration_placeholder": "Registreringsnummer",
"selected_customer": "Vald kund",
"submit": "Lägg till fordon",
"title": "Lägg till fordon",
"type_load_error": "Det gick inte att läsa in fordonstyper.",
"type_placeholder": "Välj fordonstyp",
"validation_error": "Välj kund, registreringsnummer och fordonstyp."
},
"brand": "Märke",
"color": "Färg",
"delete_vehicle": "@.capitalize:{'terms.glossary.ta'} @:{'terms.glossary.bort'} @:{'terms.glossary.fordon'}",
-6
View File
@@ -442,12 +442,6 @@ export const router = createRouter({
},
{
name: 'limitedBackofficeEmployees',
path: '/backoffice/departments/:departmentId/employees',
component: LimitedBackofficeEmployees,
meta: { middleware: authMiddleware, titleKey: 'templates.limited_backoffice.employees.title' }
},
{
name: 'limitedBackofficeEmployeesLegacy',
path: '/backoffice/employees',
component: LimitedBackofficeEmployees,
meta: { middleware: authMiddleware, titleKey: 'templates.limited_backoffice.employees.title' }
@@ -1,7 +1,6 @@
<script setup>
import { computed, onMounted, ref, watch } from "vue";
import { computed, onMounted, ref } from "vue";
import { useI18n } from "vue-i18n";
import { useRoute, useRouter } from "vue-router";
import RestrictedPageWrapper from "@/components/page/wrappers/RestrictedPageWrapper.vue";
import { SessionUser } from "@/components/session/token/SessionUser.vue";
import LimitedBackofficeLayout from "@/views/backoffice/components/LimitedBackofficeLayout.vue";
@@ -34,14 +33,6 @@ const loadQRCodeModule = () => {
};
const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const countryCodeLabels = {
denmark: () => t("templates.limited_backoffice.employees.country_codes.denmark"),
sweden: () => t("templates.limited_backoffice.employees.country_codes.sweden"),
norway: () => t("templates.limited_backoffice.employees.country_codes.norway"),
finland: () => t("templates.limited_backoffice.employees.country_codes.finland"),
};
const departments = ref([]);
const roles = ref([]);
const employees = ref([]);
@@ -69,19 +60,6 @@ const form = ref({
department_ids: [],
});
const selectedDepartmentId = computed(() => {
const departmentId = Number.parseInt(String(route.params.departmentId ?? ""), 10);
return Number.isInteger(departmentId) && departmentId > 0 ? departmentId : null;
});
const selectedDepartment = computed(() =>
departments.value.find((department) => Number(department.id) === selectedDepartmentId.value) || null
);
const hasForbiddenDepartment = computed(
() => selectedDepartmentId.value !== null && departments.value.length > 0 && !selectedDepartment.value
);
const roleMessages = computed(() => ({
viewer: {
label: t("templates.limited_backoffice.roles.viewer.label"),
@@ -278,7 +256,7 @@ const countryCodeLabel = (countryCode) => {
if (!option) {
return "";
}
return `${option.flag} +${option.value} ${countryCodeLabels[option.labelKey]?.() || ""}`;
return `${option.flag} +${option.value} ${t(`templates.limited_backoffice.employees.country_codes.${option.labelKey}`)}`;
};
const formatEmployeePhone = (employee) => {
@@ -294,23 +272,11 @@ const sanitizePhone = (event) => {
const absoluteLoginLink = (loginPath) => new URL(String(loginPath || ""), window.location.origin).toString();
const visibleEmployees = computed(() => {
if (!selectedDepartmentId.value) {
return employees.value;
}
return employees.value.filter((employee) =>
(employee.departments || []).some((department) => Number(department.id) === selectedDepartmentId.value)
);
});
const loadEmployees = async () => {
const response = await getLimitedBackofficeEmployees({ includeInactive: includeInactive.value });
employees.value = unwrapLimitedBackofficeResponse(response) || [];
};
const defaultDepartmentIds = () => (selectedDepartment.value?.id ? [Number(selectedDepartment.value.id)] : []);
const loadData = async () => {
loading.value = true;
errorMessage.value = "";
@@ -325,18 +291,6 @@ const loadData = async () => {
if (!ROLE_KEYS.includes(form.value.role_key) || !roles.value.some((role) => role.key === form.value.role_key)) {
form.value.role_key = roles.value[0]?.key || "viewer";
}
const firstDepartment = departments.value[0] || null;
if (!selectedDepartmentId.value && firstDepartment?.id) {
await router.replace(`/backoffice/departments/${firstDepartment.id}/employees`);
}
resetForm();
if (hasForbiddenDepartment.value) {
employees.value = [];
return;
}
await loadEmployees();
} catch (error) {
errorMessage.value = limitedBackofficeErrorMessage(
@@ -358,7 +312,7 @@ const resetForm = () => {
phone: "",
password: "",
role_key: roles.value[0]?.key || "viewer",
department_ids: defaultDepartmentIds(),
department_ids: [],
};
};
@@ -525,16 +479,7 @@ const closeEmployeeLoginLink = () => {
loginLinkCopyMessage.value = "";
};
const changeDepartment = async (departmentId) => {
await router.push(`/backoffice/departments/${departmentId}/employees`);
};
const reloadEmployees = async () => {
if (hasForbiddenDepartment.value) {
employees.value = [];
return;
}
loading.value = true;
errorMessage.value = "";
try {
@@ -552,36 +497,12 @@ const reloadEmployees = async () => {
onMounted(() => {
void loadData();
});
watch(
() => selectedDepartmentId.value,
async (nextDepartmentId, previousDepartmentId) => {
if (nextDepartmentId === previousDepartmentId || loading.value || departments.value.length === 0) {
return;
}
resetForm();
await reloadEmployees();
}
);
</script>
<template>
<RestrictedPageWrapper :hasPermission="SessionUser.hasPermission('limited_backoffice_access')">
<LimitedBackofficeLayout
active-tab="employees"
:departments="departments"
:selected-department-id="selectedDepartmentId"
:loading-departments="loading"
show-department-switcher
@change-department="changeDepartment"
>
<div v-if="hasForbiddenDepartment" class="notification is-danger is-light" data-testid="limited-employees-forbidden">
<strong>{{ t("templates.limited_backoffice.forbidden.title") }}</strong>
<p>{{ t("templates.limited_backoffice.forbidden.department") }}</p>
</div>
<div v-else class="columns is-variable is-5">
<LimitedBackofficeLayout active-tab="employees" :departments="departments">
<div class="columns is-variable is-5">
<div class="column is-5">
<form class="box limited-employee-form" data-testid="limited-employee-form" @submit.prevent="saveEmployee">
<h2 class="title is-5">
@@ -805,15 +726,11 @@ watch(
{{ successMessage }}
</div>
<div
v-if="!loading && visibleEmployees.length === 0"
class="notification is-light"
data-testid="limited-employees-empty"
>
<div v-if="!loading && employees.length === 0" class="notification is-light" data-testid="limited-employees-empty">
{{ t("templates.limited_backoffice.employees.empty") }}
</div>
<div v-if="!loading && visibleEmployees.length > 0" class="table-container">
<div v-if="!loading && employees.length > 0" class="table-container">
<table class="table is-fullwidth is-hoverable limited-employees-table" data-testid="limited-employees-table">
<thead>
<tr>
@@ -826,7 +743,7 @@ watch(
</tr>
</thead>
<tbody>
<tr v-for="employee in visibleEmployees" :key="employee.id" :data-testid="`limited-employee-row-${employee.id}`">
<tr v-for="employee in employees" :key="employee.id" :data-testid="`limited-employee-row-${employee.id}`">
<td>
<span class="tag is-light" :data-testid="`limited-employee-user-id-${employee.id}`">
{{ employee.user_id || employee.id }}
@@ -17,10 +17,6 @@ const departments = ref([]);
const loading = ref(false);
const errorMessage = ref("");
const changeDepartment = async (departmentId) => {
await router.push(`/backoffice/departments/${departmentId}/prices`);
};
const loadDepartments = async () => {
loading.value = true;
errorMessage.value = "";
@@ -42,6 +38,10 @@ const loadDepartments = async () => {
}
};
const changeDepartment = async (departmentId) => {
await router.push(`/backoffice/departments/${departmentId}/prices`);
};
onMounted(() => {
void loadDepartments();
});
@@ -35,12 +35,6 @@ const pricesRoute = computed(() =>
: "/backoffice"
);
const employeesRoute = computed(() =>
props.selectedDepartmentId
? `/backoffice/departments/${encodeURIComponent(String(props.selectedDepartmentId))}/employees`
: "/backoffice/employees"
);
const tabs = computed(() => [
{
key: "prices",
@@ -50,7 +44,7 @@ const tabs = computed(() => [
{
key: "employees",
label: t("templates.limited_backoffice.nav.employees"),
to: employeesRoute.value,
to: "/backoffice/employees",
},
]);
@@ -68,37 +62,8 @@ const selectDepartment = (event) => {
<section class="section limited-backoffice" data-testid="limited-backoffice">
<PageTitle
:title="t('templates.limited_backoffice.title')"
>
<template #buttons>
<div v-if="props.showDepartmentSwitcher" class="field limited-backoffice__department-field">
<label class="label is-sr-only" for="limited-backoffice-department">
{{ t("templates.limited_backoffice.department") }}
</label>
<div class="control">
<div class="select is-small is-fullwidth">
<select
id="limited-backoffice-department"
:value="props.selectedDepartmentId || ''"
:disabled="props.loadingDepartments || props.departments.length === 0"
data-testid="limited-backoffice-department-select"
@change="selectDepartment"
>
<option value="" disabled>
{{ t("templates.limited_backoffice.select_department") }}
</option>
<option v-for="department in props.departments" :key="department.id" :value="department.id">
{{ department.name }}
</option>
</select>
</div>
</div>
</div>
</template>
<p class="is-size-6 limited-backoffice__subtitle">
{{ t("templates.limited_backoffice.subtitle") }}
</p>
</PageTitle>
:subtitle="t('templates.limited_backoffice.subtitle')"
/>
<div class="limited-backoffice__toolbar">
<div class="tabs is-toggle is-small limited-backoffice__tabs" data-testid="limited-backoffice-tabs">
@@ -110,6 +75,30 @@ const selectDepartment = (event) => {
</li>
</ul>
</div>
<div v-if="props.showDepartmentSwitcher" class="field limited-backoffice__department-field">
<label class="label" for="limited-backoffice-department">
{{ t("templates.limited_backoffice.department") }}
</label>
<div class="control">
<div class="select is-fullwidth">
<select
id="limited-backoffice-department"
:value="props.selectedDepartmentId || ''"
:disabled="props.loadingDepartments || props.departments.length === 0"
data-testid="limited-backoffice-department-select"
@change="selectDepartment"
>
<option value="" disabled>
{{ t("templates.limited_backoffice.select_department") }}
</option>
<option v-for="department in props.departments" :key="department.id" :value="department.id">
{{ department.name }}
</option>
</select>
</div>
</div>
</div>
</div>
<slot />
@@ -123,8 +112,10 @@ const selectDepartment = (event) => {
.limited-backoffice__toolbar {
display: flex;
align-items: center;
justify-content: flex-start;
align-items: flex-end;
justify-content: space-between;
gap: 1rem;
flex-wrap: wrap;
margin-bottom: 1.25rem;
}
@@ -132,12 +123,8 @@ const selectDepartment = (event) => {
margin-bottom: 0;
}
.limited-backoffice__subtitle {
margin-top: -0.75rem;
}
.limited-backoffice__department-field {
min-width: min(42vw, 280px);
min-width: min(100%, 260px);
margin-bottom: 0;
}
@@ -151,16 +138,9 @@ const selectDepartment = (event) => {
align-items: stretch;
}
.limited-backoffice__tabs {
width: 100%;
}
.limited-backoffice__tabs,
.limited-backoffice__department-field {
min-width: 9rem;
}
.limited-backoffice__subtitle {
margin-top: -0.5rem;
width: 100%;
}
.limited-backoffice__tabs :deep(ul) {
+2 -73
View File
@@ -2,10 +2,9 @@
import SessionUser from "@/components/session/token/SessionUser.vue";
import WhiteBoxCard from "@/components/displays/boxes/WhiteBoxCard.vue";
import SubuserGrantSelector from "@/components/session/subuser/SubuserGrantSelector.vue";
import {ref, onMounted, nextTick, computed, onUnmounted, watch} from "vue";
import {ref, onMounted, nextTick, computed, onUnmounted} from "vue";
import { IS_DEV } from '@/config.js';
import {BLoading} from "buefy";
import { authenticatedRequest } from "@/components/session/authenticatedRequest.vue";
/**
* Subuser grant selection gate
@@ -77,59 +76,6 @@ const canShowVehicleShortcut = computed(() => SessionUser.canAccessCustomerFeatu
const canShowOrderShortcut = computed(() => SessionUser.canAccessCustomerFeature("orders", "list"));
const canShowSelfServeShortcut = computed(() => SessionUser.canAccessCustomerFeature("selfserve", "list"));
const canShowInvoiceShortcut = computed(() => canShowClassicCustomerShortcut());
const hasInvoicesAvailable = ref(false);
const isCheckingInvoiceAvailability = ref(true);
const canDownloadInvoices = computed(() => canShowInvoiceShortcut.value && hasInvoicesAvailable.value && !isCheckingInvoiceAvailability.value);
const responseHasInvoices = (response: any) => {
const total = Number(response?.data?.meta?.pagination?.total);
if (Number.isFinite(total) && total > 0) {
return true;
}
return Array.isArray(response?.data?.data) && response.data.data.length > 0;
};
const resetInvoiceAvailability = () => {
hasInvoicesAvailable.value = false;
isCheckingInvoiceAvailability.value = false;
};
const loadInvoiceAvailability = async () => {
if (!canShowInvoiceShortcut.value) {
resetInvoiceAvailability();
return;
}
isCheckingInvoiceAvailability.value = true;
try {
const response = await authenticatedRequest("/user/invoices", "GET", {
page: 1,
limit: 1,
order: "created_at:desc",
});
hasInvoicesAvailable.value = responseHasInvoices(response);
} catch (_error) {
hasInvoicesAvailable.value = false;
} finally {
isCheckingInvoiceAvailability.value = false;
setEqualHeights();
}
};
watch(
canShowInvoiceShortcut,
(canShow) => {
if (canShow) {
void loadInvoiceAvailability();
return;
}
resetInvoiceAvailability();
},
{ immediate: true }
);
const windowInnerWidth = ref(window.innerWidth);
const updateWindowInnerWidth = () => {
@@ -345,26 +291,9 @@ const isPermissionsLoading = computed(() => {
</template>
<template #footer>
<div class="card-footer-item">
<router-link
v-if="canDownloadInvoices"
to="/user/invoices"
class="button is-link is-fullwidth"
:class="classes.button"
id="download-invoices-button"
>
<router-link to="/user/invoices" class="button is-link is-fullwidth" :class="classes.button" id="download-invoices-button">
{{ $t('user_home.download_invoices') }}
</router-link>
<button
v-else
class="button is-link is-fullwidth"
:class="[classes.button, { 'is-loading': isCheckingInvoiceAvailability }]"
id="download-invoices-button"
type="button"
disabled
aria-disabled="true"
>
{{ $t('user_home.download_invoices') }}
</button>
</div>
</template>
</WhiteBoxCard>
@@ -370,12 +370,8 @@ const isInvoiced = () => {
return isInvoicedWithEconomic() || isInvoicedWithStripe();
};
const hasEconomicInvoiceDownloadContext = () => {
const module = economicModule.value || {};
return (
Object.prototype.hasOwnProperty.call(module, 'invoice_id') ||
Object.prototype.hasOwnProperty.call(module, 'invoice_draft_id')
);
const isBookedWithEconomic = () => {
return economicModule.value.invoice_id !== null;
};
const isCompleted = () => {
@@ -1380,11 +1376,7 @@ const isDisplayingReceipt = () => {
<template #rail-actions>
<ButtonsBox class="pos-actions pos-actions--rail">
<GetOrderInvoicePDFButton
:invoice_id="economicModule.invoice_id"
class="is-fullwidth"
v-if="hasEconomicInvoiceDownloadContext()"
/>
<GetOrderInvoicePDFButton :invoice_id="economicModule.invoice_id" class="is-fullwidth" v-if="isBookedWithEconomic()" />
<div
v-if="isEconomicExportBlocked"
class="message is-warning is-light"
@@ -77,15 +77,6 @@ const normalizeMetricState = (metric, fallbackState = "ready", fallbackMessage =
message: metric?.message || fallbackMessage,
});
const normalizeNullableNumber = (value) => {
if (value === null || value === undefined || value === "") {
return null;
}
const normalized = Number(value);
return Number.isFinite(normalized) ? normalized : null;
};
const resetOverviewState = () => {
count_transactions.value = 0;
count_products_sold.value = 0;
@@ -158,8 +149,6 @@ const applyOverviewResponse = (overview) => {
value: Number(product.value || 0),
out_of: Number(product.out_of || 0),
state: product.state || "ready",
target_percentage: normalizeNullableNumber(product.target_percentage),
target_department_id: normalizeNullableNumber(product.target_department_id),
},
])
);
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { ref, watch, onMounted, computed, nextTick } from 'vue';
import { ref, watch, onMounted, computed } from 'vue';
import {BSkeleton} from "buefy";
import { useI18n } from 'vue-i18n';
@@ -76,18 +76,6 @@ const props = defineProps({
type: Function,
default: () => {}
},
canEditTarget: {
type: Boolean,
default: false,
},
targetPercentage: {
type: [Number, String],
default: null,
},
saveTargetFunction: {
type: Function,
default: null,
},
styleContent: {
type: Object,
default: () => {
@@ -96,12 +84,6 @@ const props = defineProps({
}
});
const percentageElement = ref<HTMLElement|null>(null);
const targetInputElement = ref<HTMLInputElement|null>(null);
const isTargetEditorOpen = ref(false);
const targetInputValue = ref("");
const isSavingTarget = ref(false);
const targetError = ref("");
const getPercentage = () => {
if (props.state !== "ready") {
return null;
@@ -111,91 +93,6 @@ const getPercentage = () => {
}
return null;
}
const formatPercentageValue = (value: number) => `${value.toFixed(1)}%`;
const normalizedTargetPercentage = computed(() => {
if (props.targetPercentage === null || props.targetPercentage === undefined || props.targetPercentage === "") {
return null;
}
const numericTarget = Number(props.targetPercentage);
return Number.isFinite(numericTarget) ? numericTarget : null;
});
const hasTargetPercentage = computed(() => normalizedTargetPercentage.value !== null);
const formattedTargetPercentage = computed(() => (
normalizedTargetPercentage.value === null ? "" : formatPercentageValue(normalizedTargetPercentage.value)
));
const canUseTargetEditor = computed(() => Boolean(
props.canEditTarget && props.saveTargetFunction && getPercentage() !== null && !props.isLoading
));
const percentageButtonTestid = computed(() => (props.dataTestid ? `${props.dataTestid}-percentage-button` : null));
const targetButtonTestid = computed(() => (props.dataTestid ? `${props.dataTestid}-target-button` : null));
const targetInputTestid = computed(() => (props.dataTestid ? `${props.dataTestid}-target-input` : null));
const targetSaveTestid = computed(() => (props.dataTestid ? `${props.dataTestid}-target-save` : null));
const targetCancelTestid = computed(() => (props.dataTestid ? `${props.dataTestid}-target-cancel` : null));
const targetErrorTestid = computed(() => (props.dataTestid ? `${props.dataTestid}-target-error` : null));
const openTargetEditor = async () => {
if (!canUseTargetEditor.value) {
return;
}
targetInputValue.value = normalizedTargetPercentage.value === null
? ""
: String(normalizedTargetPercentage.value);
targetError.value = "";
isTargetEditorOpen.value = true;
await nextTick();
targetInputElement.value?.focus();
autoAdjustedFontSizeTitle.value = determineTitleFontSize(props.title);
};
const closeTargetEditor = () => {
targetError.value = "";
isTargetEditorOpen.value = false;
nextTick(() => {
autoAdjustedFontSizeTitle.value = determineTitleFontSize(props.title);
});
};
const parseTargetInputValue = () => {
const rawValue = String(targetInputValue.value || "").trim().replace(",", ".");
if (rawValue === "") {
return { valid: true, value: null };
}
const numericTarget = Number(rawValue);
if (!Number.isFinite(numericTarget) || numericTarget < 0 || numericTarget > 100) {
return { valid: false, value: null };
}
return { valid: true, value: Math.round(numericTarget * 10) / 10 };
};
const saveTarget = async () => {
if (!canUseTargetEditor.value || isSavingTarget.value) {
return;
}
const parsedTarget = parseTargetInputValue();
if (!parsedTarget.valid) {
targetError.value = t("admin.daily_report.product_targets.validation_range");
return;
}
isSavingTarget.value = true;
targetError.value = "";
try {
await props.saveTargetFunction(parsedTarget.value);
closeTargetEditor();
} catch (error) {
console.error("Failed to save daily report product target", error);
targetError.value = t("admin.daily_report.product_targets.save_error");
} finally {
isSavingTarget.value = false;
}
};
const getAveragePercentage = () => {
return null; // TODO: Average percentage
}
@@ -269,11 +166,6 @@ watch(() => props.count, (newVal) => {
autoAdjustedFontSize.value = determineFontSize(newVal);
determineTitleFontSize(props.title);
}, { immediate: true });
watch(() => [props.targetPercentage, isTargetEditorOpen.value], () => {
nextTick(() => {
autoAdjustedFontSizeTitle.value = determineTitleFontSize(props.title);
});
}, { immediate: true });
onMounted(() => {
autoAdjustedFontSizeTitle.value = determineTitleFontSize(props.title);
@@ -288,19 +180,12 @@ const isUnavailable = computed(() => props.state === "unavailable");
<template>
<div class="card" @click="clickFunction" :data-testid="dataTestid || null">
<div class="card-content" :style="styleContent">
<div class="daily-report-count__percentage-stack has-text-right is-flex is-flex-direction-column is-4" v-if="getPercentage() !== null" ref="percentageElement">
<button
type="button"
class="button is-small is-info"
:class="{
<div class="is-pulled-right has-text-right is-flex is-flex-direction-column is-4" style="gap: 4px;" v-if="getPercentage() !== null" ref="percentageElement">
<button class="button is-small is-info" :class="{
'has-background-success has-text-black': getAveragePercentage() !== null && isAverage(),
'has-background-danger has-text-black': getAveragePercentage() !== null && !isAverage(),
'is-outlined': getAveragePercentage() === null
}"
:aria-label="canUseTargetEditor ? t('admin.daily_report.product_targets.edit_aria') : null"
:data-testid="percentageButtonTestid"
@click.stop="openTargetEditor"
>
}">
<!--<span class="icon is-small">
<i class="fas fa-sync-alt"></i>
</span>-->
@@ -312,75 +197,6 @@ const isUnavailable = computed(() => props.state === "unavailable");
</template>
</button>
<form
v-if="isTargetEditorOpen"
class="daily-report-count__target-editor"
@submit.prevent.stop="saveTarget"
@click.stop
>
<div class="field has-addons daily-report-count__target-editor-controls">
<div class="control">
<input
ref="targetInputElement"
v-model="targetInputValue"
class="input is-small daily-report-count__target-input"
type="number"
min="0"
max="100"
step="0.1"
inputmode="decimal"
:aria-label="t('admin.daily_report.product_targets.input_label')"
:data-testid="targetInputTestid"
>
</div>
<div class="control">
<button
class="button is-small is-success"
type="submit"
:class="{ 'is-loading': isSavingTarget }"
:aria-label="t('admin.daily_report.product_targets.save_aria')"
:data-testid="targetSaveTestid"
>
<span class="icon is-small">
<i class="fas fa-check"></i>
</span>
</button>
</div>
<div class="control">
<button
class="button is-small"
type="button"
:aria-label="t('admin.daily_report.product_targets.cancel_aria')"
:data-testid="targetCancelTestid"
@click.stop="closeTargetEditor"
>
<span class="icon is-small">
<i class="fas fa-times"></i>
</span>
</button>
</div>
</div>
<p
v-if="targetError"
class="help is-danger daily-report-count__target-error"
:data-testid="targetErrorTestid"
>
{{ targetError }}
</p>
</form>
<button
v-else-if="hasTargetPercentage"
type="button"
class="button is-small is-info is-outlined daily-report-count__target-button"
:aria-label="canUseTargetEditor ? t('admin.daily_report.product_targets.edit_aria') : null"
:data-testid="targetButtonTestid"
@click.stop="openTargetEditor"
>
<i class="fas fa-bullseye daily-report-count__target-background-icon" aria-hidden="true"></i>
<span class="daily-report-count__target-value">{{ formattedTargetPercentage }}</span>
</button>
<button v-if="getAveragePercentage()" class="button is-small is-info is-outlined">
<!--<span class="icon is-small">
<i class="fas fa-sync-alt"></i>
@@ -466,56 +282,5 @@ const isUnavailable = computed(() => props.state === "unavailable");
</template>
<style scoped>
.card-content {
position: relative;
}
.daily-report-count__percentage-stack {
align-items: flex-end;
gap: 4px;
position: absolute;
right: 1.25rem;
top: 1.25rem;
z-index: 2;
}
.daily-report-count__target-button {
min-width: 64px;
overflow: hidden;
position: relative;
}
.daily-report-count__target-background-icon {
font-size: 1.35rem;
left: 50%;
opacity: 0.16;
position: absolute;
top: 50%;
transform: translate(-50%, -50%);
}
.daily-report-count__target-value {
position: relative;
z-index: 1;
}
.daily-report-count__target-editor {
width: 154px;
}
.daily-report-count__target-editor-controls {
justify-content: flex-end;
margin-bottom: 0;
}
.daily-report-count__target-input {
max-width: 68px;
text-align: right;
}
.daily-report-count__target-error {
max-width: 154px;
white-space: normal;
}
</style>
@@ -1,16 +1,9 @@
<script setup>
import { computed } from "vue";
import { Colors } from "@/ThemeConfig.vue";
import { SessionUser } from "@/components/session/token/SessionUser.vue";
import {
daily_report_products,
refreshOverview,
selected_department_ids,
} from "@/views/dashboards/departmentDashboard/modules/daily-report/DepartmentDailyReportObject.vue";
import { daily_report_products } from "@/views/dashboards/departmentDashboard/modules/daily-report/DepartmentDailyReportObject.vue";
import DepartmentDashboardDailyReportCount from "@/views/dashboards/departmentDashboard/modules/daily-report/displays/DepartmentDashboardDailyReportCount.vue";
const SET_PRODUCT_TARGET_PERMISSION = "set_department_daily_report_product_targets";
const FALLBACK_PRODUCT_TITLES = {
24: "Spot Free (Lastbil)",
25: "Fælg flex pr. enhed",
@@ -58,8 +51,6 @@ const productTile = computed(() => {
out_of: 0,
state: "ready",
message: null,
target_percentage: null,
target_department_id: null,
};
});
@@ -79,59 +70,6 @@ const resolvedTitle = computed(() => {
return FALLBACK_PRODUCT_TITLES[props.product_id] || null;
});
const selectedDepartmentId = computed(() => {
const selectedDepartmentIds = Array.isArray(selected_department_ids.value)
? selected_department_ids.value.map((departmentId) => Number(departmentId)).filter((departmentId) => departmentId > 0)
: [];
return selectedDepartmentIds.length === 1 ? selectedDepartmentIds[0] : null;
});
const targetPercentage = computed(() => {
const target = productTile.value?.target_percentage;
if (target === null || target === undefined || target === "") {
return null;
}
const numericTarget = Number(target);
return Number.isFinite(numericTarget) ? numericTarget : null;
});
const canEditProductTarget = computed(() => Boolean(
selectedDepartmentId.value !== null && SessionUser.hasPermission(SET_PRODUCT_TARGET_PERMISSION)
));
const saveProductTarget = async (nextTargetPercentage) => {
const departmentId = selectedDepartmentId.value;
if (departmentId === null) {
return null;
}
const response = await SessionUser.objects.department_daily_reports.functions.setProductTarget({
department_id: departmentId,
product_id: props.product_id,
target_percentage: nextTargetPercentage,
});
const savedTarget = response?.data?.data?.target_percentage ?? nextTargetPercentage;
const normalizedTarget = savedTarget === null || savedTarget === undefined || savedTarget === ""
? null
: Number(savedTarget);
daily_report_products.value = {
...daily_report_products.value,
[props.product_id]: {
...productTile.value,
product_id: props.product_id,
target_percentage: Number.isFinite(normalizedTarget) ? normalizedTarget : null,
target_department_id: Number.isFinite(normalizedTarget) ? departmentId : null,
},
};
await refreshOverview();
return response;
};
</script>
<template>
@@ -145,9 +83,6 @@ const saveProductTarget = async (nextTargetPercentage) => {
:isLoading="is_loading"
:state="productTile.state || 'ready'"
:unavailable-message="productTile.message || 'Ikke tilgængelig'"
:can-edit-target="canEditProductTarget"
:target-percentage="targetPercentage"
:save-target-function="saveProductTarget"
:style-content="styleContent"
:data-testid="dataTestid"
/>
@@ -14,16 +14,6 @@ import NotificationsPhonePagination
:title="$t('admin.notifications.title')"
:subtitle="$t('admin.notifications.subtitle')"
>
<header class="mb-5" data-testid="department-notifications-page-header">
<h1 class="title is-3 mb-2" data-testid="department-notifications-title">
{{ $t('admin.notifications.title') }}
</h1>
<p class="subtitle is-6 mb-0" data-testid="department-notifications-subtitle">
<span>{{ $t('admin.notifications.sms_overview') }}</span>
<br>
<span>{{ $t('admin.notifications.sms_activated_description') }}</span>
</p>
</header>
<NotFoundFallBackPageWrapper :exists="SessionUser.functions.getDepartmentIdFromUrl() && SessionUser.canAccessDepartment(SessionUser.functions.getDepartmentIdFromUrl())" :error="$t('admin.errors.select_department')">
<element-tabs-box
defaultActiveTab="sms"
@@ -34,6 +24,16 @@ import NotificationsPhonePagination
]"
>
<template #sms>
<!-- What is this? -->
<div class="message">
<div class="message-header">
<p>{{ $t('admin.notifications.sms_notifications') }}</p>
</div>
<div class="message-body">
<p>{{ $t('admin.notifications.sms_overview') }}</p>
<p>{{ $t('admin.notifications.sms_activated_description') }}</p>
</div>
</div>
<NotificationsPhonePagination />
</template>
</element-tabs-box>
@@ -44,4 +44,4 @@ import NotificationsPhonePagination
<style scoped>
</style>
</style>
@@ -1,45 +1,45 @@
<script setup>
import { computed } from "vue";
import { useRoute } from "vue-router";
import { useI18n } from "vue-i18n";
import { useRouter} from "vue-router";
import { ref } from 'vue';
import { showAuthSignOutForm } from '@/components/forms/auth/authSignOutForm.vue';
import UserNavigation from "@/components/global/UserNavigation.vue";
import { SessionUser } from "@/components/session/token/SessionUser.vue";
const router = useRouter();
// Get the user from the route
const userId = ref(router.currentRoute.value.params.userId)
const route = useRoute();
const { t } = useI18n();
const tabs = [
{ name: 'Overview', path: '/superuser/users/' + userId.value },
{ name: 'Orders', path: '/superuser/users/' + userId.value + '/orders' },
{ name: 'Pricing', path: '/superuser/users/' + userId.value + '/pricing' },
{ name: 'Other', path: '/superuser/users/' + userId.value + '/other' },
{ name: 'Vehicles', path: '/superuser/users/' + userId.value + '/vehicles' },
{ name: SessionUser.superUser.modules.xlvask.meta.title, path: '/superuser/users/' + userId.value + '/xlvask' },
];
const userId = computed(() => route.params.userId);
const basePath = computed(() => `/superuser/users/${userId.value}`);
// Get the current path
const currentPath = ref(router.currentRoute.value.path);
const tabs = computed(() => [
{ key: "overview", name: t("nav.overview"), path: basePath.value },
{ key: "orders", name: t("superuser.nav.orders"), path: `${basePath.value}/orders` },
{ key: "pricing", name: t("user_admin.overview.pricing"), path: `${basePath.value}/pricing` },
{ key: "other", name: t("user_admin.other"), path: `${basePath.value}/other` },
{ key: "vehicles", name: t("common.vehicles"), path: `${basePath.value}/vehicles` },
{ key: "xlvask", name: SessionUser.superUser.modules.xlvask.meta.title, path: `${basePath.value}/xlvask` },
]);
// Get the index of the active tab
const activeTab = tabs.findIndex(tab => tab.path === currentPath.value);
// Change the tab
const changeTab = (index) => {
router.push(tabs[index].path);
};
</script>
<template>
<nav class="user-detail-tabs" data-testid="superuser-user-tabs">
<div class="tabs is-right is-boxed">
<div>
<div class="tabs is-right">
<ul>
<li v-for="tab in tabs" :key="tab.path" :class="{ 'is-active': route.path === tab.path }">
<router-link :to="tab.path" :data-testid="`superuser-user-tab-${tab.key}`">
{{ tab.name }}
</router-link>
<li v-for="(tab, index) in tabs" :key="index" :class="{'is-active': activeTab === index}" @click="changeTab(index)">
<a>{{ tab.name }}</a>
</li>
</ul>
</div>
</nav>
</div>
</template>
<style scoped>
.user-detail-tabs {
overflow-x: auto;
}
.tabs ul {
flex-wrap: nowrap;
}
</style>
</style>
@@ -1,91 +1,15 @@
<script>
import { ref, watch } from "vue";
import {ref, watch} from "vue";
import { authenticatedRequest } from "@/components/session/authenticatedRequest.vue";
// Get the user from the route
export const userId = ref(0);
export const isUserLoading = ref(false);
export const userLoadError = ref(null);
export const selectedUserLoaded = ref(false);
let activeLoadPromise = null;
let activeLoadUserId = null;
let loadRequestSequence = 0;
const normalizeUserId = (id) => {
const parsed = Number.parseInt(String(id ?? ""), 10);
return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;
};
const defaultKeys = () => ({
open_invoice_draft: null,
});
const economicFields = {
customerNumber: null,
name: null,
address: null,
zip: null,
city: null,
mobilePhone: null,
email: null,
cvr: null,
currency: null,
country: null,
barred: null,
};
const setEconomicData = (economicCustomer = {}) => {
user.economicData.customerNumber.value = economicCustomer?.customerNumber ?? null;
user.economicData.name.value = economicCustomer?.name ?? null;
user.economicData.address.value = economicCustomer?.address ?? null;
user.economicData.zip.value = economicCustomer?.zip ?? null;
user.economicData.city.value = economicCustomer?.city ?? null;
user.economicData.mobilePhone.value = economicCustomer?.mobilePhone ?? null;
user.economicData.email.value = economicCustomer?.email ?? null;
user.economicData.cvr.value = economicCustomer?.corporateIdentificationNumber ?? economicCustomer?.cvr ?? null;
user.economicData.currency.value = economicCustomer?.currency ?? null;
user.economicData.country.value = economicCustomer?.country ?? null;
user.economicData.barred.value = economicCustomer?.barred ?? false;
};
export const resetUser = ({ preserveUserId = false } = {}) => {
if (!preserveUserId) {
userId.value = 0;
}
user.id.value = "";
user.customer_number.value = "";
user.display_name.value = "";
user.email.value = "";
user.phone.value = null;
user.group_id.value = "";
user.created_at.value = "";
user.updated_at.value = "";
setEconomicData(economicFields);
user.permissions.value = [];
user.attributes.value = [];
user.discounts.value = [];
user.orders_not_invoiced.value = [];
user.keys.value = defaultKeys();
user.wash_subscription_transactions.value = [];
selectedUserLoaded.value = false;
};
export const setUser = (id) => {
const normalizedId = normalizeUserId(id);
if (!normalizedId) {
userLoadError.value = new Error("Invalid user id");
resetUser();
return Promise.resolve(null);
}
if (userId.value !== normalizedId) {
resetUser();
userId.value = normalizedId;
}
return getUserData(normalizedId);
};
userId.value = id;
// Load the user data
getUserData();
}
export const onUserChange = (callback) => {
watch(userId, (newValue) => {
@@ -93,89 +17,48 @@ export const onUserChange = (callback) => {
callback(newValue);
}
});
};
}
export const getUserCustomerNumber = () => {
return user.customer_number.value;
};
const applyUserData = (data = {}) => {
user.id.value = data.id ?? "";
user.customer_number.value = data.customer_number ?? "";
user.display_name.value = data.display_name ?? "";
user.email.value = data.email ?? "";
user.phone.value = data.phone ?? null;
user.group_id.value = data.group_id ?? "";
user.created_at.value = data.created_at ?? "";
user.updated_at.value = data.updated_at ?? "";
setEconomicData(data.economic_customer ?? {});
user.permissions.value = Array.isArray(data.permissions) ? data.permissions : [];
user.attributes.value = Array.isArray(data.attributes) ? data.attributes : [];
user.discounts.value = Array.isArray(data.discounts) ? data.discounts : [];
user.orders_not_invoiced.value = Array.isArray(data.orders_not_invoiced) ? data.orders_not_invoiced : [];
user.keys.value = data.keys && typeof data.keys === "object" ? { ...defaultKeys(), ...data.keys } : defaultKeys();
user.wash_subscription_transactions.value = Array.isArray(data.wash_subscription_transactions)
? data.wash_subscription_transactions
: [];
selectedUserLoaded.value = true;
};
}
// Get the user data
export const getUserData = async (id = userId.value) => {
const normalizedId = normalizeUserId(id);
if (!normalizedId) {
userLoadError.value = new Error("Invalid user id");
resetUser();
return null;
}
if (activeLoadPromise && activeLoadUserId === normalizedId) {
return activeLoadPromise;
}
const requestId = ++loadRequestSequence;
activeLoadUserId = normalizedId;
isUserLoading.value = true;
userLoadError.value = null;
activeLoadPromise = authenticatedRequest(`/superuser/user?user_id=${normalizedId}`, "GET")
export const getUserData = async () => {
return await authenticatedRequest(`/superuser/user?user_id=${userId.value}`, "GET")
.then((response) => {
if (requestId !== loadRequestSequence) {
return user;
user.id.value = response.data.data.id;
user.customer_number.value = response.data.data.customer_number;
user.group_id.value = response.data.data.group_id;
user.created_at.value = response.data.data.created_at;
user.updated_at.value = response.data.data.updated_at;
if (response.data.data.economic_customer.name) {
user.economicData.customerNumber.value = response.data.data.economic_customer.customerNumber;
user.economicData.name.value = response.data.data.economic_customer.name;
user.economicData.address.value = response.data.data.economic_customer.address;
user.economicData.zip.value = response.data.data.economic_customer.zip;
user.economicData.city.value = response.data.data.economic_customer.city;
user.economicData.mobilePhone.value = response.data.data.economic_customer.mobilePhone;
user.economicData.email.value = response.data.data.economic_customer.email;
user.economicData.cvr.value = response.data.data.economic_customer.corporateIdentificationNumber;
user.economicData.currency.value = response.data.data.economic_customer.currency;
user.economicData.country.value = response.data.data.economic_customer.country;
user.economicData.barred.value = response.data.data.economic_customer.barred ?? false;
}
applyUserData(response?.data?.data ?? {});
return user;
user.permissions.value = response.data.data.permissions;
user.attributes.value = response.data.data.attributes;
user.discounts.value = response.data.data.discounts;
user.orders_not_invoiced.value = response.data.data.orders_not_invoiced || null;
user.keys.value = response.data.data.keys;
user.wash_subscription_transactions.value = response.data.data.wash_subscription_transactions || null;
console.log(user.discounts.value);
})
.catch((error) => {
if (requestId === loadRequestSequence) {
resetUser({ preserveUserId: true });
userLoadError.value = error;
}
return null;
})
.finally(() => {
if (requestId === loadRequestSequence) {
isUserLoading.value = false;
activeLoadPromise = null;
activeLoadUserId = null;
}
console.error(error);
});
return activeLoadPromise;
};
const isDirectProductDiscount = (discount, productId) => {
return discount?.product_or_category_id == productId && Number(discount?.is_category) === 0;
};
const parseFixedPriceValue = (value) => {
if (value === null || value === undefined || value === '') {
return null;
}
const parsed = Number.parseInt(String(value), 10);
return Number.isFinite(parsed) ? parsed : null;
};
/** Get user product discount */
@@ -250,25 +133,12 @@ export const getUserProductOnlyDiscount = (product) => {
// Find the discount for the product
let discount = null;
try {
discount = user.discounts.value.find(discount => isDirectProductDiscount(discount, productId)) || null;
discount = user.discounts.value.find(discount => discount.product_or_category_id == productId && !discount.is_category) || null;
} catch (e) {}
// If the discount is not found, return 0
return discount ? discount.percentage : 0;
};
export const getUserProductFixedPrice = (product) => {
const productId = product.id;
let fixedPriceDiscount = null;
try {
fixedPriceDiscount = user.discounts.value.find((discount) => (
isDirectProductDiscount(discount, productId) && parseFixedPriceValue(discount.fixed_price) !== null
)) || null;
} catch (e) {}
return fixedPriceDiscount ? parseFixedPriceValue(fixedPriceDiscount.fixed_price) : null;
};
export const isProductAllowedToApplyCategoryDiscounts = (product) => {
// Check if the product is allowed to apply category discounts
return parseInt(product.apply_category_discount) === 1;
@@ -296,27 +166,9 @@ export const getProductBestApplicableDiscount = (product) => {
return Math.max(productDiscount, categoryDiscount, globalDiscount);
}
export const getProductEffectivePrice = (product) => {
const fixedPrice = getUserProductFixedPrice(product);
if (fixedPrice !== null) {
return fixedPrice;
}
const basePrice = Number(product.price ?? 0);
const discount = Number(getProductBestApplicableDiscount(product) || 0);
if (!Number.isFinite(basePrice)) {
return 0;
}
return Number((basePrice - (basePrice * (discount / 100))).toFixed(0));
}
export const user = {
id: ref(''),
customer_number: ref(''),
display_name: ref(''),
email: ref(''),
phone: ref(null),
group_id: ref(''),
created_at: ref(''),
updated_at: ref(''),
@@ -333,23 +185,23 @@ export const user = {
country: ref(null),
barred: ref(null),
},
permissions: ref([]),
attributes: ref([]),
discounts: ref([]),
orders_not_invoiced: ref([]),
keys: ref(defaultKeys()),
wash_subscription_transactions: ref([]),
permissions: ref(null),
attributes: ref(null),
discounts: ref(null),
orders_not_invoiced: ref(null),
keys: ref({
open_invoice_draft: ref(null),
}),
wash_subscription_transactions: ref(null),
functions: {
getUserData: getUserData,
getUserProductDiscount: getUserProductDiscount,
getUserCategoryDiscount: getUserCategoryDiscount,
getUserGlobalDiscount: getUserGlobalDiscount,
getUserProductOnlyDiscount: getUserProductOnlyDiscount,
getUserProductFixedPrice: getUserProductFixedPrice,
isProductAllowedToApplyCategoryDiscounts: isProductAllowedToApplyCategoryDiscounts,
getProductCategory: getProductCategory,
getProductBestApplicableDiscount: getProductBestApplicableDiscount,
getProductEffectivePrice: getProductEffectivePrice,
},
};
</script>
@@ -1,506 +1,133 @@
<script setup>
import { computed, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useRoute } from "vue-router";
import ActionSettingsWheelButton from "@/components/displays/buttons/ActionSettingsWheelButton.vue";
import PageTitle from "@/components/global/PageTitle.vue";
import RestrictedPageWrapper from "@/components/page/wrappers/RestrictedPageWrapper.vue";
import { SessionUser } from "@/components/session/token/SessionUser.vue";
import { useRouter } from 'vue-router'
import UserSubPageWrapper from "@/views/dashboards/superUserDashboard/user/UserSubPageWrapper.vue";
import {
isUserLoading,
selectedUserLoaded,
setUser,
user,
userId,
userLoadError,
} from "@/views/dashboards/superUserDashboard/user/SuperUserSelectedUserObject.vue";
import UserDefaultDepartment from "@/views/dashboards/superUserDashboard/user/displays/UserDefaultDepartment.vue";
// Get the user from the route
const router = useRouter()
import {user, getUserData, userId, setUser} from "@/views/dashboards/superUserDashboard/user/SuperUserSelectedUserObject.vue";
import WhiteBox from "@/components/displays/boxes/WhiteBox.vue";
import UserVehicleSubscriptionsDisplay
from "@/views/dashboards/superUserDashboard/user/displays/vehicles/UserVehicleSubscriptionsDisplay.vue";
import ActionSettingsWheelButton from "@/components/displays/buttons/ActionSettingsWheelButton.vue";
import UserFixedPricing from "@/views/dashboards/superUserDashboard/user/displays/UserFixedPricing.vue";
import UserOtherSpecialArrangement from "@/views/dashboards/superUserDashboard/user/displays/other/UserOtherSpecialArrangement.vue";
import UserOtherVaskeabonnement from "@/views/dashboards/superUserDashboard/user/displays/other/UserOtherVaskeabonnement.vue";
import UserVehicleSubscriptionsDisplay from "@/views/dashboards/superUserDashboard/user/displays/vehicles/UserVehicleSubscriptionsDisplay.vue";
import UserDefaultDepartment from "@/views/dashboards/superUserDashboard/user/displays/UserDefaultDepartment.vue";
const route = useRoute();
const { t } = useI18n();
// Set the user
setUser(router.currentRoute.value.params.userId);
const vehicles = ref([]);
const vehiclesLoading = ref(false);
const vehiclesError = ref(null);
const customerNumber = computed(() => Number.parseInt(String(user.customer_number.value || 0), 10) || 0);
const basePath = computed(() => `/superuser/users/${userId.value || route.params.userId}`);
const permissions = computed(() => (Array.isArray(user.permissions.value) ? user.permissions.value : []));
const attributes = computed(() => (Array.isArray(user.attributes.value) ? user.attributes.value : []));
const discounts = computed(() => (Array.isArray(user.discounts.value) ? user.discounts.value : []));
const ordersNotInvoiced = computed(() =>
Array.isArray(user.orders_not_invoiced.value) ? user.orders_not_invoiced.value : []
);
const washSubscriptionTransactions = computed(() =>
Array.isArray(user.wash_subscription_transactions.value) ? user.wash_subscription_transactions.value : []
);
const displayName = computed(() => {
return (
user.economicData.name.value ||
user.display_name.value ||
(userId.value ? `${t("user_admin.user_id")} ${userId.value}` : t("user_admin.overview.loading_user"))
);
});
const hasCustomerNumber = computed(() => customerNumber.value > 0);
const hasEconomicData = computed(() => Boolean(user.economicData.name.value || user.economicData.customerNumber.value));
const isEconomicBarred = computed(() => [true, 1, "1", "true"].includes(user.economicData.barred.value));
const activeVehicleSubscriptions = computed(() => vehicles.value.filter((vehicle) => vehicle?.wash_subscription).length);
const selfServiceVehicles = computed(() => vehicles.value.filter((vehicle) => vehicle?.xlvask).length);
const visibleVehicles = computed(() => vehicles.value.slice(0, 8));
const visiblePermissions = computed(() => permissions.value.slice(0, 12));
const hiddenPermissionCount = computed(() => Math.max(permissions.value.length - visiblePermissions.value.length, 0));
const userDetails = computed(() => [
{ label: t("user_admin.user_id"), value: userId.value },
{ label: t("user_admin.customer_number"), value: customerNumber.value || null },
{ label: t("user_admin.group_id"), value: user.group_id.value },
{ label: t("common.email"), value: user.email?.value || user.economicData.email.value },
{ label: t("common.created"), value: user.created_at.value },
{ label: t("user_admin.updated_at"), value: user.updated_at.value },
]);
const economicDetails = computed(() => [
{ label: t("user_admin.customer_number"), value: user.economicData.customerNumber.value },
{ label: t("common.name"), value: user.economicData.name.value },
{ label: t("common.address"), value: user.economicData.address.value },
{ label: t("user_admin.zip"), value: user.economicData.zip.value },
{ label: t("user_admin.city"), value: user.economicData.city.value },
{ label: t("user_admin.mobile_phone"), value: user.economicData.mobilePhone.value },
{ label: t("common.email"), value: user.economicData.email.value },
{ label: t("user_admin.cvr"), value: user.economicData.cvr.value },
{ label: t("user_admin.currency"), value: user.economicData.currency.value },
{ label: t("common.country"), value: user.economicData.country.value },
{ label: t("user_admin.barred"), value: isEconomicBarred.value ? t("common.yes") : t("common.no") },
]);
const overviewMetrics = computed(() => [
{
key: "customer",
icon: "fas fa-id-card",
label: t("user_admin.customer_number"),
value: customerNumber.value || t("global.no_data"),
status: hasCustomerNumber.value ? t("common.active") : t("user_admin.overview.missing"),
tone: hasCustomerNumber.value ? "is-success" : "is-warning",
},
{
key: "economic",
icon: "fas fa-building",
label: t("user_admin.economic_data"),
value: hasEconomicData.value ? t("user_admin.overview.connected") : t("global.no_data"),
status: isEconomicBarred.value ? t("user_admin.barred") : t("common.active"),
tone: isEconomicBarred.value ? "is-danger" : "is-success",
},
{
key: "vehicles",
icon: "fas fa-car",
label: t("common.vehicles"),
value: vehicles.value.length,
status: vehiclesLoading.value ? t("common.loading") : t("user_admin.overview.loaded"),
tone: vehiclesError.value ? "is-warning" : "is-info",
},
{
key: "subscriptions",
icon: "fas fa-car-side",
label: t("user_admin.wash_subscriptions"),
value: activeVehicleSubscriptions.value,
status: t("user_admin.overview.active_vehicles"),
tone: activeVehicleSubscriptions.value > 0 ? "is-success" : "is-light",
},
{
key: "orders",
icon: "fas fa-file-invoice-dollar",
label: t("user_admin.overview.not_invoiced"),
value: ordersNotInvoiced.value.length,
status: user.keys.value?.open_invoice_draft ? t("user_admin.overview.open_draft") : t("global.no_data"),
tone: ordersNotInvoiced.value.length > 0 ? "is-warning" : "is-success",
},
{
key: "discounts",
icon: "fas fa-tags",
label: t("common.discount"),
value: discounts.value.length,
status: t("user_admin.overview.price_overrides"),
tone: discounts.value.length > 0 ? "is-link" : "is-light",
},
{
key: "attributes",
icon: "fas fa-sliders-h",
label: t("user_admin.overview.attributes"),
value: attributes.value.length,
status: t("user_admin.overview.customer_rules"),
tone: attributes.value.length > 0 ? "is-info" : "is-light",
},
{
key: "permissions",
icon: "fas fa-shield-alt",
label: t("user_admin.permissions"),
value: permissions.value.length,
status: t("user_admin.overview.effective_access"),
tone: permissions.value.length > 0 ? "is-info" : "is-warning",
},
]);
const hubLinks = computed(() => [
{ key: "orders", icon: "fas fa-file-alt", label: t("superuser.nav.orders"), to: `${basePath.value}/orders` },
{ key: "pricing", icon: "fas fa-tags", label: t("user_admin.overview.pricing"), to: `${basePath.value}/pricing` },
{ key: "other", icon: "fas fa-sliders-h", label: t("user_admin.other"), to: `${basePath.value}/other` },
{ key: "vehicles", icon: "fas fa-car", label: t("common.vehicles"), to: `${basePath.value}/vehicles` },
{
key: "xlvask",
icon: "fas fa-water",
label: SessionUser.superUser.modules.xlvask.meta.title,
to: `${basePath.value}/xlvask`,
},
]);
const valueOrEmpty = (value) => {
if (value === null || value === undefined || value === "") {
return t("global.no_data");
}
return value;
};
const loadVehicles = async () => {
if (!hasCustomerNumber.value) {
vehicles.value = [];
vehiclesError.value = null;
return;
}
vehiclesLoading.value = true;
vehiclesError.value = null;
try {
const response = await SessionUser.objects.vehicles.get.user(customerNumber.value);
vehicles.value = Array.isArray(response) ? response : [];
} catch (error) {
vehicles.value = [];
vehiclesError.value = error;
} finally {
vehiclesLoading.value = false;
}
};
const reloadOverview = async () => {
await setUser(route.params.userId);
await loadVehicles();
};
watch(
customerNumber,
() => {
loadVehicles();
},
{ immediate: true }
);
</script>
<template>
<RestrictedPageWrapper :hasPermission="SessionUser.canAccessSuperUser()">
<UserSubPageWrapper>
<template #title>
<PageTitle :title="$t('user_admin.title')" :subtitle="$t('user_admin.overview.subtitle')" />
<PageTitle :title="$t('user_admin.title')" :subtitle="$t('user_admin.subtitle')" />
</template>
<section class="user-overview" data-testid="superuser-user-overview-page">
<div v-if="isUserLoading && !selectedUserLoaded" class="box" data-testid="superuser-user-overview-loading">
<p class="has-text-weight-semibold">{{ $t("user_admin.overview.loading_user") }}</p>
<p class="has-text-grey">{{ $t("user_admin.orders.loading_subtitle") }}</p>
</div>
<div v-else-if="userLoadError" class="notification is-danger" data-testid="superuser-user-overview-error">
<p class="has-text-weight-semibold">{{ $t("user_admin.overview.load_failed") }}</p>
<p>{{ userLoadError?.response?.data?.message || userLoadError?.message || $t("common.unknown_error") }}</p>
<button class="button is-light mt-3" type="button" data-testid="superuser-user-overview-retry" @click="reloadOverview">
{{ $t("common.retry") }}
</button>
</div>
<template v-else-if="selectedUserLoaded">
<div class="user-overview__header box" data-testid="superuser-user-overview-header">
<div>
<p class="heading">{{ $t("user_admin.overview.management_hub") }}</p>
<h2 class="title is-3 mb-2">{{ displayName }}</h2>
<p class="subtitle is-6 mb-0">
{{ $t("user_admin.user_id") }} {{ userId }}
<span v-if="hasCustomerNumber">&middot; {{ $t("user_admin.customer_number") }} {{ customerNumber }}</span>
</p>
</div>
<div class="user-overview__header-actions">
<ActionSettingsWheelButton
:user_id="userId"
:customer_number="customerNumber || null"
data-testid="superuser-user-overview-actions"
/>
</div>
</div>
<div class="user-overview__metrics columns is-multiline" data-testid="superuser-user-overview-metrics">
<div v-for="metric in overviewMetrics" :key="metric.key" class="column is-3-desktop is-6-tablet">
<div class="box user-overview__metric" :data-testid="`superuser-user-overview-metric-${metric.key}`">
<div class="user-overview__metric-top">
<span class="icon"><i :class="metric.icon"></i></span>
<span class="tag is-light" :class="metric.tone">{{ metric.status }}</span>
</div>
<p class="heading">{{ metric.label }}</p>
<p class="title is-4">{{ metric.value }}</p>
</div>
</div>
</div>
<div class="box" data-testid="superuser-user-overview-shortcuts">
<div class="level is-mobile user-overview__section-title">
<div class="level-left">
<h3 class="title is-5 mb-0">{{ $t("user_admin.overview.workspace_shortcuts") }}</h3>
</div>
</div>
<div class="buttons">
<router-link
v-for="link in hubLinks"
:key="link.key"
class="button is-light"
:to="link.to"
:data-testid="`superuser-user-overview-link-${link.key}`"
>
<span class="icon"><i :class="link.icon"></i></span>
<span>{{ link.label }}</span>
</router-link>
</div>
</div>
<div class="columns is-multiline">
<div class="column is-6-desktop">
<section class="box" data-testid="superuser-user-overview-account">
<h3 class="title is-5">{{ $t("user_admin.user_data") }}</h3>
<dl class="user-overview__details">
<template v-for="detail in userDetails" :key="detail.label">
<dt>{{ detail.label }}</dt>
<dd>{{ valueOrEmpty(detail.value) }}</dd>
</template>
</dl>
</section>
</div>
<div class="column is-6-desktop">
<section class="box" data-testid="superuser-user-overview-economic">
<h3 class="title is-5">{{ $t("user_admin.economic_data") }}</h3>
<dl class="user-overview__details">
<template v-for="detail in economicDetails" :key="detail.label">
<dt>{{ detail.label }}</dt>
<dd>{{ valueOrEmpty(detail.value) }}</dd>
</template>
</dl>
</section>
</div>
</div>
<div class="columns is-multiline">
<div class="column is-6-desktop">
<section class="box" data-testid="superuser-user-overview-access">
<h3 class="title is-5">{{ $t("user_admin.permissions") }}</h3>
<div v-if="visiblePermissions.length" class="tags">
<span
v-for="permission in visiblePermissions"
:key="permission"
class="tag is-info is-light"
:data-testid="`superuser-user-overview-permission-${permission}`"
>
{{ permission }}
</span>
<span v-if="hiddenPermissionCount > 0" class="tag">
{{ $t("user_admin.overview.more_permissions", { count: hiddenPermissionCount }) }}
</span>
</div>
<p v-else class="has-text-grey">{{ $t("global.no_data") }}</p>
</section>
</div>
<div class="column is-6-desktop">
<section class="box" data-testid="superuser-user-overview-rules">
<h3 class="title is-5">{{ $t("user_admin.overview.customer_rules") }}</h3>
<ActionSettingsWheelButton
v-if="hasCustomerNumber"
:user_id="userId"
:customer_number="customerNumber"
:display-actions-directly="true"
data-testid="superuser-user-overview-direct-actions"
/>
<p v-else class="has-text-grey">{{ $t("user_admin.overview.customer_number_required") }}</p>
</section>
</div>
</div>
<section v-if="hasCustomerNumber" class="box" data-testid="superuser-user-overview-customer-management">
<h3 class="title is-5">{{ $t("user_admin.overview.customer_management") }}</h3>
<div class="columns is-multiline">
<div class="column is-6-desktop">
<UserFixedPricing :key="`fixed-${customerNumber}`" :customer_number="customerNumber" />
</div>
<div class="column is-6-desktop">
<UserDefaultDepartment :key="`department-${customerNumber}`" :customer_number="customerNumber" />
</div>
<div class="column is-6-desktop">
<UserOtherSpecialArrangement :key="`special-${userId}`" :user_id="userId" />
</div>
<div class="column is-6-desktop">
<UserOtherVaskeabonnement :key="`subscription-note-${userId}`" :user_id="userId" />
</div>
</div>
</section>
<section v-else class="notification is-warning" data-testid="superuser-user-overview-no-customer-number">
{{ $t("user_admin.overview.customer_number_required") }}
</section>
<section v-if="hasCustomerNumber" class="box" data-testid="superuser-user-overview-vehicles">
<div class="level is-mobile user-overview__section-title">
<div class="level-left">
<h3 class="title is-5 mb-0">{{ $t("common.vehicles") }}</h3>
</div>
<div class="level-right">
<button
class="button is-small is-light"
type="button"
:disabled="vehiclesLoading"
data-testid="superuser-user-overview-vehicles-reload"
@click="loadVehicles"
>
{{ $t("global.reload") }}
</button>
</div>
</div>
<div v-if="vehiclesError" class="notification is-warning" data-testid="superuser-user-overview-vehicles-error">
{{ $t("user_admin.overview.vehicles_load_failed") }}
</div>
<div class="columns is-multiline">
<div class="column is-4">
<div class="box user-overview__compact-stat">
<p class="heading">{{ $t("common.vehicles") }}</p>
<p class="title is-4">{{ vehicles.length }}</p>
</div>
</div>
<div class="column is-4">
<div class="box user-overview__compact-stat">
<p class="heading">{{ $t("user_admin.wash_subscriptions") }}</p>
<p class="title is-4">{{ activeVehicleSubscriptions }}</p>
</div>
</div>
<div class="column is-4">
<div class="box user-overview__compact-stat">
<p class="heading">{{ SessionUser.superUser.modules.xlvask.meta.title }}</p>
<p class="title is-4">{{ selfServiceVehicles }}</p>
</div>
</div>
</div>
<div v-if="visibleVehicles.length" class="tags" data-testid="superuser-user-overview-vehicle-preview">
<span
v-for="vehicle in visibleVehicles"
:key="vehicle.id || vehicle.reg"
class="tag is-light"
:data-testid="`superuser-user-overview-vehicle-${vehicle.id || vehicle.reg}`"
>
{{ vehicle.reg || vehicle.reference || `#${vehicle.id}` }}
<div class="columns is-multiline">
<!-- Customer small -->
<div class="column is-12">
<div class="card">
<div class="card-header">
<!-- User icon -->
<div class="card-header-icon">
<span class="icon">
<i class="fas fa-user"></i>
</span>
</div>
<p v-else-if="!vehiclesLoading" class="has-text-grey">{{ $t("global.no_data") }}</p>
<div class="buttons">
<router-link class="button is-light" :to="`${basePath}/vehicles`" data-testid="superuser-user-overview-open-vehicles">
<span class="icon"><i class="fas fa-list"></i></span>
<span>{{ $t("user_admin.overview.open_vehicles") }}</span>
</router-link>
<button
class="button is-light"
type="button"
data-testid="superuser-user-overview-add-vehicle"
@click="SessionUser.objects.vehicles.functions.showCreateObjectForCustomerForm(customerNumber, loadVehicles)"
>
<span class="icon"><i class="fas fa-plus"></i></span>
<span>{{ $t("user_vehicles.add_vehicle") }}</span>
</button>
<!-- User name -->
<div class="card-header-title">
{{ user.economicData.name }}
</div>
</section>
<section v-if="hasCustomerNumber" class="box" data-testid="superuser-user-overview-subscriptions">
<h3 class="title is-5">{{ $t("user_admin.overview.subscription_invoicing") }}</h3>
<UserVehicleSubscriptionsDisplay :key="`subscriptions-${customerNumber}`" :user="user" />
<p v-if="washSubscriptionTransactions.length === 0" class="has-text-grey">
{{ $t("user_admin.overview.no_subscription_transactions") }}
</p>
</section>
</template>
</section>
<!-- User settings wheel -->
<div class="card-header-icon">
<ActionSettingsWheelButton
:user_id="userId"
>
<template #actions>
<!-- Since there's no additional actions, we can use the default slot -->
</template>
</ActionSettingsWheelButton>
</div>
</div>
</div>
</div>
<div class="column is-12">
<div class="box">
<!-- User fixed pricing -->
<div class="mb-2">
<UserFixedPricing v-if="user.customer_number.value && user.customer_number.value > 0" v-bind:customer_number="user.customer_number.value" />
</div>
<!-- Default department -->
<div class="mb-2">
<UserDefaultDepartment v-if="user.customer_number.value && user.customer_number.value > 0" v-bind:customer_number="user.customer_number.value" />
</div>
<!-- Vehicle subscriptions -->
<UserVehicleSubscriptionsDisplay
v-if="user.customer_number.value && user.customer_number.value > 0"
:user="user"
/>
</div>
</div>
<div class="column is-6">
<div class="box">
<h3 class="title is-4">{{ $t('user_admin.user_data') }}</h3>
<div class="content">
<p>{{ $t('user_admin.user_id') }}: {{ userId }}</p>
<p>{{ $t('user_admin.customer_number') }}: {{ user.customer_number }}</p>
<p>{{ $t('user_admin.group_id') }}: {{ user.group_id }}</p>
<p>{{ $t('common.created') }}: {{ user.created_at }}</p>
<p>{{ $t('user_admin.updated_at') }}: {{ user.updated_at }}</p>
</div>
</div>
</div>
<!-- Economic data -->
<div class="column is-6">
<div class="box">
<h3 class="title is-4">{{ $t('user_admin.economic_data') }} ({{ user.economicData.name ? user.economicData.name : $t('user_admin.no_data') }})</h3>
<div class="content">
<p>{{ $t('user_admin.customer_number') }}: {{ user.economicData.customerNumber }}</p>
<p>{{ $t('common.name') }}: {{ user.economicData.name }}</p>
<p>{{ $t('common.address') }}: {{ user.economicData.address }}</p>
<p>{{ $t('user_admin.zip') }}: {{ user.economicData.zip }}</p>
<p>{{ $t('user_admin.city') }}: {{ user.economicData.city }}</p>
<p>{{ $t('user_admin.mobile_phone') }}: {{ user.economicData.mobilePhone }}</p>
<p>{{ $t('common.email') }}: {{ user.economicData.email }}</p>
<p>{{ $t('user_admin.cvr') }}: {{ user.economicData.cvr }}</p>
<p>{{ $t('user_admin.currency') }}: {{ user.economicData.currency }}</p>
<p>{{ $t('common.country') }}: {{ user.economicData.country }}</p>
<p>{{ $t('user_admin.barred') }}: {{user.economicData.barred }}</p>
</div>
</div>
</div>
<!-- Permissions -->
<div class="column is-12">
<div class="box">
<h3 class="title is-4">{{ $t('user_admin.permissions') }}</h3>
<div class="content">
<ul>
<li v-for="permission in user.permissions.value" :key="permission.id">{{ permission }}</li>
</ul>
</div>
</div>
</div>
<!-- Variables -->
<div class="column is-12">
<div class="box">
<h3 class="title is-4">{{ $t('user_admin.variables') }}</h3>
<div class="content">
<p>SessionUser: {{ SessionUser.valueOf() }}</p>
<p>userId: {{ userId }}</p>
<p>user: {{ user.valueOf() }}</p>
</div>
</div>
</div>
</div>
</UserSubPageWrapper>
</RestrictedPageWrapper>
</template>
<style scoped>
.user-overview {
padding-bottom: 2rem;
}
.user-overview__header {
align-items: flex-start;
display: flex;
gap: 1rem;
justify-content: space-between;
}
.user-overview__header-actions {
flex: 0 0 auto;
}
.user-overview__metric,
.user-overview__compact-stat {
height: 100%;
}
.user-overview__metric-top {
align-items: center;
display: flex;
justify-content: space-between;
margin-bottom: 0.75rem;
}
.user-overview__details {
display: grid;
gap: 0.5rem 1rem;
grid-template-columns: minmax(8rem, 38%) 1fr;
}
.user-overview__details dt {
color: #6b7280;
font-weight: 600;
}
.user-overview__details dd {
margin: 0;
min-width: 0;
overflow-wrap: anywhere;
}
.user-overview__section-title {
margin-bottom: 1rem;
}
@media screen and (max-width: 768px) {
.user-overview__header {
display: block;
}
.user-overview__header-actions {
margin-top: 1rem;
}
.user-overview__details {
grid-template-columns: 1fr;
}
}
</style>
</style>
@@ -3,7 +3,7 @@
import UserSubPageWrapper from "@/views/dashboards/superUserDashboard/user/UserSubPageWrapper.vue";
import PageTitle from "@/components/global/PageTitle.vue";
import { useRouter } from 'vue-router'
import { user, getUserData, userId, setUser, getUserProductDiscount, getUserGlobalDiscount, getProductBestApplicableDiscount, getUserProductOnlyDiscount, getUserProductFixedPrice, getProductEffectivePrice, getProductCategory, getUserCategoryDiscount, isProductAllowedToApplyCategoryDiscounts } from "@/views/dashboards/superUserDashboard/user/SuperUserSelectedUserObject.vue";
import { user, getUserData, userId, setUser, getUserProductDiscount, getUserGlobalDiscount, getProductBestApplicableDiscount, getUserProductOnlyDiscount, getProductCategory, getUserCategoryDiscount, isProductAllowedToApplyCategoryDiscounts } from "@/views/dashboards/superUserDashboard/user/SuperUserSelectedUserObject.vue";
import { getProducts } from "@/components/shop/Products.vue";
import { ref } from 'vue';
import { authenticatedRequest } from "@/components/session/authenticatedRequest.vue";
@@ -56,72 +56,6 @@ const editDiscount = (product, isCategory) => {
allowOutsideClick: () => !Swal.isLoading()
});
}
const formatPrice = (price) => `${Number(price || 0).toFixed(0)} Kr.`;
const getProductPriceDisplay = (product) => {
const fixedPrice = getUserProductFixedPrice(product);
if (fixedPrice !== null) {
return `${formatPrice(fixedPrice)} (fast pris)`;
}
const discount = getProductBestApplicableDiscount(product);
if (discount === 0) {
return formatPrice(product.price);
}
return `${formatPrice(getProductEffectivePrice(product))} (${discount}% rabat)`;
};
const editFixedPrice = (product) => {
const fixedPrice = getUserProductFixedPrice(product);
Swal.fire({
title: product.name + ' ( product: ' + product.id + ' )',
input: 'number',
inputValue: fixedPrice === null ? '' : fixedPrice,
inputLabel: 'Fast pris (Kr.)',
inputAttributes: {
autocapitalize: 'off',
min: 0,
step: 1
},
showCancelButton: true,
confirmButtonText: 'Save',
showLoaderOnConfirm: true,
inputValidator: (value) => {
const normalizedValue = String(value ?? '').trim();
if (normalizedValue === '') {
return null;
}
const parsedValue = Number(normalizedValue);
if (!Number.isInteger(parsedValue) || parsedValue < 0) {
return 'Fast pris skal være et heltal eller tom.';
}
return null;
},
preConfirm: (value) => {
const normalizedValue = String(value ?? '').trim();
const fixedPriceValue = normalizedValue === '' ? null : Number.parseInt(normalizedValue, 10);
return authenticatedRequest(`/superuser/user/discounts`, "POST", {
user_id: userId.value,
object_id: product.id,
discount: getUserProductOnlyDiscount(product),
fixed_price: fixedPriceValue,
is_category: false
})
.then((response) => {
console.log(response);
getUserData();
})
.catch((error) => {
console.log(error);
});
},
allowOutsideClick: () => !Swal.isLoading()
});
}
</script>
<template>
@@ -140,7 +74,6 @@ const editFixedPrice = (product) => {
<th>{{ $t('tables.common.category') }}</th>
<th>{{ $t('tables.common.product_name') }}</th>
<th>{{ $t('tables.common.price') }}</th>
<th>Fast pris</th>
<th>{{ $t('tables.common.discount_item') }}</th>
<th>{{ $t('tables.common.discount_category') }}</th>
</tr>
@@ -151,16 +84,8 @@ const editFixedPrice = (product) => {
<td>{{ getProductCategory(product)}}</td>
<td>{{ product.name }}</td>
<!-- Price -->
<td>{{ getProductPriceDisplay(product) }}</td>
<!-- Fixed price -->
<td
class="is-clickable"
@click="editFixedPrice(product)"
:data-testid="`customer-fixed-price-${product.id}`"
><template v-if="getUserProductFixedPrice(product) !== null">{{ getUserProductFixedPrice(product) }} Kr.</template><template v-else>-</template>
<i class="is-pulled-right fas fa-edit"></i>
</td>
<td v-if="getProductBestApplicableDiscount(product) === 0">{{ product.price }} Kr.</td>
<td v-else>{{ (product.price - (product.price * (getProductBestApplicableDiscount(product) / 100))).toFixed(0) }} Kr. ({{ getProductBestApplicableDiscount(product) }}% rabat)</td>
<!-- Discount: Item -->
<td
@@ -197,4 +122,4 @@ const editFixedPrice = (product) => {
<style scoped>
</style>
</style>
@@ -1,19 +1,12 @@
<script setup>
import { watch } from "vue";
import SuperUserDashboardUserNavigation from "@/views/dashboards/superUserDashboard/user/SuperUserDashboardUserNavigation.vue";
import SuperUserDashboardNavigation from "@/views/dashboards/superUserDashboard/SuperUserDashboardNavigation.vue";
import { setUser } from "@/views/dashboards/superUserDashboard/user/SuperUserSelectedUserObject.vue";
import { useRoute } from "vue-router";
import {user, getUserData, userId, setUser, getUserCustomerNumber} from "@/views/dashboards/superUserDashboard/user/SuperUserSelectedUserObject.vue";
import {useRouter} from "vue-router";
const router = useRouter()
setUser(router.currentRoute.value.params.userId);
const route = useRoute();
watch(
() => route.params.userId,
(nextUserId) => {
setUser(nextUserId);
},
{ immediate: true }
);
</script>
<template>
@@ -28,4 +21,4 @@ watch(
<style scoped>
</style>
</style>
@@ -2,6 +2,7 @@
import { ref, computed } from 'vue';
import { SessionUser } from "@/components/session/token/SessionUser.vue";
import ConfigurationCategory from "@/components/displays/superuser/configuration/ConfigurationCategory.vue";
import ConfigurationInputNumber from "@/components/displays/superuser/configuration/ConfigurationInputNumber.vue";
import ConfigurationInput from "@/components/displays/superuser/configuration/ConfigurationInput.vue";
import Swal from "sweetalert2";
import ConfigurationSelect from "@/components/displays/superuser/configuration/ConfigurationSelect.vue";
@@ -25,6 +26,7 @@ const getDefaultDepartment = async () => {
customer_number: props.customer_number,
}).then((response) => {
let responseData = response.data.data;
console.log(response.data.data, 'Default department');
department_value.value = responseData.department;
hasDefaultDepartment.value = true;
}).catch((error) => {
@@ -38,7 +40,8 @@ const onClickSubmit = async () => {
await SessionUser.request('/customer/department/default', 'POST', {
customer_number: props.customer_number,
department: department_value.value,
}).then(() => {
}).then((response) => {
console.log(response.data.data, 'Created default department');
// Get the newly created fixed pricing
getDefaultDepartment();
}).catch((error) => {
@@ -72,7 +75,8 @@ const onDeleteConfirmed = async () => {
// Delete the fixed pricing
await SessionUser.request('/customer/department/default', 'DELETE', {
customer_number: props.customer_number,
}).then(() => {
}).then((response) => {
console.log(response.data.data, 'Deleted default department');
// Get the newly created fixed pricing
getDefaultDepartment();
}).catch((error) => {
@@ -159,4 +163,4 @@ getDepartmentOptions();
<style scoped>
</style>
</style>
@@ -2,6 +2,7 @@
import { ref, computed } from 'vue';
import { SessionUser } from "@/components/session/token/SessionUser.vue";
import ConfigurationCategory from "@/components/displays/superuser/configuration/ConfigurationCategory.vue";
import ConfigurationInputNumber from "@/components/displays/superuser/configuration/ConfigurationInputNumber.vue";
import ConfigurationInput from "@/components/displays/superuser/configuration/ConfigurationInput.vue";
import Swal from "sweetalert2";
@@ -26,6 +27,8 @@ const getFixedPricing = async () => {
await SessionUser.request('/customer/pricing/fixed', 'GET', {
customer_number: props.customer_number,
}).then((response) => {
let responseData = response.data.data;
console.log(response.data.data, 'Fixed pricing');
pricing.value = response.data.data.price;
description.value = response.data.data.description;
hasFixedPricing.value = true;
@@ -41,7 +44,8 @@ const onClickSubmit = async () => {
customer_number: props.customer_number,
price: inputPrice.value,
description: inputDescription.value,
}).then(() => {
}).then((response) => {
console.log(response.data.data, 'Fixed pricing');
// Get the newly created fixed pricing
getFixedPricing();
}).catch((error) => {
@@ -77,7 +81,8 @@ const onDeleteConfirmed = async () => {
// Delete the fixed pricing
await SessionUser.request('/customer/pricing/fixed', 'DELETE', {
customer_number: props.customer_number,
}).then(() => {
}).then((response) => {
console.log(response.data.data, 'Deleted fixed pricing');
// Get the newly created fixed pricing
getFixedPricing();
}).catch((error) => {
@@ -162,4 +167,4 @@ getFixedPricing();
<style scoped>
</style>
</style>
@@ -1,8 +1,8 @@
<script setup>
import { ref, watch } from "vue";
import { ref } from 'vue';
import { SessionUser } from "@/components/session/token/SessionUser.vue";
import Swal from "sweetalert2";
import { useI18n } from "vue-i18n";
import { useI18n } from 'vue-i18n';
const { t } = useI18n();
@@ -10,73 +10,79 @@ const props = defineProps({
user_id: Number,
readOnly: {
type: Boolean,
default: false,
default: false
},
textOnly: {
type: Boolean,
default: false,
},
default: false
}
});
const OtherSpecialArrangementValue = ref(null);
const userKeys = ref({});
const showLoadError = () => {
Swal.fire({
title: t("common.error"),
text: t("common.unable_to_load"),
icon: "error",
confirmButtonText: t("common.ok"),
});
};
const showSaveError = () => {
Swal.fire({
title: t("common.error"),
text: t("common.unknown_error"),
icon: "error",
confirmButtonText: t("common.ok"),
});
};
const userKeys = ref([{
key: '',
value: ''
}]);
const getKeys = async () => {
if (!props.user_id) {
userKeys.value = {};
OtherSpecialArrangementValue.value = null;
return;
}
try {
const response = await SessionUser.request(`/superuser/user/keys?user_id=${props.user_id}`, "GET");
userKeys.value = response?.data?.data || {};
OtherSpecialArrangementValue.value = userKeys.value.OtherSpecialArrangement || null;
} catch (error) {
showLoadError();
}
// Get the special arrangement
await SessionUser.request('/superuser/user/keys?user_id=' + props.user_id, 'GET').then((response) => {
userKeys.value = response.data.data;
console.log(userKeys.value);
// Check if the key exists
try {
if (userKeys.value.OtherSpecialArrangement) {
OtherSpecialArrangementValue.value = userKeys.value.OtherSpecialArrangement;
}
} catch (e) {
console.log('Key does not exist');
}
}).catch((error) => {
Swal.fire({
title: 'Fejl',
html: '<p>Der skete en fejl ved hentning af dataen. <br>Prøv igen, eller kontakt support.</p>',
icon: 'error',
confirmButtonText: 'OK'
});
});
};
const setKey = async (key, value) => {
await SessionUser.request("/superuser/user/keys", "POST", {
// Set the key
await SessionUser.request('/superuser/user/keys', 'POST', {
user_id: props.user_id,
key: key,
value: value,
value: value
}).then((response) => {
console.log(response);
getKeys();
});
};
getKeys();
const saveForm = async () => {
if (props.readOnly) {
return;
}
// Save the form
console.log('Save the form');
await setKey('OtherSpecialArrangement', OtherSpecialArrangementValue.value ?? '').then((response) => {
console.log(response);
}).catch((error) => {
// Show the error with a sweetalert
Swal.fire({
title: 'Fejl',
html: '<p>Der skete en fejl ved gemningen af dataen. <br>Prøv igen, eller kontakt support.</p>',
icon: 'error',
confirmButtonText: 'OK'
});
});
}
try {
await setKey("OtherSpecialArrangement", OtherSpecialArrangementValue.value ?? "");
await getKeys();
} catch (error) {
showSaveError();
}
};
watch(() => props.user_id, getKeys, { immediate: true });
const parseLineBreaks = (text) => {
return text.replace(/\n/g, '<br>');
}
</script>
<template>
@@ -84,12 +90,7 @@ watch(() => props.user_id, getKeys, { immediate: true });
<div class="field">
<label class="label is-size-3">{{ t('superuser.user.special_arrangement.label') }}</label>
<div class="control">
<textarea
class="textarea"
v-model="OtherSpecialArrangementValue"
:placeholder="t('superuser.user.special_arrangement.label')"
data-testid="superuser-user-special-arrangement-input"
></textarea>
<textarea class="textarea" v-model="OtherSpecialArrangementValue" placeholder="Udfyld beskrivelse, hvis der er en intern aftale"></textarea>
</div>
</div>
<div class="field" v-if="!props.readOnly">
@@ -102,7 +103,7 @@ watch(() => props.user_id, getKeys, { immediate: true });
<div class="message is-info" v-if="OtherSpecialArrangementValue">
<div class="message-body">
<span><strong>{{ t('superuser.user.special_arrangement.label') }}</strong><br></span>
<span v-if="OtherSpecialArrangementValue" class="preserve-lines">{{ OtherSpecialArrangementValue }}</span>
<span v-if="OtherSpecialArrangementValue" v-html="parseLineBreaks(OtherSpecialArrangementValue)"></span>
</div>
</div>
</div>
@@ -116,7 +117,7 @@ watch(() => props.user_id, getKeys, { immediate: true });
<div
class="message-body"
>
<p v-if="OtherSpecialArrangementValue" class="preserve-lines">{{ OtherSpecialArrangementValue }}</p>
<p v-if="OtherSpecialArrangementValue" v-html="parseLineBreaks(OtherSpecialArrangementValue)"></p>
</div>
</div>
</div>
@@ -124,7 +125,5 @@ watch(() => props.user_id, getKeys, { immediate: true });
</template>
<style scoped>
.preserve-lines {
white-space: pre-line;
}
</style>
</style>
@@ -1,8 +1,8 @@
<script setup>
import { ref, watch } from "vue";
import { ref, watch } from 'vue';
import { SessionUser } from "@/components/session/token/SessionUser.vue";
import Swal from "sweetalert2";
import { useI18n } from "vue-i18n";
import { useI18n } from 'vue-i18n';
const { t } = useI18n();
@@ -10,86 +10,91 @@ const props = defineProps({
user_id: Number,
readOnly: {
type: Boolean,
default: false,
default: false
},
textOnly: {
type: Boolean,
default: false,
},
default: false
}
});
const OtherVaskeabonnementValue = ref(null);
const userKeys = ref({});
const showLoadError = () => {
Swal.fire({
title: t("common.error"),
text: t("common.unable_to_load"),
icon: "error",
confirmButtonText: t("common.ok"),
});
};
const showSaveError = () => {
Swal.fire({
title: t("common.error"),
text: t("common.unknown_error"),
icon: "error",
confirmButtonText: t("common.ok"),
});
};
const userKeys = ref([{
key: '',
value: ''
}]);
const getKeys = async () => {
if (!props.user_id) {
userKeys.value = {};
OtherVaskeabonnementValue.value = null;
return;
}
try {
const response = await SessionUser.request(`/superuser/user/keys?user_id=${props.user_id}`, "GET");
userKeys.value = response?.data?.data || {};
OtherVaskeabonnementValue.value = userKeys.value.OtherVaskeabonnement || null;
} catch (error) {
showLoadError();
}
// Get the special arrangement
await SessionUser.request('/superuser/user/keys?user_id=' + props.user_id, 'GET').then((response) => {
userKeys.value = response.data.data;
console.log(userKeys.value);
// Check if the key exists
try {
if (userKeys.value.OtherVaskeabonnement) {
OtherVaskeabonnementValue.value = userKeys.value.OtherVaskeabonnement;
}
} catch (e) {
console.log('Key does not exist');
}
}).catch((error) => {
Swal.fire({
title: 'Fejl',
html: '<p>Der skete en fejl ved hentning af dataen. <br>Prøv igen, eller kontakt support.</p>',
icon: 'error',
confirmButtonText: 'OK'
});
});
};
const setKey = async (key, value) => {
await SessionUser.request("/superuser/user/keys", "POST", {
// Set the key
await SessionUser.request('/superuser/user/keys', 'POST', {
user_id: props.user_id,
key: key,
value: value,
value: value
}).then((response) => {
console.log(response);
getKeys();
});
};
getKeys();
const saveForm = async () => {
if (props.readOnly) {
return;
}
// Save the form
console.log('Save the form');
await setKey('OtherVaskeabonnement', OtherVaskeabonnementValue.value ?? '').then((response) => {
console.log(response);
}).catch((error) => {
// Show the error with a sweetalert
Swal.fire({
title: 'Fejl',
html: '<p>Der skete en fejl ved gemningen af dataen. <br>Prøv igen, eller kontakt support.</p>',
icon: 'error',
confirmButtonText: 'OK'
});
});
}
try {
await setKey("OtherVaskeabonnement", OtherVaskeabonnementValue.value ?? "");
await getKeys();
} catch (error) {
showSaveError();
}
};
const parseLineBreaks = (text) => {
return text.replace(/\n/g, '<br>');
}
watch(() => props.user_id, getKeys, { immediate: true });
watch(() => props.user_id, () => {
getKeys();
});
</script>
<template>
<form class="form" @submit.prevent="saveForm" v-if="!props.readOnly && !props.textOnly">
<form class="form" @submit.prevent="saveForm" v-if="!readOnly && !textOnly">
<div class="field">
<label class="label is-size-3">{{ t('superuser.user.wash_subscription.label') }}</label>
<div class="control">
<textarea
class="textarea"
v-model="OtherVaskeabonnementValue"
:placeholder="t('superuser.user.wash_subscription.label')"
data-testid="superuser-user-wash-subscription-note-input"
></textarea>
<textarea class="textarea" v-model="OtherVaskeabonnementValue" placeholder="Udfyld beskrivelse, hvis der er en intern aftale"></textarea>
</div>
</div>
<div class="field">
@@ -102,7 +107,7 @@ watch(() => props.user_id, getKeys, { immediate: true });
<div class="message is-info" v-if="OtherVaskeabonnementValue">
<div class="message-body">
<span><strong>{{ t('superuser.user.wash_subscription.label') }}</strong><br></span>
<span v-if="OtherVaskeabonnementValue" class="preserve-lines">{{ OtherVaskeabonnementValue }}</span>
<span v-if="OtherVaskeabonnementValue" v-html="parseLineBreaks(OtherVaskeabonnementValue)"></span>
</div>
</div>
</div>
@@ -116,7 +121,7 @@ watch(() => props.user_id, getKeys, { immediate: true });
<div
class="message-body"
>
<p v-if="OtherVaskeabonnementValue" class="preserve-lines">{{ OtherVaskeabonnementValue }}</p>
<p v-if="OtherVaskeabonnementValue" v-html="parseLineBreaks(OtherVaskeabonnementValue)"></p>
</div>
</div>
</div>
@@ -124,7 +129,5 @@ watch(() => props.user_id, getKeys, { immediate: true });
</template>
<style scoped>
.preserve-lines {
white-space: pre-line;
}
</style>
</style>
@@ -35,6 +35,7 @@ const washSubscriptionVehicles = ref(null);
const load = () => {
if (!props.user.customer_number.value) {
console.log('No customer number found');
return;
}
// Load the vehicles
@@ -141,8 +142,13 @@ const showAddSubscriptionInvoiceFormOtherMonth = () => {
}).then((result) => {
if (result.isConfirmed) {
const selected = result.value;
console.log(selected);
const monthNumber = selected.substring(5, 7);
const yearNumber = selected.substring(0, 4);
// Redirect to the invoice creation page
console.log(
'Month: ' + monthNumber + ', Year: ' + yearNumber
);
createVehicleSubscriptionInvoice(monthNumber, yearNumber);
}
});
@@ -158,6 +164,7 @@ const createVehicleSubscriptionInvoice = (month, year) => {
year: year,
}
).then((response) => {
console.log(response);
// Reload the data
load();
// Redirect to the invoice creation page
@@ -1369,7 +1369,6 @@ const scheduleRecentCompletedWashRefresh = (attempt = 0) => {
}
recentCompletedRefreshTimeout.value = hostWindow.setTimeout(() => {
recentCompletedRefreshTimeout.value = null;
if (isMyWashStartUnmounted.value) {
return;
}
+4 -133
View File
@@ -4,8 +4,6 @@ import { isCompactProject } from "./support/projects";
const adminPermissions = [
"admin",
"list_department_daily_reports",
"list_bookings",
"create_department_daily_report_complaints",
"department_access_1",
"department_access_2",
@@ -28,26 +26,8 @@ const buildOverviewPayload = ({
complaintsMessage = null,
metrics = {},
products = [
{
product_id: 24,
slug: "spot-free-lastbil",
title: "Spot Free (Lastbil)",
state: "ready",
value: 3,
out_of: 8,
target_percentage: null,
target_department_id: null,
},
{
product_id: 25,
slug: "faelg-flex",
title: "Fælg flex pr. enhed",
state: "ready",
value: 2,
out_of: 8,
target_percentage: null,
target_department_id: null,
},
{ product_id: 24, slug: "spot-free-lastbil", title: "Spot Free (Lastbil)", state: "ready", value: 3, out_of: 8 },
{ product_id: 25, slug: "faelg-flex", title: "Fælg flex pr. enhed", state: "ready", value: 2, out_of: 8 },
{
product_id: 27,
slug: "extraordinary-10-min",
@@ -55,8 +35,6 @@ const buildOverviewPayload = ({
state: "ready",
value: 1,
out_of: 8,
target_percentage: null,
target_department_id: null,
},
{
product_id: 26,
@@ -65,19 +43,8 @@ const buildOverviewPayload = ({
state: "ready",
value: 4,
out_of: 8,
target_percentage: null,
target_department_id: null,
},
{
product_id: 21,
slug: "undervognsskyl",
title: "Undervognsskyl pr. enhed",
state: "ready",
value: 2,
out_of: 8,
target_percentage: null,
target_department_id: null,
},
{ product_id: 21, slug: "undervognsskyl", title: "Undervognsskyl pr. enhed", state: "ready", value: 2, out_of: 8 },
{
product_id: 22,
slug: "double-duty-kemi",
@@ -85,8 +52,6 @@ const buildOverviewPayload = ({
state: "ready",
value: 5,
out_of: 8,
target_percentage: null,
target_department_id: null,
},
],
...overrides
@@ -127,9 +92,6 @@ async function mockDailyReportDependencies(
body: Record<string, unknown>
) => Promise<ReturnType<typeof json>> | ReturnType<typeof json>;
complaintCustomerLookupHandler?: (url: URL) => Promise<ReturnType<typeof json>> | ReturnType<typeof json>;
productTargetHandler?: (
body: Record<string, unknown>
) => Promise<ReturnType<typeof json>> | ReturnType<typeof json>;
permissions?: string[];
}
| ((url: URL) => Promise<ReturnType<typeof json>> | ReturnType<typeof json>)
@@ -152,16 +114,6 @@ async function mockDailyReportDependencies(
},
}));
const complaintCustomerLookupHandler = options.complaintCustomerLookupHandler || (async () => json({ data: [] }));
const productTargetHandler =
options.productTargetHandler ||
(async (body) =>
json({
data: {
department_id: body.department_id,
product_id: body.product_id,
target_percentage: body.target_percentage ?? null,
},
}));
await seedAuthenticatedState(page);
await mockApi(page, {
@@ -215,12 +167,6 @@ async function mockDailyReportDependencies(
await route.fulfill(response);
});
await page.route(/\/departments\/daily-reports\/product-targets$/i, async (route) => {
const body = route.request().postDataJSON() as Record<string, unknown>;
const response = await productTargetHandler(body);
await route.fulfill(response);
});
await page.route(/\/departments\/daily-reports(?:\/overview)?(\?.*)?$/i, async (route) => {
const url = new URL(route.request().url());
if (url.pathname.endsWith("/departments/daily-reports/overview")) {
@@ -253,7 +199,7 @@ test.describe("Admin daily report", () => {
await page.goto("/admin/1/modules/daily-report?departmentIds=1&dateFrom=2026-03-23&dateTo=2026-03-23");
await expect(page.getByTestId("daily-report-page")).toBeVisible();
await expect(page.locator(".card[data-testid^='daily-report-tile-']")).toHaveCount(17);
await expect(page.locator("[data-testid^='daily-report-tile-']")).toHaveCount(17);
await expect(page.getByTestId("daily-report-tile-bookings")).toContainText("4");
await expect(page.getByTestId("daily-report-tile-complaints")).toContainText("2");
await expect(page.getByTestId("daily-report-complaints-add-button")).toBeVisible();
@@ -270,81 +216,6 @@ test.describe("Admin daily report", () => {
await expect(page.getByTestId("daily-report-tile-double-duty-kemi")).toContainText("Tillæg for Specialsæbe - DD");
});
test("lets permitted users set a target from an optional product percentage", async ({ page }) => {
let targetPercentage: number | null = null;
const targetRequests: Array<Record<string, unknown>> = [];
await mockDailyReportDependencies(page, {
permissions: [...adminPermissions, "set_department_daily_report_product_targets"],
overviewHandler: async () =>
json(
buildOverviewPayload({
products: [
{
product_id: 24,
slug: "spot-free-lastbil",
title: "Spot Free (Lastbil)",
state: "ready",
value: 3,
out_of: 8,
target_percentage: targetPercentage,
target_department_id: targetPercentage === null ? null : 1,
},
],
})
),
productTargetHandler: async (body) => {
targetRequests.push(body);
targetPercentage = body.target_percentage === null ? null : Number(body.target_percentage);
return json({
data: {
department_id: body.department_id,
product_id: body.product_id,
target_percentage: targetPercentage,
},
});
},
});
await page.goto("/admin/1/modules/daily-report?departmentIds=1&dateFrom=2026-03-23&dateTo=2026-03-23");
await expect(page.getByTestId("daily-report-page")).toBeVisible();
const productTile = page.getByTestId("daily-report-tile-spot-free-lastbil");
const percentageButton = page.getByTestId("daily-report-tile-spot-free-lastbil-percentage-button");
await expect(percentageButton).toBeVisible();
await expect(percentageButton).toHaveClass(/is-outlined/);
await expect(page.locator('[data-testid="daily-report-tile-spot-free-lastbil-target-button"]')).toHaveCount(0);
await percentageButton.click();
await page.getByTestId("daily-report-tile-spot-free-lastbil-target-input").fill("55.5");
await page.getByTestId("daily-report-tile-spot-free-lastbil-target-save").click();
await expect.poll(() => targetRequests.length).toBe(1);
expect(targetRequests[0]).toMatchObject({
department_id: 1,
product_id: 24,
target_percentage: 55.5,
});
await expect(page.getByTestId("daily-report-tile-spot-free-lastbil-target-button")).toContainText("55.5%");
await expect(productTile.locator(".daily-report-count__target-background-icon")).toHaveCount(1);
});
test("does not open the product target editor without permission", async ({ page }) => {
await mockDailyReportDependencies(page, {
overviewHandler: async () => json(buildOverviewPayload()),
permissions: adminPermissions,
});
await page.goto("/admin/1/modules/daily-report?departmentIds=1&dateFrom=2026-03-23&dateTo=2026-03-23");
await expect(page.getByTestId("daily-report-page")).toBeVisible();
await page.getByTestId("daily-report-tile-spot-free-lastbil-percentage-button").click();
await expect(page.locator('[data-testid="daily-report-tile-spot-free-lastbil-target-input"]')).toHaveCount(0);
await expect(page.locator('[data-testid="daily-report-tile-spot-free-lastbil-target-button"]')).toHaveCount(0);
});
test("renders rounded-up weather hours and keeps unknown productivity gray", async ({ page }) => {
await mockDailyReportDependencies(page, {
overviewHandler: async () => json(buildOverviewPayload()),
@@ -18,8 +18,6 @@ const json = (body: unknown, status = 200) => ({
});
const pageReadyTimeout = process.env.CI ? 30_000 : 15_000;
const pageBootstrapTimeoutMs = 45_000;
const setupNotificationSmsApi = async (page: Page) => {
let listRequestCount = 0;
const mutations: Array<{ method: string; body?: Record<string, unknown>; id?: number }> = [];
@@ -120,21 +118,6 @@ test("@smoke department notification SMS active toggle and delete refresh the ta
await page.goto("/admin/1/modules/notifications", { waitUntil: "domcontentloaded" });
await expect.poll(() => notificationSmsApi.listRequestCount, { timeout: pageReadyTimeout }).toBeGreaterThan(0);
const pageTitle = page.getByTestId("department-notifications-title");
await expect(pageTitle).toBeVisible({ timeout: pageBootstrapTimeoutMs });
await expect(pageTitle).toContainText(/notifikationer|notifications/i);
const pageSubtitle = page.getByTestId("department-notifications-subtitle");
await expect(pageSubtitle).toBeVisible();
await expect(pageSubtitle).toContainText(/sms/i);
await expect(page.locator(".message").filter({ hasText: /sms/i })).toHaveCount(0);
const addPhoneButton = page.getByTestId("department-notification-sms-add-button");
await expect(addPhoneButton).toBeVisible();
await expect(addPhoneButton).toHaveClass(/is-primary/);
await expect(addPhoneButton).not.toHaveClass(/is-info/);
await expect(addPhoneButton.locator(".fa-plus")).toBeVisible();
const row = page.locator("tr", { hasText: "Dispatch line" });
await expect(row).toBeVisible({ timeout: pageReadyTimeout });
const enabledToggle = page.getByTestId("department-notification-sms-enabled-toggle-501");
+1 -24
View File
@@ -1844,7 +1844,7 @@ test("shows live Stripe payment status and cancellation for open card payment or
await expect(page.getByTestId("pos-order-stripe-email-cancel")).toBeVisible();
await expect(page.getByTestId("pos-order-print-receipt")).toHaveCount(0);
await expect(page.getByRole("button", { name: /Fuldfør ordre|Complete order/ })).toHaveCount(0);
await expect(page.locator('[data-action-key="economic-invoice-pdf-download"]')).toBeDisabled();
await expect(page.getByRole("button", { name: /Hent faktura|Get invoice/ })).toHaveCount(0);
await page.getByTestId("pos-order-stripe-email-cancel").click();
await deleteStripeInvoiceRequest;
@@ -2950,28 +2950,6 @@ test.describe("Admin POS Orders - desktop locked states", () => {
await expectOrderTotal(page, 1372);
});
test("disables invoice PDF download while the Economic invoice id is missing", async ({ page }) => {
await mockApi(page, {
authenticated: true,
permissions: POS_PERMISSIONS,
edgeGateways: false,
pos: createPosFixture({
economicModuleOrdersByOrderId: {
54518: {
invoice_id: null,
invoice_draft_id: 88012,
},
},
}),
});
await primeOperatorSession(page, "pos-orders-draft-invoice-token");
await openOrderDetail(page);
const downloadButton = page.locator('[data-action-key="economic-invoice-pdf-download"]');
await expect(downloadButton).toBeVisible();
await expect(downloadButton).toBeDisabled();
});
test("hides item mutation controls when the order is already invoiced", async ({ page }) => {
await mockApi(page, {
authenticated: true,
@@ -2992,7 +2970,6 @@ test.describe("Admin POS Orders - desktop locked states", () => {
await expect(page.getByTestId("pos-order-item-edit-9101")).toHaveCount(0);
await expect(page.getByTestId("pos-order-item-delete-9101")).toHaveCount(0);
await expect(page.getByTestId("pos-order-add-item")).toHaveCount(0);
await expect(page.locator('[data-action-key="economic-invoice-pdf-download"]')).toBeEnabled();
await expectOrderTotal(page, 1372);
});
});
+2 -4
View File
@@ -825,7 +825,7 @@ test.describe("Coolify infrastructure management", () => {
await expect(actions.getByRole("button", { name: "Reconcile Coolify" })).toBeVisible();
await expect(actions.getByRole("button", { name: "Coolify failover" })).toBeVisible();
await actions.getByRole("button", { name: "Reconcile Coolify" }).click();
await expect.poll(() => state.reconciledTargets.length).toBeGreaterThan(0);
expect(state.reconciledTargets.length).toBeGreaterThan(0);
});
test("resumes Coolify-backed provisioning after page reload", async ({ page }) => {
@@ -1044,9 +1044,7 @@ test.describe("Coolify infrastructure management", () => {
await actions.locator(".action-settings-wheel-trigger").click();
await actions.getByRole("button", { name: /Rename|Omdøb/ }).click();
await expect
.poll(() => state.renamedHosts)
.toContainEqual({ kind: "database", id: 2, label: "mariadb-manual-replica" });
expect(state.renamedHosts).toContainEqual({ kind: "database", id: 2, label: "mariadb-manual-replica" });
await expect(page.getByTestId("replication-host-database-2")).toContainText("mariadb-manual-replica");
});
});
-6
View File
@@ -350,10 +350,6 @@ async function readStoredToken(page: Page) {
}
}
async function waitForAppRootMounted(page: Page) {
await expect.poll(async () => page.locator("#app > *").count(), { timeout: AUTH_TIMEOUT }).toBeGreaterThan(0);
}
async function settleAuthenticatedNavigation(page: Page, targetPath: string, targetUrl: RegExp) {
await expect.poll(() => readStoredToken(page), { timeout: AUTH_TIMEOUT }).not.toBeNull();
const navigateToTarget = async () => {
@@ -380,8 +376,6 @@ async function settleAuthenticatedNavigation(page: Page, targetPath: string, tar
await navigateToTarget();
await expect.poll(() => page.url(), { timeout: AUTH_TIMEOUT }).toMatch(targetUrl);
}
await waitForAppRootMounted(page);
}
/**
-18
View File
@@ -6,12 +6,7 @@ import { scanViewTranslationKeys, type ViewTranslationKeyUsage } from "./support
const ACTIVE_LOCALES = ["da", "en", "sv", "de", "no"] as const;
const GENERATED_LOCALES_DIRECTORY = path.join(process.cwd(), "src", "i18n", "generated");
const REVIEWED_NON_LITERAL_CALLS = new Set([
"src/views/backoffice/LimitedBackofficeEmployees.vue|t|return `${option.flag} +${option.value} ${t(`templates.limited_backoffice.employees.country_codes.${option.labelKey}`)}`;",
"src/views/dashboards/superUserDashboard/InvoicingBillingPeriod/components/InvoicingPeriodFlagList.vue|t|const translated = t(key, params);",
"src/views/dashboards/superUserDashboard/roles/SuperUserRolesPermissions.vue|t|label: t(`roles.permissions.page_access.${permission}.label`),",
"src/views/dashboards/superUserDashboard/roles/SuperUserRolesPermissions.vue|t|description: t(`roles.permissions.page_access.${permission}.description`),",
"src/views/dashboards/superUserDashboard/roles/SuperUserRolesPermissions.vue|t|label: t(`roles.permissions.groups.${group.key}.label`),",
"src/views/dashboards/superUserDashboard/roles/SuperUserRolesPermissions.vue|t|description: t(`roles.permissions.groups.${group.key}.description`),",
'src/views/dashboards/superUserDashboard/system/ReplicationManagement.vue|t|return t(`replication.status.${status || "unknown"}`);',
"src/views/dashboards/superUserDashboard/system/ReplicationManagement.vue|te|if (key && te(key)) {",
"src/views/dashboards/superUserDashboard/system/ReplicationManagement.vue|t|return t(key, params);",
@@ -19,18 +14,9 @@ const REVIEWED_NON_LITERAL_CALLS = new Set([
'src/views/dashboards/superUserDashboard/system/ReplicationManagement.vue|t|<li v-for="key in redisComposeInstructionKeys" :key="key">{{ t(key) }}</li>',
'src/views/dashboards/superUserDashboard/system/ReplicationManagement.vue|t|<li v-for="key in minioComposeInstructionKeys" :key="key">{{ t(key) }}</li>',
"src/views/dashboards/superUserDashboard/system/ReplicationManagement.vue|t|<td>{{ t(`replication.roles.${host.role}`) }}</td>",
"src/views/dashboards/superUserDashboard/roles/SuperUserRolesPermissions.vue|t|label: t(`roles.permissions.page_access.${permission}.label`),",
"src/views/dashboards/superUserDashboard/roles/SuperUserRolesPermissions.vue|t|description: t(`roles.permissions.page_access.${permission}.description`),",
"src/views/dashboards/superUserDashboard/roles/SuperUserRolesPermissions.vue|t|label: t(`roles.permissions.groups.${group.key}.label`),",
"src/views/dashboards/superUserDashboard/roles/SuperUserRolesPermissions.vue|t|description: t(`roles.permissions.groups.${group.key}.description`),",
"src/views/dashboards/superUserDashboard/configuration/ConfigurationReleaseManager.vue|t|const tr = (key, params = {}) => t(`configuration.release_manager.${key}`, params);",
"src/views/dashboards/superUserDashboard/configuration/ConfigurationReleaseManager.vue|t|const translated = t(fullKey, params);",
"src/views/dashboards/superUserDashboard/ErrorReports.vue|t|const value = t(key);",
"src/views/backoffice/LimitedBackofficeEmployees.vue|t|return `${option.flag} +${option.value} ${t(`templates.limited_backoffice.employees.country_codes.${option.labelKey}`)}`;",
"src/views/dashboards/superUserDashboard/roles/SuperUserRolesPermissions.vue|t|label: t(`roles.permissions.page_access.${permission}.label`),",
"src/views/dashboards/superUserDashboard/roles/SuperUserRolesPermissions.vue|t|description: t(`roles.permissions.page_access.${permission}.description`),",
"src/views/dashboards/superUserDashboard/roles/SuperUserRolesPermissions.vue|t|label: t(`roles.permissions.groups.${group.key}.label`),",
"src/views/dashboards/superUserDashboard/roles/SuperUserRolesPermissions.vue|t|description: t(`roles.permissions.groups.${group.key}.description`),",
'src/views/dashboards/userDashboard/wash/components/LaneSelectionSection.vue|$t|:title="option.titleKey ? $t(option.titleKey) : null"',
'src/views/dashboards/userDashboard/wash/components/LaneSelectionSection.vue|$t|:aria-label="option.titleKey ? $t(option.titleKey) : null"',
"src/views/dashboards/userDashboard/wash/components/LaneSelectionSection.vue|$t|{{ $t(option.statusLabelKey) }}",
@@ -38,10 +24,6 @@ const REVIEWED_NON_LITERAL_CALLS = new Set([
"src/views/dashboards/userDashboard/wash/components/WashTypeSelector.vue|$t|{{ $t(option.statusLabelKey) }}",
'src/views/dashboards/userDashboard/wash/MyWashStart.vue|$t|:vehicle-step-guidance="vehicleStepGuidanceKey ? $t(vehicleStepGuidanceKey) : null"',
"src/views/dashboards/userDashboard/wash/MyWashStart.vue|$t|{{ $t(confirmActionLabelKey) }}",
"src/views/dashboards/superUserDashboard/roles/SuperUserRolesPermissions.vue|t|label: t(`roles.permissions.page_access.${permission}.label`),",
"src/views/dashboards/superUserDashboard/roles/SuperUserRolesPermissions.vue|t|description: t(`roles.permissions.page_access.${permission}.description`),",
"src/views/dashboards/superUserDashboard/roles/SuperUserRolesPermissions.vue|t|label: t(`roles.permissions.groups.${group.key}.label`),",
"src/views/dashboards/superUserDashboard/roles/SuperUserRolesPermissions.vue|t|description: t(`roles.permissions.groups.${group.key}.description`),",
]);
const readGeneratedJson = (fileName: string) => {
+1 -1
View File
@@ -55,7 +55,7 @@ async function suppressVueDevtoolsOverlay(page) {
async function primeSuperuserSession(page) {
const token = "superuser-e2e-token";
await primeMockSession(page, { token, bootPath: null });
await primeMockSession(page, { token });
}
async function prepareInvoiceDistributionPage(page, overrides = {}) {
+13 -112
View File
@@ -1,4 +1,4 @@
import { expect, test, type Page } from "@playwright/test";
import { expect, test } from "@playwright/test";
import { API_HOST, seedAuthenticatedState } from "./support/network.js";
import { isDesktopProject } from "./support/projects";
@@ -14,7 +14,6 @@ const limitedManagerPermissions = [
"limited_backoffice_prices_manage",
"limited_backoffice_employees_manage",
"department_access_1",
"department_access_2",
];
const sessionData = {
@@ -63,10 +62,7 @@ const adminLimitedSessionData = {
permissions: ["user", "admin", "limited_backoffice_access", "department_access_1"],
};
const assignedDepartments = [
{ id: 1, name: "Assigned Depot", description: "", visible: true, archived: false },
{ id: 2, name: "Remote Depot", description: "", visible: true, archived: false },
];
const assignedDepartments = [{ id: 1, name: "Assigned Depot", description: "", visible: true, archived: false }];
const pricePayload = {
department: { id: 1, name: "Assigned Depot", description: "" },
@@ -239,11 +235,6 @@ const rolePermissionGroups = {
],
};
const remotePricePayload = {
...pricePayload,
department: { id: 2, name: "Remote Depot", description: "" },
};
const rolesPayload = [
{ key: "viewer", label: "Viewer", description: "Can view.", permission_groups: rolePermissionGroups.viewer },
{ key: "cashier", label: "Cashier", description: "Can sell.", permission_groups: rolePermissionGroups.cashier },
@@ -283,17 +274,6 @@ const employeesPayload = [
created_at: "2026-01-01 00:00:00",
updated_at: "2026-01-01 00:00:00",
},
{
id: 502,
customer_number: 900000502,
display_name: "Riley Remote",
email: "riley@example.com",
active: true,
role: { key: "viewer", label: "Viewer", description: "Can view." },
departments: [{ id: 2, name: "Remote Depot" }],
created_at: "2026-01-01 00:00:00",
updated_at: "2026-01-01 00:00:00",
},
];
async function seedLimitedBackofficeSession(page, token = "limited-backoffice-token") {
@@ -370,11 +350,6 @@ async function mockLimitedBackofficeApi(page, authSessionData = sessionData, opt
return;
}
if (pathname.endsWith("/limited-backoffice/departments/2/prices") && method === "GET") {
await route.fulfill(json({ data: remotePricePayload }));
return;
}
if (pathname.endsWith("/limited-backoffice/departments/1/prices") && method === "PUT") {
const body = request.postDataJSON?.() || null;
priceUpdateCalls.push(body);
@@ -487,20 +462,6 @@ async function mockLimitedBackofficeApi(page, authSessionData = sessionData, opt
};
}
async function expectDepartmentSelectorInTitleRow(page: Page) {
const headingBox = await page.getByRole("heading", { name: "Backoffice" }).boundingBox();
const selectBox = await page.getByTestId("limited-backoffice-department-select").boundingBox();
expect(headingBox).not.toBeNull();
expect(selectBox).not.toBeNull();
if (!headingBox || !selectBox) {
return;
}
expect(selectBox.x).toBeGreaterThan(headingBox.x);
expect(Math.abs(selectBox.y + selectBox.height / 2 - (headingBox.y + headingBox.height / 2))).toBeLessThan(48);
}
test.describe("Limited backoffice", () => {
test("shows the limited backoffice header shortcut only on department-scoped admin pages", async ({
page,
@@ -578,9 +539,7 @@ test.describe("Limited backoffice", () => {
await page.goto("/backoffice/departments/1/prices");
await expect(page.getByTestId("limited-prices-title")).toBeVisible();
await expectDepartmentSelectorInTitleRow(page);
await expect(page.getByTestId("limited-backoffice-department-select")).toContainText("Assigned Depot");
await expect(page.getByTestId("limited-backoffice-department-select")).toContainText("Remote Depot");
await expect(page.getByTestId("limited-backoffice-department-select")).not.toContainText("Other Depot");
await expect(page.getByTestId("limited-price-row-101")).toContainText("Truck wash");
await expect(page.getByTestId("limited-price-input-101")).toHaveValue("125");
@@ -759,16 +718,12 @@ test.describe("Limited backoffice", () => {
await seedLimitedBackofficeSession(page);
const api = await mockLimitedBackofficeApi(page);
await page.goto("/backoffice/departments/1/employees");
await page.goto("/backoffice/employees");
await expect(page.getByTestId("limited-employees-title")).toBeVisible();
await expectDepartmentSelectorInTitleRow(page);
await expect(page.getByTestId("limited-employee-row-501")).toContainText("Casey Clerk");
await expect(page.getByTestId("limited-employee-user-id-501")).toHaveText("501");
await expect(page.getByTestId("limited-employee-phone-501")).toHaveText("+45 12345678");
await expect(page.getByTestId("limited-employee-row-502")).toHaveCount(0);
await expect(page.getByTestId("limited-employee-department-1")).toBeChecked();
await expect(page.getByTestId("limited-employee-department-2")).not.toBeChecked();
await expect(page.locator("#limited-employee-role option")).toHaveCount(5);
await expect(page.getByTestId("limited-employee-role")).not.toContainText("Superuser");
await expect(page.locator("body")).not.toContainText("department_access_1");
@@ -879,14 +834,15 @@ test.describe("Limited backoffice", () => {
await expect(page.getByTestId("limited-employees-title")).toBeVisible();
await expect(page.getByTestId("limited-employee-save")).toBeDisabled();
await expect(page.getByTestId("limited-employee-save")).toHaveClass(/is-fullwidth/);
await expect(page.getByTestId("limited-employee-departments").locator(".switch")).toHaveCount(2);
await expect(page.getByTestId("limited-employee-department-1")).toBeChecked();
await expect(page.getByTestId("limited-employee-department-2")).not.toBeChecked();
await expect(page.getByTestId("limited-employee-departments").locator(".switch")).toHaveCount(1);
await expect(page.getByTestId("limited-employee-phone-country-code")).toContainText("+45");
await page.getByTestId("limited-employee-name").fill("No Phone Worker");
await page.getByTestId("limited-employee-email").fill("no-phone@example.com");
await page.getByTestId("limited-employee-password").fill("Secret123!");
await expect(page.getByTestId("limited-employee-save")).toBeDisabled();
await page.getByTestId("limited-employee-department-1").click();
await expect(page.getByTestId("limited-employee-save")).toBeEnabled();
await page.getByTestId("limited-employee-save").click();
@@ -900,13 +856,14 @@ test.describe("Limited backoffice", () => {
role_key: "viewer",
department_ids: [1],
});
await expect(page.getByTestId("limited-employee-row-903")).toContainText("No Phone Worker");
await expect(page.getByTestId("limited-employee-row-902")).toContainText("No Phone Worker");
await page.getByTestId("limited-employee-name").fill("Phone Worker");
await page.getByTestId("limited-employee-email").fill("phone@example.com");
await page.getByTestId("limited-employee-phone-country-code").selectOption("358");
await page.getByTestId("limited-employee-phone").fill("87654321");
await page.getByTestId("limited-employee-password").fill("Secret123!");
await page.getByTestId("limited-employee-department-1").click();
await expect(page.getByTestId("limited-employee-save")).toBeEnabled();
await page.getByTestId("limited-employee-save").click();
@@ -920,8 +877,8 @@ test.describe("Limited backoffice", () => {
role_key: "viewer",
department_ids: [1],
});
await expect(page.getByTestId("limited-employee-row-904")).toContainText("Phone Worker");
await expect(page.getByTestId("limited-employee-phone-904")).toHaveText("+358 87654321");
await expect(page.getByTestId("limited-employee-row-903")).toContainText("Phone Worker");
await expect(page.getByTestId("limited-employee-phone-903")).toHaveText("+358 87654321");
});
test("edits employee contact details without requiring a new password", async ({ page }) => {
@@ -955,75 +912,19 @@ test.describe("Limited backoffice", () => {
await expect(page.getByTestId("limited-employee-phone-501")).toHaveText("+358 87654321");
});
test("keeps department context across employee access navigation", async ({ page }, testInfo) => {
test.skip(!isDesktopProject(testInfo), "Desktop only");
await seedLimitedBackofficeSession(page);
const api = await mockLimitedBackofficeApi(page);
await page.goto("/backoffice/employees");
await expect(page).toHaveURL(/\/backoffice\/departments\/1\/employees$/);
await expect(page.getByTestId("limited-backoffice-tab-prices")).toHaveAttribute(
"href",
"/backoffice/departments/1/prices"
);
await expect(page.getByTestId("limited-backoffice-tab-employees")).toHaveAttribute(
"href",
"/backoffice/departments/1/employees"
);
await page.getByTestId("limited-backoffice-department-select").selectOption("2");
await expect(page).toHaveURL(/\/backoffice\/departments\/2\/employees$/);
await expect(page.getByTestId("limited-employee-row-501")).toHaveCount(0);
await expect(page.getByTestId("limited-employee-row-502")).toContainText("Riley Remote");
await expect(page.getByTestId("limited-employee-department-1")).not.toBeChecked();
await expect(page.getByTestId("limited-employee-department-2")).toBeChecked();
await expect(page.getByTestId("limited-backoffice-tab-prices")).toHaveAttribute(
"href",
"/backoffice/departments/2/prices"
);
await page.getByTestId("limited-backoffice-tab-prices").click();
await expect(page).toHaveURL(/\/backoffice\/departments\/2\/prices$/);
await expect(page.getByTestId("limited-backoffice-tab-employees")).toHaveAttribute(
"href",
"/backoffice/departments/2/employees"
);
expect(api.forbiddenCalls).toEqual([]);
});
test("does not render data for a department outside the manager scope", async ({ page }, testInfo) => {
test.skip(!isDesktopProject(testInfo), "Desktop only");
await seedLimitedBackofficeSession(page);
const api = await mockLimitedBackofficeApi(page);
await page.goto("/backoffice/departments/3/prices");
await page.goto("/backoffice/departments/2/prices");
await expect(page.getByTestId("limited-prices-forbidden")).toBeVisible();
await expect(page.locator("body")).not.toContainText("Secret Depot");
await expect(page.getByTestId("limited-prices-table")).toHaveCount(0);
expect(api.calls.some((call) => call.includes("/limited-backoffice/departments/3/prices"))).toBe(false);
expect(api.forbiddenCalls).toEqual([]);
});
test("does not render employee data for a department outside the manager scope", async ({ page }, testInfo) => {
test.skip(!isDesktopProject(testInfo), "Desktop only");
await seedLimitedBackofficeSession(page);
const api = await mockLimitedBackofficeApi(page);
await page.goto("/backoffice/departments/3/employees");
await expect(page.getByTestId("limited-employees-forbidden")).toBeVisible();
await expect(page.locator("body")).not.toContainText("Secret Depot");
await expect(page.getByTestId("limited-employees-table")).toHaveCount(0);
expect(api.calls.some((call) => call.includes("/limited-backoffice/employees"))).toBe(false);
expect(api.calls.some((call) => call.includes("/limited-backoffice/departments/2/prices"))).toBe(false);
expect(api.forbiddenCalls).toEqual([]);
});
});
Binary file not shown.

Before

Width:  |  Height:  |  Size: 98 KiB

After

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 107 KiB

After

Width:  |  Height:  |  Size: 94 KiB

+1 -5
View File
@@ -2328,11 +2328,7 @@ test("superusers manage release settings, assignments, integrations, and sync op
await expect(page.getByTestId("release-assignment-subject-manual-user-909")).toContainText("User #909");
await expect(page.getByTestId("release-assignment-subject-manual-subuser-909")).toContainText("Subuser #909");
await expect(page.getByTestId("release-assignment-subject-manual-customer-909")).toContainText("Customer #909");
await page
.getByTestId("release-assignment-subject-autocomplete")
.getByRole("button", { name: /Subuser #909/ })
.click();
await expect(assignmentSubjectInput).toHaveValue("Subuser #909 - Use typed value subuser:909");
await page.getByTestId("release-assignment-subject-manual-subuser-909").click({ force: true });
await page.getByTestId("release-assignment-form").getByRole("button", { name: "Assign" }).click();
expect(state.assignmentPayloads[state.assignmentPayloads.length - 1]).toMatchObject({
subject_type: "subuser",
+2 -23
View File
@@ -27,7 +27,7 @@ async function primeSession(page, { token, permissions, sessionData = {} }) {
await seedAuthenticatedState(page, token);
}
async function mockSelectedSubuserGrant(page, { customerNumber = 12345679, permissions = ["SELFSERVE_LIST"] } = {}) {
async function mockSelectedSubuserGrant(page, { customerNumber = 12345679, permissions = ["user"] } = {}) {
await page.route("**/subusers/me", async (route) => {
await route.fulfill({
status: 200,
@@ -249,7 +249,6 @@ test.describe("Self-serve wash", () => {
},
selfServe: true,
});
api.selfServe.commandResponseDelayMs = [500, 0];
await primeSession(page, {
token: "self-serve-user-token",
permissions: ["user"],
@@ -1046,7 +1045,7 @@ test.describe("Self-serve wash", () => {
customerNumberInput: "777",
});
const api = await mockApi(page, {
await mockApi(page, {
authenticated: true,
permissions: ["user"],
sessionData: {
@@ -1064,25 +1063,6 @@ test.describe("Self-serve wash", () => {
],
},
});
api.selfServe.previewByKey["7:ZZ00000"] = {
...api.selfServe.previewByKey["7:ZZ00000"],
questions: [],
tasks: [],
};
api.selfServe.summaryBySessionId[601] = {
...api.selfServe.summaryBySessionId[601],
questions: [],
tasks: [],
};
api.selfServe.summaryByKey["7:ZZ00000"] = {
session: api.selfServe.previewByKey["7:ZZ00000"].session,
lane: api.selfServe.previewByKey["7:ZZ00000"].lane,
questions: [],
conditions: [],
rules: [],
tasks: [],
events: [{ id: 4, type: "STARTED", created_at: "2026-01-01T11:01:00.000Z" }],
};
await primeSession(page, {
token: "self-serve-start-retry-token",
permissions: ["user"],
@@ -1183,7 +1163,6 @@ test.describe("Self-serve wash", () => {
authenticated: true,
permissions: ["user"],
selfServe: {
commandResponseDelayMs: [500, 0],
commandResponses: [
{
success: false,
+1 -21
View File
@@ -15,7 +15,6 @@ type ProductRouteOptions = {
categories?: unknown;
productOptions?: unknown;
economicProducts?: unknown;
onProductsRequest?: (url: URL) => void;
};
const collectBrowserErrors = (page: Page) => {
@@ -43,7 +42,6 @@ const stubSuperuserProductRoutes = async (
categories = [],
productOptions = [],
economicProducts = [],
onProductsRequest,
}: ProductRouteOptions
) => {
await seedAuthenticatedState(page, token);
@@ -156,7 +154,6 @@ const stubSuperuserProductRoutes = async (
}
if (pathname.endsWith("/products") && method === "GET") {
onProductsRequest?.(url);
const perPage = Number(url.searchParams.get("limit") || "100");
await route.fulfill(
@@ -276,14 +273,7 @@ test.describe("Superuser products layout", () => {
];
await page.setViewportSize({ width: 1280, height: 720 });
const productRequestUrls: string[] = [];
await stubSuperuserProductRoutes(page, {
products,
categories,
productOptions,
economicProducts,
onProductsRequest: (url) => productRequestUrls.push(url.toString()),
});
await stubSuperuserProductRoutes(page, { products, categories, productOptions, economicProducts });
await page.goto("/superuser/products");
@@ -326,16 +316,6 @@ test.describe("Superuser products layout", () => {
await expect(page.getByTestId("superuser-product-name")).toContainText("Trækker");
await expect(page.getByRole("heading", { name: "Trækker" })).toBeVisible();
const detailRequest = productRequestUrls
.map((url) => new URL(url))
.find((url) => url.searchParams.get("id") === "1");
expect(detailRequest).toBeDefined();
expect(detailRequest?.searchParams.get("department_id")).toBeNull();
expect(detailRequest?.searchParams.get("customer_id")).toBeNull();
expect(detailRequest?.searchParams.get("category_id")).toBeNull();
expect(detailRequest?.searchParams.get("final_price")).toBe("false");
expect(pageErrors).toEqual([]);
expect(consoleErrors).toEqual([]);
});
@@ -25,44 +25,6 @@ async function bootSuperuser(page, { permissions = ["superuser", "user"], edgeGa
await primeSuperuserSession(page);
}
async function waitForLayoutFrame(page) {
await page.evaluate(
() =>
new Promise((resolve) => {
requestAnimationFrame(() => requestAnimationFrame(resolve));
})
);
}
async function getActionMenuVerticalPlacement(trigger, menu) {
const [triggerBox, menuBox] = await Promise.all([trigger.boundingBox(), menu.boundingBox()]);
expect(triggerBox).not.toBeNull();
expect(menuBox).not.toBeNull();
const belowGap = menuBox.y - (triggerBox.y + triggerBox.height);
const aboveGap = triggerBox.y - (menuBox.y + menuBox.height);
const isBelowButton = belowGap >= -2 && belowGap <= 16;
const isAboveButton = aboveGap >= -2 && aboveGap <= 16;
expect(isBelowButton || isAboveButton).toBe(true);
expect(menuBox.y >= triggerBox.y + triggerBox.height - 2 || menuBox.y + menuBox.height <= triggerBox.y + 2).toBe(
true
);
return isBelowButton ? "below" : "above";
}
async function getSettledActionMenuVerticalPlacement(page, trigger, menu) {
await waitForLayoutFrame(page);
const firstPlacement = await getActionMenuVerticalPlacement(trigger, menu);
await waitForLayoutFrame(page);
const secondPlacement = await getActionMenuVerticalPlacement(trigger, menu);
expect(secondPlacement).toBe(firstPlacement);
return secondPlacement;
}
async function installSystemStatusMock(page, snapshot) {
await page.route(/\/superuser\/system\/status(?:\?.*)?$/, async (route) => {
await route.fulfill(
@@ -853,38 +815,6 @@ test.describe("Superuser system status smoke", () => {
await expect(page.getByTestId("database-status-card")).toContainText("8.0.36");
});
test("@smoke @pr superuser replication action menu keeps stable vertical placement", async ({ page }) => {
await bootSuperuser(page);
await installReplicationMock(page);
await page.goto("/superuser/system/replication");
await expect(page.getByTestId("replication-management-page")).toBeVisible({ timeout: PAGE_READY_TIMEOUT });
await expect(page.getByTestId("replication-host-database-2")).toContainText("mysql-replica-1");
const replicaActions = page.getByTestId("replication-actions-database-2");
const replicaActionTrigger = replicaActions.locator(".action-settings-wheel-trigger");
const replicaActionMenu = replicaActions.locator(".dropdown-content");
await expect(replicaActionTrigger).toBeVisible();
await replicaActionTrigger.click();
await expect(replicaActions.locator(".dropdown-item-action:visible")).toHaveCount(4);
const initialPlacement = await getSettledActionMenuVerticalPlacement(page, replicaActionTrigger, replicaActionMenu);
await page.keyboard.press("Escape");
await expect(replicaActionTrigger).not.toHaveClass(/action-settings-wheel-trigger--active/);
await replicaActionTrigger.click();
await expect(replicaActions.locator(".dropdown-item-action:visible")).toHaveCount(4);
const reopenedPlacement = await getSettledActionMenuVerticalPlacement(
page,
replicaActionTrigger,
replicaActionMenu
);
expect(reopenedPlacement).toBe(initialPlacement);
});
test("@smoke superuser replication management page renders topology and percentages", async ({ page }) => {
await bootSuperuser(page);
const replicationRequests = await installReplicationMock(page);
@@ -933,11 +863,15 @@ test.describe("Superuser system status smoke", () => {
await replicaActionTrigger.click();
await expect(replicaActions.locator(".dropdown-item-action:visible")).toHaveCount(4);
await expect(replicaActions.getByRole("button", { name: "Omdøb" })).toBeVisible();
await getSettledActionMenuVerticalPlacement(
page,
replicaActionTrigger,
replicaActions.locator(".dropdown-content")
);
const [triggerBox, menuBox] = await Promise.all([
replicaActionTrigger.boundingBox(),
replicaActions.locator(".dropdown-content").boundingBox(),
]);
expect(triggerBox).not.toBeNull();
expect(menuBox).not.toBeNull();
const isMenuBelowButton = Math.abs(menuBox.y - (triggerBox.y + triggerBox.height)) <= 12;
const isMenuAboveButton = Math.abs(menuBox.y + menuBox.height - triggerBox.y) <= 12;
expect(isMenuBelowButton || isMenuAboveButton).toBe(true);
await replicaActions.getByRole("button", { name: "Test" }).click();
expect(replicationRequests.hostTestKinds).toContain("database");
const addHostTabs = page.getByTestId("replication-add-host-tabs");
+1 -229
View File
@@ -1,6 +1,6 @@
import { expect, test } from "@playwright/test";
import { apiPathPattern, mockApi, seedAuthenticatedState } from "./support/network.js";
import { mockApi, seedAuthenticatedState } from "./support/network.js";
import { isDesktopProject } from "./support/projects";
const json = (body: unknown, status = 200) => ({
@@ -35,172 +35,6 @@ const userEnvelope = (rows: Array<Record<string, unknown>>) => ({
},
});
const overviewUser = {
id: 11,
customer_number: 12345,
display_name: "Anna Andersen",
email: "anna@example.test",
phone: {
number: "12345678",
country_code: 45,
},
group_id: 1,
created_at: "2026-01-01 08:30:00",
updated_at: "2026-02-01 09:45:00",
economic_customer: {
customerNumber: 12345,
name: "Anna Transport",
address: "Main Road 1",
zip: "2100",
city: "Copenhagen",
mobilePhone: "12345678",
email: "billing@example.test",
corporateIdentificationNumber: "12345678",
currency: "DKK",
country: "Denmark",
barred: false,
},
permissions: ["superuser", "user", "get_user", "set_custom_price"],
attributes: [{ id: 1, attribute: "invoiceAllOrdersIndividually" }],
discounts: [{ id: 999999, percentage: 10 }],
orders_not_invoiced: [{ id: 501 }],
keys: {
open_invoice_draft: "DRAFT-1",
OtherSpecialArrangement: "Night wash agreement",
OtherVaskeabonnement: "Monthly wash subscription note",
},
wash_subscription_transactions: [
{
id: 6250,
customer_id: 12345,
cashier_id: 1857,
reference: "Vaskeabonnementer",
notes: "",
department_id: 10,
reg_1: "",
reg_2: "",
reg_3: "",
completed_at: null,
created_at: "2026-03-01 00:00:01",
deleted_at: null,
total_net_amount: 694,
invoice_collection_id: 1634,
booking_id: 0,
closed_at: "2026-03-24 12:45:10",
},
],
};
const overviewVehicles = [
{
id: 301,
customer_id: 12345,
reg: "AA11223",
type: 1,
reference: "Truck 1",
wash_subscription: true,
xlvask: true,
addons: {
list: [{ product: { id: 91, name: "Interior cleaning" } }],
},
},
{
id: 302,
customer_id: 12345,
reg: "BB44556",
type: 1,
reference: "Trailer",
wash_subscription: false,
xlvask: false,
addons: {
list: [],
},
},
];
const setupOverviewApi = async (page, options: { failDetailUntilEnabled?: boolean } = {}) => {
let detailRequests = 0;
let detailSuccessEnabled = !options.failDetailUntilEnabled;
await page.route(apiPathPattern("/superuser/user"), async (route) => {
const request = route.request();
if (request.method() !== "GET") {
await route.fulfill(json({ data: { message: "OK" } }));
return;
}
detailRequests += 1;
if (!detailSuccessEnabled) {
await route.fulfill(json({ message: "User detail unavailable" }, 500));
return;
}
await route.fulfill(json({ data: overviewUser }));
});
await page.route(apiPathPattern("/superuser/user/keys"), async (route) => {
if (route.request().method() === "POST") {
await route.fulfill(json({ data: { message: "OK" } }));
return;
}
await route.fulfill(
json({
data: {
OtherSpecialArrangement: overviewUser.keys.OtherSpecialArrangement,
OtherVaskeabonnement: overviewUser.keys.OtherVaskeabonnement,
},
})
);
});
await page.route(apiPathPattern("/customer/pricing/fixed"), async (route) => {
await route.fulfill(
json({
data: {
price: 1234,
description: "Fixed agreement",
},
})
);
});
await page.route(apiPathPattern("/customer/department/default"), async (route) => {
await route.fulfill(
json({
data: {
department: 1,
},
})
);
});
await page.route(apiPathPattern("/vehicles"), async (route) => {
const request = route.request();
if (request.method() !== "GET") {
await route.fulfill(json({ data: { message: "OK" } }));
return;
}
const url = new URL(request.url());
const filters = url.searchParams.get("filters") || "";
const rows = filters.includes("wash_subscription:1")
? overviewVehicles.filter((vehicle) => vehicle.wash_subscription)
: overviewVehicles;
await route.fulfill(json({ data: rows }));
});
return {
enableDetailSuccess: () => {
detailSuccessEnabled = true;
},
detailRequests: () => detailRequests,
};
};
test.describe("Superuser employees list", () => {
test("uses shared search, pagination reload, and action wheel controls", async ({ page }, testInfo) => {
test.skip(!isDesktopProject(testInfo), "Desktop only");
@@ -259,65 +93,3 @@ test.describe("Superuser employees list", () => {
expect(searchesSeen).toContain("Anna");
});
});
test.describe("Superuser user overview", () => {
test.beforeEach(async ({ page }) => {
await seedAuthenticatedState(page, "superuser-user-overview-token");
await mockApi(page, {
authenticated: true,
permissions: ["superuser", "user", "get_user", "set_custom_price"],
pos: {
vehicles: overviewVehicles,
},
sessionData: {
group_id: 1,
},
});
});
test("loads the management hub without raw debug output", async ({ page }) => {
await setupOverviewApi(page);
await page.goto("/superuser/users/11", { waitUntil: "domcontentloaded" });
await expect(page.getByTestId("superuser-user-overview-page")).toBeVisible();
await expect(page.getByTestId("superuser-user-overview-header")).toContainText("Anna Transport");
await expect(page.getByTestId("superuser-user-tab-overview")).toHaveAttribute("href", "/superuser/users/11");
await expect(page.getByTestId("superuser-user-tab-pricing")).toHaveAttribute("href", "/superuser/users/11/pricing");
await expect(page.getByTestId("superuser-user-overview-metric-customer")).toContainText("12345");
await expect(page.getByTestId("superuser-user-overview-metric-vehicles")).toContainText("2");
await expect(page.getByTestId("superuser-user-overview-metric-orders")).toContainText("1");
await expect(page.getByTestId("superuser-user-overview-metric-discounts")).toContainText("1");
await expect(page.getByTestId("superuser-user-overview-account")).toContainText("anna@example.test");
await expect(page.getByTestId("superuser-user-overview-economic")).toContainText("billing@example.test");
await expect(page.getByTestId("superuser-user-overview-access")).toContainText("set_custom_price");
await expect(page.getByTestId("superuser-user-overview-rules")).toBeVisible();
await expect(page.getByTestId("superuser-user-special-arrangement-input")).toHaveValue("Night wash agreement");
await expect(page.getByTestId("superuser-user-wash-subscription-note-input")).toHaveValue(
"Monthly wash subscription note"
);
await expect(page.getByTestId("superuser-user-overview-vehicles")).toContainText("AA11223");
await expect(page.getByTestId("superuser-user-overview-subscriptions")).toContainText("694");
await expect(page.getByTestId("superuser-user-overview-link-vehicles")).toHaveAttribute(
"href",
"/superuser/users/11/vehicles"
);
const body = page.locator("body");
await expect(body).not.toContainText("SessionUser:");
await expect(body).not.toContainText("economicData:");
});
test("shows a retryable error when the detail request fails", async ({ page }) => {
const overviewApi = await setupOverviewApi(page, { failDetailUntilEnabled: true });
await page.goto("/superuser/users/11", { waitUntil: "domcontentloaded" });
await expect(page.getByTestId("superuser-user-overview-error")).toContainText("User detail unavailable");
expect(overviewApi.detailRequests()).toBeGreaterThan(0);
overviewApi.enableDetailSuccess();
await page.getByTestId("superuser-user-overview-retry").click();
await expect(page.getByTestId("superuser-user-overview-header")).toContainText("Anna Transport");
await expect(page.getByTestId("superuser-user-overview-error")).toHaveCount(0);
});
});
-61
View File
@@ -1317,7 +1317,6 @@ function createSelfServeFixture(overrides = {}) {
answerRequests: [],
commandResponse: { success: true },
commandResponses: null,
commandResponseDelayMs: 0,
commandRequests: [],
forceStopResponse: null,
forceStopResponses: null,
@@ -1484,14 +1483,6 @@ function buildEdgeGatewayOperationSummary(operations = []) {
);
}
function invalidateEdgeGatewayRuntimeSnapshot(gateway) {
delete gateway.active_operation;
delete gateway.recent_operations_summary;
delete gateway.version_drift;
delete gateway.diagnostics;
delete gateway.error_state;
}
function buildEdgeGatewayRuntimeFixture(gateway) {
const relayHealth = (gateway.bindings || []).map((binding) => {
const fallbackMode = binding.fallback_mode || "PREFER_LOCAL";
@@ -1859,7 +1850,6 @@ function settleEdgeGatewayWork(edgeGatewayFixture, gatewayId) {
: operation
);
delete edgeGatewayFixture.pendingDiscoveryByGatewayId[gatewayId];
invalidateEdgeGatewayRuntimeSnapshot(gateway);
}
}
@@ -5411,7 +5401,6 @@ async function handleEdgeGatewayRoute({ route, request, parsedUrl, pathname, met
{ id: Date.now(), created_at: now, action: "GATEWAY_OPERATION_CANCELLED", actor_type: "USER" },
...(gateway.audit_logs || []),
];
invalidateEdgeGatewayRuntimeSnapshot(gateway);
Object.assign(gateway, buildEdgeGatewayRuntimeFixture(gateway));
await route.fulfill(
json({
@@ -5578,7 +5567,6 @@ async function handleEdgeGatewayRoute({ route, request, parsedUrl, pathname, met
{ id: Date.now(), created_at: now, action: "GATEWAY_OPERATION_QUEUED", actor_type: "USER" },
...(gateway.audit_logs || []),
];
invalidateEdgeGatewayRuntimeSnapshot(gateway);
Object.assign(gateway, buildEdgeGatewayRuntimeFixture(gateway));
await route.fulfill(
json(
@@ -6709,10 +6697,6 @@ export async function mockApi(page, options = {}) {
Array.isArray(selfServe.commandResponses) && selfServe.commandResponses.length > 0
? selfServe.commandResponses.shift()
: selfServe.commandResponse;
const commandResponseDelayMs = Array.isArray(selfServe.commandResponseDelayMs)
? selfServe.commandResponseDelayMs.shift() || 0
: selfServe.commandResponseDelayMs;
await maybeDelayFixtureResponse(commandResponseDelayMs);
await route.fulfill(json(commandResponse));
return;
}
@@ -6740,51 +6724,6 @@ export async function mockApi(page, options = {}) {
return;
}
if (pathname.endsWith("/user/invoices") && method === "GET") {
const invoiceFixture = posFixture || { collectedInvoices: [] };
const customerNumber = Number(options.sessionData?.customer_number || 0);
const collectedInvoices = (invoiceFixture.collectedInvoices || []).filter((invoice) => {
if (!customerNumber) {
return true;
}
return Number(invoice.customer_number) === customerNumber;
});
const page = Number(parsedUrl.searchParams.get("page") || 1);
const limit = Number(parsedUrl.searchParams.get("limit") || collectedInvoices.length || 100);
await route.fulfill(
json({
data: collectedInvoices.slice((page - 1) * limit, page * limit),
meta: {
pagination: {
page,
per_page: limit,
total: collectedInvoices.length,
},
},
})
);
return;
}
if (pathname.endsWith("/invoices/pdf") && method === "GET") {
const invoiceId = String(parsedUrl.searchParams.get("id") || "").trim();
if (!invoiceId) {
await route.fulfill(json({ message: "Invoice not found" }, 404));
return;
}
await route.fulfill(
json({
data: {
url: `https://pdf.example.test/invoices/${invoiceId}.pdf`,
},
})
);
return;
}
if (pathname.endsWith("/collected-invoices") && method === "GET") {
const invoiceFixture = posFixture || { collectedInvoices: [] };
const filters = parseFilterExpressions(parsedUrl.searchParams.get("filters") || "");
+22 -48
View File
@@ -1,25 +1,20 @@
import { test, expect, type Page } from "@playwright/test";
import { createPosFixture, mockApi, seedAuthenticatedState } from "./support/network.js";
import { loginAsUser } from "./fixtures";
const USER_HOME_CUSTOMER_NUMBER = 12345679;
async function gotoUserHomeWithInvoices(page: Page, collectedInvoices: Array<Record<string, unknown>>) {
await mockApi(page, {
authenticated: true,
sessionData: {
customer_number: USER_HOME_CUSTOMER_NUMBER,
display_name: "E2E User",
permissions: ["user"],
},
pos: createPosFixture({
collectedInvoices,
}),
});
await seedAuthenticatedState(page, "user-home-invoice-shortcut-token");
await page.goto("/user", { waitUntil: "domcontentloaded" });
await expect(page).toHaveURL(/\/user(?:\/)?(?:[?#].*)?$/);
}
import { test, expect } from "@playwright/test";
import {
userCredentials,
subuserPhoneCredentials,
subuserUsernameCredentials,
operatorCredentials,
customerRegistrationData,
driverRegistrationData,
invalidCredentials,
loginAsUser,
loginAsSubuserByPhone,
loginAsSubuserByUsername,
loginAsOperator,
goToUserLogin,
goToSubuserLogin,
goToOperatorLogin,
} from "./fixtures";
/** User home Tests */
// User home page content tests
@@ -46,30 +41,9 @@ test("[PAGES][User][/user] should display the download certificate button", asyn
// Check if the "download certificate" element is visible
await expect(page.locator("a#download-certificates-button")).toBeVisible();
});
test("[PAGES][User][/user] should disable the download invoices button when no invoice exists", async ({ page }) => {
await gotoUserHomeWithInvoices(page, []);
const button = page.locator("button#download-invoices-button");
await expect(button).toBeVisible();
await expect(button).toBeDisabled();
await expect(button).not.toHaveClass(/is-loading/);
await expect(page.locator("a#download-invoices-button")).toHaveCount(0);
});
test("[PAGES][User][/user] should enable the download invoices button when an invoice exists", async ({ page }) => {
await gotoUserHomeWithInvoices(page, [
{
id: 7001,
customer_number: USER_HOME_CUSTOMER_NUMBER,
customer_name: "E2E User",
total_net_amount: 1250,
created_at: "2026-07-01",
closed_at: "2026-07-01",
},
]);
const link = page.locator("a#download-invoices-button");
await expect(link).toBeVisible();
await expect(link).toHaveAttribute("href", "/user/invoices");
await expect(page.locator("button#download-invoices-button")).toHaveCount(0);
// Download invoices button visibility test
test("[PAGES][User][/user] should display the download invoices button", async ({ page }) => {
await loginAsUser(page);
// Check if the "download invoices" element is visible
await expect(page.locator("a#download-invoices-button")).toBeVisible();
});
@@ -316,26 +316,6 @@ const flushMicrotasks = async () => {
await Promise.resolve();
};
const flushDropdownLayout = async () => {
for (let index = 0; index < 8; index += 1) {
await Promise.resolve();
}
};
const createRect = ({ left = 0, top = 0, width = 0, height = 0 }) => ({
x: left,
y: top,
top,
left,
right: left + width,
bottom: top + height,
width,
height,
toJSON() {
return this;
},
});
const setDesktopFlyoutViewport = () => {
Object.defineProperty(window, "innerWidth", {
configurable: true,
@@ -415,95 +395,6 @@ const mockMenuGeometry = () =>
};
});
const mockDropdownPlacementGeometry = ({
contentHeight = 180,
contentWidth = 240,
triggerHeight = 40,
triggerLeft = 880,
triggerTop = 520,
triggerWidth = 80,
} = {}) => {
let currentContentHeight = contentHeight;
const originalScrollHeightDescriptor = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "scrollHeight");
Object.defineProperty(HTMLElement.prototype, "scrollHeight", {
configurable: true,
get() {
if (this.classList?.contains("dropdown-content")) {
return currentContentHeight;
}
if (originalScrollHeightDescriptor?.get) {
return originalScrollHeightDescriptor.get.call(this);
}
return 0;
},
});
const rectSpy = vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function rectMock() {
if (this.classList?.contains("dropdown-trigger")) {
return createRect({
left: triggerLeft,
top: triggerTop,
width: triggerWidth,
height: triggerHeight,
});
}
if (this.classList?.contains("dropdown-content")) {
const dropdown = this.closest(".dropdown");
const menu = this.closest(".dropdown-menu");
const fixedTop = Number.parseFloat(menu?.style?.top || "");
const maxHeight = Number.parseFloat(this.style?.maxHeight || "");
const height = Number.isFinite(maxHeight) ? Math.min(currentContentHeight, maxHeight) : currentContentHeight;
const top = Number.isFinite(fixedTop)
? fixedTop
: dropdown?.classList.contains("is-up")
? triggerTop - height
: triggerTop + triggerHeight;
return createRect({
left: triggerLeft + triggerWidth - contentWidth,
top,
width: contentWidth,
height,
});
}
if (this.classList?.contains("action-wheel-clip-host")) {
return createRect({
left: 0,
top: 480,
width: 1280,
height: 120,
});
}
return createRect({
left: 0,
top: 0,
width: 1280,
height: 900,
});
});
return {
restore() {
rectSpy.mockRestore();
if (originalScrollHeightDescriptor) {
Object.defineProperty(HTMLElement.prototype, "scrollHeight", originalScrollHeightDescriptor);
} else {
delete HTMLElement.prototype.scrollHeight;
}
},
setContentHeight(nextHeight) {
currentContentHeight = nextHeight;
},
};
};
const mountDesktopFlyoutButton = (props = {}) => {
setDesktopFlyoutViewport();
@@ -525,29 +416,6 @@ const mountDesktopFlyoutButton = (props = {}) => {
});
};
const mountPositionedFlatDropdownButton = (options = {}) => {
setCompactViewport();
return mount(ActionSettingsWheelButton, {
props: {
order_id: null,
refreshFunction: vi.fn(() => Promise.resolve()),
...(options.props || {}),
},
slots: {
actions:
options.actions || '<button type="button" class="dropdown-item dropdown-item-action">Custom action</button>',
},
attachTo: options.attachTo,
global: {
plugins: [i18n],
stubs: {
CustomerModal: { template: "<div />" },
},
},
});
};
const mountFlatDropdownButton = (props = {}) => {
setCompactViewport();
@@ -696,93 +564,6 @@ describe("ActionSettingsWheelButton", () => {
wrapper.unmount();
});
it("uses the same vertical side when the dropdown is reopened with unchanged geometry", async () => {
const geometry = mockDropdownPlacementGeometry({
contentHeight: 420,
triggerTop: 520,
});
const wrapper = mountPositionedFlatDropdownButton();
await flushDropdownLayout();
const trigger = wrapper.get(".action-settings-wheel-trigger");
await trigger.trigger("click");
await flushDropdownLayout();
expect(wrapper.get(".dropdown").classes()).toContain("is-up");
await trigger.trigger("click");
await flushDropdownLayout();
expect(wrapper.get(".dropdown").classes()).not.toContain("is-active");
await trigger.trigger("click");
await flushDropdownLayout();
expect(wrapper.get(".dropdown").classes()).toContain("is-up");
wrapper.unmount();
geometry.restore();
});
it("keeps the initially selected side when the menu grows after opening", async () => {
const geometry = mockDropdownPlacementGeometry({
contentHeight: 120,
triggerTop: 520,
});
const wrapper = mountPositionedFlatDropdownButton();
await flushDropdownLayout();
await wrapper.get(".action-settings-wheel-trigger").trigger("click");
await flushDropdownLayout();
expect(wrapper.get(".dropdown").classes()).not.toContain("is-up");
geometry.setContentHeight(420);
window.dispatchEvent(new Event("resize"));
await flushDropdownLayout();
expect(wrapper.get(".dropdown").classes()).not.toContain("is-up");
expect(wrapper.get(".dropdown-content").element.style.maxHeight).toBe("328px");
wrapper.unmount();
geometry.restore();
});
it("keeps fixed-position fallback on the chosen side and clears stale content top", async () => {
const host = document.createElement("div");
host.className = "action-wheel-clip-host";
host.style.overflow = "hidden";
document.body.appendChild(host);
const geometry = mockDropdownPlacementGeometry({
contentHeight: 420,
triggerTop: 520,
});
const wrapper = mountPositionedFlatDropdownButton({ attachTo: host });
await flushDropdownLayout();
await wrapper.get(".action-settings-wheel-trigger").trigger("click");
await flushDropdownLayout();
const dropdownContent = wrapper.get(".dropdown-content").element;
const dropdownMenu = wrapper.get(".dropdown-menu").element;
expect(wrapper.get(".dropdown").classes()).toContain("is-up");
expect(dropdownMenu.style.position).toBe("fixed");
expect(dropdownMenu.style.top).toBe("100px");
expect(dropdownContent.style.top).toBe("");
dropdownContent.style.top = "24px";
window.dispatchEvent(new Event("resize"));
await flushDropdownLayout();
expect(wrapper.get(".dropdown").classes()).toContain("is-up");
expect(dropdownMenu.style.position).toBe("fixed");
expect(dropdownMenu.style.top).toBe("100px");
expect(dropdownContent.style.top).toBe("");
wrapper.unmount();
geometry.restore();
host.remove();
});
it("resolves customer user id and reloads customer rules only when the target changes in direct mode", async () => {
const wrapper = mount(ActionSettingsWheelButton, {
props: {
@@ -1,125 +0,0 @@
// @vitest-environment jsdom
import { mount } from "@vue/test-utils";
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@/components/session/authenticatedRequest.vue", () => ({
authenticatedRequest: vi.fn(),
}));
vi.mock("@/components/session/token/SessionUser.vue", () => ({
SessionUser: {},
}));
import {
getProductBestApplicableDiscount,
getProductEffectivePrice,
getUserProductFixedPrice,
user,
} from "@/views/dashboards/superUserDashboard/user/SuperUserSelectedUserObject.vue";
import CustomerProductDiscountDisplay from "@/components/displays/department/pos/displays/CustomerProductDiscountDisplay.vue";
const product = {
id: 101,
category: 9,
category_id: 9,
name: "Premium wash",
price: 1000,
apply_category_discount: 1,
};
const globalDiscount = {
id: 999999,
product_or_category_id: "global",
is_category: 1,
percentage: 50,
fixed_price: null,
};
const categoryDiscount = {
id: 200,
product_or_category_id: 9,
is_category: 1,
percentage: 80,
fixed_price: null,
};
beforeEach(() => {
user.discounts.value = [];
});
describe("customer product fixed prices", () => {
it("uses a direct fixed product price as the effective price without changing discount selection", () => {
user.discounts.value = [
globalDiscount,
categoryDiscount,
{
id: 300,
product_or_category_id: 101,
is_category: 0,
percentage: 10,
fixed_price: 350,
},
];
expect(getProductBestApplicableDiscount(product)).toBe(80);
expect(getUserProductFixedPrice(product)).toBe(350);
expect(getProductEffectivePrice(product)).toBe(350);
});
it("falls back to the existing best-discount calculation when fixed price is not set", () => {
user.discounts.value = [
globalDiscount,
{
...categoryDiscount,
percentage: 30,
},
{
id: 300,
product_or_category_id: 101,
is_category: 0,
percentage: 10,
fixed_price: null,
},
];
expect(getUserProductFixedPrice(product)).toBeNull();
expect(getProductBestApplicableDiscount(product)).toBe(50);
expect(getProductEffectivePrice(product)).toBe(500);
});
it("treats zero as a set fixed price", () => {
user.discounts.value = [
{
id: 300,
product_or_category_id: 101,
is_category: 0,
percentage: 10,
fixed_price: 0,
},
];
expect(getUserProductFixedPrice(product)).toBe(0);
expect(getProductEffectivePrice(product)).toBe(0);
});
it("shows fixed price instead of discount percentage in the POS product badge", () => {
const wrapper = mount(CustomerProductDiscountDisplay, {
props: {
product,
customer_discounts: [
categoryDiscount,
{
id: 300,
product_or_category_id: 101,
is_category: 0,
percentage: 10,
fixed_price: 350,
},
],
},
});
expect(wrapper.text()).toContain("350 Kr.");
expect(wrapper.text()).not.toContain("-80%");
});
});
@@ -85,18 +85,6 @@ const makeOverview = ({
state: "ready",
value: 3,
out_of: 9,
target_percentage: "56.5",
target_department_id: "2",
},
{
product_id: 25,
slug: "faelg-flex",
title: "Fælg flex pr. enhed",
state: "ready",
value: 0,
out_of: 9,
target_percentage: 0,
target_department_id: 2,
},
],
},
@@ -227,15 +215,6 @@ describe("DepartmentDailyReportObject behavior", () => {
slug: "spot-free-lastbil",
value: 3,
out_of: 9,
target_percentage: 56.5,
target_department_id: 2,
});
expect(module.daily_report_products.value[25]).toMatchObject({
slug: "faelg-flex",
value: 0,
out_of: 9,
target_percentage: 0,
target_department_id: 2,
});
});
@@ -1,31 +1,11 @@
// @vitest-environment jsdom
import { mount } from "@vue/test-utils";
import { nextTick } from "vue";
import { beforeEach, describe, expect, it, vi } from "vitest";
const dailyReportProductsState = vi.hoisted(() => ({ value: {} }));
const selectedDepartmentIdsState = vi.hoisted(() => ({ value: [] }));
const refreshOverviewMock = vi.hoisted(() => vi.fn());
const hasPermissionMock = vi.hoisted(() => vi.fn());
const setProductTargetMock = vi.hoisted(() => vi.fn());
vi.mock("@/views/dashboards/departmentDashboard/modules/daily-report/DepartmentDailyReportObject.vue", () => ({
daily_report_products: dailyReportProductsState,
selected_department_ids: selectedDepartmentIdsState,
refreshOverview: refreshOverviewMock,
}));
vi.mock("@/components/session/token/SessionUser.vue", () => ({
SessionUser: {
hasPermission: hasPermissionMock,
objects: {
department_daily_reports: {
functions: {
setProductTarget: setProductTargetMock,
},
},
},
},
}));
vi.mock("vue-i18n", async (importOriginal) => {
@@ -44,12 +24,6 @@ import DepartmentDashboardDailyReportProductSales from "@/views/dashboards/depar
describe("DepartmentDashboardDailyReportProductSales behavior", () => {
beforeEach(() => {
dailyReportProductsState.value = {};
selectedDepartmentIdsState.value = [];
refreshOverviewMock.mockReset();
hasPermissionMock.mockReset();
hasPermissionMock.mockReturnValue(false);
setProductTargetMock.mockReset();
setProductTargetMock.mockResolvedValue({ data: { data: { target_percentage: null } } });
});
it("renders the API title when the overview payload includes one", () => {
@@ -105,71 +79,4 @@ describe("DepartmentDashboardDailyReportProductSales behavior", () => {
expect(missingTileWrapper.text()).toContain("Tillæg for Specialsæbe - DD");
});
it("shows a saved target percentage below the product percentage", () => {
dailyReportProductsState.value = {
24: {
title: "Spot Free (Lastbil)",
value: 3,
out_of: 8,
state: "ready",
message: null,
target_percentage: 62.5,
target_department_id: 1,
},
};
const wrapper = mount(DepartmentDashboardDailyReportProductSales, {
props: {
product_id: 24,
subtitle: "Dagens salg af produktet",
dataTestid: "daily-report-tile-spot-free-lastbil",
},
});
expect(wrapper.get('[data-testid="daily-report-tile-spot-free-lastbil-target-button"]').text()).toContain("62.5%");
});
it("opens the target editor from the percentage button and saves through the daily report API", async () => {
selectedDepartmentIdsState.value = [1];
hasPermissionMock.mockImplementation((permission) => permission === "set_department_daily_report_product_targets");
setProductTargetMock.mockResolvedValue({ data: { data: { target_percentage: 70 } } });
dailyReportProductsState.value = {
24: {
title: "Spot Free (Lastbil)",
value: 3,
out_of: 8,
state: "ready",
message: null,
target_percentage: null,
target_department_id: null,
},
};
const wrapper = mount(DepartmentDashboardDailyReportProductSales, {
props: {
product_id: 24,
subtitle: "Dagens salg af produktet",
dataTestid: "daily-report-tile-spot-free-lastbil",
},
});
await wrapper.get('[data-testid="daily-report-tile-spot-free-lastbil-percentage-button"]').trigger("click");
await nextTick();
await wrapper.get('[data-testid="daily-report-tile-spot-free-lastbil-target-input"]').setValue("70");
await wrapper.find("form").trigger("submit");
await nextTick();
await Promise.resolve();
expect(setProductTargetMock).toHaveBeenCalledWith({
department_id: 1,
product_id: 24,
target_percentage: 70,
});
expect(refreshOverviewMock).toHaveBeenCalledTimes(1);
expect(dailyReportProductsState.value[24]).toMatchObject({
target_percentage: 70,
target_department_id: 1,
});
});
});
@@ -1,94 +0,0 @@
// @vitest-environment jsdom
import { mount, flushPromises } from "@vue/test-utils";
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
authenticatedRequest: vi.fn(),
handleEconomicError: vi.fn(),
}));
vi.mock("@/components/session/authenticatedRequest.vue", () => ({
authenticatedRequest: mocks.authenticatedRequest,
}));
vi.mock("@/components/request/HandleEconomicError.vue", () => ({
handleEconomicError: mocks.handleEconomicError,
}));
import GetOrderInvoicePDFButton from "@/components/search/economic/getOrderInvoicePDFButton.vue";
const LoadButtonWhileAwaitStub = {
props: ["disabled", "loadFunction", "actionKey"],
template: `
<button
type="button"
:disabled="disabled"
:data-action-key="actionKey"
@click="loadFunction"
>
<slot />
</button>
`,
};
describe("GetOrderInvoicePDFButton", () => {
beforeEach(() => {
mocks.authenticatedRequest.mockReset();
mocks.handleEconomicError.mockReset();
vi.stubGlobal("open", vi.fn());
});
it.each([null, undefined, ""])("disables the PDF download when invoice id is %s", async (invoiceId) => {
const wrapper = mount(GetOrderInvoicePDFButton, {
props: {
invoice_id: invoiceId,
},
global: {
stubs: {
LoadButtonWhileAwait: LoadButtonWhileAwaitStub,
},
},
});
const button = wrapper.get('[data-action-key="economic-invoice-pdf-download"]');
expect(button.attributes("disabled")).toBeDefined();
await button.trigger("click");
await flushPromises();
expect(mocks.authenticatedRequest).not.toHaveBeenCalled();
expect(window.open).not.toHaveBeenCalled();
});
it("requests and opens the invoice PDF when invoice id exists", async () => {
mocks.authenticatedRequest.mockResolvedValue({
data: {
data: {
url: "https://pdf.example.test/invoices/99101.pdf",
},
},
});
const wrapper = mount(GetOrderInvoicePDFButton, {
props: {
invoice_id: 99101,
},
global: {
stubs: {
LoadButtonWhileAwait: LoadButtonWhileAwaitStub,
},
},
});
const button = wrapper.get('[data-action-key="economic-invoice-pdf-download"]');
expect(button.attributes("disabled")).toBeUndefined();
await button.trigger("click");
await flushPromises();
expect(mocks.authenticatedRequest).toHaveBeenCalledWith("/invoices/pdf", "GET", {
id: 99101,
});
expect(window.open).toHaveBeenCalledWith("https://pdf.example.test/invoices/99101.pdf", "_blank");
});
});
@@ -25,125 +25,14 @@ vi.mock("@/components/session/token/SessionUser/Objects/systemUserIds.js", () =>
getSystemUserIds: () => [],
}));
vi.mock("@/components/session/token/SessionUser.vue", () => ({
SessionUser: {
objects: {
global: {
language: {
no_data: "No data",
},
},
products: {
get: {
all: vi.fn(),
},
},
},
},
}));
import Swal from "sweetalert2";
import { authenticatedRequest } from "@/components/session/authenticatedRequest.vue";
import { ObjectsGlobal } from "@/components/session/token/SessionUser/Objects/ObjectsGlobal.vue";
import { Products } from "@/components/session/token/SessionUser/Objects/Products.vue";
beforeEach(() => {
vi.clearAllMocks();
ObjectsGlobal.clearCache();
document.body.innerHTML = "";
});
describe("ObjectsGlobal query parameters", () => {
it("omits nullish object GET parameters while preserving false and zero", async () => {
authenticatedRequest.mockResolvedValueOnce({
data: {
data: {
id: 40,
},
},
});
await expect(
ObjectsGlobal.get.object("/products", {
id: 40,
department_id: null,
customer_id: undefined,
category_id: null,
final_price: false,
page: 0,
})
).resolves.toEqual({
id: 40,
});
expect(authenticatedRequest).toHaveBeenCalledWith("/products?id=40&final_price=false&page=0", "GET");
});
it("omits nullish object list parameters while preserving false", async () => {
authenticatedRequest.mockResolvedValueOnce({
data: {
data: [],
},
});
await expect(
ObjectsGlobal.get.objects("/products", {
department_id: null,
customer_id: undefined,
final_price: false,
})
).resolves.toEqual([]);
expect(authenticatedRequest).toHaveBeenCalledWith("/products", "GET", {
final_price: false,
});
});
});
describe("Products query parameters", () => {
it("omits nullish default pricing parameters for single product GETs", async () => {
authenticatedRequest.mockResolvedValueOnce({
data: {
data: {
id: 40,
},
},
});
await expect(Products.get.single(40)).resolves.toEqual({
id: 40,
});
expect(authenticatedRequest).toHaveBeenCalledWith("/products?id=40&final_price=false", "GET");
});
it("preserves explicit product pricing parameters", async () => {
authenticatedRequest.mockResolvedValueOnce({
data: {
data: {
id: 40,
},
},
});
await expect(
Products.get.single(40, {
department_id: 2,
customer_id: 12345,
category_id: 8,
final_price: true,
})
).resolves.toEqual({
id: 40,
});
expect(authenticatedRequest).toHaveBeenCalledWith(
"/products?id=40&department_id=2&customer_id=12345&category_id=8&final_price=true",
"GET"
);
});
});
describe("ObjectsGlobal select editor escaping", () => {
it("escapes option ids and names before rendering SweetAlert HTML", async () => {
const object = {
+5 -50
View File
@@ -30,76 +30,31 @@ describe("Playwright full E2E workflow grouping", () => {
);
});
it("keeps self-hosted full-suite runner pressure bounded while hosted dispatch can fan out", () => {
it("keeps full-suite runner pressure bounded and diagnosable", () => {
const source = workflowSource();
expect(source).toContain("FRONTEND_CI_STANDARD_RUNNER");
expect(source).toContain("FRONTEND_CI_E2E_RUNNER");
expect(source).toContain("FRONTEND_CI_PR_E2E_MAX_PARALLEL");
expect(source).toContain("FRONTEND_CI_FULL_E2E_MAX_PARALLEL");
expect(source).toMatch(/e2e-pr:[\s\S]*?max-parallel: \$\{\{ fromJSON\(vars\.FRONTEND_CI_PR_E2E_MAX_PARALLEL/u);
expect(source).toMatch(/e2e-full:[\s\S]*?max-parallel: \$\{\{ fromJSON\(vars\.FRONTEND_CI_FULL_E2E_MAX_PARALLEL/u);
expect(source).toMatch(/e2e-full:[\s\S]*?max-parallel: 2/u);
expect(source).toMatch(/e2e-full:[\s\S]*?PLAYWRIGHT_WORKERS: 1/u);
expect(source).toMatch(/e2e-full:[\s\S]*?PLAYWRIGHT_VIDEO_MODE: off/u);
expect(source).toContain("scripts/ci/with-systemd-inhibit.sh");
expect(source).toContain("scripts/ci/runner-diagnostics.sh");
});
it("diffs pull request changed-area tests against the PR head instead of the merge commit", () => {
const source = workflowSource();
expect(source).toContain("PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}");
expect(source).toMatch(
/if \[\[ "\$EVENT_NAME" == "pull_request" && -n "\$PR_BASE_SHA" \]\]; then[\s\S]*?head_ref="\$PR_HEAD_SHA"/u
);
expect(source).toContain('echo "head=$head_ref" >> "$GITHUB_OUTPUT"');
});
it("keeps PR E2E runner pressure bounded and diagnosable", () => {
const source = workflowSource();
expect(source).toContain("FRONTEND_CI_E2E_RUNNER");
expect(source).toMatch(
/e2e-pr:[\s\S]*?max-parallel: \$\{\{ fromJSON\(vars\.FRONTEND_CI_PR_E2E_MAX_PARALLEL \|\| '2'\) \}\}/u
);
expect(source).toMatch(/e2e-pr:[\s\S]*?max-parallel: 4/u);
expect(source).toMatch(/e2e-pr:[\s\S]*?PLAYWRIGHT_WORKERS: 1/u);
expect(source).toMatch(/e2e-pr:[\s\S]*?PLAYWRIGHT_VIDEO_MODE: on-first-retry/u);
expect(source).toMatch(/e2e-pr:[\s\S]*?--env PLAYWRIGHT_WORKERS="\$PLAYWRIGHT_WORKERS"/u);
expect(source).toMatch(/e2e-pr:[\s\S]*?--env PLAYWRIGHT_VIDEO_MODE="\$PLAYWRIGHT_VIDEO_MODE"/u);
});
it("supports repo-variable runner controls while keeping targeted reruns on Ubuntu", () => {
const source = workflowSource();
expect(source).toContain("FRONTEND_CI_STANDARD_RUNNER");
expect(source).toContain("FRONTEND_CI_E2E_RUNNER");
expect(source).toContain('["self-hosted","Linux","X64","pleno","frontend"]');
expect(source).toMatch(/e2e-targeted:[\s\S]*?runs-on: ubuntu-24\.04/u);
expect(source).toMatch(/e2e-pr:[\s\S]*?runs-on: \$\{\{ fromJSON\(vars\.FRONTEND_CI_E2E_RUNNER/u);
expect(source).toMatch(/e2e-full:[\s\S]*?frontend","docker"\]/u);
});
it("supports targeted manual Playwright reruns on GitHub-hosted runners", () => {
const source = workflowSource();
expect(source).toContain("workflow_dispatch:");
expect(source).toContain("targeted-then-full");
expect(source).toContain("target_specs:");
expect(source).toContain("target_projects:");
expect(source).toContain("e2e-targeted:");
expect(source).toContain("matrix:");
expect(source).toContain("project: ${{ fromJSON(inputs.target_projects || '[\"chromium-desktop\"]') }}");
expect(source).toMatch(/e2e-targeted:[\s\S]*?runs-on: ubuntu-24\.04/u);
expect(source).toContain('npx playwright test "${args[@]}"');
expect(source).toContain('"$spec_path" != tests/e2e/*');
expect(source).toMatch(/e2e-pr:[\s\S]*?needs: \[build-and-unit, e2e-targeted\]/u);
});
it("uses a machine-wide Playwright port lock across self-hosted runner processes", () => {
const source = workflowSource();
expect(source.match(/PLAYWRIGHT_PORT_LOCK_ROOT:-\/tmp\/pleno-playwright-port-locks/gu)).toHaveLength(3);
expect(source.match(/chmod 1777 "\$lock_root"/gu)).toHaveLength(3);
expect(source.match(/PLAYWRIGHT_PORT_LOCK_ROOT:-\/tmp\/pleno-playwright-port-locks/gu)).toHaveLength(2);
expect(source.match(/chmod 1777 "\$lock_root"/gu)).toHaveLength(2);
expect(source).not.toContain("${RUNNER_TEMP:-/tmp}/pleno-playwright-port-locks");
});
+3 -33
View File
@@ -31,41 +31,21 @@ describe("Playwright PR mapping", () => {
});
it("maps department notification table changes to the admin notification E2E coverage", () => {
const notificationPaginationSpecs = specsFor(
"src/components/displays/pagination/models/DepartmentPos/NotificationsPhonePagination.vue"
);
expect(
specsFor("src/views/dashboards/departmentDashboard/modules/notifications/DepartmentNotifications.vue")
).toContain("tests/e2e/admin-department-notifications.spec.ts");
expect(
specsFor("src/components/displays/department/notifications/departmentNotificationsPhoneTable.vue")
).toContain("tests/e2e/admin-department-notifications.spec.ts");
expect(notificationPaginationSpecs).toContain("tests/e2e/admin-department-notifications.spec.ts");
expect(notificationPaginationSpecs).not.toContain("tests/e2e/pos-flow.spec.js");
expect(notificationPaginationSpecs).not.toContain("tests/e2e/pos-mobile-order-flow.spec.js");
expect(notificationPaginationSpecs).not.toContain("tests/e2e/admin-pos-orders.spec.ts");
});
it("maps admin daily-report changes to daily-report E2E coverage", () => {
expect(
specsFor(
"src/views/dashboards/departmentDashboard/modules/daily-report/displays/DepartmentDashboardDailyReportProductSales.vue"
)
).toContain("tests/e2e/admin-daily-report.spec.ts");
expect(specsFor("src/components/session/token/SessionUser/Objects/DepartmentDailyReports.vue")).toContain(
"tests/e2e/admin-daily-report.spec.ts"
);
specsFor("src/components/displays/pagination/models/DepartmentPos/NotificationsPhonePagination.vue")
).toContain("tests/e2e/admin-department-notifications.spec.ts");
});
it("maps limited backoffice view and service changes to limited backoffice E2E coverage", () => {
it("maps limited backoffice view changes to limited backoffice E2E coverage", () => {
expect(specsFor("src/views/backoffice/LimitedBackofficePrices.vue")).toContain(
"tests/e2e/limited-backoffice.spec.ts"
);
expect(specsFor("src/views/backoffice/components/LimitedBackofficeLayout.vue")).toContain(
"tests/e2e/limited-backoffice.spec.ts"
);
expect(specsFor("src/services/limitedBackoffice.js")).toContain("tests/e2e/limited-backoffice.spec.ts");
});
it("maps superuser role permission page changes to role permissions E2E coverage", () => {
@@ -77,15 +57,6 @@ describe("Playwright PR mapping", () => {
);
});
it("maps superuser user detail changes to the superuser users E2E coverage", () => {
expect(specsFor("src/views/dashboards/superUserDashboard/user/User.vue")).toContain(
"tests/e2e/superuser-users.spec.ts"
);
expect(
specsFor("src/views/dashboards/superUserDashboard/user/displays/other/UserOtherSpecialArrangement.vue")
).toContain("tests/e2e/superuser-users.spec.ts");
});
it("maps superuser dashboard shell changes to system status E2E coverage", () => {
expect(specsFor("src/views/dashboards/superUserDashboard/SuperUserDashboardNavigation.vue")).toContain(
"tests/e2e/superuser-system-status.smoke.spec.js"
@@ -104,7 +75,6 @@ describe("Playwright PR mapping", () => {
it("maps customer product rule changes to POS customer rule E2E coverage", () => {
expect(specsFor("src/features/customer/customerProductRules.js")).toContain("tests/e2e/pos-customer-rules.spec.js");
expect(specsFor("src/components/displays/boxes/ProductBox.vue")).toContain("tests/e2e/pos-customer-rules.spec.js");
expect(specsFor("src/components/shop/POSDepartmentProcess.vue")).toContain("tests/e2e/admin-pos-orders.spec.ts");
});
it("maps limited backoffice changes to the limited backoffice E2E coverage", () => {
@@ -1,42 +0,0 @@
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
const readSource = (relativePath) =>
readFileSync(fileURLToPath(new URL(`../../${relativePath}`, import.meta.url)), "utf8");
describe("Superuser user overview source", () => {
const overviewWidgetSources = [
"src/views/dashboards/superUserDashboard/user/User.vue",
"src/views/dashboards/superUserDashboard/user/SuperUserSelectedUserObject.vue",
"src/views/dashboards/superUserDashboard/user/displays/UserDefaultDepartment.vue",
"src/views/dashboards/superUserDashboard/user/displays/UserFixedPricing.vue",
"src/views/dashboards/superUserDashboard/user/displays/other/UserOtherSpecialArrangement.vue",
"src/views/dashboards/superUserDashboard/user/displays/other/UserOtherVaskeabonnement.vue",
"src/views/dashboards/superUserDashboard/user/displays/vehicles/UserVehicleSubscriptionsDisplay.vue",
];
it("keeps the overview page on the cleaned management hub implementation", () => {
const source = readSource("src/views/dashboards/superUserDashboard/user/User.vue");
expect(source).toContain('data-testid="superuser-user-overview-page"');
expect(source).toContain("superuser-user-overview-customer-management");
expect(source).toContain("superuser-user-overview-subscriptions");
expect(source).not.toContain("SessionUser.valueOf()");
expect(source).not.toContain("JSON.stringify(user");
});
it("keeps the selected user state loadable and retry-aware", () => {
const source = readSource("src/views/dashboards/superUserDashboard/user/SuperUserSelectedUserObject.vue");
expect(source).toContain("isUserLoading");
expect(source).toContain("userLoadError");
expect(source).toContain("activeLoadPromise");
});
it("keeps the overview and directly embedded widgets free of debug logging", () => {
for (const relativePath of overviewWidgetSources) {
expect(readSource(relativePath), relativePath).not.toContain("console.log");
}
});
});
@@ -356,7 +356,6 @@ describe("system search card view-model behavior", () => {
id: 326,
customer_number: 12345679,
discount: 12.5,
fixed_price: 350,
object_id: "global",
is_category: true,
created_at: "2026-03-12T09:15:00Z",
@@ -365,7 +364,6 @@ describe("system search card view-model behavior", () => {
);
expect(vm.keyFields.some((entry) => entry.label === "Discount" && entry.value === "12.5%")).toBe(true);
expect(vm.keyFields.some((entry) => entry.label === "Fixed price" && entry.value === "350")).toBe(true);
expect(vm.keyFields.some((entry) => entry.label === "Target" && entry.value === "global")).toBe(true);
expect(vm.keyFields.some((entry) => entry.label === "Category" && entry.value === "Yes")).toBe(true);
expect(vm.keyFields.some((entry) => entry.label === "Created" && entry.value.includes("2026-03-12"))).toBe(true);
@@ -1,159 +0,0 @@
// @vitest-environment jsdom
import { flushPromises } from "@vue/test-utils";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { mountWithApp } from "./helpers/mountWithApp.js";
const mocks = vi.hoisted(() => {
const device = {
isMobile: vi.fn(() => false),
isTablet: vi.fn(() => false),
isDesktop: vi.fn(() => true),
isWidescreen: vi.fn(() => false),
isUltraWideScreen: vi.fn(() => false),
};
return {
authenticatedRequest: vi.fn(),
sessionUser: {
isSubuser: {
value: false,
},
subuser: {
selectedGrantCustomerNumber: {
value: null,
},
},
permissions: {
value: ["user"],
},
hasPermission: vi.fn((permission) => permission === "user"),
canAccessCustomerFeature: vi.fn(() => true),
canManageSubusers: vi.fn(() => false),
getName: vi.fn(() => "E2E User"),
functions: {
device,
},
},
};
});
vi.mock("@/components/session/authenticatedRequest.vue", () => ({
authenticatedRequest: mocks.authenticatedRequest,
}));
vi.mock("@/components/session/token/SessionUser.vue", () => ({
default: mocks.sessionUser,
}));
import UserDashboard from "@/views/dashboards/UserDashboard.vue";
const flushDashboard = async () => {
await flushPromises();
await flushPromises();
};
const RouterLinkStub = {
props: ["to"],
template: "<a v-bind=\"$attrs\" :href=\"typeof to === 'string' ? to : '#'\"><slot /></a>",
};
const mountDashboard = () =>
mountWithApp(UserDashboard, {
global: {
stubs: {
RouterLink: RouterLinkStub,
"router-link": RouterLinkStub,
},
},
});
describe("UserDashboard invoice shortcut", () => {
beforeEach(() => {
mocks.authenticatedRequest.mockReset();
mocks.sessionUser.isSubuser.value = false;
mocks.sessionUser.permissions.value = ["user"];
mocks.sessionUser.hasPermission.mockReset();
mocks.sessionUser.hasPermission.mockImplementation((permission) => permission === "user");
mocks.sessionUser.canAccessCustomerFeature.mockReset();
mocks.sessionUser.canAccessCustomerFeature.mockReturnValue(true);
mocks.sessionUser.canManageSubusers.mockReset();
mocks.sessionUser.canManageSubusers.mockReturnValue(false);
});
it("keeps the invoice shortcut disabled while invoice availability is loading", () => {
mocks.authenticatedRequest.mockReturnValue(new Promise(() => {}));
const wrapper = mountDashboard();
const button = wrapper.get("button#download-invoices-button");
expect(button.attributes("disabled")).toBeDefined();
expect(button.classes()).toContain("is-loading");
expect(wrapper.find("a#download-invoices-button").exists()).toBe(false);
wrapper.unmount();
});
it("keeps the invoice shortcut disabled when no invoice exists", async () => {
mocks.authenticatedRequest.mockResolvedValue({
data: {
data: [],
meta: {
pagination: {
total: 0,
},
},
},
});
const wrapper = mountDashboard();
await flushDashboard();
const button = wrapper.get("button#download-invoices-button");
expect(button.attributes("disabled")).toBeDefined();
expect(button.classes()).not.toContain("is-loading");
expect(wrapper.find("a#download-invoices-button").exists()).toBe(false);
expect(mocks.authenticatedRequest).toHaveBeenCalledWith("/user/invoices", "GET", {
page: 1,
limit: 1,
order: "created_at:desc",
});
wrapper.unmount();
});
it("enables the invoice shortcut when at least one invoice exists", async () => {
mocks.authenticatedRequest.mockResolvedValue({
data: {
data: [{ id: 501 }],
meta: {
pagination: {
total: 1,
},
},
},
});
const wrapper = mountDashboard();
await flushDashboard();
const link = wrapper.get("a#download-invoices-button");
expect(link.attributes("href")).toBe("/user/invoices");
expect(wrapper.find("button#download-invoices-button").exists()).toBe(false);
wrapper.unmount();
});
it("fails closed when invoice availability cannot be loaded", async () => {
mocks.authenticatedRequest.mockRejectedValue(new Error("Network unavailable"));
const wrapper = mountDashboard();
await flushDashboard();
const button = wrapper.get("button#download-invoices-button");
expect(button.attributes("disabled")).toBeDefined();
expect(wrapper.find("a#download-invoices-button").exists()).toBe(false);
wrapper.unmount();
});
});