diff --git a/file.go b/file.go index 7a9ba632d..0aacb96d5 100644 --- a/file.go +++ b/file.go @@ -75,6 +75,14 @@ func NewFile() *File { } } +type fileHeader struct { + Header FileHeader `json:"fileHeader"` +} + +type fileControl struct { + Control FileControl `json:"fileControl"` +} + // FileFromJson attempts to return a *File object assuming the input is valid JSON. // // Callers should always check for a nil-error before using the returned file. @@ -86,15 +94,30 @@ func FileFromJson(bs []byte) (*File, error) { return nil, errors.New("no json data provided") } - file := File{Header: NewFileHeader()} + // Read FileHeader + header := fileHeader{ + Header: NewFileHeader(), + } + if err := json.NewDecoder(bytes.NewReader(bs)).Decode(&header); err != nil { + return nil, fmt.Errorf("problem reading FileHeader: %v", err) + } - // Read what we can and then custom read batches - json.NewDecoder(bytes.NewReader(bs)).Decode(&file) + // Read FileControl + control := fileControl{ + Control: NewFileControl(), + } + if err := json.NewDecoder(bytes.NewReader(bs)).Decode(&control); err != nil { + return nil, fmt.Errorf("problem reading FileControl: %v", err) + } + + // Build resulting file + file := NewFile() if err := file.setBatchesFromJson(backup); err != nil { return nil, err } - - return &file, nil + file.Header = header.Header + file.Control = control.Control + return file, nil } func (f *File) UnmarshalJSON(p []byte) error { diff --git a/file_test.go b/file_test.go index e7c3a16f5..bf3e3cec4 100644 --- a/file_test.go +++ b/file_test.go @@ -393,10 +393,30 @@ func TestFile__readFromJson(t *testing.T) { t.Fatal(err) } + // Header + if file.Header.ImmediateOrigin != "121042882" || file.Header.ImmediateOriginName != "Wells Fargo" { + t.Errorf("origin=%s name=%s", file.Header.ImmediateOrigin, file.Header.ImmediateOriginName) + } + if file.Header.ImmediateDestination != "231380104" || file.Header.ImmediateDestinationName != "Citadel" { + t.Errorf("destination=%s name=%s", file.Header.ImmediateDestination, file.Header.ImmediateDestinationName) + } + if file.Header.FileCreationTime.IsZero() || file.Header.FileCreationDate.IsZero() { + t.Errorf("time=%v date=%v", file.Header.FileCreationTime, file.Header.FileCreationDate) + } + + // Batches if len(file.Batches) != 1 { t.Errorf("got %d batches: %v", len(file.Batches), file.Batches) } + // Control + if file.Control.BatchCount != 1 { + t.Errorf("BatchCount: %d", file.Control.BatchCount) + } + if file.Control.TotalDebitEntryDollarAmountInFile != 0 || file.Control.TotalCreditEntryDollarAmountInFile != 100000 { + t.Errorf("debit=%d credit=%d", file.Control.TotalDebitEntryDollarAmountInFile, file.Control.TotalCreditEntryDollarAmountInFile) + } + // ensure we error on struct tag unmarshal var f File err = json.Unmarshal(bs, &f)