Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/MIDAZ-204 #206

Merged
merged 2 commits into from
Nov 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions common/mmodel/asset.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package mmodel

import "time"

// CreateAssetInput is a struct design to encapsulate request create payload data.
type CreateAssetInput struct {
Name string `json:"name" validate:"max=256"`
Type string `json:"type"`
Code string `json:"code" validate:"required,max=100"`
Status Status `json:"status"`
Metadata map[string]any `json:"metadata" validate:"dive,keys,keymax=100,endkeys,nonested,valuemax=2000"`
}

// UpdateAssetInput is a struct design to encapsulate request update payload data.
type UpdateAssetInput struct {
Name string `json:"name" validate:"max=256"`
Status Status `json:"status"`
Metadata map[string]any `json:"metadata" validate:"dive,keys,keymax=100,endkeys,nonested,valuemax=2000"`
}

// Asset is a struct designed to encapsulate payload data.
type Asset struct {
ID string `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
Code string `json:"code"`
Status Status `json:"status"`
LedgerID string `json:"ledgerId"`
OrganizationID string `json:"organizationId"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt *time.Time `json:"deletedAt"`
Metadata map[string]any `json:"metadata,omitempty"`
}

// IsEmpty method that set empty or nil in fields
func (s Status) IsEmpty() bool {
return s.Code == "" && s.Description == nil
}
Binary file modified components/mdz/bin/mdz
Binary file not shown.
7 changes: 7 additions & 0 deletions components/mdz/internal/domain/repository/asset.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package repository

import "github.com/LerianStudio/midaz/common/mmodel"

type Asset interface {
Create(organizationID, ledgerID string, inp mmodel.CreateAssetInput) (*mmodel.Asset, error)
}
56 changes: 56 additions & 0 deletions components/mdz/internal/domain/repository/asset_mock.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"id": "01930219-2c25-7a37-a5b9-610d44ae0a27",
"name": "Brazilian Real",
"type": "currency",
"code": "BRL",
"status": {
"code": "ACTIVE",
"description": "Teste asset 1"
},
"ledgerId": "0192e251-328d-7390-99f5-5c54980115ed",
"organizationId": "0192e250-ed9d-7e5c-a614-9b294151b572",
"createdAt": "2024-11-06T15:30:24.421664681Z",
"updatedAt": "2024-11-06T15:30:24.421664731Z",
"deletedAt": null,
"metadata": {
"bitcoin": "3oDTprwNG37nASsyLzQGLuUBzNac",
"chave": "metadata_chave",
"boolean": false
}
}
56 changes: 56 additions & 0 deletions components/mdz/internal/rest/asset.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package rest

import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net/http"

"github.com/LerianStudio/midaz/common/mmodel"
"github.com/LerianStudio/midaz/components/mdz/pkg/factory"
)

type asset struct {
Factory *factory.Factory
}

func (r *asset) Create(organizationID, ledgerID string, inp mmodel.CreateAssetInput) (*mmodel.Asset, error) {
jsonData, err := json.Marshal(inp)
if err != nil {
return nil, fmt.Errorf("marshalling JSON: %v", err)
}

uri := fmt.Sprintf("%s/v1/organizations/%s/ledgers/%s/assets",
r.Factory.Env.URLAPILedger, organizationID, ledgerID)

req, err := http.NewRequest(http.MethodPost, uri, bytes.NewBuffer(jsonData))
if err != nil {
return nil, errors.New("creating request: " + err.Error())
}

req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+r.Factory.Token)

resp, err := r.Factory.HTTPClient.Do(req)
if err != nil {
return nil, errors.New("making POST request: " + err.Error())
}

defer resp.Body.Close()

if err := checkResponse(resp, http.StatusCreated); err != nil {
return nil, err
}

var assetRest mmodel.Asset
if err := json.NewDecoder(resp.Body).Decode(&assetRest); err != nil {
return nil, errors.New("decoding response JSON:" + err.Error())
}

return &assetRest, nil
}

func NewAsset(f *factory.Factory) *asset {
return &asset{f}
}
103 changes: 103 additions & 0 deletions components/mdz/internal/rest/asset_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
package rest

import (
"fmt"
"net/http"
"testing"
"time"

"github.com/LerianStudio/midaz/common/mmodel"
"github.com/LerianStudio/midaz/components/mdz/pkg/environment"
"github.com/LerianStudio/midaz/components/mdz/pkg/factory"
"github.com/LerianStudio/midaz/components/mdz/pkg/mockutil"
"github.com/LerianStudio/midaz/components/mdz/pkg/ptr"
"github.com/jarcoal/httpmock"
"github.com/stretchr/testify/assert"
)

func Test_asset_Create(t *testing.T) {
organizationID := "0192e250-ed9d-7e5c-a614-9b294151b572"
ledgerID := "0192e251-328d-7390-99f5-5c54980115ed"
assetID := "01930219-2c25-7a37-a5b9-610d44ae0a27"

name := "Brazilian Real"
typeV := "currency"
code := "BRL"
statusCode := "ACTIVE"
statusDescription := ptr.StringPtr("Teste asset 1")

metadata := map[string]any{
"bitcoin": "3oDTprwNG37nASsyLzQGLuUBzNac",
"chave": "metadata_chave",
"boolean": false,
}

input := mmodel.CreateAssetInput{
Name: name,
Type: typeV,
Code: code,
Status: mmodel.Status{
Code: statusCode,
Description: statusDescription,
},
Metadata: metadata,
}

expectedResult := &mmodel.Asset{
ID: assetID,
Name: name,
Type: typeV,
Code: code,
Status: mmodel.Status{
Code: statusCode,
Description: statusDescription,
},
LedgerID: ledgerID,
OrganizationID: organizationID,
CreatedAt: time.Date(2024, 11, 06, 15, 30, 24, 421664681, time.UTC),
UpdatedAt: time.Date(2024, 11, 06, 15, 30, 24, 421664731, time.UTC),
DeletedAt: nil,
Metadata: metadata,
}

client := &http.Client{}
httpmock.ActivateNonDefault(client)
defer httpmock.DeactivateAndReset()

URIAPILedger := "http://127.0.0.1:3000"

uri := fmt.Sprintf("%s/v1/organizations/%s/ledgers/%s/assets",
URIAPILedger, organizationID, ledgerID)

httpmock.RegisterResponder(http.MethodPost, uri,
mockutil.MockResponseFromFile(http.StatusCreated, "./.fixtures/asset_response_create.json"))

factory := &factory.Factory{
HTTPClient: client,
Env: &environment.Env{
URLAPILedger: URIAPILedger,
},
}

asset := NewAsset(factory)

result, err := asset.Create(organizationID, ledgerID, input)

assert.NoError(t, err)
assert.NotNil(t, result)
assert.Equal(t, expectedResult.ID, result.ID)
assert.Equal(t, expectedResult.Name, result.Name)
assert.Equal(t, expectedResult.Type, result.Type)
assert.Equal(t, expectedResult.Code, result.Code)
assert.Equal(t, expectedResult.Status.Code, result.Status.Code)
assert.Equal(t, *expectedResult.Status.Description, *result.Status.Description)
assert.Equal(t, expectedResult.LedgerID, result.LedgerID)
assert.Equal(t, expectedResult.OrganizationID, result.OrganizationID)
assert.Equal(t, expectedResult.CreatedAt, result.CreatedAt)
assert.Equal(t, expectedResult.UpdatedAt, result.UpdatedAt)
assert.Equal(t, expectedResult.DeletedAt, result.DeletedAt)
assert.Equal(t, expectedResult.Metadata, result.Metadata)

info := httpmock.GetCallCountInfo()
assert.Equal(t, 1, info["POST http://127.0.0.1:3000/v1/organizations/0192e250-ed9d-7e5c-a614-9b294151b572/ledgers/0192e251-328d-7390-99f5-5c54980115ed/assets"])
}
41 changes: 41 additions & 0 deletions components/mdz/pkg/cmd/asset/asset.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package asset

import (
"github.com/LerianStudio/midaz/components/mdz/pkg/cmd/utils"
"github.com/LerianStudio/midaz/components/mdz/pkg/factory"
"github.com/spf13/cobra"
)

type factoryAsset struct {
factory *factory.Factory
}

func (f *factoryAsset) setCmds(cmd *cobra.Command) {
cmd.AddCommand(newCmdAssetCreate(newInjectFacCreate(f.factory)))
}

func NewCmdAsset(f *factory.Factory) *cobra.Command {
fAsset := factoryAsset{
factory: f,
}
cmd := &cobra.Command{
Use: "asset",
Short: "Manages the assets allowed in the ledger.",
Long: utils.Format(
"It centralizes the management of assets allowed in the ledger",
"such as currencies, commodities and goods. The asset command makes",
"it easy to create, update, remove and consult assets, which can be",
"used in accounts and operations in the portfolio. These assets",
"represent balance and are essential for transactions and management",
"in the onboarding flow.",
),
Example: utils.Format(
"$ mdz asset",
"$ mdz asset -h",
),
}
cmd.Flags().BoolP("help", "h", false, "Displays more information about the Midaz CLI")
fAsset.setCmds(cmd)

return cmd
}
Loading
Loading