From 2ebe5251282617b2219b4c844d3193c77efd1a72 Mon Sep 17 00:00:00 2001 From: Ali Date: Wed, 15 Apr 2026 19:33:59 +0200 Subject: [PATCH 1/4] U --- .../src/sdk/modules/abac/InviteToWorkspace.ts | 141 +++++ .../modules/abac/WorkspaceInvitationDto.ts | 488 ++++++++++++++++++ .../modules/abac/usePostWorkspaceInvite.ts | 2 +- modules/abac/AbacCustomActions.dyno.go | 96 ++-- modules/abac/AbacModule3.yml | 68 ++- modules/abac/InviteToWorkspaceAction.dyno.go | 254 +++++++++ modules/abac/InviteToWorkspaceAction.go | 30 +- modules/abac/WorkspaceInvitationDto.dyno.go | 121 +++++ .../sdk/modules/abac/InviteToWorkspace.ts | 141 +++++ .../modules/abac/WorkspaceInvitationDto.ts | 488 ++++++++++++++++++ .../modules/abac/usePostWorkspaceInvite.ts | 2 +- 11 files changed, 1748 insertions(+), 83 deletions(-) create mode 100644 e2e/react-bed/src/sdk/modules/abac/InviteToWorkspace.ts create mode 100644 e2e/react-bed/src/sdk/modules/abac/WorkspaceInvitationDto.ts create mode 100644 modules/abac/InviteToWorkspaceAction.dyno.go create mode 100644 modules/abac/WorkspaceInvitationDto.dyno.go create mode 100644 modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/InviteToWorkspace.ts create mode 100644 modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/WorkspaceInvitationDto.ts diff --git a/e2e/react-bed/src/sdk/modules/abac/InviteToWorkspace.ts b/e2e/react-bed/src/sdk/modules/abac/InviteToWorkspace.ts new file mode 100644 index 000000000..1f4db27d7 --- /dev/null +++ b/e2e/react-bed/src/sdk/modules/abac/InviteToWorkspace.ts @@ -0,0 +1,141 @@ +import { WorkspaceInvitationDto } from "./WorkspaceInvitationDto"; +import { buildUrl } from "../../sdk/common/buildUrl"; +import { + fetchx, + handleFetchResponse, + type FetchxContext, + type TypedRequestInit, + type TypedResponse, +} from "../../sdk/common/fetchx"; +import { type UseMutationOptions, useMutation } from "react-query"; +import { useFetchxContext } from "../../sdk/react/useFetchx"; +import { useState } from "react"; +/** + * Action to communicate with the action InviteToWorkspace + */ +export type InviteToWorkspaceActionOptions = { + queryKey?: unknown[]; + qs?: URLSearchParams; +}; +export type InviteToWorkspaceActionMutationOptions = Omit< + UseMutationOptions, + "mutationFn" +> & + InviteToWorkspaceActionOptions & { + ctx?: FetchxContext; + onMessage?: (ev: MessageEvent) => void; + overrideUrl?: string; + headers?: Headers; + } & Partial<{ + creatorFn: (item: unknown) => WorkspaceInvitationDto; + }>; +export const useInviteToWorkspaceAction = ( + options?: InviteToWorkspaceActionMutationOptions, +) => { + const globalCtx = useFetchxContext(); + const ctx = options?.ctx ?? globalCtx ?? undefined; + const [isCompleted, setCompleteState] = useState(false); + const [response, setResponse] = useState>(); + const fn = (body: WorkspaceInvitationDto) => { + setCompleteState(false); + return InviteToWorkspaceAction.Fetch( + { + body, + headers: options?.headers, + }, + { + creatorFn: options?.creatorFn, + qs: options?.qs, + ctx, + onMessage: options?.onMessage, + overrideUrl: options?.overrideUrl, + }, + ).then((x) => { + x.done.then(() => { + setCompleteState(true); + }); + setResponse(x.response); + return x.response.result; + }); + }; + const result = useMutation({ + mutationFn: fn, + ...(options || {}), + }); + return { + ...result, + isCompleted, + response, + }; +}; +/** + * InviteToWorkspaceAction + */ +export class InviteToWorkspaceAction { + // + static URL = "/workspace/invite"; + static NewUrl = (qs?: URLSearchParams) => + buildUrl(InviteToWorkspaceAction.URL, undefined, qs); + static Method = "post"; + static Fetch$ = async ( + qs?: URLSearchParams, + ctx?: FetchxContext, + init?: TypedRequestInit, + overrideUrl?: string, + ) => { + return fetchx( + overrideUrl ?? InviteToWorkspaceAction.NewUrl(qs), + { + method: InviteToWorkspaceAction.Method, + ...(init || {}), + }, + ctx, + ); + }; + static Fetch = async ( + init?: TypedRequestInit, + { + creatorFn, + qs, + ctx, + onMessage, + overrideUrl, + }: { + creatorFn?: ((item: unknown) => WorkspaceInvitationDto) | undefined; + qs?: URLSearchParams; + ctx?: FetchxContext; + onMessage?: (ev: MessageEvent) => void; + overrideUrl?: string; + } = { + creatorFn: (item) => new WorkspaceInvitationDto(item), + }, + ) => { + creatorFn = creatorFn || ((item) => new WorkspaceInvitationDto(item)); + const res = await InviteToWorkspaceAction.Fetch$( + qs, + ctx, + init, + overrideUrl, + ); + return handleFetchResponse( + res, + (item) => (creatorFn ? creatorFn(item) : item), + onMessage, + init?.signal, + ); + }; + static Definition = { + name: "InviteToWorkspace", + cliName: "invite", + url: "/workspace/invite", + method: "post", + description: + "Invite a new person (either a user, with passport or without passport)", + in: { + dto: "WorkspaceInvitationDto", + }, + out: { + dto: "WorkspaceInvitationDto", + }, + }; +} diff --git a/e2e/react-bed/src/sdk/modules/abac/WorkspaceInvitationDto.ts b/e2e/react-bed/src/sdk/modules/abac/WorkspaceInvitationDto.ts new file mode 100644 index 000000000..7cbef18d0 --- /dev/null +++ b/e2e/react-bed/src/sdk/modules/abac/WorkspaceInvitationDto.ts @@ -0,0 +1,488 @@ +// @ts-nocheck + // This no check has been added via fireback. +import { WorkspaceEntity } from "./WorkspaceEntity"; +import { type PartialDeep } from "../../sdk/common/fetchx"; +import { withPrefix } from "../../sdk/common/withPrefix"; +/** + * The base class definition for workspaceInvitationDto + **/ +export class WorkspaceInvitationDto { + /** + * A long hash to get the user into the confirm or signup page without sending the email or phone number, for example if an administrator wants to copy the link. + * @type {string} + **/ + #publicKey: string = ""; + /** + * A long hash to get the user into the confirm or signup page without sending the email or phone number, for example if an administrator wants to copy the link. + * @returns {string} + **/ + get publicKey() { + return this.#publicKey; + } + /** + * A long hash to get the user into the confirm or signup page without sending the email or phone number, for example if an administrator wants to copy the link. + * @type {string} + **/ + set publicKey(value: string) { + this.#publicKey = String(value); + } + setPublicKey(value: string) { + this.publicKey = value; + return this; + } + /** + * The content that user will receive to understand the reason of the letter. + * @type {string} + **/ + #coverLetter: string = ""; + /** + * The content that user will receive to understand the reason of the letter. + * @returns {string} + **/ + get coverLetter() { + return this.#coverLetter; + } + /** + * The content that user will receive to understand the reason of the letter. + * @type {string} + **/ + set coverLetter(value: string) { + this.#coverLetter = String(value); + } + setCoverLetter(value: string) { + this.coverLetter = value; + return this; + } + /** + * If the invited person has a different language, then you can define that so the interface for him will be automatically translated. + * @type {string} + **/ + #targetUserLocale: string = ""; + /** + * If the invited person has a different language, then you can define that so the interface for him will be automatically translated. + * @returns {string} + **/ + get targetUserLocale() { + return this.#targetUserLocale; + } + /** + * If the invited person has a different language, then you can define that so the interface for him will be automatically translated. + * @type {string} + **/ + set targetUserLocale(value: string) { + this.#targetUserLocale = String(value); + } + setTargetUserLocale(value: string) { + this.targetUserLocale = value; + return this; + } + /** + * The email address of the person which is invited. + * @type {string} + **/ + #email: string = ""; + /** + * The email address of the person which is invited. + * @returns {string} + **/ + get email() { + return this.#email; + } + /** + * The email address of the person which is invited. + * @type {string} + **/ + set email(value: string) { + this.#email = String(value); + } + setEmail(value: string) { + this.email = value; + return this; + } + /** + * The phone number of the person which is invited. + * @type {string} + **/ + #phonenumber: string = ""; + /** + * The phone number of the person which is invited. + * @returns {string} + **/ + get phonenumber() { + return this.#phonenumber; + } + /** + * The phone number of the person which is invited. + * @type {string} + **/ + set phonenumber(value: string) { + this.#phonenumber = String(value); + } + setPhonenumber(value: string) { + this.phonenumber = value; + return this; + } + /** + * Workspace which user is being invite to. + * @type {WorkspaceEntity} + **/ + #workspace!: WorkspaceEntity; + /** + * Workspace which user is being invite to. + * @returns {WorkspaceEntity} + **/ + get workspace() { + return this.#workspace; + } + /** + * Workspace which user is being invite to. + * @type {WorkspaceEntity} + **/ + set workspace(value: WorkspaceEntity) { + // For objects, the sub type needs to always be instance of the sub class. + if (value instanceof WorkspaceEntity) { + this.#workspace = value; + } else { + this.#workspace = new WorkspaceEntity(value); + } + } + setWorkspace(value: WorkspaceEntity) { + this.workspace = value; + return this; + } + /** + * First name of the person which is invited + * @type {string} + **/ + #firstName: string = ""; + /** + * First name of the person which is invited + * @returns {string} + **/ + get firstName() { + return this.#firstName; + } + /** + * First name of the person which is invited + * @type {string} + **/ + set firstName(value: string) { + this.#firstName = String(value); + } + setFirstName(value: string) { + this.firstName = value; + return this; + } + /** + * Last name of the person which is invited. + * @type {string} + **/ + #lastName: string = ""; + /** + * Last name of the person which is invited. + * @returns {string} + **/ + get lastName() { + return this.#lastName; + } + /** + * Last name of the person which is invited. + * @type {string} + **/ + set lastName(value: string) { + this.#lastName = String(value); + } + setLastName(value: string) { + this.lastName = value; + return this; + } + /** + * If forced, the email address cannot be changed by the user which has been invited. + * @type {boolean} + **/ + #forceEmailAddress?: boolean | null = undefined; + /** + * If forced, the email address cannot be changed by the user which has been invited. + * @returns {boolean} + **/ + get forceEmailAddress() { + return this.#forceEmailAddress; + } + /** + * If forced, the email address cannot be changed by the user which has been invited. + * @type {boolean} + **/ + set forceEmailAddress(value: boolean | null | undefined) { + const correctType = + value === true || + value === false || + value === undefined || + value === null; + this.#forceEmailAddress = correctType ? value : Boolean(value); + } + setForceEmailAddress(value: boolean | null | undefined) { + this.forceEmailAddress = value; + return this; + } + /** + * If forced, user cannot change the phone number and needs to complete signup. + * @type {boolean} + **/ + #forcePhoneNumber?: boolean | null = undefined; + /** + * If forced, user cannot change the phone number and needs to complete signup. + * @returns {boolean} + **/ + get forcePhoneNumber() { + return this.#forcePhoneNumber; + } + /** + * If forced, user cannot change the phone number and needs to complete signup. + * @type {boolean} + **/ + set forcePhoneNumber(value: boolean | null | undefined) { + const correctType = + value === true || + value === false || + value === undefined || + value === null; + this.#forcePhoneNumber = correctType ? value : Boolean(value); + } + setForcePhoneNumber(value: boolean | null | undefined) { + this.forcePhoneNumber = value; + return this; + } + /** + * The role which invitee get if they accept the request. + * @type {string} + **/ + #roleId: string = ""; + /** + * The role which invitee get if they accept the request. + * @returns {string} + **/ + get roleId() { + return this.#roleId; + } + /** + * The role which invitee get if they accept the request. + * @type {string} + **/ + set roleId(value: string) { + this.#roleId = String(value); + } + setRoleId(value: string) { + this.roleId = value; + return this; + } + constructor(data: unknown = undefined) { + if (data === null || data === undefined) { + this.#lateInitFields(); + return; + } + if (typeof data === "string") { + this.applyFromObject(JSON.parse(data)); + } else if (this.#isJsonAppliable(data)) { + this.applyFromObject(data); + } else { + throw new Error( + "Instance cannot be created on an unknown value, check the content being passed. got: " + + typeof data, + ); + } + } + #isJsonAppliable(obj: unknown) { + const g = globalThis as unknown as { Buffer: any; Blob: any }; + const isBuffer = + typeof g.Buffer !== "undefined" && + typeof g.Buffer.isBuffer === "function" && + g.Buffer.isBuffer(obj); + const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; + return ( + obj && + typeof obj === "object" && + !Array.isArray(obj) && + !isBuffer && + !(obj instanceof ArrayBuffer) && + !isBlob + ); + } + /** + * casts the fields of a javascript object into the class properties one by one + **/ + applyFromObject(data = {}) { + const d = data as Partial; + if (d.publicKey !== undefined) { + this.publicKey = d.publicKey; + } + if (d.coverLetter !== undefined) { + this.coverLetter = d.coverLetter; + } + if (d.targetUserLocale !== undefined) { + this.targetUserLocale = d.targetUserLocale; + } + if (d.email !== undefined) { + this.email = d.email; + } + if (d.phonenumber !== undefined) { + this.phonenumber = d.phonenumber; + } + if (d.workspace !== undefined) { + this.workspace = d.workspace; + } + if (d.firstName !== undefined) { + this.firstName = d.firstName; + } + if (d.lastName !== undefined) { + this.lastName = d.lastName; + } + if (d.forceEmailAddress !== undefined) { + this.forceEmailAddress = d.forceEmailAddress; + } + if (d.forcePhoneNumber !== undefined) { + this.forcePhoneNumber = d.forcePhoneNumber; + } + if (d.roleId !== undefined) { + this.roleId = d.roleId; + } + this.#lateInitFields(data); + } + /** + * These are the class instances, which need to be initialised, regardless of the constructor incoming data + **/ + #lateInitFields(data = {}) { + const d = data as Partial; + if (!(d.workspace instanceof WorkspaceEntity)) { + this.workspace = new WorkspaceEntity(d.workspace || {}); + } + } + /** + * Special toJSON override, since the field are private, + * Json stringify won't see them unless we mention it explicitly. + **/ + toJSON() { + return { + publicKey: this.#publicKey, + coverLetter: this.#coverLetter, + targetUserLocale: this.#targetUserLocale, + email: this.#email, + phonenumber: this.#phonenumber, + workspace: this.#workspace, + firstName: this.#firstName, + lastName: this.#lastName, + forceEmailAddress: this.#forceEmailAddress, + forcePhoneNumber: this.#forcePhoneNumber, + roleId: this.#roleId, + }; + } + toString() { + return JSON.stringify(this); + } + static get Fields() { + return { + publicKey: "publicKey", + coverLetter: "coverLetter", + targetUserLocale: "targetUserLocale", + email: "email", + phonenumber: "phonenumber", + workspace$: "workspace", + get workspace() { + return withPrefix("workspace", WorkspaceEntity.Fields); + }, + firstName: "firstName", + lastName: "lastName", + forceEmailAddress: "forceEmailAddress", + forcePhoneNumber: "forcePhoneNumber", + roleId: "roleId", + }; + } + /** + * Creates an instance of WorkspaceInvitationDto, and possibleDtoObject + * needs to satisfy the type requirement fully, otherwise typescript compile would + * be complaining. + **/ + static from(possibleDtoObject: WorkspaceInvitationDtoType) { + return new WorkspaceInvitationDto(possibleDtoObject); + } + /** + * Creates an instance of WorkspaceInvitationDto, and partialDtoObject + * needs to satisfy the type, but partially, and rest of the content would + * be constructed according to data types and nullability. + **/ + static with(partialDtoObject: PartialDeep) { + return new WorkspaceInvitationDto(partialDtoObject); + } + copyWith( + partial: PartialDeep, + ): InstanceType { + return new WorkspaceInvitationDto({ ...this.toJSON(), ...partial }); + } + clone(): InstanceType { + return new WorkspaceInvitationDto(this.toJSON()); + } +} +export abstract class WorkspaceInvitationDtoFactory { + abstract create(data: unknown): WorkspaceInvitationDto; +} +/** + * The base type definition for workspaceInvitationDto + **/ +export type WorkspaceInvitationDtoType = { + /** + * A long hash to get the user into the confirm or signup page without sending the email or phone number, for example if an administrator wants to copy the link. + * @type {string} + **/ + publicKey: string; + /** + * The content that user will receive to understand the reason of the letter. + * @type {string} + **/ + coverLetter: string; + /** + * If the invited person has a different language, then you can define that so the interface for him will be automatically translated. + * @type {string} + **/ + targetUserLocale: string; + /** + * The email address of the person which is invited. + * @type {string} + **/ + email: string; + /** + * The phone number of the person which is invited. + * @type {string} + **/ + phonenumber: string; + /** + * Workspace which user is being invite to. + * @type {WorkspaceEntity} + **/ + workspace: WorkspaceEntity; + /** + * First name of the person which is invited + * @type {string} + **/ + firstName: string; + /** + * Last name of the person which is invited. + * @type {string} + **/ + lastName: string; + /** + * If forced, the email address cannot be changed by the user which has been invited. + * @type {boolean} + **/ + forceEmailAddress?: boolean; + /** + * If forced, user cannot change the phone number and needs to complete signup. + * @type {boolean} + **/ + forcePhoneNumber?: boolean; + /** + * The role which invitee get if they accept the request. + * @type {string} + **/ + roleId: string; +}; +// eslint-disable-next-line @typescript-eslint/no-namespace +export namespace WorkspaceInvitationDtoType {} diff --git a/e2e/react-bed/src/sdk/modules/abac/usePostWorkspaceInvite.ts b/e2e/react-bed/src/sdk/modules/abac/usePostWorkspaceInvite.ts index 2c6c07d6f..96155bbad 100644 --- a/e2e/react-bed/src/sdk/modules/abac/usePostWorkspaceInvite.ts +++ b/e2e/react-bed/src/sdk/modules/abac/usePostWorkspaceInvite.ts @@ -37,7 +37,7 @@ export function usePostWorkspaceInvite( ? execFn(options) : execApiFn(options); // Url of the remote affix. - const url = "/workspace/invite".substr(1); + const url = "/workspace-invite".substr(1); let computedUrl = `${url}?${new URLSearchParams( queryBeforeSend(query) ).toString()}`; diff --git a/modules/abac/AbacCustomActions.dyno.go b/modules/abac/AbacCustomActions.dyno.go index 3bb5a086d..2b36e75a1 100644 --- a/modules/abac/AbacCustomActions.dyno.go +++ b/modules/abac/AbacCustomActions.dyno.go @@ -261,40 +261,6 @@ var SendEmailWithProviderActionCmd cli.Command = cli.Command{ fireback.HandleActionInCli(c, result, err, map[string]map[string]string{}) }, } -var InviteToWorkspaceSecurityModel *fireback.SecurityModel = nil - -type inviteToWorkspaceActionImpSig func( - req *WorkspaceInviteEntity, - q fireback.QueryDSL) (*WorkspaceInviteEntity, - *fireback.IError, -) - -var InviteToWorkspaceActionImp inviteToWorkspaceActionImpSig - -func InviteToWorkspaceActionFn( - req *WorkspaceInviteEntity, - q fireback.QueryDSL, -) ( - *WorkspaceInviteEntity, - *fireback.IError, -) { - if InviteToWorkspaceActionImp == nil { - return nil, nil - } - return InviteToWorkspaceActionImp(req, q) -} - -var InviteToWorkspaceActionCmd cli.Command = cli.Command{ - Name: "invite", - Usage: `Invite a new person (either a user, with passport or without passport)`, - Flags: WorkspaceInviteCommonCliFlagsOptional, - Action: func(c *cli.Context) { - query := fireback.CommonCliQueryDSLBuilderAuthorize(c, InviteToWorkspaceSecurityModel) - dto := CastWorkspaceInviteFromCli(c) - result, err := InviteToWorkspaceActionFn(dto, query) - fireback.HandleActionInCli(c, result, err, map[string]map[string]string{}) - }, -} var GsmSendSmsSecurityModel *fireback.SecurityModel = nil type GsmSendSmsActionReqDto struct { @@ -486,6 +452,41 @@ var GsmSendSmsWithProviderActionCmd cli.Command = cli.Command{ /// For emi, we also need to print the handlers, and also print security model, which is a part of Fireback /// and not available in Emi (won't be) +var InviteToWorkspaceImpl func(c InviteToWorkspaceActionRequest, query fireback.QueryDSL) (*InviteToWorkspaceActionResponse, error) = nil +var InviteToWorkspaceSecurityModel *fireback.SecurityModel = nil + +// This can be both used as cli and http +var InviteToWorkspaceActionDef fireback.Module3Action = fireback.Module3Action{ + // Temporary until fireback code gen is deleted. + Skip: true, + CliName: InviteToWorkspaceActionMeta().CliName, + Description: InviteToWorkspaceActionMeta().Description, + Name: InviteToWorkspaceActionMeta().Name, + Method: InviteToWorkspaceActionMeta().Method, + Url: InviteToWorkspaceActionMeta().URL, + SecurityModel: InviteToWorkspaceSecurityModel, + // post + Handlers: []gin.HandlerFunc{ + func(m *gin.Context) { + req := InviteToWorkspaceActionRequest{ + QueryParams: m.Request.URL.Query(), + Headers: m.Request.Header, + GinCtx: m, + } + query := fireback.ExtractQueryDslFromGinContext(m) + fireback.ReadGinRequestBodyAndCastToGoStruct(m, &req.Body, query) + resp, err := InviteToWorkspaceImpl(req, query) + fireback.WriteActionResponseToGin(m, resp, err) + }, + }, + CliAction: func(c *cli.Context, security *fireback.SecurityModel) error { + query := fireback.CommonCliQueryDSLBuilderAuthorize(c, InviteToWorkspaceSecurityModel) + req := InviteToWorkspaceActionRequest{} + resp, err := InviteToWorkspaceImpl(req, query) + fireback.HandleActionInCli2(c, resp, err, map[string]map[string]string{}) + return nil + }, +} var UserInvitationsImpl func(c UserInvitationsActionRequest, query fireback.QueryDSL) (*UserInvitationsActionResponse, error) = nil var UserInvitationsSecurityModel = &fireback.SecurityModel{ ActionRequires: []fireback.PermissionInfo{}, @@ -1062,6 +1063,7 @@ var OsLoginAuthenticateActionDef fireback.Module3Action = fireback.Module3Action func AbacCustomActions() []fireback.Module3Action { routes := []fireback.Module3Action{ //// Let's add actions for emi acts + InviteToWorkspaceActionDef, UserInvitationsActionDef, SignoutActionDef, OauthAuthenticateActionDef, @@ -1148,29 +1150,6 @@ func AbacCustomActions() []fireback.Module3Action { Entity: "SendEmailWithProviderActionReqDto", }, }, - { - Method: "POST", - Url: "/workspace/invite", - SecurityModel: InviteToWorkspaceSecurityModel, - Name: "inviteToWorkspace", - Description: "Invite a new person (either a user, with passport or without passport)", - Handlers: []gin.HandlerFunc{ - func(c *gin.Context) { - // POST_ONE - post - fireback.HttpPostEntity(c, InviteToWorkspaceActionFn) - }, - }, - Format: "POST_ONE", - Action: InviteToWorkspaceActionFn, - ResponseEntity: &WorkspaceInviteEntity{}, - Out: &fireback.Module3ActionBody{ - Entity: "WorkspaceInviteEntity", - }, - RequestEntity: &WorkspaceInviteEntity{}, - In: &fireback.Module3ActionBody{ - Entity: "WorkspaceInviteEntity", - }, - }, { Method: "POST", Url: "/gsm/send/sms", @@ -1225,7 +1204,6 @@ var AbacCustomActionsCli = []cli.Command{ QueryUserRoleWorkspacesActionCmd, SendEmailActionCmd, SendEmailWithProviderActionCmd, - InviteToWorkspaceActionCmd, GsmSendSmsActionCmd, GsmSendSmsWithProviderActionCmd, } @@ -1243,6 +1221,7 @@ var AbacCliActionsBundle = &fireback.CliActionsBundle{ Usage: `Fireback ABAC module provides user authentication, basic support for most projects, including advanced role, permission module on top of fireback core module. Using this module is not essential to create fireback projects, but provides a great possibility to avoid building most user management flow. Some other helpers, such as timezone are added here.`, // Here we will include entities actions, as well as module level actions Subcommands: cli.Commands{ + InviteToWorkspaceActionDef.ToCli(), UserInvitationsActionDef.ToCli(), SignoutActionDef.ToCli(), OauthAuthenticateActionDef.ToCli(), @@ -1262,7 +1241,6 @@ var AbacCliActionsBundle = &fireback.CliActionsBundle{ QueryUserRoleWorkspacesActionCmd, SendEmailActionCmd, SendEmailWithProviderActionCmd, - InviteToWorkspaceActionCmd, GsmSendSmsActionCmd, GsmSendSmsWithProviderActionCmd, TimezoneGroupCliFn(), diff --git a/modules/abac/AbacModule3.yml b/modules/abac/AbacModule3.yml index fe27bede0..939c8e0c5 100644 --- a/modules/abac/AbacModule3.yml +++ b/modules/abac/AbacModule3.yml @@ -154,8 +154,64 @@ dtom: target: UserEntity - name: userId type: string? - + - name: workspaceInvitation + description: Workspace invitation has some common usage, so it's put here. + fields: + - name: publicKey + type: string + description: + A long hash to get the user into the confirm or signup page without sending + the email or phone number, for example if an administrator wants to copy the link. + - name: coverLetter + type: string + description: The content that user will receive to understand the reason of the letter. + - name: targetUserLocale + type: string + description: + If the invited person has a different language, then you can define + that so the interface for him will be automatically translated. + - name: email + type: string + description: The email address of the person which is invited. + - name: phonenumber + type: string + description: The phone number of the person which is invited. + - name: workspace + type: one + target: WorkspaceEntity + description: Workspace which user is being invite to. + - name: firstName + type: string + tags: + validate: required + description: First name of the person which is invited + - name: lastName + tags: + validate: required + type: string + description: Last name of the person which is invited. + - name: forceEmailAddress + type: bool? + description: If forced, the email address cannot be changed by the user which has been invited. + - name: forcePhoneNumber + type: bool? + description: If forced, user cannot change the phone number and needs to complete signup. + - name: roleId + type: string + description: The role which invitee get if they accept the request. + tags: + validate: required acts: + - name: InviteToWorkspace + url: /workspace/invite + cliName: invite + method: post + description: "Invite a new person (either a user, with passport or without passport)" + in: + dto: WorkspaceInvitationDto + out: + dto: WorkspaceInvitationDto + - name: UserInvitations description: Shows the invitations for an specific user, if the invited member already has a account. @@ -703,15 +759,7 @@ actions: fields: - name: queueId type: string - - name: inviteToWorkspace - url: /workspace/invite - cliName: invite - method: post - description: "Invite a new person (either a user, with passport or without passport)" - in: - entity: WorkspaceInviteEntity - out: - entity: WorkspaceInviteEntity + - name: gsmSendSms url: /gsm/send/sms cliName: sms diff --git a/modules/abac/InviteToWorkspaceAction.dyno.go b/modules/abac/InviteToWorkspaceAction.dyno.go new file mode 100644 index 000000000..30c9d48bc --- /dev/null +++ b/modules/abac/InviteToWorkspaceAction.dyno.go @@ -0,0 +1,254 @@ +package abac + +import ( + "bytes" + "encoding/json" + "fmt" + "github.com/gin-gonic/gin" + "github.com/torabian/emi/emigo" + "github.com/urfave/cli" + "io" + "net/http" + "net/url" +) + +/** +* Action to communicate with the action InviteToWorkspaceAction + */ +func InviteToWorkspaceActionMeta() struct { + Name string + CliName string + URL string + Method string + Description string +} { + return struct { + Name string + CliName string + URL string + Method string + Description string + }{ + Name: "InviteToWorkspaceAction", + CliName: "invite", + URL: "/workspace/invite", + Method: "POST", + Description: `Invite a new person (either a user, with passport or without passport)`, + } +} + +type InviteToWorkspaceActionResponse struct { + StatusCode int + Headers map[string]string + Payload interface{} +} + +func (x *InviteToWorkspaceActionResponse) SetContentType(contentType string) *InviteToWorkspaceActionResponse { + if x.Headers == nil { + x.Headers = make(map[string]string) + } + x.Headers["Content-Type"] = contentType + return x +} +func (x *InviteToWorkspaceActionResponse) AsStream(r io.Reader, contentType string) *InviteToWorkspaceActionResponse { + x.Payload = r + x.SetContentType(contentType) + return x +} +func (x *InviteToWorkspaceActionResponse) AsJSON(payload any) *InviteToWorkspaceActionResponse { + x.Payload = payload + x.SetContentType("application/json") + return x +} +func (x *InviteToWorkspaceActionResponse) AsHTML(payload string) *InviteToWorkspaceActionResponse { + x.Payload = payload + x.SetContentType("text/html; charset=utf-8") + return x +} +func (x *InviteToWorkspaceActionResponse) AsBytes(payload []byte) *InviteToWorkspaceActionResponse { + x.Payload = payload + x.SetContentType("application/octet-stream") + return x +} +func (x InviteToWorkspaceActionResponse) GetStatusCode() int { + return x.StatusCode +} +func (x InviteToWorkspaceActionResponse) GetRespHeaders() map[string]string { + return x.Headers +} +func (x InviteToWorkspaceActionResponse) GetPayload() interface{} { + return x.Payload +} + +// InviteToWorkspaceActionRaw registers a raw Gin route for the InviteToWorkspaceAction action. +// This gives the developer full control over middleware, handlers, and response handling. +func InviteToWorkspaceActionRaw(r *gin.Engine, handlers ...gin.HandlerFunc) { + meta := InviteToWorkspaceActionMeta() + r.Handle(meta.Method, meta.URL, handlers...) +} + +type InviteToWorkspaceActionRequestSig = func(c InviteToWorkspaceActionRequest) (*InviteToWorkspaceActionResponse, error) + +// InviteToWorkspaceActionHandler returns the HTTP method, route URL, and a typed Gin handler for the InviteToWorkspaceAction action. +// Developers implement their business logic as a function that receives a typed request object +// and returns either an *ActionResponse or nil. JSON marshalling, headers, and errors are handled automatically. +func InviteToWorkspaceActionHandler( + handler InviteToWorkspaceActionRequestSig, +) (method, url string, h gin.HandlerFunc) { + meta := InviteToWorkspaceActionMeta() + return meta.Method, meta.URL, func(m *gin.Context) { + var body WorkspaceInvitationDto + if err := m.ShouldBindJSON(&body); err != nil { + m.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON: " + err.Error()}) + return + } + // Build typed request wrapper + req := InviteToWorkspaceActionRequest{ + Body: body, + QueryParams: m.Request.URL.Query(), + Headers: m.Request.Header, + GinCtx: m, + } + resp, err := handler(req) + if err != nil { + m.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + // If the handler returned nil (and no error), it means the response was handled manually. + if resp == nil { + return + } + // Apply headers + for k, v := range resp.Headers { + m.Header(k, v) + } + // Apply status and payload + status := resp.StatusCode + if status == 0 { + status = http.StatusOK + } + if resp.Payload != nil { + m.JSON(status, resp.Payload) + } else { + m.Status(status) + } + } +} + +// InviteToWorkspaceAction is a high-level convenience wrapper around InviteToWorkspaceActionHandler. +// It automatically constructs and registers the typed route on the Gin engine. +// Use this when you don't need custom middleware or route grouping. +func InviteToWorkspaceActionGin(r gin.IRoutes, handler InviteToWorkspaceActionRequestSig) { + method, url, h := InviteToWorkspaceActionHandler(handler) + r.Handle(method, url, h) +} + +/** + * Query parameters for InviteToWorkspaceAction + */ +// Query wrapper with private fields +type InviteToWorkspaceActionQuery struct { + values url.Values + mapped map[string]interface{} + // Typesafe fields +} + +func InviteToWorkspaceActionQueryFromString(rawQuery string) InviteToWorkspaceActionQuery { + v := InviteToWorkspaceActionQuery{} + values, _ := url.ParseQuery(rawQuery) + mapped := map[string]interface{}{} + if result, err := emigo.UnmarshalQs(rawQuery); err == nil { + mapped = result + } + decoder, err := emigo.NewDecoder(&emigo.DecoderConfig{ + TagName: "json", // reuse json tags + WeaklyTypedInput: true, // "1" -> int, "true" -> bool + Result: &v, + }) + if err == nil { + _ = decoder.Decode(mapped) + } + v.values = values + v.mapped = mapped + return v +} +func InviteToWorkspaceActionQueryFromGin(c *gin.Context) InviteToWorkspaceActionQuery { + return InviteToWorkspaceActionQueryFromString(c.Request.URL.RawQuery) +} +func InviteToWorkspaceActionQueryFromHttp(r *http.Request) InviteToWorkspaceActionQuery { + return InviteToWorkspaceActionQueryFromString(r.URL.RawQuery) +} +func (q InviteToWorkspaceActionQuery) Values() url.Values { + return q.values +} +func (q InviteToWorkspaceActionQuery) Mapped() map[string]interface{} { + return q.mapped +} +func (q *InviteToWorkspaceActionQuery) SetValues(v url.Values) { + q.values = v +} +func (q *InviteToWorkspaceActionQuery) SetMapped(m map[string]interface{}) { + q.mapped = m +} + +type InviteToWorkspaceActionRequest struct { + Body WorkspaceInvitationDto + QueryParams url.Values + Headers http.Header + GinCtx *gin.Context + CliCtx *cli.Context +} +type InviteToWorkspaceActionResult struct { + resp *http.Response // embed original response + Payload interface{} +} + +func InviteToWorkspaceActionCall( + req InviteToWorkspaceActionRequest, + config *emigo.APIClient, // optional pre-built request +) (*InviteToWorkspaceActionResult, error) { + var httpReq *http.Request + if config == nil || config.Httpr == nil { + meta := InviteToWorkspaceActionMeta() + baseURL := meta.URL + // Build final URL with query string + u, err := url.Parse(baseURL) + if err != nil { + return nil, err + } + // if UrlValues present, encode and append + if len(req.QueryParams) > 0 { + u.RawQuery = req.QueryParams.Encode() + } + bodyBytes, err := json.Marshal(req.Body) + if err != nil { + return nil, err + } + req0, err := http.NewRequest(meta.Method, u.String(), bytes.NewReader(bodyBytes)) + if err != nil { + return nil, err + } + httpReq = req0 + } else { + httpReq = config.Httpr + } + httpReq.Header = req.Headers + resp, err := http.DefaultClient.Do(httpReq) + if err != nil { + return nil, err + } + var result InviteToWorkspaceActionResult + result.resp = resp + defer resp.Body.Close() + respBody, err := io.ReadAll(resp.Body) + if err != nil { + return &result, err + } + if resp.StatusCode >= 400 { + return &result, fmt.Errorf("request failed: %s", respBody) + } + if err := json.Unmarshal(respBody, &result.Payload); err != nil { + return &result, err + } + return &result, nil +} diff --git a/modules/abac/InviteToWorkspaceAction.go b/modules/abac/InviteToWorkspaceAction.go index 23abfa2af..77992608c 100644 --- a/modules/abac/InviteToWorkspaceAction.go +++ b/modules/abac/InviteToWorkspaceAction.go @@ -8,50 +8,56 @@ import ( func init() { // Override the implementation with our actual code. - InviteToWorkspaceActionImp = InviteToWorkspaceAction + InviteToWorkspaceImpl = InviteToWorkspaceAction } -func InviteToWorkspaceAction(req *WorkspaceInviteEntity, q fireback.QueryDSL) (*WorkspaceInviteEntity, *fireback.IError) { - if err := WorkspaceInviteValidator(req, false); err != nil { +func InviteToWorkspaceAction(c InviteToWorkspaceActionRequest, query fireback.QueryDSL) (*InviteToWorkspaceActionResponse, error) { + req := c.Body + + if err := fireback.CommonStructValidatorPointer(&req, false); err != nil { return nil, err } - _, roleErrors := ValidateRoleAndItsExistence(req.RoleId) + _, roleErrors := ValidateRoleAndItsExistence(fireback.NewString(req.RoleId)) if len(roleErrors) != 0 { return nil, &fireback.IError{ Errors: roleErrors, } } - userLocale := q.Language + userLocale := query.Language if strings.TrimSpace(req.TargetUserLocale) != "" { userLocale = req.TargetUserLocale } - var invite WorkspaceInviteEntity = *req - invite.WorkspaceId = fireback.NewString(q.WorkspaceId) + invite := WorkspaceInviteEntity{} + + invite.WorkspaceId = fireback.NewString(query.WorkspaceId) invite.UniqueId = fireback.UUID() invite.TargetUserLocale = userLocale - if err := fireback.GetRef(q).Create(&invite).Error; err != nil { - return &invite, fireback.GormErrorToIError(err) + if err := fireback.GetRef(query).Create(&invite).Error; err != nil { + return nil, fireback.GormErrorToIError(err) } if invite.Email != "" { - if err7 := SendInviteEmail(q, &invite); err7 != nil { + if err7 := SendInviteEmail(query, &invite); err7 != nil { return nil, err7 } } if invite.Phonenumber != "" { inviteBody := "You are invite " + invite.FirstName + " " + invite.LastName + if _, err7 := GsmSendSmsAction(&GsmSendSmsActionReqDto{ ToNumber: invite.Phonenumber, Body: inviteBody, - }, q); err7 != nil { + }, query); err7 != nil { return nil, fireback.GormErrorToIError(err7) } } - return &invite, nil + return &InviteToWorkspaceActionResponse{ + Payload: fireback.GResponseSingleItem(invite), + }, nil } diff --git a/modules/abac/WorkspaceInvitationDto.dyno.go b/modules/abac/WorkspaceInvitationDto.dyno.go new file mode 100644 index 000000000..888353197 --- /dev/null +++ b/modules/abac/WorkspaceInvitationDto.dyno.go @@ -0,0 +1,121 @@ +package abac + +import "encoding/json" +import emigo "github.com/torabian/emi/emigo" + +func GetWorkspaceInvitationDtoCliFlags(prefix string) []emigo.CliFlag { + return []emigo.CliFlag{ + { + Name: prefix + "public-key", + Type: "string", + }, + { + Name: prefix + "cover-letter", + Type: "string", + }, + { + Name: prefix + "target-user-locale", + Type: "string", + }, + { + Name: prefix + "email", + Type: "string", + }, + { + Name: prefix + "phonenumber", + Type: "string", + }, + { + Name: prefix + "workspace", + Type: "one", + }, + { + Name: prefix + "first-name", + Type: "string", + }, + { + Name: prefix + "last-name", + Type: "string", + }, + { + Name: prefix + "force-email-address", + Type: "bool?", + }, + { + Name: prefix + "force-phone-number", + Type: "bool?", + }, + { + Name: prefix + "role-id", + Type: "string", + }, + } +} +func CastWorkspaceInvitationDtoFromCli(c emigo.CliCastable) WorkspaceInvitationDto { + data := WorkspaceInvitationDto{} + if c.IsSet("public-key") { + data.PublicKey = c.String("public-key") + } + if c.IsSet("cover-letter") { + data.CoverLetter = c.String("cover-letter") + } + if c.IsSet("target-user-locale") { + data.TargetUserLocale = c.String("target-user-locale") + } + if c.IsSet("email") { + data.Email = c.String("email") + } + if c.IsSet("phonenumber") { + data.Phonenumber = c.String("phonenumber") + } + if c.IsSet("first-name") { + data.FirstName = c.String("first-name") + } + if c.IsSet("last-name") { + data.LastName = c.String("last-name") + } + if c.IsSet("force-email-address") { + emigo.ParseNullable(c.String("force-email-address"), &data.ForceEmailAddress) + } + if c.IsSet("force-phone-number") { + emigo.ParseNullable(c.String("force-phone-number"), &data.ForcePhoneNumber) + } + if c.IsSet("role-id") { + data.RoleId = c.String("role-id") + } + return data +} + +// The base class definition for workspaceInvitationDto +type WorkspaceInvitationDto struct { + // A long hash to get the user into the confirm or signup page without sending the email or phone number, for example if an administrator wants to copy the link. + PublicKey string `json:"publicKey" yaml:"publicKey"` + // The content that user will receive to understand the reason of the letter. + CoverLetter string `json:"coverLetter" yaml:"coverLetter"` + // If the invited person has a different language, then you can define that so the interface for him will be automatically translated. + TargetUserLocale string `json:"targetUserLocale" yaml:"targetUserLocale"` + // The email address of the person which is invited. + Email string `json:"email" yaml:"email"` + // The phone number of the person which is invited. + Phonenumber string `json:"phonenumber" yaml:"phonenumber"` + // Workspace which user is being invite to. + Workspace WorkspaceEntity `json:"workspace" yaml:"workspace"` + // First name of the person which is invited + FirstName string `json:"firstName" validate:"required" yaml:"firstName"` + // Last name of the person which is invited. + LastName string `json:"lastName" validate:"required" yaml:"lastName"` + // If forced, the email address cannot be changed by the user which has been invited. + ForceEmailAddress emigo.Nullable[bool] `json:"forceEmailAddress" yaml:"forceEmailAddress"` + // If forced, user cannot change the phone number and needs to complete signup. + ForcePhoneNumber emigo.Nullable[bool] `json:"forcePhoneNumber" yaml:"forcePhoneNumber"` + // The role which invitee get if they accept the request. + RoleId string `json:"roleId" validate:"required" yaml:"roleId"` +} + +func (x *WorkspaceInvitationDto) Json() string { + if x != nil { + str, _ := json.MarshalIndent(x, "", " ") + return string(str) + } + return "" +} diff --git a/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/InviteToWorkspace.ts b/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/InviteToWorkspace.ts new file mode 100644 index 000000000..1f4db27d7 --- /dev/null +++ b/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/InviteToWorkspace.ts @@ -0,0 +1,141 @@ +import { WorkspaceInvitationDto } from "./WorkspaceInvitationDto"; +import { buildUrl } from "../../sdk/common/buildUrl"; +import { + fetchx, + handleFetchResponse, + type FetchxContext, + type TypedRequestInit, + type TypedResponse, +} from "../../sdk/common/fetchx"; +import { type UseMutationOptions, useMutation } from "react-query"; +import { useFetchxContext } from "../../sdk/react/useFetchx"; +import { useState } from "react"; +/** + * Action to communicate with the action InviteToWorkspace + */ +export type InviteToWorkspaceActionOptions = { + queryKey?: unknown[]; + qs?: URLSearchParams; +}; +export type InviteToWorkspaceActionMutationOptions = Omit< + UseMutationOptions, + "mutationFn" +> & + InviteToWorkspaceActionOptions & { + ctx?: FetchxContext; + onMessage?: (ev: MessageEvent) => void; + overrideUrl?: string; + headers?: Headers; + } & Partial<{ + creatorFn: (item: unknown) => WorkspaceInvitationDto; + }>; +export const useInviteToWorkspaceAction = ( + options?: InviteToWorkspaceActionMutationOptions, +) => { + const globalCtx = useFetchxContext(); + const ctx = options?.ctx ?? globalCtx ?? undefined; + const [isCompleted, setCompleteState] = useState(false); + const [response, setResponse] = useState>(); + const fn = (body: WorkspaceInvitationDto) => { + setCompleteState(false); + return InviteToWorkspaceAction.Fetch( + { + body, + headers: options?.headers, + }, + { + creatorFn: options?.creatorFn, + qs: options?.qs, + ctx, + onMessage: options?.onMessage, + overrideUrl: options?.overrideUrl, + }, + ).then((x) => { + x.done.then(() => { + setCompleteState(true); + }); + setResponse(x.response); + return x.response.result; + }); + }; + const result = useMutation({ + mutationFn: fn, + ...(options || {}), + }); + return { + ...result, + isCompleted, + response, + }; +}; +/** + * InviteToWorkspaceAction + */ +export class InviteToWorkspaceAction { + // + static URL = "/workspace/invite"; + static NewUrl = (qs?: URLSearchParams) => + buildUrl(InviteToWorkspaceAction.URL, undefined, qs); + static Method = "post"; + static Fetch$ = async ( + qs?: URLSearchParams, + ctx?: FetchxContext, + init?: TypedRequestInit, + overrideUrl?: string, + ) => { + return fetchx( + overrideUrl ?? InviteToWorkspaceAction.NewUrl(qs), + { + method: InviteToWorkspaceAction.Method, + ...(init || {}), + }, + ctx, + ); + }; + static Fetch = async ( + init?: TypedRequestInit, + { + creatorFn, + qs, + ctx, + onMessage, + overrideUrl, + }: { + creatorFn?: ((item: unknown) => WorkspaceInvitationDto) | undefined; + qs?: URLSearchParams; + ctx?: FetchxContext; + onMessage?: (ev: MessageEvent) => void; + overrideUrl?: string; + } = { + creatorFn: (item) => new WorkspaceInvitationDto(item), + }, + ) => { + creatorFn = creatorFn || ((item) => new WorkspaceInvitationDto(item)); + const res = await InviteToWorkspaceAction.Fetch$( + qs, + ctx, + init, + overrideUrl, + ); + return handleFetchResponse( + res, + (item) => (creatorFn ? creatorFn(item) : item), + onMessage, + init?.signal, + ); + }; + static Definition = { + name: "InviteToWorkspace", + cliName: "invite", + url: "/workspace/invite", + method: "post", + description: + "Invite a new person (either a user, with passport or without passport)", + in: { + dto: "WorkspaceInvitationDto", + }, + out: { + dto: "WorkspaceInvitationDto", + }, + }; +} diff --git a/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/WorkspaceInvitationDto.ts b/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/WorkspaceInvitationDto.ts new file mode 100644 index 000000000..7cbef18d0 --- /dev/null +++ b/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/WorkspaceInvitationDto.ts @@ -0,0 +1,488 @@ +// @ts-nocheck + // This no check has been added via fireback. +import { WorkspaceEntity } from "./WorkspaceEntity"; +import { type PartialDeep } from "../../sdk/common/fetchx"; +import { withPrefix } from "../../sdk/common/withPrefix"; +/** + * The base class definition for workspaceInvitationDto + **/ +export class WorkspaceInvitationDto { + /** + * A long hash to get the user into the confirm or signup page without sending the email or phone number, for example if an administrator wants to copy the link. + * @type {string} + **/ + #publicKey: string = ""; + /** + * A long hash to get the user into the confirm or signup page without sending the email or phone number, for example if an administrator wants to copy the link. + * @returns {string} + **/ + get publicKey() { + return this.#publicKey; + } + /** + * A long hash to get the user into the confirm or signup page without sending the email or phone number, for example if an administrator wants to copy the link. + * @type {string} + **/ + set publicKey(value: string) { + this.#publicKey = String(value); + } + setPublicKey(value: string) { + this.publicKey = value; + return this; + } + /** + * The content that user will receive to understand the reason of the letter. + * @type {string} + **/ + #coverLetter: string = ""; + /** + * The content that user will receive to understand the reason of the letter. + * @returns {string} + **/ + get coverLetter() { + return this.#coverLetter; + } + /** + * The content that user will receive to understand the reason of the letter. + * @type {string} + **/ + set coverLetter(value: string) { + this.#coverLetter = String(value); + } + setCoverLetter(value: string) { + this.coverLetter = value; + return this; + } + /** + * If the invited person has a different language, then you can define that so the interface for him will be automatically translated. + * @type {string} + **/ + #targetUserLocale: string = ""; + /** + * If the invited person has a different language, then you can define that so the interface for him will be automatically translated. + * @returns {string} + **/ + get targetUserLocale() { + return this.#targetUserLocale; + } + /** + * If the invited person has a different language, then you can define that so the interface for him will be automatically translated. + * @type {string} + **/ + set targetUserLocale(value: string) { + this.#targetUserLocale = String(value); + } + setTargetUserLocale(value: string) { + this.targetUserLocale = value; + return this; + } + /** + * The email address of the person which is invited. + * @type {string} + **/ + #email: string = ""; + /** + * The email address of the person which is invited. + * @returns {string} + **/ + get email() { + return this.#email; + } + /** + * The email address of the person which is invited. + * @type {string} + **/ + set email(value: string) { + this.#email = String(value); + } + setEmail(value: string) { + this.email = value; + return this; + } + /** + * The phone number of the person which is invited. + * @type {string} + **/ + #phonenumber: string = ""; + /** + * The phone number of the person which is invited. + * @returns {string} + **/ + get phonenumber() { + return this.#phonenumber; + } + /** + * The phone number of the person which is invited. + * @type {string} + **/ + set phonenumber(value: string) { + this.#phonenumber = String(value); + } + setPhonenumber(value: string) { + this.phonenumber = value; + return this; + } + /** + * Workspace which user is being invite to. + * @type {WorkspaceEntity} + **/ + #workspace!: WorkspaceEntity; + /** + * Workspace which user is being invite to. + * @returns {WorkspaceEntity} + **/ + get workspace() { + return this.#workspace; + } + /** + * Workspace which user is being invite to. + * @type {WorkspaceEntity} + **/ + set workspace(value: WorkspaceEntity) { + // For objects, the sub type needs to always be instance of the sub class. + if (value instanceof WorkspaceEntity) { + this.#workspace = value; + } else { + this.#workspace = new WorkspaceEntity(value); + } + } + setWorkspace(value: WorkspaceEntity) { + this.workspace = value; + return this; + } + /** + * First name of the person which is invited + * @type {string} + **/ + #firstName: string = ""; + /** + * First name of the person which is invited + * @returns {string} + **/ + get firstName() { + return this.#firstName; + } + /** + * First name of the person which is invited + * @type {string} + **/ + set firstName(value: string) { + this.#firstName = String(value); + } + setFirstName(value: string) { + this.firstName = value; + return this; + } + /** + * Last name of the person which is invited. + * @type {string} + **/ + #lastName: string = ""; + /** + * Last name of the person which is invited. + * @returns {string} + **/ + get lastName() { + return this.#lastName; + } + /** + * Last name of the person which is invited. + * @type {string} + **/ + set lastName(value: string) { + this.#lastName = String(value); + } + setLastName(value: string) { + this.lastName = value; + return this; + } + /** + * If forced, the email address cannot be changed by the user which has been invited. + * @type {boolean} + **/ + #forceEmailAddress?: boolean | null = undefined; + /** + * If forced, the email address cannot be changed by the user which has been invited. + * @returns {boolean} + **/ + get forceEmailAddress() { + return this.#forceEmailAddress; + } + /** + * If forced, the email address cannot be changed by the user which has been invited. + * @type {boolean} + **/ + set forceEmailAddress(value: boolean | null | undefined) { + const correctType = + value === true || + value === false || + value === undefined || + value === null; + this.#forceEmailAddress = correctType ? value : Boolean(value); + } + setForceEmailAddress(value: boolean | null | undefined) { + this.forceEmailAddress = value; + return this; + } + /** + * If forced, user cannot change the phone number and needs to complete signup. + * @type {boolean} + **/ + #forcePhoneNumber?: boolean | null = undefined; + /** + * If forced, user cannot change the phone number and needs to complete signup. + * @returns {boolean} + **/ + get forcePhoneNumber() { + return this.#forcePhoneNumber; + } + /** + * If forced, user cannot change the phone number and needs to complete signup. + * @type {boolean} + **/ + set forcePhoneNumber(value: boolean | null | undefined) { + const correctType = + value === true || + value === false || + value === undefined || + value === null; + this.#forcePhoneNumber = correctType ? value : Boolean(value); + } + setForcePhoneNumber(value: boolean | null | undefined) { + this.forcePhoneNumber = value; + return this; + } + /** + * The role which invitee get if they accept the request. + * @type {string} + **/ + #roleId: string = ""; + /** + * The role which invitee get if they accept the request. + * @returns {string} + **/ + get roleId() { + return this.#roleId; + } + /** + * The role which invitee get if they accept the request. + * @type {string} + **/ + set roleId(value: string) { + this.#roleId = String(value); + } + setRoleId(value: string) { + this.roleId = value; + return this; + } + constructor(data: unknown = undefined) { + if (data === null || data === undefined) { + this.#lateInitFields(); + return; + } + if (typeof data === "string") { + this.applyFromObject(JSON.parse(data)); + } else if (this.#isJsonAppliable(data)) { + this.applyFromObject(data); + } else { + throw new Error( + "Instance cannot be created on an unknown value, check the content being passed. got: " + + typeof data, + ); + } + } + #isJsonAppliable(obj: unknown) { + const g = globalThis as unknown as { Buffer: any; Blob: any }; + const isBuffer = + typeof g.Buffer !== "undefined" && + typeof g.Buffer.isBuffer === "function" && + g.Buffer.isBuffer(obj); + const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; + return ( + obj && + typeof obj === "object" && + !Array.isArray(obj) && + !isBuffer && + !(obj instanceof ArrayBuffer) && + !isBlob + ); + } + /** + * casts the fields of a javascript object into the class properties one by one + **/ + applyFromObject(data = {}) { + const d = data as Partial; + if (d.publicKey !== undefined) { + this.publicKey = d.publicKey; + } + if (d.coverLetter !== undefined) { + this.coverLetter = d.coverLetter; + } + if (d.targetUserLocale !== undefined) { + this.targetUserLocale = d.targetUserLocale; + } + if (d.email !== undefined) { + this.email = d.email; + } + if (d.phonenumber !== undefined) { + this.phonenumber = d.phonenumber; + } + if (d.workspace !== undefined) { + this.workspace = d.workspace; + } + if (d.firstName !== undefined) { + this.firstName = d.firstName; + } + if (d.lastName !== undefined) { + this.lastName = d.lastName; + } + if (d.forceEmailAddress !== undefined) { + this.forceEmailAddress = d.forceEmailAddress; + } + if (d.forcePhoneNumber !== undefined) { + this.forcePhoneNumber = d.forcePhoneNumber; + } + if (d.roleId !== undefined) { + this.roleId = d.roleId; + } + this.#lateInitFields(data); + } + /** + * These are the class instances, which need to be initialised, regardless of the constructor incoming data + **/ + #lateInitFields(data = {}) { + const d = data as Partial; + if (!(d.workspace instanceof WorkspaceEntity)) { + this.workspace = new WorkspaceEntity(d.workspace || {}); + } + } + /** + * Special toJSON override, since the field are private, + * Json stringify won't see them unless we mention it explicitly. + **/ + toJSON() { + return { + publicKey: this.#publicKey, + coverLetter: this.#coverLetter, + targetUserLocale: this.#targetUserLocale, + email: this.#email, + phonenumber: this.#phonenumber, + workspace: this.#workspace, + firstName: this.#firstName, + lastName: this.#lastName, + forceEmailAddress: this.#forceEmailAddress, + forcePhoneNumber: this.#forcePhoneNumber, + roleId: this.#roleId, + }; + } + toString() { + return JSON.stringify(this); + } + static get Fields() { + return { + publicKey: "publicKey", + coverLetter: "coverLetter", + targetUserLocale: "targetUserLocale", + email: "email", + phonenumber: "phonenumber", + workspace$: "workspace", + get workspace() { + return withPrefix("workspace", WorkspaceEntity.Fields); + }, + firstName: "firstName", + lastName: "lastName", + forceEmailAddress: "forceEmailAddress", + forcePhoneNumber: "forcePhoneNumber", + roleId: "roleId", + }; + } + /** + * Creates an instance of WorkspaceInvitationDto, and possibleDtoObject + * needs to satisfy the type requirement fully, otherwise typescript compile would + * be complaining. + **/ + static from(possibleDtoObject: WorkspaceInvitationDtoType) { + return new WorkspaceInvitationDto(possibleDtoObject); + } + /** + * Creates an instance of WorkspaceInvitationDto, and partialDtoObject + * needs to satisfy the type, but partially, and rest of the content would + * be constructed according to data types and nullability. + **/ + static with(partialDtoObject: PartialDeep) { + return new WorkspaceInvitationDto(partialDtoObject); + } + copyWith( + partial: PartialDeep, + ): InstanceType { + return new WorkspaceInvitationDto({ ...this.toJSON(), ...partial }); + } + clone(): InstanceType { + return new WorkspaceInvitationDto(this.toJSON()); + } +} +export abstract class WorkspaceInvitationDtoFactory { + abstract create(data: unknown): WorkspaceInvitationDto; +} +/** + * The base type definition for workspaceInvitationDto + **/ +export type WorkspaceInvitationDtoType = { + /** + * A long hash to get the user into the confirm or signup page without sending the email or phone number, for example if an administrator wants to copy the link. + * @type {string} + **/ + publicKey: string; + /** + * The content that user will receive to understand the reason of the letter. + * @type {string} + **/ + coverLetter: string; + /** + * If the invited person has a different language, then you can define that so the interface for him will be automatically translated. + * @type {string} + **/ + targetUserLocale: string; + /** + * The email address of the person which is invited. + * @type {string} + **/ + email: string; + /** + * The phone number of the person which is invited. + * @type {string} + **/ + phonenumber: string; + /** + * Workspace which user is being invite to. + * @type {WorkspaceEntity} + **/ + workspace: WorkspaceEntity; + /** + * First name of the person which is invited + * @type {string} + **/ + firstName: string; + /** + * Last name of the person which is invited. + * @type {string} + **/ + lastName: string; + /** + * If forced, the email address cannot be changed by the user which has been invited. + * @type {boolean} + **/ + forceEmailAddress?: boolean; + /** + * If forced, user cannot change the phone number and needs to complete signup. + * @type {boolean} + **/ + forcePhoneNumber?: boolean; + /** + * The role which invitee get if they accept the request. + * @type {string} + **/ + roleId: string; +}; +// eslint-disable-next-line @typescript-eslint/no-namespace +export namespace WorkspaceInvitationDtoType {} diff --git a/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/usePostWorkspaceInvite.ts b/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/usePostWorkspaceInvite.ts index 2c6c07d6f..96155bbad 100644 --- a/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/usePostWorkspaceInvite.ts +++ b/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/usePostWorkspaceInvite.ts @@ -37,7 +37,7 @@ export function usePostWorkspaceInvite( ? execFn(options) : execApiFn(options); // Url of the remote affix. - const url = "/workspace/invite".substr(1); + const url = "/workspace-invite".substr(1); let computedUrl = `${url}?${new URLSearchParams( queryBeforeSend(query) ).toString()}`; From e4debfe1c03c36c2661875447fdea02e02965d9a Mon Sep 17 00:00:00 2001 From: Ali Date: Wed, 15 Apr 2026 20:02:01 +0200 Subject: [PATCH 2/4] Remove --- .../src/sdk/modules/abac/AbacActionsDto.ts | 28 - .../modules/abac/QueryUserRoleWorkspaces.ts | 705 ++++++++++++++++++ .../src/sdk/modules/abac/useGetUrwQuery.ts | 72 -- modules/abac/AbacCustomActions.dyno.go | 123 +-- modules/abac/AbacModule3.yml | 65 +- .../QueryUserRoleWorkspacesAction.dyno.go | 335 +++++++++ modules/abac/QueryUserRoleWorkspacesAction.go | 20 +- modules/abac/WorkspaceCli.go | 2 +- .../projectname/build-variables/local.json | 2 +- .../apps/core/WithSelfServiceRoutes.tsx | 13 +- .../layouts/useWorkspacesMenuPresenter.tsx | 9 +- .../modules/fireback/hooks/accessLevels.ts | 4 +- .../fireback/hooks/useRemoteMenuResolver.tsx | 11 +- .../src/modules/fireback/mock/api/auth.ts | 66 +- .../selfservice/SelectWorkspace.screen.tsx | 10 +- .../sdk/modules/abac/AbacActionsDto.ts | 28 - .../modules/abac/QueryUserRoleWorkspaces.ts | 705 ++++++++++++++++++ .../sdk/modules/abac/useGetUrwQuery.ts | 72 -- 18 files changed, 1891 insertions(+), 379 deletions(-) create mode 100644 e2e/react-bed/src/sdk/modules/abac/QueryUserRoleWorkspaces.ts delete mode 100644 e2e/react-bed/src/sdk/modules/abac/useGetUrwQuery.ts create mode 100644 modules/abac/QueryUserRoleWorkspacesAction.dyno.go create mode 100644 modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/QueryUserRoleWorkspaces.ts delete mode 100644 modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/useGetUrwQuery.ts diff --git a/e2e/react-bed/src/sdk/modules/abac/AbacActionsDto.ts b/e2e/react-bed/src/sdk/modules/abac/AbacActionsDto.ts index 6ec15832e..c77cfb7e5 100644 --- a/e2e/react-bed/src/sdk/modules/abac/AbacActionsDto.ts +++ b/e2e/react-bed/src/sdk/modules/abac/AbacActionsDto.ts @@ -13,34 +13,6 @@ import { import { GsmProviderEntity, } from "./GsmProviderEntity" - export class QueryUserRoleWorkspacesResDtoRoles { - public name?: string | null; - public uniqueId?: string | null; - /** - Capabilities related to this role which are available - */ - public capabilities?: string[] | null; - } -export class QueryUserRoleWorkspacesActionResDto { - public name?: string | null; - /** - Workspace level capabilities which are available - */ - public capabilities?: string[] | null; - public uniqueId?: string | null; - public roles?: QueryUserRoleWorkspacesResDtoRoles[] | null; -public static Fields = { - name: 'name', - capabilities: 'capabilities', - uniqueId: 'uniqueId', - roles$: 'roles', - roles: { - name: 'name', - uniqueId: 'uniqueId', - capabilities: 'capabilities', - }, -} -} export class SendEmailActionReqDto { public toAddress?: string | null; public body?: string | null; diff --git a/e2e/react-bed/src/sdk/modules/abac/QueryUserRoleWorkspaces.ts b/e2e/react-bed/src/sdk/modules/abac/QueryUserRoleWorkspaces.ts new file mode 100644 index 000000000..755ac01f7 --- /dev/null +++ b/e2e/react-bed/src/sdk/modules/abac/QueryUserRoleWorkspaces.ts @@ -0,0 +1,705 @@ +import { GResponse } from "../../sdk/envelopes/index"; +import { buildUrl } from "../../sdk/common/buildUrl"; +import { + fetchx, + handleFetchResponse, + type FetchxContext, + type PartialDeep, + type TypedRequestInit, + type TypedResponse, +} from "../../sdk/common/fetchx"; +import { + type UseMutationOptions, + type UseQueryOptions, + useMutation, + useQuery, +} from "react-query"; +import { useFetchxContext } from "../../sdk/react/useFetchx"; +import { useState } from "react"; +import { withPrefix } from "../../sdk/common/withPrefix"; +/** + * Action to communicate with the action QueryUserRoleWorkspaces + */ +export type QueryUserRoleWorkspacesActionOptions = { + queryKey?: unknown[]; + qs?: URLSearchParams; +}; +export type QueryUserRoleWorkspacesActionQueryOptions = Omit< + UseQueryOptions< + unknown, + unknown, + GResponse, + unknown[] + >, + "queryKey" +> & + QueryUserRoleWorkspacesActionOptions & + Partial<{ + creatorFn: (item: unknown) => QueryUserRoleWorkspacesActionRes; + }> & { + onMessage?: (ev: MessageEvent) => void; + overrideUrl?: string; + headers?: Headers; + ctx?: FetchxContext; + }; +export const useQueryUserRoleWorkspacesActionQuery = ( + options: QueryUserRoleWorkspacesActionQueryOptions, +) => { + const globalCtx = useFetchxContext(); + const ctx = options?.ctx ?? globalCtx ?? undefined; + const [isCompleted, setCompleteState] = useState(false); + const [response, setResponse] = useState>(); + const fn = () => { + setCompleteState(false); + return QueryUserRoleWorkspacesAction.Fetch( + { + headers: options?.headers, + }, + { + creatorFn: options?.creatorFn, + qs: options?.qs, + ctx, + onMessage: options?.onMessage, + overrideUrl: options?.overrideUrl, + }, + ).then((x) => { + x.done.then(() => { + setCompleteState(true); + }); + setResponse(x.response); + return x.response.result; + }); + }; + const result = useQuery({ + queryKey: [QueryUserRoleWorkspacesAction.NewUrl(options?.qs)], + queryFn: fn, + ...(options || {}), + }); + return { + ...result, + isCompleted, + response, + }; +}; +export type QueryUserRoleWorkspacesActionMutationOptions = Omit< + UseMutationOptions, + "mutationFn" +> & + QueryUserRoleWorkspacesActionOptions & { + ctx?: FetchxContext; + onMessage?: (ev: MessageEvent) => void; + overrideUrl?: string; + headers?: Headers; + } & Partial<{ + creatorFn: (item: unknown) => QueryUserRoleWorkspacesActionRes; + }>; +export const useQueryUserRoleWorkspacesAction = ( + options?: QueryUserRoleWorkspacesActionMutationOptions, +) => { + const globalCtx = useFetchxContext(); + const ctx = options?.ctx ?? globalCtx ?? undefined; + const [isCompleted, setCompleteState] = useState(false); + const [response, setResponse] = useState>(); + const fn = (body: unknown) => { + setCompleteState(false); + return QueryUserRoleWorkspacesAction.Fetch( + { + body, + headers: options?.headers, + }, + { + creatorFn: options?.creatorFn, + qs: options?.qs, + ctx, + onMessage: options?.onMessage, + overrideUrl: options?.overrideUrl, + }, + ).then((x) => { + x.done.then(() => { + setCompleteState(true); + }); + setResponse(x.response); + return x.response.result; + }); + }; + const result = useMutation({ + mutationFn: fn, + ...(options || {}), + }); + return { + ...result, + isCompleted, + response, + }; +}; +/** + * QueryUserRoleWorkspacesAction + */ +export class QueryUserRoleWorkspacesAction { + // + static URL = "/urw/query"; + static NewUrl = (qs?: URLSearchParams) => + buildUrl(QueryUserRoleWorkspacesAction.URL, undefined, qs); + static Method = "get"; + static Fetch$ = async ( + qs?: URLSearchParams, + ctx?: FetchxContext, + init?: TypedRequestInit, + overrideUrl?: string, + ) => { + return fetchx< + GResponse, + unknown, + unknown + >( + overrideUrl ?? QueryUserRoleWorkspacesAction.NewUrl(qs), + { + method: QueryUserRoleWorkspacesAction.Method, + ...(init || {}), + }, + ctx, + ); + }; + static Fetch = async ( + init?: TypedRequestInit, + { + creatorFn, + qs, + ctx, + onMessage, + overrideUrl, + }: { + creatorFn?: + | ((item: unknown) => QueryUserRoleWorkspacesActionRes) + | undefined; + qs?: URLSearchParams; + ctx?: FetchxContext; + onMessage?: (ev: MessageEvent) => void; + overrideUrl?: string; + } = { + creatorFn: (item) => new QueryUserRoleWorkspacesActionRes(item), + }, + ) => { + creatorFn = + creatorFn || ((item) => new QueryUserRoleWorkspacesActionRes(item)); + const res = await QueryUserRoleWorkspacesAction.Fetch$( + qs, + ctx, + init, + overrideUrl, + ); + return handleFetchResponse( + res, + (data) => { + const resp = new GResponse(); + if (creatorFn) { + resp.setCreator(creatorFn); + } + resp.inject(data); + return resp; + }, + onMessage, + init?.signal, + ); + }; + static Definition = { + name: "QueryUserRoleWorkspaces", + cliName: "urw", + url: "/urw/query", + method: "get", + description: + "Returns the workspaces that user belongs to, as well as his role in there, and the permissions for each role", + out: { + envelope: "GResponse", + fields: [ + { + name: "name", + type: "string", + }, + { + name: "capabilities", + description: "Workspace level capabilities which are available", + type: "slice", + primitive: "string", + }, + { + name: "uniqueId", + type: "string", + }, + { + name: "roles", + type: "array", + fields: [ + { + name: "name", + type: "string", + }, + { + name: "uniqueId", + type: "string", + }, + { + name: "capabilities", + description: + "Capabilities related to this role which are available", + type: "slice", + primitive: "string", + }, + ], + }, + ], + }, + }; +} +/** + * The base class definition for queryUserRoleWorkspacesActionRes + **/ +export class QueryUserRoleWorkspacesActionRes { + /** + * + * @type {string} + **/ + #name: string = ""; + /** + * + * @returns {string} + **/ + get name() { + return this.#name; + } + /** + * + * @type {string} + **/ + set name(value: string) { + this.#name = String(value); + } + setName(value: string) { + this.name = value; + return this; + } + /** + * Workspace level capabilities which are available + * @type {string[]} + **/ + #capabilities: string[] = []; + /** + * Workspace level capabilities which are available + * @returns {string[]} + **/ + get capabilities() { + return this.#capabilities; + } + /** + * Workspace level capabilities which are available + * @type {string[]} + **/ + set capabilities(value: string[]) { + this.#capabilities = value; + } + setCapabilities(value: string[]) { + this.capabilities = value; + return this; + } + /** + * + * @type {string} + **/ + #uniqueId: string = ""; + /** + * + * @returns {string} + **/ + get uniqueId() { + return this.#uniqueId; + } + /** + * + * @type {string} + **/ + set uniqueId(value: string) { + this.#uniqueId = String(value); + } + setUniqueId(value: string) { + this.uniqueId = value; + return this; + } + /** + * + * @type {QueryUserRoleWorkspacesActionRes.Roles} + **/ + #roles: InstanceType[] = []; + /** + * + * @returns {QueryUserRoleWorkspacesActionRes.Roles} + **/ + get roles() { + return this.#roles; + } + /** + * + * @type {QueryUserRoleWorkspacesActionRes.Roles} + **/ + set roles( + value: InstanceType[], + ) { + // For arrays, you only can pass arrays to the object + if (!Array.isArray(value)) { + return; + } + if ( + value.length > 0 && + value[0] instanceof QueryUserRoleWorkspacesActionRes.Roles + ) { + this.#roles = value; + } else { + this.#roles = value.map( + (item) => new QueryUserRoleWorkspacesActionRes.Roles(item), + ); + } + } + setRoles( + value: InstanceType[], + ) { + this.roles = value; + return this; + } + /** + * The base class definition for roles + **/ + static Roles = class Roles { + /** + * + * @type {string} + **/ + #name: string = ""; + /** + * + * @returns {string} + **/ + get name() { + return this.#name; + } + /** + * + * @type {string} + **/ + set name(value: string) { + this.#name = String(value); + } + setName(value: string) { + this.name = value; + return this; + } + /** + * + * @type {string} + **/ + #uniqueId: string = ""; + /** + * + * @returns {string} + **/ + get uniqueId() { + return this.#uniqueId; + } + /** + * + * @type {string} + **/ + set uniqueId(value: string) { + this.#uniqueId = String(value); + } + setUniqueId(value: string) { + this.uniqueId = value; + return this; + } + /** + * Capabilities related to this role which are available + * @type {string[]} + **/ + #capabilities: string[] = []; + /** + * Capabilities related to this role which are available + * @returns {string[]} + **/ + get capabilities() { + return this.#capabilities; + } + /** + * Capabilities related to this role which are available + * @type {string[]} + **/ + set capabilities(value: string[]) { + this.#capabilities = value; + } + setCapabilities(value: string[]) { + this.capabilities = value; + return this; + } + constructor(data: unknown = undefined) { + if (data === null || data === undefined) { + return; + } + if (typeof data === "string") { + this.applyFromObject(JSON.parse(data)); + } else if (this.#isJsonAppliable(data)) { + this.applyFromObject(data); + } else { + throw new Error( + "Instance cannot be created on an unknown value, check the content being passed. got: " + + typeof data, + ); + } + } + #isJsonAppliable(obj: unknown) { + const g = globalThis as unknown as { Buffer: any; Blob: any }; + const isBuffer = + typeof g.Buffer !== "undefined" && + typeof g.Buffer.isBuffer === "function" && + g.Buffer.isBuffer(obj); + const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; + return ( + obj && + typeof obj === "object" && + !Array.isArray(obj) && + !isBuffer && + !(obj instanceof ArrayBuffer) && + !isBlob + ); + } + /** + * casts the fields of a javascript object into the class properties one by one + **/ + applyFromObject(data = {}) { + const d = data as Partial; + if (d.name !== undefined) { + this.name = d.name; + } + if (d.uniqueId !== undefined) { + this.uniqueId = d.uniqueId; + } + if (d.capabilities !== undefined) { + this.capabilities = d.capabilities; + } + } + /** + * Special toJSON override, since the field are private, + * Json stringify won't see them unless we mention it explicitly. + **/ + toJSON() { + return { + name: this.#name, + uniqueId: this.#uniqueId, + capabilities: this.#capabilities, + }; + } + toString() { + return JSON.stringify(this); + } + static get Fields() { + return { + name: "name", + uniqueId: "uniqueId", + capabilities$: "capabilities", + get capabilities() { + return "roles.capabilities[:i]"; + }, + }; + } + /** + * Creates an instance of QueryUserRoleWorkspacesActionRes.Roles, and possibleDtoObject + * needs to satisfy the type requirement fully, otherwise typescript compile would + * be complaining. + **/ + static from( + possibleDtoObject: QueryUserRoleWorkspacesActionResType.RolesType, + ) { + return new QueryUserRoleWorkspacesActionRes.Roles(possibleDtoObject); + } + /** + * Creates an instance of QueryUserRoleWorkspacesActionRes.Roles, and partialDtoObject + * needs to satisfy the type, but partially, and rest of the content would + * be constructed according to data types and nullability. + **/ + static with( + partialDtoObject: PartialDeep, + ) { + return new QueryUserRoleWorkspacesActionRes.Roles(partialDtoObject); + } + copyWith( + partial: PartialDeep, + ): InstanceType { + return new QueryUserRoleWorkspacesActionRes.Roles({ + ...this.toJSON(), + ...partial, + }); + } + clone(): InstanceType { + return new QueryUserRoleWorkspacesActionRes.Roles(this.toJSON()); + } + }; + constructor(data: unknown = undefined) { + if (data === null || data === undefined) { + return; + } + if (typeof data === "string") { + this.applyFromObject(JSON.parse(data)); + } else if (this.#isJsonAppliable(data)) { + this.applyFromObject(data); + } else { + throw new Error( + "Instance cannot be created on an unknown value, check the content being passed. got: " + + typeof data, + ); + } + } + #isJsonAppliable(obj: unknown) { + const g = globalThis as unknown as { Buffer: any; Blob: any }; + const isBuffer = + typeof g.Buffer !== "undefined" && + typeof g.Buffer.isBuffer === "function" && + g.Buffer.isBuffer(obj); + const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; + return ( + obj && + typeof obj === "object" && + !Array.isArray(obj) && + !isBuffer && + !(obj instanceof ArrayBuffer) && + !isBlob + ); + } + /** + * casts the fields of a javascript object into the class properties one by one + **/ + applyFromObject(data = {}) { + const d = data as Partial; + if (d.name !== undefined) { + this.name = d.name; + } + if (d.capabilities !== undefined) { + this.capabilities = d.capabilities; + } + if (d.uniqueId !== undefined) { + this.uniqueId = d.uniqueId; + } + if (d.roles !== undefined) { + this.roles = d.roles; + } + } + /** + * Special toJSON override, since the field are private, + * Json stringify won't see them unless we mention it explicitly. + **/ + toJSON() { + return { + name: this.#name, + capabilities: this.#capabilities, + uniqueId: this.#uniqueId, + roles: this.#roles, + }; + } + toString() { + return JSON.stringify(this); + } + static get Fields() { + return { + name: "name", + capabilities$: "capabilities", + get capabilities() { + return "capabilities[:i]"; + }, + uniqueId: "uniqueId", + roles$: "roles", + get roles() { + return withPrefix( + "roles[:i]", + QueryUserRoleWorkspacesActionRes.Roles.Fields, + ); + }, + }; + } + /** + * Creates an instance of QueryUserRoleWorkspacesActionRes, and possibleDtoObject + * needs to satisfy the type requirement fully, otherwise typescript compile would + * be complaining. + **/ + static from(possibleDtoObject: QueryUserRoleWorkspacesActionResType) { + return new QueryUserRoleWorkspacesActionRes(possibleDtoObject); + } + /** + * Creates an instance of QueryUserRoleWorkspacesActionRes, and partialDtoObject + * needs to satisfy the type, but partially, and rest of the content would + * be constructed according to data types and nullability. + **/ + static with( + partialDtoObject: PartialDeep, + ) { + return new QueryUserRoleWorkspacesActionRes(partialDtoObject); + } + copyWith( + partial: PartialDeep, + ): InstanceType { + return new QueryUserRoleWorkspacesActionRes({ + ...this.toJSON(), + ...partial, + }); + } + clone(): InstanceType { + return new QueryUserRoleWorkspacesActionRes(this.toJSON()); + } +} +export abstract class QueryUserRoleWorkspacesActionResFactory { + abstract create(data: unknown): QueryUserRoleWorkspacesActionRes; +} +/** + * The base type definition for queryUserRoleWorkspacesActionRes + **/ +export type QueryUserRoleWorkspacesActionResType = { + /** + * + * @type {string} + **/ + name: string; + /** + * Workspace level capabilities which are available + * @type {string[]} + **/ + capabilities: string[]; + /** + * + * @type {string} + **/ + uniqueId: string; + /** + * + * @type {QueryUserRoleWorkspacesActionResType.RolesType[]} + **/ + roles: QueryUserRoleWorkspacesActionResType.RolesType[]; +}; +// eslint-disable-next-line @typescript-eslint/no-namespace +export namespace QueryUserRoleWorkspacesActionResType { + /** + * The base type definition for rolesType + **/ + export type RolesType = { + /** + * + * @type {string} + **/ + name: string; + /** + * + * @type {string} + **/ + uniqueId: string; + /** + * Capabilities related to this role which are available + * @type {string[]} + **/ + capabilities: string[]; + }; + // eslint-disable-next-line @typescript-eslint/no-namespace + export namespace RolesType {} +} diff --git a/e2e/react-bed/src/sdk/modules/abac/useGetUrwQuery.ts b/e2e/react-bed/src/sdk/modules/abac/useGetUrwQuery.ts deleted file mode 100644 index 3cdd7863a..000000000 --- a/e2e/react-bed/src/sdk/modules/abac/useGetUrwQuery.ts +++ /dev/null @@ -1,72 +0,0 @@ -/* -* Generated by fireback 1.2.5 -* Written by Ali Torabi. -* The code is generated for react-query@v3.39.3 -* Checkout the repository for licenses and contribution: https://github.com/torabian/fireback -*/ -import { useContext } from "react"; -import { useQuery } from "react-query"; -import { - RemoteQueryContext, - type UseRemoteQuery, - queryBeforeSend, -} from "../../core/react-tools"; -import { stringify } from "qs"; -import { execApiFn, type IResponseList } from "../../core/http-tools"; - import { - QueryUserRoleWorkspacesActionResDto, - } from "../abac/AbacActionsDto" -// Fireback gives the option to have typesafe query string -export type GetUrwQueryQs = { -} -export type GetUrwQueryUrlParams = { -} -export type GetUrwQueryHeaders = { -} -export function useGetUrwQuery({ - queryOptions, - query, - queryClient, - execFnOverride, - unauthorized, - optionFn -}: UseRemoteQuery & {query?: GetUrwQueryQs}) { - const { options, execFn } = useContext(RemoteQueryContext); - const computedOptions = optionFn ? optionFn(options) : options; - // Calculare the function which will do the remote calls. - // We consider to use global override, this specific override, or default which - // comes with the sdk. - const rpcFn = execFnOverride - ? execFnOverride(computedOptions) - : execFn - ? execFn(computedOptions) - : execApiFn(computedOptions); - // Url of the remote affix. - const url = "/urw/query".substr(1); - let computedUrl = `${url}?${stringify(query)}`; - let completeRouteUrls = true; - // Attach the details of the request to the fn - const fn = () => rpcFn("GET", computedUrl); - const auth = computedOptions?.headers?.authorization - const hasKey = auth != "undefined" && auth != undefined && auth !=null && auth != "null" && !!auth - let enabled = true; - if (!completeRouteUrls) { - enabled = false; - } else if (!hasKey && !unauthorized) { - enabled = false; - } - const query$ = useQuery, any>(["*abac.QueryUserRoleWorkspacesActionResDto", computedOptions, query], fn, { - cacheTime: 1000, - retry: false, - keepPreviousData: true, - enabled, - ...((queryOptions as any) || {}) - } as any); - const items: Array = query$.data?.data?.items || []; - return { - query: query$, - items, - keyExtractor: (item: QueryUserRoleWorkspacesActionResDto) => item.uniqueId, - }; -} -useGetUrwQuery.UKEY = "*abac.QueryUserRoleWorkspacesActionResDto" \ No newline at end of file diff --git a/modules/abac/AbacCustomActions.dyno.go b/modules/abac/AbacCustomActions.dyno.go index 2b36e75a1..a24bc78f0 100644 --- a/modules/abac/AbacCustomActions.dyno.go +++ b/modules/abac/AbacCustomActions.dyno.go @@ -15,64 +15,6 @@ import ( ) // using shared actions here -type QueryUserRoleWorkspacesResDtoRoles struct { - Name string `json:"name" xml:"name" yaml:"name" ` - UniqueId string `json:"uniqueId" xml:"uniqueId" yaml:"uniqueId" ` - // Capabilities related to this role which are available - Capabilities []string `json:"capabilities" xml:"capabilities" yaml:"capabilities" ` -} - -var QueryUserRoleWorkspacesSecurityModel = &fireback.SecurityModel{ - ActionRequires: []fireback.PermissionInfo{}, - ResolveStrategy: "user", -} - -type QueryUserRoleWorkspacesActionResDto struct { - Name string `json:"name" xml:"name" yaml:"name" ` - // Workspace level capabilities which are available - Capabilities []string `json:"capabilities" xml:"capabilities" yaml:"capabilities" ` - UniqueId string `json:"uniqueId" xml:"uniqueId" yaml:"uniqueId" ` - Roles []*QueryUserRoleWorkspacesResDtoRoles `json:"roles" xml:"roles" yaml:"roles" gorm:"foreignKey:LinkerId;references:UniqueId;constraint:OnDelete:CASCADE" ` -} - -func (x *QueryUserRoleWorkspacesActionResDto) RootObjectName() string { - return "Abac" -} - -type queryUserRoleWorkspacesActionImpSig func( - q fireback.QueryDSL) ([]*QueryUserRoleWorkspacesActionResDto, - *fireback.QueryResultMeta, - *fireback.IError, -) - -var QueryUserRoleWorkspacesActionImp queryUserRoleWorkspacesActionImpSig - -func QueryUserRoleWorkspacesActionFn( - q fireback.QueryDSL, -) ( - []*QueryUserRoleWorkspacesActionResDto, - *fireback.QueryResultMeta, - *fireback.IError, -) { - if QueryUserRoleWorkspacesActionImp == nil { - return nil, nil, nil - } - return QueryUserRoleWorkspacesActionImp(q) -} - -var QueryUserRoleWorkspacesActionCmd cli.Command = cli.Command{ - Name: "urw", - Usage: `Returns the workspaces that user belongs to, as well as his role in there, and the permissions for each role`, - Flags: fireback.CommonQueryFlags, - Action: func(c *cli.Context) { - fireback.CommonCliQueryCmd3IError( - c, - QueryUserRoleWorkspacesActionFn, - QueryUserRoleWorkspacesSecurityModel, - nil, - ) - }, -} var SendEmailSecurityModel *fireback.SecurityModel = nil type SendEmailActionReqDto struct { @@ -452,6 +394,44 @@ var GsmSendSmsWithProviderActionCmd cli.Command = cli.Command{ /// For emi, we also need to print the handlers, and also print security model, which is a part of Fireback /// and not available in Emi (won't be) +var QueryUserRoleWorkspacesImpl func(c QueryUserRoleWorkspacesActionRequest, query fireback.QueryDSL) (*QueryUserRoleWorkspacesActionResponse, error) = nil +var QueryUserRoleWorkspacesSecurityModel = &fireback.SecurityModel{ + ActionRequires: []fireback.PermissionInfo{}, + ResolveStrategy: "user", +} + +// This can be both used as cli and http +var QueryUserRoleWorkspacesActionDef fireback.Module3Action = fireback.Module3Action{ + // Temporary until fireback code gen is deleted. + Skip: true, + CliName: QueryUserRoleWorkspacesActionMeta().CliName, + Description: QueryUserRoleWorkspacesActionMeta().Description, + Name: QueryUserRoleWorkspacesActionMeta().Name, + Method: QueryUserRoleWorkspacesActionMeta().Method, + Url: QueryUserRoleWorkspacesActionMeta().URL, + SecurityModel: QueryUserRoleWorkspacesSecurityModel, + // get + Handlers: []gin.HandlerFunc{ + func(m *gin.Context) { + req := QueryUserRoleWorkspacesActionRequest{ + QueryParams: m.Request.URL.Query(), + Headers: m.Request.Header, + GinCtx: m, + } + query := fireback.ExtractQueryDslFromGinContext(m) + fireback.ReadGinRequestBodyAndCastToGoStruct(m, &req.Body, query) + resp, err := QueryUserRoleWorkspacesImpl(req, query) + fireback.WriteActionResponseToGin(m, resp, err) + }, + }, + CliAction: func(c *cli.Context, security *fireback.SecurityModel) error { + query := fireback.CommonCliQueryDSLBuilderAuthorize(c, QueryUserRoleWorkspacesSecurityModel) + req := QueryUserRoleWorkspacesActionRequest{} + resp, err := QueryUserRoleWorkspacesImpl(req, query) + fireback.HandleActionInCli2(c, resp, err, map[string]map[string]string{}) + return nil + }, +} var InviteToWorkspaceImpl func(c InviteToWorkspaceActionRequest, query fireback.QueryDSL) (*InviteToWorkspaceActionResponse, error) = nil var InviteToWorkspaceSecurityModel *fireback.SecurityModel = nil @@ -1063,6 +1043,7 @@ var OsLoginAuthenticateActionDef fireback.Module3Action = fireback.Module3Action func AbacCustomActions() []fireback.Module3Action { routes := []fireback.Module3Action{ //// Let's add actions for emi acts + QueryUserRoleWorkspacesActionDef, InviteToWorkspaceActionDef, UserInvitationsActionDef, SignoutActionDef, @@ -1081,29 +1062,6 @@ func AbacCustomActions() []fireback.Module3Action { CheckPassportMethodsActionDef, OsLoginAuthenticateActionDef, /// End for emi actions - { - Method: "GET", - Url: "/urw/query", - SecurityModel: QueryUserRoleWorkspacesSecurityModel, - Name: "queryUserRoleWorkspaces", - Description: "Returns the workspaces that user belongs to, as well as his role in there, and the permissions for each role", - Handlers: []gin.HandlerFunc{ - func(c *gin.Context) { - // QUERY - get - fireback.HttpQueryEntity( - c, - QueryUserRoleWorkspacesActionFn, - nil, - ) - }, - }, - Format: "QUERY", - Action: QueryUserRoleWorkspacesActionFn, - ResponseEntity: &QueryUserRoleWorkspacesActionResDto{}, - Out: &fireback.Module3ActionBody{ - Entity: "QueryUserRoleWorkspacesActionResDto", - }, - }, { Method: "POST", Url: "/email/send", @@ -1201,7 +1159,6 @@ func AbacCustomActions() []fireback.Module3Action { } var AbacCustomActionsCli = []cli.Command{ - QueryUserRoleWorkspacesActionCmd, SendEmailActionCmd, SendEmailWithProviderActionCmd, GsmSendSmsActionCmd, @@ -1221,6 +1178,7 @@ var AbacCliActionsBundle = &fireback.CliActionsBundle{ Usage: `Fireback ABAC module provides user authentication, basic support for most projects, including advanced role, permission module on top of fireback core module. Using this module is not essential to create fireback projects, but provides a great possibility to avoid building most user management flow. Some other helpers, such as timezone are added here.`, // Here we will include entities actions, as well as module level actions Subcommands: cli.Commands{ + QueryUserRoleWorkspacesActionDef.ToCli(), InviteToWorkspaceActionDef.ToCli(), UserInvitationsActionDef.ToCli(), SignoutActionDef.ToCli(), @@ -1238,7 +1196,6 @@ var AbacCliActionsBundle = &fireback.CliActionsBundle{ QueryWorkspaceTypesPubliclyActionDef.ToCli(), CheckPassportMethodsActionDef.ToCli(), OsLoginAuthenticateActionDef.ToCli(), - QueryUserRoleWorkspacesActionCmd, SendEmailActionCmd, SendEmailWithProviderActionCmd, GsmSendSmsActionCmd, diff --git a/modules/abac/AbacModule3.yml b/modules/abac/AbacModule3.yml index 939c8e0c5..716448c23 100644 --- a/modules/abac/AbacModule3.yml +++ b/modules/abac/AbacModule3.yml @@ -202,6 +202,38 @@ dtom: tags: validate: required acts: + - name: QueryUserRoleWorkspaces + method: get + url: /urw/query + cliName: urw + + security: + resolveStrategy: user + description: + Returns the workspaces that user belongs to, as well as his role in there, + and the permissions for each role + out: + envelope: GResponse + fields: + - name: name + type: string + - name: capabilities + type: slice + description: Workspace level capabilities which are available + primitive: string + - name: uniqueId + type: string + - name: roles + type: array + fields: + - name: name + type: string + - name: uniqueId + type: string + - name: capabilities + type: slice + description: Capabilities related to this role which are available + primitive: string - name: InviteToWorkspace url: /workspace/invite cliName: invite @@ -690,38 +722,6 @@ acts: out: dto: UserSessionDto actions: - - name: queryUserRoleWorkspaces - format: query - method: get - url: /urw/query - cliName: urw - security: - resolveStrategy: user - description: - Returns the workspaces that user belongs to, as well as his role in there, - and the permissions for each role - out: - fields: - - name: name - type: string - - name: capabilities - type: slice - description: Workspace level capabilities which are available - primitive: string - - name: uniqueId - type: string - - name: roles - type: array - fields: - - name: name - type: string - - name: uniqueId - type: string - - name: capabilities - type: slice - description: Capabilities related to this role which are available - primitive: string - - name: sendEmail url: /email/send cliName: email @@ -759,7 +759,6 @@ actions: fields: - name: queueId type: string - - name: gsmSendSms url: /gsm/send/sms cliName: sms diff --git a/modules/abac/QueryUserRoleWorkspacesAction.dyno.go b/modules/abac/QueryUserRoleWorkspacesAction.dyno.go new file mode 100644 index 000000000..3ea8eb839 --- /dev/null +++ b/modules/abac/QueryUserRoleWorkspacesAction.dyno.go @@ -0,0 +1,335 @@ +package abac + +import ( + "encoding/json" + "fmt" + "github.com/gin-gonic/gin" + "github.com/torabian/emi/emigo" + "github.com/urfave/cli" + "io" + "net/http" + "net/url" +) + +/** +* Action to communicate with the action QueryUserRoleWorkspacesAction + */ +func QueryUserRoleWorkspacesActionMeta() struct { + Name string + CliName string + URL string + Method string + Description string +} { + return struct { + Name string + CliName string + URL string + Method string + Description string + }{ + Name: "QueryUserRoleWorkspacesAction", + CliName: "urw", + URL: "/urw/query", + Method: "GET", + Description: `Returns the workspaces that user belongs to, as well as his role in there, and the permissions for each role`, + } +} +func GetQueryUserRoleWorkspacesActionResCliFlags(prefix string) []emigo.CliFlag { + return []emigo.CliFlag{ + { + Name: prefix + "name", + Type: "string", + }, + { + Name: prefix + "capabilities", + Type: "slice", + }, + { + Name: prefix + "unique-id", + Type: "string", + }, + { + Name: prefix + "roles", + Type: "array", + }, + } +} +func CastQueryUserRoleWorkspacesActionResFromCli(c emigo.CliCastable) QueryUserRoleWorkspacesActionRes { + data := QueryUserRoleWorkspacesActionRes{} + if c.IsSet("name") { + data.Name = c.String("name") + } + if c.IsSet("capabilities") { + emigo.InflatePossibleSlice(c.String("capabilities"), &data.Capabilities) + } + if c.IsSet("unique-id") { + data.UniqueId = c.String("unique-id") + } + if c.IsSet("roles") { + data.Roles = emigo.CapturePossibleArray(CastQueryUserRoleWorkspacesActionResRolesFromCli, "roles", c) + } + return data +} + +// The base class definition for queryUserRoleWorkspacesActionRes +type QueryUserRoleWorkspacesActionRes struct { + Name string `json:"name" yaml:"name"` + // Workspace level capabilities which are available + Capabilities []string `json:"capabilities" yaml:"capabilities"` + UniqueId string `json:"uniqueId" yaml:"uniqueId"` + Roles []QueryUserRoleWorkspacesActionResRoles `json:"roles" yaml:"roles"` +} + +func GetQueryUserRoleWorkspacesActionResRolesCliFlags(prefix string) []emigo.CliFlag { + return []emigo.CliFlag{ + { + Name: prefix + "name", + Type: "string", + }, + { + Name: prefix + "unique-id", + Type: "string", + }, + { + Name: prefix + "capabilities", + Type: "slice", + }, + } +} +func CastQueryUserRoleWorkspacesActionResRolesFromCli(c emigo.CliCastable) QueryUserRoleWorkspacesActionResRoles { + data := QueryUserRoleWorkspacesActionResRoles{} + if c.IsSet("name") { + data.Name = c.String("name") + } + if c.IsSet("unique-id") { + data.UniqueId = c.String("unique-id") + } + if c.IsSet("capabilities") { + emigo.InflatePossibleSlice(c.String("capabilities"), &data.Capabilities) + } + return data +} + +// The base class definition for roles +type QueryUserRoleWorkspacesActionResRoles struct { + Name string `json:"name" yaml:"name"` + UniqueId string `json:"uniqueId" yaml:"uniqueId"` + // Capabilities related to this role which are available + Capabilities []string `json:"capabilities" yaml:"capabilities"` +} + +func (x *QueryUserRoleWorkspacesActionRes) Json() string { + if x != nil { + str, _ := json.MarshalIndent(x, "", " ") + return string(str) + } + return "" +} + +type QueryUserRoleWorkspacesActionResponse struct { + StatusCode int + Headers map[string]string + Payload interface{} +} + +func (x *QueryUserRoleWorkspacesActionResponse) SetContentType(contentType string) *QueryUserRoleWorkspacesActionResponse { + if x.Headers == nil { + x.Headers = make(map[string]string) + } + x.Headers["Content-Type"] = contentType + return x +} +func (x *QueryUserRoleWorkspacesActionResponse) AsStream(r io.Reader, contentType string) *QueryUserRoleWorkspacesActionResponse { + x.Payload = r + x.SetContentType(contentType) + return x +} +func (x *QueryUserRoleWorkspacesActionResponse) AsJSON(payload any) *QueryUserRoleWorkspacesActionResponse { + x.Payload = payload + x.SetContentType("application/json") + return x +} +func (x *QueryUserRoleWorkspacesActionResponse) AsHTML(payload string) *QueryUserRoleWorkspacesActionResponse { + x.Payload = payload + x.SetContentType("text/html; charset=utf-8") + return x +} +func (x *QueryUserRoleWorkspacesActionResponse) AsBytes(payload []byte) *QueryUserRoleWorkspacesActionResponse { + x.Payload = payload + x.SetContentType("application/octet-stream") + return x +} +func (x QueryUserRoleWorkspacesActionResponse) GetStatusCode() int { + return x.StatusCode +} +func (x QueryUserRoleWorkspacesActionResponse) GetRespHeaders() map[string]string { + return x.Headers +} +func (x QueryUserRoleWorkspacesActionResponse) GetPayload() interface{} { + return x.Payload +} + +// QueryUserRoleWorkspacesActionRaw registers a raw Gin route for the QueryUserRoleWorkspacesAction action. +// This gives the developer full control over middleware, handlers, and response handling. +func QueryUserRoleWorkspacesActionRaw(r *gin.Engine, handlers ...gin.HandlerFunc) { + meta := QueryUserRoleWorkspacesActionMeta() + r.Handle(meta.Method, meta.URL, handlers...) +} + +type QueryUserRoleWorkspacesActionRequestSig = func(c QueryUserRoleWorkspacesActionRequest) (*QueryUserRoleWorkspacesActionResponse, error) + +// QueryUserRoleWorkspacesActionHandler returns the HTTP method, route URL, and a typed Gin handler for the QueryUserRoleWorkspacesAction action. +// Developers implement their business logic as a function that receives a typed request object +// and returns either an *ActionResponse or nil. JSON marshalling, headers, and errors are handled automatically. +func QueryUserRoleWorkspacesActionHandler( + handler QueryUserRoleWorkspacesActionRequestSig, +) (method, url string, h gin.HandlerFunc) { + meta := QueryUserRoleWorkspacesActionMeta() + return meta.Method, meta.URL, func(m *gin.Context) { + // Build typed request wrapper + req := QueryUserRoleWorkspacesActionRequest{ + Body: nil, + QueryParams: m.Request.URL.Query(), + Headers: m.Request.Header, + GinCtx: m, + } + resp, err := handler(req) + if err != nil { + m.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + // If the handler returned nil (and no error), it means the response was handled manually. + if resp == nil { + return + } + // Apply headers + for k, v := range resp.Headers { + m.Header(k, v) + } + // Apply status and payload + status := resp.StatusCode + if status == 0 { + status = http.StatusOK + } + if resp.Payload != nil { + m.JSON(status, resp.Payload) + } else { + m.Status(status) + } + } +} + +// QueryUserRoleWorkspacesAction is a high-level convenience wrapper around QueryUserRoleWorkspacesActionHandler. +// It automatically constructs and registers the typed route on the Gin engine. +// Use this when you don't need custom middleware or route grouping. +func QueryUserRoleWorkspacesActionGin(r gin.IRoutes, handler QueryUserRoleWorkspacesActionRequestSig) { + method, url, h := QueryUserRoleWorkspacesActionHandler(handler) + r.Handle(method, url, h) +} + +/** + * Query parameters for QueryUserRoleWorkspacesAction + */ +// Query wrapper with private fields +type QueryUserRoleWorkspacesActionQuery struct { + values url.Values + mapped map[string]interface{} + // Typesafe fields +} + +func QueryUserRoleWorkspacesActionQueryFromString(rawQuery string) QueryUserRoleWorkspacesActionQuery { + v := QueryUserRoleWorkspacesActionQuery{} + values, _ := url.ParseQuery(rawQuery) + mapped := map[string]interface{}{} + if result, err := emigo.UnmarshalQs(rawQuery); err == nil { + mapped = result + } + decoder, err := emigo.NewDecoder(&emigo.DecoderConfig{ + TagName: "json", // reuse json tags + WeaklyTypedInput: true, // "1" -> int, "true" -> bool + Result: &v, + }) + if err == nil { + _ = decoder.Decode(mapped) + } + v.values = values + v.mapped = mapped + return v +} +func QueryUserRoleWorkspacesActionQueryFromGin(c *gin.Context) QueryUserRoleWorkspacesActionQuery { + return QueryUserRoleWorkspacesActionQueryFromString(c.Request.URL.RawQuery) +} +func QueryUserRoleWorkspacesActionQueryFromHttp(r *http.Request) QueryUserRoleWorkspacesActionQuery { + return QueryUserRoleWorkspacesActionQueryFromString(r.URL.RawQuery) +} +func (q QueryUserRoleWorkspacesActionQuery) Values() url.Values { + return q.values +} +func (q QueryUserRoleWorkspacesActionQuery) Mapped() map[string]interface{} { + return q.mapped +} +func (q *QueryUserRoleWorkspacesActionQuery) SetValues(v url.Values) { + q.values = v +} +func (q *QueryUserRoleWorkspacesActionQuery) SetMapped(m map[string]interface{}) { + q.mapped = m +} + +type QueryUserRoleWorkspacesActionRequest struct { + Body interface{} + QueryParams url.Values + Headers http.Header + GinCtx *gin.Context + CliCtx *cli.Context +} +type QueryUserRoleWorkspacesActionResult struct { + resp *http.Response // embed original response + Payload interface{} +} + +func QueryUserRoleWorkspacesActionCall( + req QueryUserRoleWorkspacesActionRequest, + config *emigo.APIClient, // optional pre-built request +) (*QueryUserRoleWorkspacesActionResult, error) { + var httpReq *http.Request + if config == nil || config.Httpr == nil { + meta := QueryUserRoleWorkspacesActionMeta() + baseURL := meta.URL + // Build final URL with query string + u, err := url.Parse(baseURL) + if err != nil { + return nil, err + } + // if UrlValues present, encode and append + if len(req.QueryParams) > 0 { + u.RawQuery = req.QueryParams.Encode() + } + req0, err := http.NewRequest(meta.Method, u.String(), nil) + if err != nil { + return nil, err + } + httpReq = req0 + } else { + httpReq = config.Httpr + } + httpReq.Header = req.Headers + resp, err := http.DefaultClient.Do(httpReq) + if err != nil { + return nil, err + } + var result QueryUserRoleWorkspacesActionResult + result.resp = resp + defer resp.Body.Close() + respBody, err := io.ReadAll(resp.Body) + if err != nil { + return &result, err + } + if resp.StatusCode >= 400 { + return &result, fmt.Errorf("request failed: %s", respBody) + } + if err := json.Unmarshal(respBody, &result.Payload); err != nil { + return &result, err + } + return &result, nil +} diff --git a/modules/abac/QueryUserRoleWorkspacesAction.go b/modules/abac/QueryUserRoleWorkspacesAction.go index 354964966..fbae25a41 100644 --- a/modules/abac/QueryUserRoleWorkspacesAction.go +++ b/modules/abac/QueryUserRoleWorkspacesAction.go @@ -8,31 +8,27 @@ import ( func init() { // Override the implementation with our actual code. - QueryUserRoleWorkspacesActionImp = QueryUserRoleWorkspacesAction + QueryUserRoleWorkspacesImpl = QueryUserRoleWorkspacesAction } -func QueryUserRoleWorkspacesAction( - q fireback.QueryDSL) ([]*QueryUserRoleWorkspacesActionResDto, - *fireback.QueryResultMeta, - *fireback.IError, -) { +func QueryUserRoleWorkspacesAction(c QueryUserRoleWorkspacesActionRequest, q fireback.QueryDSL) (*QueryUserRoleWorkspacesActionResponse, error) { - items := []*QueryUserRoleWorkspacesActionResDto{} + items := []*QueryUserRoleWorkspacesActionRes{} if q.UserAccessPerWorkspace != nil { for workspaceId, content := range *q.UserAccessPerWorkspace { - roles := []*QueryUserRoleWorkspacesResDtoRoles{} + roles := []QueryUserRoleWorkspacesActionResRoles{} for roleId, roleContent := range content.UserRoles { - roles = append(roles, &QueryUserRoleWorkspacesResDtoRoles{ + roles = append(roles, QueryUserRoleWorkspacesActionResRoles{ Name: roleContent.Name, Capabilities: roleContent.Accesses, UniqueId: roleId, }) } - items = append(items, &QueryUserRoleWorkspacesActionResDto{ + items = append(items, &QueryUserRoleWorkspacesActionRes{ Name: content.Name, UniqueId: workspaceId, Roles: roles, @@ -45,5 +41,7 @@ func QueryUserRoleWorkspacesAction( return items[i].UniqueId < items[j].UniqueId }) - return items, nil, nil + return &QueryUserRoleWorkspacesActionResponse{ + Payload: fireback.GResponseQuery(items, nil, &q), + }, nil } diff --git a/modules/abac/WorkspaceCli.go b/modules/abac/WorkspaceCli.go index df8abd9a6..321d74c95 100644 --- a/modules/abac/WorkspaceCli.go +++ b/modules/abac/WorkspaceCli.go @@ -233,7 +233,7 @@ func init() { CliConfigCmd, ViewAuthorize, QueryWorkspaceTypesPubliclyActionDef.ToCli(), - QueryUserRoleWorkspacesActionCmd, + QueryUserRoleWorkspacesActionDef.ToCli(), CheckUserMeetsAPermissionCmd, WorkspaceAsCmd, PublicAuthenticationCliFn(), diff --git a/modules/fireback/codegen/react-new/src/apps/projectname/build-variables/local.json b/modules/fireback/codegen/react-new/src/apps/projectname/build-variables/local.json index 37385b4f5..1bfd8e310 100644 --- a/modules/fireback/codegen/react-new/src/apps/projectname/build-variables/local.json +++ b/modules/fireback/codegen/react-new/src/apps/projectname/build-variables/local.json @@ -8,7 +8,7 @@ "VITE_SUPPORTED_LANGUAGES": "fa,en", "VITE_FEATURE_DASHBOARD": "true", "VITE_USE_HASH_ROUTER": "true", - "VITE_INACCURATE_MOCK_MODE": "false", + "VITE_INACCURATE_MOCK_MODE": "true", "VITE_TITLE": "projectname", "VITE_ALLOW_REMOTE_LOGIN": "true", "VITE_FORCE_AUTHENTICATION": "true", diff --git a/modules/fireback/codegen/react-new/src/modules/fireback/apps/core/WithSelfServiceRoutes.tsx b/modules/fireback/codegen/react-new/src/modules/fireback/apps/core/WithSelfServiceRoutes.tsx index 0a612ba4a..b80fc4655 100644 --- a/modules/fireback/codegen/react-new/src/modules/fireback/apps/core/WithSelfServiceRoutes.tsx +++ b/modules/fireback/codegen/react-new/src/modules/fireback/apps/core/WithSelfServiceRoutes.tsx @@ -8,11 +8,11 @@ import { import { type ReactNode, useContext, useEffect } from "react"; import { useCheckAuthentication } from "../../components/layouts/ForcedAuthenticated"; +import { BUILD_VARIABLES } from "../../hooks/build-variables"; +import { SelectWorkspaceScreen } from "../../modules/selfservice/SelectWorkspace.screen"; import { useSelfServicePublicRoutes } from "../../modules/selfservice/SelfServiceRoutes"; import { RemoteQueryContext } from "../../sdk/core/react-tools"; -import { SelectWorkspaceScreen } from "../../modules/selfservice/SelectWorkspace.screen"; -import { useGetUrwQuery } from "../../sdk/modules/abac/useGetUrwQuery"; -import { BUILD_VARIABLES } from "../../hooks/build-variables"; +import { useQueryUserRoleWorkspacesActionQuery } from "../../sdk/modules/abac/QueryUserRoleWorkspaces"; const useHashRouter = BUILD_VARIABLES.USE_HASH_ROUTER === "true"; const Router = useHashRouter ? HashRouter : BrowserRouter; @@ -26,10 +26,9 @@ export const WithSelfServiceRoutes = ({ const selfServicePublicRoutes = useSelfServicePublicRoutes(); const { selectedUrw, selectUrw } = useContext(RemoteQueryContext); - const { query: queryUrw } = useGetUrwQuery({ - queryOptions: { cacheTime: 50, enabled: false }, // this react-query 3, how can I avoid it to run until later alert time to figure this out, - // as promise and continue? - query: {}, + const queryUrw = useQueryUserRoleWorkspacesActionQuery({ + cacheTime: 50, + enabled: false }); useEffect(() => { diff --git a/modules/fireback/codegen/react-new/src/modules/fireback/components/layouts/useWorkspacesMenuPresenter.tsx b/modules/fireback/codegen/react-new/src/modules/fireback/components/layouts/useWorkspacesMenuPresenter.tsx index 35c909757..9120d9a2b 100644 --- a/modules/fireback/codegen/react-new/src/modules/fireback/components/layouts/useWorkspacesMenuPresenter.tsx +++ b/modules/fireback/codegen/react-new/src/modules/fireback/components/layouts/useWorkspacesMenuPresenter.tsx @@ -2,7 +2,7 @@ import { useContext, useMemo } from "react"; import { MacTagsColor, type MenuItem } from "../../definitions/common"; import { useT } from "../../hooks/useT"; import { RemoteQueryContext } from "../../sdk/core/react-tools"; -import { useGetUrwQuery } from "../../sdk/modules/abac/useGetUrwQuery"; +import { useQueryUserRoleWorkspacesActionQuery } from "../../sdk/modules/abac/QueryUserRoleWorkspaces"; /** * It computes the menu items related to the workspaces, and active role generally @@ -13,12 +13,11 @@ import { useGetUrwQuery } from "../../sdk/modules/abac/useGetUrwQuery"; export function useWorkspacesMenuPresenter() { const t = useT(); const { selectedUrw, selectUrw } = useContext(RemoteQueryContext); - const { query: queryWorkspaces } = useGetUrwQuery({ - queryOptions: { cacheTime: 50 }, - query: {}, + const queryUrw = useQueryUserRoleWorkspacesActionQuery({ + cacheTime: 50, }); - const items = queryWorkspaces.data?.data?.items || []; + const items = queryUrw.data?.data?.items || []; const recomputeKey = items.map((item) => item.uniqueId).join("-") + "_" + diff --git a/modules/fireback/codegen/react-new/src/modules/fireback/hooks/accessLevels.ts b/modules/fireback/codegen/react-new/src/modules/fireback/hooks/accessLevels.ts index 953f70ce3..d0baef84e 100644 --- a/modules/fireback/codegen/react-new/src/modules/fireback/hooks/accessLevels.ts +++ b/modules/fireback/codegen/react-new/src/modules/fireback/hooks/accessLevels.ts @@ -1,5 +1,5 @@ import { type DisplayDetectionProps } from "../definitions/common"; -import { QueryUserRoleWorkspacesActionResDto } from "../sdk/modules/abac/AbacActionsDto"; +import type { QueryUserRoleWorkspacesActionRes } from "../sdk/modules/abac/QueryUserRoleWorkspaces"; import { CapabilityEntity } from "../sdk/modules/fireback/CapabilityEntity"; export function userMeetsAccess(urw: any, perm: string): boolean { @@ -22,7 +22,7 @@ export function userMeetsAccess(urw: any, perm: string): boolean { export function userMeetsAccess2( state: { roleId: string; workspaceId: string }, - urw: QueryUserRoleWorkspacesActionResDto[], + urw: QueryUserRoleWorkspacesActionRes[], perm: string ): boolean { let workspaceMeets = false; diff --git a/modules/fireback/codegen/react-new/src/modules/fireback/hooks/useRemoteMenuResolver.tsx b/modules/fireback/codegen/react-new/src/modules/fireback/hooks/useRemoteMenuResolver.tsx index 3e3030fda..db528dcb5 100644 --- a/modules/fireback/codegen/react-new/src/modules/fireback/hooks/useRemoteMenuResolver.tsx +++ b/modules/fireback/codegen/react-new/src/modules/fireback/hooks/useRemoteMenuResolver.tsx @@ -6,7 +6,7 @@ import { useQueryClient } from "react-query"; import { useLocale } from "./useLocale"; import { RemoteQueryContext } from "../sdk/core/react-tools"; import { userMeetsAccess2 } from "./accessLevels"; -import { useGetUrwQuery } from "../sdk/modules/abac/useGetUrwQuery"; +import { useQueryUserRoleWorkspacesActionQuery } from "../sdk/modules/abac/QueryUserRoleWorkspaces"; /** * @@ -15,12 +15,15 @@ import { useGetUrwQuery } from "../sdk/modules/abac/useGetUrwQuery"; export function useRemoteMenuResolver(menuGroup: string): MenuItem[] { const queryClient = useQueryClient(); const { selectedUrw } = useContext(RemoteQueryContext) as any; - const { query: queryWorkspaces } = useGetUrwQuery({ query: {} }); + const queryUrw = useQueryUserRoleWorkspacesActionQuery({ + cacheTime: 50, + }); + const { query } = useGetCteAppMenus({ queryClient, queryOptions: { refetchOnWindowFocus: false, - enabled: !queryWorkspaces.isError && queryWorkspaces.isSuccess, + enabled: !queryUrw.isError && queryUrw.isSuccess, }, query: { itemsPerPage: 9999, @@ -42,7 +45,7 @@ export function useRemoteMenuResolver(menuGroup: string): MenuItem[] { return userMeetsAccess2( selectedUrw, - queryWorkspaces.data?.data?.items || [], + queryUrw.data?.data?.items || [], permissionKey ); }; diff --git a/modules/fireback/codegen/react-new/src/modules/fireback/mock/api/auth.ts b/modules/fireback/codegen/react-new/src/modules/fireback/mock/api/auth.ts index 57918ab12..c5446dd6a 100644 --- a/modules/fireback/codegen/react-new/src/modules/fireback/mock/api/auth.ts +++ b/modules/fireback/codegen/react-new/src/modules/fireback/mock/api/auth.ts @@ -1,4 +1,4 @@ -import { type IResponse, type IResponseList } from "../../definitions/JSONStyle"; +import { type IResponseList } from "../../definitions/JSONStyle"; import { type Context, type DeepPartial, @@ -17,14 +17,16 @@ import { WorkspaceInviteEntity } from "../../sdk/modules/abac/WorkspaceInviteEnt import { WorkspaceTypeEntity } from "../../sdk/modules/abac/WorkspaceTypeEntity"; import { GResponse } from "../../sdk/sdk/envelopes"; -const commonSession: IResponse> = { +const commonSession: GResponse> = { data: { - user: { - firstName: "Ali", - lastName: "Torabi", + item: { + user: { + firstName: "Ali", + lastName: "Torabi", + }, + exchangeKey: "key1", + token: "token", }, - exchangeKey: "key1", - token: "token", }, }; @@ -33,7 +35,7 @@ export class AuthMockServer { @method("post") async passportAuthroizeOs( ctx: Context, - ): Promise>> { + ): Promise>> { return commonSession; } @@ -49,7 +51,7 @@ export class AuthMockServer { @method("post") async postSigninClassic( ctx: Context, - ): Promise>> { + ): Promise>> { return commonSession; } @@ -57,7 +59,7 @@ export class AuthMockServer { @method("post") async postRequestResetMail( ctx: Context, - ): Promise>> { + ): Promise>> { return commonSession; } @@ -83,23 +85,27 @@ export class AuthMockServer { @method("post") async postWorkspacePassportCheck( ctx: Context, - ): Promise>> { + ): Promise> { const isEmail = ctx?.body?.value.includes("@"); if (isEmail) { return { data: { - next: ["otp", "create-with-password"], - flags: ["enable-totp", "force-totp"], - otpInfo: null, + item: { + next: ["otp", "create-with-password"], + flags: ["enable-totp", "force-totp"], + otpInfo: null, + } }, }; } else { return { data: { - next: ["otp"], - flags: ["enable-totp", "force-totp"], - otpInfo: null, + item: { + next: ["otp"], + flags: ["enable-totp", "force-totp"], + otpInfo: null, + } }, }; } @@ -109,16 +115,18 @@ export class AuthMockServer { @method("post") async postPassportSignupClassic( ctx: Context, - ): Promise>> { + ): Promise>> { const isEmail = ctx?.body?.value.includes("@"); return { data: { - session: null, - totpUrl: - "otpauth://totp/Fireback:ali@ali.com?algorithm=SHA1\u0026digits=6\u0026issuer=Fireback\u0026period=30\u0026secret=R2AQ4NPS7FKECL3ZVTF3JMTLBYGDAAVU", - continueToTotp: true, - forcedTotp: true, + item: { + session: null, + totpUrl: + "otpauth://totp/Fireback:ali@ali.com?algorithm=SHA1\u0026digits=6\u0026issuer=Fireback\u0026period=30\u0026secret=R2AQ4NPS7FKECL3ZVTF3JMTLBYGDAAVU", + continueToTotp: true, + forcedTotp: true, + } }, }; } @@ -127,10 +135,12 @@ export class AuthMockServer { @method("post") async postConfirm( ctx: Context, - ): Promise>> { + ): Promise>> { return { data: { - session: commonSession.data, + item: { + session: commonSession.data, + } }, }; } @@ -139,10 +149,12 @@ export class AuthMockServer { @method("post") async postOtp( ctx: Context, - ): Promise>> { + ): Promise>> { return { data: { - session: commonSession.data, + item: { + session: commonSession.data, + } }, }; } diff --git a/modules/fireback/codegen/react-new/src/modules/fireback/modules/selfservice/SelectWorkspace.screen.tsx b/modules/fireback/codegen/react-new/src/modules/fireback/modules/selfservice/SelectWorkspace.screen.tsx index 36228ac5d..075bb81f5 100644 --- a/modules/fireback/codegen/react-new/src/modules/fireback/modules/selfservice/SelectWorkspace.screen.tsx +++ b/modules/fireback/codegen/react-new/src/modules/fireback/modules/selfservice/SelectWorkspace.screen.tsx @@ -1,15 +1,15 @@ import { useContext } from "react"; -import { useGetUrwQuery } from "../../sdk/modules/abac/useGetUrwQuery"; import { usePresenter } from "./SelectWorkspace.presenter"; import { RemoteQueryContext } from "../../sdk/core/react-tools"; +import { useQueryUserRoleWorkspacesActionQuery } from "../../sdk/modules/abac/QueryUserRoleWorkspaces"; export const SelectWorkspaceScreen = () => { const { s } = usePresenter(); - const { query: queryWorkspaces } = useGetUrwQuery({ - queryOptions: { cacheTime: 50 }, - query: {}, + const queryUrw = useQueryUserRoleWorkspacesActionQuery({ + cacheTime: 50, }); - const items = queryWorkspaces.data?.data?.items || []; + + const items = queryUrw.data?.data?.items || []; const { selectedUrw, selectUrw } = useContext(RemoteQueryContext); return ( diff --git a/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/AbacActionsDto.ts b/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/AbacActionsDto.ts index 6ec15832e..c77cfb7e5 100644 --- a/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/AbacActionsDto.ts +++ b/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/AbacActionsDto.ts @@ -13,34 +13,6 @@ import { import { GsmProviderEntity, } from "./GsmProviderEntity" - export class QueryUserRoleWorkspacesResDtoRoles { - public name?: string | null; - public uniqueId?: string | null; - /** - Capabilities related to this role which are available - */ - public capabilities?: string[] | null; - } -export class QueryUserRoleWorkspacesActionResDto { - public name?: string | null; - /** - Workspace level capabilities which are available - */ - public capabilities?: string[] | null; - public uniqueId?: string | null; - public roles?: QueryUserRoleWorkspacesResDtoRoles[] | null; -public static Fields = { - name: 'name', - capabilities: 'capabilities', - uniqueId: 'uniqueId', - roles$: 'roles', - roles: { - name: 'name', - uniqueId: 'uniqueId', - capabilities: 'capabilities', - }, -} -} export class SendEmailActionReqDto { public toAddress?: string | null; public body?: string | null; diff --git a/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/QueryUserRoleWorkspaces.ts b/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/QueryUserRoleWorkspaces.ts new file mode 100644 index 000000000..755ac01f7 --- /dev/null +++ b/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/QueryUserRoleWorkspaces.ts @@ -0,0 +1,705 @@ +import { GResponse } from "../../sdk/envelopes/index"; +import { buildUrl } from "../../sdk/common/buildUrl"; +import { + fetchx, + handleFetchResponse, + type FetchxContext, + type PartialDeep, + type TypedRequestInit, + type TypedResponse, +} from "../../sdk/common/fetchx"; +import { + type UseMutationOptions, + type UseQueryOptions, + useMutation, + useQuery, +} from "react-query"; +import { useFetchxContext } from "../../sdk/react/useFetchx"; +import { useState } from "react"; +import { withPrefix } from "../../sdk/common/withPrefix"; +/** + * Action to communicate with the action QueryUserRoleWorkspaces + */ +export type QueryUserRoleWorkspacesActionOptions = { + queryKey?: unknown[]; + qs?: URLSearchParams; +}; +export type QueryUserRoleWorkspacesActionQueryOptions = Omit< + UseQueryOptions< + unknown, + unknown, + GResponse, + unknown[] + >, + "queryKey" +> & + QueryUserRoleWorkspacesActionOptions & + Partial<{ + creatorFn: (item: unknown) => QueryUserRoleWorkspacesActionRes; + }> & { + onMessage?: (ev: MessageEvent) => void; + overrideUrl?: string; + headers?: Headers; + ctx?: FetchxContext; + }; +export const useQueryUserRoleWorkspacesActionQuery = ( + options: QueryUserRoleWorkspacesActionQueryOptions, +) => { + const globalCtx = useFetchxContext(); + const ctx = options?.ctx ?? globalCtx ?? undefined; + const [isCompleted, setCompleteState] = useState(false); + const [response, setResponse] = useState>(); + const fn = () => { + setCompleteState(false); + return QueryUserRoleWorkspacesAction.Fetch( + { + headers: options?.headers, + }, + { + creatorFn: options?.creatorFn, + qs: options?.qs, + ctx, + onMessage: options?.onMessage, + overrideUrl: options?.overrideUrl, + }, + ).then((x) => { + x.done.then(() => { + setCompleteState(true); + }); + setResponse(x.response); + return x.response.result; + }); + }; + const result = useQuery({ + queryKey: [QueryUserRoleWorkspacesAction.NewUrl(options?.qs)], + queryFn: fn, + ...(options || {}), + }); + return { + ...result, + isCompleted, + response, + }; +}; +export type QueryUserRoleWorkspacesActionMutationOptions = Omit< + UseMutationOptions, + "mutationFn" +> & + QueryUserRoleWorkspacesActionOptions & { + ctx?: FetchxContext; + onMessage?: (ev: MessageEvent) => void; + overrideUrl?: string; + headers?: Headers; + } & Partial<{ + creatorFn: (item: unknown) => QueryUserRoleWorkspacesActionRes; + }>; +export const useQueryUserRoleWorkspacesAction = ( + options?: QueryUserRoleWorkspacesActionMutationOptions, +) => { + const globalCtx = useFetchxContext(); + const ctx = options?.ctx ?? globalCtx ?? undefined; + const [isCompleted, setCompleteState] = useState(false); + const [response, setResponse] = useState>(); + const fn = (body: unknown) => { + setCompleteState(false); + return QueryUserRoleWorkspacesAction.Fetch( + { + body, + headers: options?.headers, + }, + { + creatorFn: options?.creatorFn, + qs: options?.qs, + ctx, + onMessage: options?.onMessage, + overrideUrl: options?.overrideUrl, + }, + ).then((x) => { + x.done.then(() => { + setCompleteState(true); + }); + setResponse(x.response); + return x.response.result; + }); + }; + const result = useMutation({ + mutationFn: fn, + ...(options || {}), + }); + return { + ...result, + isCompleted, + response, + }; +}; +/** + * QueryUserRoleWorkspacesAction + */ +export class QueryUserRoleWorkspacesAction { + // + static URL = "/urw/query"; + static NewUrl = (qs?: URLSearchParams) => + buildUrl(QueryUserRoleWorkspacesAction.URL, undefined, qs); + static Method = "get"; + static Fetch$ = async ( + qs?: URLSearchParams, + ctx?: FetchxContext, + init?: TypedRequestInit, + overrideUrl?: string, + ) => { + return fetchx< + GResponse, + unknown, + unknown + >( + overrideUrl ?? QueryUserRoleWorkspacesAction.NewUrl(qs), + { + method: QueryUserRoleWorkspacesAction.Method, + ...(init || {}), + }, + ctx, + ); + }; + static Fetch = async ( + init?: TypedRequestInit, + { + creatorFn, + qs, + ctx, + onMessage, + overrideUrl, + }: { + creatorFn?: + | ((item: unknown) => QueryUserRoleWorkspacesActionRes) + | undefined; + qs?: URLSearchParams; + ctx?: FetchxContext; + onMessage?: (ev: MessageEvent) => void; + overrideUrl?: string; + } = { + creatorFn: (item) => new QueryUserRoleWorkspacesActionRes(item), + }, + ) => { + creatorFn = + creatorFn || ((item) => new QueryUserRoleWorkspacesActionRes(item)); + const res = await QueryUserRoleWorkspacesAction.Fetch$( + qs, + ctx, + init, + overrideUrl, + ); + return handleFetchResponse( + res, + (data) => { + const resp = new GResponse(); + if (creatorFn) { + resp.setCreator(creatorFn); + } + resp.inject(data); + return resp; + }, + onMessage, + init?.signal, + ); + }; + static Definition = { + name: "QueryUserRoleWorkspaces", + cliName: "urw", + url: "/urw/query", + method: "get", + description: + "Returns the workspaces that user belongs to, as well as his role in there, and the permissions for each role", + out: { + envelope: "GResponse", + fields: [ + { + name: "name", + type: "string", + }, + { + name: "capabilities", + description: "Workspace level capabilities which are available", + type: "slice", + primitive: "string", + }, + { + name: "uniqueId", + type: "string", + }, + { + name: "roles", + type: "array", + fields: [ + { + name: "name", + type: "string", + }, + { + name: "uniqueId", + type: "string", + }, + { + name: "capabilities", + description: + "Capabilities related to this role which are available", + type: "slice", + primitive: "string", + }, + ], + }, + ], + }, + }; +} +/** + * The base class definition for queryUserRoleWorkspacesActionRes + **/ +export class QueryUserRoleWorkspacesActionRes { + /** + * + * @type {string} + **/ + #name: string = ""; + /** + * + * @returns {string} + **/ + get name() { + return this.#name; + } + /** + * + * @type {string} + **/ + set name(value: string) { + this.#name = String(value); + } + setName(value: string) { + this.name = value; + return this; + } + /** + * Workspace level capabilities which are available + * @type {string[]} + **/ + #capabilities: string[] = []; + /** + * Workspace level capabilities which are available + * @returns {string[]} + **/ + get capabilities() { + return this.#capabilities; + } + /** + * Workspace level capabilities which are available + * @type {string[]} + **/ + set capabilities(value: string[]) { + this.#capabilities = value; + } + setCapabilities(value: string[]) { + this.capabilities = value; + return this; + } + /** + * + * @type {string} + **/ + #uniqueId: string = ""; + /** + * + * @returns {string} + **/ + get uniqueId() { + return this.#uniqueId; + } + /** + * + * @type {string} + **/ + set uniqueId(value: string) { + this.#uniqueId = String(value); + } + setUniqueId(value: string) { + this.uniqueId = value; + return this; + } + /** + * + * @type {QueryUserRoleWorkspacesActionRes.Roles} + **/ + #roles: InstanceType[] = []; + /** + * + * @returns {QueryUserRoleWorkspacesActionRes.Roles} + **/ + get roles() { + return this.#roles; + } + /** + * + * @type {QueryUserRoleWorkspacesActionRes.Roles} + **/ + set roles( + value: InstanceType[], + ) { + // For arrays, you only can pass arrays to the object + if (!Array.isArray(value)) { + return; + } + if ( + value.length > 0 && + value[0] instanceof QueryUserRoleWorkspacesActionRes.Roles + ) { + this.#roles = value; + } else { + this.#roles = value.map( + (item) => new QueryUserRoleWorkspacesActionRes.Roles(item), + ); + } + } + setRoles( + value: InstanceType[], + ) { + this.roles = value; + return this; + } + /** + * The base class definition for roles + **/ + static Roles = class Roles { + /** + * + * @type {string} + **/ + #name: string = ""; + /** + * + * @returns {string} + **/ + get name() { + return this.#name; + } + /** + * + * @type {string} + **/ + set name(value: string) { + this.#name = String(value); + } + setName(value: string) { + this.name = value; + return this; + } + /** + * + * @type {string} + **/ + #uniqueId: string = ""; + /** + * + * @returns {string} + **/ + get uniqueId() { + return this.#uniqueId; + } + /** + * + * @type {string} + **/ + set uniqueId(value: string) { + this.#uniqueId = String(value); + } + setUniqueId(value: string) { + this.uniqueId = value; + return this; + } + /** + * Capabilities related to this role which are available + * @type {string[]} + **/ + #capabilities: string[] = []; + /** + * Capabilities related to this role which are available + * @returns {string[]} + **/ + get capabilities() { + return this.#capabilities; + } + /** + * Capabilities related to this role which are available + * @type {string[]} + **/ + set capabilities(value: string[]) { + this.#capabilities = value; + } + setCapabilities(value: string[]) { + this.capabilities = value; + return this; + } + constructor(data: unknown = undefined) { + if (data === null || data === undefined) { + return; + } + if (typeof data === "string") { + this.applyFromObject(JSON.parse(data)); + } else if (this.#isJsonAppliable(data)) { + this.applyFromObject(data); + } else { + throw new Error( + "Instance cannot be created on an unknown value, check the content being passed. got: " + + typeof data, + ); + } + } + #isJsonAppliable(obj: unknown) { + const g = globalThis as unknown as { Buffer: any; Blob: any }; + const isBuffer = + typeof g.Buffer !== "undefined" && + typeof g.Buffer.isBuffer === "function" && + g.Buffer.isBuffer(obj); + const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; + return ( + obj && + typeof obj === "object" && + !Array.isArray(obj) && + !isBuffer && + !(obj instanceof ArrayBuffer) && + !isBlob + ); + } + /** + * casts the fields of a javascript object into the class properties one by one + **/ + applyFromObject(data = {}) { + const d = data as Partial; + if (d.name !== undefined) { + this.name = d.name; + } + if (d.uniqueId !== undefined) { + this.uniqueId = d.uniqueId; + } + if (d.capabilities !== undefined) { + this.capabilities = d.capabilities; + } + } + /** + * Special toJSON override, since the field are private, + * Json stringify won't see them unless we mention it explicitly. + **/ + toJSON() { + return { + name: this.#name, + uniqueId: this.#uniqueId, + capabilities: this.#capabilities, + }; + } + toString() { + return JSON.stringify(this); + } + static get Fields() { + return { + name: "name", + uniqueId: "uniqueId", + capabilities$: "capabilities", + get capabilities() { + return "roles.capabilities[:i]"; + }, + }; + } + /** + * Creates an instance of QueryUserRoleWorkspacesActionRes.Roles, and possibleDtoObject + * needs to satisfy the type requirement fully, otherwise typescript compile would + * be complaining. + **/ + static from( + possibleDtoObject: QueryUserRoleWorkspacesActionResType.RolesType, + ) { + return new QueryUserRoleWorkspacesActionRes.Roles(possibleDtoObject); + } + /** + * Creates an instance of QueryUserRoleWorkspacesActionRes.Roles, and partialDtoObject + * needs to satisfy the type, but partially, and rest of the content would + * be constructed according to data types and nullability. + **/ + static with( + partialDtoObject: PartialDeep, + ) { + return new QueryUserRoleWorkspacesActionRes.Roles(partialDtoObject); + } + copyWith( + partial: PartialDeep, + ): InstanceType { + return new QueryUserRoleWorkspacesActionRes.Roles({ + ...this.toJSON(), + ...partial, + }); + } + clone(): InstanceType { + return new QueryUserRoleWorkspacesActionRes.Roles(this.toJSON()); + } + }; + constructor(data: unknown = undefined) { + if (data === null || data === undefined) { + return; + } + if (typeof data === "string") { + this.applyFromObject(JSON.parse(data)); + } else if (this.#isJsonAppliable(data)) { + this.applyFromObject(data); + } else { + throw new Error( + "Instance cannot be created on an unknown value, check the content being passed. got: " + + typeof data, + ); + } + } + #isJsonAppliable(obj: unknown) { + const g = globalThis as unknown as { Buffer: any; Blob: any }; + const isBuffer = + typeof g.Buffer !== "undefined" && + typeof g.Buffer.isBuffer === "function" && + g.Buffer.isBuffer(obj); + const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; + return ( + obj && + typeof obj === "object" && + !Array.isArray(obj) && + !isBuffer && + !(obj instanceof ArrayBuffer) && + !isBlob + ); + } + /** + * casts the fields of a javascript object into the class properties one by one + **/ + applyFromObject(data = {}) { + const d = data as Partial; + if (d.name !== undefined) { + this.name = d.name; + } + if (d.capabilities !== undefined) { + this.capabilities = d.capabilities; + } + if (d.uniqueId !== undefined) { + this.uniqueId = d.uniqueId; + } + if (d.roles !== undefined) { + this.roles = d.roles; + } + } + /** + * Special toJSON override, since the field are private, + * Json stringify won't see them unless we mention it explicitly. + **/ + toJSON() { + return { + name: this.#name, + capabilities: this.#capabilities, + uniqueId: this.#uniqueId, + roles: this.#roles, + }; + } + toString() { + return JSON.stringify(this); + } + static get Fields() { + return { + name: "name", + capabilities$: "capabilities", + get capabilities() { + return "capabilities[:i]"; + }, + uniqueId: "uniqueId", + roles$: "roles", + get roles() { + return withPrefix( + "roles[:i]", + QueryUserRoleWorkspacesActionRes.Roles.Fields, + ); + }, + }; + } + /** + * Creates an instance of QueryUserRoleWorkspacesActionRes, and possibleDtoObject + * needs to satisfy the type requirement fully, otherwise typescript compile would + * be complaining. + **/ + static from(possibleDtoObject: QueryUserRoleWorkspacesActionResType) { + return new QueryUserRoleWorkspacesActionRes(possibleDtoObject); + } + /** + * Creates an instance of QueryUserRoleWorkspacesActionRes, and partialDtoObject + * needs to satisfy the type, but partially, and rest of the content would + * be constructed according to data types and nullability. + **/ + static with( + partialDtoObject: PartialDeep, + ) { + return new QueryUserRoleWorkspacesActionRes(partialDtoObject); + } + copyWith( + partial: PartialDeep, + ): InstanceType { + return new QueryUserRoleWorkspacesActionRes({ + ...this.toJSON(), + ...partial, + }); + } + clone(): InstanceType { + return new QueryUserRoleWorkspacesActionRes(this.toJSON()); + } +} +export abstract class QueryUserRoleWorkspacesActionResFactory { + abstract create(data: unknown): QueryUserRoleWorkspacesActionRes; +} +/** + * The base type definition for queryUserRoleWorkspacesActionRes + **/ +export type QueryUserRoleWorkspacesActionResType = { + /** + * + * @type {string} + **/ + name: string; + /** + * Workspace level capabilities which are available + * @type {string[]} + **/ + capabilities: string[]; + /** + * + * @type {string} + **/ + uniqueId: string; + /** + * + * @type {QueryUserRoleWorkspacesActionResType.RolesType[]} + **/ + roles: QueryUserRoleWorkspacesActionResType.RolesType[]; +}; +// eslint-disable-next-line @typescript-eslint/no-namespace +export namespace QueryUserRoleWorkspacesActionResType { + /** + * The base type definition for rolesType + **/ + export type RolesType = { + /** + * + * @type {string} + **/ + name: string; + /** + * + * @type {string} + **/ + uniqueId: string; + /** + * Capabilities related to this role which are available + * @type {string[]} + **/ + capabilities: string[]; + }; + // eslint-disable-next-line @typescript-eslint/no-namespace + export namespace RolesType {} +} diff --git a/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/useGetUrwQuery.ts b/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/useGetUrwQuery.ts deleted file mode 100644 index 3cdd7863a..000000000 --- a/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/useGetUrwQuery.ts +++ /dev/null @@ -1,72 +0,0 @@ -/* -* Generated by fireback 1.2.5 -* Written by Ali Torabi. -* The code is generated for react-query@v3.39.3 -* Checkout the repository for licenses and contribution: https://github.com/torabian/fireback -*/ -import { useContext } from "react"; -import { useQuery } from "react-query"; -import { - RemoteQueryContext, - type UseRemoteQuery, - queryBeforeSend, -} from "../../core/react-tools"; -import { stringify } from "qs"; -import { execApiFn, type IResponseList } from "../../core/http-tools"; - import { - QueryUserRoleWorkspacesActionResDto, - } from "../abac/AbacActionsDto" -// Fireback gives the option to have typesafe query string -export type GetUrwQueryQs = { -} -export type GetUrwQueryUrlParams = { -} -export type GetUrwQueryHeaders = { -} -export function useGetUrwQuery({ - queryOptions, - query, - queryClient, - execFnOverride, - unauthorized, - optionFn -}: UseRemoteQuery & {query?: GetUrwQueryQs}) { - const { options, execFn } = useContext(RemoteQueryContext); - const computedOptions = optionFn ? optionFn(options) : options; - // Calculare the function which will do the remote calls. - // We consider to use global override, this specific override, or default which - // comes with the sdk. - const rpcFn = execFnOverride - ? execFnOverride(computedOptions) - : execFn - ? execFn(computedOptions) - : execApiFn(computedOptions); - // Url of the remote affix. - const url = "/urw/query".substr(1); - let computedUrl = `${url}?${stringify(query)}`; - let completeRouteUrls = true; - // Attach the details of the request to the fn - const fn = () => rpcFn("GET", computedUrl); - const auth = computedOptions?.headers?.authorization - const hasKey = auth != "undefined" && auth != undefined && auth !=null && auth != "null" && !!auth - let enabled = true; - if (!completeRouteUrls) { - enabled = false; - } else if (!hasKey && !unauthorized) { - enabled = false; - } - const query$ = useQuery, any>(["*abac.QueryUserRoleWorkspacesActionResDto", computedOptions, query], fn, { - cacheTime: 1000, - retry: false, - keepPreviousData: true, - enabled, - ...((queryOptions as any) || {}) - } as any); - const items: Array = query$.data?.data?.items || []; - return { - query: query$, - items, - keyExtractor: (item: QueryUserRoleWorkspacesActionResDto) => item.uniqueId, - }; -} -useGetUrwQuery.UKEY = "*abac.QueryUserRoleWorkspacesActionResDto" \ No newline at end of file From e2b2b349505ae0e08d596aab86a62cc2b8b51731 Mon Sep 17 00:00:00 2001 From: Ali Date: Wed, 15 Apr 2026 20:10:22 +0200 Subject: [PATCH 3/4] Merge --- modules/abac/AbacCustomActions.dyno.go | 628 +++++------------- modules/abac/AbacModule3.yml | 39 +- modules/abac/EmailProviderEntity.go | 6 +- modules/abac/GsmProviderEntity.go | 14 +- modules/abac/GsmSendSmsAction.dyno.go | 318 +++++++++ modules/abac/GsmSendSmsAction.go | 27 +- .../abac/GsmSendSmsWithProviderAction.dyno.go | 326 +++++++++ modules/abac/GsmSendSmsWithProviderAction.go | 16 +- modules/abac/InviteToWorkspaceAction.go | 8 +- modules/abac/SendEmailAction.dyno.go | 318 +++++++++ modules/abac/SendEmailAction.go | 12 +- .../abac/SendEmailWithProviderAction.dyno.go | 323 +++++++++ modules/abac/SendEmailWithProviderAction.go | 12 +- 13 files changed, 1504 insertions(+), 543 deletions(-) create mode 100644 modules/abac/GsmSendSmsAction.dyno.go create mode 100644 modules/abac/GsmSendSmsWithProviderAction.dyno.go create mode 100644 modules/abac/SendEmailAction.dyno.go create mode 100644 modules/abac/SendEmailWithProviderAction.dyno.go diff --git a/modules/abac/AbacCustomActions.dyno.go b/modules/abac/AbacCustomActions.dyno.go index a24bc78f0..c86f8a387 100644 --- a/modules/abac/AbacCustomActions.dyno.go +++ b/modules/abac/AbacCustomActions.dyno.go @@ -15,383 +15,6 @@ import ( ) // using shared actions here -var SendEmailSecurityModel *fireback.SecurityModel = nil - -type SendEmailActionReqDto struct { - ToAddress string `json:"toAddress" xml:"toAddress" yaml:"toAddress" validate:"required" ` - Body string `json:"body" xml:"body" yaml:"body" validate:"required" ` -} - -func (x *SendEmailActionReqDto) RootObjectName() string { - return "Abac" -} - -var SendEmailCommonCliFlagsOptional = []cli.Flag{ - &cli.StringFlag{ - Name: "x-src", - Required: false, - Usage: `Import the body of the request from a file (e.g. json/yaml) on the disk`, - }, - &cli.StringFlag{ - Name: "x-accept", - Usage: "Return type of the the content, such as json or yaml", - }, - &cli.StringFlag{ - Name: "to-address", - Required: true, - Usage: `toAddress (string)`, - }, - &cli.StringFlag{ - Name: "body", - Required: true, - Usage: `body (string)`, - }, -} - -func SendEmailActionReqValidator(dto *SendEmailActionReqDto) *fireback.IError { - err := fireback.CommonStructValidatorPointer(dto, false) - return err -} -func CastSendEmailFromCli(c *cli.Context) *SendEmailActionReqDto { - template := &SendEmailActionReqDto{} - fireback.HandleXsrc(c, template) - if c.IsSet("to-address") { - template.ToAddress = c.String("to-address") - } - if c.IsSet("body") { - template.Body = c.String("body") - } - return template -} - -type SendEmailActionResDto struct { - QueueId string `json:"queueId" xml:"queueId" yaml:"queueId" ` -} - -func (x *SendEmailActionResDto) RootObjectName() string { - return "Abac" -} - -type sendEmailActionImpSig func( - req *SendEmailActionReqDto, - q fireback.QueryDSL) (*SendEmailActionResDto, - *fireback.IError, -) - -var SendEmailActionImp sendEmailActionImpSig - -func SendEmailActionFn( - req *SendEmailActionReqDto, - q fireback.QueryDSL, -) ( - *SendEmailActionResDto, - *fireback.IError, -) { - if SendEmailActionImp == nil { - return nil, nil - } - return SendEmailActionImp(req, q) -} - -var SendEmailActionCmd cli.Command = cli.Command{ - Name: "email", - Usage: `Send a email using default root notification configuration`, - Flags: SendEmailCommonCliFlagsOptional, - Action: func(c *cli.Context) { - query := fireback.CommonCliQueryDSLBuilderAuthorize(c, SendEmailSecurityModel) - dto := CastSendEmailFromCli(c) - result, err := SendEmailActionFn(dto, query) - fireback.HandleActionInCli(c, result, err, map[string]map[string]string{}) - }, -} -var SendEmailWithProviderSecurityModel *fireback.SecurityModel = nil - -type SendEmailWithProviderActionReqDto struct { - EmailProvider *EmailProviderEntity `json:"emailProvider" xml:"emailProvider" yaml:"emailProvider" gorm:"foreignKey:EmailProviderId;references:UniqueId" ` - EmailProviderId fireback.String `json:"emailProviderId" yaml:"emailProviderId" xml:"emailProviderId" ` - ToAddress string `json:"toAddress" xml:"toAddress" yaml:"toAddress" validate:"required" ` - Body string `json:"body" xml:"body" yaml:"body" validate:"required" ` -} - -func (x *SendEmailWithProviderActionReqDto) RootObjectName() string { - return "Abac" -} - -var SendEmailWithProviderCommonCliFlagsOptional = []cli.Flag{ - &cli.StringFlag{ - Name: "x-src", - Required: false, - Usage: `Import the body of the request from a file (e.g. json/yaml) on the disk`, - }, - &cli.StringFlag{ - Name: "x-accept", - Usage: "Return type of the the content, such as json or yaml", - }, - &cli.StringFlag{ - Name: "email-provider-id", - Required: false, - Usage: `emailProvider (one)`, - }, - &cli.StringFlag{ - Name: "to-address", - Required: true, - Usage: `toAddress (string)`, - }, - &cli.StringFlag{ - Name: "body", - Required: true, - Usage: `body (string)`, - }, -} - -func SendEmailWithProviderActionReqValidator(dto *SendEmailWithProviderActionReqDto) *fireback.IError { - err := fireback.CommonStructValidatorPointer(dto, false) - return err -} -func CastSendEmailWithProviderFromCli(c *cli.Context) *SendEmailWithProviderActionReqDto { - template := &SendEmailWithProviderActionReqDto{} - fireback.HandleXsrc(c, template) - if c.IsSet("email-provider-id") { - template.EmailProviderId = fireback.NewStringAutoNull(c.String("email-provider-id")) - } - if c.IsSet("to-address") { - template.ToAddress = c.String("to-address") - } - if c.IsSet("body") { - template.Body = c.String("body") - } - return template -} - -type SendEmailWithProviderActionResDto struct { - QueueId string `json:"queueId" xml:"queueId" yaml:"queueId" ` -} - -func (x *SendEmailWithProviderActionResDto) RootObjectName() string { - return "Abac" -} - -type sendEmailWithProviderActionImpSig func( - req *SendEmailWithProviderActionReqDto, - q fireback.QueryDSL) (*SendEmailWithProviderActionResDto, - *fireback.IError, -) - -var SendEmailWithProviderActionImp sendEmailWithProviderActionImpSig - -func SendEmailWithProviderActionFn( - req *SendEmailWithProviderActionReqDto, - q fireback.QueryDSL, -) ( - *SendEmailWithProviderActionResDto, - *fireback.IError, -) { - if SendEmailWithProviderActionImp == nil { - return nil, nil - } - return SendEmailWithProviderActionImp(req, q) -} - -var SendEmailWithProviderActionCmd cli.Command = cli.Command{ - Name: "emailp", - Usage: `Send a text message using an specific gsm provider`, - Flags: SendEmailWithProviderCommonCliFlagsOptional, - Action: func(c *cli.Context) { - query := fireback.CommonCliQueryDSLBuilderAuthorize(c, SendEmailWithProviderSecurityModel) - dto := CastSendEmailWithProviderFromCli(c) - result, err := SendEmailWithProviderActionFn(dto, query) - fireback.HandleActionInCli(c, result, err, map[string]map[string]string{}) - }, -} -var GsmSendSmsSecurityModel *fireback.SecurityModel = nil - -type GsmSendSmsActionReqDto struct { - ToNumber string `json:"toNumber" xml:"toNumber" yaml:"toNumber" validate:"required" ` - Body string `json:"body" xml:"body" yaml:"body" validate:"required" ` -} - -func (x *GsmSendSmsActionReqDto) RootObjectName() string { - return "Abac" -} - -var GsmSendSmsCommonCliFlagsOptional = []cli.Flag{ - &cli.StringFlag{ - Name: "x-src", - Required: false, - Usage: `Import the body of the request from a file (e.g. json/yaml) on the disk`, - }, - &cli.StringFlag{ - Name: "x-accept", - Usage: "Return type of the the content, such as json or yaml", - }, - &cli.StringFlag{ - Name: "to-number", - Required: true, - Usage: `toNumber (string)`, - }, - &cli.StringFlag{ - Name: "body", - Required: true, - Usage: `body (string)`, - }, -} - -func GsmSendSmsActionReqValidator(dto *GsmSendSmsActionReqDto) *fireback.IError { - err := fireback.CommonStructValidatorPointer(dto, false) - return err -} -func CastGsmSendSmsFromCli(c *cli.Context) *GsmSendSmsActionReqDto { - template := &GsmSendSmsActionReqDto{} - fireback.HandleXsrc(c, template) - if c.IsSet("to-number") { - template.ToNumber = c.String("to-number") - } - if c.IsSet("body") { - template.Body = c.String("body") - } - return template -} - -type GsmSendSmsActionResDto struct { - QueueId string `json:"queueId" xml:"queueId" yaml:"queueId" ` -} - -func (x *GsmSendSmsActionResDto) RootObjectName() string { - return "Abac" -} - -type gsmSendSmsActionImpSig func( - req *GsmSendSmsActionReqDto, - q fireback.QueryDSL) (*GsmSendSmsActionResDto, - *fireback.IError, -) - -var GsmSendSmsActionImp gsmSendSmsActionImpSig - -func GsmSendSmsActionFn( - req *GsmSendSmsActionReqDto, - q fireback.QueryDSL, -) ( - *GsmSendSmsActionResDto, - *fireback.IError, -) { - if GsmSendSmsActionImp == nil { - return nil, nil - } - return GsmSendSmsActionImp(req, q) -} - -var GsmSendSmsActionCmd cli.Command = cli.Command{ - Name: "sms", - Usage: `Send a text message using default root notification configuration`, - Flags: GsmSendSmsCommonCliFlagsOptional, - Action: func(c *cli.Context) { - query := fireback.CommonCliQueryDSLBuilderAuthorize(c, GsmSendSmsSecurityModel) - dto := CastGsmSendSmsFromCli(c) - result, err := GsmSendSmsActionFn(dto, query) - fireback.HandleActionInCli(c, result, err, map[string]map[string]string{}) - }, -} -var GsmSendSmsWithProviderSecurityModel *fireback.SecurityModel = nil - -type GsmSendSmsWithProviderActionReqDto struct { - GsmProvider *GsmProviderEntity `json:"gsmProvider" xml:"gsmProvider" yaml:"gsmProvider" gorm:"foreignKey:GsmProviderId;references:UniqueId" ` - GsmProviderId fireback.String `json:"gsmProviderId" yaml:"gsmProviderId" xml:"gsmProviderId" ` - ToNumber string `json:"toNumber" xml:"toNumber" yaml:"toNumber" validate:"required" ` - Body string `json:"body" xml:"body" yaml:"body" validate:"required" ` -} - -func (x *GsmSendSmsWithProviderActionReqDto) RootObjectName() string { - return "Abac" -} - -var GsmSendSmsWithProviderCommonCliFlagsOptional = []cli.Flag{ - &cli.StringFlag{ - Name: "x-src", - Required: false, - Usage: `Import the body of the request from a file (e.g. json/yaml) on the disk`, - }, - &cli.StringFlag{ - Name: "x-accept", - Usage: "Return type of the the content, such as json or yaml", - }, - &cli.StringFlag{ - Name: "gsm-provider-id", - Required: false, - Usage: `gsmProvider (one)`, - }, - &cli.StringFlag{ - Name: "to-number", - Required: true, - Usage: `toNumber (string)`, - }, - &cli.StringFlag{ - Name: "body", - Required: true, - Usage: `body (string)`, - }, -} - -func GsmSendSmsWithProviderActionReqValidator(dto *GsmSendSmsWithProviderActionReqDto) *fireback.IError { - err := fireback.CommonStructValidatorPointer(dto, false) - return err -} -func CastGsmSendSmsWithProviderFromCli(c *cli.Context) *GsmSendSmsWithProviderActionReqDto { - template := &GsmSendSmsWithProviderActionReqDto{} - fireback.HandleXsrc(c, template) - if c.IsSet("gsm-provider-id") { - template.GsmProviderId = fireback.NewStringAutoNull(c.String("gsm-provider-id")) - } - if c.IsSet("to-number") { - template.ToNumber = c.String("to-number") - } - if c.IsSet("body") { - template.Body = c.String("body") - } - return template -} - -type GsmSendSmsWithProviderActionResDto struct { - QueueId string `json:"queueId" xml:"queueId" yaml:"queueId" ` -} - -func (x *GsmSendSmsWithProviderActionResDto) RootObjectName() string { - return "Abac" -} - -type gsmSendSmsWithProviderActionImpSig func( - req *GsmSendSmsWithProviderActionReqDto, - q fireback.QueryDSL) (*GsmSendSmsWithProviderActionResDto, - *fireback.IError, -) - -var GsmSendSmsWithProviderActionImp gsmSendSmsWithProviderActionImpSig - -func GsmSendSmsWithProviderActionFn( - req *GsmSendSmsWithProviderActionReqDto, - q fireback.QueryDSL, -) ( - *GsmSendSmsWithProviderActionResDto, - *fireback.IError, -) { - if GsmSendSmsWithProviderActionImp == nil { - return nil, nil - } - return GsmSendSmsWithProviderActionImp(req, q) -} - -var GsmSendSmsWithProviderActionCmd cli.Command = cli.Command{ - Name: "smsp", - Usage: `Send a text message using an specific gsm provider`, - Flags: GsmSendSmsWithProviderCommonCliFlagsOptional, - Action: func(c *cli.Context) { - query := fireback.CommonCliQueryDSLBuilderAuthorize(c, GsmSendSmsWithProviderSecurityModel) - dto := CastGsmSendSmsWithProviderFromCli(c) - result, err := GsmSendSmsWithProviderActionFn(dto, query) - fireback.HandleActionInCli(c, result, err, map[string]map[string]string{}) - }, -} - /// For emi, we also need to print the handlers, and also print security model, which is a part of Fireback /// and not available in Emi (won't be) var QueryUserRoleWorkspacesImpl func(c QueryUserRoleWorkspacesActionRequest, query fireback.QueryDSL) (*QueryUserRoleWorkspacesActionResponse, error) = nil @@ -1039,6 +662,146 @@ var OsLoginAuthenticateActionDef fireback.Module3Action = fireback.Module3Action return nil }, } +var SendEmailImpl func(c SendEmailActionRequest, query fireback.QueryDSL) (*SendEmailActionResponse, error) = nil +var SendEmailSecurityModel *fireback.SecurityModel = nil + +// This can be both used as cli and http +var SendEmailActionDef fireback.Module3Action = fireback.Module3Action{ + // Temporary until fireback code gen is deleted. + Skip: true, + CliName: SendEmailActionMeta().CliName, + Description: SendEmailActionMeta().Description, + Name: SendEmailActionMeta().Name, + Method: SendEmailActionMeta().Method, + Url: SendEmailActionMeta().URL, + SecurityModel: SendEmailSecurityModel, + // post + Handlers: []gin.HandlerFunc{ + func(m *gin.Context) { + req := SendEmailActionRequest{ + QueryParams: m.Request.URL.Query(), + Headers: m.Request.Header, + GinCtx: m, + } + query := fireback.ExtractQueryDslFromGinContext(m) + fireback.ReadGinRequestBodyAndCastToGoStruct(m, &req.Body, query) + resp, err := SendEmailImpl(req, query) + fireback.WriteActionResponseToGin(m, resp, err) + }, + }, + CliAction: func(c *cli.Context, security *fireback.SecurityModel) error { + query := fireback.CommonCliQueryDSLBuilderAuthorize(c, SendEmailSecurityModel) + req := SendEmailActionRequest{} + resp, err := SendEmailImpl(req, query) + fireback.HandleActionInCli2(c, resp, err, map[string]map[string]string{}) + return nil + }, +} +var SendEmailWithProviderImpl func(c SendEmailWithProviderActionRequest, query fireback.QueryDSL) (*SendEmailWithProviderActionResponse, error) = nil +var SendEmailWithProviderSecurityModel *fireback.SecurityModel = nil + +// This can be both used as cli and http +var SendEmailWithProviderActionDef fireback.Module3Action = fireback.Module3Action{ + // Temporary until fireback code gen is deleted. + Skip: true, + CliName: SendEmailWithProviderActionMeta().CliName, + Description: SendEmailWithProviderActionMeta().Description, + Name: SendEmailWithProviderActionMeta().Name, + Method: SendEmailWithProviderActionMeta().Method, + Url: SendEmailWithProviderActionMeta().URL, + SecurityModel: SendEmailWithProviderSecurityModel, + // post + Handlers: []gin.HandlerFunc{ + func(m *gin.Context) { + req := SendEmailWithProviderActionRequest{ + QueryParams: m.Request.URL.Query(), + Headers: m.Request.Header, + GinCtx: m, + } + query := fireback.ExtractQueryDslFromGinContext(m) + fireback.ReadGinRequestBodyAndCastToGoStruct(m, &req.Body, query) + resp, err := SendEmailWithProviderImpl(req, query) + fireback.WriteActionResponseToGin(m, resp, err) + }, + }, + CliAction: func(c *cli.Context, security *fireback.SecurityModel) error { + query := fireback.CommonCliQueryDSLBuilderAuthorize(c, SendEmailWithProviderSecurityModel) + req := SendEmailWithProviderActionRequest{} + resp, err := SendEmailWithProviderImpl(req, query) + fireback.HandleActionInCli2(c, resp, err, map[string]map[string]string{}) + return nil + }, +} +var GsmSendSmsImpl func(c GsmSendSmsActionRequest, query fireback.QueryDSL) (*GsmSendSmsActionResponse, error) = nil +var GsmSendSmsSecurityModel *fireback.SecurityModel = nil + +// This can be both used as cli and http +var GsmSendSmsActionDef fireback.Module3Action = fireback.Module3Action{ + // Temporary until fireback code gen is deleted. + Skip: true, + CliName: GsmSendSmsActionMeta().CliName, + Description: GsmSendSmsActionMeta().Description, + Name: GsmSendSmsActionMeta().Name, + Method: GsmSendSmsActionMeta().Method, + Url: GsmSendSmsActionMeta().URL, + SecurityModel: GsmSendSmsSecurityModel, + // post + Handlers: []gin.HandlerFunc{ + func(m *gin.Context) { + req := GsmSendSmsActionRequest{ + QueryParams: m.Request.URL.Query(), + Headers: m.Request.Header, + GinCtx: m, + } + query := fireback.ExtractQueryDslFromGinContext(m) + fireback.ReadGinRequestBodyAndCastToGoStruct(m, &req.Body, query) + resp, err := GsmSendSmsImpl(req, query) + fireback.WriteActionResponseToGin(m, resp, err) + }, + }, + CliAction: func(c *cli.Context, security *fireback.SecurityModel) error { + query := fireback.CommonCliQueryDSLBuilderAuthorize(c, GsmSendSmsSecurityModel) + req := GsmSendSmsActionRequest{} + resp, err := GsmSendSmsImpl(req, query) + fireback.HandleActionInCli2(c, resp, err, map[string]map[string]string{}) + return nil + }, +} +var GsmSendSmsWithProviderImpl func(c GsmSendSmsWithProviderActionRequest, query fireback.QueryDSL) (*GsmSendSmsWithProviderActionResponse, error) = nil +var GsmSendSmsWithProviderSecurityModel *fireback.SecurityModel = nil + +// This can be both used as cli and http +var GsmSendSmsWithProviderActionDef fireback.Module3Action = fireback.Module3Action{ + // Temporary until fireback code gen is deleted. + Skip: true, + CliName: GsmSendSmsWithProviderActionMeta().CliName, + Description: GsmSendSmsWithProviderActionMeta().Description, + Name: GsmSendSmsWithProviderActionMeta().Name, + Method: GsmSendSmsWithProviderActionMeta().Method, + Url: GsmSendSmsWithProviderActionMeta().URL, + SecurityModel: GsmSendSmsWithProviderSecurityModel, + // post + Handlers: []gin.HandlerFunc{ + func(m *gin.Context) { + req := GsmSendSmsWithProviderActionRequest{ + QueryParams: m.Request.URL.Query(), + Headers: m.Request.Header, + GinCtx: m, + } + query := fireback.ExtractQueryDslFromGinContext(m) + fireback.ReadGinRequestBodyAndCastToGoStruct(m, &req.Body, query) + resp, err := GsmSendSmsWithProviderImpl(req, query) + fireback.WriteActionResponseToGin(m, resp, err) + }, + }, + CliAction: func(c *cli.Context, security *fireback.SecurityModel) error { + query := fireback.CommonCliQueryDSLBuilderAuthorize(c, GsmSendSmsWithProviderSecurityModel) + req := GsmSendSmsWithProviderActionRequest{} + resp, err := GsmSendSmsWithProviderImpl(req, query) + fireback.HandleActionInCli2(c, resp, err, map[string]map[string]string{}) + return nil + }, +} func AbacCustomActions() []fireback.Module3Action { routes := []fireback.Module3Action{ @@ -1061,109 +824,16 @@ func AbacCustomActions() []fireback.Module3Action { QueryWorkspaceTypesPubliclyActionDef, CheckPassportMethodsActionDef, OsLoginAuthenticateActionDef, + SendEmailActionDef, + SendEmailWithProviderActionDef, + GsmSendSmsActionDef, + GsmSendSmsWithProviderActionDef, /// End for emi actions - { - Method: "POST", - Url: "/email/send", - SecurityModel: SendEmailSecurityModel, - Name: "sendEmail", - Description: "Send a email using default root notification configuration", - Handlers: []gin.HandlerFunc{ - func(c *gin.Context) { - // POST_ONE - post - fireback.HttpPostEntity(c, SendEmailActionFn) - }, - }, - Format: "POST_ONE", - Action: SendEmailActionFn, - ResponseEntity: &SendEmailActionResDto{}, - Out: &fireback.Module3ActionBody{ - Entity: "SendEmailActionResDto", - }, - RequestEntity: &SendEmailActionReqDto{}, - In: &fireback.Module3ActionBody{ - Entity: "SendEmailActionReqDto", - }, - }, - { - Method: "POST", - Url: "/emailProvider/send", - SecurityModel: SendEmailWithProviderSecurityModel, - Name: "sendEmailWithProvider", - Description: "Send a text message using an specific gsm provider", - Handlers: []gin.HandlerFunc{ - func(c *gin.Context) { - // POST_ONE - post - fireback.HttpPostEntity(c, SendEmailWithProviderActionFn) - }, - }, - Format: "POST_ONE", - Action: SendEmailWithProviderActionFn, - ResponseEntity: &SendEmailWithProviderActionResDto{}, - Out: &fireback.Module3ActionBody{ - Entity: "SendEmailWithProviderActionResDto", - }, - RequestEntity: &SendEmailWithProviderActionReqDto{}, - In: &fireback.Module3ActionBody{ - Entity: "SendEmailWithProviderActionReqDto", - }, - }, - { - Method: "POST", - Url: "/gsm/send/sms", - SecurityModel: GsmSendSmsSecurityModel, - Name: "gsmSendSms", - Description: "Send a text message using default root notification configuration", - Handlers: []gin.HandlerFunc{ - func(c *gin.Context) { - // POST_ONE - post - fireback.HttpPostEntity(c, GsmSendSmsActionFn) - }, - }, - Format: "POST_ONE", - Action: GsmSendSmsActionFn, - ResponseEntity: &GsmSendSmsActionResDto{}, - Out: &fireback.Module3ActionBody{ - Entity: "GsmSendSmsActionResDto", - }, - RequestEntity: &GsmSendSmsActionReqDto{}, - In: &fireback.Module3ActionBody{ - Entity: "GsmSendSmsActionReqDto", - }, - }, - { - Method: "POST", - Url: "/gsmProvider/send/sms", - SecurityModel: GsmSendSmsWithProviderSecurityModel, - Name: "gsmSendSmsWithProvider", - Description: "Send a text message using an specific gsm provider", - Handlers: []gin.HandlerFunc{ - func(c *gin.Context) { - // POST_ONE - post - fireback.HttpPostEntity(c, GsmSendSmsWithProviderActionFn) - }, - }, - Format: "POST_ONE", - Action: GsmSendSmsWithProviderActionFn, - ResponseEntity: &GsmSendSmsWithProviderActionResDto{}, - Out: &fireback.Module3ActionBody{ - Entity: "GsmSendSmsWithProviderActionResDto", - }, - RequestEntity: &GsmSendSmsWithProviderActionReqDto{}, - In: &fireback.Module3ActionBody{ - Entity: "GsmSendSmsWithProviderActionReqDto", - }, - }, } return routes } -var AbacCustomActionsCli = []cli.Command{ - SendEmailActionCmd, - SendEmailWithProviderActionCmd, - GsmSendSmsActionCmd, - GsmSendSmsWithProviderActionCmd, -} +var AbacCustomActionsCli = []cli.Command{} // Only to include some headers func AbacJsonInclude() { @@ -1196,10 +866,10 @@ var AbacCliActionsBundle = &fireback.CliActionsBundle{ QueryWorkspaceTypesPubliclyActionDef.ToCli(), CheckPassportMethodsActionDef.ToCli(), OsLoginAuthenticateActionDef.ToCli(), - SendEmailActionCmd, - SendEmailWithProviderActionCmd, - GsmSendSmsActionCmd, - GsmSendSmsWithProviderActionCmd, + SendEmailActionDef.ToCli(), + SendEmailWithProviderActionDef.ToCli(), + GsmSendSmsActionDef.ToCli(), + GsmSendSmsWithProviderActionDef.ToCli(), TimezoneGroupCliFn(), FileCliFn(), TableViewSizingCliFn(), diff --git a/modules/abac/AbacModule3.yml b/modules/abac/AbacModule3.yml index 716448c23..237d0e488 100644 --- a/modules/abac/AbacModule3.yml +++ b/modules/abac/AbacModule3.yml @@ -721,8 +721,8 @@ acts: for them. Useful for desktop applications. out: dto: UserSessionDto -actions: - - name: sendEmail + + - name: SendEmail url: /email/send cliName: email method: post @@ -730,16 +730,18 @@ actions: in: fields: - name: toAddress - validate: required + tags: + validate: required type: string - name: body - validate: required + tags: + validate: required type: string out: fields: - name: queueId type: string - - name: sendEmailWithProvider + - name: SendEmailWithProvider url: /emailProvider/send cliName: emailp method: post @@ -750,16 +752,18 @@ actions: type: one target: EmailProviderEntity - name: toAddress - validate: required + tags: + validate: required type: string - name: body - validate: required + tags: + validate: required type: string out: fields: - name: queueId type: string - - name: gsmSendSms + - name: GsmSendSms url: /gsm/send/sms cliName: sms method: post @@ -767,30 +771,33 @@ actions: in: fields: - name: toNumber - validate: required + tags: + validate: required type: string - name: body - validate: required + tags: + validate: required type: string out: fields: - name: queueId type: string - - name: gsmSendSmsWithProvider + - name: GsmSendSmsWithProvider url: /gsmProvider/send/sms cliName: smsp method: post description: Send a text message using an specific gsm provider in: fields: - - name: gsmProvider - type: one - target: GsmProviderEntity + - name: gsmProviderId + type: string - name: toNumber - validate: required + tags: + validate: required type: string - name: body - validate: required + tags: + validate: required type: string out: fields: diff --git a/modules/abac/EmailProviderEntity.go b/modules/abac/EmailProviderEntity.go index 3ad6aef77..9ae3ae12d 100644 --- a/modules/abac/EmailProviderEntity.go +++ b/modules/abac/EmailProviderEntity.go @@ -17,7 +17,7 @@ const ( GENERAL_SENDER EmailSenderCategory = "GENERAL_SENDER" ) -func SendEmailUsingNotificationConfig(content *EmailMessageContent, sender EmailSenderCategory) (*SendEmailWithProviderActionResDto, *fireback.IError) { +func SendEmailUsingNotificationConfig(content *EmailMessageContent, sender EmailSenderCategory) (*SendEmailWithProviderActionRes, *fireback.IError) { config, err := NotificationConfigActionGetOneByWorkspace(fireback.QueryDSL{WorkspaceId: ROOT_VAR}) @@ -34,7 +34,7 @@ func SendEmailUsingNotificationConfig(content *EmailMessageContent, sender Email log.Default().Println(content.Json()) QueueId := "printed-to-terminal" - return &SendEmailWithProviderActionResDto{QueueId: QueueId}, nil + return &SendEmailWithProviderActionRes{QueueId: QueueId}, nil } else { // @todo: Give the option to set custom senders everywhere @@ -46,7 +46,7 @@ func SendEmailUsingNotificationConfig(content *EmailMessageContent, sender Email if err := SendMail(*content, config.GeneralEmailProvider); err != nil { return nil, fireback.CastToIError(err) } else { - return &SendEmailWithProviderActionResDto{}, nil + return &SendEmailWithProviderActionRes{}, nil } } } diff --git a/modules/abac/GsmProviderEntity.go b/modules/abac/GsmProviderEntity.go index 384630e5c..b95675e0d 100644 --- a/modules/abac/GsmProviderEntity.go +++ b/modules/abac/GsmProviderEntity.go @@ -70,7 +70,7 @@ func GsmProviderActionUpdate( * for example, getting sms template for otp in europe area **/ -func GsmSendSMSUsingNotificationConfig(message string, recp []string) (*GsmSendSmsWithProviderActionResDto, *fireback.IError) { +func GsmSendSMSUsingNotificationConfig(message string, recp []string) (*GsmSendSmsWithProviderActionRes, *fireback.IError) { config, err := NotificationConfigActionGetOneByWorkspace(fireback.QueryDSL{WorkspaceId: ROOT_VAR}) if err != nil { @@ -85,13 +85,13 @@ func GsmSendSMSUsingNotificationConfig(message string, recp []string) (*GsmSendS log.Default().Println(message, recp) terminalQueue := "print-to-terminal" - return &GsmSendSmsWithProviderActionResDto{QueueId: terminalQueue}, nil + return &GsmSendSmsWithProviderActionRes{QueueId: terminalQueue}, nil } return config.GeneralGsmProvider.SendSms(message, recp) } -func GsmSendSMS(providerId string, message string, recp []string) (*GsmSendSmsWithProviderActionResDto, *fireback.IError) { +func GsmSendSMS(providerId string, message string, recp []string) (*GsmSendSmsWithProviderActionRes, *fireback.IError) { if provider, err := GsmProviderActions.GetOne(fireback.QueryDSL{UniqueId: providerId}); err != nil { return nil, err @@ -100,25 +100,25 @@ func GsmSendSMS(providerId string, message string, recp []string) (*GsmSendSmsWi } } -func (x *GsmProviderEntity) SendSms(message string, recp []string) (*GsmSendSmsWithProviderActionResDto, *fireback.IError) { +func (x *GsmProviderEntity) SendSms(message string, recp []string) (*GsmSendSmsWithProviderActionRes, *fireback.IError) { if x.Type == GsmProviderType.Url { if j, err := GsmSendSMSByHttpCall(x, message, recp); err != nil { return nil, err } else { - return &GsmSendSmsWithProviderActionResDto{QueueId: j}, nil + return &GsmSendSmsWithProviderActionRes{QueueId: j}, nil } } else if x.Type == GsmProviderType.Terminal { if j, err := GsmSendSMSByTerminal(x, message, recp); err != nil { return nil, err } else { - return &GsmSendSmsWithProviderActionResDto{QueueId: j}, nil + return &GsmSendSmsWithProviderActionRes{QueueId: j}, nil } } else if x.Type == GsmProviderType.Mediana { if j, err := GsmSendSMSByMediana(x, message, recp); err != nil { return nil, err } else { - return &GsmSendSmsWithProviderActionResDto{QueueId: j}, nil + return &GsmSendSmsWithProviderActionRes{QueueId: j}, nil } } diff --git a/modules/abac/GsmSendSmsAction.dyno.go b/modules/abac/GsmSendSmsAction.dyno.go new file mode 100644 index 000000000..ffb799773 --- /dev/null +++ b/modules/abac/GsmSendSmsAction.dyno.go @@ -0,0 +1,318 @@ +package abac + +import ( + "bytes" + "encoding/json" + "fmt" + "github.com/gin-gonic/gin" + "github.com/torabian/emi/emigo" + "github.com/urfave/cli" + "io" + "net/http" + "net/url" +) + +/** +* Action to communicate with the action GsmSendSmsAction + */ +func GsmSendSmsActionMeta() struct { + Name string + CliName string + URL string + Method string + Description string +} { + return struct { + Name string + CliName string + URL string + Method string + Description string + }{ + Name: "GsmSendSmsAction", + CliName: "sms", + URL: "/gsm/send/sms", + Method: "POST", + Description: `Send a text message using default root notification configuration`, + } +} +func GetGsmSendSmsActionReqCliFlags(prefix string) []emigo.CliFlag { + return []emigo.CliFlag{ + { + Name: prefix + "to-number", + Type: "string", + }, + { + Name: prefix + "body", + Type: "string", + }, + } +} +func CastGsmSendSmsActionReqFromCli(c emigo.CliCastable) GsmSendSmsActionReq { + data := GsmSendSmsActionReq{} + if c.IsSet("to-number") { + data.ToNumber = c.String("to-number") + } + if c.IsSet("body") { + data.Body = c.String("body") + } + return data +} + +// The base class definition for gsmSendSmsActionReq +type GsmSendSmsActionReq struct { + ToNumber string `json:"toNumber" validate:"required" yaml:"toNumber"` + Body string `json:"body" validate:"required" yaml:"body"` +} + +func (x *GsmSendSmsActionReq) Json() string { + if x != nil { + str, _ := json.MarshalIndent(x, "", " ") + return string(str) + } + return "" +} +func GetGsmSendSmsActionResCliFlags(prefix string) []emigo.CliFlag { + return []emigo.CliFlag{ + { + Name: prefix + "queue-id", + Type: "string", + }, + } +} +func CastGsmSendSmsActionResFromCli(c emigo.CliCastable) GsmSendSmsActionRes { + data := GsmSendSmsActionRes{} + if c.IsSet("queue-id") { + data.QueueId = c.String("queue-id") + } + return data +} + +// The base class definition for gsmSendSmsActionRes +type GsmSendSmsActionRes struct { + QueueId string `json:"queueId" yaml:"queueId"` +} + +func (x *GsmSendSmsActionRes) Json() string { + if x != nil { + str, _ := json.MarshalIndent(x, "", " ") + return string(str) + } + return "" +} + +type GsmSendSmsActionResponse struct { + StatusCode int + Headers map[string]string + Payload interface{} +} + +func (x *GsmSendSmsActionResponse) SetContentType(contentType string) *GsmSendSmsActionResponse { + if x.Headers == nil { + x.Headers = make(map[string]string) + } + x.Headers["Content-Type"] = contentType + return x +} +func (x *GsmSendSmsActionResponse) AsStream(r io.Reader, contentType string) *GsmSendSmsActionResponse { + x.Payload = r + x.SetContentType(contentType) + return x +} +func (x *GsmSendSmsActionResponse) AsJSON(payload any) *GsmSendSmsActionResponse { + x.Payload = payload + x.SetContentType("application/json") + return x +} +func (x *GsmSendSmsActionResponse) AsHTML(payload string) *GsmSendSmsActionResponse { + x.Payload = payload + x.SetContentType("text/html; charset=utf-8") + return x +} +func (x *GsmSendSmsActionResponse) AsBytes(payload []byte) *GsmSendSmsActionResponse { + x.Payload = payload + x.SetContentType("application/octet-stream") + return x +} +func (x GsmSendSmsActionResponse) GetStatusCode() int { + return x.StatusCode +} +func (x GsmSendSmsActionResponse) GetRespHeaders() map[string]string { + return x.Headers +} +func (x GsmSendSmsActionResponse) GetPayload() interface{} { + return x.Payload +} + +// GsmSendSmsActionRaw registers a raw Gin route for the GsmSendSmsAction action. +// This gives the developer full control over middleware, handlers, and response handling. +func GsmSendSmsActionRaw(r *gin.Engine, handlers ...gin.HandlerFunc) { + meta := GsmSendSmsActionMeta() + r.Handle(meta.Method, meta.URL, handlers...) +} + +type GsmSendSmsActionRequestSig = func(c GsmSendSmsActionRequest) (*GsmSendSmsActionResponse, error) + +// GsmSendSmsActionHandler returns the HTTP method, route URL, and a typed Gin handler for the GsmSendSmsAction action. +// Developers implement their business logic as a function that receives a typed request object +// and returns either an *ActionResponse or nil. JSON marshalling, headers, and errors are handled automatically. +func GsmSendSmsActionHandler( + handler GsmSendSmsActionRequestSig, +) (method, url string, h gin.HandlerFunc) { + meta := GsmSendSmsActionMeta() + return meta.Method, meta.URL, func(m *gin.Context) { + var body GsmSendSmsActionReq + if err := m.ShouldBindJSON(&body); err != nil { + m.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON: " + err.Error()}) + return + } + // Build typed request wrapper + req := GsmSendSmsActionRequest{ + Body: body, + QueryParams: m.Request.URL.Query(), + Headers: m.Request.Header, + GinCtx: m, + } + resp, err := handler(req) + if err != nil { + m.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + // If the handler returned nil (and no error), it means the response was handled manually. + if resp == nil { + return + } + // Apply headers + for k, v := range resp.Headers { + m.Header(k, v) + } + // Apply status and payload + status := resp.StatusCode + if status == 0 { + status = http.StatusOK + } + if resp.Payload != nil { + m.JSON(status, resp.Payload) + } else { + m.Status(status) + } + } +} + +// GsmSendSmsAction is a high-level convenience wrapper around GsmSendSmsActionHandler. +// It automatically constructs and registers the typed route on the Gin engine. +// Use this when you don't need custom middleware or route grouping. +func GsmSendSmsActionGin(r gin.IRoutes, handler GsmSendSmsActionRequestSig) { + method, url, h := GsmSendSmsActionHandler(handler) + r.Handle(method, url, h) +} + +/** + * Query parameters for GsmSendSmsAction + */ +// Query wrapper with private fields +type GsmSendSmsActionQuery struct { + values url.Values + mapped map[string]interface{} + // Typesafe fields +} + +func GsmSendSmsActionQueryFromString(rawQuery string) GsmSendSmsActionQuery { + v := GsmSendSmsActionQuery{} + values, _ := url.ParseQuery(rawQuery) + mapped := map[string]interface{}{} + if result, err := emigo.UnmarshalQs(rawQuery); err == nil { + mapped = result + } + decoder, err := emigo.NewDecoder(&emigo.DecoderConfig{ + TagName: "json", // reuse json tags + WeaklyTypedInput: true, // "1" -> int, "true" -> bool + Result: &v, + }) + if err == nil { + _ = decoder.Decode(mapped) + } + v.values = values + v.mapped = mapped + return v +} +func GsmSendSmsActionQueryFromGin(c *gin.Context) GsmSendSmsActionQuery { + return GsmSendSmsActionQueryFromString(c.Request.URL.RawQuery) +} +func GsmSendSmsActionQueryFromHttp(r *http.Request) GsmSendSmsActionQuery { + return GsmSendSmsActionQueryFromString(r.URL.RawQuery) +} +func (q GsmSendSmsActionQuery) Values() url.Values { + return q.values +} +func (q GsmSendSmsActionQuery) Mapped() map[string]interface{} { + return q.mapped +} +func (q *GsmSendSmsActionQuery) SetValues(v url.Values) { + q.values = v +} +func (q *GsmSendSmsActionQuery) SetMapped(m map[string]interface{}) { + q.mapped = m +} + +type GsmSendSmsActionRequest struct { + Body GsmSendSmsActionReq + QueryParams url.Values + Headers http.Header + GinCtx *gin.Context + CliCtx *cli.Context +} +type GsmSendSmsActionResult struct { + resp *http.Response // embed original response + Payload interface{} +} + +func GsmSendSmsActionCall( + req GsmSendSmsActionRequest, + config *emigo.APIClient, // optional pre-built request +) (*GsmSendSmsActionResult, error) { + var httpReq *http.Request + if config == nil || config.Httpr == nil { + meta := GsmSendSmsActionMeta() + baseURL := meta.URL + // Build final URL with query string + u, err := url.Parse(baseURL) + if err != nil { + return nil, err + } + // if UrlValues present, encode and append + if len(req.QueryParams) > 0 { + u.RawQuery = req.QueryParams.Encode() + } + bodyBytes, err := json.Marshal(req.Body) + if err != nil { + return nil, err + } + req0, err := http.NewRequest(meta.Method, u.String(), bytes.NewReader(bodyBytes)) + if err != nil { + return nil, err + } + httpReq = req0 + } else { + httpReq = config.Httpr + } + httpReq.Header = req.Headers + resp, err := http.DefaultClient.Do(httpReq) + if err != nil { + return nil, err + } + var result GsmSendSmsActionResult + result.resp = resp + defer resp.Body.Close() + respBody, err := io.ReadAll(resp.Body) + if err != nil { + return &result, err + } + if resp.StatusCode >= 400 { + return &result, fmt.Errorf("request failed: %s", respBody) + } + if err := json.Unmarshal(respBody, &result.Payload); err != nil { + return &result, err + } + return &result, nil +} diff --git a/modules/abac/GsmSendSmsAction.go b/modules/abac/GsmSendSmsAction.go index ac3cf4800..f5650c6a5 100644 --- a/modules/abac/GsmSendSmsAction.go +++ b/modules/abac/GsmSendSmsAction.go @@ -4,19 +4,20 @@ import "github.com/torabian/fireback/modules/fireback" func init() { // Override the implementation with our actual code. - GsmSendSmsActionImp = GsmSendSmsAction -} - -func GsmSendSmsAction(req *GsmSendSmsActionReqDto, q fireback.QueryDSL) (*GsmSendSmsActionResDto, *fireback.IError) { + GsmSendSmsImpl = func(c GsmSendSmsActionRequest, query fireback.QueryDSL) (*GsmSendSmsActionResponse, error) { + req := c.Body - if err := GsmSendSmsActionReqValidator(req); err != nil { - return nil, err - } - if res, err := GsmSendSMSUsingNotificationConfig(req.Body, []string{req.ToNumber}); err != nil { - return nil, err - } else { - return &GsmSendSmsActionResDto{ - QueueId: res.QueueId, - }, nil + if err := fireback.CommonStructValidatorPointer(&req, false); err != nil { + return nil, err + } + if res, err := GsmSendSMSUsingNotificationConfig(req.Body, []string{req.ToNumber}); err != nil { + return nil, err + } else { + return &GsmSendSmsActionResponse{ + Payload: GsmSendSmsActionRes{ + QueueId: res.QueueId, + }, + }, nil + } } } diff --git a/modules/abac/GsmSendSmsWithProviderAction.dyno.go b/modules/abac/GsmSendSmsWithProviderAction.dyno.go new file mode 100644 index 000000000..9e1d6b813 --- /dev/null +++ b/modules/abac/GsmSendSmsWithProviderAction.dyno.go @@ -0,0 +1,326 @@ +package abac + +import ( + "bytes" + "encoding/json" + "fmt" + "github.com/gin-gonic/gin" + "github.com/torabian/emi/emigo" + "github.com/urfave/cli" + "io" + "net/http" + "net/url" +) + +/** +* Action to communicate with the action GsmSendSmsWithProviderAction + */ +func GsmSendSmsWithProviderActionMeta() struct { + Name string + CliName string + URL string + Method string + Description string +} { + return struct { + Name string + CliName string + URL string + Method string + Description string + }{ + Name: "GsmSendSmsWithProviderAction", + CliName: "smsp", + URL: "/gsmProvider/send/sms", + Method: "POST", + Description: `Send a text message using an specific gsm provider`, + } +} +func GetGsmSendSmsWithProviderActionReqCliFlags(prefix string) []emigo.CliFlag { + return []emigo.CliFlag{ + { + Name: prefix + "gsm-provider-id", + Type: "string", + }, + { + Name: prefix + "to-number", + Type: "string", + }, + { + Name: prefix + "body", + Type: "string", + }, + } +} +func CastGsmSendSmsWithProviderActionReqFromCli(c emigo.CliCastable) GsmSendSmsWithProviderActionReq { + data := GsmSendSmsWithProviderActionReq{} + if c.IsSet("gsm-provider-id") { + data.GsmProviderId = c.String("gsm-provider-id") + } + if c.IsSet("to-number") { + data.ToNumber = c.String("to-number") + } + if c.IsSet("body") { + data.Body = c.String("body") + } + return data +} + +// The base class definition for gsmSendSmsWithProviderActionReq +type GsmSendSmsWithProviderActionReq struct { + GsmProviderId string `json:"gsmProviderId" yaml:"gsmProviderId"` + ToNumber string `json:"toNumber" validate:"required" yaml:"toNumber"` + Body string `json:"body" validate:"required" yaml:"body"` +} + +func (x *GsmSendSmsWithProviderActionReq) Json() string { + if x != nil { + str, _ := json.MarshalIndent(x, "", " ") + return string(str) + } + return "" +} +func GetGsmSendSmsWithProviderActionResCliFlags(prefix string) []emigo.CliFlag { + return []emigo.CliFlag{ + { + Name: prefix + "queue-id", + Type: "string", + }, + } +} +func CastGsmSendSmsWithProviderActionResFromCli(c emigo.CliCastable) GsmSendSmsWithProviderActionRes { + data := GsmSendSmsWithProviderActionRes{} + if c.IsSet("queue-id") { + data.QueueId = c.String("queue-id") + } + return data +} + +// The base class definition for gsmSendSmsWithProviderActionRes +type GsmSendSmsWithProviderActionRes struct { + QueueId string `json:"queueId" yaml:"queueId"` +} + +func (x *GsmSendSmsWithProviderActionRes) Json() string { + if x != nil { + str, _ := json.MarshalIndent(x, "", " ") + return string(str) + } + return "" +} + +type GsmSendSmsWithProviderActionResponse struct { + StatusCode int + Headers map[string]string + Payload interface{} +} + +func (x *GsmSendSmsWithProviderActionResponse) SetContentType(contentType string) *GsmSendSmsWithProviderActionResponse { + if x.Headers == nil { + x.Headers = make(map[string]string) + } + x.Headers["Content-Type"] = contentType + return x +} +func (x *GsmSendSmsWithProviderActionResponse) AsStream(r io.Reader, contentType string) *GsmSendSmsWithProviderActionResponse { + x.Payload = r + x.SetContentType(contentType) + return x +} +func (x *GsmSendSmsWithProviderActionResponse) AsJSON(payload any) *GsmSendSmsWithProviderActionResponse { + x.Payload = payload + x.SetContentType("application/json") + return x +} +func (x *GsmSendSmsWithProviderActionResponse) AsHTML(payload string) *GsmSendSmsWithProviderActionResponse { + x.Payload = payload + x.SetContentType("text/html; charset=utf-8") + return x +} +func (x *GsmSendSmsWithProviderActionResponse) AsBytes(payload []byte) *GsmSendSmsWithProviderActionResponse { + x.Payload = payload + x.SetContentType("application/octet-stream") + return x +} +func (x GsmSendSmsWithProviderActionResponse) GetStatusCode() int { + return x.StatusCode +} +func (x GsmSendSmsWithProviderActionResponse) GetRespHeaders() map[string]string { + return x.Headers +} +func (x GsmSendSmsWithProviderActionResponse) GetPayload() interface{} { + return x.Payload +} + +// GsmSendSmsWithProviderActionRaw registers a raw Gin route for the GsmSendSmsWithProviderAction action. +// This gives the developer full control over middleware, handlers, and response handling. +func GsmSendSmsWithProviderActionRaw(r *gin.Engine, handlers ...gin.HandlerFunc) { + meta := GsmSendSmsWithProviderActionMeta() + r.Handle(meta.Method, meta.URL, handlers...) +} + +type GsmSendSmsWithProviderActionRequestSig = func(c GsmSendSmsWithProviderActionRequest) (*GsmSendSmsWithProviderActionResponse, error) + +// GsmSendSmsWithProviderActionHandler returns the HTTP method, route URL, and a typed Gin handler for the GsmSendSmsWithProviderAction action. +// Developers implement their business logic as a function that receives a typed request object +// and returns either an *ActionResponse or nil. JSON marshalling, headers, and errors are handled automatically. +func GsmSendSmsWithProviderActionHandler( + handler GsmSendSmsWithProviderActionRequestSig, +) (method, url string, h gin.HandlerFunc) { + meta := GsmSendSmsWithProviderActionMeta() + return meta.Method, meta.URL, func(m *gin.Context) { + var body GsmSendSmsWithProviderActionReq + if err := m.ShouldBindJSON(&body); err != nil { + m.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON: " + err.Error()}) + return + } + // Build typed request wrapper + req := GsmSendSmsWithProviderActionRequest{ + Body: body, + QueryParams: m.Request.URL.Query(), + Headers: m.Request.Header, + GinCtx: m, + } + resp, err := handler(req) + if err != nil { + m.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + // If the handler returned nil (and no error), it means the response was handled manually. + if resp == nil { + return + } + // Apply headers + for k, v := range resp.Headers { + m.Header(k, v) + } + // Apply status and payload + status := resp.StatusCode + if status == 0 { + status = http.StatusOK + } + if resp.Payload != nil { + m.JSON(status, resp.Payload) + } else { + m.Status(status) + } + } +} + +// GsmSendSmsWithProviderAction is a high-level convenience wrapper around GsmSendSmsWithProviderActionHandler. +// It automatically constructs and registers the typed route on the Gin engine. +// Use this when you don't need custom middleware or route grouping. +func GsmSendSmsWithProviderActionGin(r gin.IRoutes, handler GsmSendSmsWithProviderActionRequestSig) { + method, url, h := GsmSendSmsWithProviderActionHandler(handler) + r.Handle(method, url, h) +} + +/** + * Query parameters for GsmSendSmsWithProviderAction + */ +// Query wrapper with private fields +type GsmSendSmsWithProviderActionQuery struct { + values url.Values + mapped map[string]interface{} + // Typesafe fields +} + +func GsmSendSmsWithProviderActionQueryFromString(rawQuery string) GsmSendSmsWithProviderActionQuery { + v := GsmSendSmsWithProviderActionQuery{} + values, _ := url.ParseQuery(rawQuery) + mapped := map[string]interface{}{} + if result, err := emigo.UnmarshalQs(rawQuery); err == nil { + mapped = result + } + decoder, err := emigo.NewDecoder(&emigo.DecoderConfig{ + TagName: "json", // reuse json tags + WeaklyTypedInput: true, // "1" -> int, "true" -> bool + Result: &v, + }) + if err == nil { + _ = decoder.Decode(mapped) + } + v.values = values + v.mapped = mapped + return v +} +func GsmSendSmsWithProviderActionQueryFromGin(c *gin.Context) GsmSendSmsWithProviderActionQuery { + return GsmSendSmsWithProviderActionQueryFromString(c.Request.URL.RawQuery) +} +func GsmSendSmsWithProviderActionQueryFromHttp(r *http.Request) GsmSendSmsWithProviderActionQuery { + return GsmSendSmsWithProviderActionQueryFromString(r.URL.RawQuery) +} +func (q GsmSendSmsWithProviderActionQuery) Values() url.Values { + return q.values +} +func (q GsmSendSmsWithProviderActionQuery) Mapped() map[string]interface{} { + return q.mapped +} +func (q *GsmSendSmsWithProviderActionQuery) SetValues(v url.Values) { + q.values = v +} +func (q *GsmSendSmsWithProviderActionQuery) SetMapped(m map[string]interface{}) { + q.mapped = m +} + +type GsmSendSmsWithProviderActionRequest struct { + Body GsmSendSmsWithProviderActionReq + QueryParams url.Values + Headers http.Header + GinCtx *gin.Context + CliCtx *cli.Context +} +type GsmSendSmsWithProviderActionResult struct { + resp *http.Response // embed original response + Payload interface{} +} + +func GsmSendSmsWithProviderActionCall( + req GsmSendSmsWithProviderActionRequest, + config *emigo.APIClient, // optional pre-built request +) (*GsmSendSmsWithProviderActionResult, error) { + var httpReq *http.Request + if config == nil || config.Httpr == nil { + meta := GsmSendSmsWithProviderActionMeta() + baseURL := meta.URL + // Build final URL with query string + u, err := url.Parse(baseURL) + if err != nil { + return nil, err + } + // if UrlValues present, encode and append + if len(req.QueryParams) > 0 { + u.RawQuery = req.QueryParams.Encode() + } + bodyBytes, err := json.Marshal(req.Body) + if err != nil { + return nil, err + } + req0, err := http.NewRequest(meta.Method, u.String(), bytes.NewReader(bodyBytes)) + if err != nil { + return nil, err + } + httpReq = req0 + } else { + httpReq = config.Httpr + } + httpReq.Header = req.Headers + resp, err := http.DefaultClient.Do(httpReq) + if err != nil { + return nil, err + } + var result GsmSendSmsWithProviderActionResult + result.resp = resp + defer resp.Body.Close() + respBody, err := io.ReadAll(resp.Body) + if err != nil { + return &result, err + } + if resp.StatusCode >= 400 { + return &result, fmt.Errorf("request failed: %s", respBody) + } + if err := json.Unmarshal(respBody, &result.Payload); err != nil { + return &result, err + } + return &result, nil +} diff --git a/modules/abac/GsmSendSmsWithProviderAction.go b/modules/abac/GsmSendSmsWithProviderAction.go index 6df18511e..81d2802ed 100644 --- a/modules/abac/GsmSendSmsWithProviderAction.go +++ b/modules/abac/GsmSendSmsWithProviderAction.go @@ -4,14 +4,22 @@ import "github.com/torabian/fireback/modules/fireback" func init() { // Override the implementation with our actual code. - GsmSendSmsWithProviderActionImp = GsmSendSmsWithProviderAction + GsmSendSmsWithProviderImpl = GsmSendSmsWithProviderActionfunc } -func GsmSendSmsWithProviderAction(req *GsmSendSmsWithProviderActionReqDto, q fireback.QueryDSL) (*GsmSendSmsWithProviderActionResDto, *fireback.IError) { +func GsmSendSmsWithProviderActionfunc(c GsmSendSmsWithProviderActionRequest, query fireback.QueryDSL) (*GsmSendSmsWithProviderActionResponse, error) { - if err := GsmSendSmsWithProviderActionReqValidator(req); err != nil { + req := c.Body + if err := fireback.CommonStructValidatorPointer(&req, false); err != nil { return nil, err } - return GsmSendSMS(req.GsmProviderId.String, req.Body, []string{req.ToNumber}) + if res, err := GsmSendSMS(req.GsmProviderId, req.Body, []string{req.ToNumber}); err != nil { + return nil, err + } else { + return &GsmSendSmsWithProviderActionResponse{ + Payload: res, + }, nil + } + } diff --git a/modules/abac/InviteToWorkspaceAction.go b/modules/abac/InviteToWorkspaceAction.go index 77992608c..27308bfc5 100644 --- a/modules/abac/InviteToWorkspaceAction.go +++ b/modules/abac/InviteToWorkspaceAction.go @@ -49,9 +49,11 @@ func InviteToWorkspaceAction(c InviteToWorkspaceActionRequest, query fireback.Qu if invite.Phonenumber != "" { inviteBody := "You are invite " + invite.FirstName + " " + invite.LastName - if _, err7 := GsmSendSmsAction(&GsmSendSmsActionReqDto{ - ToNumber: invite.Phonenumber, - Body: inviteBody, + if _, err7 := GsmSendSmsImpl(GsmSendSmsActionRequest{ + Body: GsmSendSmsActionReq{ + ToNumber: invite.Phonenumber, + Body: inviteBody, + }, }, query); err7 != nil { return nil, fireback.GormErrorToIError(err7) } diff --git a/modules/abac/SendEmailAction.dyno.go b/modules/abac/SendEmailAction.dyno.go new file mode 100644 index 000000000..50aaa29fc --- /dev/null +++ b/modules/abac/SendEmailAction.dyno.go @@ -0,0 +1,318 @@ +package abac + +import ( + "bytes" + "encoding/json" + "fmt" + "github.com/gin-gonic/gin" + "github.com/torabian/emi/emigo" + "github.com/urfave/cli" + "io" + "net/http" + "net/url" +) + +/** +* Action to communicate with the action SendEmailAction + */ +func SendEmailActionMeta() struct { + Name string + CliName string + URL string + Method string + Description string +} { + return struct { + Name string + CliName string + URL string + Method string + Description string + }{ + Name: "SendEmailAction", + CliName: "email", + URL: "/email/send", + Method: "POST", + Description: `Send a email using default root notification configuration`, + } +} +func GetSendEmailActionReqCliFlags(prefix string) []emigo.CliFlag { + return []emigo.CliFlag{ + { + Name: prefix + "to-address", + Type: "string", + }, + { + Name: prefix + "body", + Type: "string", + }, + } +} +func CastSendEmailActionReqFromCli(c emigo.CliCastable) SendEmailActionReq { + data := SendEmailActionReq{} + if c.IsSet("to-address") { + data.ToAddress = c.String("to-address") + } + if c.IsSet("body") { + data.Body = c.String("body") + } + return data +} + +// The base class definition for sendEmailActionReq +type SendEmailActionReq struct { + ToAddress string `json:"toAddress" validate:"required" yaml:"toAddress"` + Body string `json:"body" validate:"required" yaml:"body"` +} + +func (x *SendEmailActionReq) Json() string { + if x != nil { + str, _ := json.MarshalIndent(x, "", " ") + return string(str) + } + return "" +} +func GetSendEmailActionResCliFlags(prefix string) []emigo.CliFlag { + return []emigo.CliFlag{ + { + Name: prefix + "queue-id", + Type: "string", + }, + } +} +func CastSendEmailActionResFromCli(c emigo.CliCastable) SendEmailActionRes { + data := SendEmailActionRes{} + if c.IsSet("queue-id") { + data.QueueId = c.String("queue-id") + } + return data +} + +// The base class definition for sendEmailActionRes +type SendEmailActionRes struct { + QueueId string `json:"queueId" yaml:"queueId"` +} + +func (x *SendEmailActionRes) Json() string { + if x != nil { + str, _ := json.MarshalIndent(x, "", " ") + return string(str) + } + return "" +} + +type SendEmailActionResponse struct { + StatusCode int + Headers map[string]string + Payload interface{} +} + +func (x *SendEmailActionResponse) SetContentType(contentType string) *SendEmailActionResponse { + if x.Headers == nil { + x.Headers = make(map[string]string) + } + x.Headers["Content-Type"] = contentType + return x +} +func (x *SendEmailActionResponse) AsStream(r io.Reader, contentType string) *SendEmailActionResponse { + x.Payload = r + x.SetContentType(contentType) + return x +} +func (x *SendEmailActionResponse) AsJSON(payload any) *SendEmailActionResponse { + x.Payload = payload + x.SetContentType("application/json") + return x +} +func (x *SendEmailActionResponse) AsHTML(payload string) *SendEmailActionResponse { + x.Payload = payload + x.SetContentType("text/html; charset=utf-8") + return x +} +func (x *SendEmailActionResponse) AsBytes(payload []byte) *SendEmailActionResponse { + x.Payload = payload + x.SetContentType("application/octet-stream") + return x +} +func (x SendEmailActionResponse) GetStatusCode() int { + return x.StatusCode +} +func (x SendEmailActionResponse) GetRespHeaders() map[string]string { + return x.Headers +} +func (x SendEmailActionResponse) GetPayload() interface{} { + return x.Payload +} + +// SendEmailActionRaw registers a raw Gin route for the SendEmailAction action. +// This gives the developer full control over middleware, handlers, and response handling. +func SendEmailActionRaw(r *gin.Engine, handlers ...gin.HandlerFunc) { + meta := SendEmailActionMeta() + r.Handle(meta.Method, meta.URL, handlers...) +} + +type SendEmailActionRequestSig = func(c SendEmailActionRequest) (*SendEmailActionResponse, error) + +// SendEmailActionHandler returns the HTTP method, route URL, and a typed Gin handler for the SendEmailAction action. +// Developers implement their business logic as a function that receives a typed request object +// and returns either an *ActionResponse or nil. JSON marshalling, headers, and errors are handled automatically. +func SendEmailActionHandler( + handler SendEmailActionRequestSig, +) (method, url string, h gin.HandlerFunc) { + meta := SendEmailActionMeta() + return meta.Method, meta.URL, func(m *gin.Context) { + var body SendEmailActionReq + if err := m.ShouldBindJSON(&body); err != nil { + m.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON: " + err.Error()}) + return + } + // Build typed request wrapper + req := SendEmailActionRequest{ + Body: body, + QueryParams: m.Request.URL.Query(), + Headers: m.Request.Header, + GinCtx: m, + } + resp, err := handler(req) + if err != nil { + m.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + // If the handler returned nil (and no error), it means the response was handled manually. + if resp == nil { + return + } + // Apply headers + for k, v := range resp.Headers { + m.Header(k, v) + } + // Apply status and payload + status := resp.StatusCode + if status == 0 { + status = http.StatusOK + } + if resp.Payload != nil { + m.JSON(status, resp.Payload) + } else { + m.Status(status) + } + } +} + +// SendEmailAction is a high-level convenience wrapper around SendEmailActionHandler. +// It automatically constructs and registers the typed route on the Gin engine. +// Use this when you don't need custom middleware or route grouping. +func SendEmailActionGin(r gin.IRoutes, handler SendEmailActionRequestSig) { + method, url, h := SendEmailActionHandler(handler) + r.Handle(method, url, h) +} + +/** + * Query parameters for SendEmailAction + */ +// Query wrapper with private fields +type SendEmailActionQuery struct { + values url.Values + mapped map[string]interface{} + // Typesafe fields +} + +func SendEmailActionQueryFromString(rawQuery string) SendEmailActionQuery { + v := SendEmailActionQuery{} + values, _ := url.ParseQuery(rawQuery) + mapped := map[string]interface{}{} + if result, err := emigo.UnmarshalQs(rawQuery); err == nil { + mapped = result + } + decoder, err := emigo.NewDecoder(&emigo.DecoderConfig{ + TagName: "json", // reuse json tags + WeaklyTypedInput: true, // "1" -> int, "true" -> bool + Result: &v, + }) + if err == nil { + _ = decoder.Decode(mapped) + } + v.values = values + v.mapped = mapped + return v +} +func SendEmailActionQueryFromGin(c *gin.Context) SendEmailActionQuery { + return SendEmailActionQueryFromString(c.Request.URL.RawQuery) +} +func SendEmailActionQueryFromHttp(r *http.Request) SendEmailActionQuery { + return SendEmailActionQueryFromString(r.URL.RawQuery) +} +func (q SendEmailActionQuery) Values() url.Values { + return q.values +} +func (q SendEmailActionQuery) Mapped() map[string]interface{} { + return q.mapped +} +func (q *SendEmailActionQuery) SetValues(v url.Values) { + q.values = v +} +func (q *SendEmailActionQuery) SetMapped(m map[string]interface{}) { + q.mapped = m +} + +type SendEmailActionRequest struct { + Body SendEmailActionReq + QueryParams url.Values + Headers http.Header + GinCtx *gin.Context + CliCtx *cli.Context +} +type SendEmailActionResult struct { + resp *http.Response // embed original response + Payload interface{} +} + +func SendEmailActionCall( + req SendEmailActionRequest, + config *emigo.APIClient, // optional pre-built request +) (*SendEmailActionResult, error) { + var httpReq *http.Request + if config == nil || config.Httpr == nil { + meta := SendEmailActionMeta() + baseURL := meta.URL + // Build final URL with query string + u, err := url.Parse(baseURL) + if err != nil { + return nil, err + } + // if UrlValues present, encode and append + if len(req.QueryParams) > 0 { + u.RawQuery = req.QueryParams.Encode() + } + bodyBytes, err := json.Marshal(req.Body) + if err != nil { + return nil, err + } + req0, err := http.NewRequest(meta.Method, u.String(), bytes.NewReader(bodyBytes)) + if err != nil { + return nil, err + } + httpReq = req0 + } else { + httpReq = config.Httpr + } + httpReq.Header = req.Headers + resp, err := http.DefaultClient.Do(httpReq) + if err != nil { + return nil, err + } + var result SendEmailActionResult + result.resp = resp + defer resp.Body.Close() + respBody, err := io.ReadAll(resp.Body) + if err != nil { + return &result, err + } + if resp.StatusCode >= 400 { + return &result, fmt.Errorf("request failed: %s", respBody) + } + if err := json.Unmarshal(respBody, &result.Payload); err != nil { + return &result, err + } + return &result, nil +} diff --git a/modules/abac/SendEmailAction.go b/modules/abac/SendEmailAction.go index 2a858241b..148533f7a 100644 --- a/modules/abac/SendEmailAction.go +++ b/modules/abac/SendEmailAction.go @@ -4,13 +4,7 @@ import "github.com/torabian/fireback/modules/fireback" func init() { // Override the implementation with our actual code. - SendEmailActionImp = SendEmailAction -} -func SendEmailAction( - req *SendEmailActionReqDto, - q fireback.QueryDSL) (*SendEmailActionResDto, - *fireback.IError, -) { - // Implement the logic here. - return nil, nil + SendEmailImpl = func(c SendEmailActionRequest, query fireback.QueryDSL) (*SendEmailActionResponse, error) { + return nil, nil + } } diff --git a/modules/abac/SendEmailWithProviderAction.dyno.go b/modules/abac/SendEmailWithProviderAction.dyno.go new file mode 100644 index 000000000..6caec5061 --- /dev/null +++ b/modules/abac/SendEmailWithProviderAction.dyno.go @@ -0,0 +1,323 @@ +package abac + +import ( + "bytes" + "encoding/json" + "fmt" + "github.com/gin-gonic/gin" + "github.com/torabian/emi/emigo" + "github.com/urfave/cli" + "io" + "net/http" + "net/url" +) + +/** +* Action to communicate with the action SendEmailWithProviderAction + */ +func SendEmailWithProviderActionMeta() struct { + Name string + CliName string + URL string + Method string + Description string +} { + return struct { + Name string + CliName string + URL string + Method string + Description string + }{ + Name: "SendEmailWithProviderAction", + CliName: "emailp", + URL: "/emailProvider/send", + Method: "POST", + Description: `Send a text message using an specific gsm provider`, + } +} +func GetSendEmailWithProviderActionReqCliFlags(prefix string) []emigo.CliFlag { + return []emigo.CliFlag{ + { + Name: prefix + "email-provider", + Type: "one", + }, + { + Name: prefix + "to-address", + Type: "string", + }, + { + Name: prefix + "body", + Type: "string", + }, + } +} +func CastSendEmailWithProviderActionReqFromCli(c emigo.CliCastable) SendEmailWithProviderActionReq { + data := SendEmailWithProviderActionReq{} + if c.IsSet("to-address") { + data.ToAddress = c.String("to-address") + } + if c.IsSet("body") { + data.Body = c.String("body") + } + return data +} + +// The base class definition for sendEmailWithProviderActionReq +type SendEmailWithProviderActionReq struct { + EmailProvider EmailProviderEntity `json:"emailProvider" yaml:"emailProvider"` + ToAddress string `json:"toAddress" validate:"required" yaml:"toAddress"` + Body string `json:"body" validate:"required" yaml:"body"` +} + +func (x *SendEmailWithProviderActionReq) Json() string { + if x != nil { + str, _ := json.MarshalIndent(x, "", " ") + return string(str) + } + return "" +} +func GetSendEmailWithProviderActionResCliFlags(prefix string) []emigo.CliFlag { + return []emigo.CliFlag{ + { + Name: prefix + "queue-id", + Type: "string", + }, + } +} +func CastSendEmailWithProviderActionResFromCli(c emigo.CliCastable) SendEmailWithProviderActionRes { + data := SendEmailWithProviderActionRes{} + if c.IsSet("queue-id") { + data.QueueId = c.String("queue-id") + } + return data +} + +// The base class definition for sendEmailWithProviderActionRes +type SendEmailWithProviderActionRes struct { + QueueId string `json:"queueId" yaml:"queueId"` +} + +func (x *SendEmailWithProviderActionRes) Json() string { + if x != nil { + str, _ := json.MarshalIndent(x, "", " ") + return string(str) + } + return "" +} + +type SendEmailWithProviderActionResponse struct { + StatusCode int + Headers map[string]string + Payload interface{} +} + +func (x *SendEmailWithProviderActionResponse) SetContentType(contentType string) *SendEmailWithProviderActionResponse { + if x.Headers == nil { + x.Headers = make(map[string]string) + } + x.Headers["Content-Type"] = contentType + return x +} +func (x *SendEmailWithProviderActionResponse) AsStream(r io.Reader, contentType string) *SendEmailWithProviderActionResponse { + x.Payload = r + x.SetContentType(contentType) + return x +} +func (x *SendEmailWithProviderActionResponse) AsJSON(payload any) *SendEmailWithProviderActionResponse { + x.Payload = payload + x.SetContentType("application/json") + return x +} +func (x *SendEmailWithProviderActionResponse) AsHTML(payload string) *SendEmailWithProviderActionResponse { + x.Payload = payload + x.SetContentType("text/html; charset=utf-8") + return x +} +func (x *SendEmailWithProviderActionResponse) AsBytes(payload []byte) *SendEmailWithProviderActionResponse { + x.Payload = payload + x.SetContentType("application/octet-stream") + return x +} +func (x SendEmailWithProviderActionResponse) GetStatusCode() int { + return x.StatusCode +} +func (x SendEmailWithProviderActionResponse) GetRespHeaders() map[string]string { + return x.Headers +} +func (x SendEmailWithProviderActionResponse) GetPayload() interface{} { + return x.Payload +} + +// SendEmailWithProviderActionRaw registers a raw Gin route for the SendEmailWithProviderAction action. +// This gives the developer full control over middleware, handlers, and response handling. +func SendEmailWithProviderActionRaw(r *gin.Engine, handlers ...gin.HandlerFunc) { + meta := SendEmailWithProviderActionMeta() + r.Handle(meta.Method, meta.URL, handlers...) +} + +type SendEmailWithProviderActionRequestSig = func(c SendEmailWithProviderActionRequest) (*SendEmailWithProviderActionResponse, error) + +// SendEmailWithProviderActionHandler returns the HTTP method, route URL, and a typed Gin handler for the SendEmailWithProviderAction action. +// Developers implement their business logic as a function that receives a typed request object +// and returns either an *ActionResponse or nil. JSON marshalling, headers, and errors are handled automatically. +func SendEmailWithProviderActionHandler( + handler SendEmailWithProviderActionRequestSig, +) (method, url string, h gin.HandlerFunc) { + meta := SendEmailWithProviderActionMeta() + return meta.Method, meta.URL, func(m *gin.Context) { + var body SendEmailWithProviderActionReq + if err := m.ShouldBindJSON(&body); err != nil { + m.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON: " + err.Error()}) + return + } + // Build typed request wrapper + req := SendEmailWithProviderActionRequest{ + Body: body, + QueryParams: m.Request.URL.Query(), + Headers: m.Request.Header, + GinCtx: m, + } + resp, err := handler(req) + if err != nil { + m.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + // If the handler returned nil (and no error), it means the response was handled manually. + if resp == nil { + return + } + // Apply headers + for k, v := range resp.Headers { + m.Header(k, v) + } + // Apply status and payload + status := resp.StatusCode + if status == 0 { + status = http.StatusOK + } + if resp.Payload != nil { + m.JSON(status, resp.Payload) + } else { + m.Status(status) + } + } +} + +// SendEmailWithProviderAction is a high-level convenience wrapper around SendEmailWithProviderActionHandler. +// It automatically constructs and registers the typed route on the Gin engine. +// Use this when you don't need custom middleware or route grouping. +func SendEmailWithProviderActionGin(r gin.IRoutes, handler SendEmailWithProviderActionRequestSig) { + method, url, h := SendEmailWithProviderActionHandler(handler) + r.Handle(method, url, h) +} + +/** + * Query parameters for SendEmailWithProviderAction + */ +// Query wrapper with private fields +type SendEmailWithProviderActionQuery struct { + values url.Values + mapped map[string]interface{} + // Typesafe fields +} + +func SendEmailWithProviderActionQueryFromString(rawQuery string) SendEmailWithProviderActionQuery { + v := SendEmailWithProviderActionQuery{} + values, _ := url.ParseQuery(rawQuery) + mapped := map[string]interface{}{} + if result, err := emigo.UnmarshalQs(rawQuery); err == nil { + mapped = result + } + decoder, err := emigo.NewDecoder(&emigo.DecoderConfig{ + TagName: "json", // reuse json tags + WeaklyTypedInput: true, // "1" -> int, "true" -> bool + Result: &v, + }) + if err == nil { + _ = decoder.Decode(mapped) + } + v.values = values + v.mapped = mapped + return v +} +func SendEmailWithProviderActionQueryFromGin(c *gin.Context) SendEmailWithProviderActionQuery { + return SendEmailWithProviderActionQueryFromString(c.Request.URL.RawQuery) +} +func SendEmailWithProviderActionQueryFromHttp(r *http.Request) SendEmailWithProviderActionQuery { + return SendEmailWithProviderActionQueryFromString(r.URL.RawQuery) +} +func (q SendEmailWithProviderActionQuery) Values() url.Values { + return q.values +} +func (q SendEmailWithProviderActionQuery) Mapped() map[string]interface{} { + return q.mapped +} +func (q *SendEmailWithProviderActionQuery) SetValues(v url.Values) { + q.values = v +} +func (q *SendEmailWithProviderActionQuery) SetMapped(m map[string]interface{}) { + q.mapped = m +} + +type SendEmailWithProviderActionRequest struct { + Body SendEmailWithProviderActionReq + QueryParams url.Values + Headers http.Header + GinCtx *gin.Context + CliCtx *cli.Context +} +type SendEmailWithProviderActionResult struct { + resp *http.Response // embed original response + Payload interface{} +} + +func SendEmailWithProviderActionCall( + req SendEmailWithProviderActionRequest, + config *emigo.APIClient, // optional pre-built request +) (*SendEmailWithProviderActionResult, error) { + var httpReq *http.Request + if config == nil || config.Httpr == nil { + meta := SendEmailWithProviderActionMeta() + baseURL := meta.URL + // Build final URL with query string + u, err := url.Parse(baseURL) + if err != nil { + return nil, err + } + // if UrlValues present, encode and append + if len(req.QueryParams) > 0 { + u.RawQuery = req.QueryParams.Encode() + } + bodyBytes, err := json.Marshal(req.Body) + if err != nil { + return nil, err + } + req0, err := http.NewRequest(meta.Method, u.String(), bytes.NewReader(bodyBytes)) + if err != nil { + return nil, err + } + httpReq = req0 + } else { + httpReq = config.Httpr + } + httpReq.Header = req.Headers + resp, err := http.DefaultClient.Do(httpReq) + if err != nil { + return nil, err + } + var result SendEmailWithProviderActionResult + result.resp = resp + defer resp.Body.Close() + respBody, err := io.ReadAll(resp.Body) + if err != nil { + return &result, err + } + if resp.StatusCode >= 400 { + return &result, fmt.Errorf("request failed: %s", respBody) + } + if err := json.Unmarshal(respBody, &result.Payload); err != nil { + return &result, err + } + return &result, nil +} diff --git a/modules/abac/SendEmailWithProviderAction.go b/modules/abac/SendEmailWithProviderAction.go index a8d7afe45..d67924b86 100644 --- a/modules/abac/SendEmailWithProviderAction.go +++ b/modules/abac/SendEmailWithProviderAction.go @@ -4,13 +4,7 @@ import "github.com/torabian/fireback/modules/fireback" func init() { // Override the implementation with our actual code. - SendEmailWithProviderActionImp = SendEmailWithProviderAction -} -func SendEmailWithProviderAction( - req *SendEmailWithProviderActionReqDto, - q fireback.QueryDSL) (*SendEmailWithProviderActionResDto, - *fireback.IError, -) { - // Implement the logic here. - return nil, nil + SendEmailWithProviderImpl = func(c SendEmailWithProviderActionRequest, query fireback.QueryDSL) (*SendEmailWithProviderActionResponse, error) { + return nil, nil + } } From 5508bd62d3ad95c491b915af79ef26e628483185 Mon Sep 17 00:00:00 2001 From: Ali Date: Wed, 15 Apr 2026 20:13:23 +0200 Subject: [PATCH 4/4] Cleanup --- .../src/sdk/modules/abac/AbacActionsDto.ts | 81 --- .../src/sdk/modules/abac/GsmSendSms.ts | 437 +++++++++++++++ .../modules/abac/GsmSendSmsWithProvider.ts | 495 +++++++++++++++++ .../src/sdk/modules/abac/SendEmail.ts | 436 +++++++++++++++ .../sdk/modules/abac/SendEmailWithProvider.ts | 511 ++++++++++++++++++ .../modules/abac/usePostEmailProviderSend.ts | 92 ---- .../src/sdk/modules/abac/usePostEmailSend.ts | 92 ---- .../modules/abac/usePostGsmProviderSendSms.ts | 92 ---- .../src/sdk/modules/abac/usePostGsmSendSms.ts | 92 ---- .../sdk/modules/abac/AbacActionsDto.ts | 81 --- .../fireback/sdk/modules/abac/GsmSendSms.ts | 437 +++++++++++++++ .../modules/abac/GsmSendSmsWithProvider.ts | 495 +++++++++++++++++ .../fireback/sdk/modules/abac/SendEmail.ts | 436 +++++++++++++++ .../sdk/modules/abac/SendEmailWithProvider.ts | 511 ++++++++++++++++++ .../modules/abac/usePostEmailProviderSend.ts | 92 ---- .../sdk/modules/abac/usePostEmailSend.ts | 92 ---- .../modules/abac/usePostGsmProviderSendSms.ts | 92 ---- .../sdk/modules/abac/usePostGsmSendSms.ts | 92 ---- 18 files changed, 3758 insertions(+), 898 deletions(-) delete mode 100644 e2e/react-bed/src/sdk/modules/abac/AbacActionsDto.ts create mode 100644 e2e/react-bed/src/sdk/modules/abac/GsmSendSms.ts create mode 100644 e2e/react-bed/src/sdk/modules/abac/GsmSendSmsWithProvider.ts create mode 100644 e2e/react-bed/src/sdk/modules/abac/SendEmail.ts create mode 100644 e2e/react-bed/src/sdk/modules/abac/SendEmailWithProvider.ts delete mode 100644 e2e/react-bed/src/sdk/modules/abac/usePostEmailProviderSend.ts delete mode 100644 e2e/react-bed/src/sdk/modules/abac/usePostEmailSend.ts delete mode 100644 e2e/react-bed/src/sdk/modules/abac/usePostGsmProviderSendSms.ts delete mode 100644 e2e/react-bed/src/sdk/modules/abac/usePostGsmSendSms.ts delete mode 100644 modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/AbacActionsDto.ts create mode 100644 modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/GsmSendSms.ts create mode 100644 modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/GsmSendSmsWithProvider.ts create mode 100644 modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/SendEmail.ts create mode 100644 modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/SendEmailWithProvider.ts delete mode 100644 modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/usePostEmailProviderSend.ts delete mode 100644 modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/usePostEmailSend.ts delete mode 100644 modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/usePostGsmProviderSendSms.ts delete mode 100644 modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/usePostGsmSendSms.ts diff --git a/e2e/react-bed/src/sdk/modules/abac/AbacActionsDto.ts b/e2e/react-bed/src/sdk/modules/abac/AbacActionsDto.ts deleted file mode 100644 index c77cfb7e5..000000000 --- a/e2e/react-bed/src/sdk/modules/abac/AbacActionsDto.ts +++ /dev/null @@ -1,81 +0,0 @@ -/* -* Generated by fireback 1.2.5 -* Written by Ali Torabi. -* Checkout the repository for licenses and contribution: https://github.com/torabian/fireback -*/ -import { - BaseDto, - BaseEntity, -} from "../../core/definitions" -import { - EmailProviderEntity, -} from "./EmailProviderEntity" -import { - GsmProviderEntity, -} from "./GsmProviderEntity" -export class SendEmailActionReqDto { - public toAddress?: string | null; - public body?: string | null; -public static Fields = { - toAddress: 'toAddress', - body: 'body', -} -} -export class SendEmailActionResDto { - public queueId?: string | null; -public static Fields = { - queueId: 'queueId', -} -} -export class SendEmailWithProviderActionReqDto { - public emailProvider?: EmailProviderEntity | null; - emailProviderId?: string | null; - public toAddress?: string | null; - public body?: string | null; -public static Fields = { - emailProviderId: 'emailProviderId', - emailProvider$: 'emailProvider', - emailProvider: EmailProviderEntity.Fields, - toAddress: 'toAddress', - body: 'body', -} -} -export class SendEmailWithProviderActionResDto { - public queueId?: string | null; -public static Fields = { - queueId: 'queueId', -} -} -export class GsmSendSmsActionReqDto { - public toNumber?: string | null; - public body?: string | null; -public static Fields = { - toNumber: 'toNumber', - body: 'body', -} -} -export class GsmSendSmsActionResDto { - public queueId?: string | null; -public static Fields = { - queueId: 'queueId', -} -} -export class GsmSendSmsWithProviderActionReqDto { - public gsmProvider?: GsmProviderEntity | null; - gsmProviderId?: string | null; - public toNumber?: string | null; - public body?: string | null; -public static Fields = { - gsmProviderId: 'gsmProviderId', - gsmProvider$: 'gsmProvider', - gsmProvider: GsmProviderEntity.Fields, - toNumber: 'toNumber', - body: 'body', -} -} -export class GsmSendSmsWithProviderActionResDto { - public queueId?: string | null; -public static Fields = { - queueId: 'queueId', -} -} \ No newline at end of file diff --git a/e2e/react-bed/src/sdk/modules/abac/GsmSendSms.ts b/e2e/react-bed/src/sdk/modules/abac/GsmSendSms.ts new file mode 100644 index 000000000..35bf0c176 --- /dev/null +++ b/e2e/react-bed/src/sdk/modules/abac/GsmSendSms.ts @@ -0,0 +1,437 @@ +import { buildUrl } from "../../sdk/common/buildUrl"; +import { + fetchx, + handleFetchResponse, + type FetchxContext, + type PartialDeep, + type TypedRequestInit, + type TypedResponse, +} from "../../sdk/common/fetchx"; +import { type UseMutationOptions, useMutation } from "react-query"; +import { useFetchxContext } from "../../sdk/react/useFetchx"; +import { useState } from "react"; +/** + * Action to communicate with the action GsmSendSms + */ +export type GsmSendSmsActionOptions = { + queryKey?: unknown[]; + qs?: URLSearchParams; +}; +export type GsmSendSmsActionMutationOptions = Omit< + UseMutationOptions, + "mutationFn" +> & + GsmSendSmsActionOptions & { + ctx?: FetchxContext; + onMessage?: (ev: MessageEvent) => void; + overrideUrl?: string; + headers?: Headers; + } & Partial<{ + creatorFn: (item: unknown) => GsmSendSmsActionRes; + }>; +export const useGsmSendSmsAction = ( + options?: GsmSendSmsActionMutationOptions, +) => { + const globalCtx = useFetchxContext(); + const ctx = options?.ctx ?? globalCtx ?? undefined; + const [isCompleted, setCompleteState] = useState(false); + const [response, setResponse] = useState>(); + const fn = (body: GsmSendSmsActionReq) => { + setCompleteState(false); + return GsmSendSmsAction.Fetch( + { + body, + headers: options?.headers, + }, + { + creatorFn: options?.creatorFn, + qs: options?.qs, + ctx, + onMessage: options?.onMessage, + overrideUrl: options?.overrideUrl, + }, + ).then((x) => { + x.done.then(() => { + setCompleteState(true); + }); + setResponse(x.response); + return x.response.result; + }); + }; + const result = useMutation({ + mutationFn: fn, + ...(options || {}), + }); + return { + ...result, + isCompleted, + response, + }; +}; +/** + * GsmSendSmsAction + */ +export class GsmSendSmsAction { + // + static URL = "/gsm/send/sms"; + static NewUrl = (qs?: URLSearchParams) => + buildUrl(GsmSendSmsAction.URL, undefined, qs); + static Method = "post"; + static Fetch$ = async ( + qs?: URLSearchParams, + ctx?: FetchxContext, + init?: TypedRequestInit, + overrideUrl?: string, + ) => { + return fetchx( + overrideUrl ?? GsmSendSmsAction.NewUrl(qs), + { + method: GsmSendSmsAction.Method, + ...(init || {}), + }, + ctx, + ); + }; + static Fetch = async ( + init?: TypedRequestInit, + { + creatorFn, + qs, + ctx, + onMessage, + overrideUrl, + }: { + creatorFn?: ((item: unknown) => GsmSendSmsActionRes) | undefined; + qs?: URLSearchParams; + ctx?: FetchxContext; + onMessage?: (ev: MessageEvent) => void; + overrideUrl?: string; + } = { + creatorFn: (item) => new GsmSendSmsActionRes(item), + }, + ) => { + creatorFn = creatorFn || ((item) => new GsmSendSmsActionRes(item)); + const res = await GsmSendSmsAction.Fetch$(qs, ctx, init, overrideUrl); + return handleFetchResponse( + res, + (item) => (creatorFn ? creatorFn(item) : item), + onMessage, + init?.signal, + ); + }; + static Definition = { + name: "GsmSendSms", + cliName: "sms", + url: "/gsm/send/sms", + method: "post", + description: + "Send a text message using default root notification configuration", + in: { + fields: [ + { + name: "toNumber", + type: "string", + tags: { + validate: "required", + }, + }, + { + name: "body", + type: "string", + tags: { + validate: "required", + }, + }, + ], + }, + out: { + fields: [ + { + name: "queueId", + type: "string", + }, + ], + }, + }; +} +/** + * The base class definition for gsmSendSmsActionReq + **/ +export class GsmSendSmsActionReq { + /** + * + * @type {string} + **/ + #toNumber: string = ""; + /** + * + * @returns {string} + **/ + get toNumber() { + return this.#toNumber; + } + /** + * + * @type {string} + **/ + set toNumber(value: string) { + this.#toNumber = String(value); + } + setToNumber(value: string) { + this.toNumber = value; + return this; + } + /** + * + * @type {string} + **/ + #body: string = ""; + /** + * + * @returns {string} + **/ + get body() { + return this.#body; + } + /** + * + * @type {string} + **/ + set body(value: string) { + this.#body = String(value); + } + setBody(value: string) { + this.body = value; + return this; + } + constructor(data: unknown = undefined) { + if (data === null || data === undefined) { + return; + } + if (typeof data === "string") { + this.applyFromObject(JSON.parse(data)); + } else if (this.#isJsonAppliable(data)) { + this.applyFromObject(data); + } else { + throw new Error( + "Instance cannot be created on an unknown value, check the content being passed. got: " + + typeof data, + ); + } + } + #isJsonAppliable(obj: unknown) { + const g = globalThis as unknown as { Buffer: any; Blob: any }; + const isBuffer = + typeof g.Buffer !== "undefined" && + typeof g.Buffer.isBuffer === "function" && + g.Buffer.isBuffer(obj); + const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; + return ( + obj && + typeof obj === "object" && + !Array.isArray(obj) && + !isBuffer && + !(obj instanceof ArrayBuffer) && + !isBlob + ); + } + /** + * casts the fields of a javascript object into the class properties one by one + **/ + applyFromObject(data = {}) { + const d = data as Partial; + if (d.toNumber !== undefined) { + this.toNumber = d.toNumber; + } + if (d.body !== undefined) { + this.body = d.body; + } + } + /** + * Special toJSON override, since the field are private, + * Json stringify won't see them unless we mention it explicitly. + **/ + toJSON() { + return { + toNumber: this.#toNumber, + body: this.#body, + }; + } + toString() { + return JSON.stringify(this); + } + static get Fields() { + return { + toNumber: "toNumber", + body: "body", + }; + } + /** + * Creates an instance of GsmSendSmsActionReq, and possibleDtoObject + * needs to satisfy the type requirement fully, otherwise typescript compile would + * be complaining. + **/ + static from(possibleDtoObject: GsmSendSmsActionReqType) { + return new GsmSendSmsActionReq(possibleDtoObject); + } + /** + * Creates an instance of GsmSendSmsActionReq, and partialDtoObject + * needs to satisfy the type, but partially, and rest of the content would + * be constructed according to data types and nullability. + **/ + static with(partialDtoObject: PartialDeep) { + return new GsmSendSmsActionReq(partialDtoObject); + } + copyWith( + partial: PartialDeep, + ): InstanceType { + return new GsmSendSmsActionReq({ ...this.toJSON(), ...partial }); + } + clone(): InstanceType { + return new GsmSendSmsActionReq(this.toJSON()); + } +} +export abstract class GsmSendSmsActionReqFactory { + abstract create(data: unknown): GsmSendSmsActionReq; +} +/** + * The base type definition for gsmSendSmsActionReq + **/ +export type GsmSendSmsActionReqType = { + /** + * + * @type {string} + **/ + toNumber: string; + /** + * + * @type {string} + **/ + body: string; +}; +// eslint-disable-next-line @typescript-eslint/no-namespace +export namespace GsmSendSmsActionReqType {} +/** + * The base class definition for gsmSendSmsActionRes + **/ +export class GsmSendSmsActionRes { + /** + * + * @type {string} + **/ + #queueId: string = ""; + /** + * + * @returns {string} + **/ + get queueId() { + return this.#queueId; + } + /** + * + * @type {string} + **/ + set queueId(value: string) { + this.#queueId = String(value); + } + setQueueId(value: string) { + this.queueId = value; + return this; + } + constructor(data: unknown = undefined) { + if (data === null || data === undefined) { + return; + } + if (typeof data === "string") { + this.applyFromObject(JSON.parse(data)); + } else if (this.#isJsonAppliable(data)) { + this.applyFromObject(data); + } else { + throw new Error( + "Instance cannot be created on an unknown value, check the content being passed. got: " + + typeof data, + ); + } + } + #isJsonAppliable(obj: unknown) { + const g = globalThis as unknown as { Buffer: any; Blob: any }; + const isBuffer = + typeof g.Buffer !== "undefined" && + typeof g.Buffer.isBuffer === "function" && + g.Buffer.isBuffer(obj); + const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; + return ( + obj && + typeof obj === "object" && + !Array.isArray(obj) && + !isBuffer && + !(obj instanceof ArrayBuffer) && + !isBlob + ); + } + /** + * casts the fields of a javascript object into the class properties one by one + **/ + applyFromObject(data = {}) { + const d = data as Partial; + if (d.queueId !== undefined) { + this.queueId = d.queueId; + } + } + /** + * Special toJSON override, since the field are private, + * Json stringify won't see them unless we mention it explicitly. + **/ + toJSON() { + return { + queueId: this.#queueId, + }; + } + toString() { + return JSON.stringify(this); + } + static get Fields() { + return { + queueId: "queueId", + }; + } + /** + * Creates an instance of GsmSendSmsActionRes, and possibleDtoObject + * needs to satisfy the type requirement fully, otherwise typescript compile would + * be complaining. + **/ + static from(possibleDtoObject: GsmSendSmsActionResType) { + return new GsmSendSmsActionRes(possibleDtoObject); + } + /** + * Creates an instance of GsmSendSmsActionRes, and partialDtoObject + * needs to satisfy the type, but partially, and rest of the content would + * be constructed according to data types and nullability. + **/ + static with(partialDtoObject: PartialDeep) { + return new GsmSendSmsActionRes(partialDtoObject); + } + copyWith( + partial: PartialDeep, + ): InstanceType { + return new GsmSendSmsActionRes({ ...this.toJSON(), ...partial }); + } + clone(): InstanceType { + return new GsmSendSmsActionRes(this.toJSON()); + } +} +export abstract class GsmSendSmsActionResFactory { + abstract create(data: unknown): GsmSendSmsActionRes; +} +/** + * The base type definition for gsmSendSmsActionRes + **/ +export type GsmSendSmsActionResType = { + /** + * + * @type {string} + **/ + queueId: string; +}; +// eslint-disable-next-line @typescript-eslint/no-namespace +export namespace GsmSendSmsActionResType {} diff --git a/e2e/react-bed/src/sdk/modules/abac/GsmSendSmsWithProvider.ts b/e2e/react-bed/src/sdk/modules/abac/GsmSendSmsWithProvider.ts new file mode 100644 index 000000000..27929614c --- /dev/null +++ b/e2e/react-bed/src/sdk/modules/abac/GsmSendSmsWithProvider.ts @@ -0,0 +1,495 @@ +import { buildUrl } from "../../sdk/common/buildUrl"; +import { + fetchx, + handleFetchResponse, + type FetchxContext, + type PartialDeep, + type TypedRequestInit, + type TypedResponse, +} from "../../sdk/common/fetchx"; +import { type UseMutationOptions, useMutation } from "react-query"; +import { useFetchxContext } from "../../sdk/react/useFetchx"; +import { useState } from "react"; +/** + * Action to communicate with the action GsmSendSmsWithProvider + */ +export type GsmSendSmsWithProviderActionOptions = { + queryKey?: unknown[]; + qs?: URLSearchParams; +}; +export type GsmSendSmsWithProviderActionMutationOptions = Omit< + UseMutationOptions, + "mutationFn" +> & + GsmSendSmsWithProviderActionOptions & { + ctx?: FetchxContext; + onMessage?: (ev: MessageEvent) => void; + overrideUrl?: string; + headers?: Headers; + } & Partial<{ + creatorFn: (item: unknown) => GsmSendSmsWithProviderActionRes; + }>; +export const useGsmSendSmsWithProviderAction = ( + options?: GsmSendSmsWithProviderActionMutationOptions, +) => { + const globalCtx = useFetchxContext(); + const ctx = options?.ctx ?? globalCtx ?? undefined; + const [isCompleted, setCompleteState] = useState(false); + const [response, setResponse] = useState>(); + const fn = (body: GsmSendSmsWithProviderActionReq) => { + setCompleteState(false); + return GsmSendSmsWithProviderAction.Fetch( + { + body, + headers: options?.headers, + }, + { + creatorFn: options?.creatorFn, + qs: options?.qs, + ctx, + onMessage: options?.onMessage, + overrideUrl: options?.overrideUrl, + }, + ).then((x) => { + x.done.then(() => { + setCompleteState(true); + }); + setResponse(x.response); + return x.response.result; + }); + }; + const result = useMutation({ + mutationFn: fn, + ...(options || {}), + }); + return { + ...result, + isCompleted, + response, + }; +}; +/** + * GsmSendSmsWithProviderAction + */ +export class GsmSendSmsWithProviderAction { + // + static URL = "/gsmProvider/send/sms"; + static NewUrl = (qs?: URLSearchParams) => + buildUrl(GsmSendSmsWithProviderAction.URL, undefined, qs); + static Method = "post"; + static Fetch$ = async ( + qs?: URLSearchParams, + ctx?: FetchxContext, + init?: TypedRequestInit, + overrideUrl?: string, + ) => { + return fetchx< + GsmSendSmsWithProviderActionRes, + GsmSendSmsWithProviderActionReq, + unknown + >( + overrideUrl ?? GsmSendSmsWithProviderAction.NewUrl(qs), + { + method: GsmSendSmsWithProviderAction.Method, + ...(init || {}), + }, + ctx, + ); + }; + static Fetch = async ( + init?: TypedRequestInit, + { + creatorFn, + qs, + ctx, + onMessage, + overrideUrl, + }: { + creatorFn?: + | ((item: unknown) => GsmSendSmsWithProviderActionRes) + | undefined; + qs?: URLSearchParams; + ctx?: FetchxContext; + onMessage?: (ev: MessageEvent) => void; + overrideUrl?: string; + } = { + creatorFn: (item) => new GsmSendSmsWithProviderActionRes(item), + }, + ) => { + creatorFn = + creatorFn || ((item) => new GsmSendSmsWithProviderActionRes(item)); + const res = await GsmSendSmsWithProviderAction.Fetch$( + qs, + ctx, + init, + overrideUrl, + ); + return handleFetchResponse( + res, + (item) => (creatorFn ? creatorFn(item) : item), + onMessage, + init?.signal, + ); + }; + static Definition = { + name: "GsmSendSmsWithProvider", + cliName: "smsp", + url: "/gsmProvider/send/sms", + method: "post", + description: "Send a text message using an specific gsm provider", + in: { + fields: [ + { + name: "gsmProviderId", + type: "string", + }, + { + name: "toNumber", + type: "string", + tags: { + validate: "required", + }, + }, + { + name: "body", + type: "string", + tags: { + validate: "required", + }, + }, + ], + }, + out: { + fields: [ + { + name: "queueId", + type: "string", + }, + ], + }, + }; +} +/** + * The base class definition for gsmSendSmsWithProviderActionReq + **/ +export class GsmSendSmsWithProviderActionReq { + /** + * + * @type {string} + **/ + #gsmProviderId: string = ""; + /** + * + * @returns {string} + **/ + get gsmProviderId() { + return this.#gsmProviderId; + } + /** + * + * @type {string} + **/ + set gsmProviderId(value: string) { + this.#gsmProviderId = String(value); + } + setGsmProviderId(value: string) { + this.gsmProviderId = value; + return this; + } + /** + * + * @type {string} + **/ + #toNumber: string = ""; + /** + * + * @returns {string} + **/ + get toNumber() { + return this.#toNumber; + } + /** + * + * @type {string} + **/ + set toNumber(value: string) { + this.#toNumber = String(value); + } + setToNumber(value: string) { + this.toNumber = value; + return this; + } + /** + * + * @type {string} + **/ + #body: string = ""; + /** + * + * @returns {string} + **/ + get body() { + return this.#body; + } + /** + * + * @type {string} + **/ + set body(value: string) { + this.#body = String(value); + } + setBody(value: string) { + this.body = value; + return this; + } + constructor(data: unknown = undefined) { + if (data === null || data === undefined) { + return; + } + if (typeof data === "string") { + this.applyFromObject(JSON.parse(data)); + } else if (this.#isJsonAppliable(data)) { + this.applyFromObject(data); + } else { + throw new Error( + "Instance cannot be created on an unknown value, check the content being passed. got: " + + typeof data, + ); + } + } + #isJsonAppliable(obj: unknown) { + const g = globalThis as unknown as { Buffer: any; Blob: any }; + const isBuffer = + typeof g.Buffer !== "undefined" && + typeof g.Buffer.isBuffer === "function" && + g.Buffer.isBuffer(obj); + const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; + return ( + obj && + typeof obj === "object" && + !Array.isArray(obj) && + !isBuffer && + !(obj instanceof ArrayBuffer) && + !isBlob + ); + } + /** + * casts the fields of a javascript object into the class properties one by one + **/ + applyFromObject(data = {}) { + const d = data as Partial; + if (d.gsmProviderId !== undefined) { + this.gsmProviderId = d.gsmProviderId; + } + if (d.toNumber !== undefined) { + this.toNumber = d.toNumber; + } + if (d.body !== undefined) { + this.body = d.body; + } + } + /** + * Special toJSON override, since the field are private, + * Json stringify won't see them unless we mention it explicitly. + **/ + toJSON() { + return { + gsmProviderId: this.#gsmProviderId, + toNumber: this.#toNumber, + body: this.#body, + }; + } + toString() { + return JSON.stringify(this); + } + static get Fields() { + return { + gsmProviderId: "gsmProviderId", + toNumber: "toNumber", + body: "body", + }; + } + /** + * Creates an instance of GsmSendSmsWithProviderActionReq, and possibleDtoObject + * needs to satisfy the type requirement fully, otherwise typescript compile would + * be complaining. + **/ + static from(possibleDtoObject: GsmSendSmsWithProviderActionReqType) { + return new GsmSendSmsWithProviderActionReq(possibleDtoObject); + } + /** + * Creates an instance of GsmSendSmsWithProviderActionReq, and partialDtoObject + * needs to satisfy the type, but partially, and rest of the content would + * be constructed according to data types and nullability. + **/ + static with( + partialDtoObject: PartialDeep, + ) { + return new GsmSendSmsWithProviderActionReq(partialDtoObject); + } + copyWith( + partial: PartialDeep, + ): InstanceType { + return new GsmSendSmsWithProviderActionReq({ + ...this.toJSON(), + ...partial, + }); + } + clone(): InstanceType { + return new GsmSendSmsWithProviderActionReq(this.toJSON()); + } +} +export abstract class GsmSendSmsWithProviderActionReqFactory { + abstract create(data: unknown): GsmSendSmsWithProviderActionReq; +} +/** + * The base type definition for gsmSendSmsWithProviderActionReq + **/ +export type GsmSendSmsWithProviderActionReqType = { + /** + * + * @type {string} + **/ + gsmProviderId: string; + /** + * + * @type {string} + **/ + toNumber: string; + /** + * + * @type {string} + **/ + body: string; +}; +// eslint-disable-next-line @typescript-eslint/no-namespace +export namespace GsmSendSmsWithProviderActionReqType {} +/** + * The base class definition for gsmSendSmsWithProviderActionRes + **/ +export class GsmSendSmsWithProviderActionRes { + /** + * + * @type {string} + **/ + #queueId: string = ""; + /** + * + * @returns {string} + **/ + get queueId() { + return this.#queueId; + } + /** + * + * @type {string} + **/ + set queueId(value: string) { + this.#queueId = String(value); + } + setQueueId(value: string) { + this.queueId = value; + return this; + } + constructor(data: unknown = undefined) { + if (data === null || data === undefined) { + return; + } + if (typeof data === "string") { + this.applyFromObject(JSON.parse(data)); + } else if (this.#isJsonAppliable(data)) { + this.applyFromObject(data); + } else { + throw new Error( + "Instance cannot be created on an unknown value, check the content being passed. got: " + + typeof data, + ); + } + } + #isJsonAppliable(obj: unknown) { + const g = globalThis as unknown as { Buffer: any; Blob: any }; + const isBuffer = + typeof g.Buffer !== "undefined" && + typeof g.Buffer.isBuffer === "function" && + g.Buffer.isBuffer(obj); + const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; + return ( + obj && + typeof obj === "object" && + !Array.isArray(obj) && + !isBuffer && + !(obj instanceof ArrayBuffer) && + !isBlob + ); + } + /** + * casts the fields of a javascript object into the class properties one by one + **/ + applyFromObject(data = {}) { + const d = data as Partial; + if (d.queueId !== undefined) { + this.queueId = d.queueId; + } + } + /** + * Special toJSON override, since the field are private, + * Json stringify won't see them unless we mention it explicitly. + **/ + toJSON() { + return { + queueId: this.#queueId, + }; + } + toString() { + return JSON.stringify(this); + } + static get Fields() { + return { + queueId: "queueId", + }; + } + /** + * Creates an instance of GsmSendSmsWithProviderActionRes, and possibleDtoObject + * needs to satisfy the type requirement fully, otherwise typescript compile would + * be complaining. + **/ + static from(possibleDtoObject: GsmSendSmsWithProviderActionResType) { + return new GsmSendSmsWithProviderActionRes(possibleDtoObject); + } + /** + * Creates an instance of GsmSendSmsWithProviderActionRes, and partialDtoObject + * needs to satisfy the type, but partially, and rest of the content would + * be constructed according to data types and nullability. + **/ + static with( + partialDtoObject: PartialDeep, + ) { + return new GsmSendSmsWithProviderActionRes(partialDtoObject); + } + copyWith( + partial: PartialDeep, + ): InstanceType { + return new GsmSendSmsWithProviderActionRes({ + ...this.toJSON(), + ...partial, + }); + } + clone(): InstanceType { + return new GsmSendSmsWithProviderActionRes(this.toJSON()); + } +} +export abstract class GsmSendSmsWithProviderActionResFactory { + abstract create(data: unknown): GsmSendSmsWithProviderActionRes; +} +/** + * The base type definition for gsmSendSmsWithProviderActionRes + **/ +export type GsmSendSmsWithProviderActionResType = { + /** + * + * @type {string} + **/ + queueId: string; +}; +// eslint-disable-next-line @typescript-eslint/no-namespace +export namespace GsmSendSmsWithProviderActionResType {} diff --git a/e2e/react-bed/src/sdk/modules/abac/SendEmail.ts b/e2e/react-bed/src/sdk/modules/abac/SendEmail.ts new file mode 100644 index 000000000..0935ce59e --- /dev/null +++ b/e2e/react-bed/src/sdk/modules/abac/SendEmail.ts @@ -0,0 +1,436 @@ +import { buildUrl } from "../../sdk/common/buildUrl"; +import { + fetchx, + handleFetchResponse, + type FetchxContext, + type PartialDeep, + type TypedRequestInit, + type TypedResponse, +} from "../../sdk/common/fetchx"; +import { type UseMutationOptions, useMutation } from "react-query"; +import { useFetchxContext } from "../../sdk/react/useFetchx"; +import { useState } from "react"; +/** + * Action to communicate with the action SendEmail + */ +export type SendEmailActionOptions = { + queryKey?: unknown[]; + qs?: URLSearchParams; +}; +export type SendEmailActionMutationOptions = Omit< + UseMutationOptions, + "mutationFn" +> & + SendEmailActionOptions & { + ctx?: FetchxContext; + onMessage?: (ev: MessageEvent) => void; + overrideUrl?: string; + headers?: Headers; + } & Partial<{ + creatorFn: (item: unknown) => SendEmailActionRes; + }>; +export const useSendEmailAction = ( + options?: SendEmailActionMutationOptions, +) => { + const globalCtx = useFetchxContext(); + const ctx = options?.ctx ?? globalCtx ?? undefined; + const [isCompleted, setCompleteState] = useState(false); + const [response, setResponse] = useState>(); + const fn = (body: SendEmailActionReq) => { + setCompleteState(false); + return SendEmailAction.Fetch( + { + body, + headers: options?.headers, + }, + { + creatorFn: options?.creatorFn, + qs: options?.qs, + ctx, + onMessage: options?.onMessage, + overrideUrl: options?.overrideUrl, + }, + ).then((x) => { + x.done.then(() => { + setCompleteState(true); + }); + setResponse(x.response); + return x.response.result; + }); + }; + const result = useMutation({ + mutationFn: fn, + ...(options || {}), + }); + return { + ...result, + isCompleted, + response, + }; +}; +/** + * SendEmailAction + */ +export class SendEmailAction { + // + static URL = "/email/send"; + static NewUrl = (qs?: URLSearchParams) => + buildUrl(SendEmailAction.URL, undefined, qs); + static Method = "post"; + static Fetch$ = async ( + qs?: URLSearchParams, + ctx?: FetchxContext, + init?: TypedRequestInit, + overrideUrl?: string, + ) => { + return fetchx( + overrideUrl ?? SendEmailAction.NewUrl(qs), + { + method: SendEmailAction.Method, + ...(init || {}), + }, + ctx, + ); + }; + static Fetch = async ( + init?: TypedRequestInit, + { + creatorFn, + qs, + ctx, + onMessage, + overrideUrl, + }: { + creatorFn?: ((item: unknown) => SendEmailActionRes) | undefined; + qs?: URLSearchParams; + ctx?: FetchxContext; + onMessage?: (ev: MessageEvent) => void; + overrideUrl?: string; + } = { + creatorFn: (item) => new SendEmailActionRes(item), + }, + ) => { + creatorFn = creatorFn || ((item) => new SendEmailActionRes(item)); + const res = await SendEmailAction.Fetch$(qs, ctx, init, overrideUrl); + return handleFetchResponse( + res, + (item) => (creatorFn ? creatorFn(item) : item), + onMessage, + init?.signal, + ); + }; + static Definition = { + name: "SendEmail", + cliName: "email", + url: "/email/send", + method: "post", + description: "Send a email using default root notification configuration", + in: { + fields: [ + { + name: "toAddress", + type: "string", + tags: { + validate: "required", + }, + }, + { + name: "body", + type: "string", + tags: { + validate: "required", + }, + }, + ], + }, + out: { + fields: [ + { + name: "queueId", + type: "string", + }, + ], + }, + }; +} +/** + * The base class definition for sendEmailActionReq + **/ +export class SendEmailActionReq { + /** + * + * @type {string} + **/ + #toAddress: string = ""; + /** + * + * @returns {string} + **/ + get toAddress() { + return this.#toAddress; + } + /** + * + * @type {string} + **/ + set toAddress(value: string) { + this.#toAddress = String(value); + } + setToAddress(value: string) { + this.toAddress = value; + return this; + } + /** + * + * @type {string} + **/ + #body: string = ""; + /** + * + * @returns {string} + **/ + get body() { + return this.#body; + } + /** + * + * @type {string} + **/ + set body(value: string) { + this.#body = String(value); + } + setBody(value: string) { + this.body = value; + return this; + } + constructor(data: unknown = undefined) { + if (data === null || data === undefined) { + return; + } + if (typeof data === "string") { + this.applyFromObject(JSON.parse(data)); + } else if (this.#isJsonAppliable(data)) { + this.applyFromObject(data); + } else { + throw new Error( + "Instance cannot be created on an unknown value, check the content being passed. got: " + + typeof data, + ); + } + } + #isJsonAppliable(obj: unknown) { + const g = globalThis as unknown as { Buffer: any; Blob: any }; + const isBuffer = + typeof g.Buffer !== "undefined" && + typeof g.Buffer.isBuffer === "function" && + g.Buffer.isBuffer(obj); + const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; + return ( + obj && + typeof obj === "object" && + !Array.isArray(obj) && + !isBuffer && + !(obj instanceof ArrayBuffer) && + !isBlob + ); + } + /** + * casts the fields of a javascript object into the class properties one by one + **/ + applyFromObject(data = {}) { + const d = data as Partial; + if (d.toAddress !== undefined) { + this.toAddress = d.toAddress; + } + if (d.body !== undefined) { + this.body = d.body; + } + } + /** + * Special toJSON override, since the field are private, + * Json stringify won't see them unless we mention it explicitly. + **/ + toJSON() { + return { + toAddress: this.#toAddress, + body: this.#body, + }; + } + toString() { + return JSON.stringify(this); + } + static get Fields() { + return { + toAddress: "toAddress", + body: "body", + }; + } + /** + * Creates an instance of SendEmailActionReq, and possibleDtoObject + * needs to satisfy the type requirement fully, otherwise typescript compile would + * be complaining. + **/ + static from(possibleDtoObject: SendEmailActionReqType) { + return new SendEmailActionReq(possibleDtoObject); + } + /** + * Creates an instance of SendEmailActionReq, and partialDtoObject + * needs to satisfy the type, but partially, and rest of the content would + * be constructed according to data types and nullability. + **/ + static with(partialDtoObject: PartialDeep) { + return new SendEmailActionReq(partialDtoObject); + } + copyWith( + partial: PartialDeep, + ): InstanceType { + return new SendEmailActionReq({ ...this.toJSON(), ...partial }); + } + clone(): InstanceType { + return new SendEmailActionReq(this.toJSON()); + } +} +export abstract class SendEmailActionReqFactory { + abstract create(data: unknown): SendEmailActionReq; +} +/** + * The base type definition for sendEmailActionReq + **/ +export type SendEmailActionReqType = { + /** + * + * @type {string} + **/ + toAddress: string; + /** + * + * @type {string} + **/ + body: string; +}; +// eslint-disable-next-line @typescript-eslint/no-namespace +export namespace SendEmailActionReqType {} +/** + * The base class definition for sendEmailActionRes + **/ +export class SendEmailActionRes { + /** + * + * @type {string} + **/ + #queueId: string = ""; + /** + * + * @returns {string} + **/ + get queueId() { + return this.#queueId; + } + /** + * + * @type {string} + **/ + set queueId(value: string) { + this.#queueId = String(value); + } + setQueueId(value: string) { + this.queueId = value; + return this; + } + constructor(data: unknown = undefined) { + if (data === null || data === undefined) { + return; + } + if (typeof data === "string") { + this.applyFromObject(JSON.parse(data)); + } else if (this.#isJsonAppliable(data)) { + this.applyFromObject(data); + } else { + throw new Error( + "Instance cannot be created on an unknown value, check the content being passed. got: " + + typeof data, + ); + } + } + #isJsonAppliable(obj: unknown) { + const g = globalThis as unknown as { Buffer: any; Blob: any }; + const isBuffer = + typeof g.Buffer !== "undefined" && + typeof g.Buffer.isBuffer === "function" && + g.Buffer.isBuffer(obj); + const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; + return ( + obj && + typeof obj === "object" && + !Array.isArray(obj) && + !isBuffer && + !(obj instanceof ArrayBuffer) && + !isBlob + ); + } + /** + * casts the fields of a javascript object into the class properties one by one + **/ + applyFromObject(data = {}) { + const d = data as Partial; + if (d.queueId !== undefined) { + this.queueId = d.queueId; + } + } + /** + * Special toJSON override, since the field are private, + * Json stringify won't see them unless we mention it explicitly. + **/ + toJSON() { + return { + queueId: this.#queueId, + }; + } + toString() { + return JSON.stringify(this); + } + static get Fields() { + return { + queueId: "queueId", + }; + } + /** + * Creates an instance of SendEmailActionRes, and possibleDtoObject + * needs to satisfy the type requirement fully, otherwise typescript compile would + * be complaining. + **/ + static from(possibleDtoObject: SendEmailActionResType) { + return new SendEmailActionRes(possibleDtoObject); + } + /** + * Creates an instance of SendEmailActionRes, and partialDtoObject + * needs to satisfy the type, but partially, and rest of the content would + * be constructed according to data types and nullability. + **/ + static with(partialDtoObject: PartialDeep) { + return new SendEmailActionRes(partialDtoObject); + } + copyWith( + partial: PartialDeep, + ): InstanceType { + return new SendEmailActionRes({ ...this.toJSON(), ...partial }); + } + clone(): InstanceType { + return new SendEmailActionRes(this.toJSON()); + } +} +export abstract class SendEmailActionResFactory { + abstract create(data: unknown): SendEmailActionRes; +} +/** + * The base type definition for sendEmailActionRes + **/ +export type SendEmailActionResType = { + /** + * + * @type {string} + **/ + queueId: string; +}; +// eslint-disable-next-line @typescript-eslint/no-namespace +export namespace SendEmailActionResType {} diff --git a/e2e/react-bed/src/sdk/modules/abac/SendEmailWithProvider.ts b/e2e/react-bed/src/sdk/modules/abac/SendEmailWithProvider.ts new file mode 100644 index 000000000..5fafe49b4 --- /dev/null +++ b/e2e/react-bed/src/sdk/modules/abac/SendEmailWithProvider.ts @@ -0,0 +1,511 @@ +import { EmailProviderEntity } from "./EmailProviderEntity"; +import { buildUrl } from "../../sdk/common/buildUrl"; +import { + fetchx, + handleFetchResponse, + type FetchxContext, + type PartialDeep, + type TypedRequestInit, + type TypedResponse, +} from "../../sdk/common/fetchx"; +import { type UseMutationOptions, useMutation } from "react-query"; +import { useFetchxContext } from "../../sdk/react/useFetchx"; +import { useState } from "react"; +import { withPrefix } from "../../sdk/common/withPrefix"; +/** + * Action to communicate with the action SendEmailWithProvider + */ +export type SendEmailWithProviderActionOptions = { + queryKey?: unknown[]; + qs?: URLSearchParams; +}; +export type SendEmailWithProviderActionMutationOptions = Omit< + UseMutationOptions, + "mutationFn" +> & + SendEmailWithProviderActionOptions & { + ctx?: FetchxContext; + onMessage?: (ev: MessageEvent) => void; + overrideUrl?: string; + headers?: Headers; + } & Partial<{ + creatorFn: (item: unknown) => SendEmailWithProviderActionRes; + }>; +export const useSendEmailWithProviderAction = ( + options?: SendEmailWithProviderActionMutationOptions, +) => { + const globalCtx = useFetchxContext(); + const ctx = options?.ctx ?? globalCtx ?? undefined; + const [isCompleted, setCompleteState] = useState(false); + const [response, setResponse] = useState>(); + const fn = (body: SendEmailWithProviderActionReq) => { + setCompleteState(false); + return SendEmailWithProviderAction.Fetch( + { + body, + headers: options?.headers, + }, + { + creatorFn: options?.creatorFn, + qs: options?.qs, + ctx, + onMessage: options?.onMessage, + overrideUrl: options?.overrideUrl, + }, + ).then((x) => { + x.done.then(() => { + setCompleteState(true); + }); + setResponse(x.response); + return x.response.result; + }); + }; + const result = useMutation({ + mutationFn: fn, + ...(options || {}), + }); + return { + ...result, + isCompleted, + response, + }; +}; +/** + * SendEmailWithProviderAction + */ +export class SendEmailWithProviderAction { + // + static URL = "/emailProvider/send"; + static NewUrl = (qs?: URLSearchParams) => + buildUrl(SendEmailWithProviderAction.URL, undefined, qs); + static Method = "post"; + static Fetch$ = async ( + qs?: URLSearchParams, + ctx?: FetchxContext, + init?: TypedRequestInit, + overrideUrl?: string, + ) => { + return fetchx< + SendEmailWithProviderActionRes, + SendEmailWithProviderActionReq, + unknown + >( + overrideUrl ?? SendEmailWithProviderAction.NewUrl(qs), + { + method: SendEmailWithProviderAction.Method, + ...(init || {}), + }, + ctx, + ); + }; + static Fetch = async ( + init?: TypedRequestInit, + { + creatorFn, + qs, + ctx, + onMessage, + overrideUrl, + }: { + creatorFn?: + | ((item: unknown) => SendEmailWithProviderActionRes) + | undefined; + qs?: URLSearchParams; + ctx?: FetchxContext; + onMessage?: (ev: MessageEvent) => void; + overrideUrl?: string; + } = { + creatorFn: (item) => new SendEmailWithProviderActionRes(item), + }, + ) => { + creatorFn = + creatorFn || ((item) => new SendEmailWithProviderActionRes(item)); + const res = await SendEmailWithProviderAction.Fetch$( + qs, + ctx, + init, + overrideUrl, + ); + return handleFetchResponse( + res, + (item) => (creatorFn ? creatorFn(item) : item), + onMessage, + init?.signal, + ); + }; + static Definition = { + name: "SendEmailWithProvider", + cliName: "emailp", + url: "/emailProvider/send", + method: "post", + description: "Send a text message using an specific gsm provider", + in: { + fields: [ + { + name: "emailProvider", + type: "one", + target: "EmailProviderEntity", + }, + { + name: "toAddress", + type: "string", + tags: { + validate: "required", + }, + }, + { + name: "body", + type: "string", + tags: { + validate: "required", + }, + }, + ], + }, + out: { + fields: [ + { + name: "queueId", + type: "string", + }, + ], + }, + }; +} +/** + * The base class definition for sendEmailWithProviderActionReq + **/ +export class SendEmailWithProviderActionReq { + /** + * + * @type {EmailProviderEntity} + **/ + #emailProvider!: EmailProviderEntity; + /** + * + * @returns {EmailProviderEntity} + **/ + get emailProvider() { + return this.#emailProvider; + } + /** + * + * @type {EmailProviderEntity} + **/ + set emailProvider(value: EmailProviderEntity) { + // For objects, the sub type needs to always be instance of the sub class. + if (value instanceof EmailProviderEntity) { + this.#emailProvider = value; + } else { + this.#emailProvider = new EmailProviderEntity(value); + } + } + setEmailProvider(value: EmailProviderEntity) { + this.emailProvider = value; + return this; + } + /** + * + * @type {string} + **/ + #toAddress: string = ""; + /** + * + * @returns {string} + **/ + get toAddress() { + return this.#toAddress; + } + /** + * + * @type {string} + **/ + set toAddress(value: string) { + this.#toAddress = String(value); + } + setToAddress(value: string) { + this.toAddress = value; + return this; + } + /** + * + * @type {string} + **/ + #body: string = ""; + /** + * + * @returns {string} + **/ + get body() { + return this.#body; + } + /** + * + * @type {string} + **/ + set body(value: string) { + this.#body = String(value); + } + setBody(value: string) { + this.body = value; + return this; + } + constructor(data: unknown = undefined) { + if (data === null || data === undefined) { + this.#lateInitFields(); + return; + } + if (typeof data === "string") { + this.applyFromObject(JSON.parse(data)); + } else if (this.#isJsonAppliable(data)) { + this.applyFromObject(data); + } else { + throw new Error( + "Instance cannot be created on an unknown value, check the content being passed. got: " + + typeof data, + ); + } + } + #isJsonAppliable(obj: unknown) { + const g = globalThis as unknown as { Buffer: any; Blob: any }; + const isBuffer = + typeof g.Buffer !== "undefined" && + typeof g.Buffer.isBuffer === "function" && + g.Buffer.isBuffer(obj); + const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; + return ( + obj && + typeof obj === "object" && + !Array.isArray(obj) && + !isBuffer && + !(obj instanceof ArrayBuffer) && + !isBlob + ); + } + /** + * casts the fields of a javascript object into the class properties one by one + **/ + applyFromObject(data = {}) { + const d = data as Partial; + if (d.emailProvider !== undefined) { + this.emailProvider = d.emailProvider; + } + if (d.toAddress !== undefined) { + this.toAddress = d.toAddress; + } + if (d.body !== undefined) { + this.body = d.body; + } + this.#lateInitFields(data); + } + /** + * These are the class instances, which need to be initialised, regardless of the constructor incoming data + **/ + #lateInitFields(data = {}) { + const d = data as Partial; + if (!(d.emailProvider instanceof EmailProviderEntity)) { + this.emailProvider = new EmailProviderEntity(d.emailProvider || {}); + } + } + /** + * Special toJSON override, since the field are private, + * Json stringify won't see them unless we mention it explicitly. + **/ + toJSON() { + return { + emailProvider: this.#emailProvider, + toAddress: this.#toAddress, + body: this.#body, + }; + } + toString() { + return JSON.stringify(this); + } + static get Fields() { + return { + emailProvider$: "emailProvider", + get emailProvider() { + return withPrefix("emailProvider", EmailProviderEntity.Fields); + }, + toAddress: "toAddress", + body: "body", + }; + } + /** + * Creates an instance of SendEmailWithProviderActionReq, and possibleDtoObject + * needs to satisfy the type requirement fully, otherwise typescript compile would + * be complaining. + **/ + static from(possibleDtoObject: SendEmailWithProviderActionReqType) { + return new SendEmailWithProviderActionReq(possibleDtoObject); + } + /** + * Creates an instance of SendEmailWithProviderActionReq, and partialDtoObject + * needs to satisfy the type, but partially, and rest of the content would + * be constructed according to data types and nullability. + **/ + static with( + partialDtoObject: PartialDeep, + ) { + return new SendEmailWithProviderActionReq(partialDtoObject); + } + copyWith( + partial: PartialDeep, + ): InstanceType { + return new SendEmailWithProviderActionReq({ ...this.toJSON(), ...partial }); + } + clone(): InstanceType { + return new SendEmailWithProviderActionReq(this.toJSON()); + } +} +export abstract class SendEmailWithProviderActionReqFactory { + abstract create(data: unknown): SendEmailWithProviderActionReq; +} +/** + * The base type definition for sendEmailWithProviderActionReq + **/ +export type SendEmailWithProviderActionReqType = { + /** + * + * @type {EmailProviderEntity} + **/ + emailProvider: EmailProviderEntity; + /** + * + * @type {string} + **/ + toAddress: string; + /** + * + * @type {string} + **/ + body: string; +}; +// eslint-disable-next-line @typescript-eslint/no-namespace +export namespace SendEmailWithProviderActionReqType {} +/** + * The base class definition for sendEmailWithProviderActionRes + **/ +export class SendEmailWithProviderActionRes { + /** + * + * @type {string} + **/ + #queueId: string = ""; + /** + * + * @returns {string} + **/ + get queueId() { + return this.#queueId; + } + /** + * + * @type {string} + **/ + set queueId(value: string) { + this.#queueId = String(value); + } + setQueueId(value: string) { + this.queueId = value; + return this; + } + constructor(data: unknown = undefined) { + if (data === null || data === undefined) { + return; + } + if (typeof data === "string") { + this.applyFromObject(JSON.parse(data)); + } else if (this.#isJsonAppliable(data)) { + this.applyFromObject(data); + } else { + throw new Error( + "Instance cannot be created on an unknown value, check the content being passed. got: " + + typeof data, + ); + } + } + #isJsonAppliable(obj: unknown) { + const g = globalThis as unknown as { Buffer: any; Blob: any }; + const isBuffer = + typeof g.Buffer !== "undefined" && + typeof g.Buffer.isBuffer === "function" && + g.Buffer.isBuffer(obj); + const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; + return ( + obj && + typeof obj === "object" && + !Array.isArray(obj) && + !isBuffer && + !(obj instanceof ArrayBuffer) && + !isBlob + ); + } + /** + * casts the fields of a javascript object into the class properties one by one + **/ + applyFromObject(data = {}) { + const d = data as Partial; + if (d.queueId !== undefined) { + this.queueId = d.queueId; + } + } + /** + * Special toJSON override, since the field are private, + * Json stringify won't see them unless we mention it explicitly. + **/ + toJSON() { + return { + queueId: this.#queueId, + }; + } + toString() { + return JSON.stringify(this); + } + static get Fields() { + return { + queueId: "queueId", + }; + } + /** + * Creates an instance of SendEmailWithProviderActionRes, and possibleDtoObject + * needs to satisfy the type requirement fully, otherwise typescript compile would + * be complaining. + **/ + static from(possibleDtoObject: SendEmailWithProviderActionResType) { + return new SendEmailWithProviderActionRes(possibleDtoObject); + } + /** + * Creates an instance of SendEmailWithProviderActionRes, and partialDtoObject + * needs to satisfy the type, but partially, and rest of the content would + * be constructed according to data types and nullability. + **/ + static with( + partialDtoObject: PartialDeep, + ) { + return new SendEmailWithProviderActionRes(partialDtoObject); + } + copyWith( + partial: PartialDeep, + ): InstanceType { + return new SendEmailWithProviderActionRes({ ...this.toJSON(), ...partial }); + } + clone(): InstanceType { + return new SendEmailWithProviderActionRes(this.toJSON()); + } +} +export abstract class SendEmailWithProviderActionResFactory { + abstract create(data: unknown): SendEmailWithProviderActionRes; +} +/** + * The base type definition for sendEmailWithProviderActionRes + **/ +export type SendEmailWithProviderActionResType = { + /** + * + * @type {string} + **/ + queueId: string; +}; +// eslint-disable-next-line @typescript-eslint/no-namespace +export namespace SendEmailWithProviderActionResType {} diff --git a/e2e/react-bed/src/sdk/modules/abac/usePostEmailProviderSend.ts b/e2e/react-bed/src/sdk/modules/abac/usePostEmailProviderSend.ts deleted file mode 100644 index 3b8426304..000000000 --- a/e2e/react-bed/src/sdk/modules/abac/usePostEmailProviderSend.ts +++ /dev/null @@ -1,92 +0,0 @@ -/* -* Generated by fireback 1.2.5 -* Written by Ali Torabi. -* The code is generated for react-query@v3.39.3 -* Checkout the repository for licenses and contribution: https://github.com/torabian/fireback -*/ -import { type FormikHelpers } from "formik"; -import { useContext, useState, useRef } from "react"; -import { useMutation } from "react-query"; -import { - execApiFn, - type IResponse, - mutationErrorsToFormik, - type IResponseList -} from "../../core/http-tools"; -import { - RemoteQueryContext, - type UseRemoteQuery, - queryBeforeSend, -} from "../../core/react-tools"; - import { - SendEmailWithProviderActionReqDto, - SendEmailWithProviderActionResDto, - } from "../abac/AbacActionsDto" -export function usePostEmailProviderSend( - props?: UseRemoteQuery & { - } -) { - let {queryClient, query, execFnOverride} = props || {}; - query = query || {} - const { options, execFn } = useContext(RemoteQueryContext); - // Calculare the function which will do the remote calls. - // We consider to use global override, this specific override, or default which - // comes with the sdk. - const rpcFn = execFnOverride - ? execFnOverride(options) - : execFn - ? execFn(options) - : execApiFn(options); - // Url of the remote affix. - const url = "/emailProvider/send".substr(1); - let computedUrl = `${url}?${new URLSearchParams( - queryBeforeSend(query) - ).toString()}`; - let completeRouteUrls = true; - // Attach the details of the request to the fn - const fn = (body: any) => rpcFn("POST", computedUrl, body); - const mutation = useMutation< - IResponse, - IResponse, - Partial - >(fn); - // Only entities are having a store in front-end - const fnUpdater = ( - data: IResponseList | undefined, - item: IResponse - ) => { - if (!data) { - return { - data: { items: [] }, - }; - } - // To me it seems this is not a good or any correct strategy to update the store. - // When we are posting, we want to add it there, that's it. Not updating it. - // We have patch, but also posting with ID is possible. - if (data.data && item?.data) { - data.data.items = [item.data, ...(data?.data?.items || [])]; - } - return data; - }; - const submit = ( - values: Partial, - formikProps?: FormikHelpers> - ): Promise> => { - return new Promise((resolve, reject) => { - mutation.mutate(values, { - onSuccess(response: IResponse) { - queryClient?.setQueryData>( - "*abac.SendEmailWithProviderActionResDto", - (data) => fnUpdater(data, response) as any - ); - resolve(response); - }, - onError(error: any) { - formikProps?.setErrors(mutationErrorsToFormik(error)); - reject(error); - }, - }); - }); - }; - return { mutation, submit, fnUpdater }; -} diff --git a/e2e/react-bed/src/sdk/modules/abac/usePostEmailSend.ts b/e2e/react-bed/src/sdk/modules/abac/usePostEmailSend.ts deleted file mode 100644 index 55e98e386..000000000 --- a/e2e/react-bed/src/sdk/modules/abac/usePostEmailSend.ts +++ /dev/null @@ -1,92 +0,0 @@ -/* -* Generated by fireback 1.2.5 -* Written by Ali Torabi. -* The code is generated for react-query@v3.39.3 -* Checkout the repository for licenses and contribution: https://github.com/torabian/fireback -*/ -import { type FormikHelpers } from "formik"; -import { useContext, useState, useRef } from "react"; -import { useMutation } from "react-query"; -import { - execApiFn, - type IResponse, - mutationErrorsToFormik, - type IResponseList -} from "../../core/http-tools"; -import { - RemoteQueryContext, - type UseRemoteQuery, - queryBeforeSend, -} from "../../core/react-tools"; - import { - SendEmailActionReqDto, - SendEmailActionResDto, - } from "../abac/AbacActionsDto" -export function usePostEmailSend( - props?: UseRemoteQuery & { - } -) { - let {queryClient, query, execFnOverride} = props || {}; - query = query || {} - const { options, execFn } = useContext(RemoteQueryContext); - // Calculare the function which will do the remote calls. - // We consider to use global override, this specific override, or default which - // comes with the sdk. - const rpcFn = execFnOverride - ? execFnOverride(options) - : execFn - ? execFn(options) - : execApiFn(options); - // Url of the remote affix. - const url = "/email/send".substr(1); - let computedUrl = `${url}?${new URLSearchParams( - queryBeforeSend(query) - ).toString()}`; - let completeRouteUrls = true; - // Attach the details of the request to the fn - const fn = (body: any) => rpcFn("POST", computedUrl, body); - const mutation = useMutation< - IResponse, - IResponse, - Partial - >(fn); - // Only entities are having a store in front-end - const fnUpdater = ( - data: IResponseList | undefined, - item: IResponse - ) => { - if (!data) { - return { - data: { items: [] }, - }; - } - // To me it seems this is not a good or any correct strategy to update the store. - // When we are posting, we want to add it there, that's it. Not updating it. - // We have patch, but also posting with ID is possible. - if (data.data && item?.data) { - data.data.items = [item.data, ...(data?.data?.items || [])]; - } - return data; - }; - const submit = ( - values: Partial, - formikProps?: FormikHelpers> - ): Promise> => { - return new Promise((resolve, reject) => { - mutation.mutate(values, { - onSuccess(response: IResponse) { - queryClient?.setQueryData>( - "*abac.SendEmailActionResDto", - (data) => fnUpdater(data, response) as any - ); - resolve(response); - }, - onError(error: any) { - formikProps?.setErrors(mutationErrorsToFormik(error)); - reject(error); - }, - }); - }); - }; - return { mutation, submit, fnUpdater }; -} diff --git a/e2e/react-bed/src/sdk/modules/abac/usePostGsmProviderSendSms.ts b/e2e/react-bed/src/sdk/modules/abac/usePostGsmProviderSendSms.ts deleted file mode 100644 index b47bc28d9..000000000 --- a/e2e/react-bed/src/sdk/modules/abac/usePostGsmProviderSendSms.ts +++ /dev/null @@ -1,92 +0,0 @@ -/* -* Generated by fireback 1.2.5 -* Written by Ali Torabi. -* The code is generated for react-query@v3.39.3 -* Checkout the repository for licenses and contribution: https://github.com/torabian/fireback -*/ -import { type FormikHelpers } from "formik"; -import { useContext, useState, useRef } from "react"; -import { useMutation } from "react-query"; -import { - execApiFn, - type IResponse, - mutationErrorsToFormik, - type IResponseList -} from "../../core/http-tools"; -import { - RemoteQueryContext, - type UseRemoteQuery, - queryBeforeSend, -} from "../../core/react-tools"; - import { - GsmSendSmsWithProviderActionReqDto, - GsmSendSmsWithProviderActionResDto, - } from "../abac/AbacActionsDto" -export function usePostGsmProviderSendSms( - props?: UseRemoteQuery & { - } -) { - let {queryClient, query, execFnOverride} = props || {}; - query = query || {} - const { options, execFn } = useContext(RemoteQueryContext); - // Calculare the function which will do the remote calls. - // We consider to use global override, this specific override, or default which - // comes with the sdk. - const rpcFn = execFnOverride - ? execFnOverride(options) - : execFn - ? execFn(options) - : execApiFn(options); - // Url of the remote affix. - const url = "/gsmProvider/send/sms".substr(1); - let computedUrl = `${url}?${new URLSearchParams( - queryBeforeSend(query) - ).toString()}`; - let completeRouteUrls = true; - // Attach the details of the request to the fn - const fn = (body: any) => rpcFn("POST", computedUrl, body); - const mutation = useMutation< - IResponse, - IResponse, - Partial - >(fn); - // Only entities are having a store in front-end - const fnUpdater = ( - data: IResponseList | undefined, - item: IResponse - ) => { - if (!data) { - return { - data: { items: [] }, - }; - } - // To me it seems this is not a good or any correct strategy to update the store. - // When we are posting, we want to add it there, that's it. Not updating it. - // We have patch, but also posting with ID is possible. - if (data.data && item?.data) { - data.data.items = [item.data, ...(data?.data?.items || [])]; - } - return data; - }; - const submit = ( - values: Partial, - formikProps?: FormikHelpers> - ): Promise> => { - return new Promise((resolve, reject) => { - mutation.mutate(values, { - onSuccess(response: IResponse) { - queryClient?.setQueryData>( - "*abac.GsmSendSmsWithProviderActionResDto", - (data) => fnUpdater(data, response) as any - ); - resolve(response); - }, - onError(error: any) { - formikProps?.setErrors(mutationErrorsToFormik(error)); - reject(error); - }, - }); - }); - }; - return { mutation, submit, fnUpdater }; -} diff --git a/e2e/react-bed/src/sdk/modules/abac/usePostGsmSendSms.ts b/e2e/react-bed/src/sdk/modules/abac/usePostGsmSendSms.ts deleted file mode 100644 index 6e70f013a..000000000 --- a/e2e/react-bed/src/sdk/modules/abac/usePostGsmSendSms.ts +++ /dev/null @@ -1,92 +0,0 @@ -/* -* Generated by fireback 1.2.5 -* Written by Ali Torabi. -* The code is generated for react-query@v3.39.3 -* Checkout the repository for licenses and contribution: https://github.com/torabian/fireback -*/ -import { type FormikHelpers } from "formik"; -import { useContext, useState, useRef } from "react"; -import { useMutation } from "react-query"; -import { - execApiFn, - type IResponse, - mutationErrorsToFormik, - type IResponseList -} from "../../core/http-tools"; -import { - RemoteQueryContext, - type UseRemoteQuery, - queryBeforeSend, -} from "../../core/react-tools"; - import { - GsmSendSmsActionReqDto, - GsmSendSmsActionResDto, - } from "../abac/AbacActionsDto" -export function usePostGsmSendSms( - props?: UseRemoteQuery & { - } -) { - let {queryClient, query, execFnOverride} = props || {}; - query = query || {} - const { options, execFn } = useContext(RemoteQueryContext); - // Calculare the function which will do the remote calls. - // We consider to use global override, this specific override, or default which - // comes with the sdk. - const rpcFn = execFnOverride - ? execFnOverride(options) - : execFn - ? execFn(options) - : execApiFn(options); - // Url of the remote affix. - const url = "/gsm/send/sms".substr(1); - let computedUrl = `${url}?${new URLSearchParams( - queryBeforeSend(query) - ).toString()}`; - let completeRouteUrls = true; - // Attach the details of the request to the fn - const fn = (body: any) => rpcFn("POST", computedUrl, body); - const mutation = useMutation< - IResponse, - IResponse, - Partial - >(fn); - // Only entities are having a store in front-end - const fnUpdater = ( - data: IResponseList | undefined, - item: IResponse - ) => { - if (!data) { - return { - data: { items: [] }, - }; - } - // To me it seems this is not a good or any correct strategy to update the store. - // When we are posting, we want to add it there, that's it. Not updating it. - // We have patch, but also posting with ID is possible. - if (data.data && item?.data) { - data.data.items = [item.data, ...(data?.data?.items || [])]; - } - return data; - }; - const submit = ( - values: Partial, - formikProps?: FormikHelpers> - ): Promise> => { - return new Promise((resolve, reject) => { - mutation.mutate(values, { - onSuccess(response: IResponse) { - queryClient?.setQueryData>( - "*abac.GsmSendSmsActionResDto", - (data) => fnUpdater(data, response) as any - ); - resolve(response); - }, - onError(error: any) { - formikProps?.setErrors(mutationErrorsToFormik(error)); - reject(error); - }, - }); - }); - }; - return { mutation, submit, fnUpdater }; -} diff --git a/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/AbacActionsDto.ts b/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/AbacActionsDto.ts deleted file mode 100644 index c77cfb7e5..000000000 --- a/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/AbacActionsDto.ts +++ /dev/null @@ -1,81 +0,0 @@ -/* -* Generated by fireback 1.2.5 -* Written by Ali Torabi. -* Checkout the repository for licenses and contribution: https://github.com/torabian/fireback -*/ -import { - BaseDto, - BaseEntity, -} from "../../core/definitions" -import { - EmailProviderEntity, -} from "./EmailProviderEntity" -import { - GsmProviderEntity, -} from "./GsmProviderEntity" -export class SendEmailActionReqDto { - public toAddress?: string | null; - public body?: string | null; -public static Fields = { - toAddress: 'toAddress', - body: 'body', -} -} -export class SendEmailActionResDto { - public queueId?: string | null; -public static Fields = { - queueId: 'queueId', -} -} -export class SendEmailWithProviderActionReqDto { - public emailProvider?: EmailProviderEntity | null; - emailProviderId?: string | null; - public toAddress?: string | null; - public body?: string | null; -public static Fields = { - emailProviderId: 'emailProviderId', - emailProvider$: 'emailProvider', - emailProvider: EmailProviderEntity.Fields, - toAddress: 'toAddress', - body: 'body', -} -} -export class SendEmailWithProviderActionResDto { - public queueId?: string | null; -public static Fields = { - queueId: 'queueId', -} -} -export class GsmSendSmsActionReqDto { - public toNumber?: string | null; - public body?: string | null; -public static Fields = { - toNumber: 'toNumber', - body: 'body', -} -} -export class GsmSendSmsActionResDto { - public queueId?: string | null; -public static Fields = { - queueId: 'queueId', -} -} -export class GsmSendSmsWithProviderActionReqDto { - public gsmProvider?: GsmProviderEntity | null; - gsmProviderId?: string | null; - public toNumber?: string | null; - public body?: string | null; -public static Fields = { - gsmProviderId: 'gsmProviderId', - gsmProvider$: 'gsmProvider', - gsmProvider: GsmProviderEntity.Fields, - toNumber: 'toNumber', - body: 'body', -} -} -export class GsmSendSmsWithProviderActionResDto { - public queueId?: string | null; -public static Fields = { - queueId: 'queueId', -} -} \ No newline at end of file diff --git a/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/GsmSendSms.ts b/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/GsmSendSms.ts new file mode 100644 index 000000000..35bf0c176 --- /dev/null +++ b/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/GsmSendSms.ts @@ -0,0 +1,437 @@ +import { buildUrl } from "../../sdk/common/buildUrl"; +import { + fetchx, + handleFetchResponse, + type FetchxContext, + type PartialDeep, + type TypedRequestInit, + type TypedResponse, +} from "../../sdk/common/fetchx"; +import { type UseMutationOptions, useMutation } from "react-query"; +import { useFetchxContext } from "../../sdk/react/useFetchx"; +import { useState } from "react"; +/** + * Action to communicate with the action GsmSendSms + */ +export type GsmSendSmsActionOptions = { + queryKey?: unknown[]; + qs?: URLSearchParams; +}; +export type GsmSendSmsActionMutationOptions = Omit< + UseMutationOptions, + "mutationFn" +> & + GsmSendSmsActionOptions & { + ctx?: FetchxContext; + onMessage?: (ev: MessageEvent) => void; + overrideUrl?: string; + headers?: Headers; + } & Partial<{ + creatorFn: (item: unknown) => GsmSendSmsActionRes; + }>; +export const useGsmSendSmsAction = ( + options?: GsmSendSmsActionMutationOptions, +) => { + const globalCtx = useFetchxContext(); + const ctx = options?.ctx ?? globalCtx ?? undefined; + const [isCompleted, setCompleteState] = useState(false); + const [response, setResponse] = useState>(); + const fn = (body: GsmSendSmsActionReq) => { + setCompleteState(false); + return GsmSendSmsAction.Fetch( + { + body, + headers: options?.headers, + }, + { + creatorFn: options?.creatorFn, + qs: options?.qs, + ctx, + onMessage: options?.onMessage, + overrideUrl: options?.overrideUrl, + }, + ).then((x) => { + x.done.then(() => { + setCompleteState(true); + }); + setResponse(x.response); + return x.response.result; + }); + }; + const result = useMutation({ + mutationFn: fn, + ...(options || {}), + }); + return { + ...result, + isCompleted, + response, + }; +}; +/** + * GsmSendSmsAction + */ +export class GsmSendSmsAction { + // + static URL = "/gsm/send/sms"; + static NewUrl = (qs?: URLSearchParams) => + buildUrl(GsmSendSmsAction.URL, undefined, qs); + static Method = "post"; + static Fetch$ = async ( + qs?: URLSearchParams, + ctx?: FetchxContext, + init?: TypedRequestInit, + overrideUrl?: string, + ) => { + return fetchx( + overrideUrl ?? GsmSendSmsAction.NewUrl(qs), + { + method: GsmSendSmsAction.Method, + ...(init || {}), + }, + ctx, + ); + }; + static Fetch = async ( + init?: TypedRequestInit, + { + creatorFn, + qs, + ctx, + onMessage, + overrideUrl, + }: { + creatorFn?: ((item: unknown) => GsmSendSmsActionRes) | undefined; + qs?: URLSearchParams; + ctx?: FetchxContext; + onMessage?: (ev: MessageEvent) => void; + overrideUrl?: string; + } = { + creatorFn: (item) => new GsmSendSmsActionRes(item), + }, + ) => { + creatorFn = creatorFn || ((item) => new GsmSendSmsActionRes(item)); + const res = await GsmSendSmsAction.Fetch$(qs, ctx, init, overrideUrl); + return handleFetchResponse( + res, + (item) => (creatorFn ? creatorFn(item) : item), + onMessage, + init?.signal, + ); + }; + static Definition = { + name: "GsmSendSms", + cliName: "sms", + url: "/gsm/send/sms", + method: "post", + description: + "Send a text message using default root notification configuration", + in: { + fields: [ + { + name: "toNumber", + type: "string", + tags: { + validate: "required", + }, + }, + { + name: "body", + type: "string", + tags: { + validate: "required", + }, + }, + ], + }, + out: { + fields: [ + { + name: "queueId", + type: "string", + }, + ], + }, + }; +} +/** + * The base class definition for gsmSendSmsActionReq + **/ +export class GsmSendSmsActionReq { + /** + * + * @type {string} + **/ + #toNumber: string = ""; + /** + * + * @returns {string} + **/ + get toNumber() { + return this.#toNumber; + } + /** + * + * @type {string} + **/ + set toNumber(value: string) { + this.#toNumber = String(value); + } + setToNumber(value: string) { + this.toNumber = value; + return this; + } + /** + * + * @type {string} + **/ + #body: string = ""; + /** + * + * @returns {string} + **/ + get body() { + return this.#body; + } + /** + * + * @type {string} + **/ + set body(value: string) { + this.#body = String(value); + } + setBody(value: string) { + this.body = value; + return this; + } + constructor(data: unknown = undefined) { + if (data === null || data === undefined) { + return; + } + if (typeof data === "string") { + this.applyFromObject(JSON.parse(data)); + } else if (this.#isJsonAppliable(data)) { + this.applyFromObject(data); + } else { + throw new Error( + "Instance cannot be created on an unknown value, check the content being passed. got: " + + typeof data, + ); + } + } + #isJsonAppliable(obj: unknown) { + const g = globalThis as unknown as { Buffer: any; Blob: any }; + const isBuffer = + typeof g.Buffer !== "undefined" && + typeof g.Buffer.isBuffer === "function" && + g.Buffer.isBuffer(obj); + const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; + return ( + obj && + typeof obj === "object" && + !Array.isArray(obj) && + !isBuffer && + !(obj instanceof ArrayBuffer) && + !isBlob + ); + } + /** + * casts the fields of a javascript object into the class properties one by one + **/ + applyFromObject(data = {}) { + const d = data as Partial; + if (d.toNumber !== undefined) { + this.toNumber = d.toNumber; + } + if (d.body !== undefined) { + this.body = d.body; + } + } + /** + * Special toJSON override, since the field are private, + * Json stringify won't see them unless we mention it explicitly. + **/ + toJSON() { + return { + toNumber: this.#toNumber, + body: this.#body, + }; + } + toString() { + return JSON.stringify(this); + } + static get Fields() { + return { + toNumber: "toNumber", + body: "body", + }; + } + /** + * Creates an instance of GsmSendSmsActionReq, and possibleDtoObject + * needs to satisfy the type requirement fully, otherwise typescript compile would + * be complaining. + **/ + static from(possibleDtoObject: GsmSendSmsActionReqType) { + return new GsmSendSmsActionReq(possibleDtoObject); + } + /** + * Creates an instance of GsmSendSmsActionReq, and partialDtoObject + * needs to satisfy the type, but partially, and rest of the content would + * be constructed according to data types and nullability. + **/ + static with(partialDtoObject: PartialDeep) { + return new GsmSendSmsActionReq(partialDtoObject); + } + copyWith( + partial: PartialDeep, + ): InstanceType { + return new GsmSendSmsActionReq({ ...this.toJSON(), ...partial }); + } + clone(): InstanceType { + return new GsmSendSmsActionReq(this.toJSON()); + } +} +export abstract class GsmSendSmsActionReqFactory { + abstract create(data: unknown): GsmSendSmsActionReq; +} +/** + * The base type definition for gsmSendSmsActionReq + **/ +export type GsmSendSmsActionReqType = { + /** + * + * @type {string} + **/ + toNumber: string; + /** + * + * @type {string} + **/ + body: string; +}; +// eslint-disable-next-line @typescript-eslint/no-namespace +export namespace GsmSendSmsActionReqType {} +/** + * The base class definition for gsmSendSmsActionRes + **/ +export class GsmSendSmsActionRes { + /** + * + * @type {string} + **/ + #queueId: string = ""; + /** + * + * @returns {string} + **/ + get queueId() { + return this.#queueId; + } + /** + * + * @type {string} + **/ + set queueId(value: string) { + this.#queueId = String(value); + } + setQueueId(value: string) { + this.queueId = value; + return this; + } + constructor(data: unknown = undefined) { + if (data === null || data === undefined) { + return; + } + if (typeof data === "string") { + this.applyFromObject(JSON.parse(data)); + } else if (this.#isJsonAppliable(data)) { + this.applyFromObject(data); + } else { + throw new Error( + "Instance cannot be created on an unknown value, check the content being passed. got: " + + typeof data, + ); + } + } + #isJsonAppliable(obj: unknown) { + const g = globalThis as unknown as { Buffer: any; Blob: any }; + const isBuffer = + typeof g.Buffer !== "undefined" && + typeof g.Buffer.isBuffer === "function" && + g.Buffer.isBuffer(obj); + const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; + return ( + obj && + typeof obj === "object" && + !Array.isArray(obj) && + !isBuffer && + !(obj instanceof ArrayBuffer) && + !isBlob + ); + } + /** + * casts the fields of a javascript object into the class properties one by one + **/ + applyFromObject(data = {}) { + const d = data as Partial; + if (d.queueId !== undefined) { + this.queueId = d.queueId; + } + } + /** + * Special toJSON override, since the field are private, + * Json stringify won't see them unless we mention it explicitly. + **/ + toJSON() { + return { + queueId: this.#queueId, + }; + } + toString() { + return JSON.stringify(this); + } + static get Fields() { + return { + queueId: "queueId", + }; + } + /** + * Creates an instance of GsmSendSmsActionRes, and possibleDtoObject + * needs to satisfy the type requirement fully, otherwise typescript compile would + * be complaining. + **/ + static from(possibleDtoObject: GsmSendSmsActionResType) { + return new GsmSendSmsActionRes(possibleDtoObject); + } + /** + * Creates an instance of GsmSendSmsActionRes, and partialDtoObject + * needs to satisfy the type, but partially, and rest of the content would + * be constructed according to data types and nullability. + **/ + static with(partialDtoObject: PartialDeep) { + return new GsmSendSmsActionRes(partialDtoObject); + } + copyWith( + partial: PartialDeep, + ): InstanceType { + return new GsmSendSmsActionRes({ ...this.toJSON(), ...partial }); + } + clone(): InstanceType { + return new GsmSendSmsActionRes(this.toJSON()); + } +} +export abstract class GsmSendSmsActionResFactory { + abstract create(data: unknown): GsmSendSmsActionRes; +} +/** + * The base type definition for gsmSendSmsActionRes + **/ +export type GsmSendSmsActionResType = { + /** + * + * @type {string} + **/ + queueId: string; +}; +// eslint-disable-next-line @typescript-eslint/no-namespace +export namespace GsmSendSmsActionResType {} diff --git a/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/GsmSendSmsWithProvider.ts b/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/GsmSendSmsWithProvider.ts new file mode 100644 index 000000000..27929614c --- /dev/null +++ b/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/GsmSendSmsWithProvider.ts @@ -0,0 +1,495 @@ +import { buildUrl } from "../../sdk/common/buildUrl"; +import { + fetchx, + handleFetchResponse, + type FetchxContext, + type PartialDeep, + type TypedRequestInit, + type TypedResponse, +} from "../../sdk/common/fetchx"; +import { type UseMutationOptions, useMutation } from "react-query"; +import { useFetchxContext } from "../../sdk/react/useFetchx"; +import { useState } from "react"; +/** + * Action to communicate with the action GsmSendSmsWithProvider + */ +export type GsmSendSmsWithProviderActionOptions = { + queryKey?: unknown[]; + qs?: URLSearchParams; +}; +export type GsmSendSmsWithProviderActionMutationOptions = Omit< + UseMutationOptions, + "mutationFn" +> & + GsmSendSmsWithProviderActionOptions & { + ctx?: FetchxContext; + onMessage?: (ev: MessageEvent) => void; + overrideUrl?: string; + headers?: Headers; + } & Partial<{ + creatorFn: (item: unknown) => GsmSendSmsWithProviderActionRes; + }>; +export const useGsmSendSmsWithProviderAction = ( + options?: GsmSendSmsWithProviderActionMutationOptions, +) => { + const globalCtx = useFetchxContext(); + const ctx = options?.ctx ?? globalCtx ?? undefined; + const [isCompleted, setCompleteState] = useState(false); + const [response, setResponse] = useState>(); + const fn = (body: GsmSendSmsWithProviderActionReq) => { + setCompleteState(false); + return GsmSendSmsWithProviderAction.Fetch( + { + body, + headers: options?.headers, + }, + { + creatorFn: options?.creatorFn, + qs: options?.qs, + ctx, + onMessage: options?.onMessage, + overrideUrl: options?.overrideUrl, + }, + ).then((x) => { + x.done.then(() => { + setCompleteState(true); + }); + setResponse(x.response); + return x.response.result; + }); + }; + const result = useMutation({ + mutationFn: fn, + ...(options || {}), + }); + return { + ...result, + isCompleted, + response, + }; +}; +/** + * GsmSendSmsWithProviderAction + */ +export class GsmSendSmsWithProviderAction { + // + static URL = "/gsmProvider/send/sms"; + static NewUrl = (qs?: URLSearchParams) => + buildUrl(GsmSendSmsWithProviderAction.URL, undefined, qs); + static Method = "post"; + static Fetch$ = async ( + qs?: URLSearchParams, + ctx?: FetchxContext, + init?: TypedRequestInit, + overrideUrl?: string, + ) => { + return fetchx< + GsmSendSmsWithProviderActionRes, + GsmSendSmsWithProviderActionReq, + unknown + >( + overrideUrl ?? GsmSendSmsWithProviderAction.NewUrl(qs), + { + method: GsmSendSmsWithProviderAction.Method, + ...(init || {}), + }, + ctx, + ); + }; + static Fetch = async ( + init?: TypedRequestInit, + { + creatorFn, + qs, + ctx, + onMessage, + overrideUrl, + }: { + creatorFn?: + | ((item: unknown) => GsmSendSmsWithProviderActionRes) + | undefined; + qs?: URLSearchParams; + ctx?: FetchxContext; + onMessage?: (ev: MessageEvent) => void; + overrideUrl?: string; + } = { + creatorFn: (item) => new GsmSendSmsWithProviderActionRes(item), + }, + ) => { + creatorFn = + creatorFn || ((item) => new GsmSendSmsWithProviderActionRes(item)); + const res = await GsmSendSmsWithProviderAction.Fetch$( + qs, + ctx, + init, + overrideUrl, + ); + return handleFetchResponse( + res, + (item) => (creatorFn ? creatorFn(item) : item), + onMessage, + init?.signal, + ); + }; + static Definition = { + name: "GsmSendSmsWithProvider", + cliName: "smsp", + url: "/gsmProvider/send/sms", + method: "post", + description: "Send a text message using an specific gsm provider", + in: { + fields: [ + { + name: "gsmProviderId", + type: "string", + }, + { + name: "toNumber", + type: "string", + tags: { + validate: "required", + }, + }, + { + name: "body", + type: "string", + tags: { + validate: "required", + }, + }, + ], + }, + out: { + fields: [ + { + name: "queueId", + type: "string", + }, + ], + }, + }; +} +/** + * The base class definition for gsmSendSmsWithProviderActionReq + **/ +export class GsmSendSmsWithProviderActionReq { + /** + * + * @type {string} + **/ + #gsmProviderId: string = ""; + /** + * + * @returns {string} + **/ + get gsmProviderId() { + return this.#gsmProviderId; + } + /** + * + * @type {string} + **/ + set gsmProviderId(value: string) { + this.#gsmProviderId = String(value); + } + setGsmProviderId(value: string) { + this.gsmProviderId = value; + return this; + } + /** + * + * @type {string} + **/ + #toNumber: string = ""; + /** + * + * @returns {string} + **/ + get toNumber() { + return this.#toNumber; + } + /** + * + * @type {string} + **/ + set toNumber(value: string) { + this.#toNumber = String(value); + } + setToNumber(value: string) { + this.toNumber = value; + return this; + } + /** + * + * @type {string} + **/ + #body: string = ""; + /** + * + * @returns {string} + **/ + get body() { + return this.#body; + } + /** + * + * @type {string} + **/ + set body(value: string) { + this.#body = String(value); + } + setBody(value: string) { + this.body = value; + return this; + } + constructor(data: unknown = undefined) { + if (data === null || data === undefined) { + return; + } + if (typeof data === "string") { + this.applyFromObject(JSON.parse(data)); + } else if (this.#isJsonAppliable(data)) { + this.applyFromObject(data); + } else { + throw new Error( + "Instance cannot be created on an unknown value, check the content being passed. got: " + + typeof data, + ); + } + } + #isJsonAppliable(obj: unknown) { + const g = globalThis as unknown as { Buffer: any; Blob: any }; + const isBuffer = + typeof g.Buffer !== "undefined" && + typeof g.Buffer.isBuffer === "function" && + g.Buffer.isBuffer(obj); + const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; + return ( + obj && + typeof obj === "object" && + !Array.isArray(obj) && + !isBuffer && + !(obj instanceof ArrayBuffer) && + !isBlob + ); + } + /** + * casts the fields of a javascript object into the class properties one by one + **/ + applyFromObject(data = {}) { + const d = data as Partial; + if (d.gsmProviderId !== undefined) { + this.gsmProviderId = d.gsmProviderId; + } + if (d.toNumber !== undefined) { + this.toNumber = d.toNumber; + } + if (d.body !== undefined) { + this.body = d.body; + } + } + /** + * Special toJSON override, since the field are private, + * Json stringify won't see them unless we mention it explicitly. + **/ + toJSON() { + return { + gsmProviderId: this.#gsmProviderId, + toNumber: this.#toNumber, + body: this.#body, + }; + } + toString() { + return JSON.stringify(this); + } + static get Fields() { + return { + gsmProviderId: "gsmProviderId", + toNumber: "toNumber", + body: "body", + }; + } + /** + * Creates an instance of GsmSendSmsWithProviderActionReq, and possibleDtoObject + * needs to satisfy the type requirement fully, otherwise typescript compile would + * be complaining. + **/ + static from(possibleDtoObject: GsmSendSmsWithProviderActionReqType) { + return new GsmSendSmsWithProviderActionReq(possibleDtoObject); + } + /** + * Creates an instance of GsmSendSmsWithProviderActionReq, and partialDtoObject + * needs to satisfy the type, but partially, and rest of the content would + * be constructed according to data types and nullability. + **/ + static with( + partialDtoObject: PartialDeep, + ) { + return new GsmSendSmsWithProviderActionReq(partialDtoObject); + } + copyWith( + partial: PartialDeep, + ): InstanceType { + return new GsmSendSmsWithProviderActionReq({ + ...this.toJSON(), + ...partial, + }); + } + clone(): InstanceType { + return new GsmSendSmsWithProviderActionReq(this.toJSON()); + } +} +export abstract class GsmSendSmsWithProviderActionReqFactory { + abstract create(data: unknown): GsmSendSmsWithProviderActionReq; +} +/** + * The base type definition for gsmSendSmsWithProviderActionReq + **/ +export type GsmSendSmsWithProviderActionReqType = { + /** + * + * @type {string} + **/ + gsmProviderId: string; + /** + * + * @type {string} + **/ + toNumber: string; + /** + * + * @type {string} + **/ + body: string; +}; +// eslint-disable-next-line @typescript-eslint/no-namespace +export namespace GsmSendSmsWithProviderActionReqType {} +/** + * The base class definition for gsmSendSmsWithProviderActionRes + **/ +export class GsmSendSmsWithProviderActionRes { + /** + * + * @type {string} + **/ + #queueId: string = ""; + /** + * + * @returns {string} + **/ + get queueId() { + return this.#queueId; + } + /** + * + * @type {string} + **/ + set queueId(value: string) { + this.#queueId = String(value); + } + setQueueId(value: string) { + this.queueId = value; + return this; + } + constructor(data: unknown = undefined) { + if (data === null || data === undefined) { + return; + } + if (typeof data === "string") { + this.applyFromObject(JSON.parse(data)); + } else if (this.#isJsonAppliable(data)) { + this.applyFromObject(data); + } else { + throw new Error( + "Instance cannot be created on an unknown value, check the content being passed. got: " + + typeof data, + ); + } + } + #isJsonAppliable(obj: unknown) { + const g = globalThis as unknown as { Buffer: any; Blob: any }; + const isBuffer = + typeof g.Buffer !== "undefined" && + typeof g.Buffer.isBuffer === "function" && + g.Buffer.isBuffer(obj); + const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; + return ( + obj && + typeof obj === "object" && + !Array.isArray(obj) && + !isBuffer && + !(obj instanceof ArrayBuffer) && + !isBlob + ); + } + /** + * casts the fields of a javascript object into the class properties one by one + **/ + applyFromObject(data = {}) { + const d = data as Partial; + if (d.queueId !== undefined) { + this.queueId = d.queueId; + } + } + /** + * Special toJSON override, since the field are private, + * Json stringify won't see them unless we mention it explicitly. + **/ + toJSON() { + return { + queueId: this.#queueId, + }; + } + toString() { + return JSON.stringify(this); + } + static get Fields() { + return { + queueId: "queueId", + }; + } + /** + * Creates an instance of GsmSendSmsWithProviderActionRes, and possibleDtoObject + * needs to satisfy the type requirement fully, otherwise typescript compile would + * be complaining. + **/ + static from(possibleDtoObject: GsmSendSmsWithProviderActionResType) { + return new GsmSendSmsWithProviderActionRes(possibleDtoObject); + } + /** + * Creates an instance of GsmSendSmsWithProviderActionRes, and partialDtoObject + * needs to satisfy the type, but partially, and rest of the content would + * be constructed according to data types and nullability. + **/ + static with( + partialDtoObject: PartialDeep, + ) { + return new GsmSendSmsWithProviderActionRes(partialDtoObject); + } + copyWith( + partial: PartialDeep, + ): InstanceType { + return new GsmSendSmsWithProviderActionRes({ + ...this.toJSON(), + ...partial, + }); + } + clone(): InstanceType { + return new GsmSendSmsWithProviderActionRes(this.toJSON()); + } +} +export abstract class GsmSendSmsWithProviderActionResFactory { + abstract create(data: unknown): GsmSendSmsWithProviderActionRes; +} +/** + * The base type definition for gsmSendSmsWithProviderActionRes + **/ +export type GsmSendSmsWithProviderActionResType = { + /** + * + * @type {string} + **/ + queueId: string; +}; +// eslint-disable-next-line @typescript-eslint/no-namespace +export namespace GsmSendSmsWithProviderActionResType {} diff --git a/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/SendEmail.ts b/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/SendEmail.ts new file mode 100644 index 000000000..0935ce59e --- /dev/null +++ b/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/SendEmail.ts @@ -0,0 +1,436 @@ +import { buildUrl } from "../../sdk/common/buildUrl"; +import { + fetchx, + handleFetchResponse, + type FetchxContext, + type PartialDeep, + type TypedRequestInit, + type TypedResponse, +} from "../../sdk/common/fetchx"; +import { type UseMutationOptions, useMutation } from "react-query"; +import { useFetchxContext } from "../../sdk/react/useFetchx"; +import { useState } from "react"; +/** + * Action to communicate with the action SendEmail + */ +export type SendEmailActionOptions = { + queryKey?: unknown[]; + qs?: URLSearchParams; +}; +export type SendEmailActionMutationOptions = Omit< + UseMutationOptions, + "mutationFn" +> & + SendEmailActionOptions & { + ctx?: FetchxContext; + onMessage?: (ev: MessageEvent) => void; + overrideUrl?: string; + headers?: Headers; + } & Partial<{ + creatorFn: (item: unknown) => SendEmailActionRes; + }>; +export const useSendEmailAction = ( + options?: SendEmailActionMutationOptions, +) => { + const globalCtx = useFetchxContext(); + const ctx = options?.ctx ?? globalCtx ?? undefined; + const [isCompleted, setCompleteState] = useState(false); + const [response, setResponse] = useState>(); + const fn = (body: SendEmailActionReq) => { + setCompleteState(false); + return SendEmailAction.Fetch( + { + body, + headers: options?.headers, + }, + { + creatorFn: options?.creatorFn, + qs: options?.qs, + ctx, + onMessage: options?.onMessage, + overrideUrl: options?.overrideUrl, + }, + ).then((x) => { + x.done.then(() => { + setCompleteState(true); + }); + setResponse(x.response); + return x.response.result; + }); + }; + const result = useMutation({ + mutationFn: fn, + ...(options || {}), + }); + return { + ...result, + isCompleted, + response, + }; +}; +/** + * SendEmailAction + */ +export class SendEmailAction { + // + static URL = "/email/send"; + static NewUrl = (qs?: URLSearchParams) => + buildUrl(SendEmailAction.URL, undefined, qs); + static Method = "post"; + static Fetch$ = async ( + qs?: URLSearchParams, + ctx?: FetchxContext, + init?: TypedRequestInit, + overrideUrl?: string, + ) => { + return fetchx( + overrideUrl ?? SendEmailAction.NewUrl(qs), + { + method: SendEmailAction.Method, + ...(init || {}), + }, + ctx, + ); + }; + static Fetch = async ( + init?: TypedRequestInit, + { + creatorFn, + qs, + ctx, + onMessage, + overrideUrl, + }: { + creatorFn?: ((item: unknown) => SendEmailActionRes) | undefined; + qs?: URLSearchParams; + ctx?: FetchxContext; + onMessage?: (ev: MessageEvent) => void; + overrideUrl?: string; + } = { + creatorFn: (item) => new SendEmailActionRes(item), + }, + ) => { + creatorFn = creatorFn || ((item) => new SendEmailActionRes(item)); + const res = await SendEmailAction.Fetch$(qs, ctx, init, overrideUrl); + return handleFetchResponse( + res, + (item) => (creatorFn ? creatorFn(item) : item), + onMessage, + init?.signal, + ); + }; + static Definition = { + name: "SendEmail", + cliName: "email", + url: "/email/send", + method: "post", + description: "Send a email using default root notification configuration", + in: { + fields: [ + { + name: "toAddress", + type: "string", + tags: { + validate: "required", + }, + }, + { + name: "body", + type: "string", + tags: { + validate: "required", + }, + }, + ], + }, + out: { + fields: [ + { + name: "queueId", + type: "string", + }, + ], + }, + }; +} +/** + * The base class definition for sendEmailActionReq + **/ +export class SendEmailActionReq { + /** + * + * @type {string} + **/ + #toAddress: string = ""; + /** + * + * @returns {string} + **/ + get toAddress() { + return this.#toAddress; + } + /** + * + * @type {string} + **/ + set toAddress(value: string) { + this.#toAddress = String(value); + } + setToAddress(value: string) { + this.toAddress = value; + return this; + } + /** + * + * @type {string} + **/ + #body: string = ""; + /** + * + * @returns {string} + **/ + get body() { + return this.#body; + } + /** + * + * @type {string} + **/ + set body(value: string) { + this.#body = String(value); + } + setBody(value: string) { + this.body = value; + return this; + } + constructor(data: unknown = undefined) { + if (data === null || data === undefined) { + return; + } + if (typeof data === "string") { + this.applyFromObject(JSON.parse(data)); + } else if (this.#isJsonAppliable(data)) { + this.applyFromObject(data); + } else { + throw new Error( + "Instance cannot be created on an unknown value, check the content being passed. got: " + + typeof data, + ); + } + } + #isJsonAppliable(obj: unknown) { + const g = globalThis as unknown as { Buffer: any; Blob: any }; + const isBuffer = + typeof g.Buffer !== "undefined" && + typeof g.Buffer.isBuffer === "function" && + g.Buffer.isBuffer(obj); + const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; + return ( + obj && + typeof obj === "object" && + !Array.isArray(obj) && + !isBuffer && + !(obj instanceof ArrayBuffer) && + !isBlob + ); + } + /** + * casts the fields of a javascript object into the class properties one by one + **/ + applyFromObject(data = {}) { + const d = data as Partial; + if (d.toAddress !== undefined) { + this.toAddress = d.toAddress; + } + if (d.body !== undefined) { + this.body = d.body; + } + } + /** + * Special toJSON override, since the field are private, + * Json stringify won't see them unless we mention it explicitly. + **/ + toJSON() { + return { + toAddress: this.#toAddress, + body: this.#body, + }; + } + toString() { + return JSON.stringify(this); + } + static get Fields() { + return { + toAddress: "toAddress", + body: "body", + }; + } + /** + * Creates an instance of SendEmailActionReq, and possibleDtoObject + * needs to satisfy the type requirement fully, otherwise typescript compile would + * be complaining. + **/ + static from(possibleDtoObject: SendEmailActionReqType) { + return new SendEmailActionReq(possibleDtoObject); + } + /** + * Creates an instance of SendEmailActionReq, and partialDtoObject + * needs to satisfy the type, but partially, and rest of the content would + * be constructed according to data types and nullability. + **/ + static with(partialDtoObject: PartialDeep) { + return new SendEmailActionReq(partialDtoObject); + } + copyWith( + partial: PartialDeep, + ): InstanceType { + return new SendEmailActionReq({ ...this.toJSON(), ...partial }); + } + clone(): InstanceType { + return new SendEmailActionReq(this.toJSON()); + } +} +export abstract class SendEmailActionReqFactory { + abstract create(data: unknown): SendEmailActionReq; +} +/** + * The base type definition for sendEmailActionReq + **/ +export type SendEmailActionReqType = { + /** + * + * @type {string} + **/ + toAddress: string; + /** + * + * @type {string} + **/ + body: string; +}; +// eslint-disable-next-line @typescript-eslint/no-namespace +export namespace SendEmailActionReqType {} +/** + * The base class definition for sendEmailActionRes + **/ +export class SendEmailActionRes { + /** + * + * @type {string} + **/ + #queueId: string = ""; + /** + * + * @returns {string} + **/ + get queueId() { + return this.#queueId; + } + /** + * + * @type {string} + **/ + set queueId(value: string) { + this.#queueId = String(value); + } + setQueueId(value: string) { + this.queueId = value; + return this; + } + constructor(data: unknown = undefined) { + if (data === null || data === undefined) { + return; + } + if (typeof data === "string") { + this.applyFromObject(JSON.parse(data)); + } else if (this.#isJsonAppliable(data)) { + this.applyFromObject(data); + } else { + throw new Error( + "Instance cannot be created on an unknown value, check the content being passed. got: " + + typeof data, + ); + } + } + #isJsonAppliable(obj: unknown) { + const g = globalThis as unknown as { Buffer: any; Blob: any }; + const isBuffer = + typeof g.Buffer !== "undefined" && + typeof g.Buffer.isBuffer === "function" && + g.Buffer.isBuffer(obj); + const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; + return ( + obj && + typeof obj === "object" && + !Array.isArray(obj) && + !isBuffer && + !(obj instanceof ArrayBuffer) && + !isBlob + ); + } + /** + * casts the fields of a javascript object into the class properties one by one + **/ + applyFromObject(data = {}) { + const d = data as Partial; + if (d.queueId !== undefined) { + this.queueId = d.queueId; + } + } + /** + * Special toJSON override, since the field are private, + * Json stringify won't see them unless we mention it explicitly. + **/ + toJSON() { + return { + queueId: this.#queueId, + }; + } + toString() { + return JSON.stringify(this); + } + static get Fields() { + return { + queueId: "queueId", + }; + } + /** + * Creates an instance of SendEmailActionRes, and possibleDtoObject + * needs to satisfy the type requirement fully, otherwise typescript compile would + * be complaining. + **/ + static from(possibleDtoObject: SendEmailActionResType) { + return new SendEmailActionRes(possibleDtoObject); + } + /** + * Creates an instance of SendEmailActionRes, and partialDtoObject + * needs to satisfy the type, but partially, and rest of the content would + * be constructed according to data types and nullability. + **/ + static with(partialDtoObject: PartialDeep) { + return new SendEmailActionRes(partialDtoObject); + } + copyWith( + partial: PartialDeep, + ): InstanceType { + return new SendEmailActionRes({ ...this.toJSON(), ...partial }); + } + clone(): InstanceType { + return new SendEmailActionRes(this.toJSON()); + } +} +export abstract class SendEmailActionResFactory { + abstract create(data: unknown): SendEmailActionRes; +} +/** + * The base type definition for sendEmailActionRes + **/ +export type SendEmailActionResType = { + /** + * + * @type {string} + **/ + queueId: string; +}; +// eslint-disable-next-line @typescript-eslint/no-namespace +export namespace SendEmailActionResType {} diff --git a/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/SendEmailWithProvider.ts b/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/SendEmailWithProvider.ts new file mode 100644 index 000000000..5fafe49b4 --- /dev/null +++ b/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/SendEmailWithProvider.ts @@ -0,0 +1,511 @@ +import { EmailProviderEntity } from "./EmailProviderEntity"; +import { buildUrl } from "../../sdk/common/buildUrl"; +import { + fetchx, + handleFetchResponse, + type FetchxContext, + type PartialDeep, + type TypedRequestInit, + type TypedResponse, +} from "../../sdk/common/fetchx"; +import { type UseMutationOptions, useMutation } from "react-query"; +import { useFetchxContext } from "../../sdk/react/useFetchx"; +import { useState } from "react"; +import { withPrefix } from "../../sdk/common/withPrefix"; +/** + * Action to communicate with the action SendEmailWithProvider + */ +export type SendEmailWithProviderActionOptions = { + queryKey?: unknown[]; + qs?: URLSearchParams; +}; +export type SendEmailWithProviderActionMutationOptions = Omit< + UseMutationOptions, + "mutationFn" +> & + SendEmailWithProviderActionOptions & { + ctx?: FetchxContext; + onMessage?: (ev: MessageEvent) => void; + overrideUrl?: string; + headers?: Headers; + } & Partial<{ + creatorFn: (item: unknown) => SendEmailWithProviderActionRes; + }>; +export const useSendEmailWithProviderAction = ( + options?: SendEmailWithProviderActionMutationOptions, +) => { + const globalCtx = useFetchxContext(); + const ctx = options?.ctx ?? globalCtx ?? undefined; + const [isCompleted, setCompleteState] = useState(false); + const [response, setResponse] = useState>(); + const fn = (body: SendEmailWithProviderActionReq) => { + setCompleteState(false); + return SendEmailWithProviderAction.Fetch( + { + body, + headers: options?.headers, + }, + { + creatorFn: options?.creatorFn, + qs: options?.qs, + ctx, + onMessage: options?.onMessage, + overrideUrl: options?.overrideUrl, + }, + ).then((x) => { + x.done.then(() => { + setCompleteState(true); + }); + setResponse(x.response); + return x.response.result; + }); + }; + const result = useMutation({ + mutationFn: fn, + ...(options || {}), + }); + return { + ...result, + isCompleted, + response, + }; +}; +/** + * SendEmailWithProviderAction + */ +export class SendEmailWithProviderAction { + // + static URL = "/emailProvider/send"; + static NewUrl = (qs?: URLSearchParams) => + buildUrl(SendEmailWithProviderAction.URL, undefined, qs); + static Method = "post"; + static Fetch$ = async ( + qs?: URLSearchParams, + ctx?: FetchxContext, + init?: TypedRequestInit, + overrideUrl?: string, + ) => { + return fetchx< + SendEmailWithProviderActionRes, + SendEmailWithProviderActionReq, + unknown + >( + overrideUrl ?? SendEmailWithProviderAction.NewUrl(qs), + { + method: SendEmailWithProviderAction.Method, + ...(init || {}), + }, + ctx, + ); + }; + static Fetch = async ( + init?: TypedRequestInit, + { + creatorFn, + qs, + ctx, + onMessage, + overrideUrl, + }: { + creatorFn?: + | ((item: unknown) => SendEmailWithProviderActionRes) + | undefined; + qs?: URLSearchParams; + ctx?: FetchxContext; + onMessage?: (ev: MessageEvent) => void; + overrideUrl?: string; + } = { + creatorFn: (item) => new SendEmailWithProviderActionRes(item), + }, + ) => { + creatorFn = + creatorFn || ((item) => new SendEmailWithProviderActionRes(item)); + const res = await SendEmailWithProviderAction.Fetch$( + qs, + ctx, + init, + overrideUrl, + ); + return handleFetchResponse( + res, + (item) => (creatorFn ? creatorFn(item) : item), + onMessage, + init?.signal, + ); + }; + static Definition = { + name: "SendEmailWithProvider", + cliName: "emailp", + url: "/emailProvider/send", + method: "post", + description: "Send a text message using an specific gsm provider", + in: { + fields: [ + { + name: "emailProvider", + type: "one", + target: "EmailProviderEntity", + }, + { + name: "toAddress", + type: "string", + tags: { + validate: "required", + }, + }, + { + name: "body", + type: "string", + tags: { + validate: "required", + }, + }, + ], + }, + out: { + fields: [ + { + name: "queueId", + type: "string", + }, + ], + }, + }; +} +/** + * The base class definition for sendEmailWithProviderActionReq + **/ +export class SendEmailWithProviderActionReq { + /** + * + * @type {EmailProviderEntity} + **/ + #emailProvider!: EmailProviderEntity; + /** + * + * @returns {EmailProviderEntity} + **/ + get emailProvider() { + return this.#emailProvider; + } + /** + * + * @type {EmailProviderEntity} + **/ + set emailProvider(value: EmailProviderEntity) { + // For objects, the sub type needs to always be instance of the sub class. + if (value instanceof EmailProviderEntity) { + this.#emailProvider = value; + } else { + this.#emailProvider = new EmailProviderEntity(value); + } + } + setEmailProvider(value: EmailProviderEntity) { + this.emailProvider = value; + return this; + } + /** + * + * @type {string} + **/ + #toAddress: string = ""; + /** + * + * @returns {string} + **/ + get toAddress() { + return this.#toAddress; + } + /** + * + * @type {string} + **/ + set toAddress(value: string) { + this.#toAddress = String(value); + } + setToAddress(value: string) { + this.toAddress = value; + return this; + } + /** + * + * @type {string} + **/ + #body: string = ""; + /** + * + * @returns {string} + **/ + get body() { + return this.#body; + } + /** + * + * @type {string} + **/ + set body(value: string) { + this.#body = String(value); + } + setBody(value: string) { + this.body = value; + return this; + } + constructor(data: unknown = undefined) { + if (data === null || data === undefined) { + this.#lateInitFields(); + return; + } + if (typeof data === "string") { + this.applyFromObject(JSON.parse(data)); + } else if (this.#isJsonAppliable(data)) { + this.applyFromObject(data); + } else { + throw new Error( + "Instance cannot be created on an unknown value, check the content being passed. got: " + + typeof data, + ); + } + } + #isJsonAppliable(obj: unknown) { + const g = globalThis as unknown as { Buffer: any; Blob: any }; + const isBuffer = + typeof g.Buffer !== "undefined" && + typeof g.Buffer.isBuffer === "function" && + g.Buffer.isBuffer(obj); + const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; + return ( + obj && + typeof obj === "object" && + !Array.isArray(obj) && + !isBuffer && + !(obj instanceof ArrayBuffer) && + !isBlob + ); + } + /** + * casts the fields of a javascript object into the class properties one by one + **/ + applyFromObject(data = {}) { + const d = data as Partial; + if (d.emailProvider !== undefined) { + this.emailProvider = d.emailProvider; + } + if (d.toAddress !== undefined) { + this.toAddress = d.toAddress; + } + if (d.body !== undefined) { + this.body = d.body; + } + this.#lateInitFields(data); + } + /** + * These are the class instances, which need to be initialised, regardless of the constructor incoming data + **/ + #lateInitFields(data = {}) { + const d = data as Partial; + if (!(d.emailProvider instanceof EmailProviderEntity)) { + this.emailProvider = new EmailProviderEntity(d.emailProvider || {}); + } + } + /** + * Special toJSON override, since the field are private, + * Json stringify won't see them unless we mention it explicitly. + **/ + toJSON() { + return { + emailProvider: this.#emailProvider, + toAddress: this.#toAddress, + body: this.#body, + }; + } + toString() { + return JSON.stringify(this); + } + static get Fields() { + return { + emailProvider$: "emailProvider", + get emailProvider() { + return withPrefix("emailProvider", EmailProviderEntity.Fields); + }, + toAddress: "toAddress", + body: "body", + }; + } + /** + * Creates an instance of SendEmailWithProviderActionReq, and possibleDtoObject + * needs to satisfy the type requirement fully, otherwise typescript compile would + * be complaining. + **/ + static from(possibleDtoObject: SendEmailWithProviderActionReqType) { + return new SendEmailWithProviderActionReq(possibleDtoObject); + } + /** + * Creates an instance of SendEmailWithProviderActionReq, and partialDtoObject + * needs to satisfy the type, but partially, and rest of the content would + * be constructed according to data types and nullability. + **/ + static with( + partialDtoObject: PartialDeep, + ) { + return new SendEmailWithProviderActionReq(partialDtoObject); + } + copyWith( + partial: PartialDeep, + ): InstanceType { + return new SendEmailWithProviderActionReq({ ...this.toJSON(), ...partial }); + } + clone(): InstanceType { + return new SendEmailWithProviderActionReq(this.toJSON()); + } +} +export abstract class SendEmailWithProviderActionReqFactory { + abstract create(data: unknown): SendEmailWithProviderActionReq; +} +/** + * The base type definition for sendEmailWithProviderActionReq + **/ +export type SendEmailWithProviderActionReqType = { + /** + * + * @type {EmailProviderEntity} + **/ + emailProvider: EmailProviderEntity; + /** + * + * @type {string} + **/ + toAddress: string; + /** + * + * @type {string} + **/ + body: string; +}; +// eslint-disable-next-line @typescript-eslint/no-namespace +export namespace SendEmailWithProviderActionReqType {} +/** + * The base class definition for sendEmailWithProviderActionRes + **/ +export class SendEmailWithProviderActionRes { + /** + * + * @type {string} + **/ + #queueId: string = ""; + /** + * + * @returns {string} + **/ + get queueId() { + return this.#queueId; + } + /** + * + * @type {string} + **/ + set queueId(value: string) { + this.#queueId = String(value); + } + setQueueId(value: string) { + this.queueId = value; + return this; + } + constructor(data: unknown = undefined) { + if (data === null || data === undefined) { + return; + } + if (typeof data === "string") { + this.applyFromObject(JSON.parse(data)); + } else if (this.#isJsonAppliable(data)) { + this.applyFromObject(data); + } else { + throw new Error( + "Instance cannot be created on an unknown value, check the content being passed. got: " + + typeof data, + ); + } + } + #isJsonAppliable(obj: unknown) { + const g = globalThis as unknown as { Buffer: any; Blob: any }; + const isBuffer = + typeof g.Buffer !== "undefined" && + typeof g.Buffer.isBuffer === "function" && + g.Buffer.isBuffer(obj); + const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; + return ( + obj && + typeof obj === "object" && + !Array.isArray(obj) && + !isBuffer && + !(obj instanceof ArrayBuffer) && + !isBlob + ); + } + /** + * casts the fields of a javascript object into the class properties one by one + **/ + applyFromObject(data = {}) { + const d = data as Partial; + if (d.queueId !== undefined) { + this.queueId = d.queueId; + } + } + /** + * Special toJSON override, since the field are private, + * Json stringify won't see them unless we mention it explicitly. + **/ + toJSON() { + return { + queueId: this.#queueId, + }; + } + toString() { + return JSON.stringify(this); + } + static get Fields() { + return { + queueId: "queueId", + }; + } + /** + * Creates an instance of SendEmailWithProviderActionRes, and possibleDtoObject + * needs to satisfy the type requirement fully, otherwise typescript compile would + * be complaining. + **/ + static from(possibleDtoObject: SendEmailWithProviderActionResType) { + return new SendEmailWithProviderActionRes(possibleDtoObject); + } + /** + * Creates an instance of SendEmailWithProviderActionRes, and partialDtoObject + * needs to satisfy the type, but partially, and rest of the content would + * be constructed according to data types and nullability. + **/ + static with( + partialDtoObject: PartialDeep, + ) { + return new SendEmailWithProviderActionRes(partialDtoObject); + } + copyWith( + partial: PartialDeep, + ): InstanceType { + return new SendEmailWithProviderActionRes({ ...this.toJSON(), ...partial }); + } + clone(): InstanceType { + return new SendEmailWithProviderActionRes(this.toJSON()); + } +} +export abstract class SendEmailWithProviderActionResFactory { + abstract create(data: unknown): SendEmailWithProviderActionRes; +} +/** + * The base type definition for sendEmailWithProviderActionRes + **/ +export type SendEmailWithProviderActionResType = { + /** + * + * @type {string} + **/ + queueId: string; +}; +// eslint-disable-next-line @typescript-eslint/no-namespace +export namespace SendEmailWithProviderActionResType {} diff --git a/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/usePostEmailProviderSend.ts b/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/usePostEmailProviderSend.ts deleted file mode 100644 index 3b8426304..000000000 --- a/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/usePostEmailProviderSend.ts +++ /dev/null @@ -1,92 +0,0 @@ -/* -* Generated by fireback 1.2.5 -* Written by Ali Torabi. -* The code is generated for react-query@v3.39.3 -* Checkout the repository for licenses and contribution: https://github.com/torabian/fireback -*/ -import { type FormikHelpers } from "formik"; -import { useContext, useState, useRef } from "react"; -import { useMutation } from "react-query"; -import { - execApiFn, - type IResponse, - mutationErrorsToFormik, - type IResponseList -} from "../../core/http-tools"; -import { - RemoteQueryContext, - type UseRemoteQuery, - queryBeforeSend, -} from "../../core/react-tools"; - import { - SendEmailWithProviderActionReqDto, - SendEmailWithProviderActionResDto, - } from "../abac/AbacActionsDto" -export function usePostEmailProviderSend( - props?: UseRemoteQuery & { - } -) { - let {queryClient, query, execFnOverride} = props || {}; - query = query || {} - const { options, execFn } = useContext(RemoteQueryContext); - // Calculare the function which will do the remote calls. - // We consider to use global override, this specific override, or default which - // comes with the sdk. - const rpcFn = execFnOverride - ? execFnOverride(options) - : execFn - ? execFn(options) - : execApiFn(options); - // Url of the remote affix. - const url = "/emailProvider/send".substr(1); - let computedUrl = `${url}?${new URLSearchParams( - queryBeforeSend(query) - ).toString()}`; - let completeRouteUrls = true; - // Attach the details of the request to the fn - const fn = (body: any) => rpcFn("POST", computedUrl, body); - const mutation = useMutation< - IResponse, - IResponse, - Partial - >(fn); - // Only entities are having a store in front-end - const fnUpdater = ( - data: IResponseList | undefined, - item: IResponse - ) => { - if (!data) { - return { - data: { items: [] }, - }; - } - // To me it seems this is not a good or any correct strategy to update the store. - // When we are posting, we want to add it there, that's it. Not updating it. - // We have patch, but also posting with ID is possible. - if (data.data && item?.data) { - data.data.items = [item.data, ...(data?.data?.items || [])]; - } - return data; - }; - const submit = ( - values: Partial, - formikProps?: FormikHelpers> - ): Promise> => { - return new Promise((resolve, reject) => { - mutation.mutate(values, { - onSuccess(response: IResponse) { - queryClient?.setQueryData>( - "*abac.SendEmailWithProviderActionResDto", - (data) => fnUpdater(data, response) as any - ); - resolve(response); - }, - onError(error: any) { - formikProps?.setErrors(mutationErrorsToFormik(error)); - reject(error); - }, - }); - }); - }; - return { mutation, submit, fnUpdater }; -} diff --git a/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/usePostEmailSend.ts b/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/usePostEmailSend.ts deleted file mode 100644 index 55e98e386..000000000 --- a/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/usePostEmailSend.ts +++ /dev/null @@ -1,92 +0,0 @@ -/* -* Generated by fireback 1.2.5 -* Written by Ali Torabi. -* The code is generated for react-query@v3.39.3 -* Checkout the repository for licenses and contribution: https://github.com/torabian/fireback -*/ -import { type FormikHelpers } from "formik"; -import { useContext, useState, useRef } from "react"; -import { useMutation } from "react-query"; -import { - execApiFn, - type IResponse, - mutationErrorsToFormik, - type IResponseList -} from "../../core/http-tools"; -import { - RemoteQueryContext, - type UseRemoteQuery, - queryBeforeSend, -} from "../../core/react-tools"; - import { - SendEmailActionReqDto, - SendEmailActionResDto, - } from "../abac/AbacActionsDto" -export function usePostEmailSend( - props?: UseRemoteQuery & { - } -) { - let {queryClient, query, execFnOverride} = props || {}; - query = query || {} - const { options, execFn } = useContext(RemoteQueryContext); - // Calculare the function which will do the remote calls. - // We consider to use global override, this specific override, or default which - // comes with the sdk. - const rpcFn = execFnOverride - ? execFnOverride(options) - : execFn - ? execFn(options) - : execApiFn(options); - // Url of the remote affix. - const url = "/email/send".substr(1); - let computedUrl = `${url}?${new URLSearchParams( - queryBeforeSend(query) - ).toString()}`; - let completeRouteUrls = true; - // Attach the details of the request to the fn - const fn = (body: any) => rpcFn("POST", computedUrl, body); - const mutation = useMutation< - IResponse, - IResponse, - Partial - >(fn); - // Only entities are having a store in front-end - const fnUpdater = ( - data: IResponseList | undefined, - item: IResponse - ) => { - if (!data) { - return { - data: { items: [] }, - }; - } - // To me it seems this is not a good or any correct strategy to update the store. - // When we are posting, we want to add it there, that's it. Not updating it. - // We have patch, but also posting with ID is possible. - if (data.data && item?.data) { - data.data.items = [item.data, ...(data?.data?.items || [])]; - } - return data; - }; - const submit = ( - values: Partial, - formikProps?: FormikHelpers> - ): Promise> => { - return new Promise((resolve, reject) => { - mutation.mutate(values, { - onSuccess(response: IResponse) { - queryClient?.setQueryData>( - "*abac.SendEmailActionResDto", - (data) => fnUpdater(data, response) as any - ); - resolve(response); - }, - onError(error: any) { - formikProps?.setErrors(mutationErrorsToFormik(error)); - reject(error); - }, - }); - }); - }; - return { mutation, submit, fnUpdater }; -} diff --git a/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/usePostGsmProviderSendSms.ts b/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/usePostGsmProviderSendSms.ts deleted file mode 100644 index b47bc28d9..000000000 --- a/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/usePostGsmProviderSendSms.ts +++ /dev/null @@ -1,92 +0,0 @@ -/* -* Generated by fireback 1.2.5 -* Written by Ali Torabi. -* The code is generated for react-query@v3.39.3 -* Checkout the repository for licenses and contribution: https://github.com/torabian/fireback -*/ -import { type FormikHelpers } from "formik"; -import { useContext, useState, useRef } from "react"; -import { useMutation } from "react-query"; -import { - execApiFn, - type IResponse, - mutationErrorsToFormik, - type IResponseList -} from "../../core/http-tools"; -import { - RemoteQueryContext, - type UseRemoteQuery, - queryBeforeSend, -} from "../../core/react-tools"; - import { - GsmSendSmsWithProviderActionReqDto, - GsmSendSmsWithProviderActionResDto, - } from "../abac/AbacActionsDto" -export function usePostGsmProviderSendSms( - props?: UseRemoteQuery & { - } -) { - let {queryClient, query, execFnOverride} = props || {}; - query = query || {} - const { options, execFn } = useContext(RemoteQueryContext); - // Calculare the function which will do the remote calls. - // We consider to use global override, this specific override, or default which - // comes with the sdk. - const rpcFn = execFnOverride - ? execFnOverride(options) - : execFn - ? execFn(options) - : execApiFn(options); - // Url of the remote affix. - const url = "/gsmProvider/send/sms".substr(1); - let computedUrl = `${url}?${new URLSearchParams( - queryBeforeSend(query) - ).toString()}`; - let completeRouteUrls = true; - // Attach the details of the request to the fn - const fn = (body: any) => rpcFn("POST", computedUrl, body); - const mutation = useMutation< - IResponse, - IResponse, - Partial - >(fn); - // Only entities are having a store in front-end - const fnUpdater = ( - data: IResponseList | undefined, - item: IResponse - ) => { - if (!data) { - return { - data: { items: [] }, - }; - } - // To me it seems this is not a good or any correct strategy to update the store. - // When we are posting, we want to add it there, that's it. Not updating it. - // We have patch, but also posting with ID is possible. - if (data.data && item?.data) { - data.data.items = [item.data, ...(data?.data?.items || [])]; - } - return data; - }; - const submit = ( - values: Partial, - formikProps?: FormikHelpers> - ): Promise> => { - return new Promise((resolve, reject) => { - mutation.mutate(values, { - onSuccess(response: IResponse) { - queryClient?.setQueryData>( - "*abac.GsmSendSmsWithProviderActionResDto", - (data) => fnUpdater(data, response) as any - ); - resolve(response); - }, - onError(error: any) { - formikProps?.setErrors(mutationErrorsToFormik(error)); - reject(error); - }, - }); - }); - }; - return { mutation, submit, fnUpdater }; -} diff --git a/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/usePostGsmSendSms.ts b/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/usePostGsmSendSms.ts deleted file mode 100644 index 6e70f013a..000000000 --- a/modules/fireback/codegen/react-new/src/modules/fireback/sdk/modules/abac/usePostGsmSendSms.ts +++ /dev/null @@ -1,92 +0,0 @@ -/* -* Generated by fireback 1.2.5 -* Written by Ali Torabi. -* The code is generated for react-query@v3.39.3 -* Checkout the repository for licenses and contribution: https://github.com/torabian/fireback -*/ -import { type FormikHelpers } from "formik"; -import { useContext, useState, useRef } from "react"; -import { useMutation } from "react-query"; -import { - execApiFn, - type IResponse, - mutationErrorsToFormik, - type IResponseList -} from "../../core/http-tools"; -import { - RemoteQueryContext, - type UseRemoteQuery, - queryBeforeSend, -} from "../../core/react-tools"; - import { - GsmSendSmsActionReqDto, - GsmSendSmsActionResDto, - } from "../abac/AbacActionsDto" -export function usePostGsmSendSms( - props?: UseRemoteQuery & { - } -) { - let {queryClient, query, execFnOverride} = props || {}; - query = query || {} - const { options, execFn } = useContext(RemoteQueryContext); - // Calculare the function which will do the remote calls. - // We consider to use global override, this specific override, or default which - // comes with the sdk. - const rpcFn = execFnOverride - ? execFnOverride(options) - : execFn - ? execFn(options) - : execApiFn(options); - // Url of the remote affix. - const url = "/gsm/send/sms".substr(1); - let computedUrl = `${url}?${new URLSearchParams( - queryBeforeSend(query) - ).toString()}`; - let completeRouteUrls = true; - // Attach the details of the request to the fn - const fn = (body: any) => rpcFn("POST", computedUrl, body); - const mutation = useMutation< - IResponse, - IResponse, - Partial - >(fn); - // Only entities are having a store in front-end - const fnUpdater = ( - data: IResponseList | undefined, - item: IResponse - ) => { - if (!data) { - return { - data: { items: [] }, - }; - } - // To me it seems this is not a good or any correct strategy to update the store. - // When we are posting, we want to add it there, that's it. Not updating it. - // We have patch, but also posting with ID is possible. - if (data.data && item?.data) { - data.data.items = [item.data, ...(data?.data?.items || [])]; - } - return data; - }; - const submit = ( - values: Partial, - formikProps?: FormikHelpers> - ): Promise> => { - return new Promise((resolve, reject) => { - mutation.mutate(values, { - onSuccess(response: IResponse) { - queryClient?.setQueryData>( - "*abac.GsmSendSmsActionResDto", - (data) => fnUpdater(data, response) as any - ); - resolve(response); - }, - onError(error: any) { - formikProps?.setErrors(mutationErrorsToFormik(error)); - reject(error); - }, - }); - }); - }; - return { mutation, submit, fnUpdater }; -}