Skip to content

Commit

Permalink
Merge pull request #67 from LerianStudio/develop
Browse files Browse the repository at this point in the history
Develop to Main
  • Loading branch information
MartinezAvellan authored Sep 19, 2024
2 parents 54df3de + 291402b commit ce9291c
Show file tree
Hide file tree
Showing 35 changed files with 1,659 additions and 89 deletions.
36 changes: 36 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,39 @@
## [1.10.0-beta.2](https://github.com/LerianStudio/midaz/compare/v1.10.0-beta.1...v1.10.0-beta.2) (2024-09-19)


### Features

* add grpc port to midaz on 50051 to run togheter with fiber :sparkles: ([a9c4551](https://github.com/LerianStudio/midaz/commit/a9c45514be5239593b9a26d1838d140c372d3836))
* add midaz version :sparkles: ([27c56aa](https://github.com/LerianStudio/midaz/commit/27c56aac4aaeffbdd6093a69dbc80e84ea9331ee))
* add proto url, address :sparkles: ([c92ee9b](https://github.com/LerianStudio/midaz/commit/c92ee9bc2649a3c46963027e067c4eed4dddade4))
* add version onn .env file :sparkles: ([fdfdac3](https://github.com/LerianStudio/midaz/commit/fdfdac3bded8767307d7f1e3d68a3c76e5803aa8))
* create new method listbyalias to find accounts based on transaction dsl info :sparkles: ([113c00c](https://github.com/LerianStudio/midaz/commit/113c00c2b64f2577f01460b1e4a017d3750f16ea))
* create new route and server grpc and remove old account class :sparkles: ([c5d9101](https://github.com/LerianStudio/midaz/commit/c5d91011efbc8f0dca1c32091747a36abe3d6039))
* generate new query to search account by ids :sparkles: ([aa5d147](https://github.com/LerianStudio/midaz/commit/aa5d147151fdbc814a41e7ba58496f8c3bce2989))
* grpc server starting with http sever togheter :sparkles: ([6d12e14](https://github.com/LerianStudio/midaz/commit/6d12e140d21b28fe70d2f339a05cba4744cbce60))
* update account by id and get account by alias by grpc :sparkles: ([bf98e11](https://github.com/LerianStudio/midaz/commit/bf98e11eba0e8a33eddd52e1cde4226deb5af872))


### Bug Fixes

* add -d on docker compose up :bug: ([0322e13](https://github.com/LerianStudio/midaz/commit/0322e13cf0cbbc1693cd21352ccb6f142b71d835))
* adjust grpc account service :bug: ([2679e9b](https://github.com/LerianStudio/midaz/commit/2679e9bfe2d94fcc201e5672cec1f86feca5eb95))
* change print error to return error :bug: ([2e28f92](https://github.com/LerianStudio/midaz/commit/2e28f9251b91fcfcd77a33492219f27f0bedb5b0))
* go sec and go lint :bug: ([8a91b07](https://github.com/LerianStudio/midaz/commit/8a91b0746257afe7f4c4dc1ad6ce367b6f019cba))
* remove fiber print startup :bug: ([d47dd20](https://github.com/LerianStudio/midaz/commit/d47dd20ba5c888860b9c07fceb4e4ff2b432a167))
* reorganize some class and update wire. :bug: ([af0836b](https://github.com/LerianStudio/midaz/commit/af0836b86395b840b895eea7f1c256b04c5c7d17))
* update version place in log :bug: ([83980a8](https://github.com/LerianStudio/midaz/commit/83980a8aee40884cb317914c40d89e13c12f6a68))

## [1.10.0-beta.1](https://github.com/LerianStudio/midaz/compare/v1.9.1-beta.1...v1.10.0-beta.1) (2024-09-17)


### Bug Fixes

* add clean-up step for existing backup folder in PostgreSQL replica service in docker-compose ([28be466](https://github.com/LerianStudio/midaz/commit/28be466b7dda2f3dd100b73452c90d93ca574eda))
* ensure pg_basebackup runs if directory or postgresql.conf file is missing ([9f9742e](https://github.com/LerianStudio/midaz/commit/9f9742e39fe223a7cda85252935ea0d1cbbf6b81))

## [1.9.1-beta.1](https://github.com/LerianStudio/midaz/compare/v1.9.0...v1.9.1-beta.1) (2024-09-17)

## [1.9.0](https://github.com/LerianStudio/midaz/compare/v1.8.0...v1.9.0) (2024-09-16)


Expand Down
2 changes: 1 addition & 1 deletion common/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ func (l *Launcher) Add(appName string, a App) *Launcher {
return l
}

// Run run every application registered before with Run method.
// Run every application registered before with Run method.
func (l *Launcher) Run() {
count := len(l.apps)
l.wg.Add(count)
Expand Down
6 changes: 4 additions & 2 deletions common/os.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,14 +69,16 @@ var (
func InitLocalEnvConfig() *LocalEnvConfig {
fmt.Println(console.Title("InitLocalEnvConfig"))

version := GetenvOrDefault("VERSION", "NO-VERSION")
envName := GetenvOrDefault("ENV_NAME", "local")

fmt.Printf("ENVIRONMENT NAME \u001B[31m(%s)\u001B[0m\n", envName)
fmt.Printf("MIDAZ VERSION: \u001B[31m%s\u001B[0m\n", version)
fmt.Printf("ENVIRONMENT NAME: \u001B[31m(%s)\u001B[0m\n", envName)

if envName == "local" {
localEnvConfigOnce.Do(func() {
if err := godotenv.Load(); err != nil {
fmt.Println("Skipping .env file. Current env ", envName)
fmt.Println("Skipping \u001B[31m.env\u001B[0m file, using env", envName)

localEnvConfig = &LocalEnvConfig{
Initialized: false,
Expand Down
4 changes: 4 additions & 0 deletions components/ledger/.env.example
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
#ENV_NAME=production #default local
VERSION=1.8.0
SERVER_PORT=3000
SERVER_ADDRESS=:${SERVER_PORT}
PROTO_URL=localhost
PROTO_PORT=8765
PROTO_ADDRESS=:${PROTO_PORT}
MONGO_HOST=mongodb
MONGO_NAME=ledger
MONGO_USER=midaz
Expand Down
2 changes: 1 addition & 1 deletion components/ledger/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,6 @@ COPY --chown=nonroot:nonroot --from=builder /ledger-app/components/ledger/migrat

USER nonroot

EXPOSE 3000
EXPOSE 3000 50051

ENTRYPOINT ["/app"]
21 changes: 12 additions & 9 deletions components/ledger/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ services:
- replica-ledger
ports:
- ${SERVER_PORT}:${SERVER_PORT}
- ${PROTO_PORT}:${PROTO_PORT}
volumes:
- .:/usr/src/app
depends_on:
Expand Down Expand Up @@ -108,15 +109,17 @@ services:
PGPASSWORD: ${REPLICATION_PASSWORD}
command: |
bash -c "
until pg_basebackup --pgdata=/var/lib/postgresql/data -R --slot=replication_slot --host=primary-ledger --port=${DB_PORT}
do
echo 'Waiting for primary-ledger to connect...'
sleep 1s
done
echo 'Backup done..., starting replica-ledger...'
chmod 0700 /var/lib/postgresql/data
# Ensure the port is set to 5433 for the replica
sed -i 's/^#port.*/port = ${DB_REPLICA_PORT}/' /var/lib/postgresql/data/postgresql.conf
if [ ! -d \"/var/lib/postgresql/data\" ] || [ ! -f \"/var/lib/postgresql/data/postgresql.conf\" ]; then
until pg_basebackup --pgdata=/var/lib/postgresql/data -R --slot=replication_slot --host=primary-ledger --port=${DB_PORT}
do
echo 'Waiting for primary-ledger to connect...'
sleep 1s
done
echo 'Backup done..., starting replica-ledger...'
chmod 0700 /var/lib/postgresql/data
# Ensure the port is set to 5433 for the replica
sed -i 's/^#port.*/port = ${DB_REPLICA_PORT}/' /var/lib/postgresql/data/postgresql.conf
fi
exec postgres -c config_file=/var/lib/postgresql/data/postgresql.conf
"
healthcheck:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,60 @@ func (r *AccountPostgreSQLRepository) ListByIDs(ctx context.Context, organizatio
return accounts, nil
}

// ListByAlias retrieves Accounts entities from the database using the provided alias.
func (r *AccountPostgreSQLRepository) ListByAlias(ctx context.Context, organizationID, ledgerID, portfolioID uuid.UUID, alias []string) ([]*a.Account, error) {
db, err := r.connection.GetDB()
if err != nil {
return nil, err
}

var accounts []*a.Account

rows, err := db.QueryContext(ctx, "SELECT * FROM account WHERE organization_id = $1 AND ledger_id = $2 AND portfolio_id = $3 AND alias = ANY($4) AND deleted_at IS NULL ORDER BY created_at DESC",
organizationID, ledgerID, portfolioID, pq.Array(alias))
if err != nil {
return nil, err
}
defer rows.Close()

for rows.Next() {
var acc a.AccountPostgreSQLModel
if err := rows.Scan(
&acc.ID,
&acc.Name,
&acc.ParentAccountID,
&acc.EntityID,
&acc.InstrumentCode,
&acc.OrganizationID,
&acc.LedgerID,
&acc.PortfolioID,
&acc.ProductID,
&acc.AvailableBalance,
&acc.OnHoldBalance,
&acc.BalanceScale,
&acc.Status,
&acc.StatusDescription,
&acc.AllowSending,
&acc.AllowReceiving,
&acc.Alias,
&acc.Type,
&acc.CreatedAt,
&acc.UpdatedAt,
&acc.DeletedAt,
); err != nil {
return nil, err
}

accounts = append(accounts, acc.ToEntity())
}

if err := rows.Err(); err != nil {
return nil, err
}

return accounts, nil
}

// Update an Account entity into Postgresql and returns the Account updated.
func (r *AccountPostgreSQLRepository) Update(ctx context.Context, organizationID, ledgerID, portfolioID, id uuid.UUID, account *a.Account) (*a.Account, error) {
db, err := r.connection.GetDB()
Expand Down Expand Up @@ -404,3 +458,170 @@ func (r *AccountPostgreSQLRepository) Delete(ctx context.Context, organizationID

return nil
}

// ListAccountsByIDs list Accounts entity from the database using the provided IDs.
func (r *AccountPostgreSQLRepository) ListAccountsByIDs(ctx context.Context, ids []uuid.UUID) ([]*a.Account, error) {
db, err := r.connection.GetDB()
if err != nil {
return nil, err
}

var accounts []*a.Account

rows, err := db.QueryContext(ctx, "SELECT * FROM account WHERE id = ANY($1) AND deleted_at IS NULL ORDER BY created_at DESC", pq.Array(ids))
if err != nil {
return nil, err
}
defer rows.Close()

for rows.Next() {
var acc a.AccountPostgreSQLModel
if err := rows.Scan(
&acc.ID,
&acc.Name,
&acc.ParentAccountID,
&acc.EntityID,
&acc.InstrumentCode,
&acc.OrganizationID,
&acc.LedgerID,
&acc.PortfolioID,
&acc.ProductID,
&acc.AvailableBalance,
&acc.OnHoldBalance,
&acc.BalanceScale,
&acc.Status,
&acc.StatusDescription,
&acc.AllowSending,
&acc.AllowReceiving,
&acc.Alias,
&acc.Type,
&acc.CreatedAt,
&acc.UpdatedAt,
&acc.DeletedAt,
); err != nil {
return nil, err
}

accounts = append(accounts, acc.ToEntity())
}

if err := rows.Err(); err != nil {
return nil, err
}

return accounts, nil
}

// ListAccountsByAlias list Accounts entity from the database using the provided alias.
func (r *AccountPostgreSQLRepository) ListAccountsByAlias(ctx context.Context, aliases []string) ([]*a.Account, error) {
db, err := r.connection.GetDB()
if err != nil {
return nil, err
}

var accounts []*a.Account

rows, err := db.QueryContext(ctx, "SELECT * FROM account WHERE alias = ANY($1) AND deleted_at IS NULL ORDER BY created_at DESC", pq.Array(aliases))
if err != nil {
return nil, err
}
defer rows.Close()

for rows.Next() {
var acc a.AccountPostgreSQLModel
if err := rows.Scan(
&acc.ID,
&acc.Name,
&acc.ParentAccountID,
&acc.EntityID,
&acc.InstrumentCode,
&acc.OrganizationID,
&acc.LedgerID,
&acc.PortfolioID,
&acc.ProductID,
&acc.AvailableBalance,
&acc.OnHoldBalance,
&acc.BalanceScale,
&acc.Status,
&acc.StatusDescription,
&acc.AllowSending,
&acc.AllowReceiving,
&acc.Alias,
&acc.Type,
&acc.CreatedAt,
&acc.UpdatedAt,
&acc.DeletedAt,
); err != nil {
return nil, err
}

accounts = append(accounts, acc.ToEntity())
}

if err := rows.Err(); err != nil {
return nil, err
}

return accounts, nil
}

// UpdateAccountByID an update Account entity by ID only into Postgresql and returns the Account updated.
func (r *AccountPostgreSQLRepository) UpdateAccountByID(ctx context.Context, id uuid.UUID, account *a.Account) (*a.Account, error) {
db, err := r.connection.GetDB()
if err != nil {
return nil, err
}

record := &a.AccountPostgreSQLModel{}
record.FromEntity(account)

var updates []string

var args []any

if !account.Balance.IsEmpty() {
updates = append(updates, "available_balance = $"+strconv.Itoa(len(args)+1))
args = append(args, record.AvailableBalance)

updates = append(updates, "on_hold_balance = $"+strconv.Itoa(len(args)+1))
args = append(args, record.OnHoldBalance)

updates = append(updates, "balance_scale = $"+strconv.Itoa(len(args)+1))
args = append(args, record.BalanceScale)
}

record.UpdatedAt = time.Now()

updates = append(updates, "updated_at = $"+strconv.Itoa(len(args)+1))
args = append(args, record.UpdatedAt, id)

query := `UPDATE account SET ` + strings.Join(updates, ", ") +
` WHERE id = $` + strconv.Itoa(len(args)) +
` AND deleted_at IS NULL`

result, err := db.ExecContext(ctx, query, args...)
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
return nil, app.ValidatePGError(pgErr, reflect.TypeOf(a.Account{}).Name())
}

return nil, err
}

rowsAffected, err := result.RowsAffected()
if err != nil {
return nil, err
}

if rowsAffected == 0 {
return nil, common.EntityNotFoundError{
EntityType: reflect.TypeOf(a.Account{}).Name(),
Title: "Entity not found.",
Code: "0007",
Message: "No entity was found matching the provided ID. Ensure the correct ID is being used for the entity you are attempting to manage.",
}
}

return record.ToEntity(), nil
}
42 changes: 42 additions & 0 deletions components/ledger/internal/app/command/update-account-id.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package command

import (
"context"
"errors"
"fmt"
"reflect"

"github.com/LerianStudio/midaz/common"
"github.com/LerianStudio/midaz/common/mlog"
"github.com/LerianStudio/midaz/components/ledger/internal/app"
a "github.com/LerianStudio/midaz/components/ledger/internal/domain/portfolio/account"
"github.com/google/uuid"
)

// UpdateAccountByID update an account from the repository by given id.
func (uc *UseCase) UpdateAccountByID(ctx context.Context, id string, balance *a.Balance) (*a.Account, error) {
logger := mlog.NewLoggerFromContext(ctx)
logger.Infof("Trying to update account by id: %v", id)

account := &a.Account{
Balance: *balance,
}

accountUpdated, err := uc.AccountRepo.UpdateAccountByID(ctx, uuid.MustParse(id), account)
if err != nil {
logger.Errorf("Error updating account on repo by id: %v", err)

if errors.Is(err, app.ErrDatabaseItemNotFound) {
return nil, common.EntityNotFoundError{
EntityType: reflect.TypeOf(a.Account{}).Name(),
Message: fmt.Sprintf("Account with id %s was not found", id),
Code: "ACCOUNT_NOT_FOUND",
Err: err,
}
}

return nil, err
}

return accountUpdated, nil
}
Loading

0 comments on commit ce9291c

Please sign in to comment.