update inventory package

This commit is contained in:
2025-11-26 18:22:14 +01:00
parent 7ebbc97e38
commit 28c9a24dac
7 changed files with 567 additions and 25 deletions
+34 -15
View File
@@ -42,20 +42,6 @@ func (s *RedisInventoryService) LoadLuaScript(key string) error {
return nil
}
func (s *RedisInventoryService) AddWarehouse(warehouse *Warehouse) error {
// Convert warehouse to Redis-friendly format
data := map[string]interface{}{
"id": string(warehouse.ID),
"name": warehouse.Name,
"inventory": warehouse.Inventory,
}
// Store in Redis with a key pattern like "warehouse:<ID>"
key := "warehouse:" + string(warehouse.ID)
_, err := s.client.HMSet(context.Background(), key, data).Result()
return err
}
func (s *RedisInventoryService) GetInventory(ctx context.Context, sku SKU, locationID LocationID) (int64, error) {
cmd := s.client.Get(ctx, getInventoryKey(sku, locationID))
@@ -75,12 +61,45 @@ func getInventoryKey(sku SKU, locationID LocationID) string {
return fmt.Sprintf("inventory:%s:%s", sku, locationID)
}
func (s *RedisInventoryService) GetInventoryBatch(ctx context.Context, refs ...*InventoryReference) ([]InventoryResult, error) {
results := make([]InventoryResult, len(refs))
pipe := s.client.Pipeline()
cmds := make([]*redis.StringCmd, len(refs))
for i, ref := range refs {
key := getInventoryKey(ref.Sku, ref.LocationID)
cmds[i] = pipe.Get(ctx, key)
}
_, err := pipe.Exec(ctx)
if err != nil && err != redis.Nil {
return nil, err
}
for i, cmd := range cmds {
quantity, err := cmd.Int64()
if err != nil && err != redis.Nil {
return nil, err
}
results[i] = InventoryResult{
InventoryReference: refs[i],
Quantity: uint32(quantity),
}
}
return results, nil
}
func (s *RedisInventoryService) UpdateInventory(ctx context.Context, rdb redis.Pipeliner, sku SKU, locationID LocationID, quantity int64) error {
key := getInventoryKey(sku, locationID)
cmd := rdb.Set(ctx, key, quantity, 0)
return cmd.Err()
}
func (s *RedisInventoryService) DecrementInventory(ctx context.Context, rdb redis.Pipeliner, sku SKU, locationID LocationID, quantity int64) error {
key := getInventoryKey(sku, locationID)
cmd := rdb.DecrBy(ctx, key, quantity)
return cmd.Err()
}
func (s *RedisInventoryService) IncrementInventory(ctx context.Context, rdb redis.Pipeliner, sku SKU, locationID LocationID, quantity int64) error {
key := getInventoryKey(sku, locationID)
cmd := rdb.IncrBy(ctx, key, quantity)
@@ -120,7 +139,7 @@ func makeKeysAndArgs(req ...ReserveRequest) ([]string, []string) {
if r.Quantity <= 0 {
return nil, nil
}
keys[i] = getInventoryKey(r.SKU, r.LocationID)
keys[i] = getInventoryKey(r.Sku, r.LocationID)
args[i] = strconv.Itoa(int(r.Quantity))
}
return keys, args