package internal import ( "crypto/sha256" "encoding/hex" "fmt" "strings" "time" ) type HashService struct { lastRecord *LastRecord } type LastRecord struct { EmisorNIF string NumSerie string Fecha time.Time Huella string FechaGen time.Time } func NewHashService() *HashService { return &HashService{} } func (s *HashService) SetLastRecord(r *LastRecord) { s.lastRecord = r } func (s *HashService) GetLastRecord() *LastRecord { return s.lastRecord } func (s *HashService) CalculateHash(data *InvoiceData, previousHash string) string { fechaGen := data.FechaGen.Format(time.RFC3339) fields := fmt.Sprintf("%s|%s|%s|%s|%.2f|%.2f|%s|%s", data.EmisorNIF, data.NumSerie, data.Fecha.Format("02-01-2006"), data.TipoFactura, data.CuotaTotal, data.ImporteTotal, previousHash, fechaGen, ) hash := sha256.Sum256([]byte(fields)) return strings.ToUpper(hex.EncodeToString(hash[:])) } func (s *HashService) IsFirstRecord() bool { return s.lastRecord == nil } func (s *HashService) GetPreviousHash() string { if s.lastRecord == nil { return "" } return s.lastRecord.Huella } type LastRecordStorage interface { GetLastRecord(emisorNIF string) (*LastRecord, error) SaveLastRecord(r *LastRecord) error }