feat: profit sharing

This commit is contained in:
Efril
2026-08-05 19:28:38 +07:00
parent 2b80c92caa
commit b9ac97178f
26 changed files with 1378 additions and 4 deletions
+239
View File
@@ -6,6 +6,7 @@ import (
"strings"
"time"
"apskel-pos-be/internal/constants"
"apskel-pos-be/internal/entities"
"apskel-pos-be/internal/models"
"apskel-pos-be/internal/repository"
@@ -19,6 +20,8 @@ type AnalyticsProcessor interface {
GetPurchasingAnalytics(ctx context.Context, req *models.PurchasingAnalyticsRequest) (*models.PurchasingAnalyticsResponse, error)
GetProductAnalytics(ctx context.Context, req *models.ProductAnalyticsRequest) (*models.ProductAnalyticsResponse, error)
GetProductAnalyticsPerCategory(ctx context.Context, req *models.ProductAnalyticsPerCategoryRequest) (*models.ProductAnalyticsPerCategoryResponse, error)
GetProductAnalyticsPerParentCategory(ctx context.Context, req *models.ProductAnalyticsPerParentCategoryRequest) (*models.ProductAnalyticsPerParentCategoryResponse, error)
GetParentCategoryAnalyticsDetail(ctx context.Context, req *models.ParentCategoryAnalyticsDetailRequest) (*models.ParentCategoryAnalyticsDetailResponse, error)
GetDashboardAnalytics(ctx context.Context, req *models.DashboardAnalyticsRequest) (*models.DashboardAnalyticsResponse, error)
GetProfitLossAnalytics(ctx context.Context, req *models.ProfitLossAnalyticsRequest) (*models.ProfitLossAnalyticsResponse, error)
GetExclusiveSummaryPeriod(ctx context.Context, req *models.ExclusiveSummaryPeriodRequest) (*models.ExclusiveSummaryPeriodResponse, error)
@@ -356,6 +359,242 @@ func (p *AnalyticsProcessorImpl) GetProductAnalyticsPerCategory(ctx context.Cont
}, nil
}
func (p *AnalyticsProcessorImpl) GetProductAnalyticsPerParentCategory(ctx context.Context, req *models.ProductAnalyticsPerParentCategoryRequest) (*models.ProductAnalyticsPerParentCategoryResponse, error) {
// Validate date range
if req.DateFrom.After(req.DateTo) {
return nil, fmt.Errorf("date_from cannot be after date_to")
}
// Get analytics data from repository
analyticsData, err := p.analyticsRepo.GetProductAnalyticsPerParentCategory(ctx, req.OrganizationID, req.OutletID, req.DateFrom, req.DateTo)
if err != nil {
return nil, fmt.Errorf("failed to get product analytics per parent category: %w", err)
}
// Transform data
var resultData []models.ProductAnalyticsPerParentCategoryData
for _, data := range analyticsData {
resultData = append(resultData, models.ProductAnalyticsPerParentCategoryData{
ParentCategoryID: data.ParentCategoryID,
ParentCategoryName: data.ParentCategoryName,
TotalRevenue: data.TotalRevenue,
TotalQuantity: data.TotalQuantity,
CategoryCount: data.CategoryCount,
ProductCount: data.ProductCount,
OrderCount: data.OrderCount,
TotalStandardHpp: data.TotalStandardHpp,
TotalFifoHpp: data.TotalFifoHpp,
TotalMovingAverageHpp: data.TotalMovingAverageHpp,
})
}
budget, err := p.buildBudgetCutOff(ctx, req.OrganizationID, req.OutletID, nil, req.DateFrom, req.DateTo)
if err != nil {
return nil, err
}
return &models.ProductAnalyticsPerParentCategoryResponse{
OrganizationID: req.OrganizationID,
OutletID: req.OutletID,
OutletName: p.resolveOutletName(ctx, req.OrganizationID, req.OutletID),
DateFrom: req.DateFrom,
DateTo: req.DateTo,
Data: resultData,
Budget: budget,
}, nil
}
func (p *AnalyticsProcessorImpl) GetParentCategoryAnalyticsDetail(ctx context.Context, req *models.ParentCategoryAnalyticsDetailRequest) (*models.ParentCategoryAnalyticsDetailResponse, error) {
// Validate date range
if req.DateFrom.After(req.DateTo) {
return nil, fmt.Errorf("date_from cannot be after date_to")
}
detail, err := p.analyticsRepo.GetParentCategoryAnalyticsDetail(ctx, req.OrganizationID, req.OutletID, req.ParentCategoryID, req.DateFrom, req.DateTo)
if err != nil {
return nil, fmt.Errorf("failed to get parent category analytics detail: %w", err)
}
// Bucket the product rows by the category they belong to
productsByCategory := make(map[uuid.UUID][]models.ParentCategoryAnalyticsProductData)
for _, product := range detail.Products {
productsByCategory[product.CategoryID] = append(productsByCategory[product.CategoryID], models.ParentCategoryAnalyticsProductData{
ProductID: product.ProductID,
ProductName: product.ProductName,
ProductSku: product.ProductSku,
ProductPrice: product.ProductPrice,
QuantitySold: product.QuantitySold,
Revenue: product.Revenue,
AveragePrice: product.AveragePrice,
OrderCount: product.OrderCount,
StandardHppPerUnit: product.StandardHppPerUnit,
StandardHppTotal: product.StandardHppTotal,
FifoHppPerUnit: product.FifoHppPerUnit,
FifoHppTotal: product.FifoHppTotal,
MovingAverageHppPerUnit: product.MovingAverageHppPerUnit,
MovingAverageHppTotal: product.MovingAverageHppTotal,
})
}
categories := make([]models.ParentCategoryAnalyticsDetailData, 0, len(detail.Categories))
for _, category := range detail.Categories {
products := productsByCategory[category.CategoryID]
if products == nil {
products = []models.ParentCategoryAnalyticsProductData{}
}
categories = append(categories, models.ParentCategoryAnalyticsDetailData{
CategoryID: category.CategoryID,
CategoryName: category.CategoryName,
TotalRevenue: category.TotalRevenue,
TotalQuantity: category.TotalQuantity,
ProductCount: category.ProductCount,
OrderCount: category.OrderCount,
TotalStandardHpp: category.TotalStandardHpp,
TotalFifoHpp: category.TotalFifoHpp,
TotalMovingAverageHpp: category.TotalMovingAverageHpp,
Products: products,
})
}
summary := models.ParentCategoryAnalyticsDetailSummary{}
if detail.Summary != nil {
summary = models.ParentCategoryAnalyticsDetailSummary{
TotalRevenue: detail.Summary.TotalRevenue,
TotalQuantity: detail.Summary.TotalQuantity,
CategoryCount: detail.Summary.CategoryCount,
ProductCount: detail.Summary.ProductCount,
OrderCount: detail.Summary.OrderCount,
TotalStandardHpp: detail.Summary.TotalStandardHpp,
TotalFifoHpp: detail.Summary.TotalFifoHpp,
TotalMovingAverageHpp: detail.Summary.TotalMovingAverageHpp,
}
}
budget, err := p.buildBudgetCutOff(ctx, req.OrganizationID, req.OutletID, &req.ParentCategoryID, req.DateFrom, req.DateTo)
if err != nil {
return nil, err
}
return &models.ParentCategoryAnalyticsDetailResponse{
OrganizationID: req.OrganizationID,
OutletID: req.OutletID,
OutletName: p.resolveOutletName(ctx, req.OrganizationID, req.OutletID),
DateFrom: req.DateFrom,
DateTo: req.DateTo,
ParentCategoryID: detail.ParentCategoryID,
ParentCategoryName: detail.ParentCategoryName,
Summary: summary,
Categories: categories,
Budget: budget,
}, nil
}
// startOfWeek returns the Monday 00:00 of the week containing t, in t's own location.
func startOfWeek(t time.Time) time.Time {
daysSinceMonday := (int(t.Weekday()) + 6) % 7
year, month, day := t.Date()
return time.Date(year, month, day-daysSinceMonday, 0, 0, 0, 0, t.Location())
}
// endOfWeek returns the Sunday 23:59:59.999999999 of the week containing t.
func endOfWeek(t time.Time) time.Time {
return startOfWeek(t).AddDate(0, 0, 7).Add(-time.Nanosecond)
}
// newBudgetPeriod splits a period's revenue into the spending limits.
func newBudgetPeriod(start, end time.Time, revenue float64, orderCount int64) models.BudgetPeriod {
return models.BudgetPeriod{
PeriodStart: start,
PeriodEnd: end,
Revenue: revenue,
OrderCount: orderCount,
LimitPurchase: revenue * constants.BudgetLimitPurchasePercent / 100,
LimitOwner: revenue * constants.BudgetLimitOwnerPercent / 100,
LimitTeam: revenue * constants.BudgetLimitTeamPercent / 100,
}
}
// buildBudgetCutOff produces the weekly cut-off breakdown for the given scope. Weeks
// are always whole Monday-to-Sunday blocks, so the covered range is widened to the
// week boundaries around the requested dates. A nil parentCategoryID covers every
// category.
func (p *AnalyticsProcessorImpl) buildBudgetCutOff(ctx context.Context, organizationID uuid.UUID, outletID *uuid.UUID, parentCategoryID *uuid.UUID, dateFrom, dateTo time.Time) (models.BudgetCutOff, error) {
cutOffFrom := startOfWeek(dateFrom)
cutOffTo := endOfWeek(dateTo)
budget := models.BudgetCutOff{
Percentages: models.BudgetPercentages{
Purchase: constants.BudgetLimitPurchasePercent,
Owner: constants.BudgetLimitOwnerPercent,
Team: constants.BudgetLimitTeamPercent,
},
CutOffFrom: cutOffFrom,
CutOffTo: cutOffTo,
Weekly: []models.BudgetPeriod{},
Monthly: []models.BudgetMonthPeriod{},
}
rows, err := p.analyticsRepo.GetBudgetCutOffWeekly(ctx, organizationID, outletID, parentCategoryID, cutOffFrom, cutOffTo)
if err != nil {
return budget, fmt.Errorf("failed to get budget cut off: %w", err)
}
// Key the rows by their Monday so weeks without any sales can still be emitted
rowsByWeek := make(map[string]*entities.BudgetCutOffWeek, len(rows))
for _, row := range rows {
rowsByWeek[row.WeekStart.In(cutOffFrom.Location()).Format("2006-01-02")] = row
}
var (
totalRevenue float64
totalOrders int64
monthOrder []string
monthAccumulator = map[string]*models.BudgetMonthPeriod{}
)
for week := cutOffFrom; !week.After(cutOffTo); week = week.AddDate(0, 0, 7) {
var revenue float64
var orderCount int64
if row, ok := rowsByWeek[week.Format("2006-01-02")]; ok {
revenue, orderCount = row.Revenue, row.OrderCount
}
period := newBudgetPeriod(week, endOfWeek(week), revenue, orderCount)
budget.Weekly = append(budget.Weekly, period)
totalRevenue += revenue
totalOrders += orderCount
// A week belongs to the month of its Monday, so every week is counted once
monthKey := week.Format("2006-01")
month, ok := monthAccumulator[monthKey]
if !ok {
month = &models.BudgetMonthPeriod{Month: monthKey}
month.PeriodStart = period.PeriodStart
monthAccumulator[monthKey] = month
monthOrder = append(monthOrder, monthKey)
}
month.WeekCount++
month.PeriodEnd = period.PeriodEnd
month.Revenue += revenue
month.OrderCount += orderCount
}
for _, monthKey := range monthOrder {
month := monthAccumulator[monthKey]
budget.Monthly = append(budget.Monthly, models.BudgetMonthPeriod{
Month: month.Month,
WeekCount: month.WeekCount,
BudgetPeriod: newBudgetPeriod(month.PeriodStart, month.PeriodEnd, month.Revenue, month.OrderCount),
})
}
budget.Total = newBudgetPeriod(cutOffFrom, cutOffTo, totalRevenue, totalOrders)
return budget, nil
}
func (p *AnalyticsProcessorImpl) GetDashboardAnalytics(ctx context.Context, req *models.DashboardAnalyticsRequest) (*models.DashboardAnalyticsResponse, error) {
// Validate date range
if req.DateFrom.After(req.DateTo) {
@@ -14,6 +14,7 @@ import (
type analyticsRepositoryStub struct {
purchasingResult *entities.PurchasingAnalytics
budgetCutOffWeeks []*entities.BudgetCutOffWeek
profitLossResult *entities.ProfitLossAnalytics
exclusiveSummaryResults []*entities.ExclusiveSummaryAnalytics
bankBalances []entities.ExclusiveSummaryBankBalance
@@ -43,6 +44,18 @@ func (analyticsRepositoryStub) GetProductAnalyticsPerCategory(context.Context, u
return nil, nil
}
func (analyticsRepositoryStub) GetProductAnalyticsPerParentCategory(context.Context, uuid.UUID, *uuid.UUID, time.Time, time.Time) ([]*entities.ProductAnalyticsPerParentCategory, error) {
return nil, nil
}
func (analyticsRepositoryStub) GetParentCategoryAnalyticsDetail(context.Context, uuid.UUID, *uuid.UUID, uuid.UUID, time.Time, time.Time) (*entities.ParentCategoryAnalyticsDetail, error) {
return nil, nil
}
func (s analyticsRepositoryStub) GetBudgetCutOffWeekly(context.Context, uuid.UUID, *uuid.UUID, *uuid.UUID, time.Time, time.Time) ([]*entities.BudgetCutOffWeek, error) {
return s.budgetCutOffWeeks, nil
}
func (analyticsRepositoryStub) GetDashboardOverview(context.Context, uuid.UUID, *uuid.UUID, time.Time, time.Time) (*entities.DashboardOverview, error) {
return nil, nil
}
+152
View File
@@ -0,0 +1,152 @@
package processor
import (
"context"
"testing"
"time"
"apskel-pos-be/internal/entities"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
)
func jakarta(t *testing.T) *time.Location {
t.Helper()
loc, err := time.LoadLocation("Asia/Jakarta")
require.NoError(t, err)
return loc
}
func TestStartOfWeekLandsOnMonday(t *testing.T) {
loc := jakarta(t)
// 3 Aug 2026 is a Monday, so the whole week must collapse onto it
monday := time.Date(2026, 8, 3, 0, 0, 0, 0, loc)
for offset := 0; offset < 7; offset++ {
day := monday.AddDate(0, 0, offset).Add(13 * time.Hour)
got := startOfWeek(day)
require.Equal(t, monday, got, "day %s should map to %s", day, monday)
require.Equal(t, time.Monday, got.Weekday())
}
}
func TestEndOfWeekLandsOnSunday(t *testing.T) {
loc := jakarta(t)
// Sunday 9 Aug 2026 closes the week that starts Monday 3 Aug
got := endOfWeek(time.Date(2026, 8, 5, 9, 30, 0, 0, loc))
require.Equal(t, time.Sunday, got.Weekday())
require.Equal(t, 2026, got.Year())
require.Equal(t, time.August, got.Month())
require.Equal(t, 9, got.Day())
require.Equal(t, 23, got.Hour())
require.Equal(t, 59, got.Minute())
}
func TestBuildBudgetCutOffWidensToWholeWeeks(t *testing.T) {
loc := jakarta(t)
processor := &AnalyticsProcessorImpl{analyticsRepo: &analyticsRepositoryStub{}}
// Saturday 1 Aug to Monday 31 Aug 2026: both ends fall mid-week
from := time.Date(2026, 8, 1, 0, 0, 0, 0, loc)
to := time.Date(2026, 8, 31, 23, 59, 59, 0, loc)
budget, err := processor.buildBudgetCutOff(context.Background(), uuid.New(), nil, nil, from, to)
require.NoError(t, err)
// Reaches back into July and forward into September to keep weeks whole
require.Equal(t, time.Monday, budget.CutOffFrom.Weekday())
require.Equal(t, time.July, budget.CutOffFrom.Month())
require.Equal(t, 27, budget.CutOffFrom.Day())
require.Equal(t, time.Sunday, budget.CutOffTo.Weekday())
require.Equal(t, time.September, budget.CutOffTo.Month())
require.Equal(t, 6, budget.CutOffTo.Day())
require.Len(t, budget.Weekly, 6)
for _, week := range budget.Weekly {
require.Equal(t, time.Monday, week.PeriodStart.Weekday())
require.Equal(t, time.Sunday, week.PeriodEnd.Weekday())
}
// A week is filed under the month of its Monday, so the 27 Jul week counts as July
require.Len(t, budget.Monthly, 2)
require.Equal(t, "2026-07", budget.Monthly[0].Month)
require.Equal(t, 1, budget.Monthly[0].WeekCount)
require.Equal(t, "2026-08", budget.Monthly[1].Month)
require.Equal(t, 5, budget.Monthly[1].WeekCount)
}
func TestBuildBudgetCutOffAppliesLimits(t *testing.T) {
loc := jakarta(t)
weekStart := time.Date(2026, 8, 3, 0, 0, 0, 0, loc)
stub := &analyticsRepositoryStub{budgetCutOffWeeks: []*entities.BudgetCutOffWeek{
{WeekStart: weekStart, Revenue: 10_000_000, OrderCount: 120},
}}
processor := &AnalyticsProcessorImpl{analyticsRepo: stub}
budget, err := processor.buildBudgetCutOff(context.Background(), uuid.New(), nil, nil, weekStart, weekStart.AddDate(0, 0, 6))
require.NoError(t, err)
require.Len(t, budget.Weekly, 1)
// 60 / 20 / 20 of the week's revenue
week := budget.Weekly[0]
require.Equal(t, float64(6_000_000), week.LimitPurchase)
require.Equal(t, float64(2_000_000), week.LimitOwner)
require.Equal(t, float64(2_000_000), week.LimitTeam)
require.Equal(t, int64(120), week.OrderCount)
// Totals mirror the single week
require.Equal(t, week.Revenue, budget.Total.Revenue)
require.Equal(t, week.LimitPurchase, budget.Total.LimitPurchase)
}
func TestBuildBudgetCutOffAccumulatesMonthlyFromWeeks(t *testing.T) {
loc := jakarta(t)
first := time.Date(2026, 8, 3, 0, 0, 0, 0, loc)
stub := &analyticsRepositoryStub{budgetCutOffWeeks: []*entities.BudgetCutOffWeek{
{WeekStart: first, Revenue: 10_000_000, OrderCount: 100},
{WeekStart: first.AddDate(0, 0, 7), Revenue: 5_000_000, OrderCount: 60},
}}
processor := &AnalyticsProcessorImpl{analyticsRepo: stub}
budget, err := processor.buildBudgetCutOff(context.Background(), uuid.New(), nil, nil, first, first.AddDate(0, 0, 9))
require.NoError(t, err)
require.Len(t, budget.Monthly, 1)
month := budget.Monthly[0]
require.Equal(t, "2026-08", month.Month)
require.Equal(t, 2, month.WeekCount)
require.Equal(t, float64(15_000_000), month.Revenue)
require.Equal(t, int64(160), month.OrderCount)
// The month limit is the accumulation of its weeks
require.Equal(t, float64(9_000_000), month.LimitPurchase)
require.Equal(t, budget.Weekly[0].LimitPurchase+budget.Weekly[1].LimitPurchase, month.LimitPurchase)
}
func TestBuildBudgetCutOffEmitsWeeksWithoutSales(t *testing.T) {
loc := jakarta(t)
first := time.Date(2026, 8, 3, 0, 0, 0, 0, loc)
// Only the third week has sales; the two quiet weeks must still be reported
stub := &analyticsRepositoryStub{budgetCutOffWeeks: []*entities.BudgetCutOffWeek{
{WeekStart: first.AddDate(0, 0, 14), Revenue: 4_000_000, OrderCount: 40},
}}
processor := &AnalyticsProcessorImpl{analyticsRepo: stub}
budget, err := processor.buildBudgetCutOff(context.Background(), uuid.New(), nil, nil, first, first.AddDate(0, 0, 16))
require.NoError(t, err)
require.Len(t, budget.Weekly, 3)
require.Zero(t, budget.Weekly[0].Revenue)
require.Zero(t, budget.Weekly[0].LimitPurchase)
require.Zero(t, budget.Weekly[1].Revenue)
require.Equal(t, float64(4_000_000), budget.Weekly[2].Revenue)
require.Equal(t, float64(4_000_000), budget.Total.Revenue)
}
+30
View File
@@ -53,6 +53,18 @@ func (p *CategoryProcessorImpl) CreateCategory(ctx context.Context, req *models.
return nil, fmt.Errorf("category with name '%s' already exists for this organization", req.Name)
}
var parentName *string
if req.ParentID != nil {
parentCategory, err := p.categoryRepo.GetByID(ctx, *req.ParentID)
if err != nil {
return nil, fmt.Errorf("parent category not found: %w", err)
}
if parentCategory.OrganizationID != req.OrganizationID {
return nil, fmt.Errorf("parent category must belong to the same organization")
}
parentName = &parentCategory.Name
}
// Map request to entity
categoryEntity := mappers.CreateCategoryRequestToEntity(req)
@@ -63,6 +75,7 @@ func (p *CategoryProcessorImpl) CreateCategory(ctx context.Context, req *models.
// Map entity to response model
response := mappers.CategoryEntityToResponse(categoryEntity)
response.ParentName = parentName
return response, nil
}
@@ -84,6 +97,23 @@ func (p *CategoryProcessorImpl) UpdateCategory(ctx context.Context, id uuid.UUID
}
}
if req.ParentID != nil {
if *req.ParentID == id {
return nil, fmt.Errorf("category cannot be its own parent")
}
parentCategory, err := p.categoryRepo.GetByID(ctx, *req.ParentID)
if err != nil {
return nil, fmt.Errorf("parent category not found: %w", err)
}
if parentCategory.OrganizationID != existingCategory.OrganizationID {
return nil, fmt.Errorf("parent category must belong to the same organization")
}
// Refresh the preloaded association so the response carries the new parent
existingCategory.Parent = parentCategory
}
// Apply updates to entity
mappers.UpdateCategoryEntityFromRequest(existingCategory, req)