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) {