efficy-u-rpc-api
Version:
The Efficy U - RPC API is developed for server side usage in a Node.js environment and also bundled for usage inside an Efficy browser session for client-side JSON RPC requests.
1,144 lines (1,139 loc) • 39 kB
TypeScript
// Generated by dts-bundle-generator v9.5.1
export type CustomDatasetPayloads = ListSummaryPayload;
export interface ListSummaryPayload {
fields: string[];
groupBy?: string[];
nbOfLines?: number;
orderBy?: string[];
query?: string[][];
startIndex?: number;
tableName: string;
}
export type ListSummaryResponse<T = unknown> = ListSummaryServerResponse<T>;
export interface ListSummaryServerResponse<T = unknown> {
errors?: ApiError[];
list: T[];
}
export interface ApiError {
detail: string;
extra: string;
id: string;
title: string;
}
export interface EntitySearch {
entity: string;
rows: SearchItem[];
total: number;
}
export type RefinedOptions = {
autoFilterByType?: boolean;
createdDateEnd?: string;
createdDateStart?: string;
exactFieldValue?: boolean;
includeArchived?: boolean;
links?: LinkSearch[];
notLinkedTo?: UnityKey;
onlyItemsLinkedTo?: UnityKey;
onlyItemsLinkedToMe?: boolean;
onlyItemsLinkedToMeAndMyGroups?: boolean;
onlyMyItems?: boolean;
requiredFields?: RequiredFieldSearch[];
updatedDateEnd?: string;
updatedDateStart?: string;
};
export type SearchRequest = {
entities: string[];
offset: number;
quantity: number;
refinedOptions: RefinedOptions;
value: string;
};
export type RequiredFieldSearch = {
field: string;
values?: string[];
};
export type LinkSearch = {
key?: UnityKey[];
main?: boolean;
tables?: number[];
};
export interface BasicSearchItem {
key: string;
name: string;
picturePath?: string;
secondaryText?: string;
type: string;
}
export type SearchItemField<T extends JSONPrimitive = JSONPrimitive> = {
name: string;
value: T | undefined;
};
export interface SearchItemLink {
displayText: string;
objectKey: UnityKey;
}
export interface SearchItem<T extends JSONPrimitive = JSONPrimitive> extends BasicSearchItem {
key: string;
type: string;
name: string;
archived: boolean;
picturePath: string;
score: number;
fields: SearchItemField<T>[];
links?: Record<string, SearchItemLink>;
page?: RouterLink;
tag: string;
}
export type RouterLink = {
name: string;
params?: {
[key: string]: string;
};
};
export interface SearchPayload {
identifier: string;
}
export interface SearchInServerPayload extends SearchPayload {
search: SearchRequest;
}
export interface GetSearchResultPayload extends SearchInServerPayload {
searchMine?: boolean;
}
export interface SystemClearCachesDataResponse {
message: string;
}
export interface SystemCachesDataResponse {
references: Record<UnityKey, SystemCachesReference>;
refDefinitions: Record<string, SystemCachesRefDefinition>;
mapOfRefCodeByKey: Record<string, UnityKey>;
}
export interface SystemCachesReference {
refKey: UnityKey;
refCode: string;
te1: string;
te2: string;
te3: string;
pos: number;
tabName: string;
tabPrefix: string;
}
export interface SystemCachesRefDefinition {
refdKey: UnityKey;
name: string;
prefix: string;
text1: string;
text2: string;
text3: string;
radical: string;
id: UnityKey;
}
export interface RpcNamedOperation {
"@name": string;
"#id"?: string;
"@func": object[];
[key: string]: any;
}
export type UnityKey = "" | string;
export type Nil = null | undefined;
export type JSONPrimitive = number | string | boolean | Nil;
export type JSONPrimitiveRecord = Record<string, JSONPrimitive>;
export type ErrorData = Record<"title" | "id" | "detail", string | ErrorDetail>;
export type ErrorDetail = Record<"id" | "message" | "objectKey", string>;
export type QueryStringArgs = Record<string, string | undefined> | object | URLSearchParams;
export type ModulePostPayload = FormData | object | unknown[] | URLSearchParams;
export interface JsonApiResponse<Data = unknown> {
data: Data;
errors?: JsonApiErrorNode[];
status?: number[];
}
export interface JsonApiErrorNode {
detail: string;
extra: any;
id: string;
title: string;
}
export interface CrmEnvConfig {
id?: string;
url?: string;
customer?: string;
apiKey?: string;
user?: string;
pwd?: string;
cookies?: Cookie[];
logOff?: boolean;
useFetchQueue?: boolean;
retryWithNewSession?: boolean;
useCookies?: boolean;
}
export interface Cookie {
name: string;
value: string;
path?: string;
expires?: string;
}
export interface ParsedRecordKey {
licenseCode: number | null;
stblKTable: number | null;
stblName: string | null;
nextKey: number | null;
}
export interface CrmFetchRequestInterceptorFunction {
(request: Request): Promise<void>;
}
export interface CrmFetchResponseInterceptorFunction {
(response: Response): Promise<void>;
}
export interface CrmFetchErroreInterceptorFunction {
(e: Error, request: Request, requestPayload: ModulePostPayload | undefined, response: Response | null): Promise<void>;
}
declare function isRPCNamedOperation(obj: any): obj is RpcNamedOperation;
declare function isJsonApiResponse(response: any): response is JsonApiResponse;
declare function isJsonApiErrorNode(err: any): err is JsonApiErrorNode;
declare function base62Decode(recordKey: string): number | null;
declare function parseRecordKey(recordKey: string): ParsedRecordKey | null;
declare function getTableNameById(id: number): string | null;
declare abstract class CrmFetchInterceptor<T extends Function> {
private funcs;
protected abstract handle(...args: any[]): Promise<void>;
/**
* Generic use method to add interceptors
* @example
* crmEnv.interceptors.onRequest.use(async(request: Request) => {
* onRequestUrlOrigin = new URL(request.url).origin;
* })
* crmEnv.interceptors.onPositiveResponse.use(async(response: Response) => {
* onResponseCustomHeader = response.headers.get("x-efficy-status") ?? "";
* })
* crmEnv.interceptors.onError.use(async(e: Error, request: Request, requestPayload: ModulePostPayload | undefined, response: Response | null) => {
* if (requestPayload && typeof requestPayload === "object") requestObject = requestPayload;
* })
*/
use(func: T): void;
clear(): void;
get interceptors(): ReadonlyArray<T>;
protected chain(...args: any[]): Promise<void>;
}
export declare class CrmFetchRequestInterceptor extends CrmFetchInterceptor<CrmFetchRequestInterceptorFunction> {
handle(request: Request): Promise<void>;
}
export declare class CrmFetchResponseInterceptor extends CrmFetchInterceptor<CrmFetchResponseInterceptorFunction> {
handle(response: Response): Promise<void>;
}
export declare class CrmFetchErrorInterceptor extends CrmFetchInterceptor<CrmFetchErroreInterceptorFunction> {
handle(e: Error, request: Request, requestPayload: ModulePostPayload | undefined, response: Response | null): Promise<void>;
}
/**
* Defines the connection properties for your Efficy web API
*/
export declare class CrmEnv {
private env?;
private name;
id?: string;
url?: string;
customer?: string;
apiKey?: string;
user?: string;
pwd?: string;
cookies?: Cookie[];
logOff?: boolean;
useFetchQueue?: boolean;
retryWithNewSession?: boolean;
useCookies?: boolean;
/**
* Creates a CrmEnv instance.
* @param env The definition object of the targeted CRM environment.
*/
constructor(env?: CrmEnvConfig | undefined);
/**
* Updates the CRM environment configuration.
* @param env The definition object of the targeted CRM environment.
*/
setEnv(env: CrmEnvConfig): void;
clearCookies(): void;
/**
* Returns the request header for cookies.
*/
get cookieHeader(): string;
/**
* Returns the session ID from cookies.
*/
get sessionId(): string;
/**
* Returns the first part of the session ID.
*/
get shortSessionId(): string;
readonly interceptors: Readonly<{
onRequest: CrmFetchRequestInterceptor;
onPositiveResponse: CrmFetchResponseInterceptor;
onError: CrmFetchErrorInterceptor;
}>;
}
declare class CrmFetch {
crmEnv: CrmEnv;
private subpage;
private readonly isPublicAPI;
protected name: string;
protected sessionId?: string;
protected requestCounter: number;
private _lastResponseObject;
private _lastResponseStatus;
constructor(crmEnv?: CrmEnv, subpage?: string, isPublicAPI?: boolean);
fetchOptions: RequestInit;
get lastResponseObject(): object | null;
get lastResponseStatus(): number;
protected setFetchOptions(): void;
protected initJsonFetch(method: "GET" | "POST"): void;
protected crmfetch(requestUrl: string, requestPayload?: ModulePostPayload, requestOptions?: RequestInit, isRetry?: boolean): Promise<object | null>;
protected getRequestUrl(crmPath: string, queryArgs?: QueryStringArgs): string;
/**
* Parse errors in both legacy Enterprise format as from the U {data, errors, status} format
* @param responseObject
*/
private getCrmException;
}
export declare class CrmFetchError extends Error {
statusCode: number;
url: string | undefined;
static readonly appId: string;
bodyText?: string;
bodyObject?: object;
constructor(statusCode: number, body: string, url: string | undefined);
}
/**
* Technical helper for forcing zero concurrency in fetch execution of CrmRpc and CrmApi.
* @deprecated
*/
export declare class FetchQueue {
#private;
static forceSequential: boolean;
static waitTime: number;
static pending: boolean;
static fetchCount: number;
static totalRequestTime: number;
static minRequestTime: number;
static maxRequestTime: number;
constructor();
pleaseWait(): boolean;
takeTurn(): void;
finished(): void;
sleep(): Promise<void>;
waitMyTurn(): Promise<void>;
static get averageRequestTime(): number;
static get stats(): {
fetchCount: number;
averageRequestTime: number;
totalRequestTime: number;
maxRequestTime: number;
minRequestTime: number;
};
}
/**
* Efficy SDK build for requesting custom Efficy nodes (aka Webservices) on the endpoint "crm/node"
*/
export declare class CrmNode extends CrmFetch {
crmEnv: CrmEnv;
constructor(crmEnv?: CrmEnv);
/**
*
* @param nodePath The node path without the "/crm/node/"" prefix, e.g. "echo"
* @param payload
* @param queryStringArgs
* @example
* const payload = {msg: "Hello, this is a unit test!"};
* const result = await crm.crmNodeData<EchoResponse>("echo", payload);
*/
crmNodeData<R>(nodePath: string, payload?: ModulePostPayload, queryStringArgs?: QueryStringArgs): Promise<R>;
/**
*
* @param nodePath The node path without the "/crm/node/"" prefix, e.g. "echo"
* @param payload
* @param queryStringArgs
* @example
* const payload = {msg: "Hello, this is a unit test!"};
* const result = await crm.crmNode("echo", payload)?.data;
*/
crmNode(nodePath: string, payload?: ModulePostPayload, queryStringArgs?: QueryStringArgs): Promise<any>;
}
/**
* Efficy SDK build around crm JSON web requests with endpoints such as "crm/query", "crm/global-search" and "crm/save".
* Each method immediatly invokes a request to the server and returns the received data object.
*/
export declare class CrmApi extends CrmFetch {
constructor(crmEnv?: CrmEnv);
/**
* Some operations cannot create their own session (e.g. systemClearCaches), hence this explicit logon
*/
logon(): Promise<void>;
/**
* Global elastic search in Efficy, with various filtering options
* @example
* const payload: GetSearchResultPayload = {
* identifier: "",
* search: {
* entities: ["cont"],
* value: searchedContact.toLocaleLowerCase(),
* offset: 0,
* quantity: 5,
* refinedOptions: {
* onlyItemsLinkedToMe: false
* }
* }
* }
* const searchResult: EntitySearch[] = await crm.searchGlobal(payload);
*/
searchGlobal: (payload: GetSearchResultPayload) => Promise<Record<string, EntitySearch> | null>;
/**
* Generate a list summary query
* @example
* const currencyPayload: ListSummaryPayload = {
* fields: ["crcyName", "crcyCode", "crcySymbol", "crcyCode", "crcyKey"],
* tableName: "Currency",
* query: [["crcyIsDisabled = 0"]]
* };
* const result = await crm.listSummary<Crcy>(currencyPayload);
* const euro = result?.list.find(item => item.crcyCode === "EUR")
*
* const companyPayload: ListSummaryPayload = {
* fields: ["compKey", "compName"],
* tableName: "Company",
* query: [["compArchived = 1", "compName like 'Efficy%'"]]
* };
*/
listSummary<T = unknown>(payload: CustomDatasetPayloads, all?: boolean): Promise<ListSummaryResponse<T> | undefined>;
/**
* Refresh the Crm server cache. Useful after modifying security or reference values. Requires an active session.
* @example
* const crmApi = new CrmApi(crmEnv);
* await crmApi.logon(); // Makes sure there is an active session
* const result = await crmApi.clearServerCaches();
*/
systemClearCaches(): Promise<SystemClearCachesDataResponse>;
/**
* Get an optionally refresh the Crm reference cache. Requires an active session.
* @example
* const crmApi = new CrmApi(crmEnv);
* await crmApi.logon(); // Makes sure there is an active session
* const references = await crmApi.systemReference(false);
*/
systemReference(noCache: boolean): Promise<SystemCachesDataResponse>;
crmGetData: <R>(crmPath: string, payload?: QueryStringArgs) => Promise<R>;
crmPostData: <R>(crmPath: string, payload: ModulePostPayload, queryStringArgs: QueryStringArgs) => Promise<R>;
private crmGet;
private crmPost;
}
declare class RpcObject {
private remoteAPI;
protected requestObject: RpcNamedOperation | null;
protected id: string;
protected responseObject: {};
constructor(remoteAPI: JsonRpcApi);
protected get api(): JsonRpcApi;
protected afterExecute(): void;
protected asJsonRpc(): RpcNamedOperation | null;
protected registerObject(object: RpcObject): void;
protected findDataSetArray(resp: JSONPrimitiveRecord, dataSetName?: string): JSONPrimitiveRecord[];
protected findListArray(resp: JSONPrimitiveRecord, listName?: string): JSONPrimitiveRecord[];
protected findAttachment(resp: JSONPrimitiveRecord, key: string): JSONPrimitiveRecord | undefined;
protected findFunc(resp: JSONPrimitiveRecord, name: string): any;
protected findFunc2(resp: JSONPrimitiveRecord, name: string, name2: string, value2: string | number): any;
protected findFuncArray(resp: JSONPrimitiveRecord, name: string): JSONPrimitiveRecord[] | null;
protected findFuncArray2(resp: JSONPrimitiveRecord, name: string, name2: string, value2: string | number): JSONPrimitiveRecord[] | null;
}
declare class StringObject extends RpcObject {
protected operationName: string;
result: string;
constructor(remoteAPI: JsonRpcApi);
protected afterExecute(): void;
}
declare class PropertyObject extends StringObject {
name: string;
constructor(remoteAPI: JsonRpcApi, name: string);
protected asJsonRpc(): RpcNamedOperation;
}
declare class SettingObject extends StringObject {
private module;
private name;
private asString;
protected operationName: string;
/**
* @param remoteAPI
* @param module The name of the module (JSON object) that owns the setting.
* @param name The name of the setting.
* @param asString If true, the settings of type TDateTime will be returned as a string formatted with the ShortDateTime format. If false, it will be returned as a float value.
*/
constructor(remoteAPI: JsonRpcApi, module: string, name: string, asString?: boolean);
/** @protected */
asJsonRpc(): {
"#id": string;
"@name": string;
"@func": {
"@name": string;
module: string;
name: string;
asstring: boolean;
}[];
};
}
export type DataSetKind = "main" | "master" | "detail" | "category";
declare class DataSetInternal {
type: DataSetKind;
name: string;
filter?: string | undefined;
includeBlobContent?: boolean | undefined;
tableView: number;
private _items;
private _item;
constructor(type: DataSetKind, name: string, filter?: string | undefined, includeBlobContent?: boolean | undefined);
/**
* The to array converted dataset
*/
get items(): JSONPrimitiveRecord[];
/**
* When exists, the first item of the items array, else null
*/
get item(): JSONPrimitiveRecord | null;
setItems(value?: JSONPrimitiveRecord[]): void;
get func(): JSONPrimitiveRecord;
get remoteDataSet(): DataSet;
}
declare class DataSet {
ds: DataSetInternal | null;
constructor(ds: DataSetInternal | null);
get name(): string | undefined;
get type(): DataSetKind | undefined;
get filter(): string | undefined;
get includeBlobContent(): boolean | undefined;
/**
* The to array converted dataset
*/
get items(): JSONPrimitiveRecord[];
/**
* When exists, the first item of the items, else null
*/
get item(): JSONPrimitiveRecord | null;
}
declare class RemoteDataSet extends RpcObject {
protected ds: DataSetInternal | null;
constructor(remoteAPI: JsonRpcApi);
protected dataSetName?: string;
protected afterExecute(): void;
/**
* The to array converted dataset
*/
get items(): JSONPrimitiveRecord[];
/**
* When exists, the first item of the items, else null
*/
get item(): JSONPrimitiveRecord | null;
}
declare class DataSetList extends RpcObject {
private master;
private master1;
private tableView;
constructor(remoteAPI: JsonRpcApi);
getMasterDataSet(masterView?: number): DataSetInternal;
getCategoryDataSet(categoryName: string): DataSetInternal;
getDetailDataSet(detail: string, filter?: string, includeBlobContent?: boolean): DataSetInternal;
resetState(): void;
get funcs(): JSONPrimitiveRecord[];
afterExecute(): void;
setResponseObject(value: object): void;
/**
* Add the remotely fetched master, categories and detail data as properties of data
*/
setData(target: any): void;
private setDsoItems;
}
declare class UserList extends RemoteDataSet {
constructor(remoteAPI: JsonRpcApi);
protected asJsonRpc(): RpcNamedOperation;
}
declare class RecentList extends RemoteDataSet {
private entity;
private extraFields;
constructor(remoteAPI: JsonRpcApi, entity?: string, extraFields?: string[]);
protected asJsonRpc(): RpcNamedOperation;
}
declare class FavoriteList extends RemoteDataSet {
private entity?;
constructor(remoteAPI: JsonRpcApi, entity?: string | undefined);
protected asJsonRpc(): RpcNamedOperation;
}
declare class ContactsList extends RemoteDataSet {
private recipients;
private phoneNumber;
/**
* @param remoteAPI
* @param recipients The list of email addresses
* @param phoneNumber The phone number, doesn't have to be stripped from formatting
*/
constructor(remoteAPI: JsonRpcApi, recipients?: string[], phoneNumber?: string);
protected asJsonRpc(): RpcNamedOperation;
}
declare class ConsultManyObject extends RemoteDataSet {
private entity;
private whereFields;
private whereValues;
private orderByExpression;
constructor(remoteAPI: JsonRpcApi, entity: string, whereFields?: string[], whereValues?: string[], orderByExpression?: string);
protected asJsonRpc(): RpcNamedOperation;
}
declare class CollectionObject extends RemoteDataSet {
private entity;
private detail;
constructor(remoteAPI: JsonRpcApi, entity: string, detail: string);
protected asJsonRpc(): RpcNamedOperation;
}
declare class ConsultObject extends RpcObject {
entity: string;
key: UnityKey;
private dataSetList;
private isDirty;
/**
* Opens an consult context for the record identified by entity and key.
* @param remoteAPI
* @param entity The entity name of the consulted record, e.g. "Comp"
* @param key The key of the consulted record
*/
constructor(remoteAPI: JsonRpcApi, entity: string, key: UnityKey);
/**
* resetState and isDirty allows to reuse the existing class after an executeBatch
*/
private resetState;
private setDirty;
/**
* Retrieves a master DataSet from the consult context.
*/
getMasterDataSet(): DataSet;
/**
* Retrieves the DataSet for category categoryName. Can be null when the category is not available to the current user.
* @param {string} categoryName - name of the category, e.g. "DOCU$INVOICING"
*/
getCategoryDataSet(categoryName: string): DataSet;
/**
* Retrieves a relation DataSet for the specified detail in the edit context.
* @param detail The detail name, e.g. "Comp"
* @param filter SQL filter expression, e.g. "COMMENT like '%template%'"
* @param includeBlobContent If true, blob fields (e.g. memo, stream) are returned
*/
getDetailDataSet(detail: string, filter?: string, includeBlobContent?: boolean): DataSet;
protected asJsonRpc(): RpcNamedOperation;
protected afterExecute(): void;
}
declare class AttachmentList extends RpcObject {
private attachments;
constructor(remoteAPI: JsonRpcApi);
/**
* Request attachment from File table
* @param fileKey
*/
getAttachment(fileKey: UnityKey): AttachmentObject;
resetState(): void;
get funcs(): JSONPrimitiveRecord[];
setResponseObject(value: object): void;
afterExecute(): void;
}
declare class AttachmentObject {
key: UnityKey;
private stream;
constructor(key: UnityKey);
setStream(stream: string): void;
/**
* get the base64 encoded attachment stream
*/
get base64Stream(): string;
get func(): JSONPrimitiveRecord;
}
declare class EditObject extends RpcObject {
entity: string;
key: UnityKey;
protected commit: boolean;
protected closecontext: boolean;
masterData: Record<string, string | number>;
otherFuncs: object[];
categories: Map<string, JSONPrimitiveRecord>;
private attachmentList;
private dataSetList;
private isDirty;
/**
* Opens an edit context for the record identified by entity and key.
* @param remoteAPI
* @param entity The entity name, e.g. "Comp"
* @param key The key of the record. Use key = 0 to create a new record
*/
constructor(remoteAPI: JsonRpcApi, entity: string, key: UnityKey);
private resetState;
private setDirty;
/**
* Retrieves a master DataSet from the edit context.
*/
getMasterDataSet(): DataSet;
/**
* Retrieves the DataSet for category categoryName. Can be null when the category is not available to the current user.
* @param categoryName name of the category, e.g. "DOCU$INVOICING"
*/
getCategoryDataSet(categoryName: string): DataSet;
/**
* Retrieves a relation DataSet for the specified detail in the edit context.
* @param detail The detail name, e.g. "Comp"
* @param filter SQL filter expression, e.g. "COMMENT like '%template%'"
* @param includeBlobContent If true, blob fields (e.g. memo, stream) are returned
*/
getDetailDataSet(detail: string, filter?: string, includeBlobContent?: boolean): DataSet;
/**
* Request attachment from File table
*/
getAttachment(fileKey: UnityKey): AttachmentObject;
/**
* Updates the field values of a master data set
*/
updateField(name: string, value: string | number): void;
/**
* Updates the field values of a master data set.
* @param fieldsObj - e.g. {"archived": "1"}
*/
updateFields(fieldsObj: JSONPrimitiveRecord): void;
/**
* Assign a single field:value to a category dataset
*/
updateCategoryField(categoryName: string, name: string, value: string | number): void;
/**
* Assign multiple field:value's in a category dataset
* @param categoryName
* @param fieldsObj e.g. {"compcustLanguage": "FR"}
*/
updateCategoryFields(categoryName: string, fieldsObj: JSONPrimitiveRecord): void;
/**
* Inserts a detail relation
*/
insertDetail(detail: string, detailKey: UnityKey, linkMainCompany?: boolean, retrieveName?: boolean): void;
/**
* Updates field values of a detail relation. When the detail relation doesn't exist, an exception is thrown.
* @param detail The detail name, e.g. "Comp"
* @param detailKey The key of the detail. If detailKey is 0, the current detail record is used
* @param fieldsObj e.g. {"OPENED": "0"}
*/
updateDetail(detail: string, detailKey: UnityKey, fieldsObj: JSONPrimitiveRecord): void;
/**
* Deletes a detail relation
* @param detail The detail name, e.g. "Comp"
* @param detailKey The key of the detail
*/
deleteDetail(detail: string, detailKey: UnityKey): void;
/**
* Clears all relations for the specified detail
* @param detail - The detail name, e.g. "Comp"
*/
clearDetail(detail: string): void;
/**
* Activates a category. If the user does not have the appropriate rights on the category, an exception is thrown.
*/
activateCategory(categoryName: string): void;
/**
* Requests that a unique reference number be generated when committing.
*/
setReference(id: string): void;
/**
* Sets the user relations.
* @param users The array of user IDs (keys).
* @param clear If true, clears the current user selection.
*/
setUsers(users: UnityKey[], clear?: boolean): void;
/**
* Sets the security for a user or group.
* @param userKey The user or group for which security is added.
* @param securityValue A sum of one or more of the following values: 1 (search), 2 (read), 4 (write), 8 (delete) and 256 (secure). Useful combinations are 7 (read/write), 15 (read/write/delete) and 271 (full control = read/write/delete/secure).
* @see {access_code}
*/
setUserSecurity(userKey: UnityKey, securityValue: number): void;
/**
* Inserts an file
* @param attachedFileType 1 = embedded, 2 = linked, 4 = remote, 5 = large
* @param path The path of the file that will be saved in the filePath field.
*/
insertAttachment(attachedFileType: number, path: string): void;
/**
* Updates an embedded file
* @param key - Leave null or 0 to set the stream of the just inserted Attachment
* @param base64String
*/
updateAttachment(key: UnityKey | number, base64String: string): void;
/**
* Copies data from an existing record in the database. The same entity as the current is assumed.
* The table views within the index range minIndex to maxIndex are copied. By default, all table views are copied.
* To copy a single detail, obtain the table view index using IndexFromDetail and use this value as MinIndex and MaxIndex.
* @param key The key of the source record.
* @param minTableView The index of first table view to be copied.
* @param maxTableView The index of last table view to be copied.
*/
copyFromExisting(key: UnityKey, minTableView?: number, maxTableView?: number): void;
/**
* Commits the changes to the database.
*/
commitChanges(): void;
protected asJsonRpc(): RpcNamedOperation;
protected afterExecute(): void;
}
declare class DeleteEntity extends RpcObject {
entity: string;
keys: UnityKey[];
constructor(remoteAPI: JsonRpcApi, entity: string, keys: UnityKey[]);
asJsonRpc(): RpcNamedOperation;
}
declare class ListObject extends RpcObject {
map: Map<string, string>;
constructor(remoteAPI: JsonRpcApi);
protected afterExecute(): void;
}
declare class SystemSettings extends ListObject {
constructor(remoteAPI: JsonRpcApi);
protected asJsonRpc(): RpcNamedOperation;
}
declare class QuerySQLObject extends RemoteDataSet {
private sql;
private queryParams;
private loadBlobs;
private recordCount;
constructor(remoteAPI: JsonRpcApi, sql: string, queryParams?: string[], loadBlobs?: boolean, recordCount?: number);
protected asJsonRpc(): RpcNamedOperation;
}
declare class QueryObject extends RemoteDataSet {
private key?;
private master?;
private detail?;
private queryParams;
private loadBlobs;
private recordCount;
constructor(remoteAPI: JsonRpcApi, key?: string | undefined, master?: number | undefined, detail?: number | undefined, queryParams?: string[], loadBlobs?: boolean, recordCount?: number);
protected asJsonRpc(): RpcNamedOperation;
}
/**
* @private
*/
export declare class JsonRpcApi extends CrmFetch {
crmEnv: CrmEnv;
remoteObjects: RpcObject[];
constructor(crmEnv?: CrmEnv);
/**
* Execute all assembled and queued RPC operations
*/
executeBatch(): Promise<void>;
/**
* Logoff the remote session
*/
logoff(): void;
private fetchPost;
}
/**
* Efficy SDK build around JSON RPC operations send to endpoint "crm/json", the Efficy Enterprise product style.
* Multiple RPC operations can be registered in a single request until usage of method executeBatch().
* Only after this method was executed, the RPC Response objects have data available in their item and items attributes.
* @example
* const crm = new CrmRpc(crmEnv);
* const comp = crm.openConsultObject("comp", compKey);
* const dsComp = comp.getMasterDataSet();
* const dsCompCustomer = comp.getCategoryDataSet("COMP$CUSTOMER");
* const dsLinkedContacts = comp.getDetailDataSet("cont");
* await crm.executeBatch();
* const compName = dsComp.item?.compName;
*/
export declare class CrmRpc extends JsonRpcApi {
/**
* Construct a CrmRpc object
* @param [crmEnv] When empty, uses the Efficy context of the browser
* @example
* const crm = new CrmRpc(crmEnv);
*/
constructor(crmEnv?: CrmEnv);
/**
* Execute all assembled and queued RPC operations
*/
executeBatch(): Promise<void>;
/**
* Logoff the remote session
*/
logoff(): void;
/**
* Post and receive JSON with custom endpoint
*/
post(requestUrl: string, requestObject: object): Promise<object | null>;
/**
* Retrieves the alias (name) of the currently connected database
*/
get currentDatabaseAlias(): PropertyObject;
/**
* Retrieves the current license name
*/
get currentLicenseName(): PropertyObject;
/**
* Retrieves the current user full name
*/
get currentUserFullName(): PropertyObject;
/**
* Retrieves the group memberships of the current user as semicolon separated string list, e.g. "1;28;292;936"
*/
get currentUserGroups(): PropertyObject;
/**
* Retrieves the current user key
*/
get currentUserId(): PropertyObject;
/**
* Retrieves the current user code, e.g. "CRM01"
*/
get currentUserCode(): PropertyObject;
/**
* Retrieves the current user timezone
*/
get currentUserTimezone(): PropertyObject;
/**
* Request a list of system settings. Use the Map object to retrieve settings
* @example
* const settings = crm.getSystemSettings();
* await crm.executeBatch();
* settings.map.get("ShortDateFormat"); // e.g. "dd/mm/yyyy"
* settings.map.forEach(console.log); // prints each setting on console
*/
getSystemSettings(): SystemSettings;
/**
* Requests the current value of a given Efficy setting.
* @param module The name of the setting.
* @param name The name of the module (JSON object) that owns the setting.
* @param asString If true, the settings of type TDateTime will be returned as a string formatted with the ShortDateTime format. If false, it will be returned as a float value.
* @example
* const workingPeriodFrom = crm.getSetting("user", "WorkingPeriodFrom");
* const workingPeriodFromFloat = crm.getSetting("user", "WorkingPeriodFrom", false);
* await crm.executeBatch();
* workingPeriodFrom.result; // e.g. "30/12/1899 08:00"
* workingPeriodFromFloat.result; // e.g. "0.333333333333333
*/
getSetting(module: string, name: string, asString?: boolean): SettingObject;
/**
* Opens a consult context for the record identified by entity and key.
* A context remains memory-resident (on the web server) until it is closed. Always match with a closeContext() call to avoid memory consumption.
* @param entity The entity name, e.g. "Comp"
* @param key The key of the record. Use key = "" to create a new record.
* @example
* const comp = crm.openConsultObject("comp", compKey)
* const dsComp = comp.getMasterDataSet();
* const dsCompCustomer = comp.getCategoryDataSet("COMP$CUSTOMER");
* const linkedContacts = comp.getDetailDataSet("cont");
* await crm.executeBatch();
*/
openConsultObject(entity: string, key: UnityKey): ConsultObject;
/**
* Opens an edit context for the record identified by entity and key.
* A context remains memory-resident (on the web server) until it is closed. Always match with a closeContext() call to avoid memory consumption.
* @param entity - The entity name, e.g. "Comp"
* @param key - The key of the record. Use key = "" to create a new record.
*/
openEditObject(entity: string, key?: UnityKey): EditObject;
/**
* @deprecated
* Selects records that exactly match certain field values
* @param entity The entity name, e.g. "Comp"
* @param whereFields A list of field names to match (used as WHERE criteria), e.g. ["NAME", "OPENED"]
* @param whereValues A list of values to match, e.g. ["Efficy", "1"]
* @param orderByExpression SQL sort expression, e.g. "K_COMPANY desc"
* @example
* const morningMeetings = crm.consultManyEx("Acti", ["PLANNED", "D_BEGIN"], ["1", "2022-03-14 09:00:00"], "D_BEGIN");
*/
consultManyEx(entity: string, whereFields?: string[], whereValues?: string[], orderByExpression?: string): ConsultManyObject;
/**
* Consult your recent records, optionally extended by additional fields.
* @param [entity] The entity name, e.g. "Comp"
* @param [extraFields] A list of extra fields to consult for each recent entity record, e.g. ["POSTCODE", "CITY"]
* @example
* const compRecents = crm.consultRecent("Comp");
* const compRecentsEx = crm.consultRecent("Comp", ["CITY", "COUNTRY"]);
*/
consultRecent(entity?: string, extraFields?: string[]): RecentList;
/**
* Consult your favorite records.
* @param [entity] The entity name, e.g. "Comp"
* @example
* const compFavorites = crm.consultFavorites("Comp");
*/
consultFavorites(entity?: string): FavoriteList;
/**
* Request the accessible categories - for the current user - of the given entity
* @param {string} entity - The entity name, e.g. "Comp"
* @example
* const compCategories = crm.getCategoryCollection("comp");
*/
getCategoryCollection(entity: string): CollectionObject;
/**
* Requests a list of users, groups and resources
* @example
* const userList = crm.getUserList();
*/
getUserList(): UserList;
/**
* Executes a database query stored in QUERIES
* @param idQuery
* @param [queryParameters] The query parameters delivered via a JS Array
* @param [loadBlobs] If true, blob fields (e.g. memo, stream) are returned
* @param [recordCount] If 0, return all records
* @example
* const tags = crm.executeDatabaseQuery(99990034); // Query "Standard: Top company tags"
*/
executeDatabaseQuery(idQuery: UnityKey, queryParameters?: string[], loadBlobs?: boolean, recordCount?: number): QueryObject;
executeSystemQuery(master: number, detail: number, queryParameters?: string[], loadBlobs?: boolean, recordCount?: number): QueryObject;
/**
* Runs a native (SQL) database query, only if the user has SQL Exec the permissions!
* @param sqlQueryText The SQL query text
* @param [queryParameters] The query parameters delivered via a JS Array
* @param [loadBlobs] If true, blob fields (e.g. memo, stream) are returned
* @param [recordCount] Limit the returned records
*/
executeSqlQuery(sqlQueryText: string, queryParameters?: string[], loadBlobs?: boolean, recordCount?: number): QuerySQLObject;
/**
* Deletes records
* @param entity The entity name, e.g. "Comp"
* @param keys List of keys
*/
deleteEntity(entity: string, keys: UnityKey[]): void;
constants: {
access_code: {
search: number;
read: number;
write: number;
delete: number;
showcontent: number;
addcontent: number;
modifycontent: number;
deletecontent: number;
secure: number;
fullcontrol: number;
securecontent: number;
nocontent: number;
};
account_kind: {
user: number;
group: number;
resource: number;
team: number;
};
file_type: {
embedded: number;
linked: number;
remote: number;
large: number;
};
};
}
export interface DocumentFile {
/**
* CRM id of the object
* @example "00010QH200001PKZ"
*/
crm_id: string;
/**
* The name of the file, including its extension.
* @example "important.pdf"
*/
name: string;
/**
* A comment or note associated with the file.
* @example "This file is an important document"
*/
comment: string;
/**
* A Base64-encoded reference to the file stream used for uploading or linking the document.
* @example "LS0tCm9wZW5hcGk6ICIzLjAuMCIKaW5mbzoKICB0aXRsZTogImVmZmljeVUgcHVibGljQVBJIgogIHZlcnNpb246ICIxLjAuMCIKICBkZXNjcmlwdGlvbjogIkEgUHV="
*/
stream: string;
/**
* Creation date
* @example "2024-11-14T13:31:40.033Z"
*/
creation_date: string;
/**
* Date of the last modfication
* @example "2024-11-18T13:31:40.033Z"
*/
last_update_date: string;
/**
* User code of the user who last modified the object
* @example "JODOE"
*/
last_updated_by: string;
}
export interface DocumentFiles {
/**
* Number of records returned
* @example 20
*/
records_found: number;
/**
* Next page of records
* @example "/api/v1/documents/{id}/files?offset=40&limit=20"
*/
next?: string;
/**
* Previous page of records
* @example "/api/v1/documents/{id}/files?offset=0&limit=20"
*/
previous?: string;
/**
* List of document files
*/
data: DocumentFile[];
}
declare class Api extends CrmFetch {
private apiVersion;
constructor(crmEnv?: CrmEnv, apiVersion?: string);
/**
* Retrieve a list of files linked to a specific document
* @param docuKey - ID of the document
* @returns
*/
getDocumentFiles: <T = v1.DocumentFiles>(docuKey: string, queryParams?: QueryParams) => Promise<T | null>;
/**
* Retrieve file linked to a specific document
* @param docuKey - ID of the documents
* @param fileKey - ID of the file
* @returns
*/
getDocumentFile: <T = v1.DocumentFile>(docuKey: string, fileKey: string) => Promise<T | null>;
apiGetData: <R>(apiPath: string, payload?: QueryStringArgs) => Promise<R | null>;
private apiGet;
}
declare class QueryParams {
order_by?: string | undefined;
offset?: number | undefined;
limit?: number | undefined;
constructor(order_by?: string | undefined, offset?: number | undefined, limit?: number | undefined);
}
declare namespace CrmUtils {
export { base62Decode, getTableNameById, parseRecordKey };
}
declare namespace CrmRpcObjects {
export { AttachmentList, AttachmentObject, CollectionObject, ConsultManyObject, ConsultObject, ContactsList, DataSet, DataSetList, DeleteEntity, EditObject, FavoriteList, PropertyObject, QueryObject, QuerySQLObject, RecentList, RemoteDataSet, SettingObject, SystemSettings, UserList };
}
declare namespace v1 {
export { DocumentFile, DocumentFiles };
}
declare namespace PublicApi {
export { v1$1 as v1 };
}
declare namespace v1$1 {
export { Api, QueryParams };
}
declare namespace CrmTypes {
export { ApiError, BasicSearchItem, Cookie, CrmEnvConfig, CrmFetchErroreInterceptorFunction, CrmFetchRequestInterceptorFunction, CrmFetchResponseInterceptorFunction, CustomDatasetPayloads, EntitySearch, ErrorData, ErrorDetail, GetSearchResultPayload, JSONPrimitive, JSONPrimitiveRecord, JsonApiErrorNode, JsonApiResponse, LinkSearch, ListSummaryPayload, ListSummaryResponse, ListSummaryServerResponse, ModulePostPayload, Nil, ParsedRecordKey, QueryStringArgs, RefinedOptions, RequiredFieldSearch, RouterLink, RpcNamedOperation, SearchInServerPayload, SearchItem, SearchItemField, SearchItemLink, SearchPayload, SearchRequest, SystemCachesDataResponse, SystemCachesRefDefinition, SystemCachesReference, SystemClearCachesDataResponse, UnityKey };
}
declare namespace CrmDataGuards {
export { isJsonApiErrorNode, isJsonApiResponse, isRPCNamedOperation };
}
declare namespace PublicApiTypes {
export { v1 };
}
export {
CrmDataGuards,
CrmRpcObjects,
CrmTypes,
CrmUtils,
PublicApi,
PublicApiTypes,
};
export {};