108 lines
2.5 KiB
Go
108 lines
2.5 KiB
Go
package inventory
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
type RedisInventoryService struct {
|
|
client *redis.Client
|
|
ctx context.Context
|
|
luaScripts map[string]*redis.Script
|
|
}
|
|
|
|
func NewRedisInventoryService(client *redis.Client, ctx context.Context) (*RedisInventoryService, error) {
|
|
rdb := client
|
|
|
|
// Ping Redis to check connection
|
|
_, err := rdb.Ping(ctx).Result()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &RedisInventoryService{
|
|
client: rdb,
|
|
ctx: ctx,
|
|
luaScripts: make(map[string]*redis.Script),
|
|
}, nil
|
|
}
|
|
|
|
func (s *RedisInventoryService) LoadLuaScript(key string) error {
|
|
// Get the script from Redis
|
|
script, err := s.client.Get(s.ctx, key).Result()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// Load the script into the luaScripts cache
|
|
s.luaScripts[key] = redis.NewScript(script)
|
|
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(s.ctx, key, data).Result()
|
|
return err
|
|
}
|
|
|
|
func (s *RedisInventoryService) GetInventory(sku SKU, locationID LocationID) (*InventoryItem, error) {
|
|
// Get the warehouse from Redis
|
|
key := "warehouse:" + string(locationID)
|
|
result, err := s.client.HGetAll(s.ctx, key).Result()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Parse the inventory items
|
|
var inventoryItems []InventoryItem
|
|
for _, itemData := range result {
|
|
var item InventoryItem
|
|
if err := json.Unmarshal([]byte(itemData), &item); err == nil {
|
|
inventoryItems = append(inventoryItems, item)
|
|
}
|
|
}
|
|
|
|
// Find the requested SKU
|
|
for _, item := range inventoryItems {
|
|
if item.SKU == sku {
|
|
return &item, nil
|
|
}
|
|
}
|
|
|
|
return nil, errors.New("sku not found in warehouse")
|
|
}
|
|
|
|
func (s *RedisInventoryService) ReserveInventory(req ReserveRequest) error {
|
|
return nil
|
|
// Get the Lua script from Redis
|
|
// key := "lua:reserve_inventory"
|
|
// script, err := s.client.Get(s.ctx, key).Result()
|
|
// if err != nil {
|
|
// return err
|
|
// }
|
|
|
|
// luaScript := redis.NewScript(script)
|
|
|
|
// // Prepare arguments for the Lua script
|
|
// args := []interface{}{
|
|
// string(req.LocationID),
|
|
// string(req.SKU),
|
|
// req.Quantity,
|
|
// }
|
|
|
|
// // Execute the Lua script
|
|
// cmd := s.client.Eval(s.ctx, luaScript, len(args), args...)
|
|
//return err
|
|
}
|