diff --git a/STRUCTURE.md b/STRUCTURE.md index 06d0babe8..e4d48af67 100644 --- a/STRUCTURE.md +++ b/STRUCTURE.md @@ -38,7 +38,7 @@ The project is structured into several key directories, each serving specific ro │   │   │   │   ├── account │   │   │   │   ├── asset │   │   │   │   ├── portfolio -│   │   │   │   └── product +│   │   │   │   └── segment │   │   │   ├── gen │   │   │   │   └── mock │   │   │   │   ├── account @@ -47,7 +47,7 @@ The project is structured into several key directories, each serving specific ro │   │   │   │   ├── metadata │   │   │   │   ├── organization │   │   │   │   ├── portfolio -│   │   │   │   └── product +│   │   │   │   └── segment │   │   │   ├── ports │   │   │   │   └── http │   │   │   └── service diff --git a/chocolatey/tools/chocolateyinstall.ps1 b/chocolatey/tools/chocolateyinstall.ps1 index ff60aa039..f98f22376 100644 --- a/chocolatey/tools/chocolateyinstall.ps1 +++ b/chocolatey/tools/chocolateyinstall.ps1 @@ -1,4 +1,4 @@ -$version = 'v1.46.0' +$version = 'v1.47.0' $ErrorActionPreference = 'Stop'; diff --git a/components/audit/.env.example b/components/audit/.env.example index e6ab4bae6..36658c149 100644 --- a/components/audit/.env.example +++ b/components/audit/.env.example @@ -2,7 +2,7 @@ # ENV_NAME=production # APP -VERSION=v1.46.0 +VERSION=v1.47.0 SERVER_PORT=3005 SERVER_ADDRESS=:${SERVER_PORT} diff --git a/components/auth/setup/00_init.sql b/components/auth/setup/00_init.sql index c8477fb7d..4bcb61750 100644 --- a/components/auth/setup/00_init.sql +++ b/components/auth/setup/00_init.sql @@ -48,10 +48,10 @@ INSERT INTO "casbin_lerian_enforcer_rule" ("ptype", "v0", "v1", "v2", "v3", "v4" ('p', 'developer_role', 'portfolio', 'get', '', '', ''), ('p', 'developer_role', 'portfolio', 'patch', '', '', ''), ('p', 'developer_role', 'portfolio', 'put', '', '', ''), -('p', 'developer_role', 'product', 'post', '', '', ''), -('p', 'developer_role', 'product', 'get', '', '', ''), -('p', 'developer_role', 'product', 'patch', '', '', ''), -('p', 'developer_role', 'product', 'put', '', '', ''), +('p', 'developer_role', 'segment', 'post', '', '', ''), +('p', 'developer_role', 'segment', 'get', '', '', ''), +('p', 'developer_role', 'segment', 'patch', '', '', ''), +('p', 'developer_role', 'segment', 'put', '', '', ''), ('p', 'developer_role', 'account', 'post', '', '', ''), ('p', 'developer_role', 'account', 'get', '', '', ''), ('p', 'developer_role', 'account', 'patch', '', '', ''), @@ -70,7 +70,7 @@ INSERT INTO "casbin_lerian_enforcer_rule" ("ptype", "v0", "v1", "v2", "v3", "v4" ('p', 'user_role', 'ledger', 'get', '', '', ''), ('p', 'user_role', 'asset', 'get', '', '', ''), ('p', 'user_role', 'portfolio', 'get', '', '', ''), -('p', 'user_role', 'product', 'get', '', '', ''), +('p', 'user_role', 'segment', 'get', '', '', ''), ('p', 'user_role', 'account', 'get', '', '', ''), ('p', 'user_role', 'transaction', 'get', '', '', ''), ('p', 'user_role', 'operation', 'get', '', '', ''), diff --git a/components/auth/setup/init_data.json b/components/auth/setup/init_data.json index ba85ebe0c..ee0ad8ffc 100644 --- a/components/auth/setup/init_data.json +++ b/components/auth/setup/init_data.json @@ -814,7 +814,7 @@ "ledger", "organization", "portfolio", - "product", + "segment", "transaction", "operation", "asset-rate" @@ -879,7 +879,7 @@ "ledger", "organization", "portfolio", - "product", + "segment", "transaction", "operation", "asset-rate" diff --git a/components/ledger/.env.example b/components/ledger/.env.example index 2018a92a8..5973eedf7 100644 --- a/components/ledger/.env.example +++ b/components/ledger/.env.example @@ -4,7 +4,7 @@ # ENV_NAME=production # APP -VERSION=v1.46.0 +VERSION=v1.47.0 SERVER_PORT=3000 SERVER_ADDRESS=:${SERVER_PORT} diff --git a/components/ledger/api/docs.go b/components/ledger/api/docs.go index d42ac61aa..a4c4d0014 100644 --- a/components/ledger/api/docs.go +++ b/components/ledger/api/docs.go @@ -2014,16 +2014,16 @@ const docTemplate = `{ } } }, - "/v1/organizations/{organization_id}/ledgers/{ledger_id}/products": { + "/v1/organizations/{organization_id}/ledgers/{ledger_id}/segments": { "get": { - "description": "Get all Products with the input metadata or without metadata", + "description": "Get all Segments with the input metadata or without metadata", "produces": [ "application/json" ], "tags": [ - "Products" + "Segments" ], - "summary": "Get all Products", + "summary": "Get all Segments", "parameters": [ { "type": "string", @@ -2109,7 +2109,7 @@ const docTemplate = `{ "items": { "type": "array", "items": { - "$ref": "#/definitions/Product" + "$ref": "#/definitions/Segment" } }, "limit": { @@ -2126,7 +2126,7 @@ const docTemplate = `{ } }, "post": { - "description": "Create a Product with the input payload", + "description": "Create a Segment with the input payload", "consumes": [ "application/json" ], @@ -2134,9 +2134,9 @@ const docTemplate = `{ "application/json" ], "tags": [ - "Products" + "Segments" ], - "summary": "Create a Product", + "summary": "Create a Segment", "parameters": [ { "type": "string", @@ -2166,12 +2166,12 @@ const docTemplate = `{ "required": true }, { - "description": "Product", - "name": "product", + "description": "Segment", + "name": "segment", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/CreateProductInput" + "$ref": "#/definitions/CreateSegmentInput" } } ], @@ -2179,22 +2179,22 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/Product" + "$ref": "#/definitions/Segment" } } } } }, - "/v1/organizations/{organization_id}/ledgers/{ledger_id}/products/{id}": { + "/v1/organizations/{organization_id}/ledgers/{ledger_id}/segments/{id}": { "get": { - "description": "Get a Product with the input ID", + "description": "Get a Segment with the input ID", "produces": [ "application/json" ], "tags": [ - "Products" + "Segments" ], - "summary": "Get a Product by ID", + "summary": "Get a Segment by ID", "parameters": [ { "type": "string", @@ -2225,7 +2225,7 @@ const docTemplate = `{ }, { "type": "string", - "description": "Product ID", + "description": "Segment ID", "name": "id", "in": "path", "required": true @@ -2235,17 +2235,17 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/Product" + "$ref": "#/definitions/Segment" } } } }, "delete": { - "description": "Delete a Product with the input ID", + "description": "Delete a Segment with the input ID", "tags": [ - "Products" + "Segments" ], - "summary": "Delete a Product by ID", + "summary": "Delete a Segment by ID", "parameters": [ { "type": "string", @@ -2276,7 +2276,7 @@ const docTemplate = `{ }, { "type": "string", - "description": "Product ID", + "description": "Segment ID", "name": "id", "in": "path", "required": true @@ -2289,7 +2289,7 @@ const docTemplate = `{ } }, "patch": { - "description": "Update a Product with the input payload", + "description": "Update a Segment with the input payload", "consumes": [ "application/json" ], @@ -2297,9 +2297,9 @@ const docTemplate = `{ "application/json" ], "tags": [ - "Products" + "Segments" ], - "summary": "Update a Product", + "summary": "Update a Segment", "parameters": [ { "type": "string", @@ -2330,18 +2330,18 @@ const docTemplate = `{ }, { "type": "string", - "description": "Product ID", + "description": "Segment ID", "name": "id", "in": "path", "required": true }, { - "description": "Product", - "name": "product", + "description": "Segment", + "name": "segment", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/UpdateProductInput" + "$ref": "#/definitions/UpdateSegmentInput" } } ], @@ -2349,7 +2349,7 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/Product" + "$ref": "#/definitions/Segment" } } } @@ -2420,7 +2420,7 @@ const docTemplate = `{ "type": "string", "example": "00000000-0000-0000-0000-000000000000" }, - "productId": { + "segmentId": { "type": "string", "example": "00000000-0000-0000-0000-000000000000" }, @@ -2583,7 +2583,7 @@ const docTemplate = `{ "type": "string", "example": "00000000-0000-0000-0000-000000000000" }, - "productId": { + "segmentId": { "type": "string", "example": "00000000-0000-0000-0000-000000000000" }, @@ -2713,8 +2713,8 @@ const docTemplate = `{ } } }, - "CreateProductInput": { - "description": "CreateProductInput is the input payload to create a product.", + "CreateSegmentInput": { + "description": "CreateSegmentInput is the input payload to create a segment.", "type": "object", "required": [ "name" @@ -2727,7 +2727,7 @@ const docTemplate = `{ "name": { "type": "string", "maxLength": 256, - "example": "My Product" + "example": "My Segment" }, "status": { "$ref": "#/definitions/Status" @@ -2889,8 +2889,8 @@ const docTemplate = `{ } } }, - "Product": { - "description": "Product is a struct designed to store product data.", + "Segment": { + "description": "Segment is a struct designed to store segment data.", "type": "object", "properties": { "createdAt": { @@ -2915,7 +2915,7 @@ const docTemplate = `{ }, "name": { "type": "string", - "example": "My Product" + "example": "My Segment" }, "organizationId": { "type": "string", @@ -2972,11 +2972,11 @@ const docTemplate = `{ "maxLength": 256, "example": "My Account Updated" }, - "productId": { + "portfolioId": { "type": "string", "example": "00000000-0000-0000-0000-000000000000" }, - "portfolioId": { + "segmentId": { "type": "string", "example": "00000000-0000-0000-0000-000000000000" }, @@ -3072,8 +3072,8 @@ const docTemplate = `{ } } }, - "UpdateProductInput": { - "description": "UpdateProductInput is the input payload to update a product.", + "UpdateSegmentInput": { + "description": "UpdateSegmentInput is the input payload to update a segment.", "type": "object", "properties": { "metadata": { @@ -3083,7 +3083,7 @@ const docTemplate = `{ "name": { "type": "string", "maxLength": 256, - "example": "My Product Updated" + "example": "My Segment Updated" }, "status": { "$ref": "#/definitions/Status" diff --git a/components/ledger/api/openapi.yaml b/components/ledger/api/openapi.yaml index 1cbfcbd9d..8906210da 100644 --- a/components/ledger/api/openapi.yaml +++ b/components/ledger/api/openapi.yaml @@ -1470,9 +1470,9 @@ paths: tags: - Accounts x-codegen-request-body-name: account - /v1/organizations/{organization_id}/ledgers/{ledger_id}/products: + /v1/organizations/{organization_id}/ledgers/{ledger_id}/segments: get: - description: Get all Products with the input metadata or without metadata + description: Get all Segments with the input metadata or without metadata parameters: - description: Authorization Bearer Token in: header @@ -1539,11 +1539,11 @@ paths: schema: $ref: '#/components/schemas/inline_response_200_6' description: OK - summary: Get all Products + summary: Get all Segments tags: - - Products + - Segments post: - description: Create a Product with the input payload + description: Create a Segment with the input payload parameters: - description: Authorization Bearer Token in: header @@ -1572,23 +1572,23 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/CreateProductInput' - description: Product + $ref: '#/components/schemas/CreateSegmentInput' + description: Segment required: true responses: "200": content: application/json: schema: - $ref: '#/components/schemas/Product' + $ref: '#/components/schemas/Segment' description: OK - summary: Create a Product + summary: Create a Segment tags: - - Products - x-codegen-request-body-name: product - /v1/organizations/{organization_id}/ledgers/{ledger_id}/products/{id}: + - Segments + x-codegen-request-body-name: segment + /v1/organizations/{organization_id}/ledgers/{ledger_id}/segments/{id}: delete: - description: Delete a Product with the input ID + description: Delete a Segment with the input ID parameters: - description: Authorization Bearer Token in: header @@ -1613,7 +1613,7 @@ paths: required: true schema: type: string - - description: Product ID + - description: Segment ID in: path name: id required: true @@ -1623,11 +1623,11 @@ paths: "204": content: {} description: No Content - summary: Delete a Product by ID + summary: Delete a Segment by ID tags: - - Products + - Segments get: - description: Get a Product with the input ID + description: Get a Segment with the input ID parameters: - description: Authorization Bearer Token in: header @@ -1652,7 +1652,7 @@ paths: required: true schema: type: string - - description: Product ID + - description: Segment ID in: path name: id required: true @@ -1663,13 +1663,13 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/Product' + $ref: '#/components/schemas/Segment' description: OK - summary: Get a Product by ID + summary: Get a Segment by ID tags: - - Products + - Segments patch: - description: Update a Product with the input payload + description: Update a Segment with the input payload parameters: - description: Authorization Bearer Token in: header @@ -1694,7 +1694,7 @@ paths: required: true schema: type: string - - description: Product ID + - description: Segment ID in: path name: id required: true @@ -1704,20 +1704,20 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/UpdateProductInput' - description: Product + $ref: '#/components/schemas/UpdateSegmentInput' + description: Segment required: true responses: "200": content: application/json: schema: - $ref: '#/components/schemas/Product' + $ref: '#/components/schemas/Segment' description: OK - summary: Update a Product + summary: Update a Segment tags: - - Products - x-codegen-request-body-name: product + - Segments + x-codegen-request-body-name: segment components: schemas: Account: @@ -1726,7 +1726,6 @@ components: metadata: key: '{}' assetCode: BRL - productId: 00000000-0000-0000-0000-000000000000 allowReceiving: true entityId: 00000000-0000-0000-0000-000000000000 allowSending: true @@ -1741,6 +1740,7 @@ components: onHold: 500.0 available: 1500.0 scale: 2.0 + segmentId: 00000000-0000-0000-0000-000000000000 name: My Account alias: '@person1' id: 00000000-0000-0000-0000-000000000000 @@ -1794,7 +1794,7 @@ components: portfolioId: example: 00000000-0000-0000-0000-000000000000 type: string - productId: + segmentId: example: 00000000-0000-0000-0000-000000000000 type: string status: @@ -1913,8 +1913,8 @@ components: key: '{}' assetCode: BRL portfolioId: 00000000-0000-0000-0000-000000000000 - productId: 00000000-0000-0000-0000-000000000000 allowReceiving: true + segmentId: 00000000-0000-0000-0000-000000000000 name: My Account alias: '@person1' entityId: 00000000-0000-0000-0000-000000000000 @@ -1956,7 +1956,7 @@ components: portfolioId: example: 00000000-0000-0000-0000-000000000000 type: string - productId: + segmentId: example: 00000000-0000-0000-0000-000000000000 type: string status: @@ -2099,12 +2099,12 @@ components: - entityId - name type: object - CreateProductInput: - description: CreateProductInput is the input payload to create a product. + CreateSegmentInput: + description: CreateSegmentInput is the input payload to create a segment. example: metadata: key: '{}' - name: My Product + name: My Segment status: code: ACTIVE description: Active status @@ -2114,7 +2114,7 @@ components: type: object type: object name: - example: My Product + example: My Segment maxLength: 256 type: string status: @@ -2294,8 +2294,8 @@ components: example: 2021-01-01T00:00:00Z type: string type: object - Product: - description: Product is a struct designed to store product data. + Segment: + description: Segment is a struct designed to store segment data. example: ledgerId: 00000000-0000-0000-0000-000000000000 organizationId: 00000000-0000-0000-0000-000000000000 @@ -2303,7 +2303,7 @@ components: deletedAt: 2021-01-01T00:00:00Z metadata: key: '{}' - name: My Product + name: My Segment id: 00000000-0000-0000-0000-000000000000 status: code: ACTIVE @@ -2327,7 +2327,7 @@ components: type: object type: object name: - example: My Product + example: My Segment type: string organizationId: example: 00000000-0000-0000-0000-000000000000 @@ -2358,8 +2358,9 @@ components: example: metadata: key: '{}' - productId: 00000000-0000-0000-0000-000000000000 + portfolioId: 00000000-0000-0000-0000-000000000000 allowReceiving: true + segmentId: 00000000-0000-0000-0000-000000000000 name: My Account Updated alias: '@person1' allowSending: true @@ -2385,10 +2386,10 @@ components: example: My Account Updated maxLength: 256 type: string - productId: + portfolioId: example: 00000000-0000-0000-0000-000000000000 type: string - portfolioId: + segmentId: example: 00000000-0000-0000-0000-000000000000 type: string status: @@ -2498,12 +2499,12 @@ components: status: $ref: '#/components/schemas/Status' type: object - UpdateProductInput: - description: UpdateProductInput is the input payload to update a product. + UpdateSegmentInput: + description: UpdateSegmentInput is the input payload to update a segment. example: metadata: key: '{}' - name: My Product Updated + name: My Segment Updated status: code: ACTIVE description: Active status @@ -2513,7 +2514,7 @@ components: type: object type: object name: - example: My Product Updated + example: My Segment Updated maxLength: 256 type: string status: @@ -2641,7 +2642,6 @@ components: - metadata: key: '{}' assetCode: BRL - productId: 00000000-0000-0000-0000-000000000000 allowReceiving: true entityId: 00000000-0000-0000-0000-000000000000 allowSending: true @@ -2656,6 +2656,7 @@ components: onHold: 500.0 available: 1500.0 scale: 2.0 + segmentId: 00000000-0000-0000-0000-000000000000 name: My Account alias: '@person1' id: 00000000-0000-0000-0000-000000000000 @@ -2666,7 +2667,6 @@ components: - metadata: key: '{}' assetCode: BRL - productId: 00000000-0000-0000-0000-000000000000 allowReceiving: true entityId: 00000000-0000-0000-0000-000000000000 allowSending: true @@ -2681,6 +2681,7 @@ components: onHold: 500.0 available: 1500.0 scale: 2.0 + segmentId: 00000000-0000-0000-0000-000000000000 name: My Account alias: '@person1' id: 00000000-0000-0000-0000-000000000000 @@ -2812,7 +2813,6 @@ components: - metadata: key: '{}' assetCode: BRL - productId: 00000000-0000-0000-0000-000000000000 allowReceiving: true entityId: 00000000-0000-0000-0000-000000000000 allowSending: true @@ -2827,6 +2827,7 @@ components: onHold: 500.0 available: 1500.0 scale: 2.0 + segmentId: 00000000-0000-0000-0000-000000000000 name: My Account alias: '@person1' id: 00000000-0000-0000-0000-000000000000 @@ -2837,7 +2838,6 @@ components: - metadata: key: '{}' assetCode: BRL - productId: 00000000-0000-0000-0000-000000000000 allowReceiving: true entityId: 00000000-0000-0000-0000-000000000000 allowSending: true @@ -2852,6 +2852,7 @@ components: onHold: 500.0 available: 1500.0 scale: 2.0 + segmentId: 00000000-0000-0000-0000-000000000000 name: My Account alias: '@person1' id: 00000000-0000-0000-0000-000000000000 @@ -2884,7 +2885,7 @@ components: deletedAt: 2021-01-01T00:00:00Z metadata: key: '{}' - name: My Product + name: My Segment id: 00000000-0000-0000-0000-000000000000 status: code: ACTIVE @@ -2896,7 +2897,7 @@ components: deletedAt: 2021-01-01T00:00:00Z metadata: key: '{}' - name: My Product + name: My Segment id: 00000000-0000-0000-0000-000000000000 status: code: ACTIVE @@ -2907,7 +2908,7 @@ components: $ref: '#/components/schemas/Pagination' items: items: - $ref: '#/components/schemas/Product' + $ref: '#/components/schemas/Segment' type: array limit: type: integer diff --git a/components/ledger/api/swagger.json b/components/ledger/api/swagger.json index cf24437f8..495f8df3d 100644 --- a/components/ledger/api/swagger.json +++ b/components/ledger/api/swagger.json @@ -2008,16 +2008,16 @@ } } }, - "/v1/organizations/{organization_id}/ledgers/{ledger_id}/products": { + "/v1/organizations/{organization_id}/ledgers/{ledger_id}/segments": { "get": { - "description": "Get all Products with the input metadata or without metadata", + "description": "Get all Segments with the input metadata or without metadata", "produces": [ "application/json" ], "tags": [ - "Products" + "Segments" ], - "summary": "Get all Products", + "summary": "Get all Segments", "parameters": [ { "type": "string", @@ -2103,7 +2103,7 @@ "items": { "type": "array", "items": { - "$ref": "#/definitions/Product" + "$ref": "#/definitions/Segment" } }, "limit": { @@ -2120,7 +2120,7 @@ } }, "post": { - "description": "Create a Product with the input payload", + "description": "Create a Segment with the input payload", "consumes": [ "application/json" ], @@ -2128,9 +2128,9 @@ "application/json" ], "tags": [ - "Products" + "Segments" ], - "summary": "Create a Product", + "summary": "Create a Segment", "parameters": [ { "type": "string", @@ -2160,12 +2160,12 @@ "required": true }, { - "description": "Product", - "name": "product", + "description": "Segment", + "name": "segment", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/CreateProductInput" + "$ref": "#/definitions/CreateSegmentInput" } } ], @@ -2173,22 +2173,22 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/Product" + "$ref": "#/definitions/Segment" } } } } }, - "/v1/organizations/{organization_id}/ledgers/{ledger_id}/products/{id}": { + "/v1/organizations/{organization_id}/ledgers/{ledger_id}/segments/{id}": { "get": { - "description": "Get a Product with the input ID", + "description": "Get a Segment with the input ID", "produces": [ "application/json" ], "tags": [ - "Products" + "Segments" ], - "summary": "Get a Product by ID", + "summary": "Get a Segment by ID", "parameters": [ { "type": "string", @@ -2219,7 +2219,7 @@ }, { "type": "string", - "description": "Product ID", + "description": "Segment ID", "name": "id", "in": "path", "required": true @@ -2229,17 +2229,17 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/Product" + "$ref": "#/definitions/Segment" } } } }, "delete": { - "description": "Delete a Product with the input ID", + "description": "Delete a Segment with the input ID", "tags": [ - "Products" + "Segments" ], - "summary": "Delete a Product by ID", + "summary": "Delete a Segment by ID", "parameters": [ { "type": "string", @@ -2270,7 +2270,7 @@ }, { "type": "string", - "description": "Product ID", + "description": "Segment ID", "name": "id", "in": "path", "required": true @@ -2283,7 +2283,7 @@ } }, "patch": { - "description": "Update a Product with the input payload", + "description": "Update a Segment with the input payload", "consumes": [ "application/json" ], @@ -2291,9 +2291,9 @@ "application/json" ], "tags": [ - "Products" + "Segments" ], - "summary": "Update a Product", + "summary": "Update a Segment", "parameters": [ { "type": "string", @@ -2324,18 +2324,18 @@ }, { "type": "string", - "description": "Product ID", + "description": "Segment ID", "name": "id", "in": "path", "required": true }, { - "description": "Product", - "name": "product", + "description": "Segment", + "name": "segment", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/UpdateProductInput" + "$ref": "#/definitions/UpdateSegmentInput" } } ], @@ -2343,7 +2343,7 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/Product" + "$ref": "#/definitions/Segment" } } } @@ -2414,7 +2414,7 @@ "type": "string", "example": "00000000-0000-0000-0000-000000000000" }, - "productId": { + "segmentId": { "type": "string", "example": "00000000-0000-0000-0000-000000000000" }, @@ -2577,7 +2577,7 @@ "type": "string", "example": "00000000-0000-0000-0000-000000000000" }, - "productId": { + "segmentId": { "type": "string", "example": "00000000-0000-0000-0000-000000000000" }, @@ -2707,8 +2707,8 @@ } } }, - "CreateProductInput": { - "description": "CreateProductInput is the input payload to create a product.", + "CreateSegmentInput": { + "description": "CreateSegmentInput is the input payload to create a segment.", "type": "object", "required": [ "name" @@ -2721,7 +2721,7 @@ "name": { "type": "string", "maxLength": 256, - "example": "My Product" + "example": "My Segment" }, "status": { "$ref": "#/definitions/Status" @@ -2883,8 +2883,8 @@ } } }, - "Product": { - "description": "Product is a struct designed to store product data.", + "Segment": { + "description": "Segment is a struct designed to store segment data.", "type": "object", "properties": { "createdAt": { @@ -2909,7 +2909,7 @@ }, "name": { "type": "string", - "example": "My Product" + "example": "My Segment" }, "organizationId": { "type": "string", @@ -2966,11 +2966,11 @@ "maxLength": 256, "example": "My Account Updated" }, - "productId": { + "portfolioId": { "type": "string", "example": "00000000-0000-0000-0000-000000000000" }, - "portfolioId": { + "segmentId": { "type": "string", "example": "00000000-0000-0000-0000-000000000000" }, @@ -3066,8 +3066,8 @@ } } }, - "UpdateProductInput": { - "description": "UpdateProductInput is the input payload to update a product.", + "UpdateSegmentInput": { + "description": "UpdateSegmentInput is the input payload to update a segment.", "type": "object", "properties": { "metadata": { @@ -3077,7 +3077,7 @@ "name": { "type": "string", "maxLength": 256, - "example": "My Product Updated" + "example": "My Segment Updated" }, "status": { "$ref": "#/definitions/Status" diff --git a/components/ledger/api/swagger.yaml b/components/ledger/api/swagger.yaml index 4d7f3688d..16f89b74b 100644 --- a/components/ledger/api/swagger.yaml +++ b/components/ledger/api/swagger.yaml @@ -47,7 +47,7 @@ definitions: portfolioId: example: 00000000-0000-0000-0000-000000000000 type: string - productId: + segmentId: example: 00000000-0000-0000-0000-000000000000 type: string status: @@ -165,7 +165,7 @@ definitions: portfolioId: example: 00000000-0000-0000-0000-000000000000 type: string - productId: + segmentId: example: 00000000-0000-0000-0000-000000000000 type: string status: @@ -263,14 +263,14 @@ definitions: - entityId - name type: object - CreateProductInput: - description: CreateProductInput is the input payload to create a product. + CreateSegmentInput: + description: CreateSegmentInput is the input payload to create a segment. properties: metadata: additionalProperties: {} type: object name: - example: My Product + example: My Segment maxLength: 256 type: string status: @@ -393,8 +393,8 @@ definitions: example: "2021-01-01T00:00:00Z" type: string type: object - Product: - description: Product is a struct designed to store product data. + Segment: + description: Segment is a struct designed to store segment data. properties: createdAt: example: "2021-01-01T00:00:00Z" @@ -412,7 +412,7 @@ definitions: additionalProperties: {} type: object name: - example: My Product + example: My Segment type: string organizationId: example: 00000000-0000-0000-0000-000000000000 @@ -455,10 +455,10 @@ definitions: example: My Account Updated maxLength: 256 type: string - productId: + portfolioId: example: 00000000-0000-0000-0000-000000000000 type: string - portfolioId: + segmentId: example: 00000000-0000-0000-0000-000000000000 type: string status: @@ -527,14 +527,14 @@ definitions: status: $ref: '#/definitions/Status' type: object - UpdateProductInput: - description: UpdateProductInput is the input payload to update a product. + UpdateSegmentInput: + description: UpdateSegmentInput is the input payload to update a segment. properties: metadata: additionalProperties: {} type: object name: - example: My Product Updated + example: My Segment Updated maxLength: 256 type: string status: @@ -1902,9 +1902,9 @@ paths: summary: Update an Account from Portfolio tags: - Accounts - /v1/organizations/{organization_id}/ledgers/{ledger_id}/products: + /v1/organizations/{organization_id}/ledgers/{ledger_id}/segments: get: - description: Get all Products with the input metadata or without metadata + description: Get all Segments with the input metadata or without metadata parameters: - description: Authorization Bearer Token in: header @@ -1965,20 +1965,20 @@ paths: - properties: items: items: - $ref: '#/definitions/Product' + $ref: '#/definitions/Segment' type: array limit: type: integer page: type: integer type: object - summary: Get all Products + summary: Get all Segments tags: - - Products + - Segments post: consumes: - application/json - description: Create a Product with the input payload + description: Create a Segment with the input payload parameters: - description: Authorization Bearer Token in: header @@ -1999,25 +1999,25 @@ paths: name: ledger_id required: true type: string - - description: Product + - description: Segment in: body - name: product + name: segment required: true schema: - $ref: '#/definitions/CreateProductInput' + $ref: '#/definitions/CreateSegmentInput' produces: - application/json responses: "200": description: OK schema: - $ref: '#/definitions/Product' - summary: Create a Product + $ref: '#/definitions/Segment' + summary: Create a Segment tags: - - Products - /v1/organizations/{organization_id}/ledgers/{ledger_id}/products/{id}: + - Segments + /v1/organizations/{organization_id}/ledgers/{ledger_id}/segments/{id}: delete: - description: Delete a Product with the input ID + description: Delete a Segment with the input ID parameters: - description: Authorization Bearer Token in: header @@ -2038,7 +2038,7 @@ paths: name: ledger_id required: true type: string - - description: Product ID + - description: Segment ID in: path name: id required: true @@ -2046,11 +2046,11 @@ paths: responses: "204": description: No Content - summary: Delete a Product by ID + summary: Delete a Segment by ID tags: - - Products + - Segments get: - description: Get a Product with the input ID + description: Get a Segment with the input ID parameters: - description: Authorization Bearer Token in: header @@ -2071,7 +2071,7 @@ paths: name: ledger_id required: true type: string - - description: Product ID + - description: Segment ID in: path name: id required: true @@ -2082,14 +2082,14 @@ paths: "200": description: OK schema: - $ref: '#/definitions/Product' - summary: Get a Product by ID + $ref: '#/definitions/Segment' + summary: Get a Segment by ID tags: - - Products + - Segments patch: consumes: - application/json - description: Update a Product with the input payload + description: Update a Segment with the input payload parameters: - description: Authorization Bearer Token in: header @@ -2110,25 +2110,25 @@ paths: name: ledger_id required: true type: string - - description: Product ID + - description: Segment ID in: path name: id required: true type: string - - description: Product + - description: Segment in: body - name: product + name: segment required: true schema: - $ref: '#/definitions/UpdateProductInput' + $ref: '#/definitions/UpdateSegmentInput' produces: - application/json responses: "200": description: OK schema: - $ref: '#/definitions/Product' - summary: Update a Product + $ref: '#/definitions/Segment' + summary: Update a Segment tags: - - Products + - Segments swagger: "2.0" diff --git a/components/ledger/internal/adapters/http/in/routes.go b/components/ledger/internal/adapters/http/in/routes.go index b527c18b0..a7b96b914 100644 --- a/components/ledger/internal/adapters/http/in/routes.go +++ b/components/ledger/internal/adapters/http/in/routes.go @@ -14,7 +14,7 @@ import ( ) // NewRouter registerNewRouters routes to the Server. -func NewRouter(lg mlog.Logger, tl *mopentelemetry.Telemetry, cc *mcasdoor.CasdoorConnection, ah *AccountHandler, ph *PortfolioHandler, lh *LedgerHandler, ih *AssetHandler, oh *OrganizationHandler, rh *ProductHandler) *fiber.App { +func NewRouter(lg mlog.Logger, tl *mopentelemetry.Telemetry, cc *mcasdoor.CasdoorConnection, ah *AccountHandler, ph *PortfolioHandler, lh *LedgerHandler, ih *AssetHandler, oh *OrganizationHandler, sh *SegmentHandler) *fiber.App { f := fiber.New(fiber.Config{ DisableStartupMessage: true, }) @@ -53,12 +53,12 @@ func NewRouter(lg mlog.Logger, tl *mopentelemetry.Telemetry, cc *mcasdoor.Casdoo f.Get("/v1/organizations/:organization_id/ledgers/:ledger_id/portfolios/:id", jwt.ProtectHTTP(), jwt.WithPermissionHTTP("portfolio"), http.ParseUUIDPathParameters, ph.GetPortfolioByID) f.Delete("/v1/organizations/:organization_id/ledgers/:ledger_id/portfolios/:id", jwt.ProtectHTTP(), jwt.WithPermissionHTTP("portfolio"), http.ParseUUIDPathParameters, ph.DeletePortfolioByID) - // Product - f.Post("/v1/organizations/:organization_id/ledgers/:ledger_id/products", jwt.ProtectHTTP(), jwt.WithPermissionHTTP("product"), http.ParseUUIDPathParameters, http.WithBody(new(mmodel.CreateProductInput), rh.CreateProduct)) - f.Patch("/v1/organizations/:organization_id/ledgers/:ledger_id/products/:id", jwt.ProtectHTTP(), jwt.WithPermissionHTTP("product"), http.ParseUUIDPathParameters, http.WithBody(new(mmodel.UpdateProductInput), rh.UpdateProduct)) - f.Get("/v1/organizations/:organization_id/ledgers/:ledger_id/products", jwt.ProtectHTTP(), jwt.WithPermissionHTTP("product"), http.ParseUUIDPathParameters, rh.GetAllProducts) - f.Get("/v1/organizations/:organization_id/ledgers/:ledger_id/products/:id", jwt.ProtectHTTP(), jwt.WithPermissionHTTP("product"), http.ParseUUIDPathParameters, rh.GetProductByID) - f.Delete("/v1/organizations/:organization_id/ledgers/:ledger_id/products/:id", jwt.ProtectHTTP(), jwt.WithPermissionHTTP("product"), http.ParseUUIDPathParameters, rh.DeleteProductByID) + // Segment + f.Post("/v1/organizations/:organization_id/ledgers/:ledger_id/segments", jwt.ProtectHTTP(), jwt.WithPermissionHTTP("segment"), http.ParseUUIDPathParameters, http.WithBody(new(mmodel.CreateSegmentInput), sh.CreateSegment)) + f.Patch("/v1/organizations/:organization_id/ledgers/:ledger_id/segments/:id", jwt.ProtectHTTP(), jwt.WithPermissionHTTP("segment"), http.ParseUUIDPathParameters, http.WithBody(new(mmodel.UpdateSegmentInput), sh.UpdateSegment)) + f.Get("/v1/organizations/:organization_id/ledgers/:ledger_id/segments", jwt.ProtectHTTP(), jwt.WithPermissionHTTP("segment"), http.ParseUUIDPathParameters, sh.GetAllSegments) + f.Get("/v1/organizations/:organization_id/ledgers/:ledger_id/segments/:id", jwt.ProtectHTTP(), jwt.WithPermissionHTTP("segment"), http.ParseUUIDPathParameters, sh.GetSegmentByID) + f.Delete("/v1/organizations/:organization_id/ledgers/:ledger_id/segments/:id", jwt.ProtectHTTP(), jwt.WithPermissionHTTP("segment"), http.ParseUUIDPathParameters, sh.DeleteSegmentByID) // Accounts f.Post("/v1/organizations/:organization_id/ledgers/:ledger_id/accounts", jwt.ProtectHTTP(), jwt.WithPermissionHTTP("account"), http.ParseUUIDPathParameters, http.WithBody(new(mmodel.CreateAccountInput), ah.CreateAccount)) diff --git a/components/ledger/internal/adapters/http/in/product.go b/components/ledger/internal/adapters/http/in/segment.go similarity index 56% rename from components/ledger/internal/adapters/http/in/product.go rename to components/ledger/internal/adapters/http/in/segment.go index 01aa9f1cf..751dde6db 100644 --- a/components/ledger/internal/adapters/http/in/product.go +++ b/components/ledger/internal/adapters/http/in/segment.go @@ -15,41 +15,41 @@ import ( "github.com/google/uuid" ) -// ProductHandler struct contains a product use case for managing product related operations. -type ProductHandler struct { +// SegmentHandler struct contains a segment use case for managing segment related operations. +type SegmentHandler struct { Command *command.UseCase Query *query.UseCase } -// CreateProduct is a method that creates product information. +// CreateSegment is a method that creates segment information. // -// @Summary Create a Product -// @Description Create a Product with the input payload -// @Tags Products +// @Summary Create a Segment +// @Description Create a Segment with the input payload +// @Tags Segments // @Accept json // @Produce json // @Param Authorization header string true "Authorization Bearer Token" // @Param Midaz-Id header string false "Request ID" // @Param organization_id path string true "Organization ID" // @Param ledger_id path string true "Ledger ID" -// @Param product body mmodel.CreateProductInput true "Product" -// @Success 200 {object} mmodel.Product -// @Router /v1/organizations/{organization_id}/ledgers/{ledger_id}/products [post] -func (handler *ProductHandler) CreateProduct(i any, c *fiber.Ctx) error { +// @Param segment body mmodel.CreateSegmentInput true "Segment" +// @Success 200 {object} mmodel.Segment +// @Router /v1/organizations/{organization_id}/ledgers/{ledger_id}/segments [post] +func (handler *SegmentHandler) CreateSegment(i any, c *fiber.Ctx) error { ctx := c.UserContext() logger := pkg.NewLoggerFromContext(ctx) tracer := pkg.NewTracerFromContext(ctx) - ctx, span := tracer.Start(ctx, "handler.create_product") + ctx, span := tracer.Start(ctx, "handler.create_segment") defer span.End() organizationID := c.Locals("organization_id").(uuid.UUID) ledgerID := c.Locals("ledger_id").(uuid.UUID) - logger.Infof("Initiating create of Product with organization ID: %s and ledger ID: %s", organizationID.String(), ledgerID.String()) + logger.Infof("Initiating create of Segment with organization ID: %s and ledger ID: %s", organizationID.String(), ledgerID.String()) - payload := i.(*mmodel.CreateProductInput) - logger.Infof("Request to create a Product with details: %#v", payload) + payload := i.(*mmodel.CreateSegmentInput) + logger.Infof("Request to create a Segment with details: %#v", payload) err := mopentelemetry.SetSpanAttributesFromStruct(&span, "payload", payload) if err != nil { @@ -58,23 +58,23 @@ func (handler *ProductHandler) CreateProduct(i any, c *fiber.Ctx) error { return http.WithError(c, err) } - product, err := handler.Command.CreateProduct(ctx, organizationID, ledgerID, payload) + segment, err := handler.Command.CreateSegment(ctx, organizationID, ledgerID, payload) if err != nil { - mopentelemetry.HandleSpanError(&span, "Failed to create Product on command", err) + mopentelemetry.HandleSpanError(&span, "Failed to create Segment on command", err) return http.WithError(c, err) } - logger.Infof("Successfully created Product") + logger.Infof("Successfully created Segment") - return http.Created(c, product) + return http.Created(c, segment) } -// GetAllProducts is a method that retrieves all Products. +// GetAllSegments is a method that retrieves all Segments. // -// @Summary Get all Products -// @Description Get all Products with the input metadata or without metadata -// @Tags Products +// @Summary Get all Segments +// @Description Get all Segments with the input metadata or without metadata +// @Tags Segments // @Produce json // @Param Authorization header string true "Authorization Bearer Token" // @Param Midaz-Id header string false "Request ID" @@ -86,20 +86,20 @@ func (handler *ProductHandler) CreateProduct(i any, c *fiber.Ctx) error { // @Param start_date query string false "Start Date" example "2021-01-01" // @Param end_date query string false "End Date" example "2021-01-01" // @Param sort_order query string false "Sort Order" Enums(asc,desc) -// @Success 200 {object} mpostgres.Pagination{items=[]mmodel.Product,page=int,limit=int} -// @Router /v1/organizations/{organization_id}/ledgers/{ledger_id}/products [get] -func (handler *ProductHandler) GetAllProducts(c *fiber.Ctx) error { +// @Success 200 {object} mpostgres.Pagination{items=[]mmodel.Segment,page=int,limit=int} +// @Router /v1/organizations/{organization_id}/ledgers/{ledger_id}/segments [get] +func (handler *SegmentHandler) GetAllSegments(c *fiber.Ctx) error { ctx := c.UserContext() logger := pkg.NewLoggerFromContext(ctx) tracer := pkg.NewTracerFromContext(ctx) - ctx, span := tracer.Start(ctx, "handler.get_all_products") + ctx, span := tracer.Start(ctx, "handler.get_all_segments") defer span.End() organizationID := c.Locals("organization_id").(uuid.UUID) ledgerID := c.Locals("ledger_id").(uuid.UUID) - logger.Infof("Get Products with organization ID: %s and ledger ID: %s", organizationID.String(), ledgerID.String()) + logger.Infof("Get Segments with organization ID: %s and ledger ID: %s", organizationID.String(), ledgerID.String()) headerParams, err := http.ValidateParameters(c.Queries()) if err != nil { @@ -119,116 +119,116 @@ func (handler *ProductHandler) GetAllProducts(c *fiber.Ctx) error { } if headerParams.Metadata != nil { - logger.Infof("Initiating retrieval of all Products by metadata") + logger.Infof("Initiating retrieval of all Segments by metadata") - products, err := handler.Query.GetAllMetadataProducts(ctx, organizationID, ledgerID, *headerParams) + segments, err := handler.Query.GetAllMetadataSegments(ctx, organizationID, ledgerID, *headerParams) if err != nil { - mopentelemetry.HandleSpanError(&span, "Failed to retrieve all Products on query", err) + mopentelemetry.HandleSpanError(&span, "Failed to retrieve all Segments on query", err) - logger.Errorf("Failed to retrieve all Products, Error: %s", err.Error()) + logger.Errorf("Failed to retrieve all Segments, Error: %s", err.Error()) return http.WithError(c, err) } - logger.Infof("Successfully retrieved all Products by metadata") + logger.Infof("Successfully retrieved all Segments by metadata") - pagination.SetItems(products) + pagination.SetItems(segments) return http.OK(c, pagination) } - logger.Infof("Initiating retrieval of all Products ") + logger.Infof("Initiating retrieval of all Segments ") headerParams.Metadata = &bson.M{} - products, err := handler.Query.GetAllProducts(ctx, organizationID, ledgerID, *headerParams) + segments, err := handler.Query.GetAllSegments(ctx, organizationID, ledgerID, *headerParams) if err != nil { - mopentelemetry.HandleSpanError(&span, "Failed to retrieve all Products on query", err) + mopentelemetry.HandleSpanError(&span, "Failed to retrieve all Segments on query", err) - logger.Errorf("Failed to retrieve all Products, Error: %s", err.Error()) + logger.Errorf("Failed to retrieve all Segments, Error: %s", err.Error()) return http.WithError(c, err) } - logger.Infof("Successfully retrieved all Products") + logger.Infof("Successfully retrieved all Segments") - pagination.SetItems(products) + pagination.SetItems(segments) return http.OK(c, pagination) } -// GetProductByID is a method that retrieves Product information by a given id. +// GetSegmentByID is a method that retrieves Segment information by a given id. // -// @Summary Get a Product by ID -// @Description Get a Product with the input ID -// @Tags Products +// @Summary Get a Segment by ID +// @Description Get a Segment with the input ID +// @Tags Segments // @Produce json // @Param Authorization header string true "Authorization Bearer Token" // @Param Midaz-Id header string false "Request ID" // @Param organization_id path string true "Organization ID" // @Param ledger_id path string true "Ledger ID" -// @Param id path string true "Product ID" -// @Success 200 {object} mmodel.Product -// @Router /v1/organizations/{organization_id}/ledgers/{ledger_id}/products/{id} [get] -func (handler *ProductHandler) GetProductByID(c *fiber.Ctx) error { +// @Param id path string true "Segment ID" +// @Success 200 {object} mmodel.Segment +// @Router /v1/organizations/{organization_id}/ledgers/{ledger_id}/segments/{id} [get] +func (handler *SegmentHandler) GetSegmentByID(c *fiber.Ctx) error { ctx := c.UserContext() logger := pkg.NewLoggerFromContext(ctx) tracer := pkg.NewTracerFromContext(ctx) - ctx, span := tracer.Start(ctx, "handler.get_product_by_id") + ctx, span := tracer.Start(ctx, "handler.get_segment_by_id") defer span.End() organizationID := c.Locals("organization_id").(uuid.UUID) ledgerID := c.Locals("ledger_id").(uuid.UUID) id := c.Locals("id").(uuid.UUID) - logger.Infof("Initiating retrieval of Product with Organization ID: %s and Ledger ID: %s and Product ID: %s", organizationID.String(), ledgerID.String(), id.String()) + logger.Infof("Initiating retrieval of Segment with Organization ID: %s and Ledger ID: %s and Segment ID: %s", organizationID.String(), ledgerID.String(), id.String()) - product, err := handler.Query.GetProductByID(ctx, organizationID, ledgerID, id) + segment, err := handler.Query.GetSegmentByID(ctx, organizationID, ledgerID, id) if err != nil { - mopentelemetry.HandleSpanError(&span, "Failed to retrieve Product on query", err) + mopentelemetry.HandleSpanError(&span, "Failed to retrieve Segment on query", err) - logger.Errorf("Failed to retrieve Product with Ledger ID: %s and Product ID: %s, Error: %s", ledgerID.String(), id.String(), err.Error()) + logger.Errorf("Failed to retrieve Segment with Ledger ID: %s and Segment ID: %s, Error: %s", ledgerID.String(), id.String(), err.Error()) return http.WithError(c, err) } - logger.Infof("Successfully retrieved Product with Organization ID: %s and Ledger ID: %s and Product ID: %s", organizationID.String(), ledgerID.String(), id.String()) + logger.Infof("Successfully retrieved Segment with Organization ID: %s and Ledger ID: %s and Segment ID: %s", organizationID.String(), ledgerID.String(), id.String()) - return http.OK(c, product) + return http.OK(c, segment) } -// UpdateProduct is a method that updates Product information. +// UpdateSegment is a method that updates Segment information. // -// @Summary Update a Product -// @Description Update a Product with the input payload -// @Tags Products +// @Summary Update a Segment +// @Description Update a Segment with the input payload +// @Tags Segments // @Accept json // @Produce json // @Param Authorization header string true "Authorization Bearer Token" // @Param Midaz-Id header string false "Request ID" // @Param organization_id path string true "Organization ID" // @Param ledger_id path string true "Ledger ID" -// @Param id path string true "Product ID" -// @Param product body mmodel.UpdateProductInput true "Product" -// @Success 200 {object} mmodel.Product -// @Router /v1/organizations/{organization_id}/ledgers/{ledger_id}/products/{id} [patch] -func (handler *ProductHandler) UpdateProduct(i any, c *fiber.Ctx) error { +// @Param id path string true "Segment ID" +// @Param segment body mmodel.UpdateSegmentInput true "Segment" +// @Success 200 {object} mmodel.Segment +// @Router /v1/organizations/{organization_id}/ledgers/{ledger_id}/segments/{id} [patch] +func (handler *SegmentHandler) UpdateSegment(i any, c *fiber.Ctx) error { ctx := c.UserContext() logger := pkg.NewLoggerFromContext(ctx) tracer := pkg.NewTracerFromContext(ctx) - ctx, span := tracer.Start(ctx, "handler.update_product") + ctx, span := tracer.Start(ctx, "handler.update_segment") defer span.End() organizationID := c.Locals("organization_id").(uuid.UUID) ledgerID := c.Locals("ledger_id").(uuid.UUID) id := c.Locals("id").(uuid.UUID) - logger.Infof("Initiating update of Product with Organization ID: %s and Ledger ID: %s and Product ID: %s", organizationID.String(), ledgerID.String(), id.String()) + logger.Infof("Initiating update of Segment with Organization ID: %s and Ledger ID: %s and Segment ID: %s", organizationID.String(), ledgerID.String(), id.String()) - payload := i.(*mmodel.UpdateProductInput) - logger.Infof("Request to update an Product with details: %#v", payload) + payload := i.(*mmodel.UpdateSegmentInput) + logger.Infof("Request to update an Segment with details: %#v", payload) err := mopentelemetry.SetSpanAttributesFromStruct(&span, "payload", payload) if err != nil { @@ -237,65 +237,65 @@ func (handler *ProductHandler) UpdateProduct(i any, c *fiber.Ctx) error { return http.WithError(c, err) } - _, err = handler.Command.UpdateProductByID(ctx, organizationID, ledgerID, id, payload) + _, err = handler.Command.UpdateSegmentByID(ctx, organizationID, ledgerID, id, payload) if err != nil { - mopentelemetry.HandleSpanError(&span, "Failed to update Product on command", err) + mopentelemetry.HandleSpanError(&span, "Failed to update Segment on command", err) - logger.Errorf("Failed to update Product with ID: %s, Error: %s", id.String(), err.Error()) + logger.Errorf("Failed to update Segment with ID: %s, Error: %s", id.String(), err.Error()) return http.WithError(c, err) } - product, err := handler.Query.GetProductByID(ctx, organizationID, ledgerID, id) + segment, err := handler.Query.GetSegmentByID(ctx, organizationID, ledgerID, id) if err != nil { - mopentelemetry.HandleSpanError(&span, "Failed to retrieve Product on query", err) + mopentelemetry.HandleSpanError(&span, "Failed to retrieve Segment on query", err) - logger.Errorf("Failed to retrieve Product with Ledger ID: %s and Product ID: %s, Error: %s", ledgerID.String(), id.String(), err.Error()) + logger.Errorf("Failed to retrieve Segment with Ledger ID: %s and Segment ID: %s, Error: %s", ledgerID.String(), id.String(), err.Error()) return http.WithError(c, err) } - logger.Infof("Successfully updated Product with Organization ID: %s and Ledger ID: %s and Product ID: %s", organizationID.String(), ledgerID.String(), id.String()) + logger.Infof("Successfully updated Segment with Organization ID: %s and Ledger ID: %s and Segment ID: %s", organizationID.String(), ledgerID.String(), id.String()) - return http.OK(c, product) + return http.OK(c, segment) } -// DeleteProductByID is a method that removes Product information by a given ids. +// DeleteSegmentByID is a method that removes Segment information by a given ids. // -// @Summary Delete a Product by ID -// @Description Delete a Product with the input ID -// @Tags Products +// @Summary Delete a Segment by ID +// @Description Delete a Segment with the input ID +// @Tags Segments // @Param Authorization header string true "Authorization Bearer Token" // @Param Midaz-Id header string false "Request ID" // @Param organization_id path string true "Organization ID" // @Param ledger_id path string true "Ledger ID" -// @Param id path string true "Product ID" +// @Param id path string true "Segment ID" // @Success 204 -// @Router /v1/organizations/{organization_id}/ledgers/{ledger_id}/products/{id} [delete] -func (handler *ProductHandler) DeleteProductByID(c *fiber.Ctx) error { +// @Router /v1/organizations/{organization_id}/ledgers/{ledger_id}/segments/{id} [delete] +func (handler *SegmentHandler) DeleteSegmentByID(c *fiber.Ctx) error { ctx := c.UserContext() logger := pkg.NewLoggerFromContext(ctx) tracer := pkg.NewTracerFromContext(ctx) - ctx, span := tracer.Start(ctx, "handler.delete_product_by_id") + ctx, span := tracer.Start(ctx, "handler.delete_segment_by_id") defer span.End() organizationID := c.Locals("organization_id").(uuid.UUID) ledgerID := c.Locals("ledger_id").(uuid.UUID) id := c.Locals("id").(uuid.UUID) - logger.Infof("Initiating removal of Product with Organization ID: %s and Ledger ID: %s and Product ID: %s", organizationID.String(), ledgerID.String(), id.String()) + logger.Infof("Initiating removal of Segment with Organization ID: %s and Ledger ID: %s and Segment ID: %s", organizationID.String(), ledgerID.String(), id.String()) - if err := handler.Command.DeleteProductByID(ctx, organizationID, ledgerID, id); err != nil { - mopentelemetry.HandleSpanError(&span, "Failed to remove Product on command", err) + if err := handler.Command.DeleteSegmentByID(ctx, organizationID, ledgerID, id); err != nil { + mopentelemetry.HandleSpanError(&span, "Failed to remove Segment on command", err) - logger.Errorf("Failed to remove Product with Ledger ID: %s and Product ID: %s, Error: %s", ledgerID.String(), id.String(), err.Error()) + logger.Errorf("Failed to remove Segment with Ledger ID: %s and Segment ID: %s, Error: %s", ledgerID.String(), id.String(), err.Error()) return http.WithError(c, err) } - logger.Infof("Successfully removed Product with Organization ID: %s and Ledger ID: %s and Product ID: %s", organizationID.String(), ledgerID.String(), id.String()) + logger.Infof("Successfully removed Segment with Organization ID: %s and Ledger ID: %s and Segment ID: %s", organizationID.String(), ledgerID.String(), id.String()) return http.NoContent(c) } diff --git a/components/ledger/internal/adapters/postgres/account/account.go b/components/ledger/internal/adapters/postgres/account/account.go index a23920a55..affdf2573 100644 --- a/components/ledger/internal/adapters/postgres/account/account.go +++ b/components/ledger/internal/adapters/postgres/account/account.go @@ -18,7 +18,7 @@ type AccountPostgreSQLModel struct { OrganizationID string LedgerID string PortfolioID *string - ProductID *string + SegmentID *string AvailableBalance *float64 OnHoldBalance *float64 BalanceScale *float64 @@ -57,7 +57,7 @@ func (t *AccountPostgreSQLModel) ToEntity() *mmodel.Account { OrganizationID: t.OrganizationID, LedgerID: t.LedgerID, PortfolioID: t.PortfolioID, - ProductID: t.ProductID, + SegmentID: t.SegmentID, Balance: balance, Status: status, AllowSending: &t.AllowSending, @@ -88,7 +88,7 @@ func (t *AccountPostgreSQLModel) FromEntity(account *mmodel.Account) { AssetCode: account.AssetCode, OrganizationID: account.OrganizationID, LedgerID: account.LedgerID, - ProductID: account.ProductID, + SegmentID: account.SegmentID, AvailableBalance: account.Balance.Available, OnHoldBalance: account.Balance.OnHold, BalanceScale: account.Balance.Scale, diff --git a/components/ledger/internal/adapters/postgres/account/account.postgresql.go b/components/ledger/internal/adapters/postgres/account/account.postgresql.go index 54d1894be..eca491467 100644 --- a/components/ledger/internal/adapters/postgres/account/account.postgresql.go +++ b/components/ledger/internal/adapters/postgres/account/account.postgresql.go @@ -108,7 +108,7 @@ func (r *AccountPostgreSQLRepository) Create(ctx context.Context, acc *mmodel.Ac record.OrganizationID, record.LedgerID, record.PortfolioID, - record.ProductID, + record.SegmentID, record.AvailableBalance, record.OnHoldBalance, record.BalanceScale, @@ -217,7 +217,7 @@ func (r *AccountPostgreSQLRepository) FindAll(ctx context.Context, organizationI &acc.OrganizationID, &acc.LedgerID, &acc.PortfolioID, - &acc.ProductID, + &acc.SegmentID, &acc.AvailableBalance, &acc.OnHoldBalance, &acc.BalanceScale, @@ -291,7 +291,7 @@ func (r *AccountPostgreSQLRepository) Find(ctx context.Context, organizationID, &acc.OrganizationID, &acc.LedgerID, &acc.PortfolioID, - &acc.ProductID, + &acc.SegmentID, &acc.AvailableBalance, &acc.OnHoldBalance, &acc.BalanceScale, @@ -360,7 +360,7 @@ func (r *AccountPostgreSQLRepository) FindWithDeleted(ctx context.Context, organ &acc.OrganizationID, &acc.LedgerID, &acc.PortfolioID, - &acc.ProductID, + &acc.SegmentID, &acc.AvailableBalance, &acc.OnHoldBalance, &acc.BalanceScale, @@ -429,7 +429,7 @@ func (r *AccountPostgreSQLRepository) FindAlias(ctx context.Context, organizatio &acc.OrganizationID, &acc.LedgerID, &acc.PortfolioID, - &acc.ProductID, + &acc.SegmentID, &acc.AvailableBalance, &acc.OnHoldBalance, &acc.BalanceScale, @@ -544,7 +544,7 @@ func (r *AccountPostgreSQLRepository) ListByIDs(ctx context.Context, organizatio &acc.OrganizationID, &acc.LedgerID, &acc.PortfolioID, - &acc.ProductID, + &acc.SegmentID, &acc.AvailableBalance, &acc.OnHoldBalance, &acc.BalanceScale, @@ -616,7 +616,7 @@ func (r *AccountPostgreSQLRepository) ListByAlias(ctx context.Context, organizat &acc.OrganizationID, &acc.LedgerID, &acc.PortfolioID, - &acc.ProductID, + &acc.SegmentID, &acc.AvailableBalance, &acc.OnHoldBalance, &acc.BalanceScale, @@ -697,9 +697,9 @@ func (r *AccountPostgreSQLRepository) Update(ctx context.Context, organizationID args = append(args, record.Alias) } - if !pkg.IsNilOrEmpty(acc.ProductID) { - updates = append(updates, "product_id = $"+strconv.Itoa(len(args)+1)) - args = append(args, record.ProductID) + if !pkg.IsNilOrEmpty(acc.SegmentID) { + updates = append(updates, "segment_id = $"+strconv.Itoa(len(args)+1)) + args = append(args, record.SegmentID) } if !pkg.IsNilOrEmpty(acc.PortfolioID) { @@ -840,7 +840,7 @@ func (r *AccountPostgreSQLRepository) ListAccountsByIDs(ctx context.Context, org &acc.OrganizationID, &acc.LedgerID, &acc.PortfolioID, - &acc.ProductID, + &acc.SegmentID, &acc.AvailableBalance, &acc.OnHoldBalance, &acc.BalanceScale, @@ -911,7 +911,7 @@ func (r *AccountPostgreSQLRepository) ListAccountsByAlias(ctx context.Context, o &acc.OrganizationID, &acc.LedgerID, &acc.PortfolioID, - &acc.ProductID, + &acc.SegmentID, &acc.AvailableBalance, &acc.OnHoldBalance, &acc.BalanceScale, diff --git a/components/ledger/internal/adapters/postgres/product/product.mock.go b/components/ledger/internal/adapters/postgres/product/product.mock.go deleted file mode 100644 index 2a5b1da8a..000000000 --- a/components/ledger/internal/adapters/postgres/product/product.mock.go +++ /dev/null @@ -1,148 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/product (interfaces: Repository) -// -// Generated by this command: -// -// mockgen --destination=product.mock.go --package=product . Repository -// - -// Package product is a generated GoMock package. -package product - -import ( - context "context" - reflect "reflect" - - mmodel "github.com/LerianStudio/midaz/pkg/mmodel" - http "github.com/LerianStudio/midaz/pkg/net/http" - uuid "github.com/google/uuid" - gomock "go.uber.org/mock/gomock" -) - -// MockRepository is a mock of Repository interface. -type MockRepository struct { - ctrl *gomock.Controller - recorder *MockRepositoryMockRecorder - isgomock struct{} -} - -// MockRepositoryMockRecorder is the mock recorder for MockRepository. -type MockRepositoryMockRecorder struct { - mock *MockRepository -} - -// NewMockRepository creates a new mock instance. -func NewMockRepository(ctrl *gomock.Controller) *MockRepository { - mock := &MockRepository{ctrl: ctrl} - mock.recorder = &MockRepositoryMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockRepository) EXPECT() *MockRepositoryMockRecorder { - return m.recorder -} - -// Create mocks base method. -func (m *MockRepository) Create(ctx context.Context, product *mmodel.Product) (*mmodel.Product, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Create", ctx, product) - ret0, _ := ret[0].(*mmodel.Product) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Create indicates an expected call of Create. -func (mr *MockRepositoryMockRecorder) Create(ctx, product any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Create", reflect.TypeOf((*MockRepository)(nil).Create), ctx, product) -} - -// Delete mocks base method. -func (m *MockRepository) Delete(ctx context.Context, organizationID, ledgerID, id uuid.UUID) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Delete", ctx, organizationID, ledgerID, id) - ret0, _ := ret[0].(error) - return ret0 -} - -// Delete indicates an expected call of Delete. -func (mr *MockRepositoryMockRecorder) Delete(ctx, organizationID, ledgerID, id any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delete", reflect.TypeOf((*MockRepository)(nil).Delete), ctx, organizationID, ledgerID, id) -} - -// Find mocks base method. -func (m *MockRepository) Find(ctx context.Context, organizationID, ledgerID, id uuid.UUID) (*mmodel.Product, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Find", ctx, organizationID, ledgerID, id) - ret0, _ := ret[0].(*mmodel.Product) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Find indicates an expected call of Find. -func (mr *MockRepositoryMockRecorder) Find(ctx, organizationID, ledgerID, id any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Find", reflect.TypeOf((*MockRepository)(nil).Find), ctx, organizationID, ledgerID, id) -} - -// FindAll mocks base method. -func (m *MockRepository) FindAll(ctx context.Context, organizationID, ledgerID uuid.UUID, filter http.Pagination) ([]*mmodel.Product, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "FindAll", ctx, organizationID, ledgerID, filter) - ret0, _ := ret[0].([]*mmodel.Product) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// FindAll indicates an expected call of FindAll. -func (mr *MockRepositoryMockRecorder) FindAll(ctx, organizationID, ledgerID, filter any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindAll", reflect.TypeOf((*MockRepository)(nil).FindAll), ctx, organizationID, ledgerID, filter) -} - -// FindByIDs mocks base method. -func (m *MockRepository) FindByIDs(ctx context.Context, organizationID, ledgerID uuid.UUID, ids []uuid.UUID) ([]*mmodel.Product, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "FindByIDs", ctx, organizationID, ledgerID, ids) - ret0, _ := ret[0].([]*mmodel.Product) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// FindByIDs indicates an expected call of FindByIDs. -func (mr *MockRepositoryMockRecorder) FindByIDs(ctx, organizationID, ledgerID, ids any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindByIDs", reflect.TypeOf((*MockRepository)(nil).FindByIDs), ctx, organizationID, ledgerID, ids) -} - -// FindByName mocks base method. -func (m *MockRepository) FindByName(ctx context.Context, organizationID, ledgerID uuid.UUID, name string) (bool, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "FindByName", ctx, organizationID, ledgerID, name) - ret0, _ := ret[0].(bool) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// FindByName indicates an expected call of FindByName. -func (mr *MockRepositoryMockRecorder) FindByName(ctx, organizationID, ledgerID, name any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindByName", reflect.TypeOf((*MockRepository)(nil).FindByName), ctx, organizationID, ledgerID, name) -} - -// Update mocks base method. -func (m *MockRepository) Update(ctx context.Context, organizationID, ledgerID, id uuid.UUID, product *mmodel.Product) (*mmodel.Product, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Update", ctx, organizationID, ledgerID, id, product) - ret0, _ := ret[0].(*mmodel.Product) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Update indicates an expected call of Update. -func (mr *MockRepositoryMockRecorder) Update(ctx, organizationID, ledgerID, id, product any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockRepository)(nil).Update), ctx, organizationID, ledgerID, id, product) -} diff --git a/components/ledger/internal/adapters/postgres/product/product.go b/components/ledger/internal/adapters/postgres/segment/segment.go similarity index 52% rename from components/ledger/internal/adapters/postgres/product/product.go rename to components/ledger/internal/adapters/postgres/segment/segment.go index 4dd778f9c..ad1a7a462 100644 --- a/components/ledger/internal/adapters/postgres/product/product.go +++ b/components/ledger/internal/adapters/postgres/segment/segment.go @@ -1,4 +1,4 @@ -package product +package segment import ( "database/sql" @@ -8,8 +8,8 @@ import ( "github.com/LerianStudio/midaz/pkg/mmodel" ) -// ProductPostgreSQLModel represents the entity Product into SQL context in Database -type ProductPostgreSQLModel struct { +// SegmentPostgreSQLModel represents the entity Segment into SQL context in Database +type SegmentPostgreSQLModel struct { ID string Name string LedgerID string @@ -22,14 +22,14 @@ type ProductPostgreSQLModel struct { Metadata map[string]any } -// ToEntity converts an ProductPostgreSQLModel to entity.Product -func (t *ProductPostgreSQLModel) ToEntity() *mmodel.Product { +// ToEntity converts an SegmentPostgreSQLModel to entity.Segment +func (t *SegmentPostgreSQLModel) ToEntity() *mmodel.Segment { status := mmodel.Status{ Code: t.Status, Description: t.StatusDescription, } - product := &mmodel.Product{ + segment := &mmodel.Segment{ ID: t.ID, Name: t.Name, LedgerID: t.LedgerID, @@ -42,27 +42,27 @@ func (t *ProductPostgreSQLModel) ToEntity() *mmodel.Product { if !t.DeletedAt.Time.IsZero() { deletedAtCopy := t.DeletedAt.Time - product.DeletedAt = &deletedAtCopy + segment.DeletedAt = &deletedAtCopy } - return product + return segment } -// FromEntity converts an entity.Product to ProductPostgreSQLModel -func (t *ProductPostgreSQLModel) FromEntity(product *mmodel.Product) { - *t = ProductPostgreSQLModel{ +// FromEntity converts an entity.Segment to SegmentPostgreSQLModel +func (t *SegmentPostgreSQLModel) FromEntity(segment *mmodel.Segment) { + *t = SegmentPostgreSQLModel{ ID: pkg.GenerateUUIDv7().String(), - Name: product.Name, - LedgerID: product.LedgerID, - OrganizationID: product.OrganizationID, - Status: product.Status.Code, - StatusDescription: product.Status.Description, - CreatedAt: product.CreatedAt, - UpdatedAt: product.UpdatedAt, + Name: segment.Name, + LedgerID: segment.LedgerID, + OrganizationID: segment.OrganizationID, + Status: segment.Status.Code, + StatusDescription: segment.Status.Description, + CreatedAt: segment.CreatedAt, + UpdatedAt: segment.UpdatedAt, } - if product.DeletedAt != nil { - deletedAtCopy := *product.DeletedAt + if segment.DeletedAt != nil { + deletedAtCopy := *segment.DeletedAt t.DeletedAt = sql.NullTime{Time: deletedAtCopy, Valid: true} } } diff --git a/components/ledger/internal/adapters/postgres/segment/segment.mock.go b/components/ledger/internal/adapters/postgres/segment/segment.mock.go new file mode 100644 index 000000000..5e6dce4f6 --- /dev/null +++ b/components/ledger/internal/adapters/postgres/segment/segment.mock.go @@ -0,0 +1,147 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/segment (interfaces: Repository) +// +// Generated by this command: +// +// mockgen --destination=segment.mock.go --package=segment . Repository +// + +// Package segment is a generated GoMock package. +package segment + +import ( + context "context" + reflect "reflect" + + mmodel "github.com/LerianStudio/midaz/pkg/mmodel" + http "github.com/LerianStudio/midaz/pkg/net/http" + uuid "github.com/google/uuid" + gomock "go.uber.org/mock/gomock" +) + +// MockRepository is a mock of Repository interface. +type MockRepository struct { + ctrl *gomock.Controller + recorder *MockRepositoryMockRecorder +} + +// MockRepositoryMockRecorder is the mock recorder for MockRepository. +type MockRepositoryMockRecorder struct { + mock *MockRepository +} + +// NewMockRepository creates a new mock instance. +func NewMockRepository(ctrl *gomock.Controller) *MockRepository { + mock := &MockRepository{ctrl: ctrl} + mock.recorder = &MockRepositoryMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockRepository) EXPECT() *MockRepositoryMockRecorder { + return m.recorder +} + +// Create mocks base method. +func (m *MockRepository) Create(arg0 context.Context, arg1 *mmodel.Segment) (*mmodel.Segment, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Create", arg0, arg1) + ret0, _ := ret[0].(*mmodel.Segment) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Create indicates an expected call of Create. +func (mr *MockRepositoryMockRecorder) Create(arg0, arg1 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Create", reflect.TypeOf((*MockRepository)(nil).Create), arg0, arg1) +} + +// Delete mocks base method. +func (m *MockRepository) Delete(arg0 context.Context, arg1, arg2, arg3 uuid.UUID) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Delete", arg0, arg1, arg2, arg3) + ret0, _ := ret[0].(error) + return ret0 +} + +// Delete indicates an expected call of Delete. +func (mr *MockRepositoryMockRecorder) Delete(arg0, arg1, arg2, arg3 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delete", reflect.TypeOf((*MockRepository)(nil).Delete), arg0, arg1, arg2, arg3) +} + +// Find mocks base method. +func (m *MockRepository) Find(arg0 context.Context, arg1, arg2, arg3 uuid.UUID) (*mmodel.Segment, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Find", arg0, arg1, arg2, arg3) + ret0, _ := ret[0].(*mmodel.Segment) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Find indicates an expected call of Find. +func (mr *MockRepositoryMockRecorder) Find(arg0, arg1, arg2, arg3 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Find", reflect.TypeOf((*MockRepository)(nil).Find), arg0, arg1, arg2, arg3) +} + +// FindAll mocks base method. +func (m *MockRepository) FindAll(arg0 context.Context, arg1, arg2 uuid.UUID, arg3 http.Pagination) ([]*mmodel.Segment, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FindAll", arg0, arg1, arg2, arg3) + ret0, _ := ret[0].([]*mmodel.Segment) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FindAll indicates an expected call of FindAll. +func (mr *MockRepositoryMockRecorder) FindAll(arg0, arg1, arg2, arg3 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindAll", reflect.TypeOf((*MockRepository)(nil).FindAll), arg0, arg1, arg2, arg3) +} + +// FindByIDs mocks base method. +func (m *MockRepository) FindByIDs(arg0 context.Context, arg1, arg2 uuid.UUID, arg3 []uuid.UUID) ([]*mmodel.Segment, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FindByIDs", arg0, arg1, arg2, arg3) + ret0, _ := ret[0].([]*mmodel.Segment) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FindByIDs indicates an expected call of FindByIDs. +func (mr *MockRepositoryMockRecorder) FindByIDs(arg0, arg1, arg2, arg3 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindByIDs", reflect.TypeOf((*MockRepository)(nil).FindByIDs), arg0, arg1, arg2, arg3) +} + +// FindByName mocks base method. +func (m *MockRepository) FindByName(arg0 context.Context, arg1, arg2 uuid.UUID, arg3 string) (bool, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FindByName", arg0, arg1, arg2, arg3) + ret0, _ := ret[0].(bool) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FindByName indicates an expected call of FindByName. +func (mr *MockRepositoryMockRecorder) FindByName(arg0, arg1, arg2, arg3 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindByName", reflect.TypeOf((*MockRepository)(nil).FindByName), arg0, arg1, arg2, arg3) +} + +// Update mocks base method. +func (m *MockRepository) Update(arg0 context.Context, arg1, arg2, arg3 uuid.UUID, arg4 *mmodel.Segment) (*mmodel.Segment, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Update", arg0, arg1, arg2, arg3, arg4) + ret0, _ := ret[0].(*mmodel.Segment) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Update indicates an expected call of Update. +func (mr *MockRepositoryMockRecorder) Update(arg0, arg1, arg2, arg3, arg4 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockRepository)(nil).Update), arg0, arg1, arg2, arg3, arg4) +} diff --git a/components/ledger/internal/adapters/postgres/product/product.postgresql.go b/components/ledger/internal/adapters/postgres/segment/segment.postgresql.go similarity index 63% rename from components/ledger/internal/adapters/postgres/product/product.postgresql.go rename to components/ledger/internal/adapters/postgres/segment/segment.postgresql.go index 06e8b2c4d..c8a06a9cc 100644 --- a/components/ledger/internal/adapters/postgres/product/product.postgresql.go +++ b/components/ledger/internal/adapters/postgres/segment/segment.postgresql.go @@ -1,4 +1,4 @@ -package product +package segment import ( "context" @@ -24,30 +24,30 @@ import ( "github.com/lib/pq" ) -// Repository provides an interface for operations related to product entities. +// Repository provides an interface for operations related to segment entities. // -//go:generate mockgen --destination=product.mock.go --package=product . Repository +//go:generate mockgen --destination=segment.mock.go --package=segment . Repository type Repository interface { - Create(ctx context.Context, product *mmodel.Product) (*mmodel.Product, error) + Create(ctx context.Context, segment *mmodel.Segment) (*mmodel.Segment, error) FindByName(ctx context.Context, organizationID, ledgerID uuid.UUID, name string) (bool, error) - FindAll(ctx context.Context, organizationID, ledgerID uuid.UUID, filter http.Pagination) ([]*mmodel.Product, error) - FindByIDs(ctx context.Context, organizationID, ledgerID uuid.UUID, ids []uuid.UUID) ([]*mmodel.Product, error) - Find(ctx context.Context, organizationID, ledgerID, id uuid.UUID) (*mmodel.Product, error) - Update(ctx context.Context, organizationID, ledgerID, id uuid.UUID, product *mmodel.Product) (*mmodel.Product, error) + FindAll(ctx context.Context, organizationID, ledgerID uuid.UUID, filter http.Pagination) ([]*mmodel.Segment, error) + FindByIDs(ctx context.Context, organizationID, ledgerID uuid.UUID, ids []uuid.UUID) ([]*mmodel.Segment, error) + Find(ctx context.Context, organizationID, ledgerID, id uuid.UUID) (*mmodel.Segment, error) + Update(ctx context.Context, organizationID, ledgerID, id uuid.UUID, segment *mmodel.Segment) (*mmodel.Segment, error) Delete(ctx context.Context, organizationID, ledgerID, id uuid.UUID) error } -// ProductPostgreSQLRepository is a Postgresql-specific implementation of the Repository. -type ProductPostgreSQLRepository struct { +// SegmentPostgreSQLRepository is a Postgresql-specific implementation of the Repository. +type SegmentPostgreSQLRepository struct { connection *mpostgres.PostgresConnection tableName string } -// NewProductPostgreSQLRepository returns a new instance of ProductPostgreSQLRepository using the given Postgres connection. -func NewProductPostgreSQLRepository(pc *mpostgres.PostgresConnection) *ProductPostgreSQLRepository { - c := &ProductPostgreSQLRepository{ +// NewSegmentPostgreSQLRepository returns a new instance of SegmentPostgreSQLRepository using the given Postgres connection. +func NewSegmentPostgreSQLRepository(pc *mpostgres.PostgresConnection) *SegmentPostgreSQLRepository { + c := &SegmentPostgreSQLRepository{ connection: pc, - tableName: "product", + tableName: "segment", } _, err := c.connection.GetDB() @@ -58,11 +58,11 @@ func NewProductPostgreSQLRepository(pc *mpostgres.PostgresConnection) *ProductPo return c } -// Create a new product entity into Postgresql and returns it. -func (p *ProductPostgreSQLRepository) Create(ctx context.Context, product *mmodel.Product) (*mmodel.Product, error) { +// Create a new segment entity into Postgresql and returns it. +func (p *SegmentPostgreSQLRepository) Create(ctx context.Context, segment *mmodel.Segment) (*mmodel.Segment, error) { tracer := pkg.NewTracerFromContext(ctx) - ctx, span := tracer.Start(ctx, "postgres.create_product") + ctx, span := tracer.Start(ctx, "postgres.create_segment") defer span.End() db, err := p.connection.GetDB() @@ -72,19 +72,19 @@ func (p *ProductPostgreSQLRepository) Create(ctx context.Context, product *mmode return nil, err } - record := &ProductPostgreSQLModel{} - record.FromEntity(product) + record := &SegmentPostgreSQLModel{} + record.FromEntity(segment) ctx, spanExec := tracer.Start(ctx, "postgres.create.exec") - err = mopentelemetry.SetSpanAttributesFromStruct(&spanExec, "product_repository_input", record) + err = mopentelemetry.SetSpanAttributesFromStruct(&spanExec, "segment_repository_input", record) if err != nil { - mopentelemetry.HandleSpanError(&spanExec, "Failed to convert product record from entity to JSON string", err) + mopentelemetry.HandleSpanError(&spanExec, "Failed to convert segment record from entity to JSON string", err) return nil, err } - result, err := db.ExecContext(ctx, `INSERT INTO product VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING *`, + result, err := db.ExecContext(ctx, `INSERT INTO segment VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING *`, record.ID, record.Name, record.LedgerID, @@ -100,7 +100,7 @@ func (p *ProductPostgreSQLRepository) Create(ctx context.Context, product *mmode var pgErr *pgconn.PgError if errors.As(err, &pgErr) { - return nil, services.ValidatePGError(pgErr, reflect.TypeOf(mmodel.Product{}).Name()) + return nil, services.ValidatePGError(pgErr, reflect.TypeOf(mmodel.Segment{}).Name()) } return nil, err @@ -116,9 +116,9 @@ func (p *ProductPostgreSQLRepository) Create(ctx context.Context, product *mmode } if rowsAffected == 0 { - err := pkg.ValidateBusinessError(constant.ErrEntityNotFound, reflect.TypeOf(mmodel.Product{}).Name()) + err := pkg.ValidateBusinessError(constant.ErrEntityNotFound, reflect.TypeOf(mmodel.Segment{}).Name()) - mopentelemetry.HandleSpanError(&span, "Failed to create product. Rows affected is 0", err) + mopentelemetry.HandleSpanError(&span, "Failed to create segment. Rows affected is 0", err) return nil, err } @@ -126,11 +126,11 @@ func (p *ProductPostgreSQLRepository) Create(ctx context.Context, product *mmode return record.ToEntity(), nil } -// FindByName find product from the database using Organization and Ledger id and Name. -func (p *ProductPostgreSQLRepository) FindByName(ctx context.Context, organizationID, ledgerID uuid.UUID, name string) (bool, error) { +// FindByName find segment from the database using Organization and Ledger id and Name. +func (p *SegmentPostgreSQLRepository) FindByName(ctx context.Context, organizationID, ledgerID uuid.UUID, name string) (bool, error) { tracer := pkg.NewTracerFromContext(ctx) - ctx, span := tracer.Start(ctx, "postgres.find_product_by_name") + ctx, span := tracer.Start(ctx, "postgres.find_segment_by_name") defer span.End() db, err := p.connection.GetDB() @@ -140,9 +140,9 @@ func (p *ProductPostgreSQLRepository) FindByName(ctx context.Context, organizati return false, err } - ctx, spanQuery := tracer.Start(ctx, "postgres.find_product_by_name.query") + ctx, spanQuery := tracer.Start(ctx, "postgres.find_segment_by_name.query") - rows, err := db.QueryContext(ctx, "SELECT * FROM product WHERE organization_id = $1 AND ledger_id = $2 AND name LIKE $3 AND deleted_at IS NULL ORDER BY created_at DESC", + rows, err := db.QueryContext(ctx, "SELECT * FROM segment WHERE organization_id = $1 AND ledger_id = $2 AND name LIKE $3 AND deleted_at IS NULL ORDER BY created_at DESC", organizationID, ledgerID, name) if err != nil { mopentelemetry.HandleSpanError(&spanQuery, "Failed to execute query", err) @@ -154,9 +154,9 @@ func (p *ProductPostgreSQLRepository) FindByName(ctx context.Context, organizati spanQuery.End() if rows.Next() { - err := pkg.ValidateBusinessError(constant.ErrDuplicateProductName, reflect.TypeOf(mmodel.Product{}).Name(), name, ledgerID) + err := pkg.ValidateBusinessError(constant.ErrDuplicateSegmentName, reflect.TypeOf(mmodel.Segment{}).Name(), name, ledgerID) - mopentelemetry.HandleSpanError(&span, "Failed to find product by name", err) + mopentelemetry.HandleSpanError(&span, "Failed to find segment by name", err) return true, err } @@ -164,11 +164,11 @@ func (p *ProductPostgreSQLRepository) FindByName(ctx context.Context, organizati return false, nil } -// FindAll retrieves Product entities from the database. -func (p *ProductPostgreSQLRepository) FindAll(ctx context.Context, organizationID, ledgerID uuid.UUID, filter http.Pagination) ([]*mmodel.Product, error) { +// FindAll retrieves Segment entities from the database. +func (p *SegmentPostgreSQLRepository) FindAll(ctx context.Context, organizationID, ledgerID uuid.UUID, filter http.Pagination) ([]*mmodel.Segment, error) { tracer := pkg.NewTracerFromContext(ctx) - ctx, span := tracer.Start(ctx, "postgres.find_all_products") + ctx, span := tracer.Start(ctx, "postgres.find_all_segments") defer span.End() db, err := p.connection.GetDB() @@ -178,7 +178,7 @@ func (p *ProductPostgreSQLRepository) FindAll(ctx context.Context, organizationI return nil, err } - var products []*mmodel.Product + var segments []*mmodel.Segment findAll := squirrel.Select("*"). From(p.tableName). @@ -205,22 +205,22 @@ func (p *ProductPostgreSQLRepository) FindAll(ctx context.Context, organizationI if err != nil { mopentelemetry.HandleSpanError(&spanQuery, "Failed to execute query", err) - return nil, pkg.ValidateBusinessError(constant.ErrEntityNotFound, reflect.TypeOf(mmodel.Product{}).Name()) + return nil, pkg.ValidateBusinessError(constant.ErrEntityNotFound, reflect.TypeOf(mmodel.Segment{}).Name()) } defer rows.Close() spanQuery.End() for rows.Next() { - var product ProductPostgreSQLModel - if err := rows.Scan(&product.ID, &product.Name, &product.LedgerID, &product.OrganizationID, - &product.Status, &product.StatusDescription, &product.CreatedAt, &product.UpdatedAt, &product.DeletedAt); err != nil { + var segment SegmentPostgreSQLModel + if err := rows.Scan(&segment.ID, &segment.Name, &segment.LedgerID, &segment.OrganizationID, + &segment.Status, &segment.StatusDescription, &segment.CreatedAt, &segment.UpdatedAt, &segment.DeletedAt); err != nil { mopentelemetry.HandleSpanError(&span, "Failed to scan row", err) return nil, err } - products = append(products, product.ToEntity()) + segments = append(segments, segment.ToEntity()) } if err := rows.Err(); err != nil { @@ -229,14 +229,14 @@ func (p *ProductPostgreSQLRepository) FindAll(ctx context.Context, organizationI return nil, err } - return products, nil + return segments, nil } -// FindByIDs retrieves Products entities from the database using the provided IDs. -func (p *ProductPostgreSQLRepository) FindByIDs(ctx context.Context, organizationID, ledgerID uuid.UUID, ids []uuid.UUID) ([]*mmodel.Product, error) { +// FindByIDs retrieves Segments entities from the database using the provided IDs. +func (p *SegmentPostgreSQLRepository) FindByIDs(ctx context.Context, organizationID, ledgerID uuid.UUID, ids []uuid.UUID) ([]*mmodel.Segment, error) { tracer := pkg.NewTracerFromContext(ctx) - ctx, span := tracer.Start(ctx, "postgres.find_products_by_ids") + ctx, span := tracer.Start(ctx, "postgres.find_segments_by_ids") defer span.End() db, err := p.connection.GetDB() @@ -246,11 +246,11 @@ func (p *ProductPostgreSQLRepository) FindByIDs(ctx context.Context, organizatio return nil, err } - var products []*mmodel.Product + var segments []*mmodel.Segment - ctx, spanQuery := tracer.Start(ctx, "postgres.find_products_by_ids.query") + ctx, spanQuery := tracer.Start(ctx, "postgres.find_segments_by_ids.query") - rows, err := db.QueryContext(ctx, "SELECT * FROM product WHERE organization_id = $1 AND ledger_id = $2 AND id = ANY($3) AND deleted_at IS NULL ORDER BY created_at DESC", + rows, err := db.QueryContext(ctx, "SELECT * FROM segment WHERE organization_id = $1 AND ledger_id = $2 AND id = ANY($3) AND deleted_at IS NULL ORDER BY created_at DESC", organizationID, ledgerID, pq.Array(ids)) if err != nil { mopentelemetry.HandleSpanError(&spanQuery, "Failed to execute query", err) @@ -262,15 +262,15 @@ func (p *ProductPostgreSQLRepository) FindByIDs(ctx context.Context, organizatio spanQuery.End() for rows.Next() { - var product ProductPostgreSQLModel - if err := rows.Scan(&product.ID, &product.Name, &product.LedgerID, &product.OrganizationID, - &product.Status, &product.StatusDescription, &product.CreatedAt, &product.UpdatedAt, &product.DeletedAt); err != nil { + var segment SegmentPostgreSQLModel + if err := rows.Scan(&segment.ID, &segment.Name, &segment.LedgerID, &segment.OrganizationID, + &segment.Status, &segment.StatusDescription, &segment.CreatedAt, &segment.UpdatedAt, &segment.DeletedAt); err != nil { mopentelemetry.HandleSpanError(&span, "Failed to scan row", err) return nil, err } - products = append(products, product.ToEntity()) + segments = append(segments, segment.ToEntity()) } if err := rows.Err(); err != nil { @@ -279,14 +279,14 @@ func (p *ProductPostgreSQLRepository) FindByIDs(ctx context.Context, organizatio return nil, err } - return products, nil + return segments, nil } -// Find retrieves a Product entity from the database using the provided ID. -func (p *ProductPostgreSQLRepository) Find(ctx context.Context, organizationID, ledgerID, id uuid.UUID) (*mmodel.Product, error) { +// Find retrieves a Segment entity from the database using the provided ID. +func (p *SegmentPostgreSQLRepository) Find(ctx context.Context, organizationID, ledgerID, id uuid.UUID) (*mmodel.Segment, error) { tracer := pkg.NewTracerFromContext(ctx) - ctx, span := tracer.Start(ctx, "postgres.find_product") + ctx, span := tracer.Start(ctx, "postgres.find_segment") defer span.End() db, err := p.connection.GetDB() @@ -296,34 +296,34 @@ func (p *ProductPostgreSQLRepository) Find(ctx context.Context, organizationID, return nil, err } - product := &ProductPostgreSQLModel{} + segment := &SegmentPostgreSQLModel{} ctx, spanQuery := tracer.Start(ctx, "postgres.find.query") - row := db.QueryRowContext(ctx, "SELECT * FROM product WHERE organization_id = $1 AND ledger_id = $2 AND id = $3 AND deleted_at IS NULL ORDER BY created_at DESC", + row := db.QueryRowContext(ctx, "SELECT * FROM segment WHERE organization_id = $1 AND ledger_id = $2 AND id = $3 AND deleted_at IS NULL ORDER BY created_at DESC", organizationID, ledgerID, id) spanQuery.End() - if err := row.Scan(&product.ID, &product.Name, &product.LedgerID, &product.OrganizationID, - &product.Status, &product.StatusDescription, &product.CreatedAt, &product.UpdatedAt, &product.DeletedAt); err != nil { + if err := row.Scan(&segment.ID, &segment.Name, &segment.LedgerID, &segment.OrganizationID, + &segment.Status, &segment.StatusDescription, &segment.CreatedAt, &segment.UpdatedAt, &segment.DeletedAt); err != nil { mopentelemetry.HandleSpanError(&span, "Failed to scan row", err) if errors.Is(err, sql.ErrNoRows) { - return nil, pkg.ValidateBusinessError(constant.ErrEntityNotFound, reflect.TypeOf(mmodel.Product{}).Name()) + return nil, pkg.ValidateBusinessError(constant.ErrEntityNotFound, reflect.TypeOf(mmodel.Segment{}).Name()) } return nil, err } - return product.ToEntity(), nil + return segment.ToEntity(), nil } -// Update a Product entity into Postgresql and returns the Product updated. -func (p *ProductPostgreSQLRepository) Update(ctx context.Context, organizationID, ledgerID, id uuid.UUID, prd *mmodel.Product) (*mmodel.Product, error) { +// Update a Segment entity into Postgresql and returns the Segment updated. +func (p *SegmentPostgreSQLRepository) Update(ctx context.Context, organizationID, ledgerID, id uuid.UUID, prd *mmodel.Segment) (*mmodel.Segment, error) { tracer := pkg.NewTracerFromContext(ctx) - ctx, span := tracer.Start(ctx, "postgres.update_product") + ctx, span := tracer.Start(ctx, "postgres.update_segment") defer span.End() db, err := p.connection.GetDB() @@ -333,7 +333,7 @@ func (p *ProductPostgreSQLRepository) Update(ctx context.Context, organizationID return nil, err } - record := &ProductPostgreSQLModel{} + record := &SegmentPostgreSQLModel{} record.FromEntity(prd) var updates []string @@ -359,7 +359,7 @@ func (p *ProductPostgreSQLRepository) Update(ctx context.Context, organizationID args = append(args, record.UpdatedAt, organizationID, ledgerID, id) - query := `UPDATE product SET ` + strings.Join(updates, ", ") + + query := `UPDATE segment SET ` + strings.Join(updates, ", ") + ` WHERE organization_id = $` + strconv.Itoa(len(args)-2) + ` AND ledger_id = $` + strconv.Itoa(len(args)-1) + ` AND id = $` + strconv.Itoa(len(args)) + @@ -367,9 +367,9 @@ func (p *ProductPostgreSQLRepository) Update(ctx context.Context, organizationID ctx, spanExec := tracer.Start(ctx, "postgres.update.exec") - err = mopentelemetry.SetSpanAttributesFromStruct(&spanExec, "product_repository_input", record) + err = mopentelemetry.SetSpanAttributesFromStruct(&spanExec, "segment_repository_input", record) if err != nil { - mopentelemetry.HandleSpanError(&spanExec, "Failed to convert product record from entity to JSON string", err) + mopentelemetry.HandleSpanError(&spanExec, "Failed to convert segment record from entity to JSON string", err) return nil, err } @@ -380,7 +380,7 @@ func (p *ProductPostgreSQLRepository) Update(ctx context.Context, organizationID var pgErr *pgconn.PgError if errors.As(err, &pgErr) { - return nil, services.ValidatePGError(pgErr, reflect.TypeOf(mmodel.Product{}).Name()) + return nil, services.ValidatePGError(pgErr, reflect.TypeOf(mmodel.Segment{}).Name()) } return nil, err @@ -396,9 +396,9 @@ func (p *ProductPostgreSQLRepository) Update(ctx context.Context, organizationID } if rowsAffected == 0 { - err := pkg.ValidateBusinessError(constant.ErrEntityNotFound, reflect.TypeOf(mmodel.Product{}).Name()) + err := pkg.ValidateBusinessError(constant.ErrEntityNotFound, reflect.TypeOf(mmodel.Segment{}).Name()) - mopentelemetry.HandleSpanError(&span, "Failed to update product. Rows affected is 0", err) + mopentelemetry.HandleSpanError(&span, "Failed to update segment. Rows affected is 0", err) return nil, err } @@ -406,11 +406,11 @@ func (p *ProductPostgreSQLRepository) Update(ctx context.Context, organizationID return record.ToEntity(), nil } -// Delete removes a Product entity from the database using the provided IDs. -func (p *ProductPostgreSQLRepository) Delete(ctx context.Context, organizationID, ledgerID, id uuid.UUID) error { +// Delete removes a Segment entity from the database using the provided IDs. +func (p *SegmentPostgreSQLRepository) Delete(ctx context.Context, organizationID, ledgerID, id uuid.UUID) error { tracer := pkg.NewTracerFromContext(ctx) - ctx, span := tracer.Start(ctx, "postgres.delete_product") + ctx, span := tracer.Start(ctx, "postgres.delete_segment") defer span.End() db, err := p.connection.GetDB() @@ -422,7 +422,7 @@ func (p *ProductPostgreSQLRepository) Delete(ctx context.Context, organizationID ctx, spanExec := tracer.Start(ctx, "postgres.delete.exec") - result, err := db.ExecContext(ctx, `UPDATE product SET deleted_at = now() WHERE organization_id = $1 AND ledger_id = $2 AND id = $3 AND deleted_at IS NULL`, + result, err := db.ExecContext(ctx, `UPDATE segment SET deleted_at = now() WHERE organization_id = $1 AND ledger_id = $2 AND id = $3 AND deleted_at IS NULL`, organizationID, ledgerID, id) if err != nil { mopentelemetry.HandleSpanError(&spanExec, "Failed to execute delete query", err) @@ -440,9 +440,9 @@ func (p *ProductPostgreSQLRepository) Delete(ctx context.Context, organizationID } if rowsAffected == 0 { - err := pkg.ValidateBusinessError(constant.ErrEntityNotFound, reflect.TypeOf(mmodel.Product{}).Name()) + err := pkg.ValidateBusinessError(constant.ErrEntityNotFound, reflect.TypeOf(mmodel.Segment{}).Name()) - mopentelemetry.HandleSpanError(&span, "Failed to delete product. Rows affected is 0", err) + mopentelemetry.HandleSpanError(&span, "Failed to delete segment. Rows affected is 0", err) return err } diff --git a/components/ledger/internal/bootstrap/config.go b/components/ledger/internal/bootstrap/config.go index 923c9b53e..e9fb284ee 100644 --- a/components/ledger/internal/bootstrap/config.go +++ b/components/ledger/internal/bootstrap/config.go @@ -11,7 +11,7 @@ import ( "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/ledger" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/organization" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/portfolio" - "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/product" + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/segment" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/rabbitmq" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/redis" "github.com/LerianStudio/midaz/components/ledger/internal/services/command" @@ -156,7 +156,7 @@ func InitServers() *Service { organizationPostgreSQLRepository := organization.NewOrganizationPostgreSQLRepository(postgresConnection) ledgerPostgreSQLRepository := ledger.NewLedgerPostgreSQLRepository(postgresConnection) - productPostgreSQLRepository := product.NewProductPostgreSQLRepository(postgresConnection) + segmentPostgreSQLRepository := segment.NewSegmentPostgreSQLRepository(postgresConnection) portfolioPostgreSQLRepository := portfolio.NewPortfolioPostgreSQLRepository(postgresConnection) accountPostgreSQLRepository := account.NewAccountPostgreSQLRepository(postgresConnection) assetPostgreSQLRepository := asset.NewAssetPostgreSQLRepository(postgresConnection) @@ -171,7 +171,7 @@ func InitServers() *Service { commandUseCase := &command.UseCase{ OrganizationRepo: organizationPostgreSQLRepository, LedgerRepo: ledgerPostgreSQLRepository, - ProductRepo: productPostgreSQLRepository, + SegmentRepo: segmentPostgreSQLRepository, PortfolioRepo: portfolioPostgreSQLRepository, AccountRepo: accountPostgreSQLRepository, AssetRepo: assetPostgreSQLRepository, @@ -183,7 +183,7 @@ func InitServers() *Service { queryUseCase := &query.UseCase{ OrganizationRepo: organizationPostgreSQLRepository, LedgerRepo: ledgerPostgreSQLRepository, - ProductRepo: productPostgreSQLRepository, + SegmentRepo: segmentPostgreSQLRepository, PortfolioRepo: portfolioPostgreSQLRepository, AccountRepo: accountPostgreSQLRepository, AssetRepo: assetPostgreSQLRepository, @@ -217,12 +217,12 @@ func InitServers() *Service { Query: queryUseCase, } - productHandler := &httpin.ProductHandler{ + segmentHandler := &httpin.SegmentHandler{ Command: commandUseCase, Query: queryUseCase, } - httpApp := httpin.NewRouter(logger, telemetry, casDoorConnection, accountHandler, portfolioHandler, ledgerHandler, assetHandler, organizationHandler, productHandler) + httpApp := httpin.NewRouter(logger, telemetry, casDoorConnection, accountHandler, portfolioHandler, ledgerHandler, assetHandler, organizationHandler, segmentHandler) serverAPI := NewServer(cfg, httpApp, logger, telemetry) diff --git a/components/ledger/internal/services/command/command.go b/components/ledger/internal/services/command/command.go index c16f5f53e..a81db0f8d 100644 --- a/components/ledger/internal/services/command/command.go +++ b/components/ledger/internal/services/command/command.go @@ -7,7 +7,7 @@ import ( "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/ledger" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/organization" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/portfolio" - "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/product" + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/segment" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/rabbitmq" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/redis" ) @@ -20,8 +20,8 @@ type UseCase struct { // LedgerRepo provides an abstraction on top of the ledger data source. LedgerRepo ledger.Repository - // ProductRepo provides an abstraction on top of the product data source. - ProductRepo product.Repository + // SegmentRepo provides an abstraction on top of the segment data source. + SegmentRepo segment.Repository // PortfolioRepo provides an abstraction on top of the portfolio data source. PortfolioRepo portfolio.Repository diff --git a/components/ledger/internal/services/command/create-account.go b/components/ledger/internal/services/command/create-account.go index d510ee9e9..e065c39d7 100644 --- a/components/ledger/internal/services/command/create-account.go +++ b/components/ledger/internal/services/command/create-account.go @@ -106,7 +106,7 @@ func (uc *UseCase) CreateAccount(ctx context.Context, organizationID, ledgerID u Name: cai.Name, Type: cai.Type, ParentAccountID: cai.ParentAccountID, - ProductID: cai.ProductID, + SegmentID: cai.SegmentID, OrganizationID: organizationID.String(), PortfolioID: cai.PortfolioID, LedgerID: ledgerID.String(), diff --git a/components/ledger/internal/services/command/create-asset.go b/components/ledger/internal/services/command/create-asset.go index ae416d312..9134e984f 100644 --- a/components/ledger/internal/services/command/create-asset.go +++ b/components/ledger/internal/services/command/create-asset.go @@ -127,7 +127,7 @@ func (uc *UseCase) CreateAsset(ctx context.Context, organizationID, ledgerID uui OrganizationID: organizationID.String(), LedgerID: ledgerID.String(), ParentAccountID: nil, - ProductID: nil, + SegmentID: nil, PortfolioID: nil, EntityID: nil, Balance: aBalance, diff --git a/components/ledger/internal/services/command/create-portfolio_test.go b/components/ledger/internal/services/command/create-portfolio_test.go index ae5ff8b47..fea9f5c8f 100644 --- a/components/ledger/internal/services/command/create-portfolio_test.go +++ b/components/ledger/internal/services/command/create-portfolio_test.go @@ -3,6 +3,7 @@ package command import ( "context" "errors" + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/segment" "reflect" "testing" "time" @@ -13,7 +14,6 @@ import ( "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/ledger" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/organization" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/portfolio" - "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/product" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/rabbitmq" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/redis" "github.com/LerianStudio/midaz/pkg" @@ -227,7 +227,7 @@ func TestUseCase_CreatePortfolio(t *testing.T) { type fields struct { OrganizationRepo organization.Repository LedgerRepo ledger.Repository - ProductRepo product.Repository + SegmentRepo segment.Repository PortfolioRepo portfolio.Repository AccountRepo account.Repository AssetRepo asset.Repository @@ -255,7 +255,7 @@ func TestUseCase_CreatePortfolio(t *testing.T) { uc := &UseCase{ OrganizationRepo: tt.fields.OrganizationRepo, LedgerRepo: tt.fields.LedgerRepo, - ProductRepo: tt.fields.ProductRepo, + SegmentRepo: tt.fields.SegmentRepo, PortfolioRepo: tt.fields.PortfolioRepo, AccountRepo: tt.fields.AccountRepo, AssetRepo: tt.fields.AssetRepo, diff --git a/components/ledger/internal/services/command/create-product.go b/components/ledger/internal/services/command/create-segment.go similarity index 52% rename from components/ledger/internal/services/command/create-product.go rename to components/ledger/internal/services/command/create-segment.go index 314b235b1..449bee913 100644 --- a/components/ledger/internal/services/command/create-product.go +++ b/components/ledger/internal/services/command/create-segment.go @@ -11,15 +11,15 @@ import ( "github.com/google/uuid" ) -// CreateProduct creates a new product persists data in the repository. -func (uc *UseCase) CreateProduct(ctx context.Context, organizationID, ledgerID uuid.UUID, cpi *mmodel.CreateProductInput) (*mmodel.Product, error) { +// CreateSegment creates a new segment persists data in the repository. +func (uc *UseCase) CreateSegment(ctx context.Context, organizationID, ledgerID uuid.UUID, cpi *mmodel.CreateSegmentInput) (*mmodel.Segment, error) { logger := pkg.NewLoggerFromContext(ctx) tracer := pkg.NewTracerFromContext(ctx) - ctx, span := tracer.Start(ctx, "command.create_product") + ctx, span := tracer.Start(ctx, "command.create_segment") defer span.End() - logger.Infof("Trying to create product: %v", cpi) + logger.Infof("Trying to create segment: %v", cpi) var status mmodel.Status if cpi.Status.IsEmpty() || pkg.IsNilOrEmpty(&cpi.Status.Code) { @@ -32,7 +32,7 @@ func (uc *UseCase) CreateProduct(ctx context.Context, organizationID, ledgerID u status.Description = cpi.Status.Description - product := &mmodel.Product{ + segment := &mmodel.Segment{ ID: pkg.GenerateUUIDv7().String(), LedgerID: ledgerID.String(), OrganizationID: organizationID.String(), @@ -42,27 +42,27 @@ func (uc *UseCase) CreateProduct(ctx context.Context, organizationID, ledgerID u UpdatedAt: time.Now(), } - _, err := uc.ProductRepo.FindByName(ctx, organizationID, ledgerID, cpi.Name) + _, err := uc.SegmentRepo.FindByName(ctx, organizationID, ledgerID, cpi.Name) if err != nil { - pkg.NewLoggerFromContext(ctx).Errorf("Error finding product by name: %v", err) + pkg.NewLoggerFromContext(ctx).Errorf("Error finding segment by name: %v", err) return nil, err } - prod, err := uc.ProductRepo.Create(ctx, product) + prod, err := uc.SegmentRepo.Create(ctx, segment) if err != nil { - pkg.NewLoggerFromContext(ctx).Errorf("Error creating product: %v", err) + pkg.NewLoggerFromContext(ctx).Errorf("Error creating segment: %v", err) - logger.Errorf("Error creating product: %v", err) + logger.Errorf("Error creating segment: %v", err) return nil, err } - metadata, err := uc.CreateMetadata(ctx, reflect.TypeOf(mmodel.Product{}).Name(), prod.ID, cpi.Metadata) + metadata, err := uc.CreateMetadata(ctx, reflect.TypeOf(mmodel.Segment{}).Name(), prod.ID, cpi.Metadata) if err != nil { - pkg.NewLoggerFromContext(ctx).Errorf("Error creating product metadata: %v", err) + pkg.NewLoggerFromContext(ctx).Errorf("Error creating segment metadata: %v", err) - logger.Errorf("Error creating product metadata: %v", err) + logger.Errorf("Error creating segment metadata: %v", err) return nil, err } diff --git a/components/ledger/internal/services/command/create-product_test.go b/components/ledger/internal/services/command/create-segment_test.go similarity index 77% rename from components/ledger/internal/services/command/create-product_test.go rename to components/ledger/internal/services/command/create-segment_test.go index 7d17c095c..edf8e4952 100644 --- a/components/ledger/internal/services/command/create-product_test.go +++ b/components/ledger/internal/services/command/create-segment_test.go @@ -3,43 +3,43 @@ package command import ( "context" "errors" + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/segment" "testing" "time" "go.uber.org/mock/gomock" - "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/product" "github.com/LerianStudio/midaz/pkg/mmodel" "github.com/google/uuid" "github.com/stretchr/testify/assert" ) -func TestCreateProduct(t *testing.T) { +func TestCreateSegment(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() - mockRepo := product.NewMockRepository(ctrl) + mockRepo := segment.NewMockRepository(ctrl) uc := &UseCase{ - ProductRepo: mockRepo, + SegmentRepo: mockRepo, } tests := []struct { name string organizationID uuid.UUID ledgerID uuid.UUID - input *mmodel.CreateProductInput + input *mmodel.CreateSegmentInput mockSetup func() expectErr bool - expectedProd *mmodel.Product + expectedProd *mmodel.Segment }{ { name: "Success with all fields", organizationID: uuid.New(), ledgerID: uuid.New(), - input: &mmodel.CreateProductInput{ - Name: "Test Product", + input: &mmodel.CreateSegmentInput{ + Name: "Test Segment", Status: mmodel.Status{ Code: "ACTIVE", }, @@ -47,15 +47,15 @@ func TestCreateProduct(t *testing.T) { }, mockSetup: func() { mockRepo.EXPECT(). - FindByName(gomock.Any(), gomock.Any(), gomock.Any(), "Test Product"). + FindByName(gomock.Any(), gomock.Any(), gomock.Any(), "Test Segment"). Return(true, nil) mockRepo.EXPECT(). Create(gomock.Any(), gomock.Any()). - Return(&mmodel.Product{ + Return(&mmodel.Segment{ ID: "123", OrganizationID: "org123", LedgerID: "ledger123", - Name: "Test Product", + Name: "Test Segment", Status: mmodel.Status{Code: "ACTIVE"}, CreatedAt: time.Now(), UpdatedAt: time.Now(), @@ -63,8 +63,8 @@ func TestCreateProduct(t *testing.T) { }, nil) // Produto criado com sucesso }, expectErr: false, - expectedProd: &mmodel.Product{ - Name: "Test Product", + expectedProd: &mmodel.Segment{ + Name: "Test Segment", Status: mmodel.Status{Code: "ACTIVE"}, }, }, @@ -72,8 +72,8 @@ func TestCreateProduct(t *testing.T) { name: "Error when FindByName fails", organizationID: uuid.New(), ledgerID: uuid.New(), - input: &mmodel.CreateProductInput{ - Name: "Failing Product", + input: &mmodel.CreateSegmentInput{ + Name: "Failing Segment", Status: mmodel.Status{ Code: "ACTIVE", }, @@ -81,7 +81,7 @@ func TestCreateProduct(t *testing.T) { }, mockSetup: func() { mockRepo.EXPECT(). - FindByName(gomock.Any(), gomock.Any(), gomock.Any(), "Failing Product"). + FindByName(gomock.Any(), gomock.Any(), gomock.Any(), "Failing Segment"). Return(false, errors.New("repository error")) }, expectErr: true, @@ -91,22 +91,22 @@ func TestCreateProduct(t *testing.T) { name: "Success with default status", organizationID: uuid.New(), ledgerID: uuid.New(), - input: &mmodel.CreateProductInput{ - Name: "Default Status Product", + input: &mmodel.CreateSegmentInput{ + Name: "Default Status Segment", Status: mmodel.Status{}, // Empty status Metadata: nil, }, mockSetup: func() { mockRepo.EXPECT(). - FindByName(gomock.Any(), gomock.Any(), gomock.Any(), "Default Status Product"). + FindByName(gomock.Any(), gomock.Any(), gomock.Any(), "Default Status Segment"). Return(true, nil) mockRepo.EXPECT(). Create(gomock.Any(), gomock.Any()). - Return(&mmodel.Product{ + Return(&mmodel.Segment{ ID: "124", OrganizationID: "org124", LedgerID: "ledger124", - Name: "Default Status Product", + Name: "Default Status Segment", Status: mmodel.Status{Code: "ACTIVE"}, CreatedAt: time.Now(), UpdatedAt: time.Now(), @@ -114,8 +114,8 @@ func TestCreateProduct(t *testing.T) { }, nil) }, expectErr: false, - expectedProd: &mmodel.Product{ - Name: "Default Status Product", + expectedProd: &mmodel.Segment{ + Name: "Default Status Segment", Status: mmodel.Status{Code: "ACTIVE"}, }, }, @@ -126,7 +126,7 @@ func TestCreateProduct(t *testing.T) { tt.mockSetup() ctx := context.Background() - result, err := uc.CreateProduct(ctx, tt.organizationID, tt.ledgerID, tt.input) + result, err := uc.CreateSegment(ctx, tt.organizationID, tt.ledgerID, tt.input) if tt.expectErr { assert.Error(t, err) diff --git a/components/ledger/internal/services/command/delete-product.go b/components/ledger/internal/services/command/delete-segment.go similarity index 53% rename from components/ledger/internal/services/command/delete-product.go rename to components/ledger/internal/services/command/delete-segment.go index dfee79c46..4df22f60a 100644 --- a/components/ledger/internal/services/command/delete-product.go +++ b/components/ledger/internal/services/command/delete-segment.go @@ -14,23 +14,23 @@ import ( "github.com/google/uuid" ) -// DeleteProductByID delete a product from the repository by ids. -func (uc *UseCase) DeleteProductByID(ctx context.Context, organizationID, ledgerID, id uuid.UUID) error { +// DeleteSegmentByID delete a segment from the repository by ids. +func (uc *UseCase) DeleteSegmentByID(ctx context.Context, organizationID, ledgerID, id uuid.UUID) error { logger := pkg.NewLoggerFromContext(ctx) tracer := pkg.NewTracerFromContext(ctx) - ctx, span := tracer.Start(ctx, "command.delete_product_by_id") + ctx, span := tracer.Start(ctx, "command.delete_segment_by_id") defer span.End() - logger.Infof("Remove product for id: %s", id.String()) + logger.Infof("Remove segment for id: %s", id.String()) - if err := uc.ProductRepo.Delete(ctx, organizationID, ledgerID, id); err != nil { - mopentelemetry.HandleSpanError(&span, "Failed to delete product on repo by id", err) + if err := uc.SegmentRepo.Delete(ctx, organizationID, ledgerID, id); err != nil { + mopentelemetry.HandleSpanError(&span, "Failed to delete segment on repo by id", err) - logger.Errorf("Error deleting product on repo by id: %v", err) + logger.Errorf("Error deleting segment on repo by id: %v", err) if errors.Is(err, services.ErrDatabaseItemNotFound) { - return pkg.ValidateBusinessError(constant.ErrProductIDNotFound, reflect.TypeOf(mmodel.Product{}).Name()) + return pkg.ValidateBusinessError(constant.ErrSegmentIDNotFound, reflect.TypeOf(mmodel.Segment{}).Name()) } return err diff --git a/components/ledger/internal/services/command/delete-product_test.go b/components/ledger/internal/services/command/delete-segment_test.go similarity index 56% rename from components/ledger/internal/services/command/delete-product_test.go rename to components/ledger/internal/services/command/delete-segment_test.go index f9e3b0b04..8f33b681c 100644 --- a/components/ledger/internal/services/command/delete-product_test.go +++ b/components/ledger/internal/services/command/delete-segment_test.go @@ -3,31 +3,31 @@ package command import ( "context" "errors" + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/segment" "testing" "go.uber.org/mock/gomock" - "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/product" "github.com/LerianStudio/midaz/components/ledger/internal/services" "github.com/google/uuid" "github.com/stretchr/testify/assert" ) -func TestDeleteProductByID(t *testing.T) { +func TestDeleteSegmentByID(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() - mockProductRepo := product.NewMockRepository(ctrl) + mockSegmentRepo := segment.NewMockRepository(ctrl) uc := &UseCase{ - ProductRepo: mockProductRepo, + SegmentRepo: mockSegmentRepo, } ctx := context.Background() organizationID := uuid.New() ledgerID := uuid.New() - productID := uuid.New() + segmentID := uuid.New() tests := []struct { name string @@ -35,34 +35,34 @@ func TestDeleteProductByID(t *testing.T) { expectedErr error }{ { - name: "success - product deleted", + name: "success - segment deleted", setupMocks: func() { - mockProductRepo.EXPECT(). - Delete(gomock.Any(), organizationID, ledgerID, productID). + mockSegmentRepo.EXPECT(). + Delete(gomock.Any(), organizationID, ledgerID, segmentID). Return(nil). Times(1) }, expectedErr: nil, }, { - name: "failure - product not found", + name: "failure - segment not found", setupMocks: func() { - mockProductRepo.EXPECT(). - Delete(gomock.Any(), organizationID, ledgerID, productID). + mockSegmentRepo.EXPECT(). + Delete(gomock.Any(), organizationID, ledgerID, segmentID). Return(services.ErrDatabaseItemNotFound). Times(1) }, - expectedErr: errors.New("The provided product ID does not exist in our records. Please verify the product ID and try again."), + expectedErr: errors.New("The provided segment ID does not exist in our records. Please verify the segment ID and try again."), }, { name: "failure - repository error", setupMocks: func() { - mockProductRepo.EXPECT(). - Delete(gomock.Any(), organizationID, ledgerID, productID). - Return(errors.New("failed to delete product")). + mockSegmentRepo.EXPECT(). + Delete(gomock.Any(), organizationID, ledgerID, segmentID). + Return(errors.New("failed to delete segment")). Times(1) }, - expectedErr: errors.New("failed to delete product"), + expectedErr: errors.New("failed to delete segment"), }, } @@ -70,7 +70,7 @@ func TestDeleteProductByID(t *testing.T) { t.Run(tt.name, func(t *testing.T) { tt.setupMocks() - err := uc.DeleteProductByID(ctx, organizationID, ledgerID, productID) + err := uc.DeleteSegmentByID(ctx, organizationID, ledgerID, segmentID) if tt.expectedErr != nil { assert.Error(t, err) diff --git a/components/ledger/internal/services/command/update-account.go b/components/ledger/internal/services/command/update-account.go index 8df964370..98fb0a699 100644 --- a/components/ledger/internal/services/command/update-account.go +++ b/components/ledger/internal/services/command/update-account.go @@ -43,7 +43,7 @@ func (uc *UseCase) UpdateAccount(ctx context.Context, organizationID, ledgerID u Name: uai.Name, Status: uai.Status, Alias: uai.Alias, - ProductID: uai.ProductID, + SegmentID: uai.SegmentID, PortfolioID: uai.PortfolioID, AllowSending: uai.AllowSending, AllowReceiving: uai.AllowReceiving, diff --git a/components/ledger/internal/services/command/update-account_test.go b/components/ledger/internal/services/command/update-account_test.go index 5f0040325..737766f95 100644 --- a/components/ledger/internal/services/command/update-account_test.go +++ b/components/ledger/internal/services/command/update-account_test.go @@ -48,7 +48,7 @@ func TestUpdateAccount(t *testing.T) { Code: "active", }, Alias: nil, - ProductID: nil, + SegmentID: nil, Metadata: map[string]any{"key": "value"}, }, mockSetup: func() { @@ -79,7 +79,7 @@ func TestUpdateAccount(t *testing.T) { Code: "active", }, Alias: nil, - ProductID: nil, + SegmentID: nil, Metadata: nil, }, mockSetup: func() { @@ -101,7 +101,7 @@ func TestUpdateAccount(t *testing.T) { Code: "active", }, Alias: nil, - ProductID: nil, + SegmentID: nil, Metadata: map[string]any{"key": "value"}, }, mockSetup: func() { diff --git a/components/ledger/internal/services/command/update-product.go b/components/ledger/internal/services/command/update-product.go deleted file mode 100644 index 119978d61..000000000 --- a/components/ledger/internal/services/command/update-product.go +++ /dev/null @@ -1,55 +0,0 @@ -package command - -import ( - "context" - "errors" - "reflect" - - "github.com/LerianStudio/midaz/components/ledger/internal/services" - "github.com/LerianStudio/midaz/pkg" - "github.com/LerianStudio/midaz/pkg/constant" - "github.com/LerianStudio/midaz/pkg/mmodel" - "github.com/LerianStudio/midaz/pkg/mopentelemetry" - - "github.com/google/uuid" -) - -// UpdateProductByID update a product from the repository by given id. -func (uc *UseCase) UpdateProductByID(ctx context.Context, organizationID, ledgerID, id uuid.UUID, upi *mmodel.UpdateProductInput) (*mmodel.Product, error) { - logger := pkg.NewLoggerFromContext(ctx) - tracer := pkg.NewTracerFromContext(ctx) - - ctx, span := tracer.Start(ctx, "command.update_product_by_id") - defer span.End() - - logger.Infof("Trying to update product: %v", upi) - - product := &mmodel.Product{ - Name: upi.Name, - Status: upi.Status, - } - - productUpdated, err := uc.ProductRepo.Update(ctx, organizationID, ledgerID, id, product) - if err != nil { - mopentelemetry.HandleSpanError(&span, "Failed to update product on repo by id", err) - - logger.Errorf("Error updating product on repo by id: %v", err) - - if errors.Is(err, services.ErrDatabaseItemNotFound) { - return nil, pkg.ValidateBusinessError(constant.ErrProductIDNotFound, reflect.TypeOf(mmodel.Product{}).Name()) - } - - return nil, err - } - - metadataUpdated, err := uc.UpdateMetadata(ctx, reflect.TypeOf(mmodel.Product{}).Name(), id.String(), upi.Metadata) - if err != nil { - mopentelemetry.HandleSpanError(&span, "Failed to update metadata on repo by id", err) - - return nil, err - } - - productUpdated.Metadata = metadataUpdated - - return productUpdated, nil -} diff --git a/components/ledger/internal/services/command/update-segment.go b/components/ledger/internal/services/command/update-segment.go new file mode 100644 index 000000000..a15ed05cd --- /dev/null +++ b/components/ledger/internal/services/command/update-segment.go @@ -0,0 +1,55 @@ +package command + +import ( + "context" + "errors" + "reflect" + + "github.com/LerianStudio/midaz/components/ledger/internal/services" + "github.com/LerianStudio/midaz/pkg" + "github.com/LerianStudio/midaz/pkg/constant" + "github.com/LerianStudio/midaz/pkg/mmodel" + "github.com/LerianStudio/midaz/pkg/mopentelemetry" + + "github.com/google/uuid" +) + +// UpdateSegmentByID update a segment from the repository by given id. +func (uc *UseCase) UpdateSegmentByID(ctx context.Context, organizationID, ledgerID, id uuid.UUID, upi *mmodel.UpdateSegmentInput) (*mmodel.Segment, error) { + logger := pkg.NewLoggerFromContext(ctx) + tracer := pkg.NewTracerFromContext(ctx) + + ctx, span := tracer.Start(ctx, "command.update_segment_by_id") + defer span.End() + + logger.Infof("Trying to update segment: %v", upi) + + segment := &mmodel.Segment{ + Name: upi.Name, + Status: upi.Status, + } + + segmentUpdated, err := uc.SegmentRepo.Update(ctx, organizationID, ledgerID, id, segment) + if err != nil { + mopentelemetry.HandleSpanError(&span, "Failed to update segment on repo by id", err) + + logger.Errorf("Error updating segment on repo by id: %v", err) + + if errors.Is(err, services.ErrDatabaseItemNotFound) { + return nil, pkg.ValidateBusinessError(constant.ErrSegmentIDNotFound, reflect.TypeOf(mmodel.Segment{}).Name()) + } + + return nil, err + } + + metadataUpdated, err := uc.UpdateMetadata(ctx, reflect.TypeOf(mmodel.Segment{}).Name(), id.String(), upi.Metadata) + if err != nil { + mopentelemetry.HandleSpanError(&span, "Failed to update metadata on repo by id", err) + + return nil, err + } + + segmentUpdated.Metadata = metadataUpdated + + return segmentUpdated, nil +} diff --git a/components/ledger/internal/services/command/update-product_test.go b/components/ledger/internal/services/command/update-segment_test.go similarity index 73% rename from components/ledger/internal/services/command/update-product_test.go rename to components/ledger/internal/services/command/update-segment_test.go index 4cadda880..c9c33b6d9 100644 --- a/components/ledger/internal/services/command/update-product_test.go +++ b/components/ledger/internal/services/command/update-segment_test.go @@ -3,12 +3,12 @@ package command import ( "context" "errors" + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/segment" "testing" "go.uber.org/mock/gomock" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/mongodb" - "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/product" "github.com/LerianStudio/midaz/components/ledger/internal/services" "github.com/LerianStudio/midaz/pkg/mmodel" "github.com/google/uuid" @@ -16,15 +16,15 @@ import ( "github.com/stretchr/testify/assert" ) -func TestUpdateProductByID(t *testing.T) { +func TestUpdateSegmentByID(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() - mockProductRepo := product.NewMockRepository(ctrl) + mockSegmentRepo := segment.NewMockRepository(ctrl) mockMetadataRepo := mongodb.NewMockRepository(ctrl) uc := &UseCase{ - ProductRepo: mockProductRepo, + SegmentRepo: mockSegmentRepo, MetadataRepo: mockMetadataRepo, } @@ -32,25 +32,25 @@ func TestUpdateProductByID(t *testing.T) { name string organizationID uuid.UUID ledgerID uuid.UUID - productID uuid.UUID - input *mmodel.UpdateProductInput + segmentID uuid.UUID + input *mmodel.UpdateSegmentInput mockSetup func() expectErr bool }{ { - name: "Success - Product updated with metadata", + name: "Success - Segment updated with metadata", organizationID: uuid.New(), ledgerID: uuid.New(), - productID: uuid.New(), - input: &mmodel.UpdateProductInput{ - Name: "Updated Product", + segmentID: uuid.New(), + input: &mmodel.UpdateSegmentInput{ + Name: "Updated Segment", Status: mmodel.Status{Code: "active"}, Metadata: map[string]any{"key": "value"}, }, mockSetup: func() { - mockProductRepo.EXPECT(). + mockSegmentRepo.EXPECT(). Update(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). - Return(&mmodel.Product{ID: "123", Name: "Updated Product", Status: mmodel.Status{Code: "active"}, Metadata: nil}, nil) + Return(&mmodel.Segment{ID: "123", Name: "Updated Segment", Status: mmodel.Status{Code: "active"}, Metadata: nil}, nil) mockMetadataRepo.EXPECT(). FindByEntity(gomock.Any(), gomock.Any(), gomock.Any()). Return(&mongodb.Metadata{Data: map[string]any{"existing_key": "existing_value"}}, nil) @@ -61,17 +61,17 @@ func TestUpdateProductByID(t *testing.T) { expectErr: false, }, { - name: "Error - Product not found", + name: "Error - Segment not found", organizationID: uuid.New(), ledgerID: uuid.New(), - productID: uuid.New(), - input: &mmodel.UpdateProductInput{ - Name: "Nonexistent Product", + segmentID: uuid.New(), + input: &mmodel.UpdateSegmentInput{ + Name: "Nonexistent Segment", Status: mmodel.Status{Code: "inactive"}, Metadata: nil, }, mockSetup: func() { - mockProductRepo.EXPECT(). + mockSegmentRepo.EXPECT(). Update(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). Return(nil, services.ErrDatabaseItemNotFound) }, @@ -81,16 +81,16 @@ func TestUpdateProductByID(t *testing.T) { name: "Error - Failed to update metadata", organizationID: uuid.New(), ledgerID: uuid.New(), - productID: uuid.New(), - input: &mmodel.UpdateProductInput{ - Name: "Product with Metadata Error", + segmentID: uuid.New(), + input: &mmodel.UpdateSegmentInput{ + Name: "Segment with Metadata Error", Status: mmodel.Status{Code: "active"}, Metadata: map[string]any{"key": "value"}, }, mockSetup: func() { - mockProductRepo.EXPECT(). + mockSegmentRepo.EXPECT(). Update(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). - Return(&mmodel.Product{ID: "123", Name: "Product with Metadata Error", Status: mmodel.Status{Code: "active"}, Metadata: nil}, nil) + Return(&mmodel.Segment{ID: "123", Name: "Segment with Metadata Error", Status: mmodel.Status{Code: "active"}, Metadata: nil}, nil) mockMetadataRepo.EXPECT(). FindByEntity(gomock.Any(), gomock.Any(), gomock.Any()). Return(&mongodb.Metadata{Data: map[string]any{"existing_key": "existing_value"}}, nil) @@ -101,17 +101,17 @@ func TestUpdateProductByID(t *testing.T) { expectErr: true, }, { - name: "Error - Failure to update product", + name: "Error - Failure to update segment", organizationID: uuid.New(), ledgerID: uuid.New(), - productID: uuid.New(), - input: &mmodel.UpdateProductInput{ - Name: "Update Failure Product", + segmentID: uuid.New(), + input: &mmodel.UpdateSegmentInput{ + Name: "Update Failure Segment", Status: mmodel.Status{Code: "inactive"}, Metadata: nil, }, mockSetup: func() { - mockProductRepo.EXPECT(). + mockSegmentRepo.EXPECT(). Update(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). Return(nil, errors.New("update error")) }, @@ -124,7 +124,7 @@ func TestUpdateProductByID(t *testing.T) { tt.mockSetup() ctx := context.Background() - result, err := uc.UpdateProductByID(ctx, tt.organizationID, tt.ledgerID, tt.productID, tt.input) + result, err := uc.UpdateSegmentByID(ctx, tt.organizationID, tt.ledgerID, tt.segmentID, tt.input) if tt.expectErr { assert.Error(t, err) diff --git a/components/ledger/internal/services/errors.go b/components/ledger/internal/services/errors.go index cf1d948e6..5362648ba 100644 --- a/components/ledger/internal/services/errors.go +++ b/components/ledger/internal/services/errors.go @@ -23,11 +23,11 @@ func ValidatePGError(pgErr *pgconn.PgError, entityType string) error { return pkg.ValidateBusinessError(constant.ErrAssetCodeNotFound, entityType) case "account_portfolio_id_fkey": return pkg.ValidateBusinessError(constant.ErrPortfolioIDNotFound, entityType) - case "account_product_id_fkey": - return pkg.ValidateBusinessError(constant.ErrProductIDNotFound, entityType) - case "account_ledger_id_fkey", "portfolio_ledger_id_fkey", "asset_ledger_id_fkey", "product_ledger_id_fkey": + case "account_segment_id_fkey": + return pkg.ValidateBusinessError(constant.ErrSegmentIDNotFound, entityType) + case "account_ledger_id_fkey", "portfolio_ledger_id_fkey", "asset_ledger_id_fkey", "segment_ledger_id_fkey": return pkg.ValidateBusinessError(constant.ErrLedgerIDNotFound, entityType) - case "account_organization_id_fkey", "ledger_organization_id_fkey", "asset_organization_id_fkey", "portfolio_organization_id_fkey", "product_organization_id_fkey": + case "account_organization_id_fkey", "ledger_organization_id_fkey", "asset_organization_id_fkey", "portfolio_organization_id_fkey", "segment_organization_id_fkey": return pkg.ValidateBusinessError(constant.ErrOrganizationIDNotFound, entityType) default: return pgErr diff --git a/components/ledger/internal/services/query/get-all-metadata-products.go b/components/ledger/internal/services/query/get-all-metadata-segment.go similarity index 58% rename from components/ledger/internal/services/query/get-all-metadata-products.go rename to components/ledger/internal/services/query/get-all-metadata-segment.go index 0fd8b1770..e3a90c827 100644 --- a/components/ledger/internal/services/query/get-all-metadata-products.go +++ b/components/ledger/internal/services/query/get-all-metadata-segment.go @@ -15,21 +15,21 @@ import ( "github.com/google/uuid" ) -// GetAllMetadataProducts fetch all Products from the repository -func (uc *UseCase) GetAllMetadataProducts(ctx context.Context, organizationID, ledgerID uuid.UUID, filter http.QueryHeader) ([]*mmodel.Product, error) { +// GetAllMetadataSegments fetch all Segments from the repository +func (uc *UseCase) GetAllMetadataSegments(ctx context.Context, organizationID, ledgerID uuid.UUID, filter http.QueryHeader) ([]*mmodel.Segment, error) { logger := pkg.NewLoggerFromContext(ctx) tracer := pkg.NewTracerFromContext(ctx) - ctx, span := tracer.Start(ctx, "query.get_all_metadata_products") + ctx, span := tracer.Start(ctx, "query.get_all_metadata_segments") defer span.End() - logger.Infof("Retrieving products") + logger.Infof("Retrieving segments") - metadata, err := uc.MetadataRepo.FindList(ctx, reflect.TypeOf(mmodel.Product{}).Name(), filter) + metadata, err := uc.MetadataRepo.FindList(ctx, reflect.TypeOf(mmodel.Segment{}).Name(), filter) if err != nil || metadata == nil { mopentelemetry.HandleSpanError(&span, "Failed to get metadata on repo by query params", err) - return nil, pkg.ValidateBusinessError(constant.ErrNoProductsFound, reflect.TypeOf(mmodel.Product{}).Name()) + return nil, pkg.ValidateBusinessError(constant.ErrNoSegmentsFound, reflect.TypeOf(mmodel.Segment{}).Name()) } uuids := make([]uuid.UUID, len(metadata)) @@ -40,24 +40,24 @@ func (uc *UseCase) GetAllMetadataProducts(ctx context.Context, organizationID, l metadataMap[meta.EntityID] = meta.Data } - products, err := uc.ProductRepo.FindByIDs(ctx, organizationID, ledgerID, uuids) + segments, err := uc.SegmentRepo.FindByIDs(ctx, organizationID, ledgerID, uuids) if err != nil { - mopentelemetry.HandleSpanError(&span, "Failed to get products on repo by query params", err) + mopentelemetry.HandleSpanError(&span, "Failed to get segments on repo by query params", err) - logger.Errorf("Error getting products on repo by query params: %v", err) + logger.Errorf("Error getting segments on repo by query params: %v", err) if errors.Is(err, services.ErrDatabaseItemNotFound) { - return nil, pkg.ValidateBusinessError(constant.ErrNoProductsFound, reflect.TypeOf(mmodel.Product{}).Name()) + return nil, pkg.ValidateBusinessError(constant.ErrNoSegmentsFound, reflect.TypeOf(mmodel.Segment{}).Name()) } return nil, err } - for i := range products { - if data, ok := metadataMap[products[i].ID]; ok { - products[i].Metadata = data + for i := range segments { + if data, ok := metadataMap[segments[i].ID]; ok { + segments[i].Metadata = data } } - return products, nil + return segments, nil } diff --git a/components/ledger/internal/services/query/get-all-metadata-products_test.go b/components/ledger/internal/services/query/get-all-metadata-segment_test.go similarity index 79% rename from components/ledger/internal/services/query/get-all-metadata-products_test.go rename to components/ledger/internal/services/query/get-all-metadata-segment_test.go index 9b5af9666..c44b2752a 100644 --- a/components/ledger/internal/services/query/get-all-metadata-products_test.go +++ b/components/ledger/internal/services/query/get-all-metadata-segment_test.go @@ -3,12 +3,12 @@ package query import ( "context" "errors" + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/segment" "testing" "go.uber.org/mock/gomock" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/mongodb" - "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/product" "github.com/LerianStudio/midaz/pkg/mmodel" "github.com/LerianStudio/midaz/pkg/net/http" "github.com/google/uuid" @@ -16,15 +16,15 @@ import ( "github.com/stretchr/testify/assert" ) -func TestGetAllMetadataProducts(t *testing.T) { +func TestGetAllMetadataSegments(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() - mockProductRepo := product.NewMockRepository(ctrl) + mockSegmentRepo := segment.NewMockRepository(ctrl) mockMetadataRepo := mongodb.NewMockRepository(ctrl) uc := &UseCase{ - ProductRepo: mockProductRepo, + SegmentRepo: mockSegmentRepo, MetadataRepo: mockMetadataRepo, } @@ -35,10 +35,10 @@ func TestGetAllMetadataProducts(t *testing.T) { filter http.QueryHeader mockSetup func() expectErr bool - expectedResult []*mmodel.Product + expectedResult []*mmodel.Segment }{ { - name: "Success - Retrieve products with metadata", + name: "Success - Retrieve segments with metadata", organizationID: uuid.New(), ledgerID: uuid.New(), mockSetup: func() { @@ -48,15 +48,15 @@ func TestGetAllMetadataProducts(t *testing.T) { Return([]*mongodb.Metadata{ {EntityID: validUUID.String(), Data: map[string]any{"key": "value"}}, }, nil) - mockProductRepo.EXPECT(). + mockSegmentRepo.EXPECT(). FindByIDs(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Eq([]uuid.UUID{validUUID})). - Return([]*mmodel.Product{ - {ID: validUUID.String(), Name: "Test Product", Status: mmodel.Status{Code: "active"}}, + Return([]*mmodel.Segment{ + {ID: validUUID.String(), Name: "Test Segment", Status: mmodel.Status{Code: "active"}}, }, nil) }, expectErr: false, - expectedResult: []*mmodel.Product{ - {ID: "valid-uuid", Name: "Test Product", Status: mmodel.Status{Code: "active"}, Metadata: map[string]any{"key": "value"}}, + expectedResult: []*mmodel.Segment{ + {ID: "valid-uuid", Name: "Test Segment", Status: mmodel.Status{Code: "active"}, Metadata: map[string]any{"key": "value"}}, }, }, { @@ -72,7 +72,7 @@ func TestGetAllMetadataProducts(t *testing.T) { expectedResult: nil, }, { - name: "Error - Failed to retrieve products", + name: "Error - Failed to retrieve segments", organizationID: uuid.New(), ledgerID: uuid.New(), mockSetup: func() { @@ -82,7 +82,7 @@ func TestGetAllMetadataProducts(t *testing.T) { Return([]*mongodb.Metadata{ {EntityID: validUUID.String(), Data: map[string]any{"key": "value"}}, }, nil) - mockProductRepo.EXPECT(). + mockSegmentRepo.EXPECT(). FindByIDs(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Eq([]uuid.UUID{validUUID})). Return(nil, errors.New("database error")) }, @@ -96,7 +96,7 @@ func TestGetAllMetadataProducts(t *testing.T) { tt.mockSetup() ctx := context.Background() - result, err := uc.GetAllMetadataProducts(ctx, tt.organizationID, tt.ledgerID, tt.filter) + result, err := uc.GetAllMetadataSegments(ctx, tt.organizationID, tt.ledgerID, tt.filter) if tt.expectErr { assert.Error(t, err) diff --git a/components/ledger/internal/services/query/get-all-products.go b/components/ledger/internal/services/query/get-all-segment.go similarity index 51% rename from components/ledger/internal/services/query/get-all-products.go rename to components/ledger/internal/services/query/get-all-segment.go index ddb5ad508..484b2ee6b 100644 --- a/components/ledger/internal/services/query/get-all-products.go +++ b/components/ledger/internal/services/query/get-all-segment.go @@ -15,35 +15,35 @@ import ( "github.com/google/uuid" ) -// GetAllProducts fetch all Product from the repository -func (uc *UseCase) GetAllProducts(ctx context.Context, organizationID, ledgerID uuid.UUID, filter http.QueryHeader) ([]*mmodel.Product, error) { +// GetAllSegments fetch all Segment from the repository +func (uc *UseCase) GetAllSegments(ctx context.Context, organizationID, ledgerID uuid.UUID, filter http.QueryHeader) ([]*mmodel.Segment, error) { logger := pkg.NewLoggerFromContext(ctx) tracer := pkg.NewTracerFromContext(ctx) - ctx, span := tracer.Start(ctx, "query.get_all_products") + ctx, span := tracer.Start(ctx, "query.get_all_segments") defer span.End() - logger.Infof("Retrieving products") + logger.Infof("Retrieving segments") - products, err := uc.ProductRepo.FindAll(ctx, organizationID, ledgerID, filter.ToOffsetPagination()) + segments, err := uc.SegmentRepo.FindAll(ctx, organizationID, ledgerID, filter.ToOffsetPagination()) if err != nil { - mopentelemetry.HandleSpanError(&span, "Failed to get products on repo", err) + mopentelemetry.HandleSpanError(&span, "Failed to get segments on repo", err) - logger.Errorf("Error getting products on repo: %v", err) + logger.Errorf("Error getting segments on repo: %v", err) if errors.Is(err, services.ErrDatabaseItemNotFound) { - return nil, pkg.ValidateBusinessError(constant.ErrNoProductsFound, reflect.TypeOf(mmodel.Product{}).Name()) + return nil, pkg.ValidateBusinessError(constant.ErrNoSegmentsFound, reflect.TypeOf(mmodel.Segment{}).Name()) } return nil, err } - if products != nil { - metadata, err := uc.MetadataRepo.FindList(ctx, reflect.TypeOf(mmodel.Product{}).Name(), filter) + if segments != nil { + metadata, err := uc.MetadataRepo.FindList(ctx, reflect.TypeOf(mmodel.Segment{}).Name(), filter) if err != nil { mopentelemetry.HandleSpanError(&span, "Failed to get metadata on repo", err) - return nil, pkg.ValidateBusinessError(constant.ErrNoProductsFound, reflect.TypeOf(mmodel.Product{}).Name()) + return nil, pkg.ValidateBusinessError(constant.ErrNoSegmentsFound, reflect.TypeOf(mmodel.Segment{}).Name()) } metadataMap := make(map[string]map[string]any, len(metadata)) @@ -52,12 +52,12 @@ func (uc *UseCase) GetAllProducts(ctx context.Context, organizationID, ledgerID metadataMap[meta.EntityID] = meta.Data } - for i := range products { - if data, ok := metadataMap[products[i].ID]; ok { - products[i].Metadata = data + for i := range segments { + if data, ok := metadataMap[segments[i].ID]; ok { + segments[i].Metadata = data } } } - return products, nil + return segments, nil } diff --git a/components/ledger/internal/services/query/get-all-products_test.go b/components/ledger/internal/services/query/get-all-segment_test.go similarity index 78% rename from components/ledger/internal/services/query/get-all-products_test.go rename to components/ledger/internal/services/query/get-all-segment_test.go index a8e4943bd..1a2070b57 100644 --- a/components/ledger/internal/services/query/get-all-products_test.go +++ b/components/ledger/internal/services/query/get-all-segment_test.go @@ -8,7 +8,7 @@ import ( "go.uber.org/mock/gomock" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/mongodb" - "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/product" + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/segment" "github.com/LerianStudio/midaz/components/ledger/internal/services" "github.com/LerianStudio/midaz/pkg/mmodel" "github.com/LerianStudio/midaz/pkg/net/http" @@ -17,15 +17,15 @@ import ( "github.com/stretchr/testify/assert" ) -func TestGetAllProducts(t *testing.T) { +func TestGetAllSegments(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() - mockProductRepo := product.NewMockRepository(ctrl) + mockSegmentRepo := segment.NewMockRepository(ctrl) mockMetadataRepo := mongodb.NewMockRepository(ctrl) uc := &UseCase{ - ProductRepo: mockProductRepo, + SegmentRepo: mockSegmentRepo, MetadataRepo: mockMetadataRepo, } @@ -41,19 +41,19 @@ func TestGetAllProducts(t *testing.T) { filter http.QueryHeader mockSetup func() expectErr bool - expectedResult []*mmodel.Product + expectedResult []*mmodel.Segment }{ { - name: "Success - Retrieve products with metadata", + name: "Success - Retrieve segments with metadata", organizationID: uuid.New(), ledgerID: uuid.New(), filter: filter, mockSetup: func() { validUUID := uuid.New() - mockProductRepo.EXPECT(). + mockSegmentRepo.EXPECT(). FindAll(gomock.Any(), gomock.Any(), gomock.Any(), filter.ToOffsetPagination()). - Return([]*mmodel.Product{ - {ID: validUUID.String(), Name: "Test Product", Status: mmodel.Status{Code: "active"}}, + Return([]*mmodel.Segment{ + {ID: validUUID.String(), Name: "Test Segment", Status: mmodel.Status{Code: "active"}}, }, nil) mockMetadataRepo.EXPECT(). FindList(gomock.Any(), gomock.Any(), gomock.Any()). @@ -62,17 +62,17 @@ func TestGetAllProducts(t *testing.T) { }, nil) }, expectErr: false, - expectedResult: []*mmodel.Product{ - {ID: "valid-uuid", Name: "Test Product", Status: mmodel.Status{Code: "active"}, Metadata: map[string]any{"key": "value"}}, + expectedResult: []*mmodel.Segment{ + {ID: "valid-uuid", Name: "Test Segment", Status: mmodel.Status{Code: "active"}, Metadata: map[string]any{"key": "value"}}, }, }, { - name: "Error - No products found", + name: "Error - No segments found", organizationID: uuid.New(), ledgerID: uuid.New(), filter: http.QueryHeader{Limit: 10, Page: 1}, mockSetup: func() { - mockProductRepo.EXPECT(). + mockSegmentRepo.EXPECT(). FindAll(gomock.Any(), gomock.Any(), gomock.Any(), filter.ToOffsetPagination()). Return(nil, services.ErrDatabaseItemNotFound) }, @@ -86,10 +86,10 @@ func TestGetAllProducts(t *testing.T) { filter: http.QueryHeader{Limit: 10, Page: 1}, mockSetup: func() { validUUID := uuid.New() - mockProductRepo.EXPECT(). + mockSegmentRepo.EXPECT(). FindAll(gomock.Any(), gomock.Any(), gomock.Any(), filter.ToOffsetPagination()). - Return([]*mmodel.Product{ - {ID: validUUID.String(), Name: "Test Product", Status: mmodel.Status{Code: "active"}}, + Return([]*mmodel.Segment{ + {ID: validUUID.String(), Name: "Test Segment", Status: mmodel.Status{Code: "active"}}, }, nil) mockMetadataRepo.EXPECT(). FindList(gomock.Any(), gomock.Any(), gomock.Any()). @@ -105,7 +105,7 @@ func TestGetAllProducts(t *testing.T) { tt.mockSetup() ctx := context.Background() - result, err := uc.GetAllProducts(ctx, tt.organizationID, tt.ledgerID, tt.filter) + result, err := uc.GetAllSegments(ctx, tt.organizationID, tt.ledgerID, tt.filter) if tt.expectErr { assert.Error(t, err) diff --git a/components/ledger/internal/services/query/get-id-product.go b/components/ledger/internal/services/query/get-id-product.go deleted file mode 100644 index 0669aa4d4..000000000 --- a/components/ledger/internal/services/query/get-id-product.go +++ /dev/null @@ -1,56 +0,0 @@ -package query - -import ( - "context" - "errors" - "reflect" - - "github.com/LerianStudio/midaz/components/ledger/internal/services" - "github.com/LerianStudio/midaz/pkg" - "github.com/LerianStudio/midaz/pkg/constant" - "github.com/LerianStudio/midaz/pkg/mmodel" - "github.com/LerianStudio/midaz/pkg/mopentelemetry" - - "github.com/google/uuid" -) - -// GetProductByID get a Product from the repository by given id. -func (uc *UseCase) GetProductByID(ctx context.Context, organizationID, ledgerID, id uuid.UUID) (*mmodel.Product, error) { - logger := pkg.NewLoggerFromContext(ctx) - tracer := pkg.NewTracerFromContext(ctx) - - ctx, span := tracer.Start(ctx, "query.get_product_by_id") - defer span.End() - - logger.Infof("Retrieving product for id: %s", id.String()) - - product, err := uc.ProductRepo.Find(ctx, organizationID, ledgerID, id) - if err != nil { - mopentelemetry.HandleSpanError(&span, "Failed to get product on repo by id", err) - - logger.Errorf("Error getting product on repo by id: %v", err) - - if errors.Is(err, services.ErrDatabaseItemNotFound) { - return nil, pkg.ValidateBusinessError(constant.ErrProductIDNotFound, reflect.TypeOf(mmodel.Product{}).Name()) - } - - return nil, err - } - - if product != nil { - metadata, err := uc.MetadataRepo.FindByEntity(ctx, reflect.TypeOf(mmodel.Product{}).Name(), id.String()) - if err != nil { - mopentelemetry.HandleSpanError(&span, "Failed to get metadata on mongodb product", err) - - logger.Errorf("Error get metadata on mongodb product: %v", err) - - return nil, err - } - - if metadata != nil { - product.Metadata = metadata.Data - } - } - - return product, nil -} diff --git a/components/ledger/internal/services/query/get-id-segment.go b/components/ledger/internal/services/query/get-id-segment.go new file mode 100644 index 000000000..0f46ed363 --- /dev/null +++ b/components/ledger/internal/services/query/get-id-segment.go @@ -0,0 +1,56 @@ +package query + +import ( + "context" + "errors" + "reflect" + + "github.com/LerianStudio/midaz/components/ledger/internal/services" + "github.com/LerianStudio/midaz/pkg" + "github.com/LerianStudio/midaz/pkg/constant" + "github.com/LerianStudio/midaz/pkg/mmodel" + "github.com/LerianStudio/midaz/pkg/mopentelemetry" + + "github.com/google/uuid" +) + +// GetSegmentByID get a Segment from the repository by given id. +func (uc *UseCase) GetSegmentByID(ctx context.Context, organizationID, ledgerID, id uuid.UUID) (*mmodel.Segment, error) { + logger := pkg.NewLoggerFromContext(ctx) + tracer := pkg.NewTracerFromContext(ctx) + + ctx, span := tracer.Start(ctx, "query.get_segment_by_id") + defer span.End() + + logger.Infof("Retrieving segment for id: %s", id.String()) + + segment, err := uc.SegmentRepo.Find(ctx, organizationID, ledgerID, id) + if err != nil { + mopentelemetry.HandleSpanError(&span, "Failed to get segment on repo by id", err) + + logger.Errorf("Error getting segment on repo by id: %v", err) + + if errors.Is(err, services.ErrDatabaseItemNotFound) { + return nil, pkg.ValidateBusinessError(constant.ErrSegmentIDNotFound, reflect.TypeOf(mmodel.Segment{}).Name()) + } + + return nil, err + } + + if segment != nil { + metadata, err := uc.MetadataRepo.FindByEntity(ctx, reflect.TypeOf(mmodel.Segment{}).Name(), id.String()) + if err != nil { + mopentelemetry.HandleSpanError(&span, "Failed to get metadata on mongodb segment", err) + + logger.Errorf("Error get metadata on mongodb segment: %v", err) + + return nil, err + } + + if metadata != nil { + segment.Metadata = metadata.Data + } + } + + return segment, nil +} diff --git a/components/ledger/internal/services/query/get-id-product_test.go b/components/ledger/internal/services/query/get-id-segment_test.go similarity index 69% rename from components/ledger/internal/services/query/get-id-product_test.go rename to components/ledger/internal/services/query/get-id-segment_test.go index 1175d2d2b..4808358d5 100644 --- a/components/ledger/internal/services/query/get-id-product_test.go +++ b/components/ledger/internal/services/query/get-id-segment_test.go @@ -3,12 +3,12 @@ package query import ( "context" "errors" + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/segment" "testing" "go.uber.org/mock/gomock" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/mongodb" - "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/product" "github.com/LerianStudio/midaz/components/ledger/internal/services" "github.com/LerianStudio/midaz/pkg/mmodel" "github.com/google/uuid" @@ -16,15 +16,15 @@ import ( "github.com/stretchr/testify/assert" ) -func TestGetProductByID(t *testing.T) { +func TestGetSegmentByID(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() - mockProductRepo := product.NewMockRepository(ctrl) + mockSegmentRepo := segment.NewMockRepository(ctrl) mockMetadataRepo := mongodb.NewMockRepository(ctrl) uc := &UseCase{ - ProductRepo: mockProductRepo, + SegmentRepo: mockSegmentRepo, MetadataRepo: mockMetadataRepo, } @@ -32,40 +32,40 @@ func TestGetProductByID(t *testing.T) { name string organizationID uuid.UUID ledgerID uuid.UUID - productID uuid.UUID + segmentID uuid.UUID mockSetup func() expectErr bool - expectedResult *mmodel.Product + expectedResult *mmodel.Segment }{ { - name: "Success - Retrieve product with metadata", + name: "Success - Retrieve segment with metadata", organizationID: uuid.New(), ledgerID: uuid.New(), - productID: uuid.New(), + segmentID: uuid.New(), mockSetup: func() { - productID := uuid.New() - mockProductRepo.EXPECT(). + segmentID := uuid.New() + mockSegmentRepo.EXPECT(). Find(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). - Return(&mmodel.Product{ID: productID.String(), Name: "Test Product", Status: mmodel.Status{Code: "active"}}, nil) + Return(&mmodel.Segment{ID: segmentID.String(), Name: "Test Segment", Status: mmodel.Status{Code: "active"}}, nil) mockMetadataRepo.EXPECT(). FindByEntity(gomock.Any(), gomock.Any(), gomock.Any()). Return(&mongodb.Metadata{Data: map[string]any{"key": "value"}}, nil) }, expectErr: false, - expectedResult: &mmodel.Product{ + expectedResult: &mmodel.Segment{ ID: "valid-uuid", - Name: "Test Product", + Name: "Test Segment", Status: mmodel.Status{Code: "active"}, Metadata: map[string]any{"key": "value"}, }, }, { - name: "Error - Product not found", + name: "Error - Segment not found", organizationID: uuid.New(), ledgerID: uuid.New(), - productID: uuid.New(), + segmentID: uuid.New(), mockSetup: func() { - mockProductRepo.EXPECT(). + mockSegmentRepo.EXPECT(). Find(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). Return(nil, services.ErrDatabaseItemNotFound) }, @@ -76,12 +76,12 @@ func TestGetProductByID(t *testing.T) { name: "Error - Failed to retrieve metadata", organizationID: uuid.New(), ledgerID: uuid.New(), - productID: uuid.New(), + segmentID: uuid.New(), mockSetup: func() { - productID := uuid.New() - mockProductRepo.EXPECT(). + segmentID := uuid.New() + mockSegmentRepo.EXPECT(). Find(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). - Return(&mmodel.Product{ID: productID.String(), Name: "Test Product", Status: mmodel.Status{Code: "active"}}, nil) + Return(&mmodel.Segment{ID: segmentID.String(), Name: "Test Segment", Status: mmodel.Status{Code: "active"}}, nil) mockMetadataRepo.EXPECT(). FindByEntity(gomock.Any(), gomock.Any(), gomock.Any()). Return(nil, errors.New("metadata retrieval error")) @@ -96,7 +96,7 @@ func TestGetProductByID(t *testing.T) { tt.mockSetup() ctx := context.Background() - result, err := uc.GetProductByID(ctx, tt.organizationID, tt.ledgerID, tt.productID) + result, err := uc.GetSegmentByID(ctx, tt.organizationID, tt.ledgerID, tt.segmentID) if tt.expectErr { assert.Error(t, err) diff --git a/components/ledger/internal/services/query/query.go b/components/ledger/internal/services/query/query.go index 277f8f61d..3d5932493 100644 --- a/components/ledger/internal/services/query/query.go +++ b/components/ledger/internal/services/query/query.go @@ -7,7 +7,7 @@ import ( "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/ledger" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/organization" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/portfolio" - "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/product" + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/segment" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/rabbitmq" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/redis" ) @@ -20,8 +20,8 @@ type UseCase struct { // LedgerRepo provides an abstraction on top of the ledger data source. LedgerRepo ledger.Repository - // ProductRepo provides an abstraction on top of the product data source. - ProductRepo product.Repository + // SegmentRepo provides an abstraction on top of the segment data source. + SegmentRepo segment.Repository // PortfolioRepo provides an abstraction on top of the portfolio data source. PortfolioRepo portfolio.Repository diff --git a/components/ledger/migrations/000003_create_product_table.down.sql b/components/ledger/migrations/000003_create_product_table.down.sql deleted file mode 100644 index 6c3c4f5e8..000000000 --- a/components/ledger/migrations/000003_create_product_table.down.sql +++ /dev/null @@ -1 +0,0 @@ -DROP TABLE IF EXISTS product; diff --git a/components/ledger/migrations/000003_create_segment_table.down.sql b/components/ledger/migrations/000003_create_segment_table.down.sql new file mode 100644 index 000000000..9430cd5cb --- /dev/null +++ b/components/ledger/migrations/000003_create_segment_table.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS segment; diff --git a/components/ledger/migrations/000003_create_product_table.up.sql b/components/ledger/migrations/000003_create_segment_table.up.sql similarity index 94% rename from components/ledger/migrations/000003_create_product_table.up.sql rename to components/ledger/migrations/000003_create_segment_table.up.sql index cc6cca220..3cd7dc580 100644 --- a/components/ledger/migrations/000003_create_product_table.up.sql +++ b/components/ledger/migrations/000003_create_segment_table.up.sql @@ -1,4 +1,4 @@ -CREATE TABLE IF NOT EXISTS product +CREATE TABLE IF NOT EXISTS segment ( id UUID PRIMARY KEY NOT NULL, name TEXT, diff --git a/components/ledger/migrations/000005_create_account_table.up.sql b/components/ledger/migrations/000005_create_account_table.up.sql index 4ab65f56a..9c2871428 100644 --- a/components/ledger/migrations/000005_create_account_table.up.sql +++ b/components/ledger/migrations/000005_create_account_table.up.sql @@ -8,7 +8,7 @@ CREATE TABLE IF NOT EXISTS account organization_id UUID NOT NULL, ledger_id UUID NOT NULL, portfolio_id UUID, - product_id UUID, + segment_id UUID, available_balance NUMERIC NOT NULL, on_hold_balance NUMERIC NOT NULL, balance_scale NUMERIC NOT NULL, @@ -26,5 +26,5 @@ CREATE TABLE IF NOT EXISTS account FOREIGN KEY (organization_id) REFERENCES organization (id), FOREIGN KEY (ledger_id) REFERENCES ledger (id), FOREIGN KEY (portfolio_id) REFERENCES portfolio (id), - FOREIGN KEY (product_id) REFERENCES product (id) + FOREIGN KEY (segment_id) REFERENCES segment (id) ); \ No newline at end of file diff --git a/components/mdz/.env.example b/components/mdz/.env.example index 1bfe3a5d4..819f62cfc 100644 --- a/components/mdz/.env.example +++ b/components/mdz/.env.example @@ -2,4 +2,4 @@ CLIENT_ID=9670e0ca55a29a466d31 CLIENT_SECRET=dd03f916cacf4a98c6a413d9c38ba102dce436a9 URL_API_AUTH=http://127.0.0.1:8080 URL_API_LEDGER=http://127.0.0.1:3000 -VERSION=v1.46.0 +VERSION=v1.47.0 diff --git a/components/mdz/internal/domain/repository/product.go b/components/mdz/internal/domain/repository/product.go deleted file mode 100644 index 430c56b62..000000000 --- a/components/mdz/internal/domain/repository/product.go +++ /dev/null @@ -1,11 +0,0 @@ -package repository - -import "github.com/LerianStudio/midaz/pkg/mmodel" - -type Product interface { - Create(organizationID, ledgerID string, inp mmodel.CreateProductInput) (*mmodel.Product, error) - Get(organizationID, ledgerID string, limit, page int, SortOrder, StartDate, EndDate string) (*mmodel.Products, error) - GetByID(organizationID, ledgerID, productID string) (*mmodel.Product, error) - Update(organizationID, ledgerID, productID string, inp mmodel.UpdateProductInput) (*mmodel.Product, error) - Delete(organizationID, ledgerID, productID string) error -} diff --git a/components/mdz/internal/domain/repository/product_mock.go b/components/mdz/internal/domain/repository/product_mock.go deleted file mode 100644 index 781e1f838..000000000 --- a/components/mdz/internal/domain/repository/product_mock.go +++ /dev/null @@ -1,115 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: /home/max/Workspace/midaz/components/mdz/internal/domain/repository/product.go -// -// Generated by this command: -// -// mockgen -source=/home/max/Workspace/midaz/components/mdz/internal/domain/repository/product.go -destination=/home/max/Workspace/midaz/components/mdz/internal/domain/repository/product_mock.go -package repository -// - -// Package repository is a generated GoMock package. -package repository - -import ( - reflect "reflect" - - mmodel "github.com/LerianStudio/midaz/pkg/mmodel" - gomock "go.uber.org/mock/gomock" -) - -// MockProduct is a mock of Product interface. -type MockProduct struct { - ctrl *gomock.Controller - recorder *MockProductMockRecorder - isgomock struct{} -} - -// MockProductMockRecorder is the mock recorder for MockProduct. -type MockProductMockRecorder struct { - mock *MockProduct -} - -// NewMockProduct creates a new mock instance. -func NewMockProduct(ctrl *gomock.Controller) *MockProduct { - mock := &MockProduct{ctrl: ctrl} - mock.recorder = &MockProductMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockProduct) EXPECT() *MockProductMockRecorder { - return m.recorder -} - -// Create mocks base method. -func (m *MockProduct) Create(organizationID, ledgerID string, inp mmodel.CreateProductInput) (*mmodel.Product, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Create", organizationID, ledgerID, inp) - ret0, _ := ret[0].(*mmodel.Product) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Create indicates an expected call of Create. -func (mr *MockProductMockRecorder) Create(organizationID, ledgerID, inp any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Create", reflect.TypeOf((*MockProduct)(nil).Create), organizationID, ledgerID, inp) -} - -// Delete mocks base method. -func (m *MockProduct) Delete(organizationID, ledgerID, productID string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Delete", organizationID, ledgerID, productID) - ret0, _ := ret[0].(error) - return ret0 -} - -// Delete indicates an expected call of Delete. -func (mr *MockProductMockRecorder) Delete(organizationID, ledgerID, productID any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delete", reflect.TypeOf((*MockProduct)(nil).Delete), organizationID, ledgerID, productID) -} - -// Get mocks base method. -func (m *MockProduct) Get(organizationID, ledgerID string, limit, page int, SortOrder, StartDate, EndDate string) (*mmodel.Products, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Get", organizationID, ledgerID, limit, page, SortOrder, StartDate, EndDate) - ret0, _ := ret[0].(*mmodel.Products) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Get indicates an expected call of Get. -func (mr *MockProductMockRecorder) Get(organizationID, ledgerID, limit, page, SortOrder, StartDate, EndDate any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockProduct)(nil).Get), organizationID, ledgerID, limit, page, SortOrder, StartDate, EndDate) -} - -// GetByID mocks base method. -func (m *MockProduct) GetByID(organizationID, ledgerID, productID string) (*mmodel.Product, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetByID", organizationID, ledgerID, productID) - ret0, _ := ret[0].(*mmodel.Product) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetByID indicates an expected call of GetByID. -func (mr *MockProductMockRecorder) GetByID(organizationID, ledgerID, productID any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByID", reflect.TypeOf((*MockProduct)(nil).GetByID), organizationID, ledgerID, productID) -} - -// Update mocks base method. -func (m *MockProduct) Update(organizationID, ledgerID, productID string, inp mmodel.UpdateProductInput) (*mmodel.Product, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Update", organizationID, ledgerID, productID, inp) - ret0, _ := ret[0].(*mmodel.Product) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Update indicates an expected call of Update. -func (mr *MockProductMockRecorder) Update(organizationID, ledgerID, productID, inp any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockProduct)(nil).Update), organizationID, ledgerID, productID, inp) -} diff --git a/components/mdz/internal/domain/repository/segment.go b/components/mdz/internal/domain/repository/segment.go new file mode 100644 index 000000000..ff42d49dc --- /dev/null +++ b/components/mdz/internal/domain/repository/segment.go @@ -0,0 +1,11 @@ +package repository + +import "github.com/LerianStudio/midaz/pkg/mmodel" + +type Segment interface { + Create(organizationID, ledgerID string, inp mmodel.CreateSegmentInput) (*mmodel.Segment, error) + Get(organizationID, ledgerID string, limit, page int, SortOrder, StartDate, EndDate string) (*mmodel.Segments, error) + GetByID(organizationID, ledgerID, segmentID string) (*mmodel.Segment, error) + Update(organizationID, ledgerID, segmentID string, inp mmodel.UpdateSegmentInput) (*mmodel.Segment, error) + Delete(organizationID, ledgerID, segmentID string) error +} diff --git a/components/mdz/internal/domain/repository/segment_mock.go b/components/mdz/internal/domain/repository/segment_mock.go new file mode 100644 index 000000000..0ed013466 --- /dev/null +++ b/components/mdz/internal/domain/repository/segment_mock.go @@ -0,0 +1,114 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: segment.go +// +// Generated by this command: +// +// mockgen -source=segment.go -destination=segment_mock.go -package repository +// + +// Package repository is a generated GoMock package. +package repository + +import ( + reflect "reflect" + + mmodel "github.com/LerianStudio/midaz/pkg/mmodel" + gomock "go.uber.org/mock/gomock" +) + +// MockSegment is a mock of Segment interface. +type MockSegment struct { + ctrl *gomock.Controller + recorder *MockSegmentMockRecorder +} + +// MockSegmentMockRecorder is the mock recorder for MockSegment. +type MockSegmentMockRecorder struct { + mock *MockSegment +} + +// NewMockSegment creates a new mock instance. +func NewMockSegment(ctrl *gomock.Controller) *MockSegment { + mock := &MockSegment{ctrl: ctrl} + mock.recorder = &MockSegmentMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockSegment) EXPECT() *MockSegmentMockRecorder { + return m.recorder +} + +// Create mocks base method. +func (m *MockSegment) Create(organizationID, ledgerID string, inp mmodel.CreateSegmentInput) (*mmodel.Segment, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Create", organizationID, ledgerID, inp) + ret0, _ := ret[0].(*mmodel.Segment) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Create indicates an expected call of Create. +func (mr *MockSegmentMockRecorder) Create(organizationID, ledgerID, inp any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Create", reflect.TypeOf((*MockSegment)(nil).Create), organizationID, ledgerID, inp) +} + +// Delete mocks base method. +func (m *MockSegment) Delete(organizationID, ledgerID, segmentID string) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Delete", organizationID, ledgerID, segmentID) + ret0, _ := ret[0].(error) + return ret0 +} + +// Delete indicates an expected call of Delete. +func (mr *MockSegmentMockRecorder) Delete(organizationID, ledgerID, segmentID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delete", reflect.TypeOf((*MockSegment)(nil).Delete), organizationID, ledgerID, segmentID) +} + +// Get mocks base method. +func (m *MockSegment) Get(organizationID, ledgerID string, limit, page int, SortOrder, StartDate, EndDate string) (*mmodel.Segments, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Get", organizationID, ledgerID, limit, page, SortOrder, StartDate, EndDate) + ret0, _ := ret[0].(*mmodel.Segments) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Get indicates an expected call of Get. +func (mr *MockSegmentMockRecorder) Get(organizationID, ledgerID, limit, page, SortOrder, StartDate, EndDate any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockSegment)(nil).Get), organizationID, ledgerID, limit, page, SortOrder, StartDate, EndDate) +} + +// GetByID mocks base method. +func (m *MockSegment) GetByID(organizationID, ledgerID, segmentID string) (*mmodel.Segment, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetByID", organizationID, ledgerID, segmentID) + ret0, _ := ret[0].(*mmodel.Segment) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetByID indicates an expected call of GetByID. +func (mr *MockSegmentMockRecorder) GetByID(organizationID, ledgerID, segmentID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByID", reflect.TypeOf((*MockSegment)(nil).GetByID), organizationID, ledgerID, segmentID) +} + +// Update mocks base method. +func (m *MockSegment) Update(organizationID, ledgerID, segmentID string, inp mmodel.UpdateSegmentInput) (*mmodel.Segment, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Update", organizationID, ledgerID, segmentID, inp) + ret0, _ := ret[0].(*mmodel.Segment) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Update indicates an expected call of Update. +func (mr *MockSegmentMockRecorder) Update(organizationID, ledgerID, segmentID, inp any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockSegment)(nil).Update), organizationID, ledgerID, segmentID, inp) +} diff --git a/components/mdz/internal/rest/.fixtures/account_response_create.json b/components/mdz/internal/rest/.fixtures/account_response_create.json index c6a1f6238..7a1afe463 100644 --- a/components/mdz/internal/rest/.fixtures/account_response_create.json +++ b/components/mdz/internal/rest/.fixtures/account_response_create.json @@ -7,7 +7,7 @@ "organizationId": "01933f94-67b1-794c-bb13-6b75aed7591a", "ledgerId": "01933f94-8a8f-7a1e-b4ab-98f35a5f8d61", "portfolioId": "01933f94-d329-76fe-8de0-40559c7b282d", - "productId": "01933f94-fbdf-7756-af37-ef32d0e3268b", + "segmentId": "01933f94-fbdf-7756-af37-ef32d0e3268b", "balance": { "available": 0, "onHold": 0, diff --git a/components/mdz/internal/rest/.fixtures/account_response_describe.json b/components/mdz/internal/rest/.fixtures/account_response_describe.json index 1bd8ecb1c..7fa2884ad 100644 --- a/components/mdz/internal/rest/.fixtures/account_response_describe.json +++ b/components/mdz/internal/rest/.fixtures/account_response_describe.json @@ -7,7 +7,7 @@ "organizationId": "01933f94-67b1-794c-bb13-6b75aed7591a", "ledgerId": "01933f94-8a8f-7a1e-b4ab-98f35a5f8d61", "portfolioId": "01933f94-d329-76fe-8de0-40559c7b282d", - "productId": "01933f94-fbdf-7756-af37-ef32d0e3268b", + "segmentId": "01933f94-fbdf-7756-af37-ef32d0e3268b", "balance": { "available": 0, "onHold": 0, diff --git a/components/mdz/internal/rest/.fixtures/account_response_list.json b/components/mdz/internal/rest/.fixtures/account_response_list.json index 2b2f86e7c..a9ac6781e 100644 --- a/components/mdz/internal/rest/.fixtures/account_response_list.json +++ b/components/mdz/internal/rest/.fixtures/account_response_list.json @@ -9,7 +9,7 @@ "organizationId": "01933f94-67b1-794c-bb13-6b75aed7591a", "ledgerId": "01933f94-8a8f-7a1e-b4ab-98f35a5f8d61", "portfolioId": "01933f94-d329-76fe-8de0-40559c7b282d", - "productId": "01933f94-fbdf-7756-af37-ef32d0e3268b", + "segmentId": "01933f94-fbdf-7756-af37-ef32d0e3268b", "balance": { "available": 0, "onHold": 0, @@ -41,7 +41,7 @@ "organizationId": "01933f94-67b1-794c-bb13-6b75aed7591a", "ledgerId": "01933f94-8a8f-7a1e-b4ab-98f35a5f8d61", "portfolioId": "01933f94-d329-76fe-8de0-40559c7b282d", - "productId": "01933f94-fbdf-7756-af37-ef32d0e3268b", + "segmentId": "01933f94-fbdf-7756-af37-ef32d0e3268b", "balance": { "available": 0, "onHold": 0, diff --git a/components/mdz/internal/rest/.fixtures/account_response_update.json b/components/mdz/internal/rest/.fixtures/account_response_update.json index 8d153a224..606046d49 100644 --- a/components/mdz/internal/rest/.fixtures/account_response_update.json +++ b/components/mdz/internal/rest/.fixtures/account_response_update.json @@ -7,7 +7,7 @@ "organizationId": "01933f94-67b1-794c-bb13-6b75aed7591a", "ledgerId": "01933f94-8a8f-7a1e-b4ab-98f35a5f8d61", "portfolioId": "01933f94-d329-76fe-8de0-40559c7b282d", - "productId": "01933f94-fbdf-7756-af37-ef32d0e3268b", + "segmentId": "01933f94-fbdf-7756-af37-ef32d0e3268b", "balance": { "available": 0, "onHold": 0, diff --git a/components/mdz/internal/rest/.fixtures/product_response_create.json b/components/mdz/internal/rest/.fixtures/segment_response_create.json similarity index 85% rename from components/mdz/internal/rest/.fixtures/product_response_create.json rename to components/mdz/internal/rest/.fixtures/segment_response_create.json index 866c1b746..a2b36aac1 100644 --- a/components/mdz/internal/rest/.fixtures/product_response_create.json +++ b/components/mdz/internal/rest/.fixtures/segment_response_create.json @@ -1,11 +1,11 @@ { "id": "0193271b-877f-7c98-a5a6-43b664d68982", - "name": "Product Refined Cotton Chair", + "name": "Segment Refined Cotton Chair", "ledgerId": "01932715-9f93-7432-90c3-4352bcfe464d", "organizationId": "01931b04-964a-7caa-a422-c29a95387c00", "status": { "code": "ACTIVE", - "description": "Teste Product" + "description": "Teste Segment" }, "createdAt": "2024-11-13T19:58:55.868976395Z", "updatedAt": "2024-11-13T19:58:55.868979258Z", diff --git a/components/mdz/internal/rest/.fixtures/product_response_get_by_id.json b/components/mdz/internal/rest/.fixtures/segment_response_get_by_id.json similarity index 80% rename from components/mdz/internal/rest/.fixtures/product_response_get_by_id.json rename to components/mdz/internal/rest/.fixtures/segment_response_get_by_id.json index 5a6c7e157..72b50f31d 100644 --- a/components/mdz/internal/rest/.fixtures/product_response_get_by_id.json +++ b/components/mdz/internal/rest/.fixtures/segment_response_get_by_id.json @@ -1,11 +1,11 @@ { "id": "01932727-1b5a-7540-98c0-6521ffe78ce6", - "name": "Product Licensed Concrete Hat", + "name": "Segment Licensed Concrete Hat", "ledgerId": "01932715-9f93-7432-90c3-4352bcfe464d", "organizationId": "01931b04-964a-7caa-a422-c29a95387c00", "status": { "code": "ACTIVE", - "description": "Teste Product" + "description": "Teste Segment" }, "createdAt": "2024-11-13T20:11:34.617671Z", "updatedAt": "2024-11-13T20:11:34.617674Z", diff --git a/components/mdz/internal/rest/.fixtures/product_response_list.json b/components/mdz/internal/rest/.fixtures/segment_response_list.json similarity index 84% rename from components/mdz/internal/rest/.fixtures/product_response_list.json rename to components/mdz/internal/rest/.fixtures/segment_response_list.json index 527896e02..2a9dc8032 100644 --- a/components/mdz/internal/rest/.fixtures/product_response_list.json +++ b/components/mdz/internal/rest/.fixtures/segment_response_list.json @@ -2,12 +2,12 @@ "items": [ { "id": "01932727-1b5a-7540-98c0-6521ffe78ce6", - "name": "Product Licensed Concrete Hat", + "name": "Segment Licensed Concrete Hat", "ledgerId": "01932715-9f93-7432-90c3-4352bcfe464d", "organizationId": "01931b04-964a-7caa-a422-c29a95387c00", "status": { "code": "ACTIVE", - "description": "Teste Product" + "description": "Teste Segment" }, "createdAt": "2024-11-13T20:11:34.617671Z", "updatedAt": "2024-11-13T20:11:34.617674Z", @@ -15,12 +15,12 @@ }, { "id": "0193271b-877f-7c98-a5a6-43b664d68982", - "name": "Product Refined Cotton Chair", + "name": "Segment Refined Cotton Chair", "ledgerId": "01932715-9f93-7432-90c3-4352bcfe464d", "organizationId": "01931b04-964a-7caa-a422-c29a95387c00", "status": { "code": "ACTIVE", - "description": "Teste Product" + "description": "Teste Segment" }, "createdAt": "2024-11-13T19:58:55.868976Z", "updatedAt": "2024-11-13T19:58:55.868979Z", diff --git a/components/mdz/internal/rest/.fixtures/product_response_update.json b/components/mdz/internal/rest/.fixtures/segment_response_update.json similarity index 82% rename from components/mdz/internal/rest/.fixtures/product_response_update.json rename to components/mdz/internal/rest/.fixtures/segment_response_update.json index d62f7f37d..dba15a99b 100644 --- a/components/mdz/internal/rest/.fixtures/product_response_update.json +++ b/components/mdz/internal/rest/.fixtures/segment_response_update.json @@ -1,11 +1,11 @@ { "id": "01932727-1b5a-7540-98c0-6521ffe78ce6", - "name": "Product Practical Metal Sausages BLOCKED", + "name": "Segment Practical Metal Sausages BLOCKED", "ledgerId": "01932715-9f93-7432-90c3-4352bcfe464d", "organizationId": "01931b04-964a-7caa-a422-c29a95387c00", "status": { "code": "BLOCKED", - "description": "Teste Product BLOCKED" + "description": "Teste Segment BLOCKED" }, "createdAt": "2024-11-13T20:11:34.617671Z", "updatedAt": "2024-11-13T20:16:30.48922Z", diff --git a/components/mdz/internal/rest/product.go b/components/mdz/internal/rest/segment.go similarity index 68% rename from components/mdz/internal/rest/product.go rename to components/mdz/internal/rest/segment.go index 609b14046..faa384b75 100644 --- a/components/mdz/internal/rest/product.go +++ b/components/mdz/internal/rest/segment.go @@ -11,17 +11,17 @@ import ( "github.com/LerianStudio/midaz/pkg/mmodel" ) -type product struct { +type segment struct { Factory *factory.Factory } -func (r *product) Create(organizationID, ledgerID string, inp mmodel.CreateProductInput) (*mmodel.Product, error) { +func (r *segment) Create(organizationID, ledgerID string, inp mmodel.CreateSegmentInput) (*mmodel.Segment, 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/products", + uri := fmt.Sprintf("%s/v1/organizations/%s/ledgers/%s/segments", r.Factory.Env.URLAPILedger, organizationID, ledgerID) req, err := http.NewRequest(http.MethodPost, uri, bytes.NewBuffer(jsonData)) @@ -43,16 +43,16 @@ func (r *product) Create(organizationID, ledgerID string, inp mmodel.CreateProdu return nil, err } - var productResp mmodel.Product - if err := json.NewDecoder(resp.Body).Decode(&productResp); err != nil { + var segmentResp mmodel.Segment + if err := json.NewDecoder(resp.Body).Decode(&segmentResp); err != nil { return nil, errors.New("decoding response JSON:" + err.Error()) } - return &productResp, nil + return &segmentResp, nil } -func (r *product) Get(organizationID, ledgerID string, limit, page int, sortOrder, startDate, endDate string) (*mmodel.Products, error) { - baseURL := fmt.Sprintf("%s/v1/organizations/%s/ledgers/%s/products", +func (r *segment) Get(organizationID, ledgerID string, limit, page int, sortOrder, startDate, endDate string) (*mmodel.Segments, error) { + baseURL := fmt.Sprintf("%s/v1/organizations/%s/ledgers/%s/segments", r.Factory.Env.URLAPILedger, organizationID, ledgerID) reqURL, err := BuildPaginatedURL(baseURL, limit, page, sortOrder, startDate, endDate) @@ -78,17 +78,17 @@ func (r *product) Get(organizationID, ledgerID string, limit, page int, sortOrde return nil, err } - var productsResp mmodel.Products - if err := json.NewDecoder(resp.Body).Decode(&productsResp); err != nil { + var segmentsResp mmodel.Segments + if err := json.NewDecoder(resp.Body).Decode(&segmentsResp); err != nil { return nil, errors.New("decoding response JSON:" + err.Error()) } - return &productsResp, nil + return &segmentsResp, nil } -func (r *product) GetByID(organizationID, ledgerID, productID string) (*mmodel.Product, error) { - uri := fmt.Sprintf("%s/v1/organizations/%s/ledgers/%s/products/%s", - r.Factory.Env.URLAPILedger, organizationID, ledgerID, productID) +func (r *segment) GetByID(organizationID, ledgerID, segmentID string) (*mmodel.Segment, error) { + uri := fmt.Sprintf("%s/v1/organizations/%s/ledgers/%s/segments/%s", + r.Factory.Env.URLAPILedger, organizationID, ledgerID, segmentID) req, err := http.NewRequest(http.MethodGet, uri, nil) if err != nil { @@ -108,24 +108,24 @@ func (r *product) GetByID(organizationID, ledgerID, productID string) (*mmodel.P return nil, err } - var productResp mmodel.Product - if err := json.NewDecoder(resp.Body).Decode(&productResp); err != nil { + var segmentResp mmodel.Segment + if err := json.NewDecoder(resp.Body).Decode(&segmentResp); err != nil { return nil, errors.New("decoding response JSON:" + err.Error()) } - return &productResp, nil + return &segmentResp, nil } -func (r *product) Update( - organizationID, ledgerID, productID string, inp mmodel.UpdateProductInput, -) (*mmodel.Product, error) { +func (r *segment) Update( + organizationID, ledgerID, segmentID string, inp mmodel.UpdateSegmentInput, +) (*mmodel.Segment, 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/products/%s", - r.Factory.Env.URLAPILedger, organizationID, ledgerID, productID) + uri := fmt.Sprintf("%s/v1/organizations/%s/ledgers/%s/segments/%s", + r.Factory.Env.URLAPILedger, organizationID, ledgerID, segmentID) req, err := http.NewRequest(http.MethodPatch, uri, bytes.NewBuffer(jsonData)) if err != nil { @@ -145,17 +145,17 @@ func (r *product) Update( return nil, err } - var productResp mmodel.Product - if err := json.NewDecoder(resp.Body).Decode(&productResp); err != nil { + var segmentResp mmodel.Segment + if err := json.NewDecoder(resp.Body).Decode(&segmentResp); err != nil { return nil, errors.New("decoding response JSON:" + err.Error()) } - return &productResp, nil + return &segmentResp, nil } -func (r *product) Delete(organizationID, ledgerID, productID string) error { - uri := fmt.Sprintf("%s/v1/organizations/%s/ledgers/%s/products/%s", - r.Factory.Env.URLAPILedger, organizationID, ledgerID, productID) +func (r *segment) Delete(organizationID, ledgerID, segmentID string) error { + uri := fmt.Sprintf("%s/v1/organizations/%s/ledgers/%s/segments/%s", + r.Factory.Env.URLAPILedger, organizationID, ledgerID, segmentID) req, err := http.NewRequest(http.MethodDelete, uri, nil) if err != nil { @@ -179,6 +179,6 @@ func (r *product) Delete(organizationID, ledgerID, productID string) error { return nil } -func NewProduct(f *factory.Factory) *product { - return &product{f} +func NewSegment(f *factory.Factory) *segment { + return &segment{f} } diff --git a/components/mdz/internal/rest/product_test.go b/components/mdz/internal/rest/segment_test.go similarity index 75% rename from components/mdz/internal/rest/product_test.go rename to components/mdz/internal/rest/segment_test.go index b06548e1d..370c4b50e 100644 --- a/components/mdz/internal/rest/product_test.go +++ b/components/mdz/internal/rest/segment_test.go @@ -16,14 +16,14 @@ import ( "github.com/stretchr/testify/assert" ) -func Test_product_Create(t *testing.T) { - productID := "0193271b-877f-7c98-a5a6-43b664d68982" +func Test_segment_Create(t *testing.T) { + segmentID := "0193271b-877f-7c98-a5a6-43b664d68982" ledgerID := "01932715-9f93-7432-90c3-4352bcfe464d" organizationID := "01931b04-964a-7caa-a422-c29a95387c00" - name := "Product Refined Cotton Chair" + name := "Segment Refined Cotton Chair" code := "ACTIVE" - description := ptr.StringPtr("Teste Product") + description := ptr.StringPtr("Teste Segment") metadata := map[string]any{ "bitcoin": "3g9ofZcD7KRWL44BWdNa3PyM4PfzgqDG5P", @@ -31,7 +31,7 @@ func Test_product_Create(t *testing.T) { "boolean": true, } - input := mmodel.CreateProductInput{ + input := mmodel.CreateSegmentInput{ Name: name, Status: mmodel.Status{ Code: code, @@ -40,8 +40,8 @@ func Test_product_Create(t *testing.T) { Metadata: metadata, } - expectedResult := &mmodel.Product{ - ID: productID, + expectedResult := &mmodel.Segment{ + ID: segmentID, Name: name, LedgerID: ledgerID, OrganizationID: organizationID, @@ -58,11 +58,11 @@ func Test_product_Create(t *testing.T) { URIAPILedger := "http://127.0.0.1:3000" - uri := fmt.Sprintf("%s/v1/organizations/%s/ledgers/%s/products", + uri := fmt.Sprintf("%s/v1/organizations/%s/ledgers/%s/segments", URIAPILedger, organizationID, ledgerID) httpmock.RegisterResponder(http.MethodPost, uri, - mockutil.MockResponseFromFile(http.StatusCreated, "./.fixtures/product_response_create.json")) + mockutil.MockResponseFromFile(http.StatusCreated, "./.fixtures/segment_response_create.json")) factory := &factory.Factory{ HTTPClient: client, @@ -71,9 +71,9 @@ func Test_product_Create(t *testing.T) { }, } - productServ := NewProduct(factory) + segmentServ := NewSegment(factory) - result, err := productServ.Create(organizationID, ledgerID, input) + result, err := segmentServ.Create(organizationID, ledgerID, input) assert.NoError(t, err) assert.NotNil(t, result) @@ -89,23 +89,23 @@ func Test_product_Create(t *testing.T) { assert.Equal(t, 1, info["POST "+uri]) } -func Test_product_Get(t *testing.T) { +func Test_segment_Get(t *testing.T) { organizationID := "01931b04-964a-7caa-a422-c29a95387c00" ledgerID := "01931b04-c2d1-7a41-83ac-c5d6d8a3c22c" limit := 2 page := 1 - expectedResult := mmodel.Products{ + expectedResult := mmodel.Segments{ Page: page, Limit: limit, - Items: []mmodel.Product{ + Items: []mmodel.Segment{ { ID: "01932727-1b5a-7540-98c0-6521ffe78ce6", - Name: "Product Licensed Concrete Hat", + Name: "Segment Licensed Concrete Hat", Status: mmodel.Status{ Code: "ACTIVE", - Description: ptr.StringPtr("Teste Product"), + Description: ptr.StringPtr("Teste Segment"), }, OrganizationID: organizationID, LedgerID: ledgerID, @@ -118,7 +118,7 @@ func Test_product_Get(t *testing.T) { Name: "Toy30 Portfolio", Status: mmodel.Status{ Code: "ACTIVE", - Description: ptr.StringPtr("Teste Product"), + Description: ptr.StringPtr("Teste Segment"), }, OrganizationID: organizationID, LedgerID: ledgerID, @@ -140,11 +140,11 @@ func Test_product_Get(t *testing.T) { URIAPILedger := "http://127.0.0.1:3000" - uri := fmt.Sprintf("%s/v1/organizations/%s/ledgers/%s/products?limit=%d&page=%d", + uri := fmt.Sprintf("%s/v1/organizations/%s/ledgers/%s/segments?limit=%d&page=%d", URIAPILedger, organizationID, ledgerID, limit, page) httpmock.RegisterResponder(http.MethodGet, uri, - mockutil.MockResponseFromFile(http.StatusOK, "./.fixtures/product_response_list.json")) + mockutil.MockResponseFromFile(http.StatusOK, "./.fixtures/segment_response_list.json")) factory := &factory.Factory{ HTTPClient: client, @@ -153,9 +153,9 @@ func Test_product_Get(t *testing.T) { }, } - product := NewProduct(factory) + segment := NewSegment(factory) - result, err := product.Get(organizationID, ledgerID, limit, page, "", "", "") + result, err := segment.Get(organizationID, ledgerID, limit, page, "", "", "") assert.NoError(t, err) assert.NotNil(t, result) @@ -172,21 +172,21 @@ func Test_product_Get(t *testing.T) { assert.Equal(t, 1, info["GET "+uri]) } -func Test_product_GetByID(t *testing.T) { - productID := "01932727-1b5a-7540-98c0-6521ffe78ce6" +func Test_segment_GetByID(t *testing.T) { + segmentID := "01932727-1b5a-7540-98c0-6521ffe78ce6" ledgerID := "01932715-9f93-7432-90c3-4352bcfe464d" organizationID := "01931b04-964a-7caa-a422-c29a95387c00" URIAPILedger := "http://127.0.0.1:3000" - expectedResult := &mmodel.Product{ - ID: productID, - Name: "Product Licensed Concrete Hat", + expectedResult := &mmodel.Segment{ + ID: segmentID, + Name: "Segment Licensed Concrete Hat", LedgerID: ledgerID, OrganizationID: organizationID, Status: mmodel.Status{ Code: "ACTIVE", - Description: ptr.StringPtr("Teste Product"), + Description: ptr.StringPtr("Teste Segment"), }, CreatedAt: time.Date(2024, 11, 13, 20, 11, 34, 617671000, time.UTC), UpdatedAt: time.Date(2024, 11, 13, 20, 11, 34, 617674000, time.UTC), @@ -197,11 +197,11 @@ func Test_product_GetByID(t *testing.T) { httpmock.ActivateNonDefault(client) defer httpmock.DeactivateAndReset() - uri := fmt.Sprintf("%s/v1/organizations/%s/ledgers/%s/products/%s", - URIAPILedger, organizationID, ledgerID, productID) + uri := fmt.Sprintf("%s/v1/organizations/%s/ledgers/%s/segments/%s", + URIAPILedger, organizationID, ledgerID, segmentID) httpmock.RegisterResponder(http.MethodGet, uri, - mockutil.MockResponseFromFile(http.StatusOK, "./.fixtures/product_response_get_by_id.json")) + mockutil.MockResponseFromFile(http.StatusOK, "./.fixtures/segment_response_get_by_id.json")) factory := &factory.Factory{ HTTPClient: client, @@ -210,9 +210,9 @@ func Test_product_GetByID(t *testing.T) { }, } - product := NewProduct(factory) + segment := NewSegment(factory) - result, err := product.GetByID(organizationID, ledgerID, productID) + result, err := segment.GetByID(organizationID, ledgerID, segmentID) assert.NoError(t, err) assert.NotNil(t, result) assert.Equal(t, expectedResult.ID, result.ID) @@ -230,13 +230,13 @@ func Test_product_GetByID(t *testing.T) { assert.Equal(t, 1, info["GET "+uri]) } -func Test_product_Update(t *testing.T) { - productID := "01932727-1b5a-7540-98c0-6521ffe78ce6" +func Test_segment_Update(t *testing.T) { + segmentID := "01932727-1b5a-7540-98c0-6521ffe78ce6" ledgerID := "01932715-9f93-7432-90c3-4352bcfe464d" organizationID := "01931b04-964a-7caa-a422-c29a95387c00" - name := "Product Practical Metal Sausages BLOCKED" + name := "Segment Practical Metal Sausages BLOCKED" statusCode := "BLOCKED" - statusDescription := ptr.StringPtr("Teste Product BLOCKED") + statusDescription := ptr.StringPtr("Teste Segment BLOCKED") metadata := map[string]any{ "bitcoin": "35x7shF9VF1npqiTNjMsytJTRBNAoaAh", @@ -244,7 +244,7 @@ func Test_product_Update(t *testing.T) { "boolean": true, } - inp := mmodel.UpdateProductInput{ + inp := mmodel.UpdateSegmentInput{ Name: name, Status: mmodel.Status{ Code: statusCode, @@ -253,8 +253,8 @@ func Test_product_Update(t *testing.T) { Metadata: metadata, } - expectedResult := &mmodel.Product{ - ID: productID, + expectedResult := &mmodel.Segment{ + ID: segmentID, Name: name, Status: mmodel.Status{ Code: statusCode, @@ -269,12 +269,12 @@ func Test_product_Update(t *testing.T) { URIAPILedger := "http://127.0.0.1:3000" - uri := fmt.Sprintf("%s/v1/organizations/%s/ledgers/%s/products/%s", - URIAPILedger, organizationID, ledgerID, productID) + uri := fmt.Sprintf("%s/v1/organizations/%s/ledgers/%s/segments/%s", + URIAPILedger, organizationID, ledgerID, segmentID) httpmock.RegisterResponder(http.MethodPatch, uri, mockutil.MockResponseFromFile(http.StatusOK, - "./.fixtures/product_response_update.json")) + "./.fixtures/segment_response_update.json")) factory := &factory.Factory{ HTTPClient: client, @@ -283,9 +283,9 @@ func Test_product_Update(t *testing.T) { }, } - product := NewProduct(factory) + segment := NewSegment(factory) - result, err := product.Update(organizationID, ledgerID, productID, inp) + result, err := segment.Update(organizationID, ledgerID, segmentID, inp) assert.NoError(t, err) assert.NotNil(t, result) @@ -299,8 +299,8 @@ func Test_product_Update(t *testing.T) { assert.Equal(t, 1, info["PATCH "+uri]) } -func Test_product_Delete(t *testing.T) { - productID := "01930219-2c25-7a37-a5b9-610d44ae0a27" +func Test_segment_Delete(t *testing.T) { + segmentID := "01930219-2c25-7a37-a5b9-610d44ae0a27" ledgerID := "0192fc1e-14bf-7894-b167-6e4a878b3a95" organizationID := "0192fc1d-f34d-78c9-9654-83e497349241" URIAPILedger := "http://127.0.0.1:3000" @@ -309,8 +309,8 @@ func Test_product_Delete(t *testing.T) { httpmock.ActivateNonDefault(client) defer httpmock.DeactivateAndReset() - uri := fmt.Sprintf("%s/v1/organizations/%s/ledgers/%s/products/%s", - URIAPILedger, organizationID, ledgerID, productID) + uri := fmt.Sprintf("%s/v1/organizations/%s/ledgers/%s/segments/%s", + URIAPILedger, organizationID, ledgerID, segmentID) httpmock.RegisterResponder(http.MethodDelete, uri, httpmock.NewStringResponder(http.StatusNoContent, "")) @@ -322,9 +322,9 @@ func Test_product_Delete(t *testing.T) { }, } - product := NewProduct(factory) + segment := NewSegment(factory) - err := product.Delete(organizationID, ledgerID, productID) + err := segment.Delete(organizationID, ledgerID, segmentID) assert.NoError(t, err) diff --git a/components/mdz/pkg/cmd/account/create.go b/components/mdz/pkg/cmd/account/create.go index afa0f946b..9fd94f19b 100644 --- a/components/mdz/pkg/cmd/account/create.go +++ b/components/mdz/pkg/cmd/account/create.go @@ -32,7 +32,7 @@ type flagsCreate struct { Alias string Type string ParentAccountID string - ProductID string + SegmentID string EntityID string StatusCode string StatusDescription string @@ -116,8 +116,8 @@ func (f *factoryAccountCreate) createRequestFromFlags(account *mmodel.CreateAcco account.ParentAccountID = &f.ParentAccountID } - if len(f.ProductID) > 0 { - account.ProductID = &f.ProductID + if len(f.SegmentID) > 0 { + account.SegmentID = &f.SegmentID } if len(f.PortfolioID) > 0 { @@ -173,7 +173,7 @@ func (f *factoryAccountCreate) setFlags(cmd *cobra.Command) { cmd.Flags().StringVar(&f.ParentAccountID, "parent-account-id", "", "Specify the ID of the parent account.") cmd.Flags().StringVar(&f.StatusCode, "status-code", "", "Specify the status code for the organization (e.g., ACTIVE).") cmd.Flags().StringVar(&f.StatusDescription, "status-description", "", "Description of the current status of the ledger.") - cmd.Flags().StringVar(&f.ProductID, "product-id", "", "Specify the product ID.") + cmd.Flags().StringVar(&f.SegmentID, "segment-id", "", "Specify the segment ID.") cmd.Flags().StringVar(&f.EntityID, "entity-id", "", "Specify the ID of the associated entity.") cmd.Flags().StringVar(&f.AllowSending, "allow-sending", "", "Allow sending assets from this ledger (true/false).") cmd.Flags().StringVar(&f.AllowReceiving, "allow-receiving", "", "Allow receiving assets to this ledger (true/false).") diff --git a/components/mdz/pkg/cmd/account/describe.go b/components/mdz/pkg/cmd/account/describe.go index a9fd7729c..35d881d85 100644 --- a/components/mdz/pkg/cmd/account/describe.go +++ b/components/mdz/pkg/cmd/account/describe.go @@ -133,8 +133,8 @@ func (f *factoryAccountDescribe) describePrint(account *mmodel.Account) { tbl.AddRow("Entity ID:", *account.EntityID) } - if account.ProductID != nil { - tbl.AddRow("Product ID:", *account.ProductID) + if account.SegmentID != nil { + tbl.AddRow("Segment ID:", *account.SegmentID) } if account.ParentAccountID != nil { diff --git a/components/mdz/pkg/cmd/account/update.go b/components/mdz/pkg/cmd/account/update.go index e11fabeea..8ab2a1378 100644 --- a/components/mdz/pkg/cmd/account/update.go +++ b/components/mdz/pkg/cmd/account/update.go @@ -32,7 +32,7 @@ type flagsUpdate struct { StatusCode string StatusDescription string Alias string - ProductID string + SegmentID string AllowSending string AllowReceiving string Metadata string @@ -140,8 +140,8 @@ func (f *factoryAccountUpdate) UpdateRequestFromFlags(account *mmodel.UpdateAcco account.Alias = &f.Alias } - if len(f.ProductID) > 0 { - account.ProductID = &f.ProductID + if len(f.SegmentID) > 0 { + account.SegmentID = &f.SegmentID } var metadata map[string]any @@ -169,7 +169,7 @@ func (f *factoryAccountUpdate) setFlags(cmd *cobra.Command) { cmd.Flags().StringVar(&f.AllowReceiving, "allow-receiving", "", "Allow receiving assets to this ledger (true/false).") cmd.Flags().StringVar(&f.Metadata, "metadata", "{}", "Metadata in JSON format, ex: '{\"key1\": \"value\", \"key2\": 123}'") - cmd.Flags().StringVar(&f.ProductID, "product-id", "", "Specify the product ID.") + cmd.Flags().StringVar(&f.SegmentID, "segment-id", "", "Specify the segment ID.") cmd.Flags().StringVar(&f.JSONFile, "json-file", "", "Path to a JSON file containing "+ "the attributes of the Organization being Updated; you can use - for reading from stdin") cmd.Flags().BoolP("help", "h", false, "Displays more information about the Mdz CLI") diff --git a/components/mdz/pkg/cmd/product/product.go b/components/mdz/pkg/cmd/product/product.go deleted file mode 100644 index 47ec70f82..000000000 --- a/components/mdz/pkg/cmd/product/product.go +++ /dev/null @@ -1,44 +0,0 @@ -package product - -import ( - "github.com/LerianStudio/midaz/components/mdz/pkg/cmd/utils" - "github.com/LerianStudio/midaz/components/mdz/pkg/factory" - - "github.com/spf13/cobra" -) - -type factoryProduct struct { - factory *factory.Factory -} - -func (f *factoryProduct) setCmds(cmd *cobra.Command) { - cmd.AddCommand(newCmdProductCreate(newInjectFacCreate(f.factory))) - cmd.AddCommand(newCmdProductList(newInjectFacList(f.factory))) - cmd.AddCommand(newCmdProductDescribe(newInjectFacDescribe(f.factory))) - cmd.AddCommand(newCmdProductUpdate(newInjectFacUpdate(f.factory))) - cmd.AddCommand(newCmdProductDelete(newInjectFacDelete(f.factory))) -} - -func NewCmdProduct(f *factory.Factory) *cobra.Command { - fOrg := factoryProduct{ - factory: f, - } - cmd := &cobra.Command{ - Use: "product", - Short: "Shows details of a specific product.", - Long: utils.Format( - "The describe subcommand provides a detailed view of a specific", - "product, including its clustering policies and the rules applied.", - "Ideal for detailed analysis and monitoring of the settings governing", - "the grouping of customers within each product.", - ), - Example: utils.Format( - "$ mdz product", - "$ mdz product -h", - ), - } - cmd.Flags().BoolP("help", "h", false, "Displays more information about the Midaz CLI") - fOrg.setCmds(cmd) - - return cmd -} diff --git a/components/mdz/pkg/cmd/root/root.go b/components/mdz/pkg/cmd/root/root.go index 3c4e5ec9c..156721604 100644 --- a/components/mdz/pkg/cmd/root/root.go +++ b/components/mdz/pkg/cmd/root/root.go @@ -10,7 +10,7 @@ import ( "github.com/LerianStudio/midaz/components/mdz/pkg/cmd/login" "github.com/LerianStudio/midaz/components/mdz/pkg/cmd/organization" "github.com/LerianStudio/midaz/components/mdz/pkg/cmd/portfolio" - "github.com/LerianStudio/midaz/components/mdz/pkg/cmd/product" + "github.com/LerianStudio/midaz/components/mdz/pkg/cmd/segment" "github.com/LerianStudio/midaz/components/mdz/pkg/cmd/utils" "github.com/LerianStudio/midaz/components/mdz/pkg/cmd/version" "github.com/LerianStudio/midaz/components/mdz/pkg/factory" @@ -31,7 +31,7 @@ func (f *factoryRoot) setCmds(cmd *cobra.Command) { cmd.AddCommand(ledger.NewCmdLedger(f.factory)) cmd.AddCommand(asset.NewCmdAsset(f.factory)) cmd.AddCommand(portfolio.NewCmdPortfolio(f.factory)) - cmd.AddCommand(product.NewCmdProduct(f.factory)) + cmd.AddCommand(segment.NewCmdSegment(f.factory)) cmd.AddCommand(account.NewCmdAccount(f.factory)) cmd.AddCommand(configure.NewCmdConfigure(configure.NewInjectFacConfigure(f.factory))) } diff --git a/components/mdz/pkg/cmd/product/create.go b/components/mdz/pkg/cmd/segment/create.go similarity index 72% rename from components/mdz/pkg/cmd/product/create.go rename to components/mdz/pkg/cmd/segment/create.go index 11312f599..0aa78093f 100644 --- a/components/mdz/pkg/cmd/product/create.go +++ b/components/mdz/pkg/cmd/segment/create.go @@ -1,4 +1,4 @@ -package product +package segment import ( "encoding/json" @@ -15,9 +15,9 @@ import ( "github.com/spf13/cobra" ) -type factoryProductCreate struct { +type factorySegmentCreate struct { factory *factory.Factory - repoProduct repository.Product + repoSegment repository.Segment tuiInput func(message string) (string, error) flagsCreate } @@ -32,8 +32,8 @@ type flagsCreate struct { JSONFile string } -func (f *factoryProductCreate) runE(cmd *cobra.Command, _ []string) error { - product := mmodel.CreateProductInput{} +func (f *factorySegmentCreate) runE(cmd *cobra.Command, _ []string) error { + segment := mmodel.CreateSegmentInput{} if !cmd.Flags().Changed("organization-id") && len(f.OrganizationID) < 1 { id, err := f.tuiInput("Enter your organization-id") @@ -54,30 +54,30 @@ func (f *factoryProductCreate) runE(cmd *cobra.Command, _ []string) error { } if cmd.Flags().Changed("json-file") { - err := utils.FlagFileUnmarshalJSON(f.JSONFile, &product) + err := utils.FlagFileUnmarshalJSON(f.JSONFile, &segment) if err != nil { return errors.New("failed to decode the given 'json' file. Verify if " + "the file format is JSON or fix its content according to the JSON format " + "specification at https://www.json.org/json-en.html") } } else { - err := f.createRequestFromFlags(&product) + err := f.createRequestFromFlags(&segment) if err != nil { return err } } - resp, err := f.repoProduct.Create(f.OrganizationID, f.LedgerID, product) + resp, err := f.repoSegment.Create(f.OrganizationID, f.LedgerID, segment) if err != nil { return err } - output.FormatAndPrint(f.factory, resp.ID, "Product", output.Created) + output.FormatAndPrint(f.factory, resp.ID, "Segment", output.Created) return nil } -func (f *factoryProductCreate) createRequestFromFlags(portfolio *mmodel.CreateProductInput) error { +func (f *factorySegmentCreate) createRequestFromFlags(portfolio *mmodel.CreateSegmentInput) error { var err error portfolio.Name, err = utils.AssignStringField(f.Name, "name", f.tuiInput) @@ -101,7 +101,7 @@ func (f *factoryProductCreate) createRequestFromFlags(portfolio *mmodel.CreatePr return nil } -func (f *factoryProductCreate) setFlags(cmd *cobra.Command) { +func (f *factorySegmentCreate) setFlags(cmd *cobra.Command) { cmd.Flags().StringVar(&f.OrganizationID, "organization-id", "", "Specify the organization ID.") cmd.Flags().StringVar(&f.LedgerID, @@ -115,35 +115,35 @@ func (f *factoryProductCreate) setFlags(cmd *cobra.Command) { cmd.Flags().StringVar(&f.Metadata, "metadata", "{}", "Metadata in JSON format, ex: '{\"key1\": \"value\", \"key2\": 123}'") cmd.Flags().StringVar(&f.JSONFile, "json-file", "", - `Path to a JSON file containing the attributes of the Product being + `Path to a JSON file containing the attributes of the Segment being created; you can use - for reading from stdin`) cmd.Flags().BoolP("help", "h", false, "Displays more information about the Mdz CLI") } -func newInjectFacCreate(f *factory.Factory) *factoryProductCreate { - return &factoryProductCreate{ +func newInjectFacCreate(f *factory.Factory) *factorySegmentCreate { + return &factorySegmentCreate{ factory: f, - repoProduct: rest.NewProduct(f), + repoSegment: rest.NewSegment(f), tuiInput: tui.Input, } } -func newCmdProductCreate(f *factoryProductCreate) *cobra.Command { +func newCmdSegmentCreate(f *factorySegmentCreate) *cobra.Command { cmd := &cobra.Command{ Use: "create", - Short: "Creates a new product for clustering customers.", + Short: "Creates a new segment for segmenting customers.", Long: utils.Format( - "The create subcommand allows you to set up a new product, defining", + "The create subcommand allows you to set up a new segment, defining", "the policies and grouping rules to organize customers according to", "specific characteristics. This feature is useful for establishing", - "new clusters and targeting business strategies at specific groups.", + "new segments and targeting business strategies at specific groups.", ), Example: utils.Format( - "$ mdz product create", - "$ mdz product create -h", - "$ mdz product create --json-file payload.json", - "$ cat payload.json | mdz product create --json-file -", + "$ mdz segment create", + "$ mdz segment create -h", + "$ mdz segment create --json-file payload.json", + "$ cat payload.json | mdz segment create --json-file -", ), RunE: f.runE, } diff --git a/components/mdz/pkg/cmd/product/create_test.go b/components/mdz/pkg/cmd/segment/create_test.go similarity index 83% rename from components/mdz/pkg/cmd/product/create_test.go rename to components/mdz/pkg/cmd/segment/create_test.go index 2ef72e571..9141663ea 100644 --- a/components/mdz/pkg/cmd/product/create_test.go +++ b/components/mdz/pkg/cmd/segment/create_test.go @@ -1,4 +1,4 @@ -package product +package segment import ( "bytes" @@ -15,14 +15,14 @@ import ( "github.com/stretchr/testify/assert" ) -func Test_newCmdProductCreate(t *testing.T) { +func Test_newCmdSegmentCreate(t *testing.T) { t.Run("with flags", func(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() - mockRepo := repository.NewMockProduct(ctrl) + mockRepo := repository.NewMockSegment(ctrl) - productID := "01931c99-adef-7b98-ad68-72d7e263066a" + SegmentID := "01931c99-adef-7b98-ad68-72d7e263066a" ledgerID := "0192e251-328d-7390-99f5-5c54980115ed" organizationID := "0192e250-ed9d-7e5c-a614-9b294151b572" @@ -36,12 +36,12 @@ func Test_newCmdProductCreate(t *testing.T) { "chave3": true, } - orgFactory := factoryProductCreate{ + orgFactory := factorySegmentCreate{ factory: &factory.Factory{IOStreams: &iostreams.IOStreams{ Out: &bytes.Buffer{}, Err: &bytes.Buffer{}, }}, - repoProduct: mockRepo, + repoSegment: mockRepo, tuiInput: func(message string) (string, error) { return name, nil }, @@ -55,7 +55,7 @@ func Test_newCmdProductCreate(t *testing.T) { }, } - cmd := newCmdProductCreate(&orgFactory) + cmd := newCmdSegmentCreate(&orgFactory) cmd.SetArgs([]string{ "--organization-id", organizationID, "--ledger-id", ledgerID, @@ -65,8 +65,8 @@ func Test_newCmdProductCreate(t *testing.T) { "--metadata", "{\"chave1\": \"valor1\", \"chave2\": 2, \"chave3\": true}", }) - result := &mmodel.Product{ - ID: productID, + result := &mmodel.Segment{ + ID: SegmentID, LedgerID: ledgerID, OrganizationID: organizationID, Name: name, @@ -82,16 +82,16 @@ func Test_newCmdProductCreate(t *testing.T) { assert.NoError(t, err) output := orgFactory.factory.IOStreams.Out.(*bytes.Buffer).String() - assert.Contains(t, output, "The Product 01931c99-adef-7b98-ad68-72d7e263066a has been successfully created.") + assert.Contains(t, output, "The Segment 01931c99-adef-7b98-ad68-72d7e263066a has been successfully created.") }) t.Run("no flags", func(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() - mockRepo := repository.NewMockProduct(ctrl) + mockRepo := repository.NewMockSegment(ctrl) - productID := "01931c99-adef-7b98-ad68-72d7e263066a" + segmentID := "01931c99-adef-7b98-ad68-72d7e263066a" ledgerID := "0192e251-328d-7390-99f5-5c54980115ed" organizationID := "0192e250-ed9d-7e5c-a614-9b294151b572" @@ -105,12 +105,12 @@ func Test_newCmdProductCreate(t *testing.T) { "chave3": true, } - orgFactory := factoryProductCreate{ + orgFactory := factorySegmentCreate{ factory: &factory.Factory{IOStreams: &iostreams.IOStreams{ Out: &bytes.Buffer{}, Err: &bytes.Buffer{}, }}, - repoProduct: mockRepo, + repoSegment: mockRepo, tuiInput: func(message string) (string, error) { return name, nil }, @@ -128,7 +128,7 @@ func Test_newCmdProductCreate(t *testing.T) { return "123", nil } - cmd := newCmdProductCreate(&orgFactory) + cmd := newCmdSegmentCreate(&orgFactory) cmd.SetArgs([]string{ "--name", name, "--status-code", code, @@ -136,8 +136,8 @@ func Test_newCmdProductCreate(t *testing.T) { "--metadata", "{\"chave1\": \"valor1\", \"chave2\": 2, \"chave3\": true}", }) - result := &mmodel.Product{ - ID: productID, + result := &mmodel.Segment{ + ID: segmentID, LedgerID: ledgerID, OrganizationID: organizationID, Name: name, @@ -153,6 +153,6 @@ func Test_newCmdProductCreate(t *testing.T) { assert.NoError(t, err) output := orgFactory.factory.IOStreams.Out.(*bytes.Buffer).String() - assert.Contains(t, output, "The Product 01931c99-adef-7b98-ad68-72d7e263066a has been successfully created.") + assert.Contains(t, output, "The Segment 01931c99-adef-7b98-ad68-72d7e263066a has been successfully created.") }) } diff --git a/components/mdz/pkg/cmd/product/delete.go b/components/mdz/pkg/cmd/segment/delete.go similarity index 57% rename from components/mdz/pkg/cmd/product/delete.go rename to components/mdz/pkg/cmd/segment/delete.go index f2e0640e3..2df772771 100644 --- a/components/mdz/pkg/cmd/product/delete.go +++ b/components/mdz/pkg/cmd/segment/delete.go @@ -1,4 +1,4 @@ -package product +package segment import ( "github.com/LerianStudio/midaz/components/mdz/internal/domain/repository" @@ -11,16 +11,16 @@ import ( "github.com/spf13/cobra" ) -type factoryProductDelete struct { +type factorySegmentDelete struct { factory *factory.Factory - repoProduct repository.Product + repoSegment repository.Segment tuiInput func(message string) (string, error) OrganizationID string LedgerID string - ProductID string + SegmentID string } -func (f *factoryProductDelete) ensureFlagInput(cmd *cobra.Command) error { +func (f *factorySegmentDelete) ensureFlagInput(cmd *cobra.Command) error { if !cmd.Flags().Changed("organization-id") && len(f.OrganizationID) < 1 { id, err := f.tuiInput("Enter your organization-id") if err != nil { @@ -39,62 +39,62 @@ func (f *factoryProductDelete) ensureFlagInput(cmd *cobra.Command) error { f.LedgerID = id } - if !cmd.Flags().Changed("product-id") && len(f.ProductID) < 1 { - id, err := f.tuiInput("Enter your product-id") + if !cmd.Flags().Changed("segment-id") && len(f.SegmentID) < 1 { + id, err := f.tuiInput("Enter your segment-id") if err != nil { return err } - f.ProductID = id + f.SegmentID = id } return nil } -func (f *factoryProductDelete) runE(cmd *cobra.Command, _ []string) error { +func (f *factorySegmentDelete) runE(cmd *cobra.Command, _ []string) error { if err := f.ensureFlagInput(cmd); err != nil { return err } - err := f.repoProduct.Delete(f.OrganizationID, f.LedgerID, f.ProductID) + err := f.repoSegment.Delete(f.OrganizationID, f.LedgerID, f.SegmentID) if err != nil { return err } - output.FormatAndPrint(f.factory, f.ProductID, "Product", output.Deleted) + output.FormatAndPrint(f.factory, f.SegmentID, "Segment", output.Deleted) return nil } -func (f *factoryProductDelete) setFlags(cmd *cobra.Command) { +func (f *factorySegmentDelete) setFlags(cmd *cobra.Command) { cmd.Flags().StringVar(&f.OrganizationID, "organization-id", "", "Specify the organization ID.") cmd.Flags().StringVar(&f.LedgerID, "ledger-id", "", "Specify the ledger ID") - cmd.Flags().StringVar(&f.ProductID, "product-id", "", "Specify the portfolio ID") + cmd.Flags().StringVar(&f.SegmentID, "segment-id", "", "Specify the portfolio ID") cmd.Flags().BoolP("help", "h", false, "Displays more information about the Mdz CLI") } -func newInjectFacDelete(f *factory.Factory) *factoryProductDelete { - return &factoryProductDelete{ +func newInjectFacDelete(f *factory.Factory) *factorySegmentDelete { + return &factorySegmentDelete{ factory: f, - repoProduct: rest.NewProduct(f), + repoSegment: rest.NewSegment(f), tuiInput: tui.Input, } } -func newCmdProductDelete(f *factoryProductDelete) *cobra.Command { +func newCmdSegmentDelete(f *factorySegmentDelete) *cobra.Command { cmd := &cobra.Command{ Use: "delete", - Short: "Removes an existing product.", + Short: "Removes an existing segment.", Long: utils.Format( - "The delete subcommand allows you to delete a product, removing its", - "settings and clustering rules. It is useful for deactivating obsolete", - "clusters or adjusting the organization of products without changing", + "The delete subcommand allows you to delete a segment, removing its", + "settings and segmenting rules. It is useful for deactivating obsolete", + "segments or adjusting the organization of segments without changing", "the structure of customers.", ), Example: utils.Format( - "$ mdz product delete --organization-id '1234' --ledger-id '4421' --product-id '55232'", - "$ mdz product delete -i 12314", - "$ mdz product delete -h", + "$ mdz segment delete --organization-id '1234' --ledger-id '4421' --segment-id '55232'", + "$ mdz segment delete -i 12314", + "$ mdz segment delete -h", ), RunE: f.runE, } diff --git a/components/mdz/pkg/cmd/product/delete_test.go b/components/mdz/pkg/cmd/segment/delete_test.go similarity index 72% rename from components/mdz/pkg/cmd/product/delete_test.go rename to components/mdz/pkg/cmd/segment/delete_test.go index 7846c9129..6893f7291 100644 --- a/components/mdz/pkg/cmd/product/delete_test.go +++ b/components/mdz/pkg/cmd/segment/delete_test.go @@ -1,4 +1,4 @@ -package product +package segment import ( "bytes" @@ -13,29 +13,29 @@ import ( "github.com/stretchr/testify/assert" ) -func Test_newCmdProductDelete(t *testing.T) { +func Test_newCmdSegmentDelete(t *testing.T) { t.Run("with flags", func(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() - mockRepo := repository.NewMockProduct(ctrl) + mockRepo := repository.NewMockSegment(ctrl) - factory := factoryProductDelete{ + factory := factorySegmentDelete{ factory: &factory.Factory{IOStreams: &iostreams.IOStreams{ Out: &bytes.Buffer{}, Err: &bytes.Buffer{}, }}, - repoProduct: mockRepo, + repoSegment: mockRepo, OrganizationID: "321", LedgerID: "123", - ProductID: "444", + SegmentID: "444", } - cmd := newCmdProductDelete(&factory) + cmd := newCmdSegmentDelete(&factory) cmd.SetArgs([]string{ "--organization-id", "321", "--ledger-id", "123", - "--product-id", "444", + "--segment-id", "444", }) mockRepo.EXPECT().Delete(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil) @@ -44,31 +44,31 @@ func Test_newCmdProductDelete(t *testing.T) { assert.NoError(t, err) output := factory.factory.IOStreams.Out.(*bytes.Buffer).String() - assert.Contains(t, output, "The Product 444 has been successfully deleted.") + assert.Contains(t, output, "The Segment 444 has been successfully deleted.") }) t.Run("no flags", func(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() - mockRepo := repository.NewMockProduct(ctrl) + mockRepo := repository.NewMockSegment(ctrl) - factory := factoryProductDelete{ + factory := factorySegmentDelete{ factory: &factory.Factory{IOStreams: &iostreams.IOStreams{ Out: &bytes.Buffer{}, Err: &bytes.Buffer{}, }}, - repoProduct: mockRepo, + repoSegment: mockRepo, OrganizationID: "321", LedgerID: "123", - ProductID: "444", + SegmentID: "444", } factory.tuiInput = func(message string) (string, error) { return "444", nil } - cmd := newCmdProductDelete(&factory) + cmd := newCmdSegmentDelete(&factory) cmd.SetArgs([]string{}) mockRepo.EXPECT().Delete(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil) @@ -77,6 +77,6 @@ func Test_newCmdProductDelete(t *testing.T) { assert.NoError(t, err) output := factory.factory.IOStreams.Out.(*bytes.Buffer).String() - assert.Contains(t, output, "The Product 444 has been successfully deleted.") + assert.Contains(t, output, "The Segment 444 has been successfully deleted.") }) } diff --git a/components/mdz/pkg/cmd/product/describe.go b/components/mdz/pkg/cmd/segment/describe.go similarity index 75% rename from components/mdz/pkg/cmd/product/describe.go rename to components/mdz/pkg/cmd/segment/describe.go index ecc6964e8..2f6ed7b3a 100644 --- a/components/mdz/pkg/cmd/product/describe.go +++ b/components/mdz/pkg/cmd/segment/describe.go @@ -1,4 +1,4 @@ -package product +package segment import ( "encoding/json" @@ -17,18 +17,18 @@ import ( "github.com/spf13/cobra" ) -type factoryProductDescribe struct { +type factorySegmentDescribe struct { factory *factory.Factory - repoProduct repository.Product + repoSegment repository.Segment tuiInput func(message string) (string, error) OrganizationID string LedgerID string - ProductID string + SegmentID string Out string JSON bool } -func (f *factoryProductDescribe) ensureFlagInput(cmd *cobra.Command) error { +func (f *factorySegmentDescribe) ensureFlagInput(cmd *cobra.Command) error { if !cmd.Flags().Changed("organization-id") && len(f.OrganizationID) < 1 { id, err := f.tuiInput("Enter your organization-id") if err != nil { @@ -47,32 +47,32 @@ func (f *factoryProductDescribe) ensureFlagInput(cmd *cobra.Command) error { f.LedgerID = id } - if !cmd.Flags().Changed("product-id") && len(f.ProductID) < 1 { - id, err := f.tuiInput("Enter your product-id") + if !cmd.Flags().Changed("segment-id") && len(f.SegmentID) < 1 { + id, err := f.tuiInput("Enter your segment-id") if err != nil { return err } - f.ProductID = id + f.SegmentID = id } return nil } -func (f *factoryProductDescribe) runE(cmd *cobra.Command, _ []string) error { +func (f *factorySegmentDescribe) runE(cmd *cobra.Command, _ []string) error { if err := f.ensureFlagInput(cmd); err != nil { return err } - asset, err := f.repoProduct.GetByID(f.OrganizationID, f.LedgerID, f.ProductID) + asset, err := f.repoSegment.GetByID(f.OrganizationID, f.LedgerID, f.SegmentID) if err != nil { return err } - return f.outputProduct(cmd, asset) + return f.outputSegment(cmd, asset) } -func (f *factoryProductDescribe) outputProduct(cmd *cobra.Command, asset *mmodel.Product) error { +func (f *factorySegmentDescribe) outputSegment(cmd *cobra.Command, asset *mmodel.Segment) error { if f.JSON || cmd.Flags().Changed("out") { b, err := json.Marshal(asset) if err != nil { @@ -104,7 +104,7 @@ func (f *factoryProductDescribe) outputProduct(cmd *cobra.Command, asset *mmodel return nil } -func (f *factoryProductDescribe) describePrint(asset *mmodel.Product) { +func (f *factorySegmentDescribe) describePrint(asset *mmodel.Segment) { tbl := table.New("FIELDS", "VALUES") if !f.factory.NoColor { @@ -137,24 +137,24 @@ func (f *factoryProductDescribe) describePrint(asset *mmodel.Product) { tbl.Print() } -func (f *factoryProductDescribe) setFlags(cmd *cobra.Command) { +func (f *factorySegmentDescribe) setFlags(cmd *cobra.Command) { cmd.Flags().StringVar(&f.Out, "out", "", "Exports the output to the given ") cmd.Flags().BoolVar(&f.JSON, "json", false, "returns the table in json format") cmd.Flags().StringVar(&f.OrganizationID, "organization-id", "", "Specify the organization ID.") cmd.Flags().StringVar(&f.LedgerID, "ledger-id", "", "Specify the ledger ID") - cmd.Flags().StringVar(&f.ProductID, "product-id", "", "Specify the product ID to retrieve details") + cmd.Flags().StringVar(&f.SegmentID, "segment-id", "", "Specify the segment ID to retrieve details") cmd.Flags().BoolP("help", "h", false, "Displays more information about the Mdz CLI") } -func newInjectFacDescribe(f *factory.Factory) *factoryProductDescribe { - return &factoryProductDescribe{ +func newInjectFacDescribe(f *factory.Factory) *factorySegmentDescribe { + return &factorySegmentDescribe{ factory: f, - repoProduct: rest.NewProduct(f), + repoSegment: rest.NewSegment(f), tuiInput: tui.Input, } } -func newCmdProductDescribe(f *factoryProductDescribe) *cobra.Command { +func newCmdSegmentDescribe(f *factorySegmentDescribe) *cobra.Command { cmd := &cobra.Command{ Use: "describe", Short: "Shows details of a specific portfolio.", @@ -165,9 +165,9 @@ func newCmdProductDescribe(f *factoryProductDescribe) *cobra.Command { "better understand its structure.", ), Example: utils.Format( - "$ mdz product describe --organization-id 12341234 --ledger-id 12312 --product-id 432123", - "$ mdz product describe", - "$ mdz product describe -h", + "$ mdz segment describe --organization-id 12341234 --ledger-id 12312 --segment-id 432123", + "$ mdz segment describe", + "$ mdz segment describe -h", ), RunE: f.runE, } diff --git a/components/mdz/pkg/cmd/product/describe_test.go b/components/mdz/pkg/cmd/segment/describe_test.go similarity index 87% rename from components/mdz/pkg/cmd/product/describe_test.go rename to components/mdz/pkg/cmd/segment/describe_test.go index 2d8c9238b..38982d1a8 100644 --- a/components/mdz/pkg/cmd/product/describe_test.go +++ b/components/mdz/pkg/cmd/segment/describe_test.go @@ -1,4 +1,4 @@ -package product +package segment import ( "bytes" @@ -17,23 +17,23 @@ import ( "gotest.tools/golden" ) -func Test_newCmdProductDescribe(t *testing.T) { +func Test_newCmdSegmentDescribe(t *testing.T) { t.Run("happy path informing all the necessary flags", func(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() - mockRepo := repository.NewMockProduct(ctrl) + mockRepo := repository.NewMockSegment(ctrl) ledgerID := "0192e251-328d-7390-99f5-5c54980115ed" organizationID := "0192e250-ed9d-7e5c-a614-9b294151b572" portfolioID := "01931b44-6e33-791a-bfad-27992fa15984" - ledFactory := factoryProductDescribe{ + ledFactory := factorySegmentDescribe{ factory: &factory.Factory{IOStreams: &iostreams.IOStreams{ Out: &bytes.Buffer{}, Err: &bytes.Buffer{}, }}, - repoProduct: mockRepo, + repoSegment: mockRepo, OrganizationID: organizationID, LedgerID: ledgerID, Out: "", @@ -46,14 +46,14 @@ func Test_newCmdProductDescribe(t *testing.T) { "chave3": true, } - cmd := newCmdProductDescribe(&ledFactory) + cmd := newCmdSegmentDescribe(&ledFactory) cmd.SetArgs([]string{ "--ledger-id", ledgerID, "--organization-id", organizationID, - "--product-id", portfolioID, + "--segment-id", portfolioID, }) - item := mmodel.Product{ + item := mmodel.Segment{ ID: portfolioID, Name: "2Real", OrganizationID: organizationID, @@ -81,18 +81,18 @@ func Test_newCmdProductDescribe(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() - mockRepo := repository.NewMockProduct(ctrl) + mockRepo := repository.NewMockSegment(ctrl) ledgerID := "0192e251-328d-7390-99f5-5c54980115ed" organizationID := "0192e250-ed9d-7e5c-a614-9b294151b572" portfolioID := "01931b44-6e33-791a-bfad-27992fa15984" - ledFactory := factoryProductDescribe{ + ledFactory := factorySegmentDescribe{ factory: &factory.Factory{IOStreams: &iostreams.IOStreams{ Out: &bytes.Buffer{}, Err: &bytes.Buffer{}, }}, - repoProduct: mockRepo, + repoSegment: mockRepo, OrganizationID: organizationID, LedgerID: ledgerID, Out: "", @@ -109,10 +109,10 @@ func Test_newCmdProductDescribe(t *testing.T) { return "01933f96-ed04-7c57-be5b-c091388830f8", nil } - cmd := newCmdProductDescribe(&ledFactory) + cmd := newCmdSegmentDescribe(&ledFactory) cmd.SetArgs([]string{}) - item := mmodel.Product{ + item := mmodel.Segment{ ID: portfolioID, Name: "2Real", OrganizationID: organizationID, diff --git a/components/mdz/pkg/cmd/product/list.go b/components/mdz/pkg/cmd/segment/list.go similarity index 76% rename from components/mdz/pkg/cmd/product/list.go rename to components/mdz/pkg/cmd/segment/list.go index 5fc14be50..9df28d18d 100644 --- a/components/mdz/pkg/cmd/product/list.go +++ b/components/mdz/pkg/cmd/segment/list.go @@ -1,4 +1,4 @@ -package product +package segment import ( "encoding/json" @@ -15,9 +15,9 @@ import ( "github.com/spf13/cobra" ) -type factoryProductList struct { +type factorySegmentList struct { factory *factory.Factory - repoProduct repository.Product + repoSegment repository.Segment tuiInput func(message string) (string, error) OrganizationID string LedgerID string @@ -29,7 +29,7 @@ type factoryProductList struct { JSON bool } -func (f *factoryProductList) runE(cmd *cobra.Command, _ []string) error { +func (f *factorySegmentList) runE(cmd *cobra.Command, _ []string) error { if !cmd.Flags().Changed("organization-id") && len(f.OrganizationID) < 1 { id, err := f.tuiInput("Enter your organization-id") if err != nil { @@ -60,7 +60,7 @@ func (f *factoryProductList) runE(cmd *cobra.Command, _ []string) error { } } - portfolios, err := f.repoProduct.Get(f.OrganizationID, f.LedgerID, f.Limit, f.Page, + portfolios, err := f.repoSegment.Get(f.OrganizationID, f.LedgerID, f.Limit, f.Page, f.SortOrder, f.StartDate, f.EndDate) if err != nil { return err @@ -108,7 +108,7 @@ func (f *factoryProductList) runE(cmd *cobra.Command, _ []string) error { return nil } -func (f *factoryProductList) setFlags(cmd *cobra.Command) { +func (f *factorySegmentList) setFlags(cmd *cobra.Command) { cmd.Flags().StringVar(&f.OrganizationID, "organization-id", "", "Specify the organization ID.") cmd.Flags().StringVar(&f.LedgerID, "ledger-id", "", "Specify the ledger ID.") cmd.Flags().BoolVar(&f.JSON, "json", false, "returns the table in json format") @@ -125,31 +125,31 @@ func (f *factoryProductList) setFlags(cmd *cobra.Command) { cmd.Flags().BoolP("help", "h", false, "Displays more information about the Mdz CLI") } -func newInjectFacList(f *factory.Factory) *factoryProductList { - return &factoryProductList{ +func newInjectFacList(f *factory.Factory) *factorySegmentList { + return &factorySegmentList{ factory: f, - repoProduct: rest.NewProduct(f), + repoSegment: rest.NewSegment(f), tuiInput: tui.Input, } } -func newCmdProductList(f *factoryProductList) *cobra.Command { +func newCmdSegmentList(f *factorySegmentList) *cobra.Command { cmd := &cobra.Command{ Use: "list", - Short: "Lists all registered products.", + Short: "Lists all registered segments.", Long: utils.Format( - "The list subcommand displays all the products created, with details", - "of the policies and clustering rules applied. It's a quick way to", - "view existing clusters and monitor the policies associated with", - "each product.", + "The list subcommand displays all the segments created, with details", + "of the policies and segmenting rules applied. It's a quick way to", + "view existing segments and monitor the policies associated with", + "each segment.", ), Example: utils.Format( - "$ mdz product list", - "$ mdz product list -h", - "$ mdz product list --limit 10", - "$ mdz product list --organization-id 43212 --ledger-id 12333", - "$ mdz product list --organization-id 43212 --ledger-id 12333 --page 3", - "$ mdz product list --organization-id 43212 --ledger-id 12333 --limit 10 --page 2", + "$ mdz segment list", + "$ mdz segment list -h", + "$ mdz segment list --limit 10", + "$ mdz segment list --organization-id 43212 --ledger-id 12333", + "$ mdz segment list --organization-id 43212 --ledger-id 12333 --page 3", + "$ mdz segment list --organization-id 43212 --ledger-id 12333 --limit 10 --page 2", ), RunE: f.runE, } diff --git a/components/mdz/pkg/cmd/product/list_test.go b/components/mdz/pkg/cmd/segment/list_test.go similarity index 90% rename from components/mdz/pkg/cmd/product/list_test.go rename to components/mdz/pkg/cmd/segment/list_test.go index 2a642e723..1ada414fd 100644 --- a/components/mdz/pkg/cmd/product/list_test.go +++ b/components/mdz/pkg/cmd/segment/list_test.go @@ -1,4 +1,4 @@ -package product +package segment import ( "bytes" @@ -17,36 +17,36 @@ import ( "gotest.tools/golden" ) -func Test_newCmdProductList(t *testing.T) { +func Test_newCmdSegmentList(t *testing.T) { t.Run("with flags", func(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() - mockRepo := repository.NewMockProduct(ctrl) + mockRepo := repository.NewMockSegment(ctrl) organizationID := "0192e250-ed9d-7e5c-a614-9b294151b572" ledgerID := "0192e251-328d-7390-99f5-5c54980115ed" - ledFactory := factoryProductList{ + ledFactory := factorySegmentList{ factory: &factory.Factory{IOStreams: &iostreams.IOStreams{ Out: &bytes.Buffer{}, Err: &bytes.Buffer{}, }}, - repoProduct: mockRepo, + repoSegment: mockRepo, OrganizationID: organizationID, LedgerID: ledgerID, } - cmd := newCmdProductList(&ledFactory) + cmd := newCmdSegmentList(&ledFactory) cmd.SetArgs([]string{ "--organization-id", organizationID, "--ledger-id", ledgerID, }) - list := &mmodel.Products{ + list := &mmodel.Segments{ Page: 1, Limit: 2, - Items: []mmodel.Product{ + Items: []mmodel.Segment{ { ID: "01930365-4d46-7a09-a503-b932714f85af", Name: "2Real", @@ -102,17 +102,17 @@ func Test_newCmdProductList(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() - mockRepo := repository.NewMockProduct(ctrl) + mockRepo := repository.NewMockSegment(ctrl) organizationID := "0192e250-ed9d-7e5c-a614-9b294151b572" ledgerID := "0192e251-328d-7390-99f5-5c54980115ed" - ledFactory := factoryProductList{ + ledFactory := factorySegmentList{ factory: &factory.Factory{IOStreams: &iostreams.IOStreams{ Out: &bytes.Buffer{}, Err: &bytes.Buffer{}, }}, - repoProduct: mockRepo, + repoSegment: mockRepo, OrganizationID: organizationID, LedgerID: ledgerID, } @@ -121,13 +121,13 @@ func Test_newCmdProductList(t *testing.T) { return "1234", nil } - cmd := newCmdProductList(&ledFactory) + cmd := newCmdSegmentList(&ledFactory) cmd.SetArgs([]string{}) - list := &mmodel.Products{ + list := &mmodel.Segments{ Page: 1, Limit: 2, - Items: []mmodel.Product{ + Items: []mmodel.Segment{ { ID: "01930365-4d46-7a09-a503-b932714f85af", Name: "2Real", @@ -183,17 +183,17 @@ func Test_newCmdProductList(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() - mockRepo := repository.NewMockProduct(ctrl) + mockRepo := repository.NewMockSegment(ctrl) organizationID := "0192e250-ed9d-7e5c-a614-9b294151b572" ledgerID := "0192e251-328d-7390-99f5-5c54980115ed" - ledFactory := factoryProductList{ + ledFactory := factorySegmentList{ factory: &factory.Factory{IOStreams: &iostreams.IOStreams{ Out: &bytes.Buffer{}, Err: &bytes.Buffer{}, }}, - repoProduct: mockRepo, + repoSegment: mockRepo, OrganizationID: organizationID, LedgerID: ledgerID, } @@ -202,13 +202,13 @@ func Test_newCmdProductList(t *testing.T) { return "1234", nil } - cmd := newCmdProductList(&ledFactory) + cmd := newCmdSegmentList(&ledFactory) cmd.SetArgs([]string{"--start-date", "2023-11-01", "--end-date", "2023-11-10"}) - list := &mmodel.Products{ + list := &mmodel.Segments{ Page: 1, Limit: 2, - Items: []mmodel.Product{ + Items: []mmodel.Segment{ { ID: "01930365-4d46-7a09-a503-b932714f85af", Name: "2Real", diff --git a/components/mdz/pkg/cmd/segment/segment.go b/components/mdz/pkg/cmd/segment/segment.go new file mode 100644 index 000000000..8ab584efe --- /dev/null +++ b/components/mdz/pkg/cmd/segment/segment.go @@ -0,0 +1,44 @@ +package segment + +import ( + "github.com/LerianStudio/midaz/components/mdz/pkg/cmd/utils" + "github.com/LerianStudio/midaz/components/mdz/pkg/factory" + + "github.com/spf13/cobra" +) + +type factorySegment struct { + factory *factory.Factory +} + +func (f *factorySegment) setCmds(cmd *cobra.Command) { + cmd.AddCommand(newCmdSegmentCreate(newInjectFacCreate(f.factory))) + cmd.AddCommand(newCmdSegmentList(newInjectFacList(f.factory))) + cmd.AddCommand(newCmdSegmentDescribe(newInjectFacDescribe(f.factory))) + cmd.AddCommand(newCmdSegmentUpdate(newInjectFacUpdate(f.factory))) + cmd.AddCommand(newCmdSegmentDelete(newInjectFacDelete(f.factory))) +} + +func NewCmdSegment(f *factory.Factory) *cobra.Command { + fOrg := factorySegment{ + factory: f, + } + cmd := &cobra.Command{ + Use: "segment", + Short: "Shows details of a specific segment.", + Long: utils.Format( + "The describe subcommand provides a detailed view of a specific", + "segment, including its segmenting policies and the rules applied.", + "Ideal for detailed analysis and monitoring of the settings governing", + "the grouping of customers within each segment.", + ), + Example: utils.Format( + "$ mdz segment", + "$ mdz segment -h", + ), + } + cmd.Flags().BoolP("help", "h", false, "Displays more information about the Midaz CLI") + fOrg.setCmds(cmd) + + return cmd +} diff --git a/components/mdz/pkg/cmd/product/testdata/output_describe.golden b/components/mdz/pkg/cmd/segment/testdata/output_describe.golden similarity index 100% rename from components/mdz/pkg/cmd/product/testdata/output_describe.golden rename to components/mdz/pkg/cmd/segment/testdata/output_describe.golden diff --git a/components/mdz/pkg/cmd/product/testdata/output_list.golden b/components/mdz/pkg/cmd/segment/testdata/output_list.golden similarity index 100% rename from components/mdz/pkg/cmd/product/testdata/output_list.golden rename to components/mdz/pkg/cmd/segment/testdata/output_list.golden diff --git a/components/mdz/pkg/cmd/product/update.go b/components/mdz/pkg/cmd/segment/update.go similarity index 69% rename from components/mdz/pkg/cmd/product/update.go rename to components/mdz/pkg/cmd/segment/update.go index 82d61b86e..1422392f0 100644 --- a/components/mdz/pkg/cmd/product/update.go +++ b/components/mdz/pkg/cmd/segment/update.go @@ -1,4 +1,4 @@ -package product +package segment import ( "encoding/json" @@ -15,9 +15,9 @@ import ( "github.com/spf13/cobra" ) -type factoryProductUpdate struct { +type factorySegmentUpdate struct { factory *factory.Factory - repoProduct repository.Product + repoSegment repository.Segment tuiInput func(message string) (string, error) flagsUpdate } @@ -25,7 +25,7 @@ type factoryProductUpdate struct { type flagsUpdate struct { OrganizationID string LedgerID string - ProductID string + SegmentID string Name string StatusCode string StatusDescription string @@ -33,7 +33,7 @@ type flagsUpdate struct { JSONFile string } -func (f *factoryProductUpdate) ensureFlagInput(cmd *cobra.Command) error { +func (f *factorySegmentUpdate) ensureFlagInput(cmd *cobra.Command) error { if !cmd.Flags().Changed("organization-id") && len(f.OrganizationID) < 1 { id, err := f.tuiInput("Enter your organization-id") if err != nil { @@ -52,50 +52,50 @@ func (f *factoryProductUpdate) ensureFlagInput(cmd *cobra.Command) error { f.LedgerID = id } - if !cmd.Flags().Changed("product-id") && len(f.ProductID) < 1 { - id, err := f.tuiInput("Enter your product-id") + if !cmd.Flags().Changed("segment-id") && len(f.SegmentID) < 1 { + id, err := f.tuiInput("Enter your segment-id") if err != nil { return err } - f.ProductID = id + f.SegmentID = id } return nil } -func (f *factoryProductUpdate) runE(cmd *cobra.Command, _ []string) error { - product := mmodel.UpdateProductInput{} +func (f *factorySegmentUpdate) runE(cmd *cobra.Command, _ []string) error { + Segment := mmodel.UpdateSegmentInput{} if err := f.ensureFlagInput(cmd); err != nil { return err } if cmd.Flags().Changed("json-file") { - err := utils.FlagFileUnmarshalJSON(f.JSONFile, &product) + err := utils.FlagFileUnmarshalJSON(f.JSONFile, &Segment) if err != nil { return errors.New("failed to decode the given 'json' file. Verify if " + "the file format is JSON or fix its content according to the JSON format " + "specification at https://www.json.org/json-en.html") } } else { - err := f.UpdateRequestFromFlags(&product) + err := f.UpdateRequestFromFlags(&Segment) if err != nil { return err } } - resp, err := f.repoProduct.Update(f.OrganizationID, f.LedgerID, f.ProductID, product) + resp, err := f.repoSegment.Update(f.OrganizationID, f.LedgerID, f.SegmentID, Segment) if err != nil { return err } - output.FormatAndPrint(f.factory, resp.ID, "Product", output.Updated) + output.FormatAndPrint(f.factory, resp.ID, "Segment", output.Updated) return nil } -func (f *factoryProductUpdate) UpdateRequestFromFlags(portfolio *mmodel.UpdateProductInput) error { +func (f *factorySegmentUpdate) UpdateRequestFromFlags(portfolio *mmodel.UpdateSegmentInput) error { portfolio.Name = f.Name portfolio.Status.Code = f.StatusCode @@ -113,11 +113,11 @@ func (f *factoryProductUpdate) UpdateRequestFromFlags(portfolio *mmodel.UpdatePr return nil } -func (f *factoryProductUpdate) setFlags(cmd *cobra.Command) { +func (f *factorySegmentUpdate) setFlags(cmd *cobra.Command) { cmd.Flags().StringVar(&f.OrganizationID, "organization-id", "", "Specify the organization ID.") cmd.Flags().StringVar(&f.LedgerID, "ledger-id", "", "Specify the ledger ID") - cmd.Flags().StringVar(&f.ProductID, "product-id", "", "Specify the portfolio ID") - cmd.Flags().StringVar(&f.Name, "name", "", "Legal name of the Product.") + cmd.Flags().StringVar(&f.SegmentID, "segment-id", "", "Specify the portfolio ID") + cmd.Flags().StringVar(&f.Name, "name", "", "Legal name of the Segment.") cmd.Flags().StringVar(&f.StatusCode, "status-code", "", "code for the organization (e.g., ACTIVE).") cmd.Flags().StringVar(&f.StatusDescription, "status-description", "", @@ -131,29 +131,29 @@ func (f *factoryProductUpdate) setFlags(cmd *cobra.Command) { cmd.Flags().BoolP("help", "h", false, "Displays more information about the Mdz CLI") } -func newInjectFacUpdate(f *factory.Factory) *factoryProductUpdate { - return &factoryProductUpdate{ +func newInjectFacUpdate(f *factory.Factory) *factorySegmentUpdate { + return &factorySegmentUpdate{ factory: f, - repoProduct: rest.NewProduct(f), + repoSegment: rest.NewSegment(f), tuiInput: tui.Input, } } -func newCmdProductUpdate(f *factoryProductUpdate) *cobra.Command { +func newCmdSegmentUpdate(f *factorySegmentUpdate) *cobra.Command { cmd := &cobra.Command{ Use: "update", - Short: "Updates an existing product with new policies.", + Short: "Updates an existing segment with new policies.", Long: utils.Format( "The update subcommand allows you to adjust the policies and settings", - "of an existing product. With it, you can modify the clustering rules,", + "of an existing segment. With it, you can modify the segmenting rules,", "adapting the grouping of clients according to changes in business", "strategies and needs.", ), Example: utils.Format( - "$ mdz product update", - "$ mdz product update -h", - "$ mdz product update --json-file payload.json", - "$ cat payload.json | mdz product update --organization-id '1234' --ledger-id '4421' --product-id '45232' --json-file -", + "$ mdz segment update", + "$ mdz segment update -h", + "$ mdz segment update --json-file payload.json", + "$ cat payload.json | mdz segment update --organization-id '1234' --ledger-id '4421' --segment-id '45232' --json-file -", "$ mdz portfolio update --organization-id '1234' --ledger-id '4421' --portfolio-id '55232' --name 'Gislason LLCT'", ), RunE: f.runE, diff --git a/components/mdz/pkg/cmd/product/update_test.go b/components/mdz/pkg/cmd/segment/update_test.go similarity index 84% rename from components/mdz/pkg/cmd/product/update_test.go rename to components/mdz/pkg/cmd/segment/update_test.go index 8d30b94bb..fe0b29ea8 100644 --- a/components/mdz/pkg/cmd/product/update_test.go +++ b/components/mdz/pkg/cmd/segment/update_test.go @@ -1,4 +1,4 @@ -package product +package segment import ( "bytes" @@ -15,19 +15,19 @@ import ( "github.com/stretchr/testify/assert" ) -func Test_newCmdProductUpdate(t *testing.T) { +func Test_newCmdSegmentUpdate(t *testing.T) { t.Run("with flags", func(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() - mockRepo := repository.NewMockProduct(ctrl) + mockRepo := repository.NewMockSegment(ctrl) - orgFactory := factoryProductUpdate{ + orgFactory := factorySegmentUpdate{ factory: &factory.Factory{IOStreams: &iostreams.IOStreams{ Out: &bytes.Buffer{}, Err: &bytes.Buffer{}, }}, - repoProduct: mockRepo, + repoSegment: mockRepo, tuiInput: func(message string) (string, error) { return "name", nil }, @@ -39,11 +39,11 @@ func Test_newCmdProductUpdate(t *testing.T) { }, } - cmd := newCmdProductUpdate(&orgFactory) + cmd := newCmdSegmentUpdate(&orgFactory) cmd.SetArgs([]string{ "--organization-id", "123", "--ledger-id", "321", - "--product-id", "412", + "--segment-id", "412", "--name", "Test Organization", "--status-code", "BLOCKED", "--status-description", "Teste BLOCKED Ledger", @@ -56,7 +56,7 @@ func Test_newCmdProductUpdate(t *testing.T) { "chave3": true, } - gotOrg := &mmodel.Product{ + gotOrg := &mmodel.Segment{ ID: "412", Name: "Test Organization", Status: mmodel.Status{ @@ -72,21 +72,21 @@ func Test_newCmdProductUpdate(t *testing.T) { assert.NoError(t, err) output := orgFactory.factory.IOStreams.Out.(*bytes.Buffer).String() - assert.Contains(t, output, "The Product 412 has been successfully updated.") + assert.Contains(t, output, "The Segment 412 has been successfully updated.") }) t.Run("no flags", func(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() - mockRepo := repository.NewMockProduct(ctrl) + mockRepo := repository.NewMockSegment(ctrl) - orgFactory := factoryProductUpdate{ + orgFactory := factorySegmentUpdate{ factory: &factory.Factory{IOStreams: &iostreams.IOStreams{ Out: &bytes.Buffer{}, Err: &bytes.Buffer{}, }}, - repoProduct: mockRepo, + repoSegment: mockRepo, tuiInput: func(message string) (string, error) { return "name", nil }, @@ -102,7 +102,7 @@ func Test_newCmdProductUpdate(t *testing.T) { return "412", nil } - cmd := newCmdProductUpdate(&orgFactory) + cmd := newCmdSegmentUpdate(&orgFactory) cmd.SetArgs([]string{ "--name", "Test Organization", "--status-code", "BLOCKED", @@ -116,7 +116,7 @@ func Test_newCmdProductUpdate(t *testing.T) { "chave3": true, } - gotOrg := &mmodel.Product{ + gotOrg := &mmodel.Segment{ ID: "412", Name: "Test Organization", Status: mmodel.Status{ @@ -132,6 +132,6 @@ func Test_newCmdProductUpdate(t *testing.T) { assert.NoError(t, err) output := orgFactory.factory.IOStreams.Out.(*bytes.Buffer).String() - assert.Contains(t, output, "The Product 412 has been successfully updated.") + assert.Contains(t, output, "The Segment 412 has been successfully updated.") }) } diff --git a/components/mdz/test/integration/mdz_test.go b/components/mdz/test/integration/mdz_test.go index bb9440d8a..fa0d6b9db 100644 --- a/components/mdz/test/integration/mdz_test.go +++ b/components/mdz/test/integration/mdz_test.go @@ -134,29 +134,29 @@ func TestMDZ(t *testing.T) { "--name", fake.FirstName(), )) - stdout, _ = cmdRun(t, exec.Command("mdz", "product", "create", + stdout, _ = cmdRun(t, exec.Command("mdz", "segment", "create", "--organization-id", organizationID, "--ledger-id", ledgerID, "--name", fake.FirstName(), )) - stdout, _ = cmdRun(t, exec.Command("mdz", "product", "list", + stdout, _ = cmdRun(t, exec.Command("mdz", "segment", "list", "--organization-id", organizationID, "--ledger-id", ledgerID, )) - productID := getIDListOutput(t, stdout) + segmentID := getIDListOutput(t, stdout) - stdout, _ = cmdRun(t, exec.Command("mdz", "product", "describe", + stdout, _ = cmdRun(t, exec.Command("mdz", "segment", "describe", "--organization-id", organizationID, "--ledger-id", ledgerID, - "--product-id", productID, + "--segment-id", segmentID, )) - stdout, _ = cmdRun(t, exec.Command("mdz", "product", "update", + stdout, _ = cmdRun(t, exec.Command("mdz", "segment", "update", "--organization-id", organizationID, "--ledger-id", ledgerID, - "--product-id", productID, + "--segment-id", segmentID, "--name", fake.FirstName(), )) @@ -164,6 +164,7 @@ func TestMDZ(t *testing.T) { "--organization-id", organizationID, "--ledger-id", ledgerID, "--portfolio-id", portfolioID, + "--segment-id", segmentID, "--name", fake.FirstName(), "--asset-code", "BRL", "--type", "creditCard", @@ -190,7 +191,7 @@ func TestMDZ(t *testing.T) { "--ledger-id", ledgerID, "--portfolio-id", portfolioID, "--account-id", accountID, - "--product-id", productID, + "--segment-id", segmentID, "--name", fake.FirstName(), "--alias", "@wallet_"+fake.FirstName(), )) @@ -199,7 +200,7 @@ func TestMDZ(t *testing.T) { t.Log("ledger ID: ", ledgerID) t.Log("asset ID: ", assetID) t.Log("portfolio ID: ", portfolioID) - t.Log("product ID: ", productID) + t.Log("segment ID: ", segmentID) t.Log("account ID: ", accountID) stdout, _ = cmdRun(t, exec.Command("mdz", "account", "delete", @@ -215,10 +216,10 @@ func TestMDZ(t *testing.T) { "--asset-id", assetID, )) - stdout, _ = cmdRun(t, exec.Command("mdz", "product", "delete", + stdout, _ = cmdRun(t, exec.Command("mdz", "segment", "delete", "--organization-id", organizationID, "--ledger-id", ledgerID, - "--product-id", productID, + "--segment-id", segmentID, )) stdout, _ = cmdRun(t, exec.Command("mdz", "portfolio", "delete", diff --git a/components/transaction/.env.example b/components/transaction/.env.example index 900fdd983..0357636db 100644 --- a/components/transaction/.env.example +++ b/components/transaction/.env.example @@ -4,7 +4,7 @@ # ENV_NAME=production # APP -VERSION=v1.46.0 +VERSION=v1.47.0 APP_CONTEXT=/transaction/v1 SERVER_PORT=3002 SERVER_ADDRESS=:${SERVER_PORT} diff --git a/go.mod b/go.mod index e50ce0fc2..2eed3fef4 100644 --- a/go.mod +++ b/go.mod @@ -43,8 +43,8 @@ require ( go.opentelemetry.io/otel/sdk/metric v1.34.0 go.opentelemetry.io/otel/trace v1.34.0 go.uber.org/mock v0.5.0 - google.golang.org/grpc v1.69.4 - google.golang.org/protobuf v1.36.3 + google.golang.org/grpc v1.70.0 + google.golang.org/protobuf v1.36.4 gotest.tools v2.2.0+incompatible ) @@ -55,7 +55,7 @@ require ( github.com/cenkalti/backoff/v4 v4.3.0 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/charmbracelet/lipgloss v1.0.0 // indirect - github.com/charmbracelet/x/ansi v0.7.0 // indirect + github.com/charmbracelet/x/ansi v0.8.0 // indirect github.com/charmbracelet/x/term v0.2.1 // indirect github.com/corpix/uarand v0.0.0-20170723150923-031be390f409 // indirect github.com/creack/pty v1.1.17 // indirect @@ -86,15 +86,15 @@ require ( golang.org/x/net v0.34.0 // indirect golang.org/x/oauth2 v0.25.0 // indirect golang.org/x/tools v0.29.0 // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20250115164207-1a7da9e5054f // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20250115164207-1a7da9e5054f // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20250127172529-29210b9bc287 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20250127172529-29210b9bc287 // indirect ) require ( github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/decred/dcrd/dcrec/secp256k1/v4 v4.3.0 // indirect github.com/fatih/color v1.18.0 - github.com/goccy/go-json v0.10.4 // indirect + github.com/goccy/go-json v0.10.5 // indirect github.com/golang/snappy v0.0.4 // indirect github.com/hashicorp/errwrap v1.1.0 // indirect github.com/hashicorp/go-multierror v1.1.1 // indirect @@ -108,7 +108,7 @@ require ( github.com/lestrrat-go/iter v1.0.2 // indirect github.com/lestrrat-go/option v1.0.1 // indirect github.com/montanaflynn/stats v0.7.1 // indirect - github.com/spf13/pflag v1.0.5 // indirect + github.com/spf13/pflag v1.0.6 // indirect github.com/xdg-go/pbkdf2 v1.0.0 // indirect github.com/xdg-go/scram v1.1.2 // indirect github.com/xdg-go/stringprep v1.0.4 // indirect @@ -116,7 +116,7 @@ require ( go.uber.org/atomic v1.11.0 // indirect go.uber.org/multierr v1.11.0 // indirect golang.org/x/crypto v0.32.0 // indirect - golang.org/x/exp v0.0.0-20250106191152-7588d65b2ba8 // indirect + golang.org/x/exp v0.0.0-20250128182459-e0ece0dbea4c // indirect golang.org/x/sync v0.10.0 // indirect golang.org/x/text v0.21.0 gopkg.in/go-playground/assert.v1 v1.2.1 // indirect @@ -128,7 +128,7 @@ require ( github.com/bxcodec/dbresolver/v2 v2.2.0 github.com/go-playground/validator v9.31.0+incompatible github.com/golang-jwt/jwt v3.2.2+incompatible - github.com/golang-migrate/migrate/v4 v4.18.1 + github.com/golang-migrate/migrate/v4 v4.18.2 github.com/google/uuid v1.6.0 github.com/klauspost/compress v1.17.11 // indirect github.com/lestrrat-go/jwx v1.2.30 diff --git a/go.sum b/go.sum index 6eace3168..c89c1d61e 100644 --- a/go.sum +++ b/go.sum @@ -41,8 +41,8 @@ github.com/charmbracelet/bubbletea v1.2.4 h1:KN8aCViA0eps9SCOThb2/XPIlea3ANJLUkv github.com/charmbracelet/bubbletea v1.2.4/go.mod h1:Qr6fVQw+wX7JkWWkVyXYk/ZUQ92a6XNekLXa3rR18MM= github.com/charmbracelet/lipgloss v1.0.0 h1:O7VkGDvqEdGi93X+DeqsQ7PKHDgtQfF8j8/O2qFMQNg= github.com/charmbracelet/lipgloss v1.0.0/go.mod h1:U5fy9Z+C38obMs+T+tJqst9VGzlOYGj4ri9reL3qUlo= -github.com/charmbracelet/x/ansi v0.7.0 h1:/QfFmiXOGGwN6fRbzvQaYp7fu1pkxpZ3qFBZWBsP404= -github.com/charmbracelet/x/ansi v0.7.0/go.mod h1:KBUFw1la39nl0dLl10l5ORDAqGXaeurTQmwyyVKse/Q= +github.com/charmbracelet/x/ansi v0.8.0 h1:9GTq3xq9caJW8ZrBTe0LIe2fvfLR/bYXKTx2llXn7xE= +github.com/charmbracelet/x/ansi v0.8.0/go.mod h1:wdYl/ONOLHLIVmQaxbIYEC/cRKOQyjTkowiI4blgS9Q= github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ= github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg= github.com/corpix/uarand v0.0.0-20170723150923-031be390f409 h1:9A+mfQmwzZ6KwUXPc8nHxFtKgn9VIvO3gXAOspIcE3s= @@ -60,8 +60,8 @@ github.com/decred/dcrd/dcrec/secp256k1/v4 v4.3.0 h1:rpfIENRNNilwHwZeG5+P150SMrnN github.com/decred/dcrd/dcrec/secp256k1/v4 v4.3.0/go.mod h1:v57UDF4pDQJcEfFUCRop3lJL149eHGSe9Jvczhzjo/0= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= -github.com/dhui/dktest v0.4.3 h1:wquqUxAFdcUgabAVLvSCOKOlag5cIZuaOjYIBOWdsR0= -github.com/dhui/dktest v0.4.3/go.mod h1:zNK8IwktWzQRm6I/l2Wjp7MakiyaFWv4G1hjmodmMTs= +github.com/dhui/dktest v0.4.4 h1:+I4s6JRE1yGuqflzwqG+aIaMdgXIorCf5P98JnaAWa8= +github.com/dhui/dktest v0.4.4/go.mod h1:4+22R4lgsdAXrDyaH4Nqx2JEz2hLp49MqQmm9HLCQhM= github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk= github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= github.com/docker/docker v27.3.1+incompatible h1:KttF0XoteNTicmUtBO0L2tP+J7FGRFTjaEF4k6WdhfI= @@ -102,8 +102,8 @@ github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJn github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= github.com/go-playground/validator v9.31.0+incompatible h1:UA72EPEogEnq76ehGdEDp4Mit+3FDh548oRqwVgNsHA= github.com/go-playground/validator v9.31.0+incompatible/go.mod h1:yrEkQXlcI+PugkyDjY2bRrL/UBU4f3rvrgkN3V8JEig= -github.com/goccy/go-json v0.10.4 h1:JSwxQzIqKfmFX1swYPpUThQZp/Ka4wzJdK0LWVytLPM= -github.com/goccy/go-json v0.10.4/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= +github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4= +github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= github.com/gofiber/fiber/v2 v2.32.0/go.mod h1:CMy5ZLiXkn6qwthrl03YMyW1NLfj0rhxz2LKl4t7ZTY= github.com/gofiber/fiber/v2 v2.52.6 h1:Rfp+ILPiYSvvVuIPvxrBns+HJp8qGLDnLJawAu27XVI= github.com/gofiber/fiber/v2 v2.52.6/go.mod h1:YEcBbO/FB+5M1IZNBP9FO3J9281zgPAreiI1oqg8nDw= @@ -113,8 +113,8 @@ github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keL github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I= github.com/golang-jwt/jwt/v4 v4.5.1 h1:JdqV9zKUdtaa9gdPlywC3aeoEsR681PlKC+4F5gQgeo= github.com/golang-jwt/jwt/v4 v4.5.1/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= -github.com/golang-migrate/migrate/v4 v4.18.1 h1:JML/k+t4tpHCpQTCAD62Nu43NUFzHY4CV3uAuvHGC+Y= -github.com/golang-migrate/migrate/v4 v4.18.1/go.mod h1:HAX6m3sQgcdO81tdjn5exv20+3Kb13cmGli1hrD6hks= +github.com/golang-migrate/migrate/v4 v4.18.2 h1:2VSCMz7x7mjyTXx3m2zPokOY82LTRgxK1yQYKo6wWQ8= +github.com/golang-migrate/migrate/v4 v4.18.2/go.mod h1:2CM6tJvn2kqPXwnXO/d3rAQYiyoIm180VsO8PRX6Rpk= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= @@ -253,8 +253,9 @@ github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1 github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM= github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y= -github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o= +github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= @@ -348,8 +349,8 @@ golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5y golang.org/x/crypto v0.0.0-20220214200702-86341886e292/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.32.0 h1:euUpcYgM8WcP71gNpTqQCn6rC2t6ULUPiOzfWaXVVfc= golang.org/x/crypto v0.32.0/go.mod h1:ZnnJkOaASj8g0AjIduWNlq2NRxL0PlBrbKVyZ6V/Ugc= -golang.org/x/exp v0.0.0-20250106191152-7588d65b2ba8 h1:yqrTHse8TCMW1M1ZCP+VAR/l0kKxwaAIqN/il7x4voA= -golang.org/x/exp v0.0.0-20250106191152-7588d65b2ba8/go.mod h1:tujkw807nyEEAamNbDrEGzRav+ilXA7PCRAd6xsmwiU= +golang.org/x/exp v0.0.0-20250128182459-e0ece0dbea4c h1:KL/ZBHXgKGVmuZBZ01Lt57yE5ws8ZPSkkihmEyq7FXc= +golang.org/x/exp v0.0.0-20250128182459-e0ece0dbea4c/go.mod h1:tujkw807nyEEAamNbDrEGzRav+ilXA7PCRAd6xsmwiU= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.22.0 h1:D4nJWe9zXqHOmWqj4VMOJhvzj7bEZg4wEYa759z1pH4= @@ -409,14 +410,14 @@ golang.org/x/tools v0.29.0/go.mod h1:KMQVMRsVxU6nHCFXrBPhDB8XncLNLM0lIy/F14RP588 golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/genproto/googleapis/api v0.0.0-20250115164207-1a7da9e5054f h1:gap6+3Gk41EItBuyi4XX/bp4oqJ3UwuIMl25yGinuAA= -google.golang.org/genproto/googleapis/api v0.0.0-20250115164207-1a7da9e5054f/go.mod h1:Ic02D47M+zbarjYYUlK57y316f2MoN0gjAwI3f2S95o= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250115164207-1a7da9e5054f h1:OxYkA3wjPsZyBylwymxSHa7ViiW1Sml4ToBrncvFehI= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250115164207-1a7da9e5054f/go.mod h1:+2Yz8+CLJbIfL9z73EW45avw8Lmge3xVElCP9zEKi50= -google.golang.org/grpc v1.69.4 h1:MF5TftSMkd8GLw/m0KM6V8CMOCY6NZ1NQDPGFgbTt4A= -google.golang.org/grpc v1.69.4/go.mod h1:vyjdE6jLBI76dgpDojsFGNaHlxdjXN9ghpnd2o7JGZ4= -google.golang.org/protobuf v1.36.3 h1:82DV7MYdb8anAVi3qge1wSnMDrnKK7ebr+I0hHRN1BU= -google.golang.org/protobuf v1.36.3/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= +google.golang.org/genproto/googleapis/api v0.0.0-20250127172529-29210b9bc287 h1:A2ni10G3UlplFrWdCDJTl7D7mJ7GSRm37S+PDimaKRw= +google.golang.org/genproto/googleapis/api v0.0.0-20250127172529-29210b9bc287/go.mod h1:iYONQfRdizDB8JJBybql13nArx91jcUk7zCXEsOofM4= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250127172529-29210b9bc287 h1:J1H9f+LEdWAfHcez/4cvaVBox7cOYT+IU6rgqj5x++8= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250127172529-29210b9bc287/go.mod h1:8BS3B93F/U1juMFq9+EDk+qOT5CO1R9IzXxG3PTqiRk= +google.golang.org/grpc v1.70.0 h1:pWFv03aZoHzlRKHWicjsZytKAiYCtNS0dHbXnIdq7jQ= +google.golang.org/grpc v1.70.0/go.mod h1:ofIJqVKDXx/JiXrwr2IG4/zwdH9txy3IlF40RmcJSQw= +google.golang.org/protobuf v1.36.4 h1:6A3ZDJHn/eNqc1i+IdefRzy/9PokBTPvcqMySR7NNIM= +google.golang.org/protobuf v1.36.4/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/pkg/constant/errors.go b/pkg/constant/errors.go index 6eb1363ba..f8aa49239 100644 --- a/pkg/constant/errors.go +++ b/pkg/constant/errors.go @@ -21,8 +21,8 @@ var ( ErrInactiveAccountType = errors.New("0011") ErrAccountBalanceDeletion = errors.New("0012") ErrResourceAlreadyDeleted = errors.New("0013") - ErrProductIDInactive = errors.New("0014") - ErrDuplicateProductName = errors.New("0015") + ErrSegmentIDInactive = errors.New("0014") + ErrDuplicateSegmentName = errors.New("0015") ErrBalanceRemainingDeletion = errors.New("0016") ErrInvalidScriptFormat = errors.New("0017") ErrInsufficientFunds = errors.New("0018") @@ -43,7 +43,7 @@ var ( ErrInvalidCodeFormat = errors.New("0033") ErrAssetCodeNotFound = errors.New("0034") ErrPortfolioIDNotFound = errors.New("0035") - ErrProductIDNotFound = errors.New("0036") + ErrSegmentIDNotFound = errors.New("0036") ErrLedgerIDNotFound = errors.New("0037") ErrOrganizationIDNotFound = errors.New("0038") ErrParentOrganizationIDNotFound = errors.New("0039") @@ -64,7 +64,7 @@ var ( ErrIDsNotFoundForAccounts = errors.New("0054") ErrAssetIDNotFound = errors.New("0055") ErrNoAssetsFound = errors.New("0056") - ErrNoProductsFound = errors.New("0057") + ErrNoSegmentsFound = errors.New("0057") ErrNoPortfoliosFound = errors.New("0058") ErrNoOrganizationsFound = errors.New("0059") ErrNoLedgersFound = errors.New("0060") diff --git a/pkg/constant/http.go b/pkg/constant/http.go index 2f4263bc8..23e529edd 100644 --- a/pkg/constant/http.go +++ b/pkg/constant/http.go @@ -6,7 +6,7 @@ var UUIDPathParameters = []string{ "ledger_id", "asset_id", "portfolio_id", - "product_id", + "segment_id", "account_id", "transaction_id", "operation_id", diff --git a/pkg/errors.go b/pkg/errors.go index 758e02994..856beb61b 100644 --- a/pkg/errors.go +++ b/pkg/errors.go @@ -375,17 +375,17 @@ func ValidateBusinessError(err error, entityType string, args ...any) error { Title: "Resource Already Deleted", Message: "The resource you are trying to delete has already been deleted. Ensure you are using the correct ID and try again.", }, - constant.ErrProductIDInactive: ValidationError{ + constant.ErrSegmentIDInactive: ValidationError{ EntityType: entityType, - Code: constant.ErrProductIDInactive.Error(), - Title: "Product ID Inactive", - Message: "The Product ID you are attempting to use is inactive. Please use another Product ID and try again.", + Code: constant.ErrSegmentIDInactive.Error(), + Title: "Segment ID Inactive", + Message: "The Segment ID you are attempting to use is inactive. Please use another Segment ID and try again.", }, - constant.ErrDuplicateProductName: EntityConflictError{ + constant.ErrDuplicateSegmentName: EntityConflictError{ EntityType: entityType, - Code: constant.ErrDuplicateProductName.Error(), - Title: "Duplicate Product Name Error", - Message: fmt.Sprintf("A product with the name %v already exists for this ledger ID %v. Please try again with a different ledger or name.", args...), + Code: constant.ErrDuplicateSegmentName.Error(), + Title: "Duplicate Segment Name Error", + Message: fmt.Sprintf("A segment with the name %v already exists for this ledger ID %v. Please try again with a different ledger or name.", args...), }, constant.ErrBalanceRemainingDeletion: UnprocessableOperationError{ EntityType: entityType, @@ -507,11 +507,11 @@ func ValidateBusinessError(err error, entityType string, args ...any) error { Title: "Portfolio ID Not Found", Message: "The provided portfolio ID does not exist in our records. Please verify the portfolio ID and try again.", }, - constant.ErrProductIDNotFound: EntityNotFoundError{ + constant.ErrSegmentIDNotFound: EntityNotFoundError{ EntityType: entityType, - Code: constant.ErrProductIDNotFound.Error(), - Title: "Product ID Not Found", - Message: "The provided product ID does not exist in our records. Please verify the product ID and try again.", + Code: constant.ErrSegmentIDNotFound.Error(), + Title: "Segment ID Not Found", + Message: "The provided segment ID does not exist in our records. Please verify the segment ID and try again.", }, constant.ErrLedgerIDNotFound: EntityNotFoundError{ EntityType: entityType, @@ -615,11 +615,11 @@ func ValidateBusinessError(err error, entityType string, args ...any) error { Title: "No Assets Found", Message: "No assets were found in the search. Please review the search criteria and try again.", }, - constant.ErrNoProductsFound: EntityNotFoundError{ + constant.ErrNoSegmentsFound: EntityNotFoundError{ EntityType: entityType, - Code: constant.ErrNoProductsFound.Error(), - Title: "No Products Found", - Message: "No products were found in the search. Please review the search criteria and try again.", + Code: constant.ErrNoSegmentsFound.Error(), + Title: "No Segments Found", + Message: "No segments were found in the search. Please review the search criteria and try again.", }, constant.ErrNoPortfoliosFound: EntityNotFoundError{ EntityType: entityType, diff --git a/pkg/gold/transaction/model/validations.go b/pkg/gold/transaction/model/validations.go index be98aa8c3..ef4784434 100644 --- a/pkg/gold/transaction/model/validations.go +++ b/pkg/gold/transaction/model/validations.go @@ -150,7 +150,7 @@ func UpdateAccounts(operation string, fromTo map[string]Amount, accounts []*a.Ac OrganizationId: acc.OrganizationId, LedgerId: acc.LedgerId, PortfolioId: acc.PortfolioId, - ProductId: acc.ProductId, + SegmentId: acc.SegmentId, AssetCode: acc.AssetCode, Balance: &balance, Status: &status, diff --git a/pkg/mgrpc/account/account.pb.go b/pkg/mgrpc/account/account.pb.go index 6d1f5000a..e60aa56c5 100644 --- a/pkg/mgrpc/account/account.pb.go +++ b/pkg/mgrpc/account/account.pb.go @@ -198,7 +198,7 @@ type Account struct { OrganizationId string `protobuf:"bytes,6,opt,name=organization_id,json=organizationId,proto3" json:"organization_id,omitempty"` LedgerId string `protobuf:"bytes,7,opt,name=ledger_id,json=ledgerId,proto3" json:"ledger_id,omitempty"` PortfolioId string `protobuf:"bytes,8,opt,name=portfolio_id,json=portfolioId,proto3" json:"portfolio_id,omitempty"` - ProductId string `protobuf:"bytes,9,opt,name=product_id,json=productId,proto3" json:"product_id,omitempty"` + SegmentId string `protobuf:"bytes,9,opt,name=segment_id,json=segmentId,proto3" json:"segment_id,omitempty"` Balance *Balance `protobuf:"bytes,10,opt,name=balance,proto3" json:"balance,omitempty"` Status *Status `protobuf:"bytes,11,opt,name=status,proto3" json:"status,omitempty"` AllowSending bool `protobuf:"varint,12,opt,name=allow_sending,json=allowSending,proto3" json:"allow_sending,omitempty"` @@ -300,9 +300,9 @@ func (x *Account) GetPortfolioId() string { return "" } -func (x *Account) GetProductId() string { +func (x *Account) GetSegmentId() string { if x != nil { - return x.ProductId + return x.SegmentId } return "" } diff --git a/pkg/mgrpc/account/account.proto b/pkg/mgrpc/account/account.proto index f3a3cca5c..948ac7c96 100644 --- a/pkg/mgrpc/account/account.proto +++ b/pkg/mgrpc/account/account.proto @@ -27,7 +27,7 @@ message Account { string organization_id = 6; string ledger_id = 7; string portfolio_id = 8; - string product_id = 9; + string segment_id = 9; Balance balance = 10; Status status = 11; bool allow_sending= 12; diff --git a/pkg/mmodel/account.go b/pkg/mmodel/account.go index 6a54e627c..3a073ca41 100644 --- a/pkg/mmodel/account.go +++ b/pkg/mmodel/account.go @@ -16,7 +16,7 @@ type CreateAccountInput struct { Alias *string `json:"alias" validate:"max=100,prohibitedexternalaccountprefix" example:"@person1"` Type string `json:"type" validate:"required" example:"creditCard"` ParentAccountID *string `json:"parentAccountId" validate:"omitempty,uuid" example:"00000000-0000-0000-0000-000000000000"` - ProductID *string `json:"productId" validate:"omitempty,uuid" example:"00000000-0000-0000-0000-000000000000"` + SegmentID *string `json:"segmentId" validate:"omitempty,uuid" example:"00000000-0000-0000-0000-000000000000"` PortfolioID *string `json:"portfolioId" validate:"omitempty,uuid" example:"00000000-0000-0000-0000-000000000000"` EntityID *string `json:"entityId" validate:"omitempty,max=256" example:"00000000-0000-0000-0000-000000000000"` Status Status `json:"status"` @@ -35,7 +35,7 @@ type UpdateAccountInput struct { AllowSending *bool `json:"allowSending" example:"true"` AllowReceiving *bool `json:"allowReceiving" example:"true"` Alias *string `json:"alias" validate:"omitempty,max=100,prohibitedexternalaccountprefix" example:"@person1"` - ProductID *string `json:"productId" validate:"omitempty,uuid" example:"00000000-0000-0000-0000-000000000000"` + SegmentID *string `json:"segmentId" validate:"omitempty,uuid" example:"00000000-0000-0000-0000-000000000000"` PortfolioID *string `json:"portfolioId" validate:"omitempty,uuid" example:"00000000-0000-0000-0000-000000000000"` Metadata map[string]any `json:"metadata" validate:"dive,keys,keymax=100,endkeys,nonested,valuemax=2000"` } // @name UpdateAccountInput @@ -53,7 +53,7 @@ type Account struct { OrganizationID string `json:"organizationId" example:"00000000-0000-0000-0000-000000000000"` LedgerID string `json:"ledgerId" example:"00000000-0000-0000-0000-000000000000"` PortfolioID *string `json:"portfolioId" example:"00000000-0000-0000-0000-000000000000"` - ProductID *string `json:"productId" example:"00000000-0000-0000-0000-000000000000"` + SegmentID *string `json:"segmentId" example:"00000000-0000-0000-0000-000000000000"` Balance Balance `json:"balance"` Status Status `json:"status"` AllowSending *bool `json:"allowSending" example:"true"` @@ -146,8 +146,8 @@ func (e *Account) ToProto() *proto.Account { account.PortfolioId = *e.PortfolioID } - if e.ProductID != nil { - account.ProductId = *e.ProductID + if e.SegmentID != nil { + account.SegmentId = *e.SegmentID } if e.Alias != nil { diff --git a/pkg/mmodel/account_test.go b/pkg/mmodel/account_test.go index a90e25a6e..8978eb4d9 100644 --- a/pkg/mmodel/account_test.go +++ b/pkg/mmodel/account_test.go @@ -87,7 +87,7 @@ func TestAccount_ToProto(t *testing.T) { DeletedAt: timeDel, EntityID: ptr.StringPtr("EntityID"), PortfolioID: ptr.StringPtr("PortfolioID"), - ProductID: ptr.StringPtr("ProductID"), + SegmentID: ptr.StringPtr("SegmentID"), Alias: ptr.StringPtr("Alias"), }, expected: &proto.Account{ diff --git a/pkg/mmodel/product.go b/pkg/mmodel/cluster.go similarity index 55% rename from pkg/mmodel/product.go rename to pkg/mmodel/cluster.go index 7d6de61cb..e5d57b8b4 100644 --- a/pkg/mmodel/product.go +++ b/pkg/mmodel/cluster.go @@ -2,33 +2,33 @@ package mmodel import "time" -// CreateProductInput is a struct design to encapsulate request create payload data. +// CreateSegmentInput is a struct design to encapsulate request create payload data. // -// swagger:model CreateProductInput -// @Description CreateProductInput is the input payload to create a product. -type CreateProductInput struct { - Name string `json:"name" validate:"required,max=256" example:"My Product"` +// swagger:model CreateSegmentInput +// @Description CreateSegmentInput is the input payload to create a segment. +type CreateSegmentInput struct { + Name string `json:"name" validate:"required,max=256" example:"My Segment"` Status Status `json:"status"` Metadata map[string]any `json:"metadata" validate:"dive,keys,keymax=100,endkeys,nonested,valuemax=2000"` -} // @name CreateProductInput +} // @name CreateSegmentInput -// UpdateProductInput is a struct design to encapsulate request update payload data. +// UpdateSegmentInput is a struct design to encapsulate request update payload data. // -// swagger:model UpdateProductInput -// @Description UpdateProductInput is the input payload to update a product. -type UpdateProductInput struct { - Name string `json:"name" validate:"max=256" example:"My Product Updated"` +// swagger:model UpdateSegmentInput +// @Description UpdateSegmentInput is the input payload to update a segment. +type UpdateSegmentInput struct { + Name string `json:"name" validate:"max=256" example:"My Segment Updated"` Status Status `json:"status"` Metadata map[string]any `json:"metadata" validate:"dive,keys,keymax=100,endkeys,nonested,valuemax=2000"` -} // @name UpdateProductInput +} // @name UpdateSegmentInput -// Product is a struct designed to encapsulate payload data. +// Segment is a struct designed to encapsulate payload data. // -// swagger:model Product -// @Description Product is a struct designed to store product data. -type Product struct { +// swagger:model Segment +// @Description Segment is a struct designed to store segment data. +type Segment struct { ID string `json:"id" example:"00000000-0000-0000-0000-000000000000"` - Name string `json:"name" example:"My Product"` + Name string `json:"name" example:"My Segment"` LedgerID string `json:"ledgerId" example:"00000000-0000-0000-0000-000000000000"` OrganizationID string `json:"organizationId" example:"00000000-0000-0000-0000-000000000000"` Status Status `json:"status"` @@ -36,14 +36,14 @@ type Product struct { UpdatedAt time.Time `json:"updatedAt" example:"2021-01-01T00:00:00Z"` DeletedAt *time.Time `json:"deletedAt" example:"2021-01-01T00:00:00Z"` Metadata map[string]any `json:"metadata,omitempty"` -} // @name Product +} // @name Segment -// Products struct to return get all. +// Segments struct to return get all. // -// swagger:model Products -// @Description Products is the struct designed to return a list of products with pagination. -type Products struct { - Items []Product `json:"items"` +// swagger:model Segments +// @Description Segments is the struct designed to return a list of segments with pagination. +type Segments struct { + Items []Segment `json:"items"` Page int `json:"page" example:"1"` Limit int `json:"limit" example:"10"` -} // @name Products +} // @name Segments diff --git a/postman/MIDAZ.postman_collection.json b/postman/MIDAZ.postman_collection.json index 55021e7bc..c901dcb59 100644 --- a/postman/MIDAZ.postman_collection.json +++ b/postman/MIDAZ.postman_collection.json @@ -1509,10 +1509,10 @@ ] }, { - "name": "Products", + "name": "Segments", "item": [ { - "name": "Products", + "name": "Segments", "event": [ { "listen": "test", @@ -1520,9 +1520,9 @@ "exec": [ "const jsonData = JSON.parse(responseBody);", "if (jsonData.hasOwnProperty('id')) {", - " console.log(\"product_id before: \" + pm.collectionVariables.get(\"product_id\"));", - " pm.collectionVariables.set(\"product_id\", jsonData.id);", - " console.log(\"product_id after: \" + pm.collectionVariables.get(\"product_id\"));", + " console.log(\"segment_id before: \" + pm.collectionVariables.get(\"segment_id\"));", + " pm.collectionVariables.set(\"segment_id\", jsonData.id);", + " console.log(\"segment_id after: \" + pm.collectionVariables.get(\"segment_id\"));", "}" ], "type": "text/javascript", @@ -1542,7 +1542,7 @@ ], "body": { "mode": "raw", - "raw": "{\n \"name\": \"Product {{$randomProductName}}\",\n \"status\": {\n \"code\": \"ACTIVE\",\n \"description\": \"Product Test\"\n },\n \"metadata\": {\n \"chave\": \"metadata_sample\",\n \"bitcoinn\": \"{{$randomBitcoin}}\",\n \"boolean\": {{$randomBoolean}},\n \"double\": 10.5,\n \"int\": 1\n }\n}", + "raw": "{\n \"name\": \"Segment {{$randomProductName}}\",\n \"status\": {\n \"code\": \"ACTIVE\",\n \"description\": \"Segment Test\"\n },\n \"metadata\": {\n \"chave\": \"metadata_sample\",\n \"bitcoinn\": \"{{$randomBitcoin}}\",\n \"boolean\": {{$randomBoolean}},\n \"double\": 10.5,\n \"int\": 1\n }\n}", "options": { "raw": { "language": "json" @@ -1550,7 +1550,7 @@ } }, "url": { - "raw": "{{url_ledger}}/v1/organizations/{{organization_id}}/ledgers/{{ledger_id}}/products", + "raw": "{{url_ledger}}/v1/organizations/{{organization_id}}/ledgers/{{ledger_id}}/segments", "host": [ "{{url_ledger}}" ], @@ -1560,14 +1560,14 @@ "{{organization_id}}", "ledgers", "{{ledger_id}}", - "products" + "segments" ] } }, "response": [] }, { - "name": "Products", + "name": "Segments", "event": [ { "listen": "test", @@ -1592,7 +1592,7 @@ ], "body": { "mode": "raw", - "raw": "{\n \"name\": \"Product {{$randomProductName}} BLOCKED\",\n \"status\": {\n \"code\": \"BLOCKED\",\n \"description\": \"My blocked Product\"\n },\n \"metadata\": {\n \"chave\": \"metadata_sample_update\",\n \"bitcoinn\": \"{{$randomBitcoin}}\",\n \"boolean\": {{$randomBoolean}},\n \"double\": 10.5,\n \"int\": 1\n }\n}", + "raw": "{\n \"name\": \"Segment {{$randomProductName}} BLOCKED\",\n \"status\": {\n \"code\": \"BLOCKED\",\n \"description\": \"My blocked Segment\"\n },\n \"metadata\": {\n \"chave\": \"metadata_sample_update\",\n \"bitcoinn\": \"{{$randomBitcoin}}\",\n \"boolean\": {{$randomBoolean}},\n \"double\": 10.5,\n \"int\": 1\n }\n}", "options": { "raw": { "language": "json" @@ -1600,7 +1600,7 @@ } }, "url": { - "raw": "{{url_ledger}}/v1/organizations/{{organization_id}}/ledgers/{{ledger_id}}/products/{{product_id}}", + "raw": "{{url_ledger}}/v1/organizations/{{organization_id}}/ledgers/{{ledger_id}}/segments/{{segment_id}}", "host": [ "{{url_ledger}}" ], @@ -1610,15 +1610,15 @@ "{{organization_id}}", "ledgers", "{{ledger_id}}", - "products", - "{{product_id}}" + "segments", + "{{segment_id}}" ] } }, "response": [] }, { - "name": "Products", + "name": "Segments", "protocolProfileBehavior": { "disableBodyPruning": true }, @@ -1637,7 +1637,7 @@ "formdata": [] }, "url": { - "raw": "{{url_ledger}}/v1/organizations/{{organization_id}}/ledgers/{{ledger_id}}/products?limit=5&page=1", + "raw": "{{url_ledger}}/v1/organizations/{{organization_id}}/ledgers/{{ledger_id}}/segments?limit=5&page=1", "host": [ "{{url_ledger}}" ], @@ -1647,7 +1647,7 @@ "{{organization_id}}", "ledgers", "{{ledger_id}}", - "products" + "segments" ], "query": [ { @@ -1690,7 +1690,7 @@ "response": [] }, { - "name": "Products by Id", + "name": "Segments by Id", "protocolProfileBehavior": { "disableBodyPruning": true }, @@ -1709,7 +1709,7 @@ "formdata": [] }, "url": { - "raw": "{{url_ledger}}/v1/organizations/{{organization_id}}/ledgers/{{ledger_id}}/products/{{product_id}}", + "raw": "{{url_ledger}}/v1/organizations/{{organization_id}}/ledgers/{{ledger_id}}/segments/{{segment_id}}", "host": [ "{{url_ledger}}" ], @@ -1719,15 +1719,15 @@ "{{organization_id}}", "ledgers", "{{ledger_id}}", - "products", - "{{product_id}}" + "segments", + "{{segment_id}}" ] } }, "response": [] }, { - "name": "Products", + "name": "Segments", "request": { "method": "DELETE", "header": [ @@ -1743,7 +1743,7 @@ "formdata": [] }, "url": { - "raw": "{{url_ledger}}/v1/organizations/{{organization_id}}/ledgers/{{ledger_id}}/products/{{product_id}}", + "raw": "{{url_ledger}}/v1/organizations/{{organization_id}}/ledgers/{{ledger_id}}/segments/{{segment_id}}", "host": [ "{{url_ledger}}" ], @@ -1753,8 +1753,8 @@ "{{organization_id}}", "ledgers", "{{ledger_id}}", - "products", - "{{product_id}}" + "segments", + "{{segment_id}}" ] } }, @@ -1805,7 +1805,7 @@ ], "body": { "mode": "raw", - "raw": "{\n \"assetCode\": \"BRL\",\n \"name\": \"{{$randomBankAccountName}}\",\n \"alias\": \"@wallet_{{$randomBankAccount}}\",\n \"type\": \"creditCard\",\n //\"parentAccountId\": \"{{account_id}}\",\n //\"entityId\": \"{{$randomUUID}}\", //optional\n \"productId\": \"{{product_id}}\",\n \"status\": {\n \"code\": \"CREDIT\",\n \"description\": \"Account Test\"\n },\n \"allowSending\": true,\n \"allowReceiving\": true,\n \"metadata\": {\n \"chave\": \"metadata_sample\",\n \"bitcoinn\": \"{{$randomBitcoin}}\",\n \"boolean\": {{$randomBoolean}},\n \"double\": 10.5,\n \"int\": 1\n }\n}", + "raw": "{\n \"assetCode\": \"BRL\",\n \"name\": \"{{$randomBankAccountName}}\",\n \"alias\": \"@wallet_{{$randomBankAccount}}\",\n \"type\": \"creditCard\",\n //\"parentAccountId\": \"{{account_id}}\",\n //\"entityId\": \"{{$randomUUID}}\", //optional\n \"segmentId\": \"{{segment_id}}\",\n \"status\": {\n \"code\": \"CREDIT\",\n \"description\": \"Account Test\"\n },\n \"allowSending\": true,\n \"allowReceiving\": true,\n \"metadata\": {\n \"chave\": \"metadata_sample\",\n \"bitcoinn\": \"{{$randomBitcoin}}\",\n \"boolean\": {{$randomBoolean}},\n \"double\": 10.5,\n \"int\": 1\n }\n}", "options": { "raw": { "language": "json" @@ -1871,7 +1871,7 @@ ], "body": { "mode": "raw", - "raw": "{\n \"assetCode\": \"BRL\",\n \"name\": \"{{$randomBankAccountName}}\",\n \"alias\": \"@wallet_{{$randomBankAccount}}\",\n \"type\": \"creditCard\",\n //\"parentAccountId\": \"{{account_id}}\",\n //\"entityId\": \"{{$randomUUID}}\", //optional\n \"portfolioId\": \"{{portfolio_id}}\",\n \"productId\": \"{{product_id}}\",\n \"status\": {\n \"code\": \"CREDIT\",\n \"description\": \"Account Test\"\n },\n \"allowSending\": true,\n \"allowReceiving\": true,\n \"metadata\": {\n \"chave\": \"metadata_sample\",\n \"bitcoinn\": \"{{$randomBitcoin}}\",\n \"boolean\": {{$randomBoolean}},\n \"double\": 10.5,\n \"int\": 1\n }\n}", + "raw": "{\n \"assetCode\": \"BRL\",\n \"name\": \"{{$randomBankAccountName}}\",\n \"alias\": \"@wallet_{{$randomBankAccount}}\",\n \"type\": \"creditCard\",\n //\"parentAccountId\": \"{{account_id}}\",\n //\"entityId\": \"{{$randomUUID}}\", //optional\n \"portfolioId\": \"{{portfolio_id}}\",\n \"segmentId\": \"{{segment_id}}\",\n \"status\": {\n \"code\": \"CREDIT\",\n \"description\": \"Account Test\"\n },\n \"allowSending\": true,\n \"allowReceiving\": true,\n \"metadata\": {\n \"chave\": \"metadata_sample\",\n \"bitcoinn\": \"{{$randomBitcoin}}\",\n \"boolean\": {{$randomBoolean}},\n \"double\": 10.5,\n \"int\": 1\n }\n}", "options": { "raw": { "language": "json" @@ -1921,7 +1921,7 @@ ], "body": { "mode": "raw", - "raw": "{\n \"name\": \"{{$randomBankAccountName}} Blocked Account\", //opcional\n \"alias\": \"Wallet {{$randomBankAccount}}\",\n \"productId\": \"{{product_id}}\",\n \"status\": {\n \"code\": \"BLOCKED\",\n \"description\": \"My blocked account\"\n },\n \"allowSending\": true,\n \"allowReceiving\": true,\n \"metadata\": {\n \"chave\": \"metadata_sample_update\",\n \"bitcoinn\": \"{{$randomBitcoin}}\",\n \"boolean\": {{$randomBoolean}},\n \"double\": 10.5,\n \"int\": 1\n }\n}", + "raw": "{\n \"name\": \"{{$randomBankAccountName}} Blocked Account\", //opcional\n \"alias\": \"Wallet {{$randomBankAccount}}\",\n \"segmentId\": \"{{segment_id}}\",\n \"status\": {\n \"code\": \"BLOCKED\",\n \"description\": \"My blocked account\"\n },\n \"allowSending\": true,\n \"allowReceiving\": true,\n \"metadata\": {\n \"chave\": \"metadata_sample_update\",\n \"bitcoinn\": \"{{$randomBitcoin}}\",\n \"boolean\": {{$randomBoolean}},\n \"double\": 10.5,\n \"int\": 1\n }\n}", "options": { "raw": { "language": "json" @@ -1974,7 +1974,7 @@ ], "body": { "mode": "raw", - "raw": "{\n \"name\": \"{{$randomBankAccountName}} Blocked Account\", //opcional\n \"alias\": \"Wallet {{$randomBankAccount}}\",\n \"productId\": \"{{product_id}}\",\n // \"portfolioId\": {{portfolio_id}},\n \"status\": {\n \"code\": \"BLOCKED\",\n \"description\": \"My blocked account\"\n },\n \"allowSending\": true,\n \"allowReceiving\": true,\n \"metadata\": {\n \"chave\": \"metadata_sample_update\",\n \"bitcoinn\": \"{{$randomBitcoin}}\",\n \"boolean\": {{$randomBoolean}},\n \"double\": 10.5,\n \"int\": 1\n }\n}", + "raw": "{\n \"name\": \"{{$randomBankAccountName}} Blocked Account\", //opcional\n \"alias\": \"Wallet {{$randomBankAccount}}\",\n \"segmentId\": \"{{segment_id}}\",\n // \"portfolioId\": {{portfolio_id}},\n \"status\": {\n \"code\": \"BLOCKED\",\n \"description\": \"My blocked account\"\n },\n \"allowSending\": true,\n \"allowReceiving\": true,\n \"metadata\": {\n \"chave\": \"metadata_sample_update\",\n \"bitcoinn\": \"{{$randomBitcoin}}\",\n \"boolean\": {{$randomBoolean}},\n \"double\": 10.5,\n \"int\": 1\n }\n}", "options": { "raw": { "language": "json" @@ -3689,7 +3689,7 @@ "type": "default" }, { - "key": "product_id", + "key": "segment_id", "value": "", "type": "default" },