diff --git a/apps/csms/drizzle/0003_milky_supreme_intelligence.sql b/apps/csms/drizzle/0003_milky_supreme_intelligence.sql new file mode 100644 index 0000000..6ffb63e --- /dev/null +++ b/apps/csms/drizzle/0003_milky_supreme_intelligence.sql @@ -0,0 +1,17 @@ +CREATE TABLE "tariff" ( + "id" varchar PRIMARY KEY NOT NULL, + "slots" jsonb NOT NULL, + "peak_electricity_price" integer DEFAULT 0 NOT NULL, + "peak_service_fee" integer DEFAULT 0 NOT NULL, + "valley_electricity_price" integer DEFAULT 0 NOT NULL, + "valley_service_fee" integer DEFAULT 0 NOT NULL, + "flat_electricity_price" integer DEFAULT 0 NOT NULL, + "flat_service_fee" integer DEFAULT 0 NOT NULL, + "is_active" boolean DEFAULT true NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +ALTER TABLE "charge_point" ADD COLUMN "pricing_mode" varchar DEFAULT 'fixed' NOT NULL;--> statement-breakpoint +ALTER TABLE "transaction" ADD COLUMN "electricity_fee" integer;--> statement-breakpoint +ALTER TABLE "transaction" ADD COLUMN "service_fee" integer; \ No newline at end of file diff --git a/apps/csms/drizzle/meta/0003_snapshot.json b/apps/csms/drizzle/meta/0003_snapshot.json new file mode 100644 index 0000000..9f65f21 --- /dev/null +++ b/apps/csms/drizzle/meta/0003_snapshot.json @@ -0,0 +1,1936 @@ +{ + "id": "7507bde1-447c-4b9b-8219-678a5e7414b0", + "prevId": "8fd4c986-cb5b-40ad-a152-55933ddc6d44", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.account": { + "name": "account", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "account_id": { + "name": "account_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "access_token": { + "name": "access_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_token": { + "name": "refresh_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "id_token": { + "name": "id_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "access_token_expires_at": { + "name": "access_token_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "refresh_token_expires_at": { + "name": "refresh_token_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "account_userId_idx": { + "name": "account_userId_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "account_user_id_user_id_fk": { + "name": "account_user_id_user_id_fk", + "tableFrom": "account", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.passkey": { + "name": "passkey", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "public_key": { + "name": "public_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "credential_id": { + "name": "credential_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "counter": { + "name": "counter", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "device_type": { + "name": "device_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "backed_up": { + "name": "backed_up", + "type": "boolean", + "primaryKey": false, + "notNull": true + }, + "transports": { + "name": "transports", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "aaguid": { + "name": "aaguid", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "passkey_userId_idx": { + "name": "passkey_userId_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "passkey_credentialID_idx": { + "name": "passkey_credentialID_idx", + "columns": [ + { + "expression": "credential_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "passkey_user_id_user_id_fk": { + "name": "passkey_user_id_user_id_fk", + "tableFrom": "passkey", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.session": { + "name": "session", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "ip_address": { + "name": "ip_address", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "impersonated_by": { + "name": "impersonated_by", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "session_userId_idx": { + "name": "session_userId_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "session_user_id_user_id_fk": { + "name": "session_user_id_user_id_fk", + "tableFrom": "session", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "session_token_unique": { + "name": "session_token_unique", + "nullsNotDistinct": false, + "columns": [ + "token" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user": { + "name": "user", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email_verified": { + "name": "email_verified", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "banned": { + "name": "banned", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": false + }, + "ban_reason": { + "name": "ban_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "ban_expires": { + "name": "ban_expires", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "username": { + "name": "username", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "display_username": { + "name": "display_username", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "user_email_unique": { + "name": "user_email_unique", + "nullsNotDistinct": false, + "columns": [ + "email" + ] + }, + "user_username_unique": { + "name": "user_username_unique", + "nullsNotDistinct": false, + "columns": [ + "username" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.verification": { + "name": "verification", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "identifier": { + "name": "identifier", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "verification_identifier_idx": { + "name": "verification_identifier_idx", + "columns": [ + { + "expression": "identifier", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.charge_point": { + "name": "charge_point", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "varchar", + "primaryKey": true, + "notNull": true + }, + "charge_point_identifier": { + "name": "charge_point_identifier", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true + }, + "charge_point_serial_number": { + "name": "charge_point_serial_number", + "type": "varchar(25)", + "primaryKey": false, + "notNull": false + }, + "charge_point_model": { + "name": "charge_point_model", + "type": "varchar(20)", + "primaryKey": false, + "notNull": true + }, + "charge_point_vendor": { + "name": "charge_point_vendor", + "type": "varchar(20)", + "primaryKey": false, + "notNull": true + }, + "firmware_version": { + "name": "firmware_version", + "type": "varchar(50)", + "primaryKey": false, + "notNull": false + }, + "iccid": { + "name": "iccid", + "type": "varchar(20)", + "primaryKey": false, + "notNull": false + }, + "imsi": { + "name": "imsi", + "type": "varchar(20)", + "primaryKey": false, + "notNull": false + }, + "meter_serial_number": { + "name": "meter_serial_number", + "type": "varchar(25)", + "primaryKey": false, + "notNull": false + }, + "meter_type": { + "name": "meter_type", + "type": "varchar(25)", + "primaryKey": false, + "notNull": false + }, + "registration_status": { + "name": "registration_status", + "type": "varchar", + "primaryKey": false, + "notNull": true, + "default": "'Pending'" + }, + "heartbeat_interval": { + "name": "heartbeat_interval", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 60 + }, + "last_heartbeat_at": { + "name": "last_heartbeat_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_boot_notification_at": { + "name": "last_boot_notification_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "fee_per_kwh": { + "name": "fee_per_kwh", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "pricing_mode": { + "name": "pricing_mode", + "type": "varchar", + "primaryKey": false, + "notNull": true, + "default": "'fixed'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "charge_point_charge_point_identifier_unique": { + "name": "charge_point_charge_point_identifier_unique", + "nullsNotDistinct": false, + "columns": [ + "charge_point_identifier" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.charging_profile": { + "name": "charging_profile", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true + }, + "charge_point_id": { + "name": "charge_point_id", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "connector_id": { + "name": "connector_id", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "connector_number": { + "name": "connector_number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "transaction_id": { + "name": "transaction_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "stack_level": { + "name": "stack_level", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "charging_profile_purpose": { + "name": "charging_profile_purpose", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "charging_profile_kind": { + "name": "charging_profile_kind", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "recurrency_kind": { + "name": "recurrency_kind", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "valid_from": { + "name": "valid_from", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "valid_to": { + "name": "valid_to", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "charging_schedule": { + "name": "charging_schedule", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_charging_profile_charge_point_id": { + "name": "idx_charging_profile_charge_point_id", + "columns": [ + { + "expression": "charge_point_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_charging_profile_connector_id": { + "name": "idx_charging_profile_connector_id", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_charging_profile_purpose_stack": { + "name": "idx_charging_profile_purpose_stack", + "columns": [ + { + "expression": "connector_number", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "charging_profile_purpose", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "stack_level", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "charging_profile_charge_point_id_charge_point_id_fk": { + "name": "charging_profile_charge_point_id_charge_point_id_fk", + "tableFrom": "charging_profile", + "tableTo": "charge_point", + "columnsFrom": [ + "charge_point_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "charging_profile_connector_id_connector_id_fk": { + "name": "charging_profile_connector_id_connector_id_fk", + "tableFrom": "charging_profile", + "tableTo": "connector", + "columnsFrom": [ + "connector_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "charging_profile_transaction_id_transaction_id_fk": { + "name": "charging_profile_transaction_id_transaction_id_fk", + "tableFrom": "charging_profile", + "tableTo": "transaction", + "columnsFrom": [ + "transaction_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.connector": { + "name": "connector", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "varchar", + "primaryKey": true, + "notNull": true + }, + "charge_point_id": { + "name": "charge_point_id", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "connector_id": { + "name": "connector_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "varchar", + "primaryKey": false, + "notNull": true, + "default": "'Unavailable'" + }, + "error_code": { + "name": "error_code", + "type": "varchar", + "primaryKey": false, + "notNull": true, + "default": "'NoError'" + }, + "info": { + "name": "info", + "type": "varchar(50)", + "primaryKey": false, + "notNull": false + }, + "vendor_id": { + "name": "vendor_id", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false + }, + "vendor_error_code": { + "name": "vendor_error_code", + "type": "varchar(50)", + "primaryKey": false, + "notNull": false + }, + "last_status_at": { + "name": "last_status_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_connector_charge_point_id": { + "name": "idx_connector_charge_point_id", + "columns": [ + { + "expression": "charge_point_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_connector_charge_point_connector": { + "name": "idx_connector_charge_point_connector", + "columns": [ + { + "expression": "charge_point_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "connector_charge_point_id_charge_point_id_fk": { + "name": "connector_charge_point_id_charge_point_id_fk", + "tableFrom": "connector", + "tableTo": "charge_point", + "columnsFrom": [ + "charge_point_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.connector_status_history": { + "name": "connector_status_history", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "varchar", + "primaryKey": true, + "notNull": true + }, + "connector_id": { + "name": "connector_id", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "connector_number": { + "name": "connector_number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "error_code": { + "name": "error_code", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "info": { + "name": "info", + "type": "varchar(50)", + "primaryKey": false, + "notNull": false + }, + "vendor_id": { + "name": "vendor_id", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false + }, + "vendor_error_code": { + "name": "vendor_error_code", + "type": "varchar(50)", + "primaryKey": false, + "notNull": false + }, + "status_timestamp": { + "name": "status_timestamp", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "received_at": { + "name": "received_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_status_history_connector_id": { + "name": "idx_status_history_connector_id", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_status_history_timestamp": { + "name": "idx_status_history_timestamp", + "columns": [ + { + "expression": "status_timestamp", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_status_history_received_at": { + "name": "idx_status_history_received_at", + "columns": [ + { + "expression": "received_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "connector_status_history_connector_id_connector_id_fk": { + "name": "connector_status_history_connector_id_connector_id_fk", + "tableFrom": "connector_status_history", + "tableTo": "connector", + "columnsFrom": [ + "connector_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.id_tag": { + "name": "id_tag", + "schema": "", + "columns": { + "id_tag": { + "name": "id_tag", + "type": "varchar(20)", + "primaryKey": true, + "notNull": true + }, + "parent_id_tag": { + "name": "parent_id_tag", + "type": "varchar(20)", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "varchar", + "primaryKey": false, + "notNull": true, + "default": "'Accepted'" + }, + "expiry_date": { + "name": "expiry_date", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "balance": { + "name": "balance", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "card_layout": { + "name": "card_layout", + "type": "varchar", + "primaryKey": false, + "notNull": false, + "default": "'around'" + }, + "card_skin": { + "name": "card_skin", + "type": "varchar", + "primaryKey": false, + "notNull": false, + "default": "'circles'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "id_tag_user_id_user_id_fk": { + "name": "id_tag_user_id_user_id_fk", + "tableFrom": "id_tag", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.local_auth_list": { + "name": "local_auth_list", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "varchar", + "primaryKey": true, + "notNull": true + }, + "charge_point_id": { + "name": "charge_point_id", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "list_version": { + "name": "list_version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "id_tag": { + "name": "id_tag", + "type": "varchar(20)", + "primaryKey": false, + "notNull": true + }, + "parent_id_tag": { + "name": "parent_id_tag", + "type": "varchar(20)", + "primaryKey": false, + "notNull": false + }, + "id_tag_status": { + "name": "id_tag_status", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "expiry_date": { + "name": "expiry_date", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_local_auth_list_charge_point_id_tag": { + "name": "idx_local_auth_list_charge_point_id_tag", + "columns": [ + { + "expression": "charge_point_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id_tag", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "local_auth_list_charge_point_id_charge_point_id_fk": { + "name": "local_auth_list_charge_point_id_charge_point_id_fk", + "tableFrom": "local_auth_list", + "tableTo": "charge_point", + "columnsFrom": [ + "charge_point_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.meter_value": { + "name": "meter_value", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "varchar", + "primaryKey": true, + "notNull": true + }, + "transaction_id": { + "name": "transaction_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "connector_id": { + "name": "connector_id", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "charge_point_id": { + "name": "charge_point_id", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "connector_number": { + "name": "connector_number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "timestamp": { + "name": "timestamp", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "sampled_values": { + "name": "sampled_values", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "received_at": { + "name": "received_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_meter_value_transaction_id": { + "name": "idx_meter_value_transaction_id", + "columns": [ + { + "expression": "transaction_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_meter_value_connector_id": { + "name": "idx_meter_value_connector_id", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_meter_value_timestamp": { + "name": "idx_meter_value_timestamp", + "columns": [ + { + "expression": "timestamp", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "meter_value_transaction_id_transaction_id_fk": { + "name": "meter_value_transaction_id_transaction_id_fk", + "tableFrom": "meter_value", + "tableTo": "transaction", + "columnsFrom": [ + "transaction_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "meter_value_connector_id_connector_id_fk": { + "name": "meter_value_connector_id_connector_id_fk", + "tableFrom": "meter_value", + "tableTo": "connector", + "columnsFrom": [ + "connector_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "meter_value_charge_point_id_charge_point_id_fk": { + "name": "meter_value_charge_point_id_charge_point_id_fk", + "tableFrom": "meter_value", + "tableTo": "charge_point", + "columnsFrom": [ + "charge_point_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.reservation": { + "name": "reservation", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true + }, + "charge_point_id": { + "name": "charge_point_id", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "connector_id": { + "name": "connector_id", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "connector_number": { + "name": "connector_number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "expiry_date": { + "name": "expiry_date", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "id_tag": { + "name": "id_tag", + "type": "varchar(20)", + "primaryKey": false, + "notNull": true + }, + "parent_id_tag": { + "name": "parent_id_tag", + "type": "varchar(20)", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "varchar", + "primaryKey": false, + "notNull": true, + "default": "'Active'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_reservation_charge_point_id": { + "name": "idx_reservation_charge_point_id", + "columns": [ + { + "expression": "charge_point_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_reservation_status": { + "name": "idx_reservation_status", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_reservation_expiry_date": { + "name": "idx_reservation_expiry_date", + "columns": [ + { + "expression": "expiry_date", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "reservation_charge_point_id_charge_point_id_fk": { + "name": "reservation_charge_point_id_charge_point_id_fk", + "tableFrom": "reservation", + "tableTo": "charge_point", + "columnsFrom": [ + "charge_point_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "reservation_connector_id_connector_id_fk": { + "name": "reservation_connector_id_connector_id_fk", + "tableFrom": "reservation", + "tableTo": "connector", + "columnsFrom": [ + "connector_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.transaction": { + "name": "transaction", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "charge_point_id": { + "name": "charge_point_id", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "connector_id": { + "name": "connector_id", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "connector_number": { + "name": "connector_number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "id_tag": { + "name": "id_tag", + "type": "varchar(20)", + "primaryKey": false, + "notNull": true + }, + "id_tag_status": { + "name": "id_tag_status", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "start_timestamp": { + "name": "start_timestamp", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "start_meter_value": { + "name": "start_meter_value", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "stop_id_tag": { + "name": "stop_id_tag", + "type": "varchar(20)", + "primaryKey": false, + "notNull": false + }, + "stop_timestamp": { + "name": "stop_timestamp", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "stop_meter_value": { + "name": "stop_meter_value", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "stop_reason": { + "name": "stop_reason", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "charge_amount": { + "name": "charge_amount", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "electricity_fee": { + "name": "electricity_fee", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "service_fee": { + "name": "service_fee", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "reservation_id": { + "name": "reservation_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_transaction_charge_point_id": { + "name": "idx_transaction_charge_point_id", + "columns": [ + { + "expression": "charge_point_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_transaction_connector_id": { + "name": "idx_transaction_connector_id", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_transaction_id_tag": { + "name": "idx_transaction_id_tag", + "columns": [ + { + "expression": "id_tag", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_transaction_start_timestamp": { + "name": "idx_transaction_start_timestamp", + "columns": [ + { + "expression": "start_timestamp", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "transaction_charge_point_id_charge_point_id_fk": { + "name": "transaction_charge_point_id_charge_point_id_fk", + "tableFrom": "transaction", + "tableTo": "charge_point", + "columnsFrom": [ + "charge_point_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "transaction_connector_id_connector_id_fk": { + "name": "transaction_connector_id_connector_id_fk", + "tableFrom": "transaction", + "tableTo": "connector", + "columnsFrom": [ + "connector_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tariff": { + "name": "tariff", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "varchar", + "primaryKey": true, + "notNull": true + }, + "slots": { + "name": "slots", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "peak_electricity_price": { + "name": "peak_electricity_price", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "peak_service_fee": { + "name": "peak_service_fee", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "valley_electricity_price": { + "name": "valley_electricity_price", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "valley_service_fee": { + "name": "valley_service_fee", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "flat_electricity_price": { + "name": "flat_electricity_price", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "flat_service_fee": { + "name": "flat_service_fee", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "is_active": { + "name": "is_active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/apps/csms/drizzle/meta/_journal.json b/apps/csms/drizzle/meta/_journal.json index 75c7888..c1fc072 100644 --- a/apps/csms/drizzle/meta/_journal.json +++ b/apps/csms/drizzle/meta/_journal.json @@ -22,6 +22,13 @@ "when": 1773293422460, "tag": "0002_sweet_the_professor", "breakpoints": true + }, + { + "idx": 3, + "version": "7", + "when": 1773307380017, + "tag": "0003_milky_supreme_intelligence", + "breakpoints": true } ] } \ No newline at end of file diff --git a/apps/csms/src/db/ocpp-schema.ts b/apps/csms/src/db/ocpp-schema.ts index 16c5594..40aa984 100644 --- a/apps/csms/src/db/ocpp-schema.ts +++ b/apps/csms/src/db/ocpp-schema.ts @@ -69,9 +69,17 @@ export const chargePoint = pgTable('charge_point', { /** * 电价(单位:分/kWh,即 0.01 CNY/kWh) * 交易结束时按实际用电量从储值卡扣费:fee = ceil(energyWh * feePerKwh / 1000) - * 默认为 0,即不计费 + * 默认为 0,即不计费。仅在 pricingMode = 'fixed' 时生效。 */ feePerKwh: integer('fee_per_kwh').notNull().default(0), + /** + * 计费模式 + * fixed = 使用本桩固定电价 feePerKwh + * tou = 使用系统峰谷电价配置 + */ + pricingMode: varchar('pricing_mode', { enum: ['fixed', 'tou'] }) + .notNull() + .default('fixed'), createdAt: timestamp('created_at', { withTimezone: true }) .notNull() .defaultNow(), @@ -385,6 +393,15 @@ export const transaction = pgTable( * null 表示未计费(如免费充电桩或交易异常终止) */ chargeAmount: integer('charge_amount'), + /** + * 电费部分(单位:分)= 各时段(电价 × 用电量)之和 + * 注:chargeAmount = electricityFee + serviceFee + */ + electricityFee: integer('electricity_fee'), + /** + * 服务费部分(单位:分)= 各时段(服务费 × 用电量)之和 + */ + serviceFee: integer('service_fee'), /** * 关联的预约 ID(若本次充电由预约触发) * StartTransaction.req.reservationId(optional) diff --git a/apps/csms/src/db/schema.ts b/apps/csms/src/db/schema.ts index 4d88575..65ebd35 100644 --- a/apps/csms/src/db/schema.ts +++ b/apps/csms/src/db/schema.ts @@ -1,2 +1,4 @@ export * from './auth-schema.ts' export * from './ocpp-schema.ts' +export * from './tariff-schema.ts' +export * from './tariff-schema.ts' diff --git a/apps/csms/src/db/tariff-schema.ts b/apps/csms/src/db/tariff-schema.ts new file mode 100644 index 0000000..463168f --- /dev/null +++ b/apps/csms/src/db/tariff-schema.ts @@ -0,0 +1,58 @@ +import { pgTable, timestamp, varchar, integer, jsonb, boolean } from "drizzle-orm/pg-core"; + +// --------------------------------------------------------------------------- +// 峰谷电价配置 / Time-of-Use Tariff +// --------------------------------------------------------------------------- + +/** + * 时段-电价类型映射 + * "peak" 峰时 | "valley" 谷时 | "flat" 平时 + */ +export type PriceTier = "peak" | "valley" | "flat"; + +/** + * 电价时段(紧凑格式) + * start:起始小时(含,0–23) + * end:结束小时(不含,1–24) + * 示例:{ start: 8, end: 12, tier: "peak" } 表示 08:00–12:00 为峰时 + */ +export type TariffSlot = { + start: number; + end: number; + tier: PriceTier; +}; + +/** + * 峰谷电价配置表(单例,通过 isActive 标记当前生效的版本) + * + * 价格以整数"分"存储(1 分 = 0.01 CNY),精度 0.01 元/kWh: + * fen = Math.round(CNY * 100) + * CNY = fen / 100 + * + * 时段列表存储为 JSONB(TariffSlot[])。 + * 若无任何 isActive=true 的记录,计费逻辑将回退到 chargePoint.feePerKwh 平均电价。 + */ +export const tariff = pgTable("tariff", { + id: varchar("id").primaryKey(), + /** 24 小时时段列表(紧凑格式,TariffSlot[]) */ + slots: jsonb("slots").notNull().$type(), + /** 峰时电价(分/kWh) */ + peakElectricityPrice: integer("peak_electricity_price").notNull().default(0), + /** 峰时服务费(分/kWh) */ + peakServiceFee: integer("peak_service_fee").notNull().default(0), + /** 谷时电价(分/kWh) */ + valleyElectricityPrice: integer("valley_electricity_price").notNull().default(0), + /** 谷时服务费(分/kWh) */ + valleyServiceFee: integer("valley_service_fee").notNull().default(0), + /** 平时电价(分/kWh) */ + flatElectricityPrice: integer("flat_electricity_price").notNull().default(0), + /** 平时服务费(分/kWh) */ + flatServiceFee: integer("flat_service_fee").notNull().default(0), + /** 是否为当前生效配置(同时只允许一条 isActive=true) */ + isActive: boolean("is_active").notNull().default(true), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }) + .notNull() + .defaultNow() + .$onUpdate(() => new Date()), +}); diff --git a/apps/csms/src/index.ts b/apps/csms/src/index.ts index 8b0fc78..870aee0 100644 --- a/apps/csms/src/index.ts +++ b/apps/csms/src/index.ts @@ -15,6 +15,7 @@ import transactionRoutes from './routes/transactions.ts' import idTagRoutes from './routes/id-tags.ts' import userRoutes from './routes/users.ts' import setupRoutes from './routes/setup.ts' +import tariffRoutes from './routes/tariff.ts' import type { HonoEnv } from './types/hono.ts' @@ -41,7 +42,7 @@ app.use( '/api/*', cors({ origin: process.env.WEB_ORIGIN ?? '*', - allowMethods: ['GET', 'POST', 'PATCH', 'DELETE', 'OPTIONS'], + allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], allowHeaders: ['Content-Type', 'Authorization'], exposeHeaders: ['Content-Length'], credentials: true, @@ -58,6 +59,7 @@ app.route('/api/transactions', transactionRoutes) app.route('/api/id-tags', idTagRoutes) app.route('/api/users', userRoutes) app.route('/api/setup', setupRoutes) +app.route('/api/tariff', tariffRoutes) app.get('/api', (c) => { const user = c.get('user') diff --git a/apps/csms/src/ocpp/actions/stop-transaction.ts b/apps/csms/src/ocpp/actions/stop-transaction.ts index 25faf5c..ef72993 100644 --- a/apps/csms/src/ocpp/actions/stop-transaction.ts +++ b/apps/csms/src/ocpp/actions/stop-transaction.ts @@ -1,7 +1,10 @@ -import { eq, sql } from "drizzle-orm"; +import { asc, eq, sql } from "drizzle-orm"; import dayjs from "dayjs"; import { useDrizzle } from "@/lib/db.js"; import { chargePoint, connector, idTag, meterValue, transaction } from "@/db/schema.js"; +import { tariff } from "@/db/schema.js"; +import type { SampledValue } from "@/db/schema.js"; +import type { TariffSlot, PriceTier } from "@/db/tariff-schema.ts"; import type { StopTransactionRequest, StopTransactionResponse, @@ -64,20 +67,103 @@ export async function handleStopTransaction( const energyWh = payload.meterStop - tx.startMeterValue; - // Deduct balance from the idTag based on actual energy consumed + // Load active tariff and charge point fee const [cp] = await db - .select({ feePerKwh: chargePoint.feePerKwh }) + .select({ feePerKwh: chargePoint.feePerKwh, pricingMode: chargePoint.pricingMode }) .from(chargePoint) .where(eq(chargePoint.id, tx.chargePointId)) .limit(1); - const feeFen = - cp && cp.feePerKwh > 0 && energyWh > 0 ? Math.ceil((energyWh * cp.feePerKwh) / 1000) : 0; + const [activeTariff] = await db.select().from(tariff).where(eq(tariff.isActive, true)).limit(1); + + let electricityFen: number | null = null; + let serviceFeeFen: number | null = null; + let feeFen = 0; + + if (activeTariff && cp?.pricingMode === 'tou' && energyWh > 0 && tx.startTimestamp) { + const stopTs = dayjs(payload.timestamp).toDate(); + const slots = activeTariff.slots as TariffSlot[]; + + const priceMap: Record = { + peak: { + electricity: activeTariff.peakElectricityPrice, + service: activeTariff.peakServiceFee, + }, + valley: { + electricity: activeTariff.valleyElectricityPrice, + service: activeTariff.valleyServiceFee, + }, + flat: { + electricity: activeTariff.flatElectricityPrice, + service: activeTariff.flatServiceFee, + }, + }; + + // Build checkpoints from intermediate meter value readings. + // Each checkpoint is (timestamp, cumulativeWh), sorted ascending. + // Using actual intermediate readings lets each interval's known energy delta + // be assigned to its true time slot rather than assuming uniform charging rate. + const intervalReadings = await db + .select({ timestamp: meterValue.timestamp, sampledValues: meterValue.sampledValues }) + .from(meterValue) + .where(eq(meterValue.transactionId, tx.id)) + .orderBy(asc(meterValue.timestamp)); + + const checkpoints: { ts: Date; wh: number }[] = [ + { ts: tx.startTimestamp, wh: tx.startMeterValue }, + ]; + for (const mv of intervalReadings) { + const svList = mv.sampledValues as SampledValue[]; + // Per OCPP 1.6 §7.17: absent measurand defaults to Energy.Active.Import.Register + const energySv = svList.find( + (sv) => (!sv.measurand || sv.measurand === "Energy.Active.Import.Register") && !sv.phase, + ); + if (!energySv) continue; + const rawVal = parseFloat(energySv.value); + if (isNaN(rawVal)) continue; + const wh = (energySv.unit ?? "Wh") === "kWh" ? rawVal * 1000 : rawVal; + checkpoints.push({ ts: mv.timestamp, wh }); + } + checkpoints.push({ ts: stopTs, wh: payload.meterStop }); + + // For each interval, compute actual energy delta and distribute across tiers + // by walking minute-by-minute only within that interval. + const tierEnergyWh: Record = { peak: 0, valley: 0, flat: 0 }; + for (let i = 0; i + 1 < checkpoints.length; i++) { + const { ts: t1, wh: wh1 } = checkpoints[i]; + const { ts: t2, wh: wh2 } = checkpoints[i + 1]; + const deltaWh = Math.max(0, wh2 - wh1); + if (deltaWh === 0) continue; + const fractions = calcTierFractions(t1, t2, slots); + for (const tier of ["peak", "valley", "flat"] as PriceTier[]) { + tierEnergyWh[tier] += deltaWh * fractions[tier]; + } + } + + let elecFen = 0; + let svcFen = 0; + for (const tier of ["peak", "valley", "flat"] as PriceTier[]) { + const energyKwh = tierEnergyWh[tier] / 1000; + elecFen += energyKwh * priceMap[tier].electricity; + svcFen += energyKwh * priceMap[tier].service; + } + electricityFen = Math.ceil(elecFen); + serviceFeeFen = Math.ceil(svcFen); + feeFen = electricityFen + serviceFeeFen; + } else if (cp && cp.feePerKwh > 0 && energyWh > 0) { + // Fallback: flat rate per charge point + feeFen = Math.ceil((energyWh * cp.feePerKwh) / 1000); + } // Always record the charge amount (0 if free) await db .update(transaction) - .set({ chargeAmount: feeFen, updatedAt: dayjs().toDate() }) + .set({ + chargeAmount: feeFen, + electricityFee: electricityFen, + serviceFee: serviceFeeFen, + updatedAt: dayjs().toDate(), + }) .where(eq(transaction.id, tx.id)); if (feeFen > 0) { @@ -92,7 +178,8 @@ export async function handleStopTransaction( console.log( `[OCPP] StopTransaction txId=${payload.transactionId} ` + - `reason=${payload.reason ?? "none"} energyWh=${energyWh} feeFen=${feeFen}`, + `reason=${payload.reason ?? "none"} energyWh=${energyWh} ` + + `feeFen=${feeFen} (elec=${electricityFen ?? "flat"} svc=${serviceFeeFen ?? "-"})`, ); // Resolve idTagInfo for the stop tag if provided (no balance check — charging already occurred) @@ -100,3 +187,48 @@ export async function handleStopTransaction( return { idTagInfo }; } + +// ── helpers ──────────────────────────────────────────────────────────────── + +/** + * Given a charging session's start/stop timestamps and the active tariff slots, + * returns the fraction of total session duration spent in each price tier. + * Fractions sum to 1.0. + * + * Strategy: walk minute-by-minute over the session and bucket each minute into + * its tier. Using minutes keeps the implementation simple and introduces at most + * 1 minute of rounding error (negligible for billing amounts in fen). + */ +function calcTierFractions( + start: Date, + stop: Date, + slots: TariffSlot[], +): Record { + const totals: Record = { peak: 0, valley: 0, flat: 0 }; + + // Build a 24-element hour → tier lookup + const hourTier: PriceTier[] = []; + for (let i = 0; i < 24; i++) hourTier.push("flat"); + for (const slot of slots) { + for (let h = slot.start; h < slot.end; h++) { + hourTier[h] = slot.tier; + } + } + + const startMs = start.getTime(); + const stopMs = stop.getTime(); + const totalMinutes = Math.max(1, Math.round((stopMs - startMs) / 60_000)); + + for (let m = 0; m < totalMinutes; m++) { + const t = new Date(startMs + m * 60_000); + // 北京时间 = UTC + 8h,峰谷时段以北京时间为准 + const hourBeijing = Math.floor((t.getUTCHours() * 60 + t.getUTCMinutes() + 480) / 60) % 24; + totals[hourTier[hourBeijing]]++; + } + + return { + peak: totals.peak / totalMinutes, + valley: totals.valley / totalMinutes, + flat: totals.flat / totalMinutes, + }; +} diff --git a/apps/csms/src/routes/charge-points.ts b/apps/csms/src/routes/charge-points.ts index c6a26ad..7bb4534 100644 --- a/apps/csms/src/routes/charge-points.ts +++ b/apps/csms/src/routes/charge-points.ts @@ -69,6 +69,7 @@ app.post("/", async (c) => { chargePointModel?: string; registrationStatus?: "Accepted" | "Pending" | "Rejected"; feePerKwh?: number; + pricingMode?: "fixed" | "tou"; }>(); if (!body.chargePointIdentifier?.trim()) { @@ -77,6 +78,9 @@ app.post("/", async (c) => { if (body.feePerKwh !== undefined && (!Number.isInteger(body.feePerKwh) || body.feePerKwh < 0)) { return c.json({ error: "feePerKwh must be a non-negative integer" }, 400); } + if (body.pricingMode !== undefined && !['fixed', 'tou'].includes(body.pricingMode)) { + return c.json({ error: "pricingMode must be 'fixed' or 'tou'" }, 400); + } const [created] = await db .insert(chargePoint) @@ -87,6 +91,7 @@ app.post("/", async (c) => { chargePointModel: body.chargePointModel?.trim() || "Unknown", registrationStatus: body.registrationStatus ?? "Pending", feePerKwh: body.feePerKwh ?? 0, + pricingMode: body.pricingMode ?? "fixed", }) .returning() .catch((err: Error) => { @@ -125,6 +130,7 @@ app.patch("/:id", async (c) => { const id = c.req.param("id"); const body = await c.req.json<{ feePerKwh?: number; + pricingMode?: "fixed" | "tou"; registrationStatus?: string; chargePointVendor?: string; chargePointModel?: string; @@ -132,6 +138,7 @@ app.patch("/:id", async (c) => { const set: { feePerKwh?: number; + pricingMode?: "fixed" | "tou"; registrationStatus?: "Accepted" | "Pending" | "Rejected"; chargePointVendor?: string; chargePointModel?: string; @@ -152,6 +159,12 @@ app.patch("/:id", async (c) => { } if (body.chargePointVendor !== undefined) set.chargePointVendor = body.chargePointVendor.trim() || "Unknown"; if (body.chargePointModel !== undefined) set.chargePointModel = body.chargePointModel.trim() || "Unknown"; + if (body.pricingMode !== undefined) { + if (!['fixed', 'tou'].includes(body.pricingMode)) { + return c.json({ error: "pricingMode must be 'fixed' or 'tou'" }, 400); + } + set.pricingMode = body.pricingMode; + } const [updated] = await db .update(chargePoint) diff --git a/apps/csms/src/routes/tariff.ts b/apps/csms/src/routes/tariff.ts new file mode 100644 index 0000000..f63a9db --- /dev/null +++ b/apps/csms/src/routes/tariff.ts @@ -0,0 +1,98 @@ +import { Hono } from "hono"; +import { eq } from "drizzle-orm"; +import { useDrizzle } from "@/lib/db.js"; +import { tariff } from "@/db/schema.js"; +import type { HonoEnv } from "@/types/hono.ts"; +import type { PriceTier, TariffSlot } from "@/db/tariff-schema.ts"; + +const app = new Hono(); + +/** GET /api/tariff — 返回当前生效的电价配置(任何已登录用户) */ +app.get("/", async (c) => { + const db = useDrizzle(); + const [row] = await db.select().from(tariff).where(eq(tariff.isActive, true)).limit(1); + + if (!row) return c.json(null); + + return c.json(rowToPayload(row)); +}); + +/** PUT /api/tariff — 更新/初始化电价配置(仅管理员) */ +app.put("/", async (c) => { + const currentUser = c.get("user"); + if (currentUser?.role !== "admin") { + return c.json({ error: "Forbidden" }, 403); + } + + type TierPricing = { electricityPrice: number; serviceFee: number }; + type TariffBody = { + slots: TariffSlot[]; + prices: Record; + }; + + let body: TariffBody; + try { + body = await c.req.json(); + } catch { + return c.json({ error: "Invalid JSON" }, 400); + } + + const { slots, prices } = body; + if (!Array.isArray(slots) || !prices) { + return c.json({ error: "Missing slots or prices" }, 400); + } + + const db = useDrizzle(); + + // 停用旧配置 + await db.update(tariff).set({ isActive: false }); + + const [row] = await db + .insert(tariff) + .values({ + id: crypto.randomUUID(), + slots, + peakElectricityPrice: fenFromCny(prices.peak?.electricityPrice), + peakServiceFee: fenFromCny(prices.peak?.serviceFee), + valleyElectricityPrice: fenFromCny(prices.valley?.electricityPrice), + valleyServiceFee: fenFromCny(prices.valley?.serviceFee), + flatElectricityPrice: fenFromCny(prices.flat?.electricityPrice), + flatServiceFee: fenFromCny(prices.flat?.serviceFee), + isActive: true, + }) + .returning(); + + return c.json(rowToPayload(row)); +}); + +// ── helpers ──────────────────────────────────────────────────────────────── + +function fenFromCny(cny: number | undefined): number { + if (typeof cny !== "number" || isNaN(cny)) return 0; + return Math.round(cny * 100); +} + +function rowToPayload(row: typeof tariff.$inferSelect) { + return { + id: row.id, + slots: row.slots as TariffSlot[], + prices: { + peak: { + electricityPrice: row.peakElectricityPrice / 100, + serviceFee: row.peakServiceFee / 100, + }, + valley: { + electricityPrice: row.valleyElectricityPrice / 100, + serviceFee: row.valleyServiceFee / 100, + }, + flat: { + electricityPrice: row.flatElectricityPrice / 100, + serviceFee: row.flatServiceFee / 100, + }, + }, + createdAt: row.createdAt, + updatedAt: row.updatedAt, + }; +} + +export default app; diff --git a/apps/web/app/dashboard/charge-points/[id]/page.tsx b/apps/web/app/dashboard/charge-points/[id]/page.tsx index 1a21855..cc08bd8 100644 --- a/apps/web/app/dashboard/charge-points/[id]/page.tsx +++ b/apps/web/app/dashboard/charge-points/[id]/page.tsx @@ -78,6 +78,7 @@ type EditForm = { chargePointVendor: string; chargePointModel: string; registrationStatus: "Accepted" | "Pending" | "Rejected"; + pricingMode: "fixed" | "tou"; feePerKwh: string; }; @@ -96,6 +97,7 @@ export default function ChargePointDetailPage({ params }: { params: Promise<{ id chargePointVendor: "", chargePointModel: "", registrationStatus: "Pending", + pricingMode: "fixed", feePerKwh: "0", }); @@ -121,6 +123,7 @@ export default function ChargePointDetailPage({ params }: { params: Promise<{ id chargePointVendor: cp.chargePointVendor ?? "", chargePointModel: cp.chargePointModel ?? "", registrationStatus: cp.registrationStatus as EditForm["registrationStatus"], + pricingMode: cp.pricingMode, feePerKwh: String(cp.feePerKwh), }); setEditOpen(true); @@ -135,7 +138,8 @@ export default function ChargePointDetailPage({ params }: { params: Promise<{ id chargePointVendor: editForm.chargePointVendor, chargePointModel: editForm.chargePointModel, registrationStatus: editForm.registrationStatus, - feePerKwh: fee, + pricingMode: editForm.pricingMode, + feePerKwh: editForm.pricingMode === "fixed" ? fee : 0, }); await cpQuery.refetch(); setEditOpen(false); @@ -309,7 +313,9 @@ export default function ChargePointDetailPage({ params }: { params: Promise<{ id
电价
- {cp.feePerKwh > 0 ? ( + {cp.pricingMode === "tou" ? ( + 峰谷电价 + ) : cp.feePerKwh > 0 ? ( {cp.feePerKwh} 分/kWh @@ -373,7 +379,9 @@ export default function ChargePointDetailPage({ params }: { params: Promise<{ id
单位电价
- {cp.feePerKwh > 0 ? ( + {cp.pricingMode === "tou" ? ( + 峰谷电价 + ) : cp.feePerKwh > 0 ? ( ¥{(cp.feePerKwh / 100).toFixed(2)} /kWh @@ -601,8 +609,33 @@ export default function ChargePointDetailPage({ params }: { params: Promise<{ id
+
+ + +
+ {editForm.pricingMode === "fixed" && ( - + setEditForm((f) => ({ ...f, feePerKwh: e.target.value }))} /> + )} + + + ); } @@ -498,7 +497,9 @@ function ChargePageContent() { /{cp.connectors.length} 空闲 - {cp.feePerKwh > 0 ? ( + {cp.pricingMode === "tou" ? ( + 峰谷电价 + ) : cp.feePerKwh > 0 ? ( ¥{(cp.feePerKwh / 100).toFixed(2)} /kWh diff --git a/apps/web/app/dashboard/pricing/page.tsx b/apps/web/app/dashboard/pricing/page.tsx new file mode 100644 index 0000000..c4489e5 --- /dev/null +++ b/apps/web/app/dashboard/pricing/page.tsx @@ -0,0 +1,233 @@ +"use client"; + +import { useQuery } from "@tanstack/react-query"; +import { Spinner } from "@heroui/react"; +import { TagDollar, ChartLine } from "@gravity-ui/icons"; +import { api, type PriceTier, type TariffConfig, type TariffSlot } from "@/lib/api"; + +// ── Tier meta (matches admin pricing editor colors) ─────────────────────────── + +const TIER_META: Record< + PriceTier, + { label: string; sublabel: string; cellBg: string; text: string; border: string; dot: string } +> = { + peak: { + label: "峰时", + sublabel: "高峰时段", + cellBg: "bg-orange-500/70", + text: "text-orange-500", + border: "border-orange-500/40", + dot: "bg-orange-500", + }, + flat: { + label: "平时", + sublabel: "肩峰时段", + cellBg: "bg-neutral-400/45", + text: "text-neutral-400", + border: "border-neutral-400/40", + dot: "bg-neutral-400", + }, + valley: { + label: "谷时", + sublabel: "低谷时段", + cellBg: "bg-blue-500/65", + text: "text-blue-500", + border: "border-blue-500/40", + dot: "bg-blue-500", + }, +}; + +// ── Slot cards ──────────────────────────────────────────────────────────────── + +function SlotCards({ tariff }: { tariff: TariffConfig }) { + const sorted = [...tariff.slots].sort((a, b) => a.start - b.start); + return ( +
+ {sorted.map((slot: TariffSlot, i) => { + const meta = TIER_META[slot.tier]; + const p = tariff.prices[slot.tier]; + const total = p.electricityPrice + p.serviceFee; + return ( +
+ {/* Header */} +
+
+ + {meta.label} + {meta.sublabel} +
+ + {String(slot.start).padStart(2, "0")}:00 – {String(slot.end).padStart(2, "0")}:00 + +
+ {/* Prices */} +
+
+
+ 电费 + + ¥{p.electricityPrice.toFixed(4)} + /kWh + +
+
+ 服务费 + + ¥{p.serviceFee.toFixed(4)} + /kWh + +
+
+
+ 单价 + + ¥{total.toFixed(4)} + /kWh + +
+
+
+ ); + })} +
+ ); +} + +// ── Page ───────────────────────────────────────────────────────────────────── + +export default function PricingPage() { + const { + data: tariff, + isLoading, + isError, + } = useQuery({ + queryKey: ["tariff"], + queryFn: () => api.tariff.get(), + }); + + return ( +
+ {/* Header */} +
+
+ +
+
+

电价标准

+

今日实行的电价标准

+
+
+ + {isLoading && ( +
+ +
+ )} + + {isError && ( +
+ 电价信息加载失败,请刷新页面重试。 +
+ )} + + {!isLoading && !isError && !tariff && ( +
+ +

尚未配置峰谷电价

+

+ 各充电桩使用独立固定电价,请查看充电桩详情页了解具体费率。 +

+
+ )} + + {tariff && ( + <> + {/* Timeline + legend */} +
+
+
+ +
+
+

24 小时时段分布

+

实际扣费以交易完成时系统计算为准

+
+
+ +
+ {/* Tick labels */} +
+ {[0, 6, 12, 18, 24].map((h) => ( + 0 ? "translateX(-50%)" : undefined, + }} + > + {String(h).padStart(2, "0")}:00 + + ))} +
+ + {/* Colored bar */} +
+ {(() => { + const hourTier: PriceTier[] = Array(24).fill("flat" as PriceTier); + for (const slot of tariff.slots) { + for (let h = slot.start; h < slot.end; h++) hourTier[h] = slot.tier; + } + return hourTier.map((tier, h) => ( +
+ + {String(h).padStart(2, "0")} + +
+ )); + })()} +
+ + {/* Legend */} +
+ {(["peak", "flat", "valley"] as PriceTier[]).map((tier) => { + const meta = TIER_META[tier]; + const hours = tariff.slots + .filter((s) => s.tier === tier) + .reduce((acc, s) => acc + (s.end - s.start), 0); + const total = + tariff.prices[tier].electricityPrice + tariff.prices[tier].serviceFee; + return ( +
+ + + {meta.label} + + {hours}h · ¥{total.toFixed(4)}/kWh + + +
+ ); + })} +
+
+
+ + {/* Slot cards */} +
+

各时段费率

+ +

+ 合计费率 = 电费 + 服务费。实际扣费以交易完成时系统计算为准。 +

+
+ + )} +
+ ); +} diff --git a/apps/web/app/dashboard/settings/pricing/page.tsx b/apps/web/app/dashboard/settings/pricing/page.tsx index 4340eaf..c7ee6f1 100644 --- a/apps/web/app/dashboard/settings/pricing/page.tsx +++ b/apps/web/app/dashboard/settings/pricing/page.tsx @@ -1,10 +1,12 @@ "use client"; import { useState, useCallback, useEffect, useRef } from "react"; +import { useQuery, useQueryClient } from "@tanstack/react-query"; import { Button, Input, Label, Spinner, TextField, toast } from "@heroui/react"; import { TagDollar, Lock, ArrowRotateRight, ChartLine } from "@gravity-ui/icons"; // TagDollar is used in the page header badge import { useSession } from "@/lib/auth-client"; +import { api } from "@/lib/api"; // ───────────────────────────────────────────────────────────────────────────── // Types (designed for future backend API integration) @@ -155,6 +157,14 @@ const DEFAULT_PRICES: Record = { export default function PricingPage() { const { data: session } = useSession(); const isAdmin = session?.user?.role === "admin"; + const queryClient = useQueryClient(); + + // Load current tariff from API + const { data: remoteTariff, isLoading: loadingTariff } = useQuery({ + queryKey: ["tariff"], + queryFn: () => api.tariff.get(), + enabled: isAdmin, + }); const [schedule, setSchedule] = useState([...DEFAULT_SCHEDULE]); @@ -176,6 +186,26 @@ export default function PricingPage() { const [saving, setSaving] = useState(false); const [showPayload, setShowPayload] = useState(false); + // Populate state once remote tariff loads + useEffect(() => { + if (!remoteTariff) return; + // Reconstruct 24-element schedule from slots + const s: PriceTier[] = []; + for (let i = 0; i < 24; i++) s.push("flat"); + for (const slot of remoteTariff.slots) { + for (let h = slot.start; h < slot.end; h++) s[h] = slot.tier as PriceTier; + } + setSchedule(s); + const p = remoteTariff.prices as Record; + setPrices(p); + setPriceStrings({ + peak: toStrings(p.peak), + valley: toStrings(p.valley), + flat: toStrings(p.flat), + }); + setIsDirty(false); + }, [remoteTariff]); + // ── Drag state via ref (avoids stale closures in global handler) ───────── const dragRef = useRef({ active: false, @@ -239,14 +269,16 @@ export default function PricingPage() { setIsDirty(false); }; - // ── Save (stub: simulates API call) ───────────────────────────────────── + // ── Save ────────────────────────────────────────────────────────────────────── const handleSave = async () => { setSaving(true); try { - // Future: await apiFetch("/api/tariff", { method: "PUT", body: JSON.stringify(apiPayload) }) - await new Promise((r) => setTimeout(r, 700)); + await api.tariff.put({ slots, prices }); setIsDirty(false); + queryClient.invalidateQueries({ queryKey: ["tariff"] }); toast.success("电价配置已保存"); + } catch { + toast.warning("保存失败,请稍候重试"); } finally { setSaving(false); } @@ -269,6 +301,14 @@ export default function PricingPage() { ); } + if (loadingTariff) { + return ( +
+ +
+ ); + } + return (
{/* ── Page header ───────────────────────────────────────────────────── */} @@ -479,28 +519,6 @@ export default function PricingPage() {
- {/* ── API Payload preview ───────────────────────────────────────────── */} -
- - {showPayload && ( -
-
-              {JSON.stringify(apiPayload, null, 2)}
-            
-
- )} -
- {/* ── Actions ───────────────────────────────────────────────────────── */}