Sahibinden Clone – Classifieds & Marketplace Platform - Frontend Development Prompts

AI-assisted frontend development prompts for Sahibinden Clone – Classifieds & Marketplace Platform

This document contains all frontend development prompts that can be used to build the user interface for this project. Each prompt provides detailed specifications for implementing specific frontend features.


Table of Contents


Introduction

Project Overview

Sahibinden Clone – Classifieds & Marketplace Platform

Version : 1.0.13

clonesahibinden is a scalable classified ads platform where users can register, list items across multiple categories such as vehicles, real estate, goods, and jobs, interact via messaging, and manage their listings with support for premium ad features and role-based moderation. The platform offers advanced category management, powerful search and filtering, and a comprehensive admin and moderation dashboard.

How to Use Project Documents

The Clonesahibinden project has been designed and generated using Mindbricks, a powerful microservice-based backend generation platform. All documentation is automatically produced by the Mindbricks Genesis Engine, based on the high-level architectural patterns defined by the user or inferred by AI.

This documentation set is intended for both AI agents and human developers—including frontend and backend engineers—who need precise and structured information about how to interact with the backend services of this project. Each document reflects the live architecture of the system, providing a reliable reference for API consumption, data models, authentication flows, and business logic.

By following this documentation, developers can seamlessly integrate with the backend, while AI agents can use it to reason about the service structure, make accurate decisions, or even generate compatible client-side code.

Accessing Project Services

Each service generated by Mindbricks is exposed via a dedicated REST API endpoint. Every service documentation set includes the base URL of that service along with the specific API paths for each available route.

Before consuming any API, developers or agents must understand the service URL structure and environment-specific endpoints.

Service Endpoint Structure

Environment URL Pattern Example
Preview https://clonesahibinden.prw.mindbricks.com/auth-api
Staging https://clonesahibinden-stage.mindbricks.co/auth-api
Production https://clonesahibinden.mindbricks.co/auth-api

Replace auth with the actual service name as lower case (e.g., order-api, bff-service, customermanagement-api etc.).

Environment Usage Notes

Frontend applications should be designed to easily switch between environments, allowing dynamic endpoint targeting for Preview, Staging, and Production.

Getting Started: Use the Auth Service First

Before interacting with other services in the Clonesahibinden project, AI agents and developers should begin by integrating with the Auth Service.

Mindbricks automatically generates a dedicated authentication microservice based on the project’s authentication definitions provided by the architect. This service provides the essential user and access management foundation for the project.

Agents should first utilize the Auth Service to:

Auth Service Documentation

Use the following resources to understand and integrate the Auth Service:

Note: For most frontend use cases, the REST API Guide will be the primary source. The Event Guide and Service Design documents are especially useful when integrating with other backend microservices or building systems that interact with the auth service indirectly.

Using the BFF (Backend-for-Frontend) Service

In Mindbricks, all backend services are designed with an advanced CQRS (Command Query Responsibility Segregation) architecture. Within this architecture, business services are responsible for managing their respective domains and ensuring the accuracy and freshness of domain data.

The BFF service complements these business services by providing a read-only aggregation and query layer tailored specifically for frontend and client-side applications.

Key Principles of the BFF Service

BFF Service Documentation

Tip: Use the BFF service as the main entry point for all frontend data queries. It simplifies access, reduces round-trips, and ensures that data is shaped appropriately for the UI layer.

Business Services Overview

The Sahibinden Clone – Classifieds & Marketplace Platform project consists of multiple business services, each responsible for managing a specific domain within the system. These services expose their own REST APIs and documentation sets, and are accessible based on the environment (Preview, Staging, Production).

Usage Guidance

Business services are primarily designed to:

For advanced query needs across multiple services or aggregated views, prefer using the BFF service.

Available Business Services

adminModeration Service

Description: Admin and moderation service for logging, approval/denial, banning, role/config management, and audit actions. Orchestrates administrative and moderation business APIs, ensures every critical action is logged for traceability, and enables moderator/admin workflows.

Documentation:

Base URL Examples:

Environment URL
Preview https://clonesahibinden.prw.mindbricks.com/adminmoderation-api
Staging https://clonesahibinden-stage.mindbricks.co/adminmoderation-api
Production https://clonesahibinden.mindbricks.co/adminmoderation-api

categoryLocation Service

Description: Manages the category and location hierarchies for listings. Provides CRUD with uniqueness enforcement, navigation endpoints for category/location trees, and supports efficient public browsing with heavy read optimization.

Documentation:

Base URL Examples:

Environment URL
Preview https://clonesahibinden.prw.mindbricks.com/categorylocation-api
Staging https://clonesahibinden-stage.mindbricks.co/categorylocation-api
Production https://clonesahibinden.mindbricks.co/categorylocation-api

conversation Service

Description: Manages user-to-user messaging threads tied to listings, with message storage, read/unread and moderation support.

Documentation:

Base URL Examples:

Environment URL
Preview https://clonesahibinden.prw.mindbricks.com/conversation-api
Staging https://clonesahibinden-stage.mindbricks.co/conversation-api
Production https://clonesahibinden.mindbricks.co/conversation-api

favorite Service

Description: Handles all user favorites for classified listings, including add/remove, listing user-specific collections, and providing favorited status for listings. Prevents duplicate favorites and maintains favorite counts on listings for optimal UX. Cascade-cleans favorites if user or listing is deleted.

Documentation:

Base URL Examples:

Environment URL
Preview https://clonesahibinden.prw.mindbricks.com/favorite-api
Staging https://clonesahibinden-stage.mindbricks.co/favorite-api
Production https://clonesahibinden.mindbricks.co/favorite-api

listing Service

Description: Manages classified listings, their lifecycle, premium features, status transitions, and provides filtering/search for marketplace ads. Integrates with users, categories, locations, and Stripe for premium ad upgrades. Enforces ad and user type business logic.

Documentation:

Base URL Examples:

Environment URL
Preview https://clonesahibinden.prw.mindbricks.com/listing-api
Staging https://clonesahibinden-stage.mindbricks.co/listing-api
Production https://clonesahibinden.mindbricks.co/listing-api

listingImage Service

Description: Manages uploading, linking, ordering, and storing all images attached to classified listings. Enforces image file format, size, count, and metadata standards; supports multi-resolution handling and per-listing image count limits.

Documentation:

Base URL Examples:

Environment URL
Preview https://clonesahibinden.prw.mindbricks.com/listingimage-api
Staging https://clonesahibinden-stage.mindbricks.co/listingimage-api
Production https://clonesahibinden.mindbricks.co/listingimage-api

payment Service

Description: Handles Stripe payment flow for one-time premium upgrades on classified listings. Creates and tracks payment transactions, manages Stripe Checkout session and webhooks, and notifies the listing service to update premium status. Exposes payment history endpoints for users and reconciliation for admin.

Documentation:

Base URL Examples:

Environment URL
Preview https://clonesahibinden.prw.mindbricks.com/payment-api
Staging https://clonesahibinden-stage.mindbricks.co/payment-api
Production https://clonesahibinden.mindbricks.co/payment-api

Conclusion

This documentation set provides a comprehensive guide for understanding and consuming the Sahibinden Clone – Classifieds & Marketplace Platform backend, generated by the Mindbricks platform. It is structured to support both AI agents and human developers in navigating authentication, data access, service responsibilities, and system architecture.

To summarize:

Each service offers a complete set of documentation—REST API guides, event interface definitions, and design insights—to help you integrate efficiently and confidently.

Whether you are building a frontend application, configuring an automation agent, or simply exploring the architecture, this documentation is your primary reference for working with the backend of this project.

For environment-specific access, ensure you’re using the correct base URLs (Preview, Staging, Production), and coordinate with the project owner for any custom deployments.


How to Use These Prompts

These prompts are designed to be used with AI coding assistants to help build frontend features. Each prompt includes:

  1. Feature Description - What the feature does and its purpose
  2. Data Models - The backend data structures to work with
  3. API Endpoints - Available REST APIs for the feature
  4. UI Requirements - Specific user interface requirements
  5. Implementation Guidelines - Best practices and patterns to follow

When using these prompts with an AI assistant:


Frontend Development Prompts

CLONESAHIBINDEN

FRONTEND GUIDE FOR AI CODING AGENTS - PART 1 - Authentication Management

This document is the first part of a REST API guide for the clonesahibinden project. It is designed for AI agents that will generate frontend code to consume the project’s backend.

This first document includes general information about the project and its authentication management. Please read it carefully and implement all requirements described here.

The project has 1 auth service, 1 notification service, 1 BFF service, and 7 business services, plus other helper services such as bucket and realtime. In this document you will be informed only about the auth service. The initial frontend will be generated to use this service.

Each service is a separate microservice application and listens for HTTP requests at different service URLs.

Services may be deployed to the preview server, staging server, or production server. Therefore, each service has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the home page.

Project Introduction

clonesahibinden is a scalable classified ads platform where users can register, list items across multiple categories such as vehicles, real estate, goods, and jobs, interact via messaging, and manage their listings with support for premium ad features and role-based moderation. The platform offers advanced category management, powerful search and filtering, and a comprehensive admin and moderation dashboard.

API Structure

Object Structure of a Successful Response

When the service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope includes the data and essential metadata such as configuration details and pagination information, providing context to the client.

HTTP Status Codes:

Success Response Format:

For successful operations, the response includes a "status": "OK" property, signaling that the request executed successfully. The structure of a successful response is outlined below:

{
  "status":"OK",
  "statusCode": 200,   
  "elapsedMs":126,
  "ssoTime":120,
  "source": "db",
  "cacheKey": "hexCode",
  "userId": "ID",
  "sessionId": "ID",
  "requestId": "ID",
  "dataName":"products",
  "method":"GET",
  "action":"list",
  "appVersion":"Version",
  "rowCount":3,
  "products":[{},{},{}],
  "paging": {
    "pageNumber":1, 
    "pageRowCount":25, 
    "totalRowCount":3,
    "pageCount":1
  },
  "filters": [],
  "uiPermissions": []
}

Additional Data

Each API may include additional data besides the main data object, depending on the business logic of the API. These will be provided in each API’s response signature.

Error Response

If a request encounters an issue—whether due to a logical fault or a technical problem—the service responds with a standardized JSON error structure. The HTTP status code indicates the nature of the error, using commonly recognized codes for clarity:

Each error response is structured to provide meaningful insight into the problem, assisting in efficient diagnosis and resolution.

{
  "result": "ERR",
  "status": 400,
  "message": "errMsg_organizationIdisNotAValidID",
  "errCode": 400,
  "date": "2024-03-19T12:13:54.124Z",
  "detail": "String"
}

Accessing the backend

Each backend service has its own URL for each deployment environment. Users may want to test the frontend in one of the three deployments—preview, staging, or production. Please ensure that the home page includes a deployment server selection option so that, as the frontend coding agent, you can set the base URL for all services.

The base URL of the application in each environment is as follows:

For the auth service, the base URLs are:

For each other service, the service base URL will be given in the service sections.

Any request that requires login must include a valid token in the Bearer authorization header.

Please note that for each service in the project (which will be introduced in following pages) will use a different address so it is a good practice to define a separate client for each service in the frontend application lib source. Not only the different base urls, some services even may need different access rules when shaping the request.

Home page

First build a home page which shows some static content about the application, and has got login and registration (if is public) buttons. The home page shpuld be updated later according to the content that each service provides, as a frontend developer use best and common practices to reflect the service content to the home page. User may also give extra information for the home page content in addtion to this prompt.

Note that this page should include a deployment (environment) selection option to set the base URL. Set the default to production.

After user logs in, page header should show the current login state as in modern web pages, logged in user fullname, avatar, email and with a logout link, make a fancy current user component. The home page may have different views before and after login.

Registration Management

User Registration

User registration is public in the application, ensure that the register and login pages include a deployment server selection option so that you can set the base URL for all services. Start with a home page and set up the registration , verification, and login flow.

Using the registeruser route of the auth API, send the required fields from your registration page. Please create a simple and polished registration page that includes only the necessary fields of the registration API.

The registerUser API in the auth service is described with the request and response structure below.

Note that since the registerUser API is a business API, it is versioned; call it with the given version like /v1/registeruser.

Register User API

This api is used by public users to register themselves

Rest Route

The registerUser API REST controller can be triggered via the following route:

/v1/registeruser

Rest Request Parameters

The registerUser api has got 6 regular request parameters

Parameter Type Required Population
avatar String false request.body?.[“avatar”]
password String true request.body?.[“password”]
fullname String true request.body?.[“fullname”]
email String true request.body?.[“email”]
mobile String false request.body?.[“mobile”]
userType Enum false request.body?.[“userType”]
avatar : The avatar url of the user. If not sent, a default random one will be generated.
password : The password defined by the the user that is being registered.
fullname : The fullname defined by the the user that is being registered.
email : The email defined by the the user that is being registered.
mobile : The mobile number defined by the the user that is being registered.
userType : Indicates whether the user is an individual or a corporate account.

REST Request To access the api you can use the REST controller with the path POST /v1/registeruser

  axios({
    method: 'POST',
    url: '/v1/registeruser',
    data: {
            avatar:"String",  
            password:"String",  
            fullname:"String",  
            email:"String",  
            mobile:"String",  
            userType:"Enum",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

After a successful registration, the frontend code should handle any verification requirements. Verification Management will be given in teh next prompt.

The registration response will include a user object in the root envelope; this object contains user information with an id field.

Login Management

After successful registration and completing any required verifications, the user can log in. Please create a minimal, polished login page where the user can enter email and password. Note that this page should respect the deployment (environment) selection option made in the home page to set the base URL. If the user reaches this page directly skipping home page, the default productiondeployment will be used.

The login API returns a created session. This session can be retrieved later with the access token using the /currentuser system route.

Any request that requires login must include a valid token. When a user logs in successfully, the response JSON includes a JWT access token in the accessToken field. Under normal conditions, this token is also set as a cookie and consumed automatically. However, since AI coding agents’ preview options may fail to use cookies, ensure that each request includes the access token in the Bearer authorization header.

If the login fails due to verification requirements, the response JSON includes an errCode. If it is EmailVerificationNeeded, start the email verification flow; if it is MobileVerificationNeeded, start the mobile verification flow.

After a successful login, you can access session (user) information at any time with the /currentuser API. On inner pages, show brief profile information (avatar, name, etc.) using the session information from this API.

Note that the currentuser API returns a session object, so there is no id property; instead, the values for the user and session are exposed as userId and sessionId. The response combines user and session information.

The login, logout, and currentuser APIs are as follows. They are system routes and are not versioned.

POST /login — User Login

Purpose: Verifies user credentials and creates an authenticated session with a JWT access token.

Access Routes:

Request Parameters

Parameter Type Required Source
username String Yes request.body.username
password String Yes request.body.password

Behavior

Example

axios.post("/login", {
  username: "user@example.com",
  password: "securePassword"
});

Success Response

{
  "sessionId": "e81c7d2b-4e95-9b1e-842e-3fb9c8c1df38",
  "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
  "email": "user@example.com",
  "fullname": "John Doe",
  //...
  "accessToken": "ey7....",
  "userBucketToken": "e56d...."
}

Error Responses


POST /logout — User Logout

Purpose: Terminates the current session and clears associated authentication tokens.

Behavior

Example

axios.post("/logout", {}, {
  headers: { "Authorization": "Bearer your-jwt-token" }
});

Notes

Success Response

{ "status": "OK", "message": "User logged out successfully" }

GET /currentuser — Current Session

Purpose Returns the currently authenticated user’s session.

Route Type sessionInfo

Authentication Requires a valid access token (header or cookie).

Request

No parameters.

Example

axios.get("/currentuser", {
  headers: { Authorization: "Bearer <jwt>" }
});

Success (200)

Returns the session object (identity, tenancy, token metadata):

{
  "sessionId": "9cf23fa8-07d4-4e7c-80a6-ec6d6ac96bb9",
  "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
  "email": "user@example.com",
  "fullname": "John Doe",
  "roleId": "user",
  "tenantId": "abc123",
  "accessToken": "jwt-token-string",
  "...": "..."
}

Note that the currentuser API returns a session object, so there is no id property, instead, the values for the user and session are exposed as userId and sessionId. The response is a mix of user and session information.

Errors

Notes

After you complete this first step, please ensure you have not made the following common mistakes:

  1. When the application starts, please ensure that the baseUrl is set to the production server URL, and that the environment selector dropdown has the Production option selected by default.
  2. Note that any api call to the application backend is based on a service base url, in this propmpt all auth apis should be called by /auth-api prefix after application’s base url.
  3. The /currentuser API returns a mix of session and user data. There is no id property —use userId and sessionId.
  4. Please note that, the deployemnt environment selector will only be used in the home page. If any page is called directly bypassign home page, the page will use the stored or default environment.

After this prompt, the user may give you new instructions to update your first output or provide subsequent prompts about the project.


CLONESAHIBINDEN

FRONTEND GUIDE FOR AI CODING AGENTS - PART 2 - Verification Management

This document is a part of a REST API guide for the clonesahibinden project. It is designed for AI agents that will generate frontend code to consume the project’s backend.

This document includes the verification processes for the autheitcation flow. Please read it carefully and implement all requirements described here.

The project has 1 auth service, 1 notification service, 1 BFF service, and 7 business services, plus other helper services such as bucket and realtime. In this document you will be informed only about the auth service.

Each service is a separate microservice application and listens for HTTP requests at different service URLs.

Services may be deployed to the preview server, staging server, or production server. Therefore, each service has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the home page.

Accessing the backend

Each backend service has its own URL for each deployment environment. Users may want to test the frontend in one of the three deployments—preview, staging, or production. Please ensure that the home page includes a deployment server selection option so that, as the frontend coding agent, you can set the base URL for all services.

For the auth service, the base URLs are:

Any request that requires login must include a valid token in the Bearer authorization header.

After User Registration

Frontend should also be aware of verification after any login attempt. The login request may return a 401 or 403 with the error codes that indicates the verification needs.

{
  //...
  "errCode": "EmailVerificationNeeded",
  // or
  "errCode": "MobileVerificationNeeded",
}

Email Verification

In the registration response, check the emailVerificationNeeded property in the response root. If it is true, start the email verification flow.

After the login process, if you receive an HTTP error and the response contains an errCode with the value EmailVerificationNeeded, start the email verification flow.

  1. Call the email verification start route of the backend (described below) with the user’s email. The backend will send a secret code to the provided email address. The backend can send the email if the architect has configured a real mail service or SMTP server. During development, the backend also returns the secret code to the frontend. You can read this code from the secretCode property of the response.
  2. The secret code in the email will be a 6-digit code. Provide an input page so the user can paste this code into the frontend application. Navigate to this input page after starting the verification process. If the secretCode is sent to the frontend for testing, display it on the input page so the user can copy and paste it.
  3. The start response includes a codeIndex property. Display its value on the input page so the user can match the index in the message with the one on the screen.
  4. When the user submits the code, complete the email verification using the complete route of the backend (described below) with the user’s email and the secret code.
  5. After a successful email verification response, please check the response object to have the property ‘mobileVerificationNeeded’ as true, if so navigate to the mobile verification flow as described below. If no mobile verification is needed then just navigate the login page.

Below are the start and complete routes for email verification. These are system routes and therefore are not versioned.

POST /verification-services/email-verification/start

Purpose: Starts email verification by generating and sending a secret code.

Parameter Type Required Description
email String Yes User’s email address to verify

Example Request

{ "email": "user@example.com" }

Success Response

{
  "status": "OK", 
  "codeIndex": 1,
  // timeStamp : Milliseconds since Jan 1, 1970, 00:00:00.000 GMT
  "timeStamp": 1784578660000,
  "date": "Mon Jul 20 2026 23:17:40 GMT+0300 (GMT+03:00)",
  // expireTime: in seconds
  "expireTime": 86400,
  "verificationType": "byLink",

  // in testMode
  "secretCode": "123456",
  "userId": "user-uuid"
}

⚠️ In production, secretCode is not returned — it is only sent via email.

Error Responses


POST /verification-services/email-verification/complete

Purpose: Completes verification using the received code.

Parameter Type Required Description
email String Yes User’s email
secretCode String Yes Verification code

Success Response

{
  "status": "OK", 
  "isVerified": true,
  "email": "user@email.com",
  // in testMode
  "userId": "user-uuid"
}

Error Responses


Mobile Verification

In the registration response, check the mobileVerificationNeeded property in the response root. If it is true, start the mobile verification flow.

After the login process, if you receive a 403 error and the response contains an errCode with the value MobileVerificationNeeded, start the mobile verification flow.

  1. Call the mobile verification start route of the backend (described below) with the user’s email. The backend will send a secret code to the user’s mobile number. If a real texting service is configured, the backend sends the SMS. During development, the backend also returns the secret code to the frontend in the secretCode property.
  2. The secret code in the SMS will be a 6-digit code. Provide an input page so the user can paste this code. Navigate to this input page after starting the verification process. If the secretCode is returned for testing, display it on the input page for easy copy/paste.
  3. When the user submits the code, complete mobile verification using the complete route of the backend (described below) with the user’s email and the secret code.
  4. The start response includes a codeIndex property. Display its value on the input page so the user can match the index shown in the message with the one on the screen.
  5. After a successful mobile verification response, navigate to the login page.

Verification Order If both emailVerificationNeeded and mobileVerificationNeeded are true, handle both verification flows in order. First complete email verification, then mobile verification.

Below are the start and complete routes for mobile verification. These are system routes and therefore are not versioned.

POST /verification-services/mobile-verification/start

Parameter Type Required Description
email String Yes User’s email to locate mobile record

Success Response

{
  "status": "OK", 
  "codeIndex": 1,
  // timeStamp : Milliseconds since Jan 1, 1970, 00:00:00.000 GMT
  "timeStamp": 1784578660000,
  "date": "Mon Jul 20 2026 23:17:40 GMT+0300 (GMT+03:00)",
  // expireTime: in seconds
  "expireTime": 180,
  "verificationType": "byCode",

  // in testMode
  "secretCode": "123456",
  "userId": "user-uuid"
}

⚠️ secretCode is returned only in development.

Errors


POST /verification-services/mobile-verification/complete

Parameter Type Required Description
email String Yes Associated email
secretCode String Yes Code received via SMS

Success Response

{
  "status": "OK", 
  "isVerified": true,
  "mobile": "+1 333 ...",
  // in testMode
  "userId": "user-uuid"
}

Resetting Password

Users can reset their forgotten passwords without a login required, through email and mobile verification. To be able to start a password reset flow, users will click on the “Reset Password” link in the login page.

Since there are two verification methods, by email or by mobile, for password reset, when the reset password link is clicked, frontend should ask user if they want to make the verification through email of mobile. According to the users selection the frontend shoudl start the related flow as explaned below step by step.

Password Reset By Email Flow

  1. Call the password reset by email verification start route of the backend (described below) with the user’s email. The backend will send a secret code to the provided email address. The backend can send the email if the architect has configured a real mail service or SMTP server. During development, the backend also returns the secret code to the frontend. You can read this code from the secretCode property of the response.
  2. The secret code in the email will be a 6-digit code. Provide an input page so the user can paste this code into the frontend application. Navigate to this input page after starting the verification process. If the secretCode is sent to the frontend for testing, display it on the input page so the user can copy and paste it.
  3. The start response includes a codeIndex property. Display its value on the input page so the user can match the index in the message with the one on the screen.
  4. The input page should also include a double input area for the user to enter and confirm their new password.
  5. When the user submits the code and the new password, complete the password reset by email using the complete route of the backend (described below) with the user’s email , the secret code and new password.
  6. After a successful verification response, navigate to the login page.

Below are the start and complete routes for password reset by email verification. These are system routes and therefore are not versioned.

POST /verification-services/password-reset-by-email/start

Purpose:
Starts the password reset process by generating and sending a secret verification code.

Request Body

Parameter Type Required Description
email String Yes The email address of the user
{
  "email": "user@example.com"
}

Success Response

Returns secret code details (only in development environment) and confirmation that the verification step has been started.

{
  "userId": "user-uuid",
  "email": "user@example.com",
  "codeIndex": 1,
  "secretCode": "123456", 
  "timeStamp": 1765484354,
  "expireTime": 86400,
  "date": "2024-04-29T10:00:00.000Z",
  "verificationType": "byLink",
}

⚠️ In production, the secret code is only sent via email and not exposed in the API response.

Error Responses


POST /verification-services/password-reset-by-email/complete

Purpose:
Completes the password reset process by validating the secret code and updating the user’s password.

Request Body

Parameter Type Required Description
email String Yes The email address of the user
secretCode String Yes The code received via email
password String Yes The new password the user wants to set
{
  "email": "user@example.com",
  "secretCode": "123456",
  "password": "newSecurePassword123"
}

Success Response

{
  "userId": "user-uuid",
  "email": "user@example.com",
  "isVerified": true
}

Error Responses


Password Reset By Mobile Flow

  1. Call the password reset by mobile verification start route of the backend (described below) with the user’s email. The backend will send a secret code to the user’s mobile number. If a real texting service is configured, the backend sends the SMS. During development, the backend also returns the secret code to the frontend in the secretCode property.
  2. The secret code in the SMS will be a 6-digit code. Provide an input page so the user can paste this code. Navigate to this input page after starting the verification process. If the secretCode is returned for testing, display it on the input page for easy copy/paste.
  3. The start response includes a codeIndex property. Display its value on the input page so the user can match the index in the message with the one on the screen. Also display the half masked mobilenumber that comes in the response, to tell the user that their code is sent to this number.
  4. The input page should also include a double input area for the user to enter and confirm their new password.
  5. When the user submits the code, complete mobile verification using the complete route of the backend (described below) with the user’s email and the secret code.
  6. After a successful mobile verification response, navigate to the login page.

Below are the start and complete routes for password reset by mobile verification. These are system routes and therefore are not versioned.

POST /verification-services/password-reset-by-mobile/start

Purpose:
Initiates the mobile-based password reset by sending a verification code to the user’s mobile.

Request Body

Parameter Type Required Description
email String Yes The email of the user that resets the pssword
{
  "email": "user@user.com"
}

Success Response

Returns the verification context (code returned only in development):

{
  "status": "OK",
  "codeIndex": 1,
  timeStamp: 133241255,
  "mobile": "+905.....67",
  "secretCode": "123456", 
  "expireTime": 86400,
  "date": "2024-04-29T10:00:00.000Z",
  verificationType: "byLink"
}

⚠️ In production, the secretCode is not included in the response and is only sent via SMS.

Error Responses


POST /verification-services/password-reset-by-mobile/complete

Purpose:
Finalizes the password reset process by validating the received verification code and updating the user’s password.

Request Body

Parameter Type Required Description
email String Yes The email address of the user
secretCode String Yes The code received via SMS
password String Yes The new password to assign
{
  "email": "user@example.com",
  "secretCode": "123456",
  "password": "NewSecurePassword123!"
}

Success Response

{
  "userId": "user-uuid",
  "isVerified": true
}

** Please dont forget to arrange the code to be able to navigate to the verification pages both after registrations and login attempts if verification is needed.**

After this prompt, the user may give you new instructions to update your first output or provide subsequent prompts about the project.


CLONESAHIBINDEN

FRONTEND GUIDE FOR AI CODING AGENTS - PART 3 - Profile Management

This document is a part of a REST API guide for the clonesahibinden project. It is designed for AI agents that will generate frontend code to consume the project’s backend.

This document includes information and api descriptions about building a profile page in the frontend using the auth service profile api calls, and also in this document the bucket service will be introduced to manage the avatar.

The project has 1 auth service, 1 notification service, 1 BFF service, and 7 business services, plus other helper services such as bucket and realtime. In this document you will use the auth service and bucket service.

Each service is a separate microservice application and listens for HTTP requests at different service URLs.

Services may be deployed to the preview server, staging server, or production server. Therefore, each service has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the home page.

Accessing the backend

Each backend service has its own URL for each deployment environment. Users may want to test the frontend in one of the three deployments—preview, staging, or production. Please ensure that the register and login pages include a deployment server selection option so that, as the frontend coding agent, you can set the base URL for all services.

The base URL of the application in each environment is as follows:

For the auth service, service urls are as follows:

For each other service, the service URL will be given in the service sections.

Any request that requires login must include a valid token in the Bearer authorization header.

Bucket Management

This application has a bucket service used to store user files and other object-related files. The bucket service is login-agnostic, so for write operations or private reads, include a bucket token (provided by services) in the request’s Authorization header as a Bearer token.

Please note that all other business services require the access token in the Bearer header, while the bucket service expects a bucket token because it is login-agnostic. Ensure you manage the required token injection properly; any auth interceptor should not replace the bucket token with the access token.

To access the bucket service in each environement use the bucket service api urls below:

User Bucket This bucket stores public user files for each user.

When a user logs in—or in the /currentuser response—there is a userBucketToken to use when sending user-related public files to the bucket service.

{
  //...
  "userBucketToken": "e56d...."
}

To upload a file

POST {bucketServiceUrl}/upload

The request body is form-data which includes the bucketId and the file binary in the files field.

{
    bucketId: "{userId}-public-user-bucket",
    files: {binary}
}

Response status is 200 on success, e.g., body:

{
    "success": true,
    "data": [
        {
            "fileId": "9da03f6d-0409-41ad-bb06-225a244ae408",
            "originalName": "test (10).png",
            "mimeType": "image/png",
            "size": 604063,
            "status": "uploaded",
            "bucketName": "f7103b85-fcda-4dec-92c6-c336f71fd3a2-public-user-bucket",
            "isPublic": true,
            "downloadUrl": "https://babilcom.mindbricks.co/bucket/download/9da03f6d-0409-41ad-bb06-225a244ae408"
        }
    ]
}

To download a file from the bucket, you need its fileId. If you upload an avatar or other asset, ensure the download URL or the fileId is stored in the backend.

Buckets are mostly used in object creations that require an additional file, such as a product image or user avatar. After uploading your image to the bucket, insert the returned download URL into the related property of the target object record.

Application Bucket

This Clonesahibinden application also includes a common public bucket that anyone can read, but only users with the superAdmin, admin, or saasAdmin roles can write (upload) to it.

When a user with one of these admin roles is logged in, the /login response or the /currentuser response also returns an applicationBucketToken field, which is used when uploading any file to the application bucket.

{
  //...
  "applicationBucketToken": "e23fd...."
}

The common public application bucket ID is

"clonesahibinden-public-common-bucket"

In certain admin areas—such as product management pages—since the user already has the application bucket token, they will be able to upload related object images.

Please configure your UI to upload files to the application bucket using this bucket token whenever needed.

Object Buckets Some objects may also return a bucket token for uploading or accessing files related to that object. For example, in a project management application, when you fetch a project’s data, a public or private bucket token may be provided to upload or download project-related files.

These buckets will be used as described in the relevant object definitions.

Profile Page

Design a profile page to manage (view and edit) user information. The profile page should also be able to upload the user avatar to the user’s public bucket. For bucket information, see the Bucket Management section above.

On the profile page, you will need 4 business APIs: getUser , updateProfile, updateUserPassword and archiveProfile. Do not rely on the /currentuser response for profile data, because it contains session information. The most recent user data is in the user database and should be accessed via the getUser business API.

The updateProfile, updateUserPassword and archiveProfile api can only be called by the users themselves. They are designed specific to the profile page.

The avatar upload component should include an image-cropping component with zoom and pan capabilities. The frontend will send the image to the bucket after it is scaled and cropped.

Do not implement your own cropping component; instead, use the library component react-easy-crop by installing it.

Note that the user cannot change/update their email or roleId.

For password update you should make a separate block in the UI, so that user can enter old password, new password and confirm new password before calling the updateUserPassword.

Here are the 3 auth APIs—getUser , updateProfile and updateUserPassword— as follows: You can access these APIs through the auth service base URL, {appUrl}/auth-api.

Get User API

This api is used by admin roles or the users themselves to get the user profile information.

Rest Route

The getUser API REST controller can be triggered via the following route:

/v1/users/:userId

Rest Request Parameters

The getUser api has got 1 regular request parameter

Parameter Type Required Population
userId ID true request.params?.[“userId”]
userId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/users/:userId

  axios({
    method: 'GET',
    url: `/v1/users/${userId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Profile API

This route is used by users to update their profiles.

Rest Route

The updateProfile API REST controller can be triggered via the following route:

/v1/profile/:userId

Rest Request Parameters

The updateProfile api has got 5 regular request parameters

Parameter Type Required Population
userId ID true request.params?.[“userId”]
fullname String false request.body?.[“fullname”]
avatar String false request.body?.[“avatar”]
mobile String false request.body?.[“mobile”]
userType Enum false request.body?.[“userType”]
userId : This id paremeter is used to select the required data object that will be updated
fullname : A string value to represent the fullname of the user
avatar : The avatar url of the user. A random avatar will be generated if not provided
mobile : A string value to represent the user’s mobile number.
userType : Indicates whether the user is an individual or a corporate account.

REST Request To access the api you can use the REST controller with the path PATCH /v1/profile/:userId

  axios({
    method: 'PATCH',
    url: `/v1/profile/${userId}`,
    data: {
            fullname:"String",  
            avatar:"String",  
            mobile:"String",  
            userType:"Enum",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Userpassword API

This route is used to update the password of users in the profile page by users themselves

Rest Route

The updateUserPassword API REST controller can be triggered via the following route:

/v1/userpassword/:userId

Rest Request Parameters

The updateUserPassword api has got 3 regular request parameters

Parameter Type Required Population
userId ID true request.params?.[“userId”]
oldPassword String true request.body?.[“oldPassword”]
newPassword String true request.body?.[“newPassword”]
userId : This id paremeter is used to select the required data object that will be updated
oldPassword : The old password of the user that will be overridden bu the new one. Send for double check.
newPassword : The new password of the user to be updated

REST Request To access the api you can use the REST controller with the path PATCH /v1/userpassword/:userId

  axios({
    method: 'PATCH',
    url: `/v1/userpassword/${userId}`,
    data: {
            oldPassword:"String",  
            newPassword:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Archiving A Profile

A user may want to archive their profile. So the profile page should include an archive section for the users to archive their accounts. When an account is archived, it is marked as archived and an aarchiveDate is atteched to the profile. All user data is kept in the database for 1 month after user archived. If user tries to login or register with the same email, the account will be activated again. But if no login or register occures in 1 month after archiving, the profile and its related data will be deleted permanenetly. So in the profile page,

  1. The arcihve options should be accepted after user writes a text like (“ARCHİVE MY ACCOUNT”) to a confirmation dialog, so that frontend UX can ensure this is not an unconscious request.
  2. The user should be warned about the process, that his account will be available for a restore for 1 month.

The archive api, can only be called by the users themselves and its used as follows.

Archive Profile API

This api is used by users to archive their profiles.

Rest Route

The archiveProfile API REST controller can be triggered via the following route:

/v1/archiveprofile/:userId

Rest Request Parameters

The archiveProfile api has got 1 regular request parameter

Parameter Type Required Population
userId ID true request.params?.[“userId”]
userId : This id paremeter is used to select the required data object that will be deleted

REST Request To access the api you can use the REST controller with the path DELETE /v1/archiveprofile/:userId

  axios({
    method: 'DELETE',
    url: `/v1/archiveprofile/${userId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_idx": "Integer",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

After you complete this step, please ensure you have not made the following common mistakes:

  1. The auth API and bucket API are different services, and both URLs should be set according to the selected environment (production, staging, preview).
  2. Note that any api call to the application backend is based on a service base url, in this propmpt all auth apis should be called by /auth-api prefix after application’s base url, and bucket apis should be called by /bucket prefix after base url.
  3. The auth API and bucket API use different tokens. The auth API requires the accessToken in the Bearer header; the bucket API requires bucket-specific tokens such as userBucketToken or other application-specific bucket tokens. You may need two separate Axios clients: one for auth (always using the access token) and one for bucket operations (using the relevant bucket token).
  4. On the profile page, fetch the latest user data from the service using getUser. The /currentuser API is session-stored data; the latest data is in the database.
  5. When you upload the avatar image on the profile page, use the returned download URL as the user’s avatar property and update the user record when the Save button is clicked.

After this prompt, the user may give you new instructions to update your first output or provide subsequent prompts about the project.


CLONESAHIBINDEN

FRONTEND GUIDE FOR AI CODING AGENTS - PART 4 - User Management

This document is the 2nd part of a REST API guide for the clonesahibinden project. It is designed for AI agents that will generate frontend code to consume the project’s backend.

This document provides extensive instruction for administrative user management.

Service Access

User management is handled through auth service again.

Auth service may be deployed to the preview server, staging server, or production server. Therefore,it has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the login page (already handled in first part.).

For the auth service, the base URLs are:

Please note that any feature in this document is open to admins only. When the user logins, the response includes a roleId field.

This roleId should one of these following admin roles. superAdmin, admin,

Scope

Auth service provides following feature for user management in clonesahibinden application.

These features are already handled in the previous part.

  1. User Registration
  2. User Authentication
  3. Password Reset
  4. Email (and/or) Mobile Verification
  5. Profile Management

These features will be handled in this part.

API Structure

Object Structure of a Successful Response

When the service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope includes the data and essential metadata such as configuration details and pagination information, providing context to the client.

HTTP Status Codes:

Success Response Format:

For successful operations, the response includes a "status": "OK" property, signaling that the request executed successfully. The structure of a successful response is outlined below:

{
  "status":"OK",
  "statusCode": 200,   
  "elapsedMs":126,
  "ssoTime":120,
  "source": "db",
  "cacheKey": "hexCode",
  "userId": "ID",
  "sessionId": "ID",
  "requestId": "ID",
  "dataName":"products",
  "method":"GET",
  "action":"list",
  "appVersion":"Version",
  "rowCount":3,
  "products":[{},{},{}],
  "paging": {
    "pageNumber":1, 
    "pageRowCount":25, 
    "totalRowCount":3,
    "pageCount":1
  },
  "filters": [],
  "uiPermissions": []
}

Additional Data

Each API may include additional data besides the main data object, depending on the business logic of the API. These will be provided in each API’s response signature.

Error Response

If a request encounters an issue—whether due to a logical fault or a technical problem—the service responds with a standardized JSON error structure. The HTTP status code indicates the nature of the error, using commonly recognized codes for clarity:

Each error response is structured to provide meaningful insight into the problem, assisting in efficient diagnosis and resolution.

{
  "result": "ERR",
  "status": 400,
  "message": "errMsg_organizationIdisNotAValidID",
  "errCode": 400,
  "date": "2024-03-19T12:13:54.124Z",
  "detail": "String"
}

User Management

User management will be one of the main parts of the administrative manageemnts, so there will be a minimal but fancy users page in the admin dashboard.

User Roles

Along with the default roles, this project also configured to have the following roles: moderator

The roles object is a hardcoded object in the generated code, and it contains the following roles:

{
  "superAdmin": "'superAdmin'",
  "admin": "'admin'",
  "user": "'user'",
  "moderator": "'moderator'"
}

Each user may have only one role, and it is given in /login , /currentuser or /users/:userId response as follows

{
  // ...
  "roleId":"superAdmin",
  // ...
}

Listing Users

You can list users using the listUsers api.

List Users API

The list of users is filtered by the tenantId.

Rest Route

The listUsers API REST controller can be triggered via the following route:

/v1/users

Rest Request Parameters

Filter Parameters

The listUsers api supports 4 optional filter parameters for filtering list results:

email (String): A string value to represent the user’s email.

fullname (String): A string value to represent the fullname of the user

roleId (String): A string value to represent the roleId of the user.

mobile (String): A string value to represent the user’s mobile number.

REST Request To access the api you can use the REST controller with the path GET /v1/users

  axios({
    method: 'GET',
    url: '/v1/users',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // email: '<value>' // Filter by email
        // fullname: '<value>' // Filter by fullname
        // roleId: '<value>' // Filter by roleId
        // mobile: '<value>' // Filter by mobile
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "users",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"users": [
		{
			"id": "ID",
			"email": "String",
			"password": "String",
			"fullname": "String",
			"avatar": "String",
			"roleId": "String",
			"mobile": "String",
			"mobileVerified": "Boolean",
			"emailVerified": "Boolean",
			"userType": "Enum",
			"userType_idx": "Integer",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Searching Users

You may search users with their full names and emails. The search is done in elasticsearch index of the user table so a fast response is provided by the backend. You can send search request on each character update in the search box but start searching after 3 chars. The keyword parameter that is used in the business logic of the api, is read from the keyword query parameter.

eg: GET /v1/searchusers?keyword=Joe

When the user deletes the search keyword, use the listUsers api to get the full list again.

Search Users API

The list of users is filtered by the tenantId.

Rest Route

The searchUsers API REST controller can be triggered via the following route:

/v1/searchusers

Rest Request Parameters

The searchUsers api has got 1 regular request parameter

Parameter Type Required Population
keyword String true request.query?.[“keyword”]
keyword :

Filter Parameters

The searchUsers api supports 2 optional filter parameters for filtering list results:

roleId (String): A string value to represent the roleId of the user.

mobile (String): A string value to represent the user’s mobile number.

REST Request To access the api you can use the REST controller with the path GET /v1/searchusers

  axios({
    method: 'GET',
    url: '/v1/searchusers',
    data: {
    
    },
    params: {
             keyword:'"String"',  
    
        // Filter parameters (see Filter Parameters section above)
        // roleId: '<value>' // Filter by roleId
        // mobile: '<value>' // Filter by mobile
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "users",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"users": [
		{
			"id": "ID",
			"email": "String",
			"password": "String",
			"fullname": "String",
			"avatar": "String",
			"roleId": "String",
			"mobile": "String",
			"mobileVerified": "Boolean",
			"emailVerified": "Boolean",
			"userType": "Enum",
			"userType_idx": "Integer",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Pagination

When you list the users please use pagination. To be able to use pagination you should provide a pageNumber paramater in the query. The default row count for one page is 25, add an option for user to change it to 50 or 100. You can provide this value to the api through the pageRowCount parameter;

GET /users?pageNumber=1&pageRowCount=50

Creatng Users

The user management console in the admin dashboard should provide UX components for user creating by admins. When creating users, it should also be possible to upload user avatar. Note that when creating, updating users , admins can not set emailVerified (or mobileVerified if exists) as true, since it is a logical mechanism and should be verified only through verification processes.

Create User API

This api is used by admin roles to create a new user manually from admin panels

Rest Route

The createUser API REST controller can be triggered via the following route:

/v1/users

Rest Request Parameters

The createUser api has got 6 regular request parameters

Parameter Type Required Population
avatar String false request.body?.[“avatar”]
email String true request.body?.[“email”]
password String true request.body?.[“password”]
fullname String true request.body?.[“fullname”]
mobile String false request.body?.[“mobile”]
userType Enum false request.body?.[“userType”]
avatar : The avatar url of the user. If not sent, a default random one will be generated.
email : A string value to represent the user’s email.
password : A string value to represent the user’s password. It will be stored as hashed.
fullname : A string value to represent the fullname of the user
mobile : A string value to represent the user’s mobile number.
userType : Indicates whether the user is an individual or a corporate account.

REST Request To access the api you can use the REST controller with the path POST /v1/users

  axios({
    method: 'POST',
    url: '/v1/users',
    data: {
            avatar:"String",  
            email:"String",  
            password:"String",  
            fullname:"String",  
            mobile:"String",  
            userType:"Enum",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Avatar Upload

Normally when user registers by his own, the avatar is uploaded to the logged in user’s public bucket, however in this user admin panel, if any avatar upload is needed, it should be uploaded to the application public bucket. To access this application bucket, the applicationBucketToken should be used in the bearer header, and the bucketId in the payload should be given as "clonesahibinden-public-common-bucket" .

Before the avatar upload, a specific componenet from react-easy-crop lib should be used for zoom, pan and crop. This component also requested in the PART 1 prompt for profile page, so ensure taht you reuse the previous code if exists.

Updating Users

User update is possible by updateUserapi. However since this update api is also called by teh user themselves it is lmited with name and avatar change (or any other user related property). For roleId and password updates seperate apis are used. So arrange the user update UI as to update the user info, as to set roleId and as to update password.

Update User API

This route is used by admins to update user profiles.

Rest Route

The updateUser API REST controller can be triggered via the following route:

/v1/users/:userId

Rest Request Parameters

The updateUser api has got 5 regular request parameters

Parameter Type Required Population
userId ID true request.params?.[“userId”]
fullname String false request.body?.[“fullname”]
avatar String false request.body?.[“avatar”]
mobile String false request.body?.[“mobile”]
userType Enum false request.body?.[“userType”]
userId : This id paremeter is used to select the required data object that will be updated
fullname : A string value to represent the fullname of the user
avatar : The avatar url of the user. A random avatar will be generated if not provided
mobile : A string value to represent the user’s mobile number.
userType : Indicates whether the user is an individual or a corporate account.

REST Request To access the api you can use the REST controller with the path PATCH /v1/users/:userId

  axios({
    method: 'PATCH',
    url: `/v1/users/${userId}`,
    data: {
            fullname:"String",  
            avatar:"String",  
            mobile:"String",  
            userType:"Enum",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

For role updates there are some rules.

  1. Superadmin role can not be unassigned even by superadmin.
  2. Admin roles can be assgined or unassgined only by superadmin.
  3. All other roles can be assigned and unassgined by admins and superadmin.

For password updates there are some rules.

  1. Superadmin and admin passwords can be updated only by superadmin.
  2. Admins can update only non-admin passwords.

Update Userrole API

This route is used by admin roles to update the user role.The default role is user when a user is registered. A user’s role can be updated by superAdmin or admin

Rest Route

The updateUserRole API REST controller can be triggered via the following route:

/v1/userrole/:userId

Rest Request Parameters

The updateUserRole api has got 2 regular request parameters

Parameter Type Required Population
userId ID true request.params?.[“userId”]
roleId String true request.body?.[“roleId”]
userId : This id paremeter is used to select the required data object that will be updated
roleId : The new roleId of the user to be updated

REST Request To access the api you can use the REST controller with the path PATCH /v1/userrole/:userId

  axios({
    method: 'PATCH',
    url: `/v1/userrole/${userId}`,
    data: {
            roleId:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Userpasswordbyadmin API

This route is used to change any user password by admins only. Superadmin can chnage all passwords, admins can change only nonadmin passwords

Rest Route

The updateUserPasswordByAdmin API REST controller can be triggered via the following route:

/v1/userpasswordbyadmin/:userId

Rest Request Parameters

The updateUserPasswordByAdmin api has got 2 regular request parameters

Parameter Type Required Population
userId ID true request.params?.[“userId”]
password String true request.body?.[“password”]
userId : This id paremeter is used to select the required data object that will be updated
password : The new password of the user to be updated

REST Request To access the api you can use the REST controller with the path PATCH /v1/userpasswordbyadmin/:userId

  axios({
    method: 'PATCH',
    url: `/v1/userpasswordbyadmin/${userId}`,
    data: {
            password:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Deleting Users

Deleting users is possible in certain conditions.

  1. SuperAdmin can not be deleted.
  2. Admins can be deleted by only superadmin.
  3. Users can be deleted by admins or superadmin.

Delete User API

This api is used by admins to delete user profiles.

Rest Route

The deleteUser API REST controller can be triggered via the following route:

/v1/users/:userId

Rest Request Parameters

The deleteUser api has got 1 regular request parameter

Parameter Type Required Population
userId ID true request.params?.[“userId”]
userId : This id paremeter is used to select the required data object that will be deleted

REST Request To access the api you can use the REST controller with the path DELETE /v1/users/:userId

  axios({
    method: 'DELETE',
    url: `/v1/users/${userId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_idx": "Integer",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

When you list user group members, a user object will also be inserted in each userGroupMember object, with fullname, avatar and email.

Bucket Management

(This information is also given in PART 1 prompt.)

This application has a bucket service used to store user files and other object-related files. The bucket service is login-agnostic, so for write operations or private reads, include a bucket token (provided by services) in the request’s Authorization header as a Bearer token.

Please note that all other business services require the access token in the Bearer header, while the bucket service expects a bucket token because it is login-agnostic. Ensure you manage the required token injection properly; any auth interceptor should not replace the bucket token with the access token.

User Bucket This bucket stores public user files for each user.

When a user logs in—or in the /currentuser response—there is a userBucketToken to use when sending user-related public files to the bucket service.

{
  //...
  "userBucketToken": "e56d...."
}

To upload a file

POST {baseUrl}/bucket/upload

The request body is form-data which includes the bucketId and the file binary in the files field.

{
    bucketId: "{userId}-public-user-bucket",
    files: {binary}
}

Response status is 200 on success, e.g., body:

{
    "success": true,
    "data": [
        {
            "fileId": "9da03f6d-0409-41ad-bb06-225a244ae408",
            "originalName": "test (10).png",
            "mimeType": "image/png",
            "size": 604063,
            "status": "uploaded",
            "bucketName": "f7103b85-fcda-4dec-92c6-c336f71fd3a2-public-user-bucket",
            "isPublic": true,
            "downloadUrl": "https://babilcom.mindbricks.co/bucket/download/9da03f6d-0409-41ad-bb06-225a244ae408"
        }
    ]
}

To download a file from the bucket, you need its fileId. If you upload an avatar or other asset, ensure the download URL or the fileId is stored in the backend.

Buckets are mostly used in object creations that require an additional file, such as a product image or user avatar. After uploading your image to the bucket, insert the returned download URL into the related property of the target object record.

Application Bucket

This Clonesahibinden application also includes a common public bucket that anyone can read, but only users with the superAdmin, admin, or saasAdmin roles can write (upload) to it.

When a user with one of these admin roles is logged in, the /login response or the /currentuser response also returns an applicationBucketToken field, which is used when uploading any file to the application bucket.

{
  //...
  "applicationBucketToken": "e23fd...."
}

The common public application bucket ID is

"clonesahibinden-public-common-bucket"

In certain admin areas—such as product management pages—since the user already has the application bucket token, they will be able to upload related object images.

Please configure your UI to upload files to the application bucket using this bucket token whenever needed.

Object Buckets Some objects may also return a bucket token for uploading or accessing files related to that object. For example, in a project management application, when you fetch a project’s data, a public or private bucket token may be provided to upload or download project-related files.

These buckets will be used as described in the relevant object definitions.

After this prompt, the user may give you new instructions to update the output of this prompt or provide subsequent prompts about the project.


CLONESAHIBINDEN

FRONTEND GUIDE FOR AI CODING AGENTS - PART 5 - MCP BFF Integration

This document is a part of a REST API guide for the clonesahibinden project. It is designed for AI agents that will generate frontend code to consume the project’s backend.

This document provides comprehensive instructions for integrating the MCP BFF (Model Context Protocol - Backend for Frontend) service into the frontend application. The MCP BFF is the central gateway between the frontend AI chat and all backend services.


MCP BFF Architecture Overview

The Clonesahibinden application uses an MCP BFF service that aggregates multiple backend MCP servers into a single frontend-facing API. Instead of the frontend connecting to each service’s MCP endpoint directly, it communicates exclusively through the MCP BFF.

┌────────────┐     ┌───────────┐     ┌─────────────────┐
│  Frontend   │────▶│  MCP BFF  │────▶│  Auth Service    │
│  (Chat UI)  │     │  :3005    │────▶│  Business Svc 1  │
│             │◀────│           │────▶│  Business Svc N  │
└────────────┘ SSE └───────────┘     └─────────────────┘

Key Responsibilities

MCP BFF Service URLs

For the MCP BFF service, the base URLs are:

All endpoints below are relative to the MCP BFF base URL.


Authentication

All MCP BFF endpoints require authentication. The user’s access token (obtained from the Auth service login) must be included in every request:

const headers = {
  'Content-Type': 'application/json',
  'Authorization': `Bearer ${accessToken}`,
};

Chat API (AI Interaction)

The chat API is the primary interface for AI-powered conversations. It supports both regular HTTP responses and SSE streaming for real-time output.

POST /api/chat — Regular Chat

Send a message and receive the complete AI response.

const response = await fetch(`${mcpBffUrl}/api/chat`, {
  method: 'POST',
  headers,
  body: JSON.stringify({
    message: "Show me all orders from last week",
    conversationId: "optional-conversation-id",  // for conversation context
    context: {}  // additional context
  }),
});

POST /api/chat/stream — SSE Streaming Chat (Recommended)

Stream the AI response in real-time. This is the recommended approach for chat UIs as it provides immediate feedback.

const response = await fetch(`${mcpBffUrl}/api/chat/stream`, {
  method: 'POST',
  headers,
  body: JSON.stringify({
    message: "Create a new product called Widget",
    conversationId: conversationId,
  }),
});

const reader = response.body.getReader();
const decoder = new TextDecoder();

while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  
  const chunk = decoder.decode(value, { stream: true });
  const lines = chunk.split('\n');
  
  for (const line of lines) {
    if (line.startsWith('event: ')) {
      const eventType = line.slice(7).trim();
      // Handle event type
    }
    if (line.startsWith('data: ')) {
      const data = JSON.parse(line.slice(6));
      // Handle event data
    }
  }
}

SSE Event Types

The streaming endpoint emits the following event types:

Event Description Data
start Stream started { conversationId }
text AI text chunk { text: "partial response..." }
tool_start AI is calling a tool { toolName, toolArgs }
tool_executing Tool is being executed { toolName }
tool_result Tool execution completed { toolName, result }check for __frontendAction
error Error occurred { error: "message" }
done Stream completed { conversationId, fullResponse }

Handling __frontendAction in Tool Results

When the AI calls certain tools (e.g., payment, secret reveal), the tool result may contain a __frontendAction object. This signals the frontend to render a special UI component instead of displaying raw tool output.

// In your SSE handler for 'tool_result' events:
function handleToolResult(data) {
  const action = extractFrontendAction(data.result);
  if (action) {
    // Render ActionCard component with this action
    renderActionCard(action);
  } else {
    // Display raw tool result as JSON or formatted text
    displayToolResult(data);
  }
}

// Extract __frontendAction from various response formats
function extractFrontendAction(result) {
  if (!result) return null;
  if (result.__frontendAction) return result.__frontendAction;
  
  // Unwrap MCP wrapper format
  let data = result;
  if (result?.result?.content) data = result.result;
  
  if (data?.content && Array.isArray(data.content)) {
    const textContent = data.content.find(c => c.type === 'text');
    if (textContent?.text) {
      try {
        const parsed = JSON.parse(textContent.text);
        if (parsed?.__frontendAction) return parsed.__frontendAction;
      } catch { /* not JSON */ }
    }
  }
  return null;
}

Frontend Action Types

Action Type Component Description
qrcode QrCodeActionCard Renders any string value as a QR code card
dataView DataViewActionCard Fetches a Business API route and renders a grid or gallery
payment PaymentActionCard “Pay Now” button that opens Stripe checkout modal

QR Code Action (type: "qrcode")

Triggered by the showQrCode MCP tool. Renders a QR code card from any string value.

{
  "__frontendAction": {
    "type": "qrcode",
    "value": "https://example.com/invite/ABC123",
    "title": "Invite Link",
    "subtitle": "Scan to open"
  }
}

Data View Action (type: "dataView")

Triggered by showBusinessApiListInFrontEnd or showBusinessApiGalleryInFrontEnd. Frontend calls the provided Business API route using the user’s bearer token, then renders:

{
  "__frontendAction": {
    "type": "dataView",
    "viewType": "grid",
    "title": "Recent Orders",
    "serviceName": "commerce",
    "apiName": "fetchListOrder",
    "routePath": "/v1/_fetchlistorder",
    "httpMethod": "GET",
    "queryParams": { "pageNo": 1, "pageRowCount": 10 },
    "columns": [
      { "field": "id", "label": "Order ID" },
      { "field": "orderAmount", "label": "Amount", "format": "currency" }
    ]
  }
}

Payment Action (type: "payment")

Triggered by the initiatePayment MCP tool. Renders a payment card with amount and a “Pay Now” button.

{
  "__frontendAction": {
    "type": "payment",
    "orderId": "uuid",
    "orderType": "order",
    "serviceName": "commerce",
    "amount": 99.99,
    "currency": "USD",
    "description": "Order #abc123"
  }
}

Conversation Management

// List user's conversations
GET /api/chat/conversations

// Get conversation history
GET /api/chat/conversations/:conversationId

// Delete a conversation
DELETE /api/chat/conversations/:conversationId

MCP Tool Discovery & Direct Invocation

The MCP BFF exposes endpoints for discovering and directly calling MCP tools (useful for debugging or building custom UIs).

GET /api/tools — List All Tools

const response = await fetch(`${mcpBffUrl}/api/tools`, { headers });
const { tools, count } = await response.json();
// tools: [{ name, description, inputSchema, service }, ...]

GET /api/tools/service/:serviceName — List Service Tools

const response = await fetch(`${mcpBffUrl}/api/tools/service/commerce`, { headers });
const { tools } = await response.json();

POST /api/tools/call — Call a Tool Directly

const response = await fetch(`${mcpBffUrl}/api/tools/call`, {
  method: 'POST',
  headers,
  body: JSON.stringify({
    toolName: "listProducts",
    args: { page: 1, limit: 10 },
  }),
});
const result = await response.json();

GET /api/tools/status — Connection Status

const status = await fetch(`${mcpBffUrl}/api/tools/status`, { headers });
// Returns health of each MCP service connection

POST /api/tools/refresh — Reconnect Services

await fetch(`${mcpBffUrl}/api/tools/refresh`, { method: 'POST', headers });
// Reconnects to all MCP services and refreshes the tool registry

Elasticsearch API

The MCP BFF provides direct access to Elasticsearch for searching, filtering, and aggregating data across all project indices.

All Elasticsearch endpoints are under /api/elastic.

GET /api/elastic/allIndices — List Project Indices

Returns all Elasticsearch indices belonging to this project (prefixed with clonesahibinden_).

const indices = await fetch(`${mcpBffUrl}/api/elastic/allIndices`, { headers });
// ["clonesahibinden_products", "clonesahibinden_orders", ...]

POST /api/elastic/:indexName/rawsearch — Raw Elasticsearch Query

Execute a raw Elasticsearch query on a specific index.

const response = await fetch(`${mcpBffUrl}/api/elastic/products/rawsearch`, {
  method: 'POST',
  headers,
  body: JSON.stringify({
    query: {
      bool: {
        must: [
          { match: { status: "active" } },
          { range: { price: { gte: 10, lte: 100 } } }
        ]
      }
    },
    size: 20,
    from: 0,
    sort: [{ createdAt: "desc" }]
  }),
});
const { total, hits, aggregations, took } = await response.json();
// hits: [{ _id, _index, _score, _source: { ...document... } }, ...]

Note: The index name is automatically prefixed with clonesahibinden_ if not already prefixed.

POST /api/elastic/:indexName/search — Simplified Search

A higher-level search API with built-in support for filters, sorting, and pagination.

const response = await fetch(`${mcpBffUrl}/api/elastic/products/search`, {
  method: 'POST',
  headers,
  body: JSON.stringify({
    search: "wireless headphones",           // Full-text search
    filters: { status: "active" },           // Field filters
    sort: { field: "createdAt", order: "desc" },
    page: 1,
    limit: 25,
  }),
});

POST /api/elastic/:indexName/aggregate — Aggregations

Run aggregation queries for analytics and dashboards.

const response = await fetch(`${mcpBffUrl}/api/elastic/orders/aggregate`, {
  method: 'POST',
  headers,
  body: JSON.stringify({
    aggs: {
      status_counts: { terms: { field: "status.keyword" } },
      total_revenue: { sum: { field: "amount" } },
      monthly_orders: {
        date_histogram: { field: "createdAt", calendar_interval: "month" }
      }
    },
    query: { range: { createdAt: { gte: "now-1y" } } }
  }),
});

GET /api/elastic/:indexName/mapping — Index Mapping

Get the field mapping for an index (useful for building dynamic filter UIs).

const mapping = await fetch(`${mcpBffUrl}/api/elastic/products/mapping`, { headers });

POST /api/elastic/:indexName/ai-search — AI-Assisted Search

Uses the configured AI model to convert a natural-language query into an Elasticsearch query.

const response = await fetch(`${mcpBffUrl}/api/elastic/orders/ai-search`, {
  method: 'POST',
  headers,
  body: JSON.stringify({
    query: "orders over $100 from last month that are still pending",
  }),
});
// Returns: { total, hits, generatedQuery, ... }

Log API

The MCP BFF provides log viewing endpoints for monitoring application behavior.

GET /api/logs — Query Logs

const response = await fetch(`${mcpBffUrl}/api/logs?page=1&limit=50&logType=2&service=commerce&search=payment`, {
  headers,
});

Query Parameters:

GET /api/logs/stream — Real-time Console Stream (SSE)

Streams real-time console output from all services via Server-Sent Events.

const eventSource = new EventSource(`${mcpBffUrl}/api/logs/stream?services=commerce,auth`, {
  headers: { 'Authorization': `Bearer ${accessToken}` },
});

eventSource.addEventListener('log', (event) => {
  const logEntry = JSON.parse(event.data);
  // { service, timestamp, level, message, ... }
});

Available Services

The MCP BFF connects to the following backend services:

Service Description
auth Authentication, user management, sessions
adminModeration Admin and moderation service for logging, approval/denial, banning, role/config management, and audit actions. Orchestrates administrative and moderation business APIs, ensures every critical action is logged for traceability, and enables moderator/admin workflows.
categoryLocation Manages the category and location hierarchies for listings. Provides CRUD with uniqueness enforcement, navigation endpoints for category/location trees, and supports efficient public browsing with heavy read optimization.
conversation Manages user-to-user messaging threads tied to listings, with message storage, read/unread and moderation support.
favorite Handles all user favorites for classified listings, including add/remove, listing user-specific collections, and providing favorited status for listings. Prevents duplicate favorites and maintains favorite counts on listings for optimal UX. Cascade-cleans favorites if user or listing is deleted.
listing Manages classified listings, their lifecycle, premium features, status transitions, and provides filtering/search for marketplace ads. Integrates with users, categories, locations, and Stripe for premium ad upgrades. Enforces ad and user type business logic.
listingImage Manages uploading, linking, ordering, and storing all images attached to classified listings. Enforces image file format, size, count, and metadata standards; supports multi-resolution handling and per-listing image count limits.
payment Handles Stripe payment flow for one-time premium upgrades on classified listings. Creates and tracks payment transactions, manages Stripe Checkout session and webhooks, and notifies the listing service to update premium status. Exposes payment history endpoints for users and reconciliation for admin.

Each service exposes MCP tools that the AI can call through the BFF. Use GET /api/tools to discover all available tools at runtime, or GET /api/tools/service/:serviceName to list tools for a specific service.


After this prompt, the user may give you new instructions to update the output of this prompt or provide subsequent prompts about the project.


CLONESAHIBINDEN

FRONTEND GUIDE FOR AI CODING AGENTS - PART 6 - AdminModeration Service

This document is a part of a REST API guide for the clonesahibinden project. It is designed for AI agents that will generate frontend code to consume the project’s backend.

This document provides extensive instruction for the usage of adminModeration

Service Access

AdminModeration service management is handled through service specific base urls.

AdminModeration service may be deployed to the preview server, staging server, or production server. Therefore,it has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the login page (already handled in first part.).

For the adminModeration service, the base URLs are:

Scope

AdminModeration Service Description

Admin and moderation service for logging, approval/denial, banning, role/config management, and audit actions. Orchestrates administrative and moderation business APIs, ensures every critical action is logged for traceability, and enables moderator/admin workflows.

AdminModeration service provides apis and business logic for following data objects in clonesahibinden application. Each data object may be either a central domain of the application data structure or a related helper data object for a central concept. Note that data object concept is equal to table concept in the database, in the service database each data object is represented as a db table scheme and the object instances as table rows.

adminActionLog Data Object: Records every moderation/admin action: who, what, target, reason, metadata, and timestamp. Used for full audit compliance and enables appeals, overrides, and reporting. Immutable except for soft delete.

AdminModeration Service Frontend Description By The Backend Architect

This service exposes moderation/admin workflows (approve/deny/ban/role assign/etc.), drives all admin UI and logs, and provides full audit trail for compliance/appeal. All actions must be routed through APIs here for UI management. For each operation, expect immediate confirmation or actionable error feedback. Admin/facilitator/frontends can use listAdminActionLogs for reporting, filters by action/target/date/admin. Logs are immutable; update/delete not supported. Dashboard metrics/status endpoints can be routed here or via BFF as needed.

API Structure

Object Structure of a Successful Response

When the service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope includes the data and essential metadata such as configuration details and pagination information, providing context to the client.

HTTP Status Codes:

Success Response Format:

For successful operations, the response includes a "status": "OK" property, signaling that the request executed successfully. The structure of a successful response is outlined below:

{
  "status":"OK",
  "statusCode": 200,   
  "elapsedMs":126,
  "ssoTime":120,
  "source": "db",
  "cacheKey": "hexCode",
  "userId": "ID",
  "sessionId": "ID",
  "requestId": "ID",
  "dataName":"products",
  "method":"GET",
  "action":"list",
  "appVersion":"Version",
  "rowCount":3,
  "products":[{},{},{}],
  "paging": {
    "pageNumber":1, 
    "pageRowCount":25, 
    "totalRowCount":3,
    "pageCount":1
  },
  "filters": [],
  "uiPermissions": []
}

Additional Data

Each API may include additional data besides the main data object, depending on the business logic of the API. These will be provided in each API’s response signature.

Error Response

If a request encounters an issue—whether due to a logical fault or a technical problem—the service responds with a standardized JSON error structure. The HTTP status code indicates the nature of the error, using commonly recognized codes for clarity:

Each error response is structured to provide meaningful insight into the problem, assisting in efficient diagnosis and resolution.

{
  "result": "ERR",
  "status": 400,
  "message": "errMsg_organizationIdisNotAValidID",
  "errCode": 400,
  "date": "2024-03-19T12:13:54.124Z",
  "detail": "String"
}

Bucket Management

(This information is also given in PART 1 prompt.)

This application has a bucket service used to store user files and other object-related files. The bucket service is login-agnostic, so for write operations or private reads, include a bucket token (provided by services) in the request’s Authorization header as a Bearer token.

Please note that all other business services require the access token in the Bearer header, while the bucket service expects a bucket token because it is login-agnostic. Ensure you manage the required token injection properly; any auth interceptor should not replace the bucket token with the access token.

User Bucket This bucket stores public user files for each user.

When a user logs in—or in the /currentuser response—there is a userBucketToken to use when sending user-related public files to the bucket service.

{
  //...
  "userBucketToken": "e56d...."
}

To upload a file

POST {baseUrl}/bucket/upload

The request body is form-data which includes the bucketId and the file binary in the files field.

{
    bucketId: "{userId}-public-user-bucket",
    files: {binary}
}

Response status is 200 on success, e.g., body:

{
    "success": true,
    "data": [
        {
            "fileId": "9da03f6d-0409-41ad-bb06-225a244ae408",
            "originalName": "test (10).png",
            "mimeType": "image/png",
            "size": 604063,
            "status": "uploaded",
            "bucketName": "f7103b85-fcda-4dec-92c6-c336f71fd3a2-public-user-bucket",
            "isPublic": true,
            "downloadUrl": "https://babilcom.mindbricks.co/bucket/download/9da03f6d-0409-41ad-bb06-225a244ae408"
        }
    ]
}

To download a file from the bucket, you need its fileId. If you upload an avatar or other asset, ensure the download URL or the fileId is stored in the backend.

Buckets are mostly used in object creations that require an additional file, such as a product image or user avatar. After uploading your image to the bucket, insert the returned download URL into the related property of the target object record.

Application Bucket

This Clonesahibinden application also includes a common public bucket that anyone can read, but only users with the superAdmin, admin, or saasAdmin roles can write (upload) to it.

When a user with one of these admin roles is logged in, the /login response or the /currentuser response also returns an applicationBucketToken field, which is used when uploading any file to the application bucket.

{
  //...
  "applicationBucketToken": "e23fd...."
}

The common public application bucket ID is

"clonesahibinden-public-common-bucket"

In certain admin areas—such as product management pages—since the user already has the application bucket token, they will be able to upload related object images.

Please configure your UI to upload files to the application bucket using this bucket token whenever needed.

Object Buckets Some objects may also return a bucket token for uploading or accessing files related to that object. For example, in a project management application, when you fetch a project’s data, a public or private bucket token may be provided to upload or download project-related files.

These buckets will be used as described in the relevant object definitions.

AdminActionLog Data Object

Records every moderation/admin action: who, what, target, reason, metadata, and timestamp. Used for full audit compliance and enables appeals, overrides, and reporting. Immutable except for soft delete.

AdminActionLog Data Object Frontend Description By The Backend Architect

An immutable log entry. Used for compliance, audit trail, admin dashboards. Not directly editable or deletable; only created by system/admin APIs. Each entry shows moderator/admin, action, affected entity, timestamp, reason, and expanded details in metadata for complex events.

AdminActionLog Data Object Properties

AdminActionLog data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
action String false Yes No Action performed (e.g., approveListing, denyListing, banUser, assignRole, etc.)
actionAt Date false Yes No Date and time the action was performed, UTC.
adminUserId ID false Yes No User ID of admin/moderator who initiated the action (refers to auth:user).
metadata Object false No No Extended details/JSON object with details relevant to the action (previous/new values, related entities, etc.)
reason String false No No Reason for action (required on denial, ban; optional for others).
targetId ID false Yes No ID of the affected resource/entity (listing, user, message, etc.)
targetType String false Yes No Kind of entity affected by the action (e.g., listing, user, conversationMessage, roleAssignment, category, etc.)

Relation Properties

adminUserId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one.

In frontend, please ensure that,

1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

Filter Properties

action actionAt adminUserId targetId targetType

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.

Default CRUD APIs

For each data object, the backend architect may designate default APIs for standard operations (create, update, delete, get, list). These are the APIs that frontend CRUD forms and AI agents should use for basic record management. If no default is explicitly set (isDefaultApi), the frontend generator auto-discovers the most general API for each operation.

AdminActionLog Default APIs

Operation API Name Route Explicitly Set
Create createAdminActionLog /v1/adminactionlogs Auto
Update none - Auto
Delete none - Auto
Get getAdminActionLog /v1/adminactionlogs/:adminActionLogId Auto
List listAdminActionLogs /v1/adminactionlogs System

When building CRUD forms for a data object, use the default create/update APIs listed above. The form fields should correspond to the API’s body parameters. For relation fields, render a dropdown loaded from the related object’s list API using the display label property.

API Reference

Create Adminactionlog API

Appends a new immutable moderation/admin audit log entry for every critical action (listing, user, message, role, etc). Used both by internal workflows and explicit admin APIs.

API Frontend Description By The Backend Architect

Frontends should not invoke directly; log entries are created automatically via moderation/admin actions (approve/deny/ban/etc). Accepts adminUserId (from session), action, targetType, targetId, reason (required on denial/ban), metadata (optional), actionAt (server time, auto).

Rest Route

The createAdminActionLog API REST controller can be triggered via the following route:

/v1/adminactionlogs

Rest Request Parameters

The createAdminActionLog api has got 5 regular request parameters

Parameter Type Required Population
action String true request.body?.[“action”]
metadata Object false request.body?.[“metadata”]
reason String false request.body?.[“reason”]
targetId ID true request.body?.[“targetId”]
targetType String true request.body?.[“targetType”]
action : Action performed (e.g., approveListing, denyListing, banUser, assignRole, etc.)
metadata : Extended details/JSON object with details relevant to the action (previous/new values, related entities, etc.)
reason : Reason for action (required on denial, ban; optional for others).
targetId : ID of the affected resource/entity (listing, user, message, etc.)
targetType : Kind of entity affected by the action (e.g., listing, user, conversationMessage, roleAssignment, category, etc.)

REST Request To access the api you can use the REST controller with the path POST /v1/adminactionlogs

  axios({
    method: 'POST',
    url: '/v1/adminactionlogs',
    data: {
            action:"String",  
            metadata:"Object",  
            reason:"String",  
            targetId:"ID",  
            targetType:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "adminActionLog",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"adminActionLog": {
		"id": "ID",
		"action": "String",
		"actionAt": "Date",
		"adminUserId": "ID",
		"metadata": "Object",
		"reason": "String",
		"targetId": "ID",
		"targetType": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Adminactionlog API

Retrieve a single moderation/admin action log entry by ID. Used for detailed audit review or appeals.

API Frontend Description By The Backend Architect

Admin/staff frontend can use to show full details of an individual moderation event for investigation, override, or dispute resolution. Only available to admin/moderator roles.

Rest Route

The getAdminActionLog API REST controller can be triggered via the following route:

/v1/adminactionlogs/:adminActionLogId

Rest Request Parameters

The getAdminActionLog api has got 1 regular request parameter

Parameter Type Required Population
adminActionLogId ID true request.params?.[“adminActionLogId”]
adminActionLogId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/adminactionlogs/:adminActionLogId

  axios({
    method: 'GET',
    url: `/v1/adminactionlogs/${adminActionLogId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

This route’s response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "adminActionLog",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"adminActionLog": {
		"adminUser": {
			"email": "String",
			"fullname": "String",
			"roleId": "String"
		},
		"isActive": true
	}
}

List Adminactionlogs API

List all moderation/admin action logs with full filter/sort for dashboard or traceability/audit needs. Supports filtering by action, targetType, targetId, adminUserId, actionAt.

API Frontend Description By The Backend Architect

Feeds moderation dashboard. Supports filtering/searching by action (approve, deny, ban, etc), affected entity, targetId, admin/mod, time range. Pagination enabled for large result sets. Intended for admin/mod use only.

Rest Route

The listAdminActionLogs API REST controller can be triggered via the following route:

/v1/adminactionlogs

Rest Request Parameters The listAdminActionLogs api has got no request parameters.

REST Request To access the api you can use the REST controller with the path GET /v1/adminactionlogs

  axios({
    method: 'GET',
    url: '/v1/adminactionlogs',
    data: {
    
    },
    params: {
    
        }
  });

REST Response

This route’s response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "adminActionLogs",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"adminActionLogs": [
		{
			"adminUser": [
				{
					"email": "String",
					"fullname": "String",
					"roleId": "String"
				},
				{},
				{}
			],
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

_fetch Listadminactionlog API

System API to fetch list of adminActionLog records for frontend application. Auto-generated, not visible in design.

Rest Route

The _fetchListAdminActionLog API REST controller can be triggered via the following route:

/v1/_fetchlistadminactionlog

Rest Request Parameters

Filter Parameters

The _fetchListAdminActionLog api supports 5 optional filter parameters for filtering list results:

action (String): Action performed (e.g., approveListing, denyListing, banUser, assignRole, etc.)

actionAt (Date): Date and time the action was performed, UTC.

adminUserId (ID): User ID of admin/moderator who initiated the action (refers to auth:user).

targetId (ID): ID of the affected resource/entity (listing, user, message, etc.)

targetType (String): Kind of entity affected by the action (e.g., listing, user, conversationMessage, roleAssignment, category, etc.)

REST Request To access the api you can use the REST controller with the path GET /v1/_fetchlistadminactionlog

  axios({
    method: 'GET',
    url: '/v1/_fetchlistadminactionlog',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // action: '<value>' // Filter by action
        // actionAt: '<value>' // Filter by actionAt
        // adminUserId: '<value>' // Filter by adminUserId
        // targetId: '<value>' // Filter by targetId
        // targetType: '<value>' // Filter by targetType
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "adminActionLogs",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"adminActionLogs": [
		{
			"id": "ID",
			"action": "String",
			"actionAt": "Date",
			"adminUserId": "ID",
			"metadata": "Object",
			"reason": "String",
			"targetId": "ID",
			"targetType": "String",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"adminUser": [
				{
					"fullname": "String"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

After this prompt, the user may give you new instructions to update the output of this prompt or provide subsequent prompts about the project.


CLONESAHIBINDEN

FRONTEND GUIDE FOR AI CODING AGENTS - PART 7 - CategoryLocation Service

This document is a part of a REST API guide for the clonesahibinden project. It is designed for AI agents that will generate frontend code to consume the project’s backend.

This document provides extensive instruction for the usage of categoryLocation

Service Access

CategoryLocation service management is handled through service specific base urls.

CategoryLocation service may be deployed to the preview server, staging server, or production server. Therefore,it has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the login page (already handled in first part.).

For the categoryLocation service, the base URLs are:

Scope

CategoryLocation Service Description

Manages the category and location hierarchies for listings. Provides CRUD with uniqueness enforcement, navigation endpoints for category/location trees, and supports efficient public browsing with heavy read optimization.

CategoryLocation service provides apis and business logic for following data objects in clonesahibinden application. Each data object may be either a central domain of the application data structure or a related helper data object for a central concept. Note that data object concept is equal to table concept in the database, in the service database each data object is represented as a db table scheme and the object instances as table rows.

category Data Object: Represents a listing category; supports up to three levels of nesting for hierarchical browsing and filtering. Self-referencing parent-child relationship. Slug is unique for public URL routing. Sort order is unique within parent for ordered display.

location Data Object: Represents a hierarchical location of country/city/district for listings. Used for filtering/search/location field on all listings.

CategoryLocation Service Frontend Description By The Backend Architect

AI Prompt: The backend provides hierarchical listing/category/location endpoints for navigation, filtering, and selection. When rendering category or location selectors, provide the nested structure plus a count of descendant listings/categories for fast navigation. Editing/deletion endpoints are admin-only. When referencing categories/locations elsewhere (e.g., listing editor), use these APIs for search/dropdown population. All slugs are unique for SEO-friendly URLs.

API Structure

Object Structure of a Successful Response

When the service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope includes the data and essential metadata such as configuration details and pagination information, providing context to the client.

HTTP Status Codes:

Success Response Format:

For successful operations, the response includes a "status": "OK" property, signaling that the request executed successfully. The structure of a successful response is outlined below:

{
  "status":"OK",
  "statusCode": 200,   
  "elapsedMs":126,
  "ssoTime":120,
  "source": "db",
  "cacheKey": "hexCode",
  "userId": "ID",
  "sessionId": "ID",
  "requestId": "ID",
  "dataName":"products",
  "method":"GET",
  "action":"list",
  "appVersion":"Version",
  "rowCount":3,
  "products":[{},{},{}],
  "paging": {
    "pageNumber":1, 
    "pageRowCount":25, 
    "totalRowCount":3,
    "pageCount":1
  },
  "filters": [],
  "uiPermissions": []
}

Additional Data

Each API may include additional data besides the main data object, depending on the business logic of the API. These will be provided in each API’s response signature.

Error Response

If a request encounters an issue—whether due to a logical fault or a technical problem—the service responds with a standardized JSON error structure. The HTTP status code indicates the nature of the error, using commonly recognized codes for clarity:

Each error response is structured to provide meaningful insight into the problem, assisting in efficient diagnosis and resolution.

{
  "result": "ERR",
  "status": 400,
  "message": "errMsg_organizationIdisNotAValidID",
  "errCode": 400,
  "date": "2024-03-19T12:13:54.124Z",
  "detail": "String"
}

Bucket Management

(This information is also given in PART 1 prompt.)

This application has a bucket service used to store user files and other object-related files. The bucket service is login-agnostic, so for write operations or private reads, include a bucket token (provided by services) in the request’s Authorization header as a Bearer token.

Please note that all other business services require the access token in the Bearer header, while the bucket service expects a bucket token because it is login-agnostic. Ensure you manage the required token injection properly; any auth interceptor should not replace the bucket token with the access token.

User Bucket This bucket stores public user files for each user.

When a user logs in—or in the /currentuser response—there is a userBucketToken to use when sending user-related public files to the bucket service.

{
  //...
  "userBucketToken": "e56d...."
}

To upload a file

POST {baseUrl}/bucket/upload

The request body is form-data which includes the bucketId and the file binary in the files field.

{
    bucketId: "{userId}-public-user-bucket",
    files: {binary}
}

Response status is 200 on success, e.g., body:

{
    "success": true,
    "data": [
        {
            "fileId": "9da03f6d-0409-41ad-bb06-225a244ae408",
            "originalName": "test (10).png",
            "mimeType": "image/png",
            "size": 604063,
            "status": "uploaded",
            "bucketName": "f7103b85-fcda-4dec-92c6-c336f71fd3a2-public-user-bucket",
            "isPublic": true,
            "downloadUrl": "https://babilcom.mindbricks.co/bucket/download/9da03f6d-0409-41ad-bb06-225a244ae408"
        }
    ]
}

To download a file from the bucket, you need its fileId. If you upload an avatar or other asset, ensure the download URL or the fileId is stored in the backend.

Buckets are mostly used in object creations that require an additional file, such as a product image or user avatar. After uploading your image to the bucket, insert the returned download URL into the related property of the target object record.

Application Bucket

This Clonesahibinden application also includes a common public bucket that anyone can read, but only users with the superAdmin, admin, or saasAdmin roles can write (upload) to it.

When a user with one of these admin roles is logged in, the /login response or the /currentuser response also returns an applicationBucketToken field, which is used when uploading any file to the application bucket.

{
  //...
  "applicationBucketToken": "e23fd...."
}

The common public application bucket ID is

"clonesahibinden-public-common-bucket"

In certain admin areas—such as product management pages—since the user already has the application bucket token, they will be able to upload related object images.

Please configure your UI to upload files to the application bucket using this bucket token whenever needed.

Object Buckets Some objects may also return a bucket token for uploading or accessing files related to that object. For example, in a project management application, when you fetch a project’s data, a public or private bucket token may be provided to upload or download project-related files.

These buckets will be used as described in the relevant object definitions.

Category Data Object

Represents a listing category; supports up to three levels of nesting for hierarchical browsing and filtering. Self-referencing parent-child relationship. Slug is unique for public URL routing. Sort order is unique within parent for ordered display.

Category Data Object Frontend Description By The Backend Architect

AI Prompt: When rendering category selectors (dropdowns, trees) or category navigation lists, fetch via listCategories. Use sortOrder for display ordering. Show child count for expandable parents. Use slug field for SEO-friendly category URLs. Admins can create, edit, disable (isActive=false), or delete categories; most users view only. Parent selection enforced on create/update. Cannot create loops.

Category Data Object Properties

Category data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
description Text false No No Optional extended description for category (for admin display or frontend info).
icon String false No No Icon identifier (string or URL to a static asset) for this category.
name String false Yes No Category name, e.g. ‘Automobiles’, ‘Electronics’.
parentCategoryId ID false No No References parent category for hierarchy. Top-level (root) categories have null.
slug String false Yes No SEO-friendly unique slug for URL and search. Lowercase, hyphens only.
sortOrder Integer false Yes No Order for listing within siblings. Unique per parent.

Relation Properties

parentCategoryId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one.

In frontend, please ensure that,

1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: No

Filter Properties

name parentCategoryId slug

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.

Location Data Object

Represents a hierarchical location of country/city/district for listings. Used for filtering/search/location field on all listings.

Location Data Object Frontend Description By The Backend Architect

AI Prompt: Use listLocations to fetch hierarchical selectable location objects for search and listing creation forms. Filter in the frontend by country/city/district. Display latitude/longitude on map if needed. Admins can add, edit, delete or disable (isActive=false) locations. Public users may only browse.

Location Data Object Properties

Location data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
city String false Yes No City name.
country String false Yes No Country name (typically ‘Turkey’).
district String false Yes No District name, for fine-grained search.
latitude Double false No No Latitude for map/search.
longitude Double false No No Longitude for map/search.
postalCode String false No No Postal code for location.

Filter Properties

city country district

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.

Default CRUD APIs

For each data object, the backend architect may designate default APIs for standard operations (create, update, delete, get, list). These are the APIs that frontend CRUD forms and AI agents should use for basic record management. If no default is explicitly set (isDefaultApi), the frontend generator auto-discovers the most general API for each operation.

Category Default APIs

Operation API Name Route Explicitly Set
Create createCategory /v1/categories Auto
Update updateCategory /v1/categories/:categoryId Auto
Delete deleteCategory /v1/categories/:categoryId Auto
Get getCategory /v1/categories/:categoryId Auto
List listCategories /v1/categories System

Location Default APIs

Operation API Name Route Explicitly Set
Create createLocation /v1/locations Auto
Update updateLocation /v1/locations/:locationId Auto
Delete deleteLocation /v1/locations/:locationId Auto
Get getLocation /v1/locations/:locationId Auto
List listLocations /v1/locations System

When building CRUD forms for a data object, use the default create/update APIs listed above. The form fields should correspond to the API’s body parameters. For relation fields, render a dropdown loaded from the related object’s list API using the display label property.

API Reference

Create Category API

Creates a new category. Slug must be globally unique. Only admin may create categories.

API Frontend Description By The Backend Architect

Only admins can create categories. The slug field must be unique and URL-friendly. Parent selection (for nesting) is validated. Use for admin consoles and bulk management.

Rest Route

The createCategory API REST controller can be triggered via the following route:

/v1/categories

Rest Request Parameters

The createCategory api has got 6 regular request parameters

Parameter Type Required Population
description Text false request.body?.[“description”]
icon String false request.body?.[“icon”]
name String true request.body?.[“name”]
parentCategoryId ID false request.body?.[“parentCategoryId”]
slug String true request.body?.[“slug”]
sortOrder Integer true request.body?.[“sortOrder”]
description : Optional extended description for category (for admin display or frontend info).
icon : Icon identifier (string or URL to a static asset) for this category.
name : Category name, e.g. ‘Automobiles’, ‘Electronics’.
parentCategoryId : References parent category for hierarchy. Top-level (root) categories have null.
slug : SEO-friendly unique slug for URL and search. Lowercase, hyphens only.
sortOrder : Order for listing within siblings. Unique per parent.

REST Request To access the api you can use the REST controller with the path POST /v1/categories

  axios({
    method: 'POST',
    url: '/v1/categories',
    data: {
            description:"Text",  
            icon:"String",  
            name:"String",  
            parentCategoryId:"ID",  
            slug:"String",  
            sortOrder:"Integer",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "category",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"category": {
		"id": "ID",
		"description": "Text",
		"icon": "String",
		"name": "String",
		"parentCategoryId": "ID",
		"slug": "String",
		"sortOrder": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Create Location API

Create a new location entry (country, city, district). Only admin allowed. Composite uniqueness enforced.

API Frontend Description By The Backend Architect

For admin use only. Location uniqueness validated on (country, city, district). For multi-level selectors, call this repeatedly to populate country/city/district lists.

Rest Route

The createLocation API REST controller can be triggered via the following route:

/v1/locations

Rest Request Parameters

The createLocation api has got 6 regular request parameters

Parameter Type Required Population
city String true request.body?.[“city”]
country String true request.body?.[“country”]
district String true request.body?.[“district”]
latitude Double false request.body?.[“latitude”]
longitude Double false request.body?.[“longitude”]
postalCode String false request.body?.[“postalCode”]
city : City name.
country : Country name (typically ‘Turkey’).
district : District name, for fine-grained search.
latitude : Latitude for map/search.
longitude : Longitude for map/search.
postalCode : Postal code for location.

REST Request To access the api you can use the REST controller with the path POST /v1/locations

  axios({
    method: 'POST',
    url: '/v1/locations',
    data: {
            city:"String",  
            country:"String",  
            district:"String",  
            latitude:"Double",  
            longitude:"Double",  
            postalCode:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "location",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"location": {
		"id": "ID",
		"city": "String",
		"country": "String",
		"district": "String",
		"latitude": "Double",
		"longitude": "Double",
		"postalCode": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Delete Category API

Deletes a category by id (soft delete). Only admin allowed.

API Frontend Description By The Backend Architect

Admin-only. Deleting a parent category sets parentCategoryId to null on children. Category is soft-deleted for restoration if needed.

Rest Route

The deleteCategory API REST controller can be triggered via the following route:

/v1/categories/:categoryId

Rest Request Parameters

The deleteCategory api has got 1 regular request parameter

Parameter Type Required Population
categoryId ID true request.params?.[“categoryId”]
categoryId : This id paremeter is used to select the required data object that will be deleted

REST Request To access the api you can use the REST controller with the path DELETE /v1/categories/:categoryId

  axios({
    method: 'DELETE',
    url: `/v1/categories/${categoryId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "category",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"category": {
		"id": "ID",
		"description": "Text",
		"icon": "String",
		"name": "String",
		"parentCategoryId": "ID",
		"slug": "String",
		"sortOrder": "Integer",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Delete Location API

Soft-delete a location for admin-only. Used for removing obsolete/corrected locations.

API Frontend Description By The Backend Architect

Admin-only. Set isActive=false to remove location from public selectors. If referenced elsewhere, deletion may be blocked until listings/categories updated.

Rest Route

The deleteLocation API REST controller can be triggered via the following route:

/v1/locations/:locationId

Rest Request Parameters

The deleteLocation api has got 1 regular request parameter

Parameter Type Required Population
locationId ID true request.params?.[“locationId”]
locationId : This id paremeter is used to select the required data object that will be deleted

REST Request To access the api you can use the REST controller with the path DELETE /v1/locations/:locationId

  axios({
    method: 'DELETE',
    url: `/v1/locations/${locationId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "location",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"location": {
		"id": "ID",
		"city": "String",
		"country": "String",
		"district": "String",
		"latitude": "Double",
		"longitude": "Double",
		"postalCode": "String",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Category API

Fetch a single category by id. Publicly accessible.

API Frontend Description By The Backend Architect

Get category details for a given id. Enrich response with child category count and parent info for navigation trees. Used for editing/viewing category details.

Rest Route

The getCategory API REST controller can be triggered via the following route:

/v1/categories/:categoryId

Rest Request Parameters

The getCategory api has got 1 regular request parameter

Parameter Type Required Population
categoryId ID true request.params?.[“categoryId”]
categoryId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/categories/:categoryId

  axios({
    method: 'GET',
    url: `/v1/categories/${categoryId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

This route’s response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "category",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"category": {
		"parentCategory": {
			"name": "String",
			"slug": "String"
		},
		"childCategories": {
			"name": "String",
			"slug": "String",
			"isActive": true
		},
		"isActive": true
	}
}

Get Location API

Get details of a location by id. Publicly accessible for search/forms. Used by listing creation editors, etc.

API Frontend Description By The Backend Architect

Fetch all fields for display or editing/location picker. Admins use for management forms; public users for navigation/filter search.

Rest Route

The getLocation API REST controller can be triggered via the following route:

/v1/locations/:locationId

Rest Request Parameters

The getLocation api has got 1 regular request parameter

Parameter Type Required Population
locationId ID true request.params?.[“locationId”]
locationId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/locations/:locationId

  axios({
    method: 'GET',
    url: `/v1/locations/${locationId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

This route’s response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "location",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"location": {
		"isActive": true
	}
}

List Categories API

Returns all categories (optionally filtered by parentCategoryId or isActive). Used for category trees, navigation, and dropdowns. Public.

API Frontend Description By The Backend Architect

Use this endpoint for building category selection/search trees, sidebars, or dropdowns. Accepts parentCategoryId as a filter for fetching children. Returns all data for public display. Pagination not enabled (few hundred at most). Children included via join. Optionally returns count of active children for expandable UI.

Rest Route

The listCategories API REST controller can be triggered via the following route:

/v1/categories

Rest Request Parameters The listCategories api has got no request parameters.

REST Request To access the api you can use the REST controller with the path GET /v1/categories

  axios({
    method: 'GET',
    url: '/v1/categories',
    data: {
    
    },
    params: {
    
        }
  });

REST Response

This route’s response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "categories",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"categories": [
		{
			"childCategories": [
				{
					"name": "String",
					"slug": "String",
					"isActive": true
				},
				{},
				{}
			],
			"activeChildCount": [
				null,
				null,
				null
			],
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

List Locations API

List all locations (optionally filter by country/city/district). Used for populating selectors and browsing. Public. No pagination (few thousand max).

API Frontend Description By The Backend Architect

Request all locations or optionally filter by country/city/district for cascading selectors. Public use for forms, admin for management. If needed, can expand to support location grouping/child-count in future.

Rest Route

The listLocations API REST controller can be triggered via the following route:

/v1/locations

Rest Request Parameters The listLocations api has got no request parameters.

REST Request To access the api you can use the REST controller with the path GET /v1/locations

  axios({
    method: 'GET',
    url: '/v1/locations',
    data: {
    
    },
    params: {
    
        }
  });

REST Response

This route’s response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "locations",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"locations": [
		{
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Update Category API

Update an existing category. Only admin allowed. Slug uniqueness enforced.

API Frontend Description By The Backend Architect

Admins can update any field of a category including parent/child relationships. Changing parentCategoryId triggers structure update. Slug must remain unique.

Rest Route

The updateCategory API REST controller can be triggered via the following route:

/v1/categories/:categoryId

Rest Request Parameters

The updateCategory api has got 7 regular request parameters

Parameter Type Required Population
categoryId ID true request.params?.[“categoryId”]
description Text false request.body?.[“description”]
icon String false request.body?.[“icon”]
name String false request.body?.[“name”]
parentCategoryId ID false request.body?.[“parentCategoryId”]
slug String false request.body?.[“slug”]
sortOrder Integer false request.body?.[“sortOrder”]
categoryId : This id paremeter is used to select the required data object that will be updated
description : Optional extended description for category (for admin display or frontend info).
icon : Icon identifier (string or URL to a static asset) for this category.
name : Category name, e.g. ‘Automobiles’, ‘Electronics’.
parentCategoryId : References parent category for hierarchy. Top-level (root) categories have null.
slug : SEO-friendly unique slug for URL and search. Lowercase, hyphens only.
sortOrder : Order for listing within siblings. Unique per parent.

REST Request To access the api you can use the REST controller with the path PATCH /v1/categories/:categoryId

  axios({
    method: 'PATCH',
    url: `/v1/categories/${categoryId}`,
    data: {
            description:"Text",  
            icon:"String",  
            name:"String",  
            parentCategoryId:"ID",  
            slug:"String",  
            sortOrder:"Integer",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "category",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"category": {
		"id": "ID",
		"description": "Text",
		"icon": "String",
		"name": "String",
		"parentCategoryId": "ID",
		"slug": "String",
		"sortOrder": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Location API

Update existing location entry. Only admin allowed. Composite key must remain unique.

API Frontend Description By The Backend Architect

Admin-only. Location string fields (country, city, district) must not create a duplicate. Use for typo correction or boundary updates; minimal public usage.

Rest Route

The updateLocation API REST controller can be triggered via the following route:

/v1/locations/:locationId

Rest Request Parameters

The updateLocation api has got 7 regular request parameters

Parameter Type Required Population
locationId ID true request.params?.[“locationId”]
city String false request.body?.[“city”]
country String false request.body?.[“country”]
district String false request.body?.[“district”]
latitude Double false request.body?.[“latitude”]
longitude Double false request.body?.[“longitude”]
postalCode String false request.body?.[“postalCode”]
locationId : This id paremeter is used to select the required data object that will be updated
city : City name.
country : Country name (typically ‘Turkey’).
district : District name, for fine-grained search.
latitude : Latitude for map/search.
longitude : Longitude for map/search.
postalCode : Postal code for location.

REST Request To access the api you can use the REST controller with the path PATCH /v1/locations/:locationId

  axios({
    method: 'PATCH',
    url: `/v1/locations/${locationId}`,
    data: {
            city:"String",  
            country:"String",  
            district:"String",  
            latitude:"Double",  
            longitude:"Double",  
            postalCode:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "location",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"location": {
		"id": "ID",
		"city": "String",
		"country": "String",
		"district": "String",
		"latitude": "Double",
		"longitude": "Double",
		"postalCode": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

_fetch Listcategory API

System API to fetch list of category records for frontend application. Auto-generated, not visible in design.

Rest Route

The _fetchListCategory API REST controller can be triggered via the following route:

/v1/_fetchlistcategory

Rest Request Parameters

Filter Parameters

The _fetchListCategory api supports 3 optional filter parameters for filtering list results:

name (String): Category name, e.g. ‘Automobiles’, ‘Electronics’.

parentCategoryId (ID): References parent category for hierarchy. Top-level (root) categories have null.

slug (String): SEO-friendly unique slug for URL and search. Lowercase, hyphens only.

REST Request To access the api you can use the REST controller with the path GET /v1/_fetchlistcategory

  axios({
    method: 'GET',
    url: '/v1/_fetchlistcategory',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // name: '<value>' // Filter by name
        // parentCategoryId: '<value>' // Filter by parentCategoryId
        // slug: '<value>' // Filter by slug
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "categories",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"categories": [
		{
			"id": "ID",
			"description": "Text",
			"icon": "String",
			"name": "String",
			"parentCategoryId": "ID",
			"slug": "String",
			"sortOrder": "Integer",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"parent": [
				{
					"description": "Text",
					"icon": "String",
					"name": "String",
					"parentCategoryId": "ID",
					"slug": "String",
					"sortOrder": "Integer"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

_fetch Listlocation API

System API to fetch list of location records for frontend application. Auto-generated, not visible in design.

Rest Route

The _fetchListLocation API REST controller can be triggered via the following route:

/v1/_fetchlistlocation

Rest Request Parameters

Filter Parameters

The _fetchListLocation api supports 3 optional filter parameters for filtering list results:

city (String): City name.

country (String): Country name (typically ‘Turkey’).

district (String): District name, for fine-grained search.

REST Request To access the api you can use the REST controller with the path GET /v1/_fetchlistlocation

  axios({
    method: 'GET',
    url: '/v1/_fetchlistlocation',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // city: '<value>' // Filter by city
        // country: '<value>' // Filter by country
        // district: '<value>' // Filter by district
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "locations",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"locations": [
		{
			"id": "ID",
			"city": "String",
			"country": "String",
			"district": "String",
			"latitude": "Double",
			"longitude": "Double",
			"postalCode": "String",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

After this prompt, the user may give you new instructions to update the output of this prompt or provide subsequent prompts about the project.


CLONESAHIBINDEN

FRONTEND GUIDE FOR AI CODING AGENTS - PART 8 - Conversation Service

This document is a part of a REST API guide for the clonesahibinden project. It is designed for AI agents that will generate frontend code to consume the project’s backend.

This document provides extensive instruction for the usage of conversation

Service Access

Conversation service management is handled through service specific base urls.

Conversation service may be deployed to the preview server, staging server, or production server. Therefore,it has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the login page (already handled in first part.).

For the conversation service, the base URLs are:

Scope

Conversation Service Description

Manages user-to-user messaging threads tied to listings, with message storage, read/unread and moderation support.

Conversation service provides apis and business logic for following data objects in clonesahibinden application. Each data object may be either a central domain of the application data structure or a related helper data object for a central concept. Note that data object concept is equal to table concept in the database, in the service database each data object is represented as a db table scheme and the object instances as table rows.

conversationMessage Data Object: A single message sent between two users within a conversation about a listing. Tracks sender, receiver, timestamps and read status.

conversationThread Data Object: Private messaging thread between two users regarding a specific listing. Unique per (listing, user pair), order-invariant. Tracks last message time for inbox sorting.

Conversation Service Frontend Description By The Backend Architect

Conversation Microservice UX Guidance

API Structure

Object Structure of a Successful Response

When the service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope includes the data and essential metadata such as configuration details and pagination information, providing context to the client.

HTTP Status Codes:

Success Response Format:

For successful operations, the response includes a "status": "OK" property, signaling that the request executed successfully. The structure of a successful response is outlined below:

{
  "status":"OK",
  "statusCode": 200,   
  "elapsedMs":126,
  "ssoTime":120,
  "source": "db",
  "cacheKey": "hexCode",
  "userId": "ID",
  "sessionId": "ID",
  "requestId": "ID",
  "dataName":"products",
  "method":"GET",
  "action":"list",
  "appVersion":"Version",
  "rowCount":3,
  "products":[{},{},{}],
  "paging": {
    "pageNumber":1, 
    "pageRowCount":25, 
    "totalRowCount":3,
    "pageCount":1
  },
  "filters": [],
  "uiPermissions": []
}

Additional Data

Each API may include additional data besides the main data object, depending on the business logic of the API. These will be provided in each API’s response signature.

Error Response

If a request encounters an issue—whether due to a logical fault or a technical problem—the service responds with a standardized JSON error structure. The HTTP status code indicates the nature of the error, using commonly recognized codes for clarity:

Each error response is structured to provide meaningful insight into the problem, assisting in efficient diagnosis and resolution.

{
  "result": "ERR",
  "status": 400,
  "message": "errMsg_organizationIdisNotAValidID",
  "errCode": 400,
  "date": "2024-03-19T12:13:54.124Z",
  "detail": "String"
}

Bucket Management

(This information is also given in PART 1 prompt.)

This application has a bucket service used to store user files and other object-related files. The bucket service is login-agnostic, so for write operations or private reads, include a bucket token (provided by services) in the request’s Authorization header as a Bearer token.

Please note that all other business services require the access token in the Bearer header, while the bucket service expects a bucket token because it is login-agnostic. Ensure you manage the required token injection properly; any auth interceptor should not replace the bucket token with the access token.

User Bucket This bucket stores public user files for each user.

When a user logs in—or in the /currentuser response—there is a userBucketToken to use when sending user-related public files to the bucket service.

{
  //...
  "userBucketToken": "e56d...."
}

To upload a file

POST {baseUrl}/bucket/upload

The request body is form-data which includes the bucketId and the file binary in the files field.

{
    bucketId: "{userId}-public-user-bucket",
    files: {binary}
}

Response status is 200 on success, e.g., body:

{
    "success": true,
    "data": [
        {
            "fileId": "9da03f6d-0409-41ad-bb06-225a244ae408",
            "originalName": "test (10).png",
            "mimeType": "image/png",
            "size": 604063,
            "status": "uploaded",
            "bucketName": "f7103b85-fcda-4dec-92c6-c336f71fd3a2-public-user-bucket",
            "isPublic": true,
            "downloadUrl": "https://babilcom.mindbricks.co/bucket/download/9da03f6d-0409-41ad-bb06-225a244ae408"
        }
    ]
}

To download a file from the bucket, you need its fileId. If you upload an avatar or other asset, ensure the download URL or the fileId is stored in the backend.

Buckets are mostly used in object creations that require an additional file, such as a product image or user avatar. After uploading your image to the bucket, insert the returned download URL into the related property of the target object record.

Application Bucket

This Clonesahibinden application also includes a common public bucket that anyone can read, but only users with the superAdmin, admin, or saasAdmin roles can write (upload) to it.

When a user with one of these admin roles is logged in, the /login response or the /currentuser response also returns an applicationBucketToken field, which is used when uploading any file to the application bucket.

{
  //...
  "applicationBucketToken": "e23fd...."
}

The common public application bucket ID is

"clonesahibinden-public-common-bucket"

In certain admin areas—such as product management pages—since the user already has the application bucket token, they will be able to upload related object images.

Please configure your UI to upload files to the application bucket using this bucket token whenever needed.

Object Buckets Some objects may also return a bucket token for uploading or accessing files related to that object. For example, in a project management application, when you fetch a project’s data, a public or private bucket token may be provided to upload or download project-related files.

These buckets will be used as described in the relevant object definitions.

ConversationMessage Data Object

A single message sent between two users within a conversation about a listing. Tracks sender, receiver, timestamps and read status.

ConversationMessage Data Object Frontend Description By The Backend Architect

Represents individual messages inside a conversation. Sender and receiver must match the thread participants. Users only see their own conversations and messages. Moderators can view all.

ConversationMessage Data Object Properties

ConversationMessage data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
content Text false Yes No Message text body. Sanitized before saving.
conversationThreadId ID false Yes No Parent thread for this message.
isRead Boolean false Yes No True if the receiver has read this message.
readAt Date false No No Timestamp when the receiver read the message (null if unread).
receiverId ID false Yes No User receiving the message (must be the other participant of the thread).
senderId ID false Yes No User sending the message (must be a participant of the thread).
sentAt Date false Yes No Timestamp when message was sent.

Relation Properties

conversationThreadId receiverId senderId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one.

In frontend, please ensure that,

1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

ConversationThread Data Object

Private messaging thread between two users regarding a specific listing. Unique per (listing, user pair), order-invariant. Tracks last message time for inbox sorting.

ConversationThread Data Object Frontend Description By The Backend Architect

Each thread uniquely represents all messages between two users about one listing. Users see these in inbox; moderators can list/search all for review.

ConversationThread Data Object Properties

ConversationThread data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
lastMessageAt Date false Yes No Date/time of the latest message in the thread (for sorting inbox).
listingId ID false Yes No ID of the listing being discussed.
receiverId ID false Yes No User B in the conversation (order-invariant with senderId).
senderId ID false Yes No User A in the conversation (order-invariant with receiverId).

Relation Properties

listingId receiverId senderId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one.

In frontend, please ensure that,

1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

Default CRUD APIs

For each data object, the backend architect may designate default APIs for standard operations (create, update, delete, get, list). These are the APIs that frontend CRUD forms and AI agents should use for basic record management. If no default is explicitly set (isDefaultApi), the frontend generator auto-discovers the most general API for each operation.

ConversationMessage Default APIs

Operation API Name Route Explicitly Set
Create createConversationMessage /v1/conversationmessages Auto
Update markMessageAsRead /v1/markmessageasread/:conversationMessageId Auto
Delete deleteConversationMessage /v1/conversationmessages/:conversationMessageId Auto
Get getConversationMessage /v1/conversationmessages/:conversationMessageId Auto
List listConversationMessages /v1/listconversationmessages/:conversationThreadId System

ConversationThread Default APIs

Operation API Name Route Explicitly Set
Create createConversationThread /v1/conversationthreads Auto
Update none - Auto
Delete none - Auto
Get getConversationThread /v1/conversationthreads/:conversationThreadId Auto
List listConversationThreads /v1/conversationthreads System

When building CRUD forms for a data object, use the default create/update APIs listed above. The form fields should correspond to the API’s body parameters. For relation fields, render a dropdown loaded from the related object’s list API using the display label property.

API Reference

Create Conversationmessage API

Send a new message in a conversation. Only thread participants can send; updates thread’s lastMessageAt.

API Frontend Description By The Backend Architect

Used when a user sends a message in a conversation (thread). On success, new message appears in thread; unread by receiver.

Rest Route

The createConversationMessage API REST controller can be triggered via the following route:

/v1/conversationmessages

Rest Request Parameters

The createConversationMessage api has got 7 regular request parameters

Parameter Type Required Population
content Text true request.body?.[“content”]
conversationThreadId ID true request.body?.[“conversationThreadId”]
isRead Boolean true request.body?.[“isRead”]
readAt Date false request.body?.[“readAt”]
receiverId ID true request.body?.[“receiverId”]
senderId ID true request.body?.[“senderId”]
sentAt Date true request.body?.[“sentAt”]
content : Message text body. Sanitized before saving.
conversationThreadId : Parent thread for this message.
isRead : True if the receiver has read this message.
readAt : Timestamp when the receiver read the message (null if unread).
receiverId : User receiving the message (must be the other participant of the thread).
senderId : User sending the message (must be a participant of the thread).
sentAt : Timestamp when message was sent.

REST Request To access the api you can use the REST controller with the path POST /v1/conversationmessages

  axios({
    method: 'POST',
    url: '/v1/conversationmessages',
    data: {
            content:"Text",  
            conversationThreadId:"ID",  
            isRead:"Boolean",  
            readAt:"Date",  
            receiverId:"ID",  
            senderId:"ID",  
            sentAt:"Date",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "conversationMessage",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"conversationMessage": {
		"id": "ID",
		"content": "Text",
		"conversationThreadId": "ID",
		"isRead": "Boolean",
		"readAt": "Date",
		"receiverId": "ID",
		"senderId": "ID",
		"sentAt": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Create Conversationthread API

Starts a new conversation thread between two users for a specific listing. Prevents duplicate threads for the same user pair/listing.

API Frontend Description By The Backend Architect

Invoked when user contacts seller about a listing. If an existing thread exists for this user pair/listing (any order), it is reused. Only listing owner or buyers can start a thread.

Rest Route

The createConversationThread API REST controller can be triggered via the following route:

/v1/conversationthreads

Rest Request Parameters

The createConversationThread api has got 4 regular request parameters

Parameter Type Required Population
lastMessageAt Date true request.body?.[“lastMessageAt”]
listingId ID true request.body?.[“listingId”]
receiverId ID true request.body?.[“receiverId”]
senderId ID true request.body?.[“senderId”]
lastMessageAt : Date/time of the latest message in the thread (for sorting inbox).
listingId : ID of the listing being discussed.
receiverId : User B in the conversation (order-invariant with senderId).
senderId : User A in the conversation (order-invariant with receiverId).

REST Request To access the api you can use the REST controller with the path POST /v1/conversationthreads

  axios({
    method: 'POST',
    url: '/v1/conversationthreads',
    data: {
            lastMessageAt:"Date",  
            listingId:"ID",  
            receiverId:"ID",  
            senderId:"ID",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "conversationThread",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"conversationThread": {
		"id": "ID",
		"lastMessageAt": "Date",
		"listingId": "ID",
		"receiverId": "ID",
		"senderId": "ID",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Delete Conversationmessage API

Soft-deletes a message. Only moderator/admins can fully delete; users may hide/delete for self (future phase).

API Frontend Description By The Backend Architect

Used for moderation; message remains for audit trail/history.

Rest Route

The deleteConversationMessage API REST controller can be triggered via the following route:

/v1/conversationmessages/:conversationMessageId

Rest Request Parameters

The deleteConversationMessage api has got 1 regular request parameter

Parameter Type Required Population
conversationMessageId ID true request.params?.[“conversationMessageId”]
conversationMessageId : This id paremeter is used to select the required data object that will be deleted

REST Request To access the api you can use the REST controller with the path DELETE /v1/conversationmessages/:conversationMessageId

  axios({
    method: 'DELETE',
    url: `/v1/conversationmessages/${conversationMessageId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "conversationMessage",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"conversationMessage": {
		"id": "ID",
		"content": "Text",
		"conversationThreadId": "ID",
		"isRead": "Boolean",
		"readAt": "Date",
		"receiverId": "ID",
		"senderId": "ID",
		"sentAt": "Date",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Conversationmessage API

Fetch a single message by ID. Only accessible to participants or moderators/admins.

API Frontend Description By The Backend Architect

Loads a message for display in UI. Fails if not participant or staff.

Rest Route

The getConversationMessage API REST controller can be triggered via the following route:

/v1/conversationmessages/:conversationMessageId

Rest Request Parameters

The getConversationMessage api has got 1 regular request parameter

Parameter Type Required Population
conversationMessageId ID true request.params?.[“conversationMessageId”]
conversationMessageId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/conversationmessages/:conversationMessageId

  axios({
    method: 'GET',
    url: `/v1/conversationmessages/${conversationMessageId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "conversationMessage",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"conversationMessage": {
		"id": "ID",
		"content": "Text",
		"conversationThreadId": "ID",
		"isRead": "Boolean",
		"readAt": "Date",
		"receiverId": "ID",
		"senderId": "ID",
		"sentAt": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Conversationthread API

Get a conversation thread by ID. Only visible to participants or staff.

API Frontend Description By The Backend Architect

Shows full thread info for inbox/detail view. Fails if user does not participate or is not moderator/admin.

Rest Route

The getConversationThread API REST controller can be triggered via the following route:

/v1/conversationthreads/:conversationThreadId

Rest Request Parameters

The getConversationThread api has got 1 regular request parameter

Parameter Type Required Population
conversationThreadId ID true request.params?.[“conversationThreadId”]
conversationThreadId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/conversationthreads/:conversationThreadId

  axios({
    method: 'GET',
    url: `/v1/conversationthreads/${conversationThreadId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

This route’s response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "conversationThread",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"conversationThread": {
		"listing": {
			"status": "Enum",
			"status_idx": "Integer",
			"title": "String",
			"userId": "ID"
		},
		"isActive": true
	}
}

List Conversationmessages API

List all messages in a thread, sorted oldest to newest. Only accessible to thread participants or staff.

API Frontend Description By The Backend Architect

Loads the chat history in UI for reading; includes isRead, sender info, etc. Used for conversation detail view.

Rest Route

The listConversationMessages API REST controller can be triggered via the following route:

/v1/listconversationmessages/:conversationThreadId

Rest Request Parameters

The listConversationMessages api has got 1 regular request parameter

Parameter Type Required Population
conversationThreadId ID true request.query?.[“conversationThreadId”]
conversationThreadId : Thread to load messages from.

REST Request To access the api you can use the REST controller with the path GET /v1/listconversationmessages/:conversationThreadId

  axios({
    method: 'GET',
    url: `/v1/listconversationmessages/${conversationThreadId}`,
    data: {
    
    },
    params: {
             conversationThreadId:'"ID"',  
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "conversationMessages",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"conversationMessages": [
		{
			"id": "ID",
			"content": "Text",
			"conversationThreadId": "ID",
			"isRead": "Boolean",
			"readAt": "Date",
			"receiverId": "ID",
			"senderId": "ID",
			"sentAt": "Date",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

List Conversationthreads API

List all threads a user participates in, most recent first. Also used for moderator search/all-list.

API Frontend Description By The Backend Architect

Shows all user’s conversation threads in inbox. Moderators can search all.

Rest Route

The listConversationThreads API REST controller can be triggered via the following route:

/v1/conversationthreads

Rest Request Parameters The listConversationThreads api has got no request parameters.

REST Request To access the api you can use the REST controller with the path GET /v1/conversationthreads

  axios({
    method: 'GET',
    url: '/v1/conversationthreads',
    data: {
    
    },
    params: {
    
        }
  });

REST Response

This route’s response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "conversationThreads",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"conversationThreads": [
		{
			"listing": [
				{
					"status": "Enum",
					"status_idx": "Integer",
					"title": "String",
					"userId": "ID"
				},
				{},
				{}
			],
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Mark Messageasread API

Marks a message as read (isRead=true, readAt=now); only allowed for receiver.

API Frontend Description By The Backend Architect

When viewing messages, receiver marks message as read – triggers unread count decrement in UI, updates message status.

Rest Route

The markMessageAsRead API REST controller can be triggered via the following route:

/v1/markmessageasread/:conversationMessageId

Rest Request Parameters

The markMessageAsRead api has got 3 regular request parameters

Parameter Type Required Population
conversationMessageId ID true request.params?.[“conversationMessageId”]
isRead Boolean false request.body?.[“isRead”]
readAt Date false request.body?.[“readAt”]
conversationMessageId : This id paremeter is used to select the required data object that will be updated
isRead : True if the receiver has read this message.
readAt : Timestamp when the receiver read the message (null if unread).

REST Request To access the api you can use the REST controller with the path PATCH /v1/markmessageasread/:conversationMessageId

  axios({
    method: 'PATCH',
    url: `/v1/markmessageasread/${conversationMessageId}`,
    data: {
            isRead:"Boolean",  
            readAt:"Date",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "conversationMessage",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"conversationMessage": {
		"id": "ID",
		"content": "Text",
		"conversationThreadId": "ID",
		"isRead": "Boolean",
		"readAt": "Date",
		"receiverId": "ID",
		"senderId": "ID",
		"sentAt": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

_fetch Listconversationmessage API

System API to fetch list of conversationMessage records for frontend application. Auto-generated, not visible in design.

Rest Route

The _fetchListConversationMessage API REST controller can be triggered via the following route:

/v1/_fetchlistconversationmessage

Rest Request Parameters The _fetchListConversationMessage api has got no request parameters.

REST Request To access the api you can use the REST controller with the path GET /v1/_fetchlistconversationmessage

  axios({
    method: 'GET',
    url: '/v1/_fetchlistconversationmessage',
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "conversationMessages",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"conversationMessages": [
		{
			"id": "ID",
			"content": "Text",
			"conversationThreadId": "ID",
			"isRead": "Boolean",
			"readAt": "Date",
			"receiverId": "ID",
			"senderId": "ID",
			"sentAt": "Date",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"thread": [
				{
					"lastMessageAt": "Date",
					"listingId": "ID",
					"receiverId": "ID",
					"senderId": "ID"
				},
				{},
				{}
			],
			"receiverUser": [
				{
					"fullname": "String"
				},
				{},
				{}
			],
			"senderUser": [
				{
					"fullname": "String"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

_fetch Listconversationthread API

System API to fetch list of conversationThread records for frontend application. Auto-generated, not visible in design.

Rest Route

The _fetchListConversationThread API REST controller can be triggered via the following route:

/v1/_fetchlistconversationthread

Rest Request Parameters The _fetchListConversationThread api has got no request parameters.

REST Request To access the api you can use the REST controller with the path GET /v1/_fetchlistconversationthread

  axios({
    method: 'GET',
    url: '/v1/_fetchlistconversationthread',
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "conversationThreads",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"conversationThreads": [
		{
			"id": "ID",
			"lastMessageAt": "Date",
			"listingId": "ID",
			"receiverId": "ID",
			"senderId": "ID",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"listing": [
				{
					"attributes": "Object",
					"categoryId": "ID",
					"condition": "Enum",
					"condition_idx": "Integer",
					"contactEmail": "String",
					"contactPhone": "String",
					"currency": "String",
					"description": "Text",
					"expiresAt": "Date",
					"favoriteCount": "Integer",
					"isPremium": "Boolean",
					"listingType": "Enum",
					"listingType_idx": "Integer",
					"locationId": "ID",
					"_paymentConfirmation": "String",
					"premiumExpiry": "Date",
					"premiumType": "Enum",
					"premiumType_idx": "Integer",
					"price": "Double",
					"status": "Enum",
					"status_idx": "Integer",
					"subcategoryId": "ID",
					"title": "String",
					"userId": "ID",
					"viewsCount": "Integer"
				},
				{},
				{}
			],
			"receiverUser": [
				{
					"fullname": "String"
				},
				{},
				{}
			],
			"senderUser": [
				{
					"fullname": "String"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

After this prompt, the user may give you new instructions to update the output of this prompt or provide subsequent prompts about the project.


CLONESAHIBINDEN

FRONTEND GUIDE FOR AI CODING AGENTS - PART 9 - Favorite Service

This document is a part of a REST API guide for the clonesahibinden project. It is designed for AI agents that will generate frontend code to consume the project’s backend.

This document provides extensive instruction for the usage of favorite

Service Access

Favorite service management is handled through service specific base urls.

Favorite service may be deployed to the preview server, staging server, or production server. Therefore,it has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the login page (already handled in first part.).

For the favorite service, the base URLs are:

Scope

Favorite Service Description

Handles all user favorites for classified listings, including add/remove, listing user-specific collections, and providing favorited status for listings. Prevents duplicate favorites and maintains favorite counts on listings for optimal UX. Cascade-cleans favorites if user or listing is deleted.

Favorite service provides apis and business logic for following data objects in clonesahibinden application. Each data object may be either a central domain of the application data structure or a related helper data object for a central concept. Note that data object concept is equal to table concept in the database, in the service database each data object is represented as a db table scheme and the object instances as table rows.

favorite Data Object: Stores which user favorited which listing, with timestamp. Enforces unique favorites per (user,listing) pair, and cascades on user/listing deletion.

Favorite Service Frontend Description By The Backend Architect

AI Dev: All favoriting actions require login. The UX must make favoriting/unfavoriting instant, providing clear feedback (heart icon animation, etc). The ‘Favorites’ page should show listing summary (titles and cover image at minimum). Show an “Already favorited” state in listing cards and details for each listing display. Any removal/addition must be reflected immediately in all screens due to eventual consistency (favoriteCount). For each listing in feeds or details, display if favorited by current user by pulling the user’s favorites or calling getFavorite for relevant pair. Listing favorite count must update optimistically on the UI after favorite/unfavorite. Do not allow favoriting own listings (enforced by backend API as well).

API Structure

Object Structure of a Successful Response

When the service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope includes the data and essential metadata such as configuration details and pagination information, providing context to the client.

HTTP Status Codes:

Success Response Format:

For successful operations, the response includes a "status": "OK" property, signaling that the request executed successfully. The structure of a successful response is outlined below:

{
  "status":"OK",
  "statusCode": 200,   
  "elapsedMs":126,
  "ssoTime":120,
  "source": "db",
  "cacheKey": "hexCode",
  "userId": "ID",
  "sessionId": "ID",
  "requestId": "ID",
  "dataName":"products",
  "method":"GET",
  "action":"list",
  "appVersion":"Version",
  "rowCount":3,
  "products":[{},{},{}],
  "paging": {
    "pageNumber":1, 
    "pageRowCount":25, 
    "totalRowCount":3,
    "pageCount":1
  },
  "filters": [],
  "uiPermissions": []
}

Additional Data

Each API may include additional data besides the main data object, depending on the business logic of the API. These will be provided in each API’s response signature.

Error Response

If a request encounters an issue—whether due to a logical fault or a technical problem—the service responds with a standardized JSON error structure. The HTTP status code indicates the nature of the error, using commonly recognized codes for clarity:

Each error response is structured to provide meaningful insight into the problem, assisting in efficient diagnosis and resolution.

{
  "result": "ERR",
  "status": 400,
  "message": "errMsg_organizationIdisNotAValidID",
  "errCode": 400,
  "date": "2024-03-19T12:13:54.124Z",
  "detail": "String"
}

Bucket Management

(This information is also given in PART 1 prompt.)

This application has a bucket service used to store user files and other object-related files. The bucket service is login-agnostic, so for write operations or private reads, include a bucket token (provided by services) in the request’s Authorization header as a Bearer token.

Please note that all other business services require the access token in the Bearer header, while the bucket service expects a bucket token because it is login-agnostic. Ensure you manage the required token injection properly; any auth interceptor should not replace the bucket token with the access token.

User Bucket This bucket stores public user files for each user.

When a user logs in—or in the /currentuser response—there is a userBucketToken to use when sending user-related public files to the bucket service.

{
  //...
  "userBucketToken": "e56d...."
}

To upload a file

POST {baseUrl}/bucket/upload

The request body is form-data which includes the bucketId and the file binary in the files field.

{
    bucketId: "{userId}-public-user-bucket",
    files: {binary}
}

Response status is 200 on success, e.g., body:

{
    "success": true,
    "data": [
        {
            "fileId": "9da03f6d-0409-41ad-bb06-225a244ae408",
            "originalName": "test (10).png",
            "mimeType": "image/png",
            "size": 604063,
            "status": "uploaded",
            "bucketName": "f7103b85-fcda-4dec-92c6-c336f71fd3a2-public-user-bucket",
            "isPublic": true,
            "downloadUrl": "https://babilcom.mindbricks.co/bucket/download/9da03f6d-0409-41ad-bb06-225a244ae408"
        }
    ]
}

To download a file from the bucket, you need its fileId. If you upload an avatar or other asset, ensure the download URL or the fileId is stored in the backend.

Buckets are mostly used in object creations that require an additional file, such as a product image or user avatar. After uploading your image to the bucket, insert the returned download URL into the related property of the target object record.

Application Bucket

This Clonesahibinden application also includes a common public bucket that anyone can read, but only users with the superAdmin, admin, or saasAdmin roles can write (upload) to it.

When a user with one of these admin roles is logged in, the /login response or the /currentuser response also returns an applicationBucketToken field, which is used when uploading any file to the application bucket.

{
  //...
  "applicationBucketToken": "e23fd...."
}

The common public application bucket ID is

"clonesahibinden-public-common-bucket"

In certain admin areas—such as product management pages—since the user already has the application bucket token, they will be able to upload related object images.

Please configure your UI to upload files to the application bucket using this bucket token whenever needed.

Object Buckets Some objects may also return a bucket token for uploading or accessing files related to that object. For example, in a project management application, when you fetch a project’s data, a public or private bucket token may be provided to upload or download project-related files.

These buckets will be used as described in the relevant object definitions.

Favorite Data Object

Stores which user favorited which listing, with timestamp. Enforces unique favorites per (user,listing) pair, and cascades on user/listing deletion.

Favorite Data Object Frontend Description By The Backend Architect

AI Dev: Each favorite represents a single (user,listing) pair—no duplicate favorites allowed. Used for rendering heart/check in listing cards and assembling user’s favorites page. Listing preview must be fetched alongside favorite info.

Favorite Data Object Properties

Favorite data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
favoritedAt Date false Yes No Date and time when the favorite was added.
listingId ID false Yes No Target listing being favorited.
userId ID false Yes No User who favorited the listing.

Relation Properties

listingId userId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one.

In frontend, please ensure that,

1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

Default CRUD APIs

For each data object, the backend architect may designate default APIs for standard operations (create, update, delete, get, list). These are the APIs that frontend CRUD forms and AI agents should use for basic record management. If no default is explicitly set (isDefaultApi), the frontend generator auto-discovers the most general API for each operation.

Favorite Default APIs

Operation API Name Route Explicitly Set
Create createFavorite /v1/favorites Auto
Update none - Auto
Delete deleteFavorite /v1/favorites/:favoriteId Auto
Get getFavorite /v1/favorites/:favoriteId Auto
List listFavorites /v1/favorites System

When building CRUD forms for a data object, use the default create/update APIs listed above. The form fields should correspond to the API’s body parameters. For relation fields, render a dropdown loaded from the related object’s list API using the display label property.

API Reference

Create Favorite API

Add a favorite for a listing for the current user. Prevents duplicate (user,listing) pairs, and can’t favorite own listing.

API Frontend Description By The Backend Architect

AI Dev: Call this API to favorite a listing; on success, update UI state and increment count. If already favorited, show appropriate feedback. Cannot favorite own listings. No double favoriting allowed.

Rest Route

The createFavorite API REST controller can be triggered via the following route:

/v1/favorites

Rest Request Parameters

The createFavorite api has got 1 regular request parameter

Parameter Type Required Population
listingId ID true request.body?.[“listingId”]
listingId : Target listing being favorited.

REST Request To access the api you can use the REST controller with the path POST /v1/favorites

  axios({
    method: 'POST',
    url: '/v1/favorites',
    data: {
            listingId:"ID",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "favorite",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"favorite": {
		"id": "ID",
		"favoritedAt": "Date",
		"listingId": "ID",
		"userId": "ID",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Delete Favorite API

Unfavorite (remove favorite) the given listing for current user. Decrements favoriteCount on related listing when possible.

API Frontend Description By The Backend Architect

AI Dev: Use this API to unfavorite a listing. On success, update UI (remove highlight) and decrement displayed favorite count. If not found, treat as idempotent success for best UX.

Rest Route

The deleteFavorite API REST controller can be triggered via the following route:

/v1/favorites/:favoriteId

Rest Request Parameters

The deleteFavorite api has got 2 regular request parameters

Parameter Type Required Population
favoriteId ID true request.params?.[“favoriteId”]
listingId ID true request.query?.[“listingId”]
favoriteId : This id paremeter is used to select the required data object that will be deleted
listingId : Target listing being favorited… The parameter is used to query data.

REST Request To access the api you can use the REST controller with the path DELETE /v1/favorites/:favoriteId

  axios({
    method: 'DELETE',
    url: `/v1/favorites/${favoriteId}`,
    data: {
    
    },
    params: {
             listingId:'"ID"',  
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "favorite",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"favorite": {
		"id": "ID",
		"favoritedAt": "Date",
		"listingId": "ID",
		"userId": "ID",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Favorite API

Get a specific favorite by id or by userId+listingId, mainly used to check if a listing is favorited by user (for heart/check display in feeds/details). Only accessible by owner or admin.

API Frontend Description By The Backend Architect

AI Dev: Use to check if a given listing is in the user’s favorites; supports single-record fetch via id or userId+listingId composite. If no record, treat as not favorited in UI.

Rest Route

The getFavorite API REST controller can be triggered via the following route:

/v1/favorites/:favoriteId

Rest Request Parameters

The getFavorite api has got 1 regular request parameter

Parameter Type Required Population
favoriteId ID true request.params?.[“favoriteId”]
favoriteId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/favorites/:favoriteId

  axios({
    method: 'GET',
    url: `/v1/favorites/${favoriteId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

This route’s response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "favorite",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"favorite": {
		"listing": {
			"isPremium": "Boolean",
			"premiumType": "Enum",
			"premiumType_idx": "Integer",
			"price": "Double",
			"status": "Enum",
			"status_idx": "Integer",
			"title": "String"
		},
		"isActive": true
	}
}

List Favorites API

List all listings favorited by the current user, joined with listing summary and preview (title, price, cover image, etc). Private; only owner or admin can access.

API Frontend Description By The Backend Architect

AI Dev: Use this to render the user’s entire favorites collection for the profile page. Each item must provide at least listing id, title, price, and main image for visual feed. Paginate and sort newest first by favoritedAt.

Rest Route

The listFavorites API REST controller can be triggered via the following route:

/v1/favorites

Rest Request Parameters The listFavorites api has got no request parameters.

REST Request To access the api you can use the REST controller with the path GET /v1/favorites

  axios({
    method: 'GET',
    url: '/v1/favorites',
    data: {
    
    },
    params: {
    
        }
  });

REST Response

This route’s response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "favorites",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"favorites": [
		{
			"listing": [
				{
					"currency": "String",
					"isPremium": "Boolean",
					"premiumType": "Enum",
					"premiumType_idx": "Integer",
					"price": "Double",
					"status": "Enum",
					"status_idx": "Integer",
					"title": "String"
				},
				{},
				{}
			],
			"mainImage": {
				"sortOrder": "Integer",
				"thumbnailUrl": "String",
				"url": "String"
			},
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

_fetch Listfavorite API

System API to fetch list of favorite records for frontend application. Auto-generated, not visible in design.

Rest Route

The _fetchListFavorite API REST controller can be triggered via the following route:

/v1/_fetchlistfavorite

Rest Request Parameters The _fetchListFavorite api has got no request parameters.

REST Request To access the api you can use the REST controller with the path GET /v1/_fetchlistfavorite

  axios({
    method: 'GET',
    url: '/v1/_fetchlistfavorite',
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "favorites",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"favorites": [
		{
			"id": "ID",
			"favoritedAt": "Date",
			"listingId": "ID",
			"userId": "ID",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"listing": [
				{
					"attributes": "Object",
					"categoryId": "ID",
					"condition": "Enum",
					"condition_idx": "Integer",
					"contactEmail": "String",
					"contactPhone": "String",
					"currency": "String",
					"description": "Text",
					"expiresAt": "Date",
					"favoriteCount": "Integer",
					"isPremium": "Boolean",
					"listingType": "Enum",
					"listingType_idx": "Integer",
					"locationId": "ID",
					"_paymentConfirmation": "String",
					"premiumExpiry": "Date",
					"premiumType": "Enum",
					"premiumType_idx": "Integer",
					"price": "Double",
					"status": "Enum",
					"status_idx": "Integer",
					"subcategoryId": "ID",
					"title": "String",
					"userId": "ID",
					"viewsCount": "Integer"
				},
				{},
				{}
			],
			"user": [
				{
					"fullname": "String"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

After this prompt, the user may give you new instructions to update the output of this prompt or provide subsequent prompts about the project.


CLONESAHIBINDEN

FRONTEND GUIDE FOR AI CODING AGENTS - PART 10 - Listing Service

This document is a part of a REST API guide for the clonesahibinden project. It is designed for AI agents that will generate frontend code to consume the project’s backend.

This document provides extensive instruction for the usage of listing

Service Access

Listing service management is handled through service specific base urls.

Listing service may be deployed to the preview server, staging server, or production server. Therefore,it has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the login page (already handled in first part.).

For the listing service, the base URLs are:

Scope

Listing Service Description

Manages classified listings, their lifecycle, premium features, status transitions, and provides filtering/search for marketplace ads. Integrates with users, categories, locations, and Stripe for premium ad upgrades. Enforces ad and user type business logic.

Listing service provides apis and business logic for following data objects in clonesahibinden application. Each data object may be either a central domain of the application data structure or a related helper data object for a central concept. Note that data object concept is equal to table concept in the database, in the service database each data object is represented as a db table scheme and the object instances as table rows.

listing Data Object: Core object for classified ads. Contains main listing information, relations, status, premium logic, price, attributes, contact info, and custom attributes. Supports premium upgrades via Stripe and lifecycle management.

sys_listingPayment Data Object: A payment storage object to store the payment life cyle of orders based on listing object. It is autocreated based on the source object's checkout config

sys_paymentCustomer Data Object: A payment storage object to store the customer values of the payment platform

sys_paymentMethod Data Object: A payment storage object to store the payment methods of the platform customers

Listing Service Frontend Description By The Backend Architect

Listing Service UX Hints

API Structure

Object Structure of a Successful Response

When the service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope includes the data and essential metadata such as configuration details and pagination information, providing context to the client.

HTTP Status Codes:

Success Response Format:

For successful operations, the response includes a "status": "OK" property, signaling that the request executed successfully. The structure of a successful response is outlined below:

{
  "status":"OK",
  "statusCode": 200,   
  "elapsedMs":126,
  "ssoTime":120,
  "source": "db",
  "cacheKey": "hexCode",
  "userId": "ID",
  "sessionId": "ID",
  "requestId": "ID",
  "dataName":"products",
  "method":"GET",
  "action":"list",
  "appVersion":"Version",
  "rowCount":3,
  "products":[{},{},{}],
  "paging": {
    "pageNumber":1, 
    "pageRowCount":25, 
    "totalRowCount":3,
    "pageCount":1
  },
  "filters": [],
  "uiPermissions": []
}

Additional Data

Each API may include additional data besides the main data object, depending on the business logic of the API. These will be provided in each API’s response signature.

Error Response

If a request encounters an issue—whether due to a logical fault or a technical problem—the service responds with a standardized JSON error structure. The HTTP status code indicates the nature of the error, using commonly recognized codes for clarity:

Each error response is structured to provide meaningful insight into the problem, assisting in efficient diagnosis and resolution.

{
  "result": "ERR",
  "status": 400,
  "message": "errMsg_organizationIdisNotAValidID",
  "errCode": 400,
  "date": "2024-03-19T12:13:54.124Z",
  "detail": "String"
}

Bucket Management

(This information is also given in PART 1 prompt.)

This application has a bucket service used to store user files and other object-related files. The bucket service is login-agnostic, so for write operations or private reads, include a bucket token (provided by services) in the request’s Authorization header as a Bearer token.

Please note that all other business services require the access token in the Bearer header, while the bucket service expects a bucket token because it is login-agnostic. Ensure you manage the required token injection properly; any auth interceptor should not replace the bucket token with the access token.

User Bucket This bucket stores public user files for each user.

When a user logs in—or in the /currentuser response—there is a userBucketToken to use when sending user-related public files to the bucket service.

{
  //...
  "userBucketToken": "e56d...."
}

To upload a file

POST {baseUrl}/bucket/upload

The request body is form-data which includes the bucketId and the file binary in the files field.

{
    bucketId: "{userId}-public-user-bucket",
    files: {binary}
}

Response status is 200 on success, e.g., body:

{
    "success": true,
    "data": [
        {
            "fileId": "9da03f6d-0409-41ad-bb06-225a244ae408",
            "originalName": "test (10).png",
            "mimeType": "image/png",
            "size": 604063,
            "status": "uploaded",
            "bucketName": "f7103b85-fcda-4dec-92c6-c336f71fd3a2-public-user-bucket",
            "isPublic": true,
            "downloadUrl": "https://babilcom.mindbricks.co/bucket/download/9da03f6d-0409-41ad-bb06-225a244ae408"
        }
    ]
}

To download a file from the bucket, you need its fileId. If you upload an avatar or other asset, ensure the download URL or the fileId is stored in the backend.

Buckets are mostly used in object creations that require an additional file, such as a product image or user avatar. After uploading your image to the bucket, insert the returned download URL into the related property of the target object record.

Application Bucket

This Clonesahibinden application also includes a common public bucket that anyone can read, but only users with the superAdmin, admin, or saasAdmin roles can write (upload) to it.

When a user with one of these admin roles is logged in, the /login response or the /currentuser response also returns an applicationBucketToken field, which is used when uploading any file to the application bucket.

{
  //...
  "applicationBucketToken": "e23fd...."
}

The common public application bucket ID is

"clonesahibinden-public-common-bucket"

In certain admin areas—such as product management pages—since the user already has the application bucket token, they will be able to upload related object images.

Please configure your UI to upload files to the application bucket using this bucket token whenever needed.

Object Buckets Some objects may also return a bucket token for uploading or accessing files related to that object. For example, in a project management application, when you fetch a project’s data, a public or private bucket token may be provided to upload or download project-related files.

These buckets will be used as described in the relevant object definitions.

Listing Data Object

Core object for classified ads. Contains main listing information, relations, status, premium logic, price, attributes, contact info, and custom attributes. Supports premium upgrades via Stripe and lifecycle management.

Listing Data Object Frontend Description By The Backend Architect

Data Object: listing

Listing Data Object Properties

Listing data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
attributes Object false No No JSON object for custom per-category attributes (structured as required by category schema).
categoryId ID false Yes No Main category for the listing (categoryLocation:category).
condition Enum false Yes No Item condition: new, used, other.
contactEmail String false No No Contact email (recommended to send via platform only).
contactPhone String false No No Display phone/contact for listing; may be masked by front end.
currency String false Yes No Currency (ISO-4217 code, e.g. ‘TRY’, ‘USD’).
description Text false Yes No Full description/body of listing.
expiresAt Date false No No UTC expiry for listing; after this, listing is automatically expired.
favoriteCount Integer false Yes No Favorite count (updated asynchronously by favorite service, not directly settable by user).
isPremium Boolean false Yes No If true, the listing is premium (highlighted/pinned, eligible for special placement).
listingType Enum false Yes No Type of listing (sale, rent, service, etc.).
locationId ID false Yes No Location (categoryLocation:location).
_paymentConfirmation String false No No Stripe payment result details (Stripe webhook metadata, internal use only).
premiumExpiry Date false No No UTC date when premium status expires. Null if not premium or not applicable.
premiumType Enum false No No Which premium package (gold, silver, none, etc.).
price Double false Yes No Listing price.
status Enum false Yes No Lifecycle status: pending_review, active, denied, sold, expired, deleted.
subcategoryId ID false No No Subcategory for the listing, can be null for top-level (categoryLocation:category).
title String false Yes No Listing title, short and clear.
userId ID false Yes No Owner (poster) of the listing (auth:user).
viewsCount Integer false Yes No View count (updated asynchronously; not directly settable by user).
paymentConfirmation Enum false Yes No An automatic property that is used to check the confirmed status of the payment set by webhooks.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an additional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options.

Relation Properties

categoryId locationId subcategoryId userId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one.

In frontend, please ensure that,

1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: No

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

Filter Properties

categoryId condition expiresAt isPremium listingType locationId premiumExpiry premiumType price status subcategoryId title userId paymentConfirmation

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.

Sys_listingPayment Data Object

A payment storage object to store the payment life cyle of orders based on listing object. It is autocreated based on the source object's checkout config

Sys_listingPayment Data Object Properties

Sys_listingPayment data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
ownerId ID false No No An ID value to represent owner user who created the order
orderId ID false Yes No an ID value to represent the orderId which is the ID parameter of the source listing object
paymentId String false Yes No A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type
paymentStatus String false Yes No A string value to represent the payment status which belongs to the lifecyle of a Stripe payment.
statusLiteral String false Yes No A string value to represent the logical payment status which belongs to the application lifecycle itself.
redirectUrl String false No No A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client.

Filter Properties

ownerId orderId paymentId paymentStatus statusLiteral redirectUrl

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.

Sys_paymentCustomer Data Object

A payment storage object to store the customer values of the payment platform

Sys_paymentCustomer Data Object Properties

Sys_paymentCustomer data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
userId ID false No No An ID value to represent the user who is created as a stripe customer
customerId String false Yes No A string value to represent the customer id which is generated on the Stripe gateway. This id is used to represent the customer in the Stripe gateway
platform String false Yes No A String value to represent payment platform which is used to make the payment. It is stripe as default. It will be used to distinguesh the payment gateways in the future.

Filter Properties

userId customerId platform

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.

Sys_paymentMethod Data Object

A payment storage object to store the payment methods of the platform customers

Sys_paymentMethod Data Object Properties

Sys_paymentMethod data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
paymentMethodId String false Yes No A string value to represent the id of the payment method on the payment platform.
userId ID false Yes No An ID value to represent the user who owns the payment method
customerId String false Yes No A string value to represent the customer id which is generated on the payment gateway.
cardHolderName String false No No A string value to represent the name of the card holder. It can be different than the registered customer.
cardHolderZip String false No No A string value to represent the zip code of the card holder. It is used for address verification in specific countries.
platform String false Yes No A String value to represent payment platform which teh paymentMethod belongs. It is stripe as default. It will be used to distinguesh the payment gateways in the future.
cardInfo Object false Yes No A Json value to store the card details of the payment method.

Filter Properties

paymentMethodId userId customerId cardHolderName cardHolderZip platform cardInfo

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.

Default CRUD APIs

For each data object, the backend architect may designate default APIs for standard operations (create, update, delete, get, list). These are the APIs that frontend CRUD forms and AI agents should use for basic record management. If no default is explicitly set (isDefaultApi), the frontend generator auto-discovers the most general API for each operation.

Listing Default APIs

Operation API Name Route Explicitly Set
Create createListing /v1/listings Auto
Update updateListing /v1/listings/:listingId Auto
Delete deleteListing /v1/listings/:listingId Auto
Get getListing /v1/listings/:listingId Auto
List listListings /v1/listings System

Sys_listingPayment Default APIs

Operation API Name Route Explicitly Set
Create createListingPayment /v1/listingpayment Auto
Update updateListingPayment /v1/listingpayment/:sys_listingPaymentId Auto
Delete deleteListingPayment /v1/listingpayment/:sys_listingPaymentId Auto
Get getListingPayment /v1/listingpayment/:sys_listingPaymentId Auto
List listListingPayments /v1/listingpayments System

Sys_paymentCustomer Default APIs

Operation API Name Route Explicitly Set
Create none - Auto
Update none - Auto
Delete none - Auto
Get getPaymentCustomerByUserId /v1/paymentcustomers/:userId Auto
List listPaymentCustomers /v1/paymentcustomers System

Sys_paymentMethod Default APIs

Operation API Name Route Explicitly Set
Create none - Auto
Update none - Auto
Delete none - Auto
Get none - Auto
List listPaymentCustomerMethods /v1/paymentcustomermethods/:userId System

When building CRUD forms for a data object, use the default create/update APIs listed above. The form fields should correspond to the API’s body parameters. For relation fields, render a dropdown loaded from the related object’s list API using the display label property.

API Reference

Create Listing API

Create a new classified listing. Sets status to ‘pending_review’ (may be updated by moderator process). Accepts all mandatory fields, accepts premiumType for premium upgrade.

API Frontend Description By The Backend Architect

Rest Route

The createListing API REST controller can be triggered via the following route:

/v1/listings

Rest Request Parameters

The createListing api has got 19 regular request parameters

Parameter Type Required Population
attributes Object false request.body?.[“attributes”]
categoryId ID true request.body?.[“categoryId”]
condition Enum true request.body?.[“condition”]
contactEmail String false request.body?.[“contactEmail”]
contactPhone String false request.body?.[“contactPhone”]
currency String true request.body?.[“currency”]
description Text true request.body?.[“description”]
expiresAt Date false request.body?.[“expiresAt”]
favoriteCount Integer true request.body?.[“favoriteCount”]
listingType Enum true request.body?.[“listingType”]
locationId ID true request.body?.[“locationId”]
_paymentConfirmation String false request.body?.[“_paymentConfirmation”]
premiumExpiry Date false request.body?.[“premiumExpiry”]
premiumType Enum false request.body?.[“premiumType”]
price Double true request.body?.[“price”]
status Enum true request.body?.[“status”]
subcategoryId ID false request.body?.[“subcategoryId”]
title String true request.body?.[“title”]
viewsCount Integer true request.body?.[“viewsCount”]
attributes : JSON object for custom per-category attributes (structured as required by category schema).
categoryId : Main category for the listing (categoryLocation:category).
condition : Item condition: new, used, other.
contactEmail : Contact email (recommended to send via platform only).
contactPhone : Display phone/contact for listing; may be masked by front end.
currency : Currency (ISO-4217 code, e.g. ‘TRY’, ‘USD’).
description : Full description/body of listing.
expiresAt : UTC expiry for listing; after this, listing is automatically expired.
favoriteCount : Favorite count (updated asynchronously by favorite service, not directly settable by user).
listingType : Type of listing (sale, rent, service, etc.).
locationId : Location (categoryLocation:location).
_paymentConfirmation : Stripe payment result details (Stripe webhook metadata, internal use only).
premiumExpiry : UTC date when premium status expires. Null if not premium or not applicable.
premiumType : Which premium package (gold, silver, none, etc.).
price : Listing price.
status : Lifecycle status: pending_review, active, denied, sold, expired, deleted.
subcategoryId : Subcategory for the listing, can be null for top-level (categoryLocation:category).
title : Listing title, short and clear.
viewsCount : View count (updated asynchronously; not directly settable by user).

REST Request To access the api you can use the REST controller with the path POST /v1/listings

  axios({
    method: 'POST',
    url: '/v1/listings',
    data: {
            attributes:"Object",  
            categoryId:"ID",  
            condition:"Enum",  
            contactEmail:"String",  
            contactPhone:"String",  
            currency:"String",  
            description:"Text",  
            expiresAt:"Date",  
            favoriteCount:"Integer",  
            listingType:"Enum",  
            locationId:"ID",  
            _paymentConfirmation:"String",  
            premiumExpiry:"Date",  
            premiumType:"Enum",  
            price:"Double",  
            status:"Enum",  
            subcategoryId:"ID",  
            title:"String",  
            viewsCount:"Integer",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listing",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"listing": {
		"id": "ID",
		"attributes": "Object",
		"categoryId": "ID",
		"condition": "Enum",
		"condition_idx": "Integer",
		"contactEmail": "String",
		"contactPhone": "String",
		"currency": "String",
		"description": "Text",
		"expiresAt": "Date",
		"favoriteCount": "Integer",
		"isPremium": "Boolean",
		"listingType": "Enum",
		"listingType_idx": "Integer",
		"locationId": "ID",
		"_paymentConfirmation": "String",
		"premiumExpiry": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"price": "Double",
		"status": "Enum",
		"status_idx": "Integer",
		"subcategoryId": "ID",
		"title": "String",
		"userId": "ID",
		"viewsCount": "Integer",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Delete Listing API

Delete a listing (soft delete, sets status to ‘deleted’). Only allowed by listing owner, admin, or moderator.

API Frontend Description By The Backend Architect

Rest Route

The deleteListing API REST controller can be triggered via the following route:

/v1/listings/:listingId

Rest Request Parameters

The deleteListing api has got 1 regular request parameter

Parameter Type Required Population
listingId ID true request.params?.[“listingId”]
listingId : This id paremeter is used to select the required data object that will be deleted

REST Request To access the api you can use the REST controller with the path DELETE /v1/listings/:listingId

  axios({
    method: 'DELETE',
    url: `/v1/listings/${listingId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listing",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"listing": {
		"id": "ID",
		"attributes": "Object",
		"categoryId": "ID",
		"condition": "Enum",
		"condition_idx": "Integer",
		"contactEmail": "String",
		"contactPhone": "String",
		"currency": "String",
		"description": "Text",
		"expiresAt": "Date",
		"favoriteCount": "Integer",
		"isPremium": "Boolean",
		"listingType": "Enum",
		"listingType_idx": "Integer",
		"locationId": "ID",
		"_paymentConfirmation": "String",
		"premiumExpiry": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"price": "Double",
		"status": "Enum",
		"status_idx": "Integer",
		"subcategoryId": "ID",
		"title": "String",
		"userId": "ID",
		"viewsCount": "Integer",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Expire Premiumsandlistings API

Scheduled job to expire listings or premium status as needed (cron call, not user). Sets status to expired, or disables isPremium when premiumExpiry is in the past.

API Frontend Description By The Backend Architect

Rest Route

The expirePremiumsAndListings API REST controller can be triggered via the following route:

/v1/expirepremiumsandlistings/:listingId

Rest Request Parameters

The expirePremiumsAndListings api has got 1 regular request parameter

Parameter Type Required Population
listingId ID true request.params?.[“listingId”]
listingId : This id paremeter is used to select the required data object that will be updated

REST Request To access the api you can use the REST controller with the path ** /v1/expirepremiumsandlistings/:listingId**

  axios({
    method: '',
    url: `/v1/expirepremiumsandlistings/${listingId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listing",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"listing": {
		"id": "ID",
		"attributes": "Object",
		"categoryId": "ID",
		"condition": "Enum",
		"condition_idx": "Integer",
		"contactEmail": "String",
		"contactPhone": "String",
		"currency": "String",
		"description": "Text",
		"expiresAt": "Date",
		"favoriteCount": "Integer",
		"isPremium": "Boolean",
		"listingType": "Enum",
		"listingType_idx": "Integer",
		"locationId": "ID",
		"_paymentConfirmation": "String",
		"premiumExpiry": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"price": "Double",
		"status": "Enum",
		"status_idx": "Integer",
		"subcategoryId": "ID",
		"title": "String",
		"userId": "ID",
		"viewsCount": "Integer",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Listing API

Retrieve one listing with all primary fields, including category, subcategory, location, user info. Optionally, frontend can request joined images/favorites from other services.

API Frontend Description By The Backend Architect

Rest Route

The getListing API REST controller can be triggered via the following route:

/v1/listings/:listingId

Rest Request Parameters

The getListing api has got 1 regular request parameter

Parameter Type Required Population
listingId ID true request.params?.[“listingId”]
listingId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/listings/:listingId

  axios({
    method: 'GET',
    url: `/v1/listings/${listingId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

This route’s response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listing",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"listing": {
		"user": {
			"fullname": "String",
			"avatar": "String",
			"roleId": "String"
		},
		"category": {
			"name": "String",
			"parentCategoryId": "ID",
			"slug": "String"
		},
		"subcategory": {
			"name": "String",
			"parentCategoryId": "ID",
			"slug": "String"
		},
		"location": {
			"city": "String",
			"country": "String",
			"district": "String"
		},
		"isActive": true
	}
}

List Listings API

Search/browse listings with advanced filtering (category, location, keyword, price range, condition, type, premium, status, etc.) and sorting. Publicly accessible. Supports pagination and all major sort orders. Full-text search on title/description.

API Frontend Description By The Backend Architect

Rest Route

The listListings API REST controller can be triggered via the following route:

/v1/listings

Rest Request Parameters The listListings api has got no request parameters.

REST Request To access the api you can use the REST controller with the path GET /v1/listings

  axios({
    method: 'GET',
    url: '/v1/listings',
    data: {
    
    },
    params: {
    
        }
  });

REST Response

This route’s response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listings",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"listings": [
		{
			"user": [
				{
					"fullname": "String",
					"avatar": "String"
				},
				{},
				{}
			],
			"category": [
				{
					"name": "String"
				},
				{},
				{}
			],
			"subcategory": [
				{
					"name": "String"
				},
				{},
				{}
			],
			"location": [
				{
					"city": "String",
					"district": "String"
				},
				{},
				{}
			],
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Update Listing API

Update any mutable field of a listing. Only allowed by owner, admin, or moderator. If significant fields change and listing is active, status may return to pending_review until approved.

API Frontend Description By The Backend Architect

Rest Route

The updateListing API REST controller can be triggered via the following route:

/v1/listings/:listingId

Rest Request Parameters

The updateListing api has got 17 regular request parameters

Parameter Type Required Population
listingId ID true request.params?.[“listingId”]
attributes Object false request.body?.[“attributes”]
categoryId ID false request.body?.[“categoryId”]
condition Enum false request.body?.[“condition”]
contactEmail String false request.body?.[“contactEmail”]
contactPhone String false request.body?.[“contactPhone”]
currency String false request.body?.[“currency”]
description Text false request.body?.[“description”]
expiresAt Date false request.body?.[“expiresAt”]
listingType Enum false request.body?.[“listingType”]
locationId ID false request.body?.[“locationId”]
premiumExpiry Date false request.body?.[“premiumExpiry”]
premiumType Enum false request.body?.[“premiumType”]
price Double false request.body?.[“price”]
status Enum false request.body?.[“status”]
subcategoryId ID false request.body?.[“subcategoryId”]
title String false request.body?.[“title”]
listingId : This id paremeter is used to select the required data object that will be updated
attributes : JSON object for custom per-category attributes (structured as required by category schema).
categoryId : Main category for the listing (categoryLocation:category).
condition : Item condition: new, used, other.
contactEmail : Contact email (recommended to send via platform only).
contactPhone : Display phone/contact for listing; may be masked by front end.
currency : Currency (ISO-4217 code, e.g. ‘TRY’, ‘USD’).
description : Full description/body of listing.
expiresAt : UTC expiry for listing; after this, listing is automatically expired.
listingType : Type of listing (sale, rent, service, etc.).
locationId : Location (categoryLocation:location).
premiumExpiry : UTC date when premium status expires. Null if not premium or not applicable.
premiumType : Which premium package (gold, silver, none, etc.).
price : Listing price.
status : Lifecycle status: pending_review, active, denied, sold, expired, deleted.
subcategoryId : Subcategory for the listing, can be null for top-level (categoryLocation:category).
title : Listing title, short and clear.

REST Request To access the api you can use the REST controller with the path PATCH /v1/listings/:listingId

  axios({
    method: 'PATCH',
    url: `/v1/listings/${listingId}`,
    data: {
            attributes:"Object",  
            categoryId:"ID",  
            condition:"Enum",  
            contactEmail:"String",  
            contactPhone:"String",  
            currency:"String",  
            description:"Text",  
            expiresAt:"Date",  
            listingType:"Enum",  
            locationId:"ID",  
            premiumExpiry:"Date",  
            premiumType:"Enum",  
            price:"Double",  
            status:"Enum",  
            subcategoryId:"ID",  
            title:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listing",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"listing": {
		"id": "ID",
		"attributes": "Object",
		"categoryId": "ID",
		"condition": "Enum",
		"condition_idx": "Integer",
		"contactEmail": "String",
		"contactPhone": "String",
		"currency": "String",
		"description": "Text",
		"expiresAt": "Date",
		"favoriteCount": "Integer",
		"isPremium": "Boolean",
		"listingType": "Enum",
		"listingType_idx": "Integer",
		"locationId": "ID",
		"_paymentConfirmation": "String",
		"premiumExpiry": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"price": "Double",
		"status": "Enum",
		"status_idx": "Integer",
		"subcategoryId": "ID",
		"title": "String",
		"userId": "ID",
		"viewsCount": "Integer",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Upgrade Listingpremium API

Upgrades a listing to premium status after successful payment. Sets isPremium=true, premiumType, premiumExpiry based on duration, and records payment confirmation. Called internally by payment service via interservice call.

API Frontend Description By The Backend Architect

Rest Route

The upgradeListingPremium API REST controller can be triggered via the following route:

/v1/listings/upgrade-premium

Rest Request Parameters

The upgradeListingPremium api has got 4 regular request parameters

Parameter Type Required Population
listingId ID true request.body?.[“listingId”]
premiumType Enum true request.body?.[“premiumType”]
premiumDuration Integer true request.body?.[“premiumDuration”]
paymentTransactionId ID true request.body?.[“paymentTransactionId”]
listingId : ID of the listing to upgrade
premiumType : Premium package type (bronze, silver, gold)
premiumDuration : Duration of premium in days
paymentTransactionId : Payment transaction ID for confirmation record

REST Request To access the api you can use the REST controller with the path POST /v1/listings/upgrade-premium

  axios({
    method: 'POST',
    url: '/v1/listings/upgrade-premium',
    data: {
            listingId:"ID",  
            premiumType:"Enum",  
            premiumDuration:"Integer",  
            paymentTransactionId:"ID",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listing",
	"method": "POST",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"listing": {
		"id": "ID",
		"attributes": "Object",
		"categoryId": "ID",
		"condition": "Enum",
		"condition_idx": "Integer",
		"contactEmail": "String",
		"contactPhone": "String",
		"currency": "String",
		"description": "Text",
		"expiresAt": "Date",
		"favoriteCount": "Integer",
		"isPremium": "Boolean",
		"listingType": "Enum",
		"listingType_idx": "Integer",
		"locationId": "ID",
		"_paymentConfirmation": "String",
		"premiumExpiry": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"price": "Double",
		"status": "Enum",
		"status_idx": "Integer",
		"subcategoryId": "ID",
		"title": "String",
		"userId": "ID",
		"viewsCount": "Integer",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Listingpayment API

This route is used to get the payment information by ID.

Rest Route

The getListingPayment API REST controller can be triggered via the following route:

/v1/listingpayment/:sys_listingPaymentId

Rest Request Parameters

The getListingPayment api has got 1 regular request parameter

Parameter Type Required Population
sys_listingPaymentId ID true request.params?.[“sys_listingPaymentId”]
sys_listingPaymentId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/listingpayment/:sys_listingPaymentId

  axios({
    method: 'GET',
    url: `/v1/listingpayment/${sys_listingPaymentId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_listingPayment",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_listingPayment": {
		"id": "ID",
		"ownerId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "String",
		"statusLiteral": "String",
		"redirectUrl": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

List Listingpayments API

This route is used to list all payments.

Rest Route

The listListingPayments API REST controller can be triggered via the following route:

/v1/listingpayments

Rest Request Parameters

Filter Parameters

The listListingPayments api supports 6 optional filter parameters for filtering list results:

ownerId (ID): An ID value to represent owner user who created the order

orderId (ID): an ID value to represent the orderId which is the ID parameter of the source listing object

paymentId (String): A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type

paymentStatus (String): A string value to represent the payment status which belongs to the lifecyle of a Stripe payment.

statusLiteral (String): A string value to represent the logical payment status which belongs to the application lifecycle itself.

redirectUrl (String): A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client.

REST Request To access the api you can use the REST controller with the path GET /v1/listingpayments

  axios({
    method: 'GET',
    url: '/v1/listingpayments',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // ownerId: '<value>' // Filter by ownerId
        // orderId: '<value>' // Filter by orderId
        // paymentId: '<value>' // Filter by paymentId
        // paymentStatus: '<value>' // Filter by paymentStatus
        // statusLiteral: '<value>' // Filter by statusLiteral
        // redirectUrl: '<value>' // Filter by redirectUrl
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_listingPayments",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_listingPayments": [
		{
			"id": "ID",
			"ownerId": "ID",
			"orderId": "ID",
			"paymentId": "String",
			"paymentStatus": "String",
			"statusLiteral": "String",
			"redirectUrl": "String",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Create Listingpayment API

This route is used to create a new payment.

Rest Route

The createListingPayment API REST controller can be triggered via the following route:

/v1/listingpayment

Rest Request Parameters

The createListingPayment api has got 5 regular request parameters

Parameter Type Required Population
orderId ID true request.body?.[“orderId”]
paymentId String true request.body?.[“paymentId”]
paymentStatus String true request.body?.[“paymentStatus”]
statusLiteral String true request.body?.[“statusLiteral”]
redirectUrl String false request.body?.[“redirectUrl”]
orderId : an ID value to represent the orderId which is the ID parameter of the source listing object
paymentId : A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type
paymentStatus : A string value to represent the payment status which belongs to the lifecyle of a Stripe payment.
statusLiteral : A string value to represent the logical payment status which belongs to the application lifecycle itself.
redirectUrl : A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client.

REST Request To access the api you can use the REST controller with the path POST /v1/listingpayment

  axios({
    method: 'POST',
    url: '/v1/listingpayment',
    data: {
            orderId:"ID",  
            paymentId:"String",  
            paymentStatus:"String",  
            statusLiteral:"String",  
            redirectUrl:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_listingPayment",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_listingPayment": {
		"id": "ID",
		"ownerId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "String",
		"statusLiteral": "String",
		"redirectUrl": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Listingpayment API

This route is used to update an existing payment.

Rest Route

The updateListingPayment API REST controller can be triggered via the following route:

/v1/listingpayment/:sys_listingPaymentId

Rest Request Parameters

The updateListingPayment api has got 5 regular request parameters

Parameter Type Required Population
sys_listingPaymentId ID true request.params?.[“sys_listingPaymentId”]
paymentId String false request.body?.[“paymentId”]
paymentStatus String false request.body?.[“paymentStatus”]
statusLiteral String false request.body?.[“statusLiteral”]
redirectUrl String false request.body?.[“redirectUrl”]
sys_listingPaymentId : This id paremeter is used to select the required data object that will be updated
paymentId : A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type
paymentStatus : A string value to represent the payment status which belongs to the lifecyle of a Stripe payment.
statusLiteral : A string value to represent the logical payment status which belongs to the application lifecycle itself.
redirectUrl : A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client.

REST Request To access the api you can use the REST controller with the path PATCH /v1/listingpayment/:sys_listingPaymentId

  axios({
    method: 'PATCH',
    url: `/v1/listingpayment/${sys_listingPaymentId}`,
    data: {
            paymentId:"String",  
            paymentStatus:"String",  
            statusLiteral:"String",  
            redirectUrl:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_listingPayment",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_listingPayment": {
		"id": "ID",
		"ownerId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "String",
		"statusLiteral": "String",
		"redirectUrl": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Delete Listingpayment API

This route is used to delete a payment.

Rest Route

The deleteListingPayment API REST controller can be triggered via the following route:

/v1/listingpayment/:sys_listingPaymentId

Rest Request Parameters

The deleteListingPayment api has got 1 regular request parameter

Parameter Type Required Population
sys_listingPaymentId ID true request.params?.[“sys_listingPaymentId”]
sys_listingPaymentId : This id paremeter is used to select the required data object that will be deleted

REST Request To access the api you can use the REST controller with the path DELETE /v1/listingpayment/:sys_listingPaymentId

  axios({
    method: 'DELETE',
    url: `/v1/listingpayment/${sys_listingPaymentId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_listingPayment",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_listingPayment": {
		"id": "ID",
		"ownerId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "String",
		"statusLiteral": "String",
		"redirectUrl": "String",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Listingpaymentbyorderid API

This route is used to get the payment information by order id.

Rest Route

The getListingPaymentByOrderId API REST controller can be triggered via the following route:

/v1/listingpaymentbyorderid/:orderId

Rest Request Parameters

The getListingPaymentByOrderId api has got 2 regular request parameters

Parameter Type Required Population
sys_listingPaymentId ID true request.params?.[“sys_listingPaymentId”]
orderId ID true request.params?.[“orderId”]
sys_listingPaymentId : This id paremeter is used to query the required data object.
orderId : an ID value to represent the orderId which is the ID parameter of the source listing object. The parameter is used to query data.

REST Request To access the api you can use the REST controller with the path GET /v1/listingpaymentbyorderid/:orderId

  axios({
    method: 'GET',
    url: `/v1/listingpaymentbyorderid/${orderId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_listingPayment",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_listingPayment": {
		"id": "ID",
		"ownerId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "String",
		"statusLiteral": "String",
		"redirectUrl": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Listingpaymentbypaymentid API

This route is used to get the payment information by payment id.

Rest Route

The getListingPaymentByPaymentId API REST controller can be triggered via the following route:

/v1/listingpaymentbypaymentid/:paymentId

Rest Request Parameters

The getListingPaymentByPaymentId api has got 2 regular request parameters

Parameter Type Required Population
sys_listingPaymentId ID true request.params?.[“sys_listingPaymentId”]
paymentId String true request.params?.[“paymentId”]
sys_listingPaymentId : This id paremeter is used to query the required data object.
paymentId : A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type. The parameter is used to query data.

REST Request To access the api you can use the REST controller with the path GET /v1/listingpaymentbypaymentid/:paymentId

  axios({
    method: 'GET',
    url: `/v1/listingpaymentbypaymentid/${paymentId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_listingPayment",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_listingPayment": {
		"id": "ID",
		"ownerId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "String",
		"statusLiteral": "String",
		"redirectUrl": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Start Listingpayment API

Start payment for listing

Rest Route

The startListingPayment API REST controller can be triggered via the following route:

/v1/startlistingpayment/:listingId

Rest Request Parameters

The startListingPayment api has got 2 regular request parameters

Parameter Type Required Population
listingId ID true request.params?.[“listingId”]
paymentUserParams Object false request.body?.[“paymentUserParams”]
listingId : This id paremeter is used to select the required data object that will be updated
paymentUserParams : The user parameters that should be defined to start a stripe payment process

REST Request To access the api you can use the REST controller with the path PATCH /v1/startlistingpayment/:listingId

  axios({
    method: 'PATCH',
    url: `/v1/startlistingpayment/${listingId}`,
    data: {
            paymentUserParams:"Object",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listing",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"listing": {
		"id": "ID",
		"attributes": "Object",
		"categoryId": "ID",
		"condition": "Enum",
		"condition_idx": "Integer",
		"contactEmail": "String",
		"contactPhone": "String",
		"currency": "String",
		"description": "Text",
		"expiresAt": "Date",
		"favoriteCount": "Integer",
		"isPremium": "Boolean",
		"listingType": "Enum",
		"listingType_idx": "Integer",
		"locationId": "ID",
		"_paymentConfirmation": "String",
		"premiumExpiry": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"price": "Double",
		"status": "Enum",
		"status_idx": "Integer",
		"subcategoryId": "ID",
		"title": "String",
		"userId": "ID",
		"viewsCount": "Integer",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	},
	"paymentResult": {
		"paymentTicketId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "Enum",
		"paymentIntentInfo": "Object",
		"statusLiteral": "String",
		"amount": "Double",
		"currency": "String",
		"success": true,
		"description": "String",
		"metadata": "Object",
		"paymentUserParams": "Object"
	}
}

Refresh Listingpayment API

Refresh payment info for listing from Stripe

Rest Route

The refreshListingPayment API REST controller can be triggered via the following route:

/v1/refreshlistingpayment/:listingId

Rest Request Parameters

The refreshListingPayment api has got 2 regular request parameters

Parameter Type Required Population
listingId ID true request.params?.[“listingId”]
paymentUserParams Object false request.body?.[“paymentUserParams”]
listingId : This id paremeter is used to select the required data object that will be updated
paymentUserParams : The user parameters that should be defined to refresh a stripe payment process

REST Request To access the api you can use the REST controller with the path PATCH /v1/refreshlistingpayment/:listingId

  axios({
    method: 'PATCH',
    url: `/v1/refreshlistingpayment/${listingId}`,
    data: {
            paymentUserParams:"Object",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listing",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"listing": {
		"id": "ID",
		"attributes": "Object",
		"categoryId": "ID",
		"condition": "Enum",
		"condition_idx": "Integer",
		"contactEmail": "String",
		"contactPhone": "String",
		"currency": "String",
		"description": "Text",
		"expiresAt": "Date",
		"favoriteCount": "Integer",
		"isPremium": "Boolean",
		"listingType": "Enum",
		"listingType_idx": "Integer",
		"locationId": "ID",
		"_paymentConfirmation": "String",
		"premiumExpiry": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"price": "Double",
		"status": "Enum",
		"status_idx": "Integer",
		"subcategoryId": "ID",
		"title": "String",
		"userId": "ID",
		"viewsCount": "Integer",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	},
	"paymentResult": {
		"paymentTicketId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "Enum",
		"paymentIntentInfo": "Object",
		"statusLiteral": "String",
		"amount": "Double",
		"currency": "String",
		"success": true,
		"description": "String",
		"metadata": "Object",
		"paymentUserParams": "Object"
	}
}

Callback Listingpayment API

Refresh payment values by gateway webhook call for listing

Rest Route

The callbackListingPayment API REST controller can be triggered via the following route:

/v1/callbacklistingpayment

Rest Request Parameters

The callbackListingPayment api has got 1 regular request parameter

Parameter Type Required Population
listingId ID true request.body?.[“listingId”]
listingId : The order id parameter that will be read from webhook callback params

REST Request To access the api you can use the REST controller with the path POST /v1/callbacklistingpayment

  axios({
    method: 'POST',
    url: '/v1/callbacklistingpayment',
    data: {
            listingId:"ID",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listing",
	"method": "POST",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"listing": {
		"id": "ID",
		"attributes": "Object",
		"categoryId": "ID",
		"condition": "Enum",
		"condition_idx": "Integer",
		"contactEmail": "String",
		"contactPhone": "String",
		"currency": "String",
		"description": "Text",
		"expiresAt": "Date",
		"favoriteCount": "Integer",
		"isPremium": "Boolean",
		"listingType": "Enum",
		"listingType_idx": "Integer",
		"locationId": "ID",
		"_paymentConfirmation": "String",
		"premiumExpiry": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"price": "Double",
		"status": "Enum",
		"status_idx": "Integer",
		"subcategoryId": "ID",
		"title": "String",
		"userId": "ID",
		"viewsCount": "Integer",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	},
	"paymentResult": {
		"paymentTicketId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "Enum",
		"paymentIntentInfo": "Object",
		"statusLiteral": "String",
		"amount": "Double",
		"currency": "String",
		"success": true,
		"description": "String",
		"metadata": "Object",
		"paymentUserParams": "Object"
	}
}

Get Paymentcustomerbyuserid API

This route is used to get the payment customer information by user id.

Rest Route

The getPaymentCustomerByUserId API REST controller can be triggered via the following route:

/v1/paymentcustomers/:userId

Rest Request Parameters

The getPaymentCustomerByUserId api has got 2 regular request parameters

Parameter Type Required Population
sys_paymentCustomerId ID true request.params?.[“sys_paymentCustomerId”]
userId ID true request.params?.[“userId”]
sys_paymentCustomerId : This id paremeter is used to query the required data object.
userId : An ID value to represent the user who is created as a stripe customer. The parameter is used to query data.

REST Request To access the api you can use the REST controller with the path GET /v1/paymentcustomers/:userId

  axios({
    method: 'GET',
    url: `/v1/paymentcustomers/${userId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_paymentCustomer",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_paymentCustomer": {
		"id": "ID",
		"userId": "ID",
		"customerId": "String",
		"platform": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

List Paymentcustomers API

This route is used to list all payment customers.

Rest Route

The listPaymentCustomers API REST controller can be triggered via the following route:

/v1/paymentcustomers

Rest Request Parameters

Filter Parameters

The listPaymentCustomers api supports 3 optional filter parameters for filtering list results:

userId (ID): An ID value to represent the user who is created as a stripe customer

customerId (String): A string value to represent the customer id which is generated on the Stripe gateway. This id is used to represent the customer in the Stripe gateway

platform (String): A String value to represent payment platform which is used to make the payment. It is stripe as default. It will be used to distinguesh the payment gateways in the future.

REST Request To access the api you can use the REST controller with the path GET /v1/paymentcustomers

  axios({
    method: 'GET',
    url: '/v1/paymentcustomers',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // userId: '<value>' // Filter by userId
        // customerId: '<value>' // Filter by customerId
        // platform: '<value>' // Filter by platform
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_paymentCustomers",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_paymentCustomers": [
		{
			"id": "ID",
			"userId": "ID",
			"customerId": "String",
			"platform": "String",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

List Paymentcustomermethods API

This route is used to list all payment customer methods.

Rest Route

The listPaymentCustomerMethods API REST controller can be triggered via the following route:

/v1/paymentcustomermethods/:userId

Rest Request Parameters

Filter Parameters

The listPaymentCustomerMethods api supports 6 optional filter parameters for filtering list results:

paymentMethodId (String): A string value to represent the id of the payment method on the payment platform.

customerId (String): A string value to represent the customer id which is generated on the payment gateway.

cardHolderName (String): A string value to represent the name of the card holder. It can be different than the registered customer.

cardHolderZip (String): A string value to represent the zip code of the card holder. It is used for address verification in specific countries.

platform (String): A String value to represent payment platform which teh paymentMethod belongs. It is stripe as default. It will be used to distinguesh the payment gateways in the future.

cardInfo (Object): A Json value to store the card details of the payment method.

REST Request To access the api you can use the REST controller with the path GET /v1/paymentcustomermethods/:userId

  axios({
    method: 'GET',
    url: `/v1/paymentcustomermethods/${userId}`,
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // paymentMethodId: '<value>' // Filter by paymentMethodId
        // customerId: '<value>' // Filter by customerId
        // cardHolderName: '<value>' // Filter by cardHolderName
        // cardHolderZip: '<value>' // Filter by cardHolderZip
        // platform: '<value>' // Filter by platform
        // cardInfo: '<value>' // Filter by cardInfo
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_paymentMethods",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_paymentMethods": [
		{
			"id": "ID",
			"paymentMethodId": "String",
			"userId": "ID",
			"customerId": "String",
			"cardHolderName": "String",
			"cardHolderZip": "String",
			"platform": "String",
			"cardInfo": "Object",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

_fetch Listlisting API

System API to fetch list of listing records for frontend application. Auto-generated, not visible in design.

Rest Route

The _fetchListListing API REST controller can be triggered via the following route:

/v1/_fetchlistlisting

Rest Request Parameters

Filter Parameters

The _fetchListListing api supports 14 optional filter parameters for filtering list results:

categoryId (ID): Main category for the listing (categoryLocation:category).

condition (Enum): Item condition: new, used, other.

expiresAt (Date): UTC expiry for listing; after this, listing is automatically expired.

isPremium (Boolean): If true, the listing is premium (highlighted/pinned, eligible for special placement).

listingType (Enum): Type of listing (sale, rent, service, etc.).

locationId (ID): Location (categoryLocation:location).

premiumExpiry (Date): UTC date when premium status expires. Null if not premium or not applicable.

premiumType (Enum): Which premium package (gold, silver, none, etc.).

price (Double): Listing price.

status (Enum): Lifecycle status: pending_review, active, denied, sold, expired, deleted.

subcategoryId (ID): Subcategory for the listing, can be null for top-level (categoryLocation:category).

title (String): Listing title, short and clear.

userId (ID): Owner (poster) of the listing (auth:user).

paymentConfirmation (Enum): An automatic property that is used to check the confirmed status of the payment set by webhooks.

REST Request To access the api you can use the REST controller with the path GET /v1/_fetchlistlisting

  axios({
    method: 'GET',
    url: '/v1/_fetchlistlisting',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // categoryId: '<value>' // Filter by categoryId
        // condition: '<value>' // Filter by condition
        // expiresAt: '<value>' // Filter by expiresAt
        // isPremium: '<value>' // Filter by isPremium
        // listingType: '<value>' // Filter by listingType
        // locationId: '<value>' // Filter by locationId
        // premiumExpiry: '<value>' // Filter by premiumExpiry
        // premiumType: '<value>' // Filter by premiumType
        // price: '<value>' // Filter by price
        // status: '<value>' // Filter by status
        // subcategoryId: '<value>' // Filter by subcategoryId
        // title: '<value>' // Filter by title
        // userId: '<value>' // Filter by userId
        // paymentConfirmation: '<value>' // Filter by paymentConfirmation
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listings",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"listings": [
		{
			"id": "ID",
			"attributes": "Object",
			"categoryId": "ID",
			"condition": "Enum",
			"condition_idx": "Integer",
			"contactEmail": "String",
			"contactPhone": "String",
			"currency": "String",
			"description": "Text",
			"expiresAt": "Date",
			"favoriteCount": "Integer",
			"isPremium": "Boolean",
			"listingType": "Enum",
			"listingType_idx": "Integer",
			"locationId": "ID",
			"_paymentConfirmation": "String",
			"premiumExpiry": "Date",
			"premiumType": "Enum",
			"premiumType_idx": "Integer",
			"price": "Double",
			"status": "Enum",
			"status_idx": "Integer",
			"subcategoryId": "ID",
			"title": "String",
			"userId": "ID",
			"viewsCount": "Integer",
			"paymentConfirmation": "Enum",
			"paymentConfirmation_idx": "Integer",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"mainCategory": [
				{
					"description": "Text",
					"icon": "String",
					"name": "String",
					"parentCategoryId": "ID",
					"slug": "String",
					"sortOrder": "Integer"
				},
				{},
				{}
			],
			"location": [
				{
					"city": "String",
					"country": "String",
					"district": "String",
					"latitude": "Double",
					"longitude": "Double",
					"postalCode": "String"
				},
				{},
				{}
			],
			"subCategory": [
				{
					"description": "Text",
					"icon": "String",
					"name": "String",
					"parentCategoryId": "ID",
					"slug": "String",
					"sortOrder": "Integer"
				},
				{},
				{}
			],
			"user": [
				{
					"fullname": "String"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

_fetch Listsys_listingpayment API

System API to fetch list of sys_listingPayment records for frontend application. Auto-generated, not visible in design.

Rest Route

The _fetchListSys_listingPayment API REST controller can be triggered via the following route:

/v1/_fetchlistsys_listingpayment

Rest Request Parameters

Filter Parameters

The _fetchListSys_listingPayment api supports 6 optional filter parameters for filtering list results:

ownerId (ID): An ID value to represent owner user who created the order

orderId (ID): an ID value to represent the orderId which is the ID parameter of the source listing object

paymentId (String): A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type

paymentStatus (String): A string value to represent the payment status which belongs to the lifecyle of a Stripe payment.

statusLiteral (String): A string value to represent the logical payment status which belongs to the application lifecycle itself.

redirectUrl (String): A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client.

REST Request To access the api you can use the REST controller with the path GET /v1/_fetchlistsys_listingpayment

  axios({
    method: 'GET',
    url: '/v1/_fetchlistsys_listingpayment',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // ownerId: '<value>' // Filter by ownerId
        // orderId: '<value>' // Filter by orderId
        // paymentId: '<value>' // Filter by paymentId
        // paymentStatus: '<value>' // Filter by paymentStatus
        // statusLiteral: '<value>' // Filter by statusLiteral
        // redirectUrl: '<value>' // Filter by redirectUrl
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_listingPayments",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_listingPayments": [
		{
			"id": "ID",
			"ownerId": "ID",
			"orderId": "ID",
			"paymentId": "String",
			"paymentStatus": "String",
			"statusLiteral": "String",
			"redirectUrl": "String",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

_fetch Listsys_paymentcustomer API

System API to fetch list of sys_paymentCustomer records for frontend application. Auto-generated, not visible in design.

Rest Route

The _fetchListSys_paymentCustomer API REST controller can be triggered via the following route:

/v1/_fetchlistsys_paymentcustomer

Rest Request Parameters

Filter Parameters

The _fetchListSys_paymentCustomer api supports 3 optional filter parameters for filtering list results:

userId (ID): An ID value to represent the user who is created as a stripe customer

customerId (String): A string value to represent the customer id which is generated on the Stripe gateway. This id is used to represent the customer in the Stripe gateway

platform (String): A String value to represent payment platform which is used to make the payment. It is stripe as default. It will be used to distinguesh the payment gateways in the future.

REST Request To access the api you can use the REST controller with the path GET /v1/_fetchlistsys_paymentcustomer

  axios({
    method: 'GET',
    url: '/v1/_fetchlistsys_paymentcustomer',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // userId: '<value>' // Filter by userId
        // customerId: '<value>' // Filter by customerId
        // platform: '<value>' // Filter by platform
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_paymentCustomers",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_paymentCustomers": [
		{
			"id": "ID",
			"userId": "ID",
			"customerId": "String",
			"platform": "String",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

_fetch Listsys_paymentmethod API

System API to fetch list of sys_paymentMethod records for frontend application. Auto-generated, not visible in design.

Rest Route

The _fetchListSys_paymentMethod API REST controller can be triggered via the following route:

/v1/_fetchlistsys_paymentmethod

Rest Request Parameters

Filter Parameters

The _fetchListSys_paymentMethod api supports 7 optional filter parameters for filtering list results:

paymentMethodId (String): A string value to represent the id of the payment method on the payment platform.

userId (ID): An ID value to represent the user who owns the payment method

customerId (String): A string value to represent the customer id which is generated on the payment gateway.

cardHolderName (String): A string value to represent the name of the card holder. It can be different than the registered customer.

cardHolderZip (String): A string value to represent the zip code of the card holder. It is used for address verification in specific countries.

platform (String): A String value to represent payment platform which teh paymentMethod belongs. It is stripe as default. It will be used to distinguesh the payment gateways in the future.

cardInfo (Object): A Json value to store the card details of the payment method.

REST Request To access the api you can use the REST controller with the path GET /v1/_fetchlistsys_paymentmethod

  axios({
    method: 'GET',
    url: '/v1/_fetchlistsys_paymentmethod',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // paymentMethodId: '<value>' // Filter by paymentMethodId
        // userId: '<value>' // Filter by userId
        // customerId: '<value>' // Filter by customerId
        // cardHolderName: '<value>' // Filter by cardHolderName
        // cardHolderZip: '<value>' // Filter by cardHolderZip
        // platform: '<value>' // Filter by platform
        // cardInfo: '<value>' // Filter by cardInfo
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_paymentMethods",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_paymentMethods": [
		{
			"id": "ID",
			"paymentMethodId": "String",
			"userId": "ID",
			"customerId": "String",
			"cardHolderName": "String",
			"cardHolderZip": "String",
			"platform": "String",
			"cardInfo": "Object",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

After this prompt, the user may give you new instructions to update the output of this prompt or provide subsequent prompts about the project.


CLONESAHIBINDEN

FRONTEND GUIDE FOR AI CODING AGENTS - PART 11 - Listing Service Listing Payment Flow

This document is a part of a REST API guide for the clonesahibinden project. It is designed for AI agents that will generate frontend code to consume the project’s backend.

Stripe Payment Flow For Listing

Listing is a data object that stores order information used for Stripe payments. The payment flow can only start after an instance of this data object is created in the database.

The ID of this data object—referenced as listingId in the general business logic—will be used as the orderId in the payment flow.

Accessing the service API for the payment flow API

The Clonesahibinden application doesn’t have a separate payment service; the payment flow is handled within the same service that manages orders. To access the related APIs, use the base URL of the listing service. Note that the application may be deployed to Preview, Staging, or Production. As with all API access, you should call the API using the base URL for the selected deployment.

For the listing service, the base URLs are:

Creating the Listing

While creating the listing instance is part of the business logic and can be implemented according to your architecture, this instance acts as the central hub for the payment flow and its related data objects. The order object is typically created via its own API (see the Business API for the create route of listing). The payment flow begins after the object is created.

Because of the data object’s Stripe order settings, the payment flow is aware of the following fields, references, and their purposes:

Before Payment Flow Starts

It is assumed that the frontend provides a “Pay” or “Checkout” button that initiates the payment flow. The following steps occur after the user clicks this button.
Note that an listing instance must already exist to represent the order being paid, with its initial status set.

A Stripe payment flow can be implemented in several ways, but the best practice is to use a PaymentIntent and manage it jointly from the backend and frontend.
A PaymentIntent represents the intent to collect payment for a given order (or any payable entity).
In the Clonesahibinden application, the PaymentIntent is created in the backend, while the PaymentMethod (the user’s stored card information) is created in the frontend.
Only the PaymentMethod ID and minimal metadata are stored in the backend for later reference.

The frontend first requests the current user’s saved payment methods from the backend, displays them in a list, and provides UI options to add or remove payment methods.
The user must select a Payment Method before starting the payment flow.

Listing the Payment Methods for the User

To list the payment methods of the currently logged-in user, call the following system API (unversioned):

GET /payment-methods/list

This endpoint requires no parameters and returns an array of payment methods belonging to the user — without any envelope.

const response = await fetch("$serviceUrl/payment-methods/list", {
  method: "GET",
  headers: { "Content-Type": "application/json" },
});

Example response:

[
  {
    "id": "19a5fbfd-3c25-405b-a7f7-06f023f2ca01",
    "paymentMethodId": "pm_1SQv9CP5uUv56Cse5BQ3nGW8",
    "userId": "f7103b85-fcda-4dec-92c6-c336f71fd3a2",
    "customerId": "cus_TNgWUw5QkmUPLa",
    "cardHolderName": "John Doe",
    "cardHolderZip": "34662",
    "platform": "stripe",
    "cardInfo": {
      "brand": "visa",
      "last4": "4242",
      "checks": {
        "cvc_check": "pass",
        "address_postal_code_check": "pass"
      },
      "funding": "credit",
      "exp_month": 11,
      "exp_year": 2033
    },
    "isActive": true,
    "createdAt": "2025-11-07T19:16:38.469Z",
    "updatedAt": "2025-11-07T19:16:38.469Z",
    "_owner": "f7103b85-fcda-4dec-92c6-c336f71fd3a2"
  }
]

In each payment method object, the following fields are useful for displaying to the user:

for (const method of paymentMethods) {
  const brand = method.cardInfo.brand; // use brand for displaying VISA/MASTERCARD icons
  const paymentMethodId = method.paymentMethodId; // send this when initiating the payment flow
  const cardHolderName = method.cardHolderName; // show in list
  const number = `**** **** **** ${method.cardInfo.last4}`; // masked card number
  const expDate = `${method.cardInfo.exp_month}/${method.cardInfo.exp_year}`; // expiry date
  const id = method.id; // internal DB record ID, used for deletion
  const customerId = method.customerId; // Stripe customer reference
}

If the list is empty, prompt the user to add a new payment method.

Creating a Payment Method

The payment page (or user profile page) should allow users to add a new payment method (credit card). Creating a Payment Method is a secure operation handled entirely through Stripe.js on the frontend — the backend never handles sensitive card data. After a card is successfully created, the backend only stores its reference (PaymentMethod ID) for reuse.

Stripe provides multiple ways to collect card information, all through secure UI elements. Below is an example setup — refer to the latest Stripe documentation for alternative patterns.

To initialize Stripe on the frontend, include your public key:

<script src="https://js.stripe.com/v3/?advancedFraudSignals=false"></script>
const stripe = Stripe("pk_test_51POkqt4..................");
const elements = stripe.elements();

const cardNumberElement = elements.create("cardNumber", {
  style: { base: { color: "#545454", fontSize: "16px" } },
});
cardNumberElement.mount("#card-number-element");

const cardExpiryElement = elements.create("cardExpiry", {
  style: { base: { color: "#545454", fontSize: "16px" } },
});
cardExpiryElement.mount("#card-expiry-element");

const cardCvcElement = elements.create("cardCvc", {
  style: { base: { color: "#545454", fontSize: "16px" } },
});
cardCvcElement.mount("#card-cvc-element");

// Note: cardholder name and ZIP code are collected via non-Stripe inputs (not secure).

You can dynamically show the card brand while typing:

cardNumberElement.on("change", (event) => {
  const cardBrand = event.brand;
  const cardNumberDiv = document.getElementById("card-number-element");
  cardNumberDiv.style.backgroundImage = getBrandImageUrl(cardBrand);
});

Once the user completes the card form, create the Payment Method on Stripe. Note that the expiry and CVC fields are securely handled by Stripe.js and are never readable from your code.

const { paymentMethod, error } = await stripe.createPaymentMethod({
  type: "card",
  card: cardNumberElement,
  billing_details: {
    name: cardholderName.value,
    address: { postal_code: cardholderZip.value },
  },
});

When a paymentMethod is successfully created, send its ID to your backend to attach it to the logged-in user’s account.

Use the system API (unversioned):

POST /payment-methods/add

Example:

const response = await fetch("$serviceUrl/payment-methods/add", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ paymentMethodId: paymentMethod.id }),
});

When addPaymentMethod is called, the backend retrieves or creates the user’s Stripe Customer ID, attaches the Payment Method to that customer, and stores the reference in the local database for future use.

Example response:

{
  "isActive": true,
  "cardHolderName": "John Doe",
  "userId": "f7103b85-fcda-4dec-92c6-c336f71fd3a2",
  "customerId": "cus_TNgWUw5QkmUPLa",
  "paymentMethodId": "pm_1SQw5aP5uUv56CseDGzT1dzP",
  "platform": "stripe",
  "cardHolderZip": "34662",
  "cardInfo": {
    "brand": "visa",
    "last4": "4242",
    "funding": "credit",
    "exp_month": 11,
    "exp_year": 2033
  },
  "id": "19a5ff70-4986-4760-8fc4-6b591bd6bbbf",
  "createdAt": "2025-11-07T20:16:55.451Z",
  "updatedAt": "2025-11-07T20:16:55.451Z"
}

You can append this new entry directly to the UI list or refresh the list using the listPaymentMethods API.

Deleting a Payment Method

To remove a saved payment method from the current user’s account, call the system API (unversioned):

DELETE /payment-methods/delete/:paymentMethodId

Example:

await fetch(
  `$serviceUrl/payment-methods/delete/${paymentMethodId}`,
  {
    method: "DELETE",
    headers: { "Content-Type": "application/json" },
  }
);

Starting the Payment Flow in Backend — Creation and Confirmation of the PaymentIntent Object

The payment flow is initiated in the backend through the startListingPayment API.
This API must be called with one of the user’s existing payment methods. Therefore, ensure that the frontend forces the user to select a payment method before initiating the payment.

The startListingPayment API is a versioned Business Logic API and follows the same structure as other business APIs.

In the Clonesahibinden application, the payment flow starts by creating a Stripe PaymentIntent and confirming it in a single step within the backend.
In a typical (“happy”) path, when the startListingPayment API is called, the response will include a successful or failed PaymentIntent result inside the paymentResult object, along with the listing object.

However, in certain edge cases—such as when 3D Secure (3DS) or other bank-level authentication is required—the confirmation step cannot complete immediately.
In such cases, control should return to a frontend page to allow the user to finish the process.
To enable this, a return_url must be provided during the PaymentIntent creation step.

Although technically optional, it is strongly recommended to include a return_url.
This ensures that the frontend payment result page can display both successful and failed payments and complete flows that require user interaction.
The return_url must be a frontend URL.

The paymentUserParams parameter of the startListingPayment API contains the data necessary to create the Stripe PaymentIntent.

Call the API as follows:

const response = await fetch(
  `$serviceUrl/v1/startlistingpayment/${orderId}`,
  {
    method: "PATCH",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      paymentUserParams: {
        paymentMethodId,
        return_url: `${yourFrontendReturnUrl}`,
      },
    }),
  }
);

The API response will contain a paymentResult object. If an error occurs, it will begin with { "result": "ERR" }. Otherwise, it will include the PaymentIntent information:

{
  "paymentResult": {
    "success": true,
    "paymentTicketId": "19a60f8f-eeff-43a2-9954-58b18839e1da",
    "orderId": "19a60f84-56ee-40c4-b9c1-392f83877838",
    "paymentId": "pi_3SR0UHP5uUv56Cse1kwQWCK8",
    "paymentStatus": "succeeded",
    "paymentIntentInfo": {
      "paymentIntentId": "pi_3SR0UHP5uUv56Cse1kwQWCK8",
      "clientSecret": "pi_3SR0UHP5uUv56Cse1kwQWCK8_secret_PTc3DriD0YU5Th4isBepvDWdg",
      "publicKey": "pk_test_51POkqWP5uU",
      "status": "succeeded"
    },
    "statusLiteral": "success",
    "amount": 10,
    "currency": "USD",
    "description": "Your credit card is charged for babilOrder for 10",
    "metadata": {
      "order": "Purchase-Purchase-order",
      "orderId": "19a60f84-56ee-40c4-b9c1-392f83877838",
      "checkoutName": "babilOrder"
    },
    "paymentUserParams": {
      "paymentMethodId": "pm_1SQw5aP5uUv56CseDGzT1dzP",
      "return_url": "${yourFrontendReturnUrl}"
    }
  }
}

Start Listingpayment API

Start payment for listing

Rest Route

The startListingPayment API REST controller can be triggered via the following route:

/v1/startlistingpayment/:listingId

Rest Request Parameters

The startListingPayment api has got 2 regular request parameters

Parameter Type Required Population
listingId ID true request.params?.[“listingId”]
paymentUserParams Object false request.body?.[“paymentUserParams”]
listingId : This id paremeter is used to select the required data object that will be updated
paymentUserParams : The user parameters that should be defined to start a stripe payment process

REST Request To access the api you can use the REST controller with the path PATCH /v1/startlistingpayment/:listingId

  axios({
    method: 'PATCH',
    url: `/v1/startlistingpayment/${listingId}`,
    data: {
            paymentUserParams:"Object",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listing",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"listing": {
		"id": "ID",
		"attributes": "Object",
		"categoryId": "ID",
		"condition": "Enum",
		"condition_idx": "Integer",
		"contactEmail": "String",
		"contactPhone": "String",
		"currency": "String",
		"description": "Text",
		"expiresAt": "Date",
		"favoriteCount": "Integer",
		"isPremium": "Boolean",
		"listingType": "Enum",
		"listingType_idx": "Integer",
		"locationId": "ID",
		"_paymentConfirmation": "String",
		"premiumExpiry": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"price": "Double",
		"status": "Enum",
		"status_idx": "Integer",
		"subcategoryId": "ID",
		"title": "String",
		"userId": "ID",
		"viewsCount": "Integer",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	},
	"paymentResult": {
		"paymentTicketId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "Enum",
		"paymentIntentInfo": "Object",
		"statusLiteral": "String",
		"amount": "Double",
		"currency": "String",
		"success": true,
		"description": "String",
		"metadata": "Object",
		"paymentUserParams": "Object"
	}
}

Analyzing the API Response

After calling the startListingPayment API, the most common expected outcome is a confirmed and completed payment. However, several alternate cases should be handled on the frontend.

System Error Case

The API may return a classic service-level error (unrelated to payment). Check the HTTP status code of the response. It should be 200 or 201. Any 400, 401, 403, or 404 indicates a system error.

{
  "result": "ERR",
  "status": 404,
  "message": "Record not found",
  "date": "2025-11-08T00:57:54.820Z"
}

Handle system errors on the payment page (show a retry option). Do not navigate to the result page.

Payment Error Case

The API performs both database operations and the Stripe payment operation. If the payment fails but the service logic succeeds, the API may still return a 200 OK status, with the failure recorded in the paymentResult.

In this case, show an error message and allow the user to retry.

{
  "status": "OK",
  "statusCode": "200",
  "listing": {
    "id": "19a60f8f-eeff-43a2-9954-58b18839e1da",
    "status": "failed"
  },
  "paymentResult": {
    "result": "ERR",
    "status": 500,
    "message": "Stripe error message: Your card number is incorrect.",
    "errCode": "invalid_number",
    "date": "2025-11-08T00:57:54.820Z"
  }
}

Payment errors should be handled on the payment page (retry option). Do not go to the result page.


Happy Case

When both the service and payment result succeed, this is considered the happy path. In this case, use the listing and paymentResult objects in the response to display a success message to the user.

amount and description values are included to help you show payment details on the result page.

{
  "status": "OK",
  "statusCode": "200",
  "order": {
    "id": "19a60f8f-eeff-43a2-9954-58b18839e1da",
    "status": "paid"
  },
  "paymentResult": {
    "success": true,
    "paymentStatus": "succeeded",
    "paymentIntentInfo": {
      "status": "succeeded"
    },
    "amount": 10,
    "currency": "USD",
    "description": "Your credit card is charged for babilOrder for 10"
  }
}

To verify success:

if (paymentResult.paymentIntentInfo.status === "succeeded") {
  // Redirect to result page
}

Note: A successful result does not trigger fulfillment immediately. Fulfillment begins only after the Stripe webhook updates the database. It’s recommended to show a short “success” toast, wait a few milliseconds, and then navigate to the result page.

Handle the happy case in the result page by sending the listingId and the payment intent secret.

const orderId = new URLSearchParams(window.location.search).get("orderId");
const url = new URL(`$yourResultPageUrl`, location.origin);
url.searchParams.set("orderId", orderId);
url.searchParams.set("payment_intent_client_secret", currentPaymentIntent.clientSecret);
setTimeout(() => { window.location.href = url.toString(); }, 600);

Edge Cases

Although startListingPayment is designed to handle both creation and confirmation in one step, Stripe may return an incomplete result if third-party authentication or redirect steps are required.

You must handle these cases in both the payment page and the result page, because some next actions are available immediately, while others occur only after a redirect.

If the paymentIntentInfo.status equals "requires_action", handle it using Stripe.js as shown below:

if (paymentResult.paymentIntentInfo.status === "requires_action") {
  await runNextAction(
    paymentResult.paymentIntentInfo.clientSecret,
    paymentResult.paymentIntentInfo.publicKey
  );
}

Helper function:

async function runNextAction(clientSecret, publicKey) {
  const stripe = Stripe(publicKey);
  const { error } = await stripe.handleNextAction({ clientSecret });
  if (error) {
    console.log("next_action error:", error);
    showToast(error.code + ": " + error.message, "fa-circle-xmark text-red-500");
    throw new Error(error.message);
  }
}

After handling the next action, re-fetch the PaymentIntent from Stripe, evaluate its status, show appropriate feedback, and navigate to the result page.

const { paymentIntent } = await stripe.retrievePaymentIntent(clientSecret);

if (paymentIntent.status === "succeeded") {
  showToast("Payment successful!", "fa-circle-check text-green-500");
} else if (paymentIntent.status === "processing") {
  showToast("Payment is processing…", "fa-circle-info text-blue-500");
} else if (paymentIntent.status === "requires_payment_method") {
  showToast("Payment failed. Try another card.", "fa-circle-xmark text-red-500");
}

const orderId = new URLSearchParams(window.location.search).get("orderId");
const url = new URL(`$yourResultPageUrl`, location.origin);
url.searchParams.set("orderId", orderId);
url.searchParams.set("payment_intent_client_secret", currentPaymentIntent.clientSecret);
setTimeout(() => { window.location.href = url.toString(); }, 600);

The Result Page

The payment result page should handle the following steps:

  1. Read orderId and payment_intent_client_secret from the query parameters.
  2. Retrieve the PaymentIntent from Stripe and check its status.
  3. If required, handle any next_action and re-fetch the PaymentIntent.
  4. If the status is "succeeded", display a clear visual confirmation.
  5. Fetch the listing instance from the backend to display any additional order or fulfillment details.

Note that paymentIntent status only gives information about the Stripe side. The listing instance in the service should also ve updated to start the fulfillment. In most cases, the startlistingPayment api updates the status of the order using the response of the paymentIntent confirmation, but as stated above in some cases this update can be done only when the webhook executes. So in teh result page always get the final payment status in the `listing.

To ensure that service i To fetch the listing instance, you van use the related api which is given before, and to ensure that the service is updated with the latest status read the paymentConfirmation field of the listing instance.

if (listing.paymentConfirmation == "canceled") {
  // the payment is canceled, user can be informed that they should try again
} if (listing.paymentConfirmation == "paid") {
  // service knows that payment is done, user can be informed that fullfillment started
} else {
  // it may be pending, processing
  // Fetch the object again until a canceled or paid status
}

Payment Flow via MCP (AI Chat Integration)

The payment flow is also accessible through the MCP (Model Context Protocol) AI chat interface. The listing service exposes an initiatePayment MCP tool that the AI can call when the user wants to pay for an order.

How initiatePayment Works in MCP

  1. User asks to pay — e.g., “I want to pay for my order”
  2. AI calls initiatePayment MCP tool with orderId (and orderType if multiple order types exist)
  3. Tool validates the order exists, is payable, and the user is authorized
  4. Tool returns __frontendAction with type: "payment" — this is NOT a direct payment execution
  5. Frontend chat UI renders a PaymentActionCard with a “Pay Now” button
  6. User clicks “Pay Now” — the frontend opens a payment modal with CheckoutForm
  7. Standard Stripe flow proceeds (payment method selection, 3DS handling, etc.)

Frontend Action Response Format

The initiatePayment MCP tool returns:

{
  "__frontendAction": {
    "type": "payment",
    "orderId": "uuid",
    "orderType": "listing",
    "serviceName": "listing",
    "amount": 99.99,
    "currency": "USD",
    "description": "Order description"
  },
  "message": "Payment is ready. Click the button below to proceed."
}

MCP Client Architecture

The frontend communicates with MCP tools through the MCP BFF (Backend-for-Frontend) service. The MCP BFF aggregates tool calls across all backend services and provides:

The PaymentActionCard component handles the rest: fetching order details, rendering the payment UI, and completing the Stripe checkout flow — all within the chat interface.


CLONESAHIBINDEN

FRONTEND GUIDE FOR AI CODING AGENTS - PART 12 - ListingImage Service

This document is a part of a REST API guide for the clonesahibinden project. It is designed for AI agents that will generate frontend code to consume the project’s backend.

This document provides extensive instruction for the usage of listingImage

Service Access

ListingImage service management is handled through service specific base urls.

ListingImage service may be deployed to the preview server, staging server, or production server. Therefore,it has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the login page (already handled in first part.).

For the listingImage service, the base URLs are:

Scope

ListingImage Service Description

Manages uploading, linking, ordering, and storing all images attached to classified listings. Enforces image file format, size, count, and metadata standards; supports multi-resolution handling and per-listing image count limits.

ListingImage service provides apis and business logic for following data objects in clonesahibinden application. Each data object may be either a central domain of the application data structure or a related helper data object for a central concept. Note that data object concept is equal to table concept in the database, in the service database each data object is represented as a db table scheme and the object instances as table rows.

listingImage Data Object: Stores metadata about each image attached to a classified listing, with enforced image count, format, size, and dimension constraints. Four separate URL fields for different resolutions. Tied to listing; managed by listing owner/admin/mod.

ListingImage Service Frontend Description By The Backend Architect

Each image attached to a listing is tracked via this service. Display order/sort of images is controlled via the sortOrder field. No more than 10 images are allowed for any listing, and only supported formats/size are accepted. Read-only access is public, create/update/delete is restricted to listing owner/admin/moderator. Images display in ordered gallery, with optional main/cover selection based on sortOrder=1. On exceeding image count or constraint errors, display informative error. Deletion is soft for restoration until the listing is removed or archived.

API Structure

Object Structure of a Successful Response

When the service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope includes the data and essential metadata such as configuration details and pagination information, providing context to the client.

HTTP Status Codes:

Success Response Format:

For successful operations, the response includes a "status": "OK" property, signaling that the request executed successfully. The structure of a successful response is outlined below:

{
  "status":"OK",
  "statusCode": 200,   
  "elapsedMs":126,
  "ssoTime":120,
  "source": "db",
  "cacheKey": "hexCode",
  "userId": "ID",
  "sessionId": "ID",
  "requestId": "ID",
  "dataName":"products",
  "method":"GET",
  "action":"list",
  "appVersion":"Version",
  "rowCount":3,
  "products":[{},{},{}],
  "paging": {
    "pageNumber":1, 
    "pageRowCount":25, 
    "totalRowCount":3,
    "pageCount":1
  },
  "filters": [],
  "uiPermissions": []
}

Additional Data

Each API may include additional data besides the main data object, depending on the business logic of the API. These will be provided in each API’s response signature.

Error Response

If a request encounters an issue—whether due to a logical fault or a technical problem—the service responds with a standardized JSON error structure. The HTTP status code indicates the nature of the error, using commonly recognized codes for clarity:

Each error response is structured to provide meaningful insight into the problem, assisting in efficient diagnosis and resolution.

{
  "result": "ERR",
  "status": 400,
  "message": "errMsg_organizationIdisNotAValidID",
  "errCode": 400,
  "date": "2024-03-19T12:13:54.124Z",
  "detail": "String"
}

Bucket Management

(This information is also given in PART 1 prompt.)

This application has a bucket service used to store user files and other object-related files. The bucket service is login-agnostic, so for write operations or private reads, include a bucket token (provided by services) in the request’s Authorization header as a Bearer token.

Please note that all other business services require the access token in the Bearer header, while the bucket service expects a bucket token because it is login-agnostic. Ensure you manage the required token injection properly; any auth interceptor should not replace the bucket token with the access token.

User Bucket This bucket stores public user files for each user.

When a user logs in—or in the /currentuser response—there is a userBucketToken to use when sending user-related public files to the bucket service.

{
  //...
  "userBucketToken": "e56d...."
}

To upload a file

POST {baseUrl}/bucket/upload

The request body is form-data which includes the bucketId and the file binary in the files field.

{
    bucketId: "{userId}-public-user-bucket",
    files: {binary}
}

Response status is 200 on success, e.g., body:

{
    "success": true,
    "data": [
        {
            "fileId": "9da03f6d-0409-41ad-bb06-225a244ae408",
            "originalName": "test (10).png",
            "mimeType": "image/png",
            "size": 604063,
            "status": "uploaded",
            "bucketName": "f7103b85-fcda-4dec-92c6-c336f71fd3a2-public-user-bucket",
            "isPublic": true,
            "downloadUrl": "https://babilcom.mindbricks.co/bucket/download/9da03f6d-0409-41ad-bb06-225a244ae408"
        }
    ]
}

To download a file from the bucket, you need its fileId. If you upload an avatar or other asset, ensure the download URL or the fileId is stored in the backend.

Buckets are mostly used in object creations that require an additional file, such as a product image or user avatar. After uploading your image to the bucket, insert the returned download URL into the related property of the target object record.

Application Bucket

This Clonesahibinden application also includes a common public bucket that anyone can read, but only users with the superAdmin, admin, or saasAdmin roles can write (upload) to it.

When a user with one of these admin roles is logged in, the /login response or the /currentuser response also returns an applicationBucketToken field, which is used when uploading any file to the application bucket.

{
  //...
  "applicationBucketToken": "e23fd...."
}

The common public application bucket ID is

"clonesahibinden-public-common-bucket"

In certain admin areas—such as product management pages—since the user already has the application bucket token, they will be able to upload related object images.

Please configure your UI to upload files to the application bucket using this bucket token whenever needed.

Object Buckets Some objects may also return a bucket token for uploading or accessing files related to that object. For example, in a project management application, when you fetch a project’s data, a public or private bucket token may be provided to upload or download project-related files.

These buckets will be used as described in the relevant object definitions.

ListingImage Data Object

Stores metadata about each image attached to a classified listing, with enforced image count, format, size, and dimension constraints. Four separate URL fields for different resolutions. Tied to listing; managed by listing owner/admin/mod.

ListingImage Data Object Frontend Description By The Backend Architect

Displays individual image information related to a listing, including all available sizes and original asset. Used in the gallery/carousel of listing details. Allows reordering (via sortOrder), and restricts total images per listing to 10. All constraints (file type, minimum/maximum dimensions, and size) must be checked before saving. Image deletion disables but does not erase record until listing is deleted. Main image is the one with the lowest sortOrder value.

ListingImage Data Object Properties

ListingImage data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
fileSize Integer false Yes No Size of the image file in bytes.
fullUrl String false Yes No URL to a full-res processed but possibly optimized image (e.g. with max side 1600px, for gallery display).
height Float false Yes No Height of the original image, in pixels.
listingId ID false Yes No The related listing that this image belongs to.
mediumUrl String false Yes No URL to the medium-sized processed image version (e.g. 400x300px or similar).
mimeType String false Yes No MIME type of the image (e.g., image/jpeg, image/png, image/webp, image/gif).
sortOrder Integer false Yes No Order value for display in UI; the lowest value image is the cover/main image.
thumbnailUrl String false Yes No URL to the thumbnail image (small size, e.g. 120x90px).
uploadedAt Date false Yes No UTC timestamp when image was uploaded to platform.
url String false Yes No URL to the original uploaded image file (full resolution/original).
width Float false Yes No Width of the original image, in pixels.

Relation Properties

listingId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one.

In frontend, please ensure that,

1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

Filter Properties

listingId

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.

Default CRUD APIs

For each data object, the backend architect may designate default APIs for standard operations (create, update, delete, get, list). These are the APIs that frontend CRUD forms and AI agents should use for basic record management. If no default is explicitly set (isDefaultApi), the frontend generator auto-discovers the most general API for each operation.

ListingImage Default APIs

Operation API Name Route Explicitly Set
Create createListingImage /v1/listingimages Auto
Update updateListingImage /v1/listingimages/:listingImageId Auto
Delete deleteListingImage /v1/listingimages/:listingImageId Auto
Get getListingImage /v1/listingimages/:listingImageId Auto
List listListingImages /v1/listlistingimages/:listingId System

When building CRUD forms for a data object, use the default create/update APIs listed above. The form fields should correspond to the API’s body parameters. For relation fields, render a dropdown loaded from the related object’s list API using the display label property.

API Reference

Create Listingimage API

Create an image record attached to a listing. Enforces max 10 images per listing, allowed file types (image/jpeg, png, webp, gif), max file size (10MB), and minimum dimensions (400x300px). Only owner of related listing, admin, or moderator can add.

API Frontend Description By The Backend Architect

Show file/image upload UI, allow per-image progress and preview, error on more than 10 images, reject unsupported types/sizes/resolutions. On success, show image in gallery. Only listing owner/moderator/admin may add images.

Rest Route

The createListingImage API REST controller can be triggered via the following route:

/v1/listingimages

Rest Request Parameters

The createListingImage api has got 11 regular request parameters

Parameter Type Required Population
fileSize Integer true request.body?.[“fileSize”]
fullUrl String true request.body?.[“fullUrl”]
height Float true request.body?.[“height”]
listingId ID true request.body?.[“listingId”]
mediumUrl String true request.body?.[“mediumUrl”]
mimeType String true request.body?.[“mimeType”]
sortOrder Integer true request.body?.[“sortOrder”]
thumbnailUrl String true request.body?.[“thumbnailUrl”]
uploadedAt Date true request.body?.[“uploadedAt”]
url String true request.body?.[“url”]
width Float true request.body?.[“width”]
fileSize : Size of the image file in bytes.
fullUrl : URL to a full-res processed but possibly optimized image (e.g. with max side 1600px, for gallery display).
height : Height of the original image, in pixels.
listingId : The related listing that this image belongs to.
mediumUrl : URL to the medium-sized processed image version (e.g. 400x300px or similar).
mimeType : MIME type of the image (e.g., image/jpeg, image/png, image/webp, image/gif).
sortOrder : Order value for display in UI; the lowest value image is the cover/main image.
thumbnailUrl : URL to the thumbnail image (small size, e.g. 120x90px).
uploadedAt : UTC timestamp when image was uploaded to platform.
url : URL to the original uploaded image file (full resolution/original).
width : Width of the original image, in pixels.

REST Request To access the api you can use the REST controller with the path POST /v1/listingimages

  axios({
    method: 'POST',
    url: '/v1/listingimages',
    data: {
            fileSize:"Integer",  
            fullUrl:"String",  
            height:"Float",  
            listingId:"ID",  
            mediumUrl:"String",  
            mimeType:"String",  
            sortOrder:"Integer",  
            thumbnailUrl:"String",  
            uploadedAt:"Date",  
            url:"String",  
            width:"Float",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listingImage",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"listingImage": {
		"id": "ID",
		"fileSize": "Integer",
		"fullUrl": "String",
		"height": "Float",
		"listingId": "ID",
		"mediumUrl": "String",
		"mimeType": "String",
		"sortOrder": "Integer",
		"thumbnailUrl": "String",
		"uploadedAt": "Date",
		"url": "String",
		"width": "Float",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Delete Listingimage API

Remove (soft delete) this image record. Only admin, moderator, or owner of related listing may take action. Image stays in database; actual asset removal is scheduled or handled in listing/bucket image service.

API Frontend Description By The Backend Architect

Provide a delete/trash icon per image. Show immediate feedback on delete (soft delete). Remove from gallery and reflow grid/order. Deletion disables but does not erase image from DB or storage bucket (handled asynchronously).

Rest Route

The deleteListingImage API REST controller can be triggered via the following route:

/v1/listingimages/:listingImageId

Rest Request Parameters

The deleteListingImage api has got 1 regular request parameter

Parameter Type Required Population
listingImageId ID true request.params?.[“listingImageId”]
listingImageId : This id paremeter is used to select the required data object that will be deleted

REST Request To access the api you can use the REST controller with the path DELETE /v1/listingimages/:listingImageId

  axios({
    method: 'DELETE',
    url: `/v1/listingimages/${listingImageId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listingImage",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"listingImage": {
		"id": "ID",
		"fileSize": "Integer",
		"fullUrl": "String",
		"height": "Float",
		"listingId": "ID",
		"mediumUrl": "String",
		"mimeType": "String",
		"sortOrder": "Integer",
		"thumbnailUrl": "String",
		"uploadedAt": "Date",
		"url": "String",
		"width": "Float",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Listingimage API

Retrieve details/metadata of one image for a listing. Publicly accessible for gallery/carousel; has no sensitive info.

API Frontend Description By The Backend Architect

Used to fetch image details (URLs for all resolutions and display order) for single-image views. All users can access listing image detail for active listings.

Rest Route

The getListingImage API REST controller can be triggered via the following route:

/v1/listingimages/:listingImageId

Rest Request Parameters

The getListingImage api has got 1 regular request parameter

Parameter Type Required Population
listingImageId ID true request.params?.[“listingImageId”]
listingImageId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/listingimages/:listingImageId

  axios({
    method: 'GET',
    url: `/v1/listingimages/${listingImageId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

This route’s response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listingImage",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"listingImage": {
		"isActive": true
	}
}

List Listingimages API

List all images belonging to a specific listing, sorted by sortOrder ascending. Returns up to 10 images per listing. Publicly accessible for populating image galleries.

API Frontend Description By The Backend Architect

Display all images in a listing as a gallery or carousel, sorted by sortOrder (lowest/1 is main image/cover). Maximum images per listing is 10. Used on public listing detail pages and for listing management.

Rest Route

The listListingImages API REST controller can be triggered via the following route:

/v1/listlistingimages/:listingId

Rest Request Parameters

The listListingImages api has got 1 regular request parameter

Parameter Type Required Population
listingId ID true request.query?.[“listingId”]
listingId : The related listing that this image belongs to… The parameter is used to query data.

REST Request To access the api you can use the REST controller with the path GET /v1/listlistingimages/:listingId

  axios({
    method: 'GET',
    url: `/v1/listlistingimages/${listingId}`,
    data: {
    
    },
    params: {
             listingId:'"ID"',  
    
        }
  });

REST Response

This route’s response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listingImages",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"listingImages": [
		{
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Update Listingimage API

Update sort order or image metadata; user is limited to manipulating images of their own listings (or admins/mods). Cannot move image to another listing. Can revalidate constraints on request.

API Frontend Description By The Backend Architect

Allow user to reorder images of a listing (changing sortOrder), set another main image (sortOrder=1), or update image metadata. Show error if trying to move image between listings or violate constraints.

Rest Route

The updateListingImage API REST controller can be triggered via the following route:

/v1/listingimages/:listingImageId

Rest Request Parameters

The updateListingImage api has got 2 regular request parameters

Parameter Type Required Population
listingImageId ID true request.params?.[“listingImageId”]
sortOrder Integer false request.body?.[“sortOrder”]
listingImageId : This id paremeter is used to select the required data object that will be updated
sortOrder : Order value for display in UI; the lowest value image is the cover/main image.

REST Request To access the api you can use the REST controller with the path PATCH /v1/listingimages/:listingImageId

  axios({
    method: 'PATCH',
    url: `/v1/listingimages/${listingImageId}`,
    data: {
            sortOrder:"Integer",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listingImage",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"listingImage": {
		"id": "ID",
		"fileSize": "Integer",
		"fullUrl": "String",
		"height": "Float",
		"listingId": "ID",
		"mediumUrl": "String",
		"mimeType": "String",
		"sortOrder": "Integer",
		"thumbnailUrl": "String",
		"uploadedAt": "Date",
		"url": "String",
		"width": "Float",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

_fetch Listlistingimage API

System API to fetch list of listingImage records for frontend application. Auto-generated, not visible in design.

Rest Route

The _fetchListListingImage API REST controller can be triggered via the following route:

/v1/_fetchlistlistingimage

Rest Request Parameters

Filter Parameters

The _fetchListListingImage api supports 1 optional filter parameter for filtering list results:

listingId (ID): The related listing that this image belongs to.

REST Request To access the api you can use the REST controller with the path GET /v1/_fetchlistlistingimage

  axios({
    method: 'GET',
    url: '/v1/_fetchlistlistingimage',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // listingId: '<value>' // Filter by listingId
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listingImages",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"listingImages": [
		{
			"id": "ID",
			"fileSize": "Integer",
			"fullUrl": "String",
			"height": "Float",
			"listingId": "ID",
			"mediumUrl": "String",
			"mimeType": "String",
			"sortOrder": "Integer",
			"thumbnailUrl": "String",
			"uploadedAt": "Date",
			"url": "String",
			"width": "Float",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"listing": [
				{
					"attributes": "Object",
					"categoryId": "ID",
					"condition": "Enum",
					"condition_idx": "Integer",
					"contactEmail": "String",
					"contactPhone": "String",
					"currency": "String",
					"description": "Text",
					"expiresAt": "Date",
					"favoriteCount": "Integer",
					"isPremium": "Boolean",
					"listingType": "Enum",
					"listingType_idx": "Integer",
					"locationId": "ID",
					"_paymentConfirmation": "String",
					"premiumExpiry": "Date",
					"premiumType": "Enum",
					"premiumType_idx": "Integer",
					"price": "Double",
					"status": "Enum",
					"status_idx": "Integer",
					"subcategoryId": "ID",
					"title": "String",
					"userId": "ID",
					"viewsCount": "Integer",
					"paymentConfirmation": "Enum",
					"paymentConfirmation_idx": "Integer"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

After this prompt, the user may give you new instructions to update the output of this prompt or provide subsequent prompts about the project.


CLONESAHIBINDEN

FRONTEND GUIDE FOR AI CODING AGENTS - PART 13 - Payment Service

This document is a part of a REST API guide for the clonesahibinden project. It is designed for AI agents that will generate frontend code to consume the project’s backend.

This document provides extensive instruction for the usage of payment

Service Access

Payment service management is handled through service specific base urls.

Payment service may be deployed to the preview server, staging server, or production server. Therefore,it has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the login page (already handled in first part.).

For the payment service, the base URLs are:

Scope

Payment Service Description

Handles Stripe payment flow for one-time premium upgrades on classified listings. Creates and tracks payment transactions, manages Stripe Checkout session and webhooks, and notifies the listing service to update premium status. Exposes payment history endpoints for users and reconciliation for admin.

Payment service provides apis and business logic for following data objects in clonesahibinden application. Each data object may be either a central domain of the application data structure or a related helper data object for a central concept. Note that data object concept is equal to table concept in the database, in the service database each data object is represented as a db table scheme and the object instances as table rows.

paymentTransaction Data Object: Represents a Stripe-based payment for a one-time premium listing upgrade. Linked to user and listing, with payment metadata, premium details, status, and Stripe reconciliation fields. Immutable except for webhook-driven status updates.

Payment Service Frontend Description By The Backend Architect

Payment Microservice – Frontend Integration Guidance

API Structure

Object Structure of a Successful Response

When the service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope includes the data and essential metadata such as configuration details and pagination information, providing context to the client.

HTTP Status Codes:

Success Response Format:

For successful operations, the response includes a "status": "OK" property, signaling that the request executed successfully. The structure of a successful response is outlined below:

{
  "status":"OK",
  "statusCode": 200,   
  "elapsedMs":126,
  "ssoTime":120,
  "source": "db",
  "cacheKey": "hexCode",
  "userId": "ID",
  "sessionId": "ID",
  "requestId": "ID",
  "dataName":"products",
  "method":"GET",
  "action":"list",
  "appVersion":"Version",
  "rowCount":3,
  "products":[{},{},{}],
  "paging": {
    "pageNumber":1, 
    "pageRowCount":25, 
    "totalRowCount":3,
    "pageCount":1
  },
  "filters": [],
  "uiPermissions": []
}

Additional Data

Each API may include additional data besides the main data object, depending on the business logic of the API. These will be provided in each API’s response signature.

Error Response

If a request encounters an issue—whether due to a logical fault or a technical problem—the service responds with a standardized JSON error structure. The HTTP status code indicates the nature of the error, using commonly recognized codes for clarity:

Each error response is structured to provide meaningful insight into the problem, assisting in efficient diagnosis and resolution.

{
  "result": "ERR",
  "status": 400,
  "message": "errMsg_organizationIdisNotAValidID",
  "errCode": 400,
  "date": "2024-03-19T12:13:54.124Z",
  "detail": "String"
}

Bucket Management

(This information is also given in PART 1 prompt.)

This application has a bucket service used to store user files and other object-related files. The bucket service is login-agnostic, so for write operations or private reads, include a bucket token (provided by services) in the request’s Authorization header as a Bearer token.

Please note that all other business services require the access token in the Bearer header, while the bucket service expects a bucket token because it is login-agnostic. Ensure you manage the required token injection properly; any auth interceptor should not replace the bucket token with the access token.

User Bucket This bucket stores public user files for each user.

When a user logs in—or in the /currentuser response—there is a userBucketToken to use when sending user-related public files to the bucket service.

{
  //...
  "userBucketToken": "e56d...."
}

To upload a file

POST {baseUrl}/bucket/upload

The request body is form-data which includes the bucketId and the file binary in the files field.

{
    bucketId: "{userId}-public-user-bucket",
    files: {binary}
}

Response status is 200 on success, e.g., body:

{
    "success": true,
    "data": [
        {
            "fileId": "9da03f6d-0409-41ad-bb06-225a244ae408",
            "originalName": "test (10).png",
            "mimeType": "image/png",
            "size": 604063,
            "status": "uploaded",
            "bucketName": "f7103b85-fcda-4dec-92c6-c336f71fd3a2-public-user-bucket",
            "isPublic": true,
            "downloadUrl": "https://babilcom.mindbricks.co/bucket/download/9da03f6d-0409-41ad-bb06-225a244ae408"
        }
    ]
}

To download a file from the bucket, you need its fileId. If you upload an avatar or other asset, ensure the download URL or the fileId is stored in the backend.

Buckets are mostly used in object creations that require an additional file, such as a product image or user avatar. After uploading your image to the bucket, insert the returned download URL into the related property of the target object record.

Application Bucket

This Clonesahibinden application also includes a common public bucket that anyone can read, but only users with the superAdmin, admin, or saasAdmin roles can write (upload) to it.

When a user with one of these admin roles is logged in, the /login response or the /currentuser response also returns an applicationBucketToken field, which is used when uploading any file to the application bucket.

{
  //...
  "applicationBucketToken": "e23fd...."
}

The common public application bucket ID is

"clonesahibinden-public-common-bucket"

In certain admin areas—such as product management pages—since the user already has the application bucket token, they will be able to upload related object images.

Please configure your UI to upload files to the application bucket using this bucket token whenever needed.

Object Buckets Some objects may also return a bucket token for uploading or accessing files related to that object. For example, in a project management application, when you fetch a project’s data, a public or private bucket token may be provided to upload or download project-related files.

These buckets will be used as described in the relevant object definitions.

PaymentTransaction Data Object

Represents a Stripe-based payment for a one-time premium listing upgrade. Linked to user and listing, with payment metadata, premium details, status, and Stripe reconciliation fields. Immutable except for webhook-driven status updates.

PaymentTransaction Data Object Frontend Description By The Backend Architect

paymentTransaction Usage Guidance

PaymentTransaction Data Object Properties

PaymentTransaction data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
amount Double false Yes No Payment amount for selected premiumType, in target currency.
currency String false Yes No Currency in ISO-4217 format (e.g., ‘TRY’,‘USD’) used for Stripe checkout.
listingId ID false Yes No Target classified listing being upgraded to premium.
paymentConfirmedAt Date false No No Date/time when payment was confirmed and premium was granted. Null if never successful/aborted.
premiumType Enum false Yes No Premium upgrade package: bronze, silver, gold (matches frontend/listing options).
status Enum false Yes No Status of payment: pending, awaiting_confirmation (stripe checkout created, awaiting webhook), success (confirmed), failed (declined or errored), canceled (user canceled).
stripeEventId String false No No Last Stripe event webhook ID processed for this payment (used for double-spend/deduplication of webhook).
stripeSessionId String false No No Stripe Checkout Session ID associated with this payment (used for reconciling gateway callbacks).
userId ID false Yes No User (buyer) who made the payment (auth:user)

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an additional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options.

Relation Properties

listingId userId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one.

In frontend, please ensure that,

1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

Filter Properties

listingId paymentConfirmedAt premiumType status userId

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.

Default CRUD APIs

For each data object, the backend architect may designate default APIs for standard operations (create, update, delete, get, list). These are the APIs that frontend CRUD forms and AI agents should use for basic record management. If no default is explicitly set (isDefaultApi), the frontend generator auto-discovers the most general API for each operation.

PaymentTransaction Default APIs

Operation API Name Route Explicitly Set
Create createPaymentTransaction /v1/payments/create Auto
Update stripeWebhookCallback /v1/payments/webhook Auto
Delete none - Auto
Get getPaymentTransaction /v1/payments/:id Auto
List listPaymentTransactions /v1/payments System

When building CRUD forms for a data object, use the default create/update APIs listed above. The form fields should correspond to the API’s body parameters. For relation fields, render a dropdown loaded from the related object’s list API using the display label property.

API Reference

Create Paymenttransaction API

Create a paymentTransaction to initiate a Stripe Checkout for premium upgrade on a listing. Checks listing and user, prevents duplicate active payments, creates transaction with status=‘pending’, triggers Stripe checkout, and returns checkout session URL/info.

API Frontend Description By The Backend Architect

Initiate Premium Payment

Rest Route

The createPaymentTransaction API REST controller can be triggered via the following route:

/v1/payments/create

Rest Request Parameters

The createPaymentTransaction api has got 2 regular request parameters

Parameter Type Required Population
listingId ID true request.body?.[“listingId”]
premiumType String true request.body?.[“premiumType”]
listingId : ID of the listing to upgrade to premium
premiumType : PremiumType to purchase (‘bronze’, ‘silver’, ‘gold’)

REST Request To access the api you can use the REST controller with the path POST /v1/payments/create

  axios({
    method: 'POST',
    url: '/v1/payments/create',
    data: {
            listingId:"ID",  
            premiumType:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "paymentTransaction",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"paymentTransaction": {
		"id": "ID",
		"amount": "Double",
		"currency": "String",
		"listingId": "ID",
		"paymentConfirmedAt": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"status": "Enum",
		"status_idx": "Integer",
		"stripeEventId": "String",
		"stripeSessionId": "String",
		"userId": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	},
	"paymentResult": {
		"paymentTicketId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "Enum",
		"paymentIntentInfo": "Object",
		"statusLiteral": "String",
		"amount": "Double",
		"currency": "String",
		"success": true,
		"description": "String",
		"metadata": "Object",
		"paymentUserParams": "Object"
	}
}

Get Paymenttransaction API

Retrieve a paymentTransaction by ID. Only owner or admin may access. Used for order confirmation display, receipt, etc.

API Frontend Description By The Backend Architect

Rest Route

The getPaymentTransaction API REST controller can be triggered via the following route:

/v1/payments/:id

Rest Request Parameters

The getPaymentTransaction api has got 2 regular request parameters

Parameter Type Required Population
paymentTransactionId ID true request.params?.[“paymentTransactionId”]
id String true request.params?.[“id”]
paymentTransactionId : This id paremeter is used to query the required data object.
id : This parameter will be used to select the data object that is queried

REST Request To access the api you can use the REST controller with the path GET /v1/payments/:id

  axios({
    method: 'GET',
    url: `/v1/payments/${id}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

This route’s response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "paymentTransaction",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"paymentTransaction": {
		"listingInfo": {
			"categoryId": "ID",
			"isPremium": "Boolean",
			"premiumExpiry": "Date",
			"premiumType": "Enum",
			"premiumType_idx": "Integer",
			"subcategoryId": "ID",
			"title": "String"
		},
		"isActive": true
	}
}

List Paymenttransactions API

List all paymentTransactions for current user, paginated. Admin can query all users. Used for user payment history and admin reconciliation.

API Frontend Description By The Backend Architect

Rest Route

The listPaymentTransactions API REST controller can be triggered via the following route:

/v1/payments

Rest Request Parameters The listPaymentTransactions api has got no request parameters.

REST Request To access the api you can use the REST controller with the path GET /v1/payments

  axios({
    method: 'GET',
    url: '/v1/payments',
    data: {
    
    },
    params: {
    
        }
  });

REST Response

This route’s response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "paymentTransactions",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"paymentTransactions": [
		{
			"listingInfo": [
				{
					"categoryId": "ID",
					"isPremium": "Boolean",
					"premiumExpiry": "Date",
					"premiumType": "Enum",
					"premiumType_idx": "Integer",
					"subcategoryId": "ID",
					"title": "String"
				},
				{},
				{}
			],
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Stripe Webhookcallback API

Receives Stripe webhook events, updates corresponding paymentTransaction (status, confirmation), triggers listing premium upgrade via interservice call. Only accepts trusted Stripe event payloads. No login required.

API Frontend Description By The Backend Architect

Rest Route

The stripeWebhookCallback API REST controller can be triggered via the following route:

/v1/payments/webhook

Rest Request Parameters

The stripeWebhookCallback api has got 1 regular request parameter

Parameter Type Required Population
paymentTransactionId ID true request.params?.[“paymentTransactionId”]
paymentTransactionId : This id paremeter is used to select the required data object that will be updated

REST Request To access the api you can use the REST controller with the path POST /v1/payments/webhook

  axios({
    method: 'POST',
    url: '/v1/payments/webhook',
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "paymentTransaction",
	"method": "POST",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"paymentTransaction": {
		"id": "ID",
		"amount": "Double",
		"currency": "String",
		"listingId": "ID",
		"paymentConfirmedAt": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"status": "Enum",
		"status_idx": "Integer",
		"stripeEventId": "String",
		"stripeSessionId": "String",
		"userId": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

_fetch Listpaymenttransaction API

System API to fetch list of paymentTransaction records for frontend application. Auto-generated, not visible in design.

Rest Route

The _fetchListPaymentTransaction API REST controller can be triggered via the following route:

/v1/_fetchlistpaymenttransaction

Rest Request Parameters

Filter Parameters

The _fetchListPaymentTransaction api supports 5 optional filter parameters for filtering list results:

listingId (ID): Target classified listing being upgraded to premium.

paymentConfirmedAt (Date): Date/time when payment was confirmed and premium was granted. Null if never successful/aborted.

premiumType (Enum): Premium upgrade package: bronze, silver, gold (matches frontend/listing options).

status (Enum): Status of payment: pending, awaiting_confirmation (stripe checkout created, awaiting webhook), success (confirmed), failed (declined or errored), canceled (user canceled).

userId (ID): User (buyer) who made the payment (auth:user)

REST Request To access the api you can use the REST controller with the path GET /v1/_fetchlistpaymenttransaction

  axios({
    method: 'GET',
    url: '/v1/_fetchlistpaymenttransaction',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // listingId: '<value>' // Filter by listingId
        // paymentConfirmedAt: '<value>' // Filter by paymentConfirmedAt
        // premiumType: '<value>' // Filter by premiumType
        // status: '<value>' // Filter by status
        // userId: '<value>' // Filter by userId
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "paymentTransactions",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"paymentTransactions": [
		{
			"id": "ID",
			"amount": "Double",
			"currency": "String",
			"listingId": "ID",
			"paymentConfirmedAt": "Date",
			"premiumType": "Enum",
			"premiumType_idx": "Integer",
			"status": "Enum",
			"status_idx": "Integer",
			"stripeEventId": "String",
			"stripeSessionId": "String",
			"userId": "ID",
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"listing": [
				{
					"attributes": "Object",
					"categoryId": "ID",
					"condition": "Enum",
					"condition_idx": "Integer",
					"contactEmail": "String",
					"contactPhone": "String",
					"currency": "String",
					"description": "Text",
					"expiresAt": "Date",
					"favoriteCount": "Integer",
					"isPremium": "Boolean",
					"listingType": "Enum",
					"listingType_idx": "Integer",
					"locationId": "ID",
					"_paymentConfirmation": "String",
					"premiumExpiry": "Date",
					"premiumType": "Enum",
					"premiumType_idx": "Integer",
					"price": "Double",
					"status": "Enum",
					"status_idx": "Integer",
					"subcategoryId": "ID",
					"title": "String",
					"userId": "ID",
					"viewsCount": "Integer",
					"paymentConfirmation": "Enum",
					"paymentConfirmation_idx": "Integer"
				},
				{},
				{}
			],
			"buyer": [
				{
					"fullname": "String"
				},
				{},
				{}
			],
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

After this prompt, the user may give you new instructions to update the output of this prompt or provide subsequent prompts about the project.



Related Documentation

For more detailed information, refer to:


Generated by Mindbricks Genesis Engine