Skip to content

Enhancement/31 salecalculator class #45

Merged
merged 3 commits into from
Feb 20, 2026
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 78 additions & 0 deletions src/main/java/edu/ntnu/idi/idatt2003/g40/mappe/SaleCalculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package edu.ntnu.idi.idatt2003.g40.mappe;

import java.math.BigDecimal;

/**
* Calculator for sale transactions.
* <p>
* Calculates gross value, commission, tax and total sale value
* based on the share's purchase price, current sales price and quantity.
* </p>
*/
public class SaleCalculator implements TransactionCalculator {

private static final BigDecimal COMMISSION_RATE = new BigDecimal("0.01"); // 1%
private static final BigDecimal TAX_RATE = new BigDecimal("0.30"); // 30%

private final BigDecimal purchasePrice;
private final BigDecimal salesPrice;
private final BigDecimal quantity;

/**
* Creates a new {@code SaleCalculator} based on a share.
*
* @param share the share to base calculations on
*/
public SaleCalculator(Share share) {
this.purchasePrice = share.getPurchasePrice();
this.salesPrice = share.getStock().getSalesPrice();
this.quantity = share.getQuantity();
}

/**
* {@inheritDoc}
* Gross value = salesPrice * quantity.
*/
@Override
public BigDecimal calculateGross() {
return salesPrice.multiply(quantity);
}

/**
* {@inheritDoc}
* Commission = 1% of gross value.
*/
@Override
public BigDecimal calculateCommission() {
return calculateGross().multiply(COMMISSION_RATE);
}

/**
* {@inheritDoc}
* Tax = 30% of profit.
* Profit = gross - commission - (purchasePrice * quantity).
* If profit is negative or zero, tax is zero.
*/
@Override
public BigDecimal calculateTax() {
BigDecimal purchaseCost = purchasePrice.multiply(quantity);
BigDecimal profit = calculateGross()
.subtract(calculateCommission())
.subtract(purchaseCost);

return profit.signum() > 0
? profit.multiply(TAX_RATE)
: BigDecimal.ZERO;
}

/**
* {@inheritDoc}
* Total value = gross - commission - tax.
*/
@Override
public BigDecimal calculateTotal() {
return calculateGross()
.subtract(calculateCommission())
.subtract(calculateTax());
}
}