app-cloudep-order-server/internal/logic/orderservice/decimal_tools.go

93 lines
1.7 KiB
Go

package orderservicelogic
import (
"github.com/shopspring/decimal"
"github.com/zeromicro/go-zero/core/logx"
"go.mongodb.org/mongo-driver/bson/primitive"
)
// Helper function for decimal conversion with nil support and logging
func decimalPtrFromString(val string) *decimal.Decimal {
if val == "" {
return nil
}
dec, err := decimal.NewFromString(val)
if err != nil {
logx.Errorf("Failed to convert string to decimal: %v", err)
return nil
}
return &dec
}
// Convert decimal.Decimal to primitive.Decimal128 and handle nil values
func convertDecimalPtrToDecimal128(d *decimal.Decimal) *primitive.Decimal128 {
if d == nil {
return nil
}
result, err := primitive.ParseDecimal128(d.String())
if err != nil {
logx.Errorf("Failed to convert decimal to Decimal128: %v", err)
return nil
}
return &result
}
// Convert decimal.Decimal (non-pointer) to primitive.Decimal128 and log errors
func convertDecimalToDecimal128(d decimal.Decimal) primitive.Decimal128 {
result, err := primitive.ParseDecimal128(d.String())
if err != nil {
logx.Errorf("Failed to convert decimal to Decimal128: %v", err)
return primitive.NewDecimal128(0, 0)
}
return result
}
// 將 primitive.Decimal128 轉換為字符串
func convertDecimal128ToString(d128 *primitive.Decimal128) *string {
if d128 == nil {
return nil
}
result := d128.String()
return &result
}
// Helper functions for optional fields
func optionalString(s *string) *string {
if s != nil {
return s
}
return nil
}
func optionalInt64(i *int64) *int64 {
if i != nil {
return i
}
return nil
}
func nilString(s *string) *string {
if s == nil {
return nil
}
return s
}
func nilInt64(i *int64) *int64 {
if i == nil {
return nil
}
return i
}