github.com/condensat/bank-core@v0.1.0/database/query/batchwithdraw.go (about)

     1  // Copyright 2020 Condensat Tech. All rights reserved.
     2  // Use of this source code is governed by a MIT
     3  // license that can be found in the LICENSE file.
     4  
     5  package query
     6  
     7  import (
     8  	"errors"
     9  
    10  	"github.com/condensat/bank-core/database"
    11  	"github.com/condensat/bank-core/database/model"
    12  
    13  	"github.com/jinzhu/gorm"
    14  )
    15  
    16  var (
    17  	ErrInvalidBatchWithdrawID = errors.New("Invalid BatchWithdrawID")
    18  )
    19  
    20  func AddWithdrawToBatch(db database.Context, batchID model.BatchID, withdraws ...model.WithdrawID) error {
    21  	gdb := db.DB().(*gorm.DB)
    22  	if db == nil {
    23  		return database.ErrInvalidDatabase
    24  	}
    25  
    26  	if batchID == 0 {
    27  		return ErrInvalidBatchID
    28  	}
    29  
    30  	for _, wID := range withdraws {
    31  		if wID == 0 {
    32  			return ErrInvalidBatchWithdrawID
    33  		}
    34  	}
    35  
    36  	for _, wID := range withdraws {
    37  		entry := model.BatchWithdraw{
    38  			BatchID:    batchID,
    39  			WithdrawID: wID,
    40  		}
    41  		err := gdb.Create(&entry).Error
    42  		if err != nil {
    43  			return err
    44  		}
    45  	}
    46  
    47  	return nil
    48  }
    49  
    50  func GetBatchWithdraws(db database.Context, batchID model.BatchID) ([]model.WithdrawID, error) {
    51  	gdb := db.DB().(*gorm.DB)
    52  	if db == nil {
    53  		return nil, database.ErrInvalidDatabase
    54  	}
    55  
    56  	if batchID == 0 {
    57  		return nil, ErrInvalidBatchID
    58  	}
    59  
    60  	var list []*model.BatchWithdraw
    61  	err := gdb.
    62  		Where(model.BatchWithdraw{
    63  			BatchID: batchID,
    64  		}).
    65  		Order("batch_id ASC").
    66  		Find(&list).Error
    67  
    68  	if err != nil && err != gorm.ErrRecordNotFound {
    69  		return nil, err
    70  	}
    71  
    72  	return convertWithdrawList(list), nil
    73  }
    74  
    75  func convertWithdrawList(list []*model.BatchWithdraw) []model.WithdrawID {
    76  	var result []model.WithdrawID
    77  	for _, curr := range list {
    78  		if curr != nil {
    79  			result = append(result, curr.WithdrawID)
    80  		}
    81  	}
    82  
    83  	return result[:]
    84  }