Compare commits

..

2 Commits

Author SHA1 Message Date
aa0f4d292e Billing status displaying 2025-02-18 23:18:38 +08:00
8b02381392 ♻️ Update billing algorithm 2025-02-18 23:12:51 +08:00
3 changed files with 40 additions and 5 deletions

View File

@ -2,6 +2,7 @@ package api
import (
"fmt"
"github.com/spf13/viper"
"strings"
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
@ -13,6 +14,25 @@ import (
"github.com/gofiber/fiber/v2"
)
func getBillingStatus(c *fiber.Ctx) error {
if err := sec.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("nex_user").(*sec.UserInfo)
currentBytes, err := services.GetLastDayUploadedBytes(user.ID)
if err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
}
discountFileSize := viper.GetInt64("payment.discount")
return c.JSON(fiber.Map{
"current_bytes": currentBytes,
"discount_file_size": discountFileSize,
"included_ratio": float64(currentBytes) / float64(discountFileSize),
})
}
func openAttachment(c *fiber.Ctx) error {
id := c.Params("id")
region := c.Query("region")

View File

@ -9,6 +9,7 @@ func MapAPIs(app *fiber.App, baseURL string) {
api := app.Group(baseURL).Name("API")
{
api.Get("/destinations", listDestination)
api.Get("/billing", getBillingStatus)
boost := api.Group("/boosts").Name("Boosts API")
{

View File

@ -3,6 +3,8 @@ package services
import (
"context"
"fmt"
"git.solsynth.dev/hypernet/paperclip/pkg/internal/database"
"git.solsynth.dev/hypernet/paperclip/pkg/internal/models"
"time"
"git.solsynth.dev/hypernet/paperclip/pkg/internal/gap"
@ -12,22 +14,34 @@ import (
"github.com/spf13/viper"
)
func GetLastDayUploadedBytes(user uint) (int64, error) {
deadline := time.Now().Add(-24 * time.Hour)
var totalSize int64
if err := database.C.
Model(&models.Attachment{}).
Where("account_id = ?", user).
Where("created_at <= ?", deadline).
Select("SUM(size)").
Scan(&totalSize).Error; err != nil {
return totalSize, err
}
return totalSize, nil
}
// PlaceOrder create a transaction if needed for user
// Pricing according here: https://kb.solsynth.dev/solar-network/wallet#file-uploads
func PlaceOrder(user uint, filesize int64, withDiscount bool) error {
currentBytes, _ := GetLastDayUploadedBytes(user)
discountFileSize := viper.GetInt64("payment.discount")
if filesize <= discountFileSize && withDiscount {
if currentBytes+filesize <= discountFileSize {
// Discount included
return nil
}
var amount float64
if withDiscount {
billableSize := filesize - discountFileSize
amount = float64(billableSize) / 1024 / 1024 * 1
} else if filesize > discountFileSize {
amount = 50 + float64(filesize-discountFileSize)/1024/1024*5
amount = float64(filesize) / 1024 / 1024 * 1
} else {
amount = float64(filesize) / 1024 / 1024 * 1
}