1 Commits

Author SHA1 Message Date
agentd
5d83ffaa76 Mengenrabatt: Staffel im Rechner und eine Seite im Web
agentd task 4027a3aa01be47e9b677e7c687e4b183
2026-08-07 13:04:33 +00:00
15 changed files with 516 additions and 224 deletions

View File

@@ -16,7 +16,57 @@ public static class PriceCalculator
throw new ArgumentOutOfRangeException(nameof(discountPercent), "A discount is between 0 and 100 percent."); throw new ArgumentOutOfRangeException(nameof(discountPercent), "A discount is between 0 and 100 percent.");
} }
var raw = price * (100 - discountPercent) / 100; return price * (1m - discountPercent / 100m);
return Math.Round(raw / 0.05m, MidpointRounding.AwayFromZero) * 0.05m; }
/// <summary>Rounds an amount to the nearest 0.05, rounding halves away from zero.</summary>
public static decimal RoundToFiveRappen(decimal amount)
{
return Math.Round(amount * 20m, MidpointRounding.AwayFromZero) / 20m;
}
/// <summary>Returns the quantity discount percent for a quantity: 0, 5 or 10.</summary>
public static int GetQuantityDiscountPercent(int quantity)
{
if (quantity < 1)
{
throw new ArgumentOutOfRangeException(nameof(quantity), "A quantity must be at least 1.");
}
return quantity switch
{
>= 50 => 10,
>= 10 => 5,
_ => 0,
};
}
/// <summary>
/// Calculates the total: percentage discount on the unit price first, then the quantity
/// discount on the total, then rounds the end amount to the nearest 0.05.
/// </summary>
public static decimal CalculateTotal(decimal unitPrice, int quantity, decimal discountPercent)
{
if (unitPrice < 0)
{
throw new ArgumentOutOfRangeException(nameof(unitPrice), "A price cannot be negative.");
}
if (quantity < 1)
{
throw new ArgumentOutOfRangeException(nameof(quantity), "A quantity must be at least 1.");
}
if (discountPercent is < 0 or > 100)
{
throw new ArgumentOutOfRangeException(nameof(discountPercent), "A discount is between 0 and 100 percent.");
}
var discountedUnitPrice = ApplyDiscount(unitPrice, discountPercent);
var totalBeforeQuantityDiscount = discountedUnitPrice * quantity;
var quantityDiscountPercent = GetQuantityDiscountPercent(quantity);
var totalBeforeRounding = totalBeforeQuantityDiscount * (1m - quantityDiscountPercent / 100m);
return RoundToFiveRappen(totalBeforeRounding);
} }
} }

View File

@@ -35,29 +35,92 @@ public sealed class PriceCalculatorTests
} }
[Fact] [Fact]
public void Swiss_rounding_example() public void Quantity_9_gets_no_quantity_discount()
{ {
// 99.90 * 90 / 100 = 89.91, gerundet auf 0.05 = 89.90 Assert.Equal(0, PriceCalculator.GetQuantityDiscountPercent(9));
Assert.Equal(89.90m, PriceCalculator.ApplyDiscount(99.90m, 10m));
} }
[Fact] [Fact]
public void Swiss_rounding_exact() public void Quantity_10_gets_five_percent_quantity_discount()
{ {
// 100.00 * 85 / 100 = 85.00, exakt ein 0.05-Vielfaches Assert.Equal(5, PriceCalculator.GetQuantityDiscountPercent(10));
Assert.Equal(85.00m, PriceCalculator.ApplyDiscount(100.00m, 15m));
} }
[Fact] [Fact]
public void Swiss_rounding_midpoint_up() public void Quantity_49_gets_five_percent_quantity_discount()
{ {
// 10.00 * 95 / 100 = 9.50, exakt Assert.Equal(5, PriceCalculator.GetQuantityDiscountPercent(49));
Assert.Equal(9.50m, PriceCalculator.ApplyDiscount(10.00m, 5m));
} }
[Fact] [Fact]
public void Negative_price_throws() public void Quantity_50_gets_ten_percent_quantity_discount()
{ {
Assert.Throws<ArgumentOutOfRangeException>(() => PriceCalculator.ApplyDiscount(-1m, 10m)); Assert.Equal(10, PriceCalculator.GetQuantityDiscountPercent(50));
}
[Fact]
public void Quantity_below_one_is_refused()
{
Assert.Throws<ArgumentOutOfRangeException>(() => PriceCalculator.GetQuantityDiscountPercent(0));
}
[Fact]
public void Total_applies_five_percent_quantity_discount()
{
Assert.Equal(950m, PriceCalculator.CalculateTotal(100m, 10, 0m));
}
[Fact]
public void Total_applies_percentage_discount_before_quantity_discount()
{
Assert.Equal(712.5m, PriceCalculator.CalculateTotal(100m, 10, 25m));
}
[Fact]
public void Total_applies_ten_percent_quantity_discount_for_fifty_pieces()
{
Assert.Equal(4500m, PriceCalculator.CalculateTotal(100m, 50, 0m));
}
[Fact]
public void Rounding_rounds_up_to_the_nearest_five_rappen()
{
Assert.Equal(1.25m, PriceCalculator.RoundToFiveRappen(1.23m));
}
[Fact]
public void Rounding_rounds_down_to_the_nearest_five_rappen()
{
Assert.Equal(1.20m, PriceCalculator.RoundToFiveRappen(1.21m));
}
[Fact]
public void Rounding_rounds_midpoints_away_from_zero()
{
Assert.Equal(1.15m, PriceCalculator.RoundToFiveRappen(1.125m));
}
[Fact]
public void Total_rounds_after_the_quantity_discount()
{
Assert.Equal(15.85m, PriceCalculator.CalculateTotal(1.67m, 10, 0m));
}
[Fact]
public void Total_refuses_a_negative_unit_price()
{
Assert.Throws<ArgumentOutOfRangeException>(() => PriceCalculator.CalculateTotal(-1m, 1, 0m));
}
[Fact]
public void Total_refuses_a_quantity_below_one()
{
Assert.Throws<ArgumentOutOfRangeException>(() => PriceCalculator.CalculateTotal(10m, 0, 0m));
}
[Fact]
public void Total_refuses_a_discount_above_100_percent()
{
Assert.Throws<ArgumentOutOfRangeException>(() => PriceCalculator.CalculateTotal(10m, 1, 101m));
} }
} }

View File

@@ -1,3 +1,9 @@
<main class="main"> <header class="app-header">
<h1 class="app-title">{{ title() }}</h1>
<nav class="app-nav">
<a routerLink="/mengenrabatt" class="app-nav-link">Mengenrabatt-Rechner</a>
</nav>
</header>
<main class="app-main">
<router-outlet /> <router-outlet />
</main> </main>

View File

@@ -1,9 +1,7 @@
import { Routes } from '@angular/router'; import { Routes } from '@angular/router';
import { DiscountCalculator } from './discount-calculator/discount-calculator'; import { MengenrabattRechner } from './mengenrabatt-rechner/mengenrabatt-rechner';
export const routes: Routes = [ export const routes: Routes = [
{ { path: 'mengenrabatt', component: MengenrabattRechner },
path: '', { path: '', pathMatch: 'full', redirectTo: 'mengenrabatt' },
component: DiscountCalculator,
},
]; ];

View File

@@ -0,0 +1,41 @@
:host {
display: block;
min-height: 100dvh;
font-family: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
color: var(--app-fg, #1a1a1a);
background: var(--app-bg, #f7f7f7);
}
.app-header {
display: flex;
align-items: center;
gap: 1.5rem;
padding: 1rem 1.5rem;
background: var(--app-header-bg, #ffffff);
border-bottom: 1px solid var(--app-border, #d0d0d0);
}
.app-title {
margin: 0;
font-size: 1.25rem;
font-weight: 600;
}
.app-nav {
display: flex;
gap: 1rem;
}
.app-nav-link {
color: var(--app-link, #0a58ca);
text-decoration: none;
}
.app-nav-link:hover,
.app-nav-link:focus {
text-decoration: underline;
}
.app-main {
display: block;
}

View File

@@ -1,6 +1,6 @@
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { App } from './app';
import { provideRouter } from '@angular/router'; import { provideRouter } from '@angular/router';
import { App } from './app';
import { routes } from './app.routes'; import { routes } from './app.routes';
describe('App', () => { describe('App', () => {
@@ -17,10 +17,20 @@ describe('App', () => {
expect(app).toBeTruthy(); expect(app).toBeTruthy();
}); });
it('should render the router outlet', async () => { it('should render the app title', async () => {
const fixture = TestBed.createComponent(App); const fixture = TestBed.createComponent(App);
fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
const compiled = fixture.nativeElement as HTMLElement; const compiled = fixture.nativeElement as HTMLElement;
expect(compiled.querySelector('router-outlet')).toBeTruthy(); expect(compiled.querySelector('h1')?.textContent).toContain('Preisrechner');
});
it('should render the navigation link to the volume discount calculator', async () => {
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
await fixture.whenStable();
const compiled = fixture.nativeElement as HTMLElement;
const link = compiled.querySelector('a[href="/mengenrabatt"]');
expect(link?.textContent).toContain('Mengenrabatt-Rechner');
}); });
}); });

View File

@@ -1,12 +1,13 @@
import { Component, signal } from '@angular/core'; import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { RouterOutlet } from '@angular/router'; import { RouterLink, RouterOutlet } from '@angular/router';
@Component({ @Component({
selector: 'app-root', selector: 'app-root',
imports: [RouterOutlet], changeDetection: ChangeDetectionStrategy.OnPush,
imports: [RouterOutlet, RouterLink],
templateUrl: './app.html', templateUrl: './app.html',
styleUrl: './app.scss' styleUrl: './app.scss',
}) })
export class App { export class App {
protected readonly title = signal('web'); protected readonly title = signal('Preisrechner');
} }

View File

@@ -1,39 +0,0 @@
<div class="calculator">
<h2>Rabattrechner</h2>
<div class="field">
<label for="price">Preis (CHF):</label>
<input
id="price"
type="number"
step="0.01"
min="0"
[value]="price()"
(input)="onPriceInput($event)"
placeholder="z. B. 99.90"
/>
</div>
<div class="field">
<label for="discount">Rabatt (%):</label>
<input
id="discount"
type="number"
step="0.1"
min="0"
max="100"
[value]="discountPercent()"
(input)="onDiscountInput($event)"
placeholder="z. B. 10"
/>
</div>
<button (click)="calculate()" class="btn">Berechnen</button>
@if (result() !== null) {
<div class="result">
<span class="result-label">Reduzierter Preis:</span>
<span class="result-value">{{ result()!.toFixed(2) }} CHF</span>
</div>
}
</div>

View File

@@ -1,79 +0,0 @@
.calculator {
max-width: 400px;
margin: 2rem auto;
padding: 2rem;
border: 1px solid #ddd;
border-radius: 8px;
background: #fafafa;
h2 {
margin-top: 0;
margin-bottom: 1.5rem;
font-size: 1.5rem;
color: #333;
}
.field {
margin-bottom: 1rem;
label {
display: block;
margin-bottom: 0.25rem;
font-weight: 500;
color: #555;
}
input {
width: 100%;
padding: 0.5rem;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 1rem;
box-sizing: border-box;
&:focus {
outline: none;
border-color: #007bff;
box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
}
}
}
.btn {
display: inline-block;
padding: 0.5rem 1.5rem;
font-size: 1rem;
color: #fff;
background: #007bff;
border: none;
border-radius: 4px;
cursor: pointer;
margin-top: 0.5rem;
&:hover {
background: #0056b3;
}
}
.result {
margin-top: 1.5rem;
padding: 1rem;
background: #e8f5e9;
border: 1px solid #c8e6c9;
border-radius: 4px;
text-align: center;
.result-label {
display: block;
font-size: 0.9rem;
color: #555;
margin-bottom: 0.25rem;
}
.result-value {
font-size: 1.75rem;
font-weight: 700;
color: #2e7d32;
}
}
}

View File

@@ -1,44 +0,0 @@
import { TestBed } from '@angular/core/testing';
import { DiscountCalculator } from './discount-calculator';
describe('DiscountCalculator', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [DiscountCalculator],
}).compileComponents();
});
it('should create the component', () => {
const fixture = TestBed.createComponent(DiscountCalculator);
const component = fixture.componentInstance;
expect(component).toBeTruthy();
});
it('should calculate 89.90 for price 99.90 and discount 10%', () => {
const fixture = TestBed.createComponent(DiscountCalculator);
const component = fixture.componentInstance;
component.price.set(99.90);
component.discountPercent.set(10);
component.calculate();
expect(component.result()).toBeCloseTo(89.90, 2);
});
it('should round to nearest 0.05 (Swiss Rappenrundung)', () => {
const fixture = TestBed.createComponent(DiscountCalculator);
const component = fixture.componentInstance;
component.price.set(10);
component.discountPercent.set(2.5);
component.calculate();
// 10 * (100 - 2.5) / 100 = 9.75 → rounded to 0.05 → 9.75
expect(component.result()).toBeCloseTo(9.75, 2);
});
it('should handle zero price', () => {
const fixture = TestBed.createComponent(DiscountCalculator);
const component = fixture.componentInstance;
component.price.set(0);
component.discountPercent.set(50);
component.calculate();
expect(component.result()).toBeCloseTo(0, 2);
});
});

View File

@@ -1,30 +0,0 @@
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-discount-calculator',
templateUrl: './discount-calculator.html',
styleUrl: './discount-calculator.scss',
})
export class DiscountCalculator {
readonly price = signal<number>(0);
readonly discountPercent = signal<number>(0);
readonly result = signal<number | null>(null);
onPriceInput(event: Event): void {
const input = event.target as HTMLInputElement;
this.price.set(parseFloat(input.value) || 0);
this.result.set(null);
}
onDiscountInput(event: Event): void {
const input = event.target as HTMLInputElement;
this.discountPercent.set(parseFloat(input.value) || 0);
this.result.set(null);
}
calculate(): void {
const discountedPrice = this.price() * (100 - this.discountPercent()) / 100;
const rounded = Math.round(discountedPrice / 0.05) * 0.05;
this.result.set(rounded);
}
}

View File

@@ -0,0 +1,54 @@
<section class="mengenrabatt-rechner">
<h1>Mengenrabatt-Rechner</h1>
<div class="field">
<label for="unit-price">Stückpreis (CHF)</label>
<input
id="unit-price"
type="number"
inputmode="decimal"
min="0"
step="0.05"
[value]="unitPriceInput()"
(input)="unitPriceInput.set($any($event.target).value)"
/>
</div>
<div class="field">
<label for="quantity">Menge</label>
<input
id="quantity"
type="number"
inputmode="numeric"
min="1"
step="1"
[value]="quantityInput()"
(input)="quantityInput.set($any($event.target).value)"
/>
</div>
<div class="field">
<label for="percent-discount">Prozentrabatt (%)</label>
<input
id="percent-discount"
type="number"
inputmode="decimal"
min="0"
max="100"
step="0.1"
[value]="percentDiscountInput()"
(input)="percentDiscountInput.set($any($event.target).value)"
/>
</div>
<dl class="result">
<div class="result-row">
<dt>Endbetrag</dt>
<dd data-testid="endbetrag">{{ endbetragLabel() }}</dd>
</div>
<div class="result-row">
<dt>Staffelstufe</dt>
<dd data-testid="staffelstufe">{{ staffelLabel() }}</dd>
</div>
</dl>
</section>

View File

@@ -0,0 +1,55 @@
.mengenrabatt-rechner {
display: grid;
gap: 1rem;
max-width: 32rem;
margin: 2rem auto;
padding: 1.5rem;
border: 1px solid var(--app-border, #d0d0d0);
border-radius: 0.5rem;
font-family: inherit;
}
.mengenrabatt-rechner h1 {
margin: 0;
font-size: 1.5rem;
}
.field {
display: grid;
gap: 0.25rem;
}
.field label {
font-weight: 600;
}
.field input {
padding: 0.5rem 0.75rem;
font: inherit;
border: 1px solid var(--app-border, #d0d0d0);
border-radius: 0.25rem;
}
.result {
display: grid;
gap: 0.5rem;
margin: 0;
padding-top: 1rem;
border-top: 1px solid var(--app-border, #d0d0d0);
}
.result-row {
display: flex;
justify-content: space-between;
align-items: baseline;
margin: 0;
}
.result-row dt {
font-weight: 600;
}
.result-row dd {
margin: 0;
font-variant-numeric: tabular-nums;
}

View File

@@ -0,0 +1,107 @@
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { MengenrabattRechner } from './mengenrabatt-rechner';
function setInputs(
fixture: ComponentFixture<MengenrabattRechner>,
unitPrice: string,
quantity: string,
percent: string,
): void {
const inputs = fixture.nativeElement.querySelectorAll('input');
(inputs[0] as HTMLInputElement).value = unitPrice;
inputs[0].dispatchEvent(new Event('input'));
(inputs[1] as HTMLInputElement).value = quantity;
inputs[1].dispatchEvent(new Event('input'));
(inputs[2] as HTMLInputElement).value = percent;
inputs[2].dispatchEvent(new Event('input'));
fixture.detectChanges();
}
function compute(unitPrice: string, quantity: string, percent: string): {
endbetrag: string;
staffelstufe: string;
} {
const fixture = TestBed.createComponent(MengenrabattRechner);
fixture.detectChanges();
setInputs(fixture, unitPrice, quantity, percent);
const compiled = fixture.nativeElement as HTMLElement;
return {
endbetrag: (compiled.querySelector('[data-testid="endbetrag"]')?.textContent ?? '').trim(),
staffelstufe: (compiled.querySelector('[data-testid="staffelstufe"]')?.textContent ?? '').trim(),
};
}
describe('MengenrabattRechner', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [MengenrabattRechner],
}).compileComponents();
});
describe('quantity tiers', () => {
it('uses the 0% tier for 9 pieces', () => {
const { endbetrag, staffelstufe } = compute('10', '9', '0');
expect(staffelstufe).toBe('0 % (19 Stück)');
expect(endbetrag).toContain('90.00');
});
it('switches to the 5% tier at 10 pieces', () => {
const { endbetrag, staffelstufe } = compute('10', '10', '0');
expect(staffelstufe).toBe('5 % (1049 Stück)');
expect(endbetrag).toContain('95.00');
});
it('stays on the 5% tier at 49 pieces', () => {
const { endbetrag, staffelstufe } = compute('1', '49', '0');
expect(staffelstufe).toBe('5 % (1049 Stück)');
// 1 * 0.95 * 49 = 46.55
expect(endbetrag).toContain('46.55');
});
it('switches to the 10% tier at 50 pieces', () => {
const { endbetrag, staffelstufe } = compute('1', '50', '0');
expect(staffelstufe).toBe('10 % (ab 50 Stück)');
// 1 * 0.9 * 50 = 45.00
expect(endbetrag).toContain('45.00');
});
});
describe('discount pipeline', () => {
it('applies percentage discount first, then the quantity tier discount (100/10/25 → 712.50)', () => {
const { endbetrag, staffelstufe } = compute('100', '10', '25');
// 100 * 0.75 = 75; 75 * 10 = 750; quantity tier 5%: 750 * 0.95 = 712.50
expect(endbetrag).toContain('712.50');
expect(staffelstufe).toBe('5 % (1049 Stück)');
});
});
describe('rounding to 0.05', () => {
it('rounds 1.23 up to 1.25', () => {
const { endbetrag } = compute('1.23', '1', '0');
// 1 piece is in the 19 tier (0%); rounded to 0.05: 1.23 -> 1.25
expect(endbetrag).toContain('1.25');
});
});
describe('invalid input', () => {
it('shows the placeholder when inputs are empty', () => {
const { endbetrag, staffelstufe } = compute('', '', '');
expect(endbetrag).toBe('—');
expect(staffelstufe).toBe('—');
});
it('shows the placeholder for a non-integer quantity', () => {
const { endbetrag } = compute('10', '3.5', '0');
expect(endbetrag).toBe('—');
});
});
describe('DOM output', () => {
it('renders the Endbetrag with two decimals and the German Staffelstufe label', () => {
const { endbetrag, staffelstufe } = compute('100', '10', '25');
expect(endbetrag).toMatch(/\d+\.\d{2}/);
expect(endbetrag).toContain('712.50');
expect(staffelstufe).toBe('5 % (1049 Stück)');
});
});
});

View File

@@ -0,0 +1,99 @@
import { ChangeDetectionStrategy, Component, computed, signal } from '@angular/core';
interface DiscountTier {
readonly minQuantity: number;
readonly maxQuantity: number | null;
readonly percent: number;
readonly label: string;
}
const TIERS: readonly DiscountTier[] = [
{ minQuantity: 1, maxQuantity: 9, percent: 0, label: '0 % (19 Stück)' },
{ minQuantity: 10, maxQuantity: 49, percent: 5, label: '5 % (1049 Stück)' },
{ minQuantity: 50, maxQuantity: null, percent: 10, label: '10 % (ab 50 Stück)' },
];
const PERCENT_DIVISOR = 100;
const ROUNDING_STEP = 20; // 1 / 0.05 → multiply before rounding
function tierFor(quantity: number): DiscountTier | null {
for (const tier of TIERS) {
if (quantity >= tier.minQuantity && (tier.maxQuantity === null || quantity <= tier.maxQuantity)) {
return tier;
}
}
return null;
}
function parseNumber(value: string): number | null {
if (value.trim() === '') {
return null;
}
const parsed = Number(value.replace(',', '.'));
return Number.isFinite(parsed) ? parsed : null;
}
function formatChf(value: number): string {
return `CHF\u00a0${value.toFixed(2)}`;
}
@Component({
selector: 'app-mengenrabatt-rechner',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [],
templateUrl: './mengenrabatt-rechner.html',
styleUrl: './mengenrabatt-rechner.scss',
})
export class MengenrabattRechner {
protected readonly unitPriceInput = signal('');
protected readonly quantityInput = signal('');
protected readonly percentDiscountInput = signal('');
private readonly unitPrice = computed(() => parseNumber(this.unitPriceInput()));
private readonly quantity = computed(() => {
const value = parseNumber(this.quantityInput());
if (value === null || !Number.isInteger(value) || value <= 0) {
return null;
}
return value;
});
private readonly percentDiscount = computed(() => {
const value = parseNumber(this.percentDiscountInput());
if (value === null || value < 0 || value > 100) {
return null;
}
return value;
});
protected readonly tier = computed<DiscountTier | null>(() => {
const quantity = this.quantity();
return quantity === null ? null : tierFor(quantity);
});
private readonly total = computed<number | null>(() => {
const unitPrice = this.unitPrice();
const quantity = this.quantity();
const percentDiscount = this.percentDiscount();
const tier = this.tier();
if (
unitPrice === null ||
unitPrice < 0 ||
quantity === null ||
percentDiscount === null ||
tier === null
) {
return null;
}
const discountedUnit = unitPrice * (1 - percentDiscount / PERCENT_DIVISOR);
const subtotal = discountedUnit * quantity;
const withTierDiscount = subtotal * (1 - tier.percent / PERCENT_DIVISOR);
return Math.round(withTierDiscount * ROUNDING_STEP) / ROUNDING_STEP;
});
protected readonly endbetragLabel = computed<string>(() => {
const value = this.total();
return value === null ? '—' : formatChf(value);
});
protected readonly staffelLabel = computed<string>(() => this.tier()?.label ?? '—');
}