Resuelve conflictos al hacer merge con main
This commit is contained in:
2
.env.example
Normal file
2
.env.example
Normal file
@@ -0,0 +1,2 @@
|
||||
VITE_API_BASE_URL=domain_url
|
||||
VITE_API_TOKEN=api_token
|
||||
7
.gitignore
vendored
7
.gitignore
vendored
@@ -12,6 +12,13 @@ dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Environment variables
|
||||
.env
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
|
||||
206
src/api/concentrators.ts
Normal file
206
src/api/concentrators.ts
Normal file
@@ -0,0 +1,206 @@
|
||||
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;
|
||||
export const CONCENTRATORS_API_URL = `${API_BASE_URL}/api/v3/data/ppfu31vhv5gf6i0/mqqvi3woqdw5ziq/records`;
|
||||
const API_TOKEN = import.meta.env.VITE_API_TOKEN;
|
||||
|
||||
const getAuthHeaders = () => ({
|
||||
Authorization: `Bearer ${API_TOKEN}`,
|
||||
"Content-Type": "application/json",
|
||||
});
|
||||
|
||||
export interface ConcentratorRecord {
|
||||
id: string;
|
||||
fields: {
|
||||
"Area Name": string;
|
||||
"Device S/N": string;
|
||||
"Device Name": string;
|
||||
"Device Time": string;
|
||||
"Device Status": string;
|
||||
"Operator": string;
|
||||
"Installed Time": string;
|
||||
"Communication Time": string;
|
||||
"Instruction Manual": string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface ConcentratorsResponse {
|
||||
records: ConcentratorRecord[];
|
||||
next?: string;
|
||||
prev?: string;
|
||||
nestedNext?: string;
|
||||
nestedPrev?: string;
|
||||
}
|
||||
|
||||
export interface Concentrator {
|
||||
id: string;
|
||||
"Area Name": string;
|
||||
"Device S/N": string;
|
||||
"Device Name": string;
|
||||
"Device Time": string;
|
||||
"Device Status": string;
|
||||
"Operator": string;
|
||||
"Installed Time": string;
|
||||
"Communication Time": string;
|
||||
"Instruction Manual": string;
|
||||
}
|
||||
|
||||
export const fetchConcentrators = async (): Promise<Concentrator[]> => {
|
||||
try {
|
||||
const response = await fetch(CONCENTRATORS_API_URL, {
|
||||
method: "GET",
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to fetch concentrators");
|
||||
}
|
||||
|
||||
const data: ConcentratorsResponse = await response.json();
|
||||
|
||||
return data.records.map((r: ConcentratorRecord) => ({
|
||||
id: r.id,
|
||||
"Area Name": r.fields["Area Name"] || "",
|
||||
"Device S/N": r.fields["Device S/N"] || "",
|
||||
"Device Name": r.fields["Device Name"] || "",
|
||||
"Device Time": r.fields["Device Time"] || "",
|
||||
"Device Status": r.fields["Device Status"] || "",
|
||||
"Operator": r.fields["Operator"] || "",
|
||||
"Installed Time": r.fields["Installed Time"] || "",
|
||||
"Communication Time": r.fields["Communication Time"] || "",
|
||||
"Instruction Manual": r.fields["Instruction Manual"] || "",
|
||||
}));
|
||||
} catch (error) {
|
||||
console.error("Error fetching concentrators:", error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export const createConcentrator = async (
|
||||
concentratorData: Omit<Concentrator, "id">
|
||||
): Promise<Concentrator> => {
|
||||
try {
|
||||
const response = await fetch(CONCENTRATORS_API_URL, {
|
||||
method: "POST",
|
||||
headers: getAuthHeaders(),
|
||||
body: JSON.stringify({
|
||||
fields: {
|
||||
"Area Name": concentratorData["Area Name"],
|
||||
"Device S/N": concentratorData["Device S/N"],
|
||||
"Device Name": concentratorData["Device Name"],
|
||||
"Device Time": concentratorData["Device Time"],
|
||||
"Device Status": concentratorData["Device Status"],
|
||||
"Operator": concentratorData["Operator"],
|
||||
"Installed Time": concentratorData["Installed Time"],
|
||||
"Communication Time": concentratorData["Communication Time"],
|
||||
"Instruction Manual": concentratorData["Instruction Manual"],
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to create concentrator: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
const createdRecord = data.records?.[0];
|
||||
|
||||
if (!createdRecord) {
|
||||
throw new Error("Invalid response format: no record returned");
|
||||
}
|
||||
|
||||
return {
|
||||
id: createdRecord.id,
|
||||
"Area Name": createdRecord.fields["Area Name"] || concentratorData["Area Name"],
|
||||
"Device S/N": createdRecord.fields["Device S/N"] || concentratorData["Device S/N"],
|
||||
"Device Name": createdRecord.fields["Device Name"] || concentratorData["Device Name"],
|
||||
"Device Time": createdRecord.fields["Device Time"] || concentratorData["Device Time"],
|
||||
"Device Status": createdRecord.fields["Device Status"] || concentratorData["Device Status"],
|
||||
"Operator": createdRecord.fields["Operator"] || concentratorData["Operator"],
|
||||
"Installed Time": createdRecord.fields["Installed Time"] || concentratorData["Installed Time"],
|
||||
"Communication Time": createdRecord.fields["Communication Time"] || concentratorData["Communication Time"],
|
||||
"Instruction Manual": createdRecord.fields["Instruction Manual"] || concentratorData["Instruction Manual"],
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Error creating concentrator:", error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export const updateConcentrator = async (
|
||||
id: string,
|
||||
concentratorData: Omit<Concentrator, "id">
|
||||
): Promise<Concentrator> => {
|
||||
try {
|
||||
const response = await fetch(CONCENTRATORS_API_URL, {
|
||||
method: "PATCH",
|
||||
headers: getAuthHeaders(),
|
||||
body: JSON.stringify({
|
||||
id: id,
|
||||
fields: {
|
||||
"Area Name": concentratorData["Area Name"],
|
||||
"Device S/N": concentratorData["Device S/N"],
|
||||
"Device Name": concentratorData["Device Name"],
|
||||
"Device Time": concentratorData["Device Time"],
|
||||
"Device Status": concentratorData["Device Status"],
|
||||
"Operator": concentratorData["Operator"],
|
||||
"Installed Time": concentratorData["Installed Time"],
|
||||
"Communication Time": concentratorData["Communication Time"],
|
||||
"Instruction Manual": concentratorData["Instruction Manual"],
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.status === 400) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(`Bad Request: ${errorData.msg || "Invalid data provided"}`);
|
||||
}
|
||||
throw new Error(`Failed to update concentrator: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
const updatedRecord = data.records?.[0];
|
||||
|
||||
if (!updatedRecord) {
|
||||
throw new Error("Invalid response format: no record returned");
|
||||
}
|
||||
|
||||
return {
|
||||
id: updatedRecord.id,
|
||||
"Area Name": updatedRecord.fields["Area Name"] || concentratorData["Area Name"],
|
||||
"Device S/N": updatedRecord.fields["Device S/N"] || concentratorData["Device S/N"],
|
||||
"Device Name": updatedRecord.fields["Device Name"] || concentratorData["Device Name"],
|
||||
"Device Time": updatedRecord.fields["Device Time"] || concentratorData["Device Time"],
|
||||
"Device Status": updatedRecord.fields["Device Status"] || concentratorData["Device Status"],
|
||||
"Operator": updatedRecord.fields["Operator"] || concentratorData["Operator"],
|
||||
"Installed Time": updatedRecord.fields["Installed Time"] || concentratorData["Installed Time"],
|
||||
"Communication Time": updatedRecord.fields["Communication Time"] || concentratorData["Communication Time"],
|
||||
"Instruction Manual": updatedRecord.fields["Instruction Manual"] || concentratorData["Instruction Manual"],
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Error updating concentrator:", error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export const deleteConcentrator = async (id: string): Promise<void> => {
|
||||
try {
|
||||
const response = await fetch(CONCENTRATORS_API_URL, {
|
||||
method: "DELETE",
|
||||
headers: getAuthHeaders(),
|
||||
body: JSON.stringify({
|
||||
id: id,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.status === 400) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(`Bad Request: ${errorData.msg || "Invalid data provided"}`);
|
||||
}
|
||||
throw new Error(`Failed to delete concentrator: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error deleting concentrator:", error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
278
src/api/meters.ts
Normal file
278
src/api/meters.ts
Normal file
@@ -0,0 +1,278 @@
|
||||
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;
|
||||
export const METERS_API_URL = `${API_BASE_URL}/api/v3/data/ppfu31vhv5gf6i0/mp1izvcpok5rk6s/records`;
|
||||
const API_TOKEN = import.meta.env.VITE_API_TOKEN;
|
||||
|
||||
const getAuthHeaders = () => ({
|
||||
Authorization: `Bearer ${API_TOKEN}`,
|
||||
"Content-Type": "application/json",
|
||||
});
|
||||
|
||||
export interface MeterRecord {
|
||||
id: string;
|
||||
fields: {
|
||||
CreatedAt: string;
|
||||
UpdatedAt: string;
|
||||
"Area Name": string;
|
||||
"Account Number": string | null;
|
||||
"User Name": string | null;
|
||||
"User Address": string | null;
|
||||
"Meter S/N": string;
|
||||
"Meter Name": string;
|
||||
"Meter Status": string;
|
||||
"Protocol Type": string;
|
||||
"Price No.": string | null;
|
||||
"Price Name": string | null;
|
||||
"DMA Partition": string | null;
|
||||
"Supply Types": string;
|
||||
"Device ID": string;
|
||||
"Device Name": string;
|
||||
"Device Type": string;
|
||||
"Usage Analysis Type": string;
|
||||
"Installed Time": string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface MetersResponse {
|
||||
records: MeterRecord[];
|
||||
next?: string;
|
||||
prev?: string;
|
||||
nestedNext?: string;
|
||||
nestedPrev?: string;
|
||||
}
|
||||
|
||||
export interface Meter {
|
||||
id: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
areaName: string;
|
||||
accountNumber: string | null;
|
||||
userName: string | null;
|
||||
userAddress: string | null;
|
||||
meterSerialNumber: string;
|
||||
meterName: string;
|
||||
meterStatus: string;
|
||||
protocolType: string;
|
||||
priceNo: string | null;
|
||||
priceName: string | null;
|
||||
dmaPartition: string | null;
|
||||
supplyTypes: string;
|
||||
deviceId: string;
|
||||
deviceName: string;
|
||||
deviceType: string;
|
||||
usageAnalysisType: string;
|
||||
installedTime: string;
|
||||
}
|
||||
|
||||
export const fetchMeters = async (): Promise<Meter[]> => {
|
||||
try {
|
||||
const response = await fetch(METERS_API_URL, {
|
||||
method: "GET",
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to fetch meters");
|
||||
}
|
||||
|
||||
const data: MetersResponse = await response.json();
|
||||
const ans = data.records.map((r: MeterRecord) => ({
|
||||
id: r.id,
|
||||
createdAt: r.fields.CreatedAt || "",
|
||||
updatedAt: r.fields.UpdatedAt || "",
|
||||
areaName: r.fields["Area Name"] || "",
|
||||
accountNumber: r.fields["Account Number"] || null,
|
||||
userName: r.fields["User Name"] || null,
|
||||
userAddress: r.fields["User Address"] || null,
|
||||
meterSerialNumber: r.fields["Meter S/N"] || "",
|
||||
meterName: r.fields["Meter Name"] || "",
|
||||
meterStatus: r.fields["Meter Status"] || "",
|
||||
protocolType: r.fields["Protocol Type"] || "",
|
||||
priceNo: r.fields["Price No."] || null,
|
||||
priceName: r.fields["Price Name"] || null,
|
||||
dmaPartition: r.fields["DMA Partition"] || null,
|
||||
supplyTypes: r.fields["Supply Types"] || "",
|
||||
deviceId: r.fields["Device ID"] || "",
|
||||
deviceName: r.fields["Device Name"] || "",
|
||||
deviceType: r.fields["Device Type"] || "",
|
||||
usageAnalysisType: r.fields["Usage Analysis Type"] || "",
|
||||
installedTime: r.fields["Installed Time"] || "",
|
||||
}));
|
||||
console.log ("ans", ans);
|
||||
|
||||
return ans;
|
||||
} catch (error) {
|
||||
console.error("Error fetching meters:", error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export const createMeter = async (
|
||||
meterData: Omit<Meter, "id">
|
||||
): Promise<Meter> => {
|
||||
try {
|
||||
const response = await fetch(METERS_API_URL, {
|
||||
method: "POST",
|
||||
headers: getAuthHeaders(),
|
||||
body: JSON.stringify({
|
||||
fields: {
|
||||
CreatedAt: meterData.createdAt,
|
||||
UpdatedAt: meterData.updatedAt,
|
||||
"Area Name": meterData.areaName,
|
||||
"Account Number": meterData.accountNumber,
|
||||
"User Name": meterData.userName,
|
||||
"User Address": meterData.userAddress,
|
||||
"Meter S/N": meterData.meterSerialNumber,
|
||||
"Meter Name": meterData.meterName,
|
||||
"Meter Status": meterData.meterStatus,
|
||||
"Protocol Type": meterData.protocolType,
|
||||
"Price No.": meterData.priceNo,
|
||||
"Price Name": meterData.priceName,
|
||||
"DMA Partition": meterData.dmaPartition,
|
||||
"Supply Types": meterData.supplyTypes,
|
||||
"Device ID": meterData.deviceId,
|
||||
"Device Name": meterData.deviceName,
|
||||
"Device Type": meterData.deviceType,
|
||||
"Usage Analysis Type": meterData.usageAnalysisType,
|
||||
"Installed Time": meterData.installedTime,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to create meter: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
const createdRecord = data.records?.[0];
|
||||
|
||||
if (!createdRecord) {
|
||||
throw new Error("Invalid response format: no record returned");
|
||||
}
|
||||
|
||||
return {
|
||||
id: createdRecord.id,
|
||||
createdAt: createdRecord.fields.CreatedAt || meterData.createdAt,
|
||||
updatedAt: createdRecord.fields.UpdatedAt || meterData.updatedAt,
|
||||
areaName: createdRecord.fields["Area Name"] || meterData.areaName,
|
||||
accountNumber: createdRecord.fields["Account Number"] || meterData.accountNumber,
|
||||
userName: createdRecord.fields["User Name"] || meterData.userName,
|
||||
userAddress: createdRecord.fields["User Address"] || meterData.userAddress,
|
||||
meterSerialNumber: createdRecord.fields["Meter S/N"] || meterData.meterSerialNumber,
|
||||
meterName: createdRecord.fields["Meter Name"] || meterData.meterName,
|
||||
meterStatus: createdRecord.fields["Meter Status"] || meterData.meterStatus,
|
||||
protocolType: createdRecord.fields["Protocol Type"] || meterData.protocolType,
|
||||
priceNo: createdRecord.fields["Price No."] || meterData.priceNo,
|
||||
priceName: createdRecord.fields["Price Name"] || meterData.priceName,
|
||||
dmaPartition: createdRecord.fields["DMA Partition"] || meterData.dmaPartition,
|
||||
supplyTypes: createdRecord.fields["Supply Types"] || meterData.supplyTypes,
|
||||
deviceId: createdRecord.fields["Device ID"] || meterData.deviceId,
|
||||
deviceName: createdRecord.fields["Device Name"] || meterData.deviceName,
|
||||
deviceType: createdRecord.fields["Device Type"] || meterData.deviceType,
|
||||
usageAnalysisType: createdRecord.fields["Usage Analysis Type"] || meterData.usageAnalysisType,
|
||||
installedTime: createdRecord.fields["Installed Time"] || meterData.installedTime,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Error creating meter:", error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export const updateMeter = async (
|
||||
id: string,
|
||||
meterData: Omit<Meter, "id">
|
||||
): Promise<Meter> => {
|
||||
try {
|
||||
const response = await fetch(METERS_API_URL, {
|
||||
method: "PATCH",
|
||||
headers: getAuthHeaders(),
|
||||
body: JSON.stringify({
|
||||
id: id,
|
||||
fields: {
|
||||
CreatedAt: meterData.createdAt,
|
||||
UpdatedAt: meterData.updatedAt,
|
||||
"Area Name": meterData.areaName,
|
||||
"Account Number": meterData.accountNumber,
|
||||
"User Name": meterData.userName,
|
||||
"User Address": meterData.userAddress,
|
||||
"Meter S/N": meterData.meterSerialNumber,
|
||||
"Meter Name": meterData.meterName,
|
||||
"Meter Status": meterData.meterStatus,
|
||||
"Protocol Type": meterData.protocolType,
|
||||
"Price No.": meterData.priceNo,
|
||||
"Price Name": meterData.priceName,
|
||||
"DMA Partition": meterData.dmaPartition,
|
||||
"Supply Types": meterData.supplyTypes,
|
||||
"Device ID": meterData.deviceId,
|
||||
"Device Name": meterData.deviceName,
|
||||
"Device Type": meterData.deviceType,
|
||||
"Usage Analysis Type": meterData.usageAnalysisType,
|
||||
"Installed Time": meterData.installedTime,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.status === 400) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(`Bad Request: ${errorData.msg || "Invalid data provided"}`);
|
||||
}
|
||||
throw new Error(`Failed to update meter: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
const updatedRecord = data.records?.[0];
|
||||
|
||||
if (!updatedRecord) {
|
||||
throw new Error("Invalid response format: no record returned");
|
||||
}
|
||||
|
||||
return {
|
||||
id: updatedRecord.id,
|
||||
createdAt: updatedRecord.fields.CreatedAt || meterData.createdAt,
|
||||
updatedAt: updatedRecord.fields.UpdatedAt || meterData.updatedAt,
|
||||
areaName: updatedRecord.fields["Area Name"] || meterData.areaName,
|
||||
accountNumber: updatedRecord.fields["Account Number"] || meterData.accountNumber,
|
||||
userName: updatedRecord.fields["User Name"] || meterData.userName,
|
||||
userAddress: updatedRecord.fields["User Address"] || meterData.userAddress,
|
||||
meterSerialNumber: updatedRecord.fields["Meter S/N"] || meterData.meterSerialNumber,
|
||||
meterName: updatedRecord.fields["Meter Name"] || meterData.meterName,
|
||||
meterStatus: updatedRecord.fields["Meter Status"] || meterData.meterStatus,
|
||||
protocolType: updatedRecord.fields["Protocol Type"] || meterData.protocolType,
|
||||
priceNo: updatedRecord.fields["Price No."] || meterData.priceNo,
|
||||
priceName: updatedRecord.fields["Price Name"] || meterData.priceName,
|
||||
dmaPartition: updatedRecord.fields["DMA Partition"] || meterData.dmaPartition,
|
||||
supplyTypes: updatedRecord.fields["Supply Types"] || meterData.supplyTypes,
|
||||
deviceId: updatedRecord.fields["Device ID"] || meterData.deviceId,
|
||||
deviceName: updatedRecord.fields["Device Name"] || meterData.deviceName,
|
||||
deviceType: updatedRecord.fields["Device Type"] || meterData.deviceType,
|
||||
usageAnalysisType: updatedRecord.fields["Usage Analysis Type"] || meterData.usageAnalysisType,
|
||||
installedTime: updatedRecord.fields["Installed Time"] || meterData.installedTime,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Error updating meter:", error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export const deleteMeter = async (id: string): Promise<void> => {
|
||||
try {
|
||||
const response = await fetch(METERS_API_URL, {
|
||||
method: "DELETE",
|
||||
headers: getAuthHeaders(),
|
||||
body: JSON.stringify({
|
||||
id: id,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.status === 400) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(`Bad Request: ${errorData.msg || "Invalid data provided"}`);
|
||||
}
|
||||
throw new Error(`Failed to delete meter: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error deleting meter:", error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
253
src/api/projects.ts
Normal file
253
src/api/projects.ts
Normal file
@@ -0,0 +1,253 @@
|
||||
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;
|
||||
export const PROJECTS_API_URL = `${API_BASE_URL}/api/v3/data/ppfu31vhv5gf6i0/m05u6wpquvdbv3c/records`;
|
||||
const API_TOKEN = import.meta.env.VITE_API_TOKEN;
|
||||
|
||||
export const getAuthHeaders = () => ({
|
||||
Authorization: `Bearer ${API_TOKEN}`,
|
||||
"Content-Type": "application/json",
|
||||
});
|
||||
|
||||
export interface ProjectRecord {
|
||||
id: number;
|
||||
fields: {
|
||||
"Area name"?: string;
|
||||
"Device S/N"?: string;
|
||||
"Device Name"?: string;
|
||||
"Device Type"?: string;
|
||||
"Device Status"?: string;
|
||||
Operator?: string;
|
||||
"Installed Time"?: string;
|
||||
"Communication Time"?: string;
|
||||
"Instruction Manual"?: string | null;
|
||||
};
|
||||
}
|
||||
|
||||
export interface ProjectsResponse {
|
||||
records: ProjectRecord[];
|
||||
next?: string;
|
||||
prev?: string;
|
||||
nestedNext?: string;
|
||||
nestedPrev?: string;
|
||||
}
|
||||
|
||||
export interface Project {
|
||||
id: string;
|
||||
areaName: string;
|
||||
deviceSN: string;
|
||||
deviceName: string;
|
||||
deviceType: string;
|
||||
deviceStatus: "ACTIVE" | "INACTIVE";
|
||||
operator: string;
|
||||
installedTime: string;
|
||||
communicationTime: string;
|
||||
instructionManual: string;
|
||||
}
|
||||
|
||||
export const fetchProjectNames = async (): Promise<string[]> => {
|
||||
try {
|
||||
const response = await fetch(PROJECTS_API_URL, {
|
||||
method: "GET",
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to fetch projects");
|
||||
}
|
||||
|
||||
const data: ProjectsResponse = await response.json();
|
||||
|
||||
if (!data.records || data.records.length === 0) {
|
||||
console.warn("No project records found from API");
|
||||
return [];
|
||||
}
|
||||
|
||||
const projectNames = [
|
||||
...new Set(
|
||||
data.records
|
||||
.map((record) => record.fields["Area name"] || "")
|
||||
.filter((name) => name)
|
||||
),
|
||||
];
|
||||
|
||||
return projectNames;
|
||||
} catch (error) {
|
||||
console.error("Error fetching project names:", error);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
export const fetchProjects = async (): Promise<Project[]> => {
|
||||
try {
|
||||
const response = await fetch(PROJECTS_API_URL, {
|
||||
method: "GET",
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to fetch projects");
|
||||
}
|
||||
|
||||
const data: ProjectsResponse = await response.json();
|
||||
|
||||
return data.records.map((r: ProjectRecord) => ({
|
||||
id: r.id.toString(),
|
||||
areaName: r.fields["Area name"] ?? "",
|
||||
deviceSN: r.fields["Device S/N"] ?? "",
|
||||
deviceName: r.fields["Device Name"] ?? "",
|
||||
deviceType: r.fields["Device Type"] ?? "",
|
||||
deviceStatus:
|
||||
r.fields["Device Status"] === "Installed" ? "ACTIVE" : "INACTIVE",
|
||||
operator: r.fields["Operator"] ?? "",
|
||||
installedTime: r.fields["Installed Time"] ?? "",
|
||||
communicationTime: r.fields["Communication Time"] ?? "",
|
||||
instructionManual: r.fields["Instruction Manual"] ?? "",
|
||||
}));
|
||||
} catch (error) {
|
||||
console.error("Error fetching projects:", error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export const createProject = async (
|
||||
projectData: Omit<Project, "id">
|
||||
): Promise<Project> => {
|
||||
const response = await fetch(PROJECTS_API_URL, {
|
||||
method: "POST",
|
||||
headers: getAuthHeaders(),
|
||||
body: JSON.stringify({
|
||||
fields: {
|
||||
"Area name": projectData.areaName,
|
||||
"Device S/N": projectData.deviceSN,
|
||||
"Device Name": projectData.deviceName,
|
||||
"Device Type": projectData.deviceType,
|
||||
"Device Status":
|
||||
projectData.deviceStatus === "ACTIVE" ? "Installed" : "Inactive",
|
||||
Operator: projectData.operator,
|
||||
"Installed Time": projectData.installedTime,
|
||||
"Communication Time": projectData.communicationTime,
|
||||
"Instruction Manual": projectData.instructionManual,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
`Failed to create project: ${response.status} ${response.statusText}`
|
||||
);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
const createdRecord = data.records?.[0];
|
||||
if (!createdRecord) {
|
||||
throw new Error("Invalid response format: no record returned");
|
||||
}
|
||||
|
||||
return {
|
||||
id: createdRecord.id.toString(),
|
||||
areaName: createdRecord.fields["Area name"] ?? projectData.areaName,
|
||||
deviceSN: createdRecord.fields["Device S/N"] ?? projectData.deviceSN,
|
||||
deviceName: createdRecord.fields["Device Name"] ?? projectData.deviceName,
|
||||
deviceType: createdRecord.fields["Device Type"] ?? projectData.deviceType,
|
||||
deviceStatus:
|
||||
createdRecord.fields["Device Status"] === "Installed"
|
||||
? "ACTIVE"
|
||||
: "INACTIVE",
|
||||
operator: createdRecord.fields["Operator"] ?? projectData.operator,
|
||||
installedTime:
|
||||
createdRecord.fields["Installed Time"] ?? projectData.installedTime,
|
||||
communicationTime:
|
||||
createdRecord.fields["Communication Time"] ??
|
||||
projectData.communicationTime,
|
||||
instructionManual:
|
||||
createdRecord.fields["Instruction Manual"] ??
|
||||
projectData.instructionManual,
|
||||
};
|
||||
};
|
||||
|
||||
export const updateProject = async (
|
||||
id: string,
|
||||
projectData: Omit<Project, "id">
|
||||
): Promise<Project> => {
|
||||
const response = await fetch(PROJECTS_API_URL, {
|
||||
method: "PATCH",
|
||||
headers: getAuthHeaders(),
|
||||
body: JSON.stringify({
|
||||
id: parseInt(id),
|
||||
fields: {
|
||||
"Area name": projectData.areaName,
|
||||
"Device S/N": projectData.deviceSN,
|
||||
"Device Name": projectData.deviceName,
|
||||
"Device Type": projectData.deviceType,
|
||||
"Device Status":
|
||||
projectData.deviceStatus === "ACTIVE" ? "Installed" : "Inactive",
|
||||
Operator: projectData.operator,
|
||||
"Installed Time": projectData.installedTime,
|
||||
"Communication Time": projectData.communicationTime,
|
||||
"Instruction Manual": projectData.instructionManual,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.status === 400) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(
|
||||
`Bad Request: ${errorData.msg || "Invalid data provided"}`
|
||||
);
|
||||
}
|
||||
throw new Error(
|
||||
`Failed to update project: ${response.status} ${response.statusText}`
|
||||
);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
const updatedRecord = data.records?.[0];
|
||||
if (!updatedRecord) {
|
||||
throw new Error("Invalid response format: no record returned");
|
||||
}
|
||||
|
||||
return {
|
||||
id: updatedRecord.id.toString(),
|
||||
areaName: updatedRecord.fields["Area name"] ?? projectData.areaName,
|
||||
deviceSN: updatedRecord.fields["Device S/N"] ?? projectData.deviceSN,
|
||||
deviceName: updatedRecord.fields["Device Name"] ?? projectData.deviceName,
|
||||
deviceType: updatedRecord.fields["Device Type"] ?? projectData.deviceType,
|
||||
deviceStatus:
|
||||
updatedRecord.fields["Device Status"] === "Installed"
|
||||
? "ACTIVE"
|
||||
: "INACTIVE",
|
||||
operator: updatedRecord.fields["Operator"] ?? projectData.operator,
|
||||
installedTime:
|
||||
updatedRecord.fields["Installed Time"] ?? projectData.installedTime,
|
||||
communicationTime:
|
||||
updatedRecord.fields["Communication Time"] ??
|
||||
projectData.communicationTime,
|
||||
instructionManual:
|
||||
updatedRecord.fields["Instruction Manual"] ??
|
||||
projectData.instructionManual,
|
||||
};
|
||||
};
|
||||
|
||||
export const deleteProject = async (id: string): Promise<void> => {
|
||||
const response = await fetch(PROJECTS_API_URL, {
|
||||
method: "DELETE",
|
||||
headers: getAuthHeaders(),
|
||||
body: JSON.stringify({
|
||||
id: id,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.status === 400) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(
|
||||
`Bad Request: ${errorData.msg || "Invalid data provided"}`
|
||||
);
|
||||
}
|
||||
throw new Error(
|
||||
`Failed to delete project: ${response.status} ${response.statusText}`
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -1,20 +1,16 @@
|
||||
import { useState, useEffect, useMemo } from "react";
|
||||
import { Plus, Trash2, Pencil, RefreshCcw } from "lucide-react";
|
||||
import MaterialTable from "@material-table/core";
|
||||
import { fetchProjects, createConcentrator } from "./concentrators.api";
|
||||
import { fetchProjectNames } from "../../api/projects";
|
||||
import {
|
||||
fetchConcentrators,
|
||||
createConcentrator,
|
||||
updateConcentrator,
|
||||
deleteConcentrator,
|
||||
type Concentrator,
|
||||
} from "../../api/concentrators";
|
||||
|
||||
/* ================= TYPES ================= */
|
||||
interface Concentrator {
|
||||
"Area Name": string;
|
||||
"Device S/N": string;
|
||||
"Device Name": string;
|
||||
"Device Time": string;
|
||||
"Device Status": string;
|
||||
"Operator": string;
|
||||
"Installed Time": string;
|
||||
"Communication Time": string;
|
||||
"Instruction Manual": string;
|
||||
}
|
||||
|
||||
interface User {
|
||||
name: string;
|
||||
@@ -33,15 +29,16 @@ export default function ConcentratorsPage() {
|
||||
|
||||
const [allProjects, setAllProjects] = useState<string[]>([]);
|
||||
const [loadingProjects, setLoadingProjects] = useState(true);
|
||||
const [loadingConcentrators, setLoadingConcentrators] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
const loadProjects = async () => {
|
||||
try {
|
||||
const projects = await fetchProjects();
|
||||
const projects = await fetchProjectNames();
|
||||
setAllProjects(projects);
|
||||
} catch (error) {
|
||||
console.error('Error loading projects:', error);
|
||||
setAllProjects(["GRH (PADRE)", "CESPT", "Proyecto A", "Proyecto B"]);
|
||||
setAllProjects([]);
|
||||
} finally {
|
||||
setLoadingProjects(false);
|
||||
}
|
||||
@@ -61,6 +58,7 @@ export default function ConcentratorsPage() {
|
||||
);
|
||||
|
||||
const [selectedProject, setSelectedProject] = useState("");
|
||||
const [concentrators, setConcentrators] = useState<Concentrator[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (visibleProjects.length > 0 && !selectedProject) {
|
||||
@@ -68,41 +66,22 @@ export default function ConcentratorsPage() {
|
||||
}
|
||||
}, [visibleProjects, selectedProject]);
|
||||
|
||||
const [concentrators, setConcentrators] = useState<Concentrator[]>([
|
||||
{
|
||||
"Area Name": "GRH (PADRE)",
|
||||
"Device S/N": "SN001",
|
||||
"Device Name": "Concentrador A",
|
||||
"Device Time": "2025-12-17T10:00:00Z",
|
||||
"Device Status": "ACTIVE",
|
||||
"Operator": "Operador 1",
|
||||
"Installed Time": "2025-12-17",
|
||||
"Communication Time": "2025-12-17T10:30:00Z",
|
||||
"Instruction Manual": "Manual A",
|
||||
},
|
||||
{
|
||||
"Area Name": "CESPT",
|
||||
"Device S/N": "SN002",
|
||||
"Device Name": "Concentrador B",
|
||||
"Device Time": "2025-12-16T11:00:00Z",
|
||||
"Device Status": "INACTIVE",
|
||||
"Operator": "Operador 2",
|
||||
"Installed Time": "2025-12-16",
|
||||
"Communication Time": "2025-12-16T11:30:00Z",
|
||||
"Instruction Manual": "Manual B",
|
||||
},
|
||||
{
|
||||
"Area Name": "Proyecto A",
|
||||
"Device S/N": "SN003",
|
||||
"Device Name": "Concentrador C",
|
||||
"Device Time": "2025-12-15T12:00:00Z",
|
||||
"Device Status": "ACTIVE",
|
||||
"Operator": "Operador 3",
|
||||
"Installed Time": "2025-12-15",
|
||||
"Communication Time": "2025-12-15T12:30:00Z",
|
||||
"Instruction Manual": "Manual C",
|
||||
},
|
||||
]);
|
||||
const loadConcentrators = async () => {
|
||||
setLoadingConcentrators(true);
|
||||
try {
|
||||
const data = await fetchConcentrators();
|
||||
setConcentrators(data);
|
||||
} catch (error) {
|
||||
console.error("Error loading concentrators:", error);
|
||||
setConcentrators([]);
|
||||
} finally {
|
||||
setLoadingConcentrators(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
loadConcentrators();
|
||||
}, []);
|
||||
|
||||
const [activeConcentrator, setActiveConcentrator] = useState<Concentrator | null>(null);
|
||||
const [search, setSearch] = useState("");
|
||||
@@ -128,14 +107,20 @@ export default function ConcentratorsPage() {
|
||||
const handleSave = async () => {
|
||||
try {
|
||||
if (editingSerial) {
|
||||
const concentratorToUpdate = concentrators.find(c => c["Device S/N"] === editingSerial);
|
||||
if (!concentratorToUpdate) {
|
||||
throw new Error("Concentrator to update not found");
|
||||
}
|
||||
|
||||
const updatedConcentrator = await updateConcentrator(concentratorToUpdate.id, form);
|
||||
setConcentrators((prev) =>
|
||||
prev.map((c) =>
|
||||
c["Device S/N"] === editingSerial ? { ...form } : c
|
||||
c.id === concentratorToUpdate.id ? updatedConcentrator : c
|
||||
)
|
||||
);
|
||||
} else {
|
||||
await createConcentrator(form);
|
||||
setConcentrators((prev) => [...prev, { ...form }]);
|
||||
const newConcentrator = await createConcentrator(form);
|
||||
setConcentrators((prev) => [...prev, newConcentrator]);
|
||||
}
|
||||
setShowModal(false);
|
||||
setEditingSerial(null);
|
||||
@@ -143,20 +128,35 @@ export default function ConcentratorsPage() {
|
||||
setActiveConcentrator(null);
|
||||
} catch (error) {
|
||||
console.error('Error saving concentrator:', error);
|
||||
setConcentrators((prev) => [...prev, { ...form }]);
|
||||
setShowModal(false);
|
||||
setEditingSerial(null);
|
||||
setForm({ ...getEmptyConcentrator(), "Area Name": selectedProject });
|
||||
setActiveConcentrator(null);
|
||||
alert(
|
||||
`Error saving concentrator: ${
|
||||
error instanceof Error ? error.message : "Please try again."
|
||||
}`
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = () => {
|
||||
const handleDelete = async () => {
|
||||
if (!activeConcentrator) return;
|
||||
setConcentrators((prev) =>
|
||||
prev.filter((c) => c["Device S/N"] !== activeConcentrator["Device S/N"])
|
||||
|
||||
const confirmDelete = window.confirm(
|
||||
`Are you sure you want to delete the concentrator "${activeConcentrator["Device Name"]}"?`
|
||||
);
|
||||
setActiveConcentrator(null);
|
||||
|
||||
if (!confirmDelete) return;
|
||||
|
||||
try {
|
||||
await deleteConcentrator(activeConcentrator.id);
|
||||
setConcentrators((prev) => prev.filter((c) => c.id !== activeConcentrator.id));
|
||||
setActiveConcentrator(null);
|
||||
} catch (error) {
|
||||
console.error("Error deleting concentrator:", error);
|
||||
alert(
|
||||
`Error deleting concentrator: ${
|
||||
error instanceof Error ? error.message : "Please try again."
|
||||
}`
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
/* ================= FILTER ================= */
|
||||
@@ -180,10 +180,12 @@ export default function ConcentratorsPage() {
|
||||
value={selectedProject}
|
||||
onChange={(e) => setSelectedProject(e.target.value)}
|
||||
className="w-full border px-3 py-2 rounded"
|
||||
disabled={loadingProjects}
|
||||
disabled={loadingProjects || visibleProjects.length === 0}
|
||||
>
|
||||
{loadingProjects ? (
|
||||
<option>Loading projects...</option>
|
||||
) : visibleProjects.length === 0 ? (
|
||||
<option>No projects available</option>
|
||||
) : (
|
||||
visibleProjects.map((proj) => (
|
||||
<option key={proj} value={proj}>
|
||||
@@ -192,6 +194,12 @@ export default function ConcentratorsPage() {
|
||||
))
|
||||
)}
|
||||
</select>
|
||||
|
||||
{visibleProjects.length === 0 && !loadingProjects && (
|
||||
<p className="text-sm text-gray-500 mt-2">
|
||||
No projects available. Please contact your administrator.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* MAIN */}
|
||||
@@ -213,7 +221,8 @@ export default function ConcentratorsPage() {
|
||||
setEditingSerial(null);
|
||||
setShowModal(true);
|
||||
}}
|
||||
className="flex items-center gap-2 px-4 py-2 bg-white text-[#4c5f9e] rounded-lg"
|
||||
disabled={!selectedProject || visibleProjects.length === 0}
|
||||
className="flex items-center gap-2 px-4 py-2 bg-white text-[#4c5f9e] rounded-lg disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<Plus size={16} /> Add
|
||||
</button>
|
||||
@@ -222,7 +231,17 @@ export default function ConcentratorsPage() {
|
||||
onClick={() => {
|
||||
if (!activeConcentrator) return;
|
||||
setEditingSerial(activeConcentrator["Device S/N"]);
|
||||
setForm(activeConcentrator);
|
||||
setForm({
|
||||
"Area Name": activeConcentrator["Area Name"],
|
||||
"Device S/N": activeConcentrator["Device S/N"],
|
||||
"Device Name": activeConcentrator["Device Name"],
|
||||
"Device Time": activeConcentrator["Device Time"],
|
||||
"Device Status": activeConcentrator["Device Status"],
|
||||
"Operator": activeConcentrator["Operator"],
|
||||
"Installed Time": activeConcentrator["Installed Time"],
|
||||
"Communication Time": activeConcentrator["Communication Time"],
|
||||
"Instruction Manual": activeConcentrator["Instruction Manual"],
|
||||
});
|
||||
setShowModal(true);
|
||||
}}
|
||||
disabled={!activeConcentrator}
|
||||
@@ -240,18 +259,11 @@ export default function ConcentratorsPage() {
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => {
|
||||
setSearch("");
|
||||
setActiveConcentrator(null);
|
||||
setShowModal(false);
|
||||
setEditingSerial(null);
|
||||
setForm(getEmptyConcentrator());
|
||||
}}
|
||||
className="flex items-center gap-2 px-4 py-2 border border-white/40 rounded-lg"
|
||||
>
|
||||
<RefreshCcw size={16} /> Refresh
|
||||
</button>
|
||||
|
||||
onClick={loadConcentrators}
|
||||
className="flex items-center gap-2 px-4 py-2 border border-white/40 rounded-lg"
|
||||
>
|
||||
<RefreshCcw size={16} /> Refresh
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -266,6 +278,7 @@ export default function ConcentratorsPage() {
|
||||
{/* TABLE */}
|
||||
<MaterialTable
|
||||
title="Concentrators"
|
||||
isLoading={loadingConcentrators}
|
||||
columns={[
|
||||
{ title: "Device Name", field: "Device Name" },
|
||||
{ title: "Device S/N", field: "Device S/N" },
|
||||
@@ -297,11 +310,18 @@ export default function ConcentratorsPage() {
|
||||
sorting: true,
|
||||
rowStyle: (rowData) => ({
|
||||
backgroundColor:
|
||||
activeConcentrator?.["Device S/N"] === (rowData as Concentrator)["Device S/N"]
|
||||
activeConcentrator?.id === (rowData as Concentrator).id
|
||||
? "#EEF2FF"
|
||||
: "#FFFFFF",
|
||||
}),
|
||||
}}
|
||||
localization={{
|
||||
body: {
|
||||
emptyDataSourceMessage: loadingConcentrators
|
||||
? "Loading concentrators..."
|
||||
: "No concentrators found. Click 'Add' to create your first concentrator.",
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,132 +0,0 @@
|
||||
interface ProjectRecord {
|
||||
id: string;
|
||||
fields: {
|
||||
"Project ID": string;
|
||||
"Area name": string;
|
||||
"Device S/N": string;
|
||||
"Device Name": string;
|
||||
"Device Type": string;
|
||||
"Device Status": string;
|
||||
"Operator": string;
|
||||
"Installed Time": string;
|
||||
"Communication Time": string;
|
||||
"Instruction Manual": string;
|
||||
};
|
||||
}
|
||||
|
||||
interface ProjectsResponse {
|
||||
records: ProjectRecord[];
|
||||
next?: string;
|
||||
prev?: string;
|
||||
nestedNext?: string;
|
||||
nestedPrev?: string;
|
||||
}
|
||||
|
||||
export const createConcentrator = async (concentratorData: {
|
||||
"Area Name": string;
|
||||
"Device S/N": string;
|
||||
"Device Name": string;
|
||||
"Device Time": string;
|
||||
"Device Status": string;
|
||||
"Operator": string;
|
||||
"Installed Time": string;
|
||||
"Communication Time": string;
|
||||
"Instruction Manual": string;
|
||||
}): Promise<void> => {
|
||||
try {
|
||||
// const response = await fetch('/api/v3/data/ppfu31vhv5gf6i0/mqqvi3woqdw5ziq/records', {
|
||||
// method: 'POST',
|
||||
// headers: {
|
||||
// 'Content-Type': 'application/json',
|
||||
// },
|
||||
// body: JSON.stringify({ fields: concentratorData }),
|
||||
// });
|
||||
// if (!response.ok) {
|
||||
// throw new Error('Failed to create concentrator');
|
||||
// }
|
||||
|
||||
console.log('Creating concentrator with data:', concentratorData);
|
||||
} catch (error) {
|
||||
console.error('Error creating concentrator:', error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export const fetchProjects = async (): Promise<string[]> => {
|
||||
try {
|
||||
// const response = await fetch('/api/v3/data/ppfu31vhv5gf6i0/m05u6wpquvdbv3c/records');
|
||||
// const data: ProjectsResponse = await response.json();
|
||||
|
||||
const dummyResponse: ProjectsResponse = {
|
||||
records: [
|
||||
{
|
||||
id: "rec1",
|
||||
fields: {
|
||||
"Project ID": "1",
|
||||
"Area name": "GRH (PADRE)",
|
||||
"Device S/N": "SN001",
|
||||
"Device Name": "Device 1",
|
||||
"Device Type": "Type A",
|
||||
"Device Status": "Active",
|
||||
"Operator": "Op1",
|
||||
"Installed Time": "2023-01-01",
|
||||
"Communication Time": "2023-01-02",
|
||||
"Instruction Manual": "Manual 1"
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "rec2",
|
||||
fields: {
|
||||
"Project ID": "2",
|
||||
"Area name": "CESPT",
|
||||
"Device S/N": "SN002",
|
||||
"Device Name": "Device 2",
|
||||
"Device Type": "Type B",
|
||||
"Device Status": "Active",
|
||||
"Operator": "Op2",
|
||||
"Installed Time": "2023-01-02",
|
||||
"Communication Time": "2023-01-03",
|
||||
"Instruction Manual": "Manual 2"
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "rec3",
|
||||
fields: {
|
||||
"Project ID": "3",
|
||||
"Area name": "Proyecto A",
|
||||
"Device S/N": "SN003",
|
||||
"Device Name": "Device 3",
|
||||
"Device Type": "Type C",
|
||||
"Device Status": "Inactive",
|
||||
"Operator": "Op3",
|
||||
"Installed Time": "2023-01-03",
|
||||
"Communication Time": "2023-01-04",
|
||||
"Instruction Manual": "Manual 3"
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "rec4",
|
||||
fields: {
|
||||
"Project ID": "4",
|
||||
"Area name": "Proyecto B",
|
||||
"Device S/N": "SN004",
|
||||
"Device Name": "Device 4",
|
||||
"Device Type": "Type D",
|
||||
"Device Status": "Active",
|
||||
"Operator": "Op4",
|
||||
"Installed Time": "2023-01-04",
|
||||
"Communication Time": "2023-01-05",
|
||||
"Instruction Manual": "Manual 4"
|
||||
}
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
const projectNames = [...new Set(dummyResponse.records.map(record => record.fields["Area name"]))];
|
||||
|
||||
return projectNames;
|
||||
} catch (error) {
|
||||
console.error('Error fetching projects:', error);
|
||||
return ["GRH (PADRE)", "CESPT", "Proyecto A", "Proyecto B"];
|
||||
}
|
||||
};
|
||||
@@ -1,15 +1,16 @@
|
||||
import { useState } from "react";
|
||||
import { useState, useEffect, useMemo } from "react";
|
||||
import { Plus, Trash2, Pencil, RefreshCcw } from "lucide-react";
|
||||
import MaterialTable from "@material-table/core";
|
||||
import { fetchProjectNames } from "../../api/projects";
|
||||
import {
|
||||
fetchMeters,
|
||||
createMeter,
|
||||
updateMeter,
|
||||
deleteMeter,
|
||||
type Meter,
|
||||
} from "../../api/meters";
|
||||
|
||||
/* ================= TYPES ================= */
|
||||
export interface Meter {
|
||||
id: string; // recordId
|
||||
serialNumber: string;
|
||||
status: "ACTIVE" | "INACTIVE";
|
||||
project: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
interface User {
|
||||
name: string;
|
||||
@@ -26,47 +27,45 @@ export default function MeterManagement() {
|
||||
project: "CESPT",
|
||||
};
|
||||
|
||||
// Lista de proyectos disponibles
|
||||
const allProjects = ["GRH (PADRE)", "CESPT", "Proyecto A", "Proyecto B"];
|
||||
const [allProjects, setAllProjects] = useState<string[]>([]);
|
||||
const [loadingProjects, setLoadingProjects] = useState(true);
|
||||
|
||||
// Proyectos visibles según el usuario
|
||||
const visibleProjects =
|
||||
const visibleProjects = useMemo(() =>
|
||||
currentUser.role === "SUPER_ADMIN"
|
||||
? allProjects
|
||||
: currentUser.project
|
||||
? [currentUser.project]
|
||||
: [];
|
||||
|
||||
const [selectedProject, setSelectedProject] = useState(
|
||||
visibleProjects[0] || ""
|
||||
: [],
|
||||
[allProjects, currentUser.role, currentUser.project]
|
||||
);
|
||||
|
||||
// Datos locales iniciales (simulan la API)
|
||||
const initialMeters: Meter[] = [
|
||||
{
|
||||
id: "1",
|
||||
serialNumber: "SN001",
|
||||
status: "ACTIVE",
|
||||
project: "GRH (PADRE)",
|
||||
createdAt: "2025-12-17",
|
||||
},
|
||||
{
|
||||
id: "2",
|
||||
serialNumber: "SN002",
|
||||
status: "INACTIVE",
|
||||
project: "CESPT",
|
||||
createdAt: "2025-12-16",
|
||||
},
|
||||
{
|
||||
id: "3",
|
||||
serialNumber: "SN003",
|
||||
status: "ACTIVE",
|
||||
project: "Proyecto A",
|
||||
createdAt: "2025-12-15",
|
||||
},
|
||||
];
|
||||
const [selectedProject, setSelectedProject] = useState("");
|
||||
|
||||
const [meters, setMeters] = useState<Meter[]>(initialMeters);
|
||||
useEffect(() => {
|
||||
const loadProjects = async () => {
|
||||
try {
|
||||
const projects = await fetchProjectNames();
|
||||
setAllProjects(projects);
|
||||
} catch (error) {
|
||||
console.error('Error loading projects:', error);
|
||||
setAllProjects([]);
|
||||
} finally {
|
||||
setLoadingProjects(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadProjects();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (visibleProjects.length > 0 && !selectedProject) {
|
||||
setSelectedProject(visibleProjects[0]);
|
||||
}
|
||||
}, [visibleProjects, selectedProject]);
|
||||
|
||||
const [meters, setMeters] = useState<Meter[]>([]);
|
||||
const [loadingMeters, setLoadingMeters] = useState(true);
|
||||
const [activeMeter, setActiveMeter] = useState<Meter | null>(null);
|
||||
const [search, setSearch] = useState("");
|
||||
|
||||
@@ -74,54 +73,113 @@ export default function MeterManagement() {
|
||||
const [editingId, setEditingId] = useState<string | null>(null);
|
||||
|
||||
const emptyMeter: Omit<Meter, "id"> = {
|
||||
serialNumber: "",
|
||||
status: "ACTIVE",
|
||||
project: selectedProject,
|
||||
createdAt: new Date().toISOString().slice(0, 10),
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
areaName: "",
|
||||
accountNumber: null,
|
||||
userName: null,
|
||||
userAddress: null,
|
||||
meterSerialNumber: "",
|
||||
meterName: "",
|
||||
meterStatus: "Installed",
|
||||
protocolType: "",
|
||||
priceNo: null,
|
||||
priceName: null,
|
||||
dmaPartition: null,
|
||||
supplyTypes: "",
|
||||
deviceId: "",
|
||||
deviceName: "",
|
||||
deviceType: "",
|
||||
usageAnalysisType: "",
|
||||
installedTime: new Date().toISOString(),
|
||||
};
|
||||
|
||||
const [form, setForm] = useState<Omit<Meter, "id">>(emptyMeter);
|
||||
|
||||
/* ================= CRUD LOCAL ================= */
|
||||
const handleSave = () => {
|
||||
if (editingId) {
|
||||
setMeters((prev) =>
|
||||
prev.map((m) =>
|
||||
m.id === editingId ? { ...m, ...form } : m
|
||||
)
|
||||
);
|
||||
} else {
|
||||
const newMeter: Meter = {
|
||||
id: (Math.random() * 1000000).toFixed(0),
|
||||
...form,
|
||||
};
|
||||
setMeters((prev) => [...prev, newMeter]);
|
||||
const loadMeters = async () => {
|
||||
setLoadingMeters(true);
|
||||
try {
|
||||
const data = await fetchMeters();
|
||||
setMeters(data);
|
||||
} catch (error) {
|
||||
console.error("Error loading meters:", error);
|
||||
setMeters([]);
|
||||
} finally {
|
||||
setLoadingMeters(false);
|
||||
}
|
||||
|
||||
setShowModal(false);
|
||||
setEditingId(null);
|
||||
setForm({ ...emptyMeter, project: selectedProject });
|
||||
setActiveMeter(null);
|
||||
};
|
||||
|
||||
const handleDelete = () => {
|
||||
useEffect(() => {
|
||||
loadMeters();
|
||||
}, []);
|
||||
|
||||
const handleSave = async () => {
|
||||
try {
|
||||
if (editingId) {
|
||||
const meterToUpdate = meters.find(m => m.id === editingId);
|
||||
if (!meterToUpdate) {
|
||||
throw new Error("Meter to update not found");
|
||||
}
|
||||
|
||||
const updatedMeter = await updateMeter(editingId, form);
|
||||
setMeters((prev) =>
|
||||
prev.map((m) =>
|
||||
m.id === editingId ? updatedMeter : m
|
||||
)
|
||||
);
|
||||
} else {
|
||||
const newMeter = await createMeter(form);
|
||||
setMeters((prev) => [...prev, newMeter]);
|
||||
}
|
||||
setShowModal(false);
|
||||
setEditingId(null);
|
||||
setForm(emptyMeter);
|
||||
setActiveMeter(null);
|
||||
} catch (error) {
|
||||
console.error('Error saving meter:', error);
|
||||
alert(
|
||||
`Error saving meter: ${
|
||||
error instanceof Error ? error.message : "Please try again."
|
||||
}`
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!activeMeter) return;
|
||||
setMeters((prev) => prev.filter((m) => m.id !== activeMeter.id));
|
||||
setActiveMeter(null);
|
||||
|
||||
const confirmDelete = window.confirm(
|
||||
`Are you sure you want to delete the meter "${activeMeter.meterName}" (${activeMeter.meterSerialNumber})?`
|
||||
);
|
||||
|
||||
if (!confirmDelete) return;
|
||||
|
||||
try {
|
||||
await deleteMeter(activeMeter.id);
|
||||
setMeters((prev) => prev.filter((m) => m.id !== activeMeter.id));
|
||||
setActiveMeter(null);
|
||||
} catch (error) {
|
||||
console.error("Error deleting meter:", error);
|
||||
alert(
|
||||
`Error deleting meter: ${
|
||||
error instanceof Error ? error.message : "Please try again."
|
||||
}`
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRefresh = () => {
|
||||
// Simula recargar los datos originales
|
||||
setMeters(initialMeters);
|
||||
loadMeters();
|
||||
setActiveMeter(null);
|
||||
};
|
||||
|
||||
/* ================= FILTER ================= */
|
||||
const filtered = meters.filter(
|
||||
(m) =>
|
||||
(m.serialNumber.toLowerCase().includes(search.toLowerCase()) ||
|
||||
m.project.toLowerCase().includes(search.toLowerCase())) &&
|
||||
m.project === selectedProject
|
||||
(m.meterName.toLowerCase().includes(search.toLowerCase()) ||
|
||||
m.meterSerialNumber.toLowerCase().includes(search.toLowerCase()) ||
|
||||
m.deviceId.toLowerCase().includes(search.toLowerCase()) ||
|
||||
m.areaName.toLowerCase().includes(search.toLowerCase()))
|
||||
);
|
||||
|
||||
/* ================= UI ================= */
|
||||
@@ -137,13 +195,26 @@ export default function MeterManagement() {
|
||||
value={selectedProject}
|
||||
onChange={(e) => setSelectedProject(e.target.value)}
|
||||
className="w-full border px-3 py-2 rounded"
|
||||
disabled={loadingProjects || visibleProjects.length === 0}
|
||||
>
|
||||
{visibleProjects.map((proj) => (
|
||||
<option key={proj} value={proj}>
|
||||
{proj}
|
||||
</option>
|
||||
))}
|
||||
{loadingProjects ? (
|
||||
<option>Loading projects...</option>
|
||||
) : visibleProjects.length === 0 ? (
|
||||
<option>No projects available</option>
|
||||
) : (
|
||||
visibleProjects.map((proj) => (
|
||||
<option key={proj} value={proj}>
|
||||
{proj}
|
||||
</option>
|
||||
))
|
||||
)}
|
||||
</select>
|
||||
|
||||
{visibleProjects.length === 0 && !loadingProjects && (
|
||||
<p className="text-sm text-gray-500 mt-2">
|
||||
No projects available. Please contact your administrator.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* MAIN */}
|
||||
@@ -164,11 +235,12 @@ export default function MeterManagement() {
|
||||
<div className="flex gap-3">
|
||||
<button
|
||||
onClick={() => {
|
||||
setForm({ ...emptyMeter, project: selectedProject });
|
||||
setForm(emptyMeter);
|
||||
setEditingId(null);
|
||||
setShowModal(true);
|
||||
}}
|
||||
className="flex items-center gap-2 px-4 py-2 bg-white text-[#4c5f9e] rounded-lg"
|
||||
disabled={!selectedProject || visibleProjects.length === 0}
|
||||
className="flex items-center gap-2 px-4 py-2 bg-white text-[#4c5f9e] rounded-lg disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<Plus size={16} /> Add
|
||||
</button>
|
||||
@@ -177,7 +249,27 @@ export default function MeterManagement() {
|
||||
onClick={() => {
|
||||
if (!activeMeter) return;
|
||||
setEditingId(activeMeter.id);
|
||||
setForm({ ...activeMeter });
|
||||
setForm({
|
||||
createdAt: activeMeter.createdAt,
|
||||
updatedAt: activeMeter.updatedAt,
|
||||
areaName: activeMeter.areaName,
|
||||
accountNumber: activeMeter.accountNumber,
|
||||
userName: activeMeter.userName,
|
||||
userAddress: activeMeter.userAddress,
|
||||
meterSerialNumber: activeMeter.meterSerialNumber,
|
||||
meterName: activeMeter.meterName,
|
||||
meterStatus: activeMeter.meterStatus,
|
||||
protocolType: activeMeter.protocolType,
|
||||
priceNo: activeMeter.priceNo,
|
||||
priceName: activeMeter.priceName,
|
||||
dmaPartition: activeMeter.dmaPartition,
|
||||
supplyTypes: activeMeter.supplyTypes,
|
||||
deviceId: activeMeter.deviceId,
|
||||
deviceName: activeMeter.deviceName,
|
||||
deviceType: activeMeter.deviceType,
|
||||
usageAnalysisType: activeMeter.usageAnalysisType,
|
||||
installedTime: activeMeter.installedTime,
|
||||
});
|
||||
setShowModal(true);
|
||||
}}
|
||||
disabled={!activeMeter}
|
||||
@@ -206,7 +298,7 @@ export default function MeterManagement() {
|
||||
{/* SEARCH */}
|
||||
<input
|
||||
className="bg-white rounded-lg shadow px-4 py-2 text-sm"
|
||||
placeholder="Search meter..."
|
||||
placeholder="Search by meter name, serial number, device ID, or area..."
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
/>
|
||||
@@ -214,25 +306,32 @@ export default function MeterManagement() {
|
||||
{/* TABLE */}
|
||||
<MaterialTable
|
||||
title="Meters"
|
||||
isLoading={loadingMeters}
|
||||
columns={[
|
||||
{ title: "Serial", field: "serialNumber" },
|
||||
{ title: "Meter Name", field: "meterName" },
|
||||
{ title: "Serial Number", field: "meterSerialNumber" },
|
||||
{ title: "Area", field: "areaName" },
|
||||
{ title: "Device ID", field: "deviceId" },
|
||||
{ title: "Device Name", field: "deviceName" },
|
||||
{
|
||||
title: "Status",
|
||||
field: "status",
|
||||
field: "meterStatus",
|
||||
render: (rowData) => (
|
||||
<span
|
||||
className={`px-3 py-1 rounded-full text-xs font-semibold border ${
|
||||
rowData.status === "ACTIVE"
|
||||
? "text-blue-600 border-blue-600"
|
||||
: "text-red-600 border-red-600"
|
||||
rowData.meterStatus === "Installed"
|
||||
? "text-green-600 border-green-600"
|
||||
: "text-gray-600 border-gray-600"
|
||||
}`}
|
||||
>
|
||||
{rowData.status}
|
||||
{rowData.meterStatus}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{ title: "Project", field: "project" },
|
||||
{ title: "Created", field: "createdAt", type: "date" },
|
||||
{ title: "Protocol", field: "protocolType" },
|
||||
{ title: "Device Type", field: "deviceType" },
|
||||
{ title: "Created At", field: "createdAt", type: "datetime" },
|
||||
{ title: "Updated At", field: "updatedAt", type: "datetime" },
|
||||
]}
|
||||
data={filtered}
|
||||
onRowClick={(_, rowData) => setActiveMeter(rowData as Meter)}
|
||||
@@ -248,55 +347,196 @@ export default function MeterManagement() {
|
||||
: "#FFFFFF",
|
||||
}),
|
||||
}}
|
||||
localization={{
|
||||
body: {
|
||||
emptyDataSourceMessage: loadingMeters
|
||||
? "Loading meters..."
|
||||
: "No meters found. Click 'Add' to create your first meter.",
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* MODAL */}
|
||||
{showModal && (
|
||||
<div className="fixed inset-0 bg-black/40 flex items-center justify-center">
|
||||
<div className="bg-white rounded-xl p-6 w-96 space-y-3">
|
||||
<div className="bg-white rounded-xl p-6 w-96 max-h-[80vh] overflow-y-auto space-y-3">
|
||||
<h2 className="text-lg font-semibold">
|
||||
{editingId ? "Edit Meter" : "Add Meter"}
|
||||
</h2>
|
||||
|
||||
<input
|
||||
className="w-full border px-3 py-2 rounded"
|
||||
placeholder="Serial Number"
|
||||
value={form.serialNumber}
|
||||
onChange={(e) =>
|
||||
setForm({ ...form, serialNumber: e.target.value })
|
||||
}
|
||||
/>
|
||||
<div className="space-y-1">
|
||||
<label className="block text-sm font-medium text-gray-700">Meter Name</label>
|
||||
<input
|
||||
className="w-full border px-3 py-2 rounded"
|
||||
placeholder="Meter Name"
|
||||
value={form.meterName}
|
||||
onChange={(e) => setForm({ ...form, meterName: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={() =>
|
||||
setForm({
|
||||
...form,
|
||||
status: form.status === "ACTIVE" ? "INACTIVE" : "ACTIVE",
|
||||
})
|
||||
}
|
||||
className="w-full border rounded px-3 py-2"
|
||||
>
|
||||
Status: {form.status}
|
||||
</button>
|
||||
<div className="space-y-1">
|
||||
<label className="block text-sm font-medium text-gray-700">Meter Serial Number</label>
|
||||
<input
|
||||
className="w-full border px-3 py-2 rounded"
|
||||
placeholder="Meter S/N"
|
||||
value={form.meterSerialNumber}
|
||||
onChange={(e) => setForm({ ...form, meterSerialNumber: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<input
|
||||
className="w-full border px-3 py-2 rounded"
|
||||
placeholder="Project"
|
||||
value={form.project}
|
||||
onChange={(e) =>
|
||||
setForm({ ...form, project: e.target.value })
|
||||
}
|
||||
/>
|
||||
<div className="space-y-1">
|
||||
<label className="block text-sm font-medium text-gray-700">Area Name</label>
|
||||
<input
|
||||
className="w-full border px-3 py-2 rounded"
|
||||
placeholder="Area Name"
|
||||
value={form.areaName}
|
||||
onChange={(e) => setForm({ ...form, areaName: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<input
|
||||
type="date"
|
||||
className="w-full border px-3 py-2 rounded"
|
||||
value={form.createdAt}
|
||||
onChange={(e) =>
|
||||
setForm({ ...form, createdAt: e.target.value })
|
||||
}
|
||||
/>
|
||||
<div className="space-y-1">
|
||||
<label className="block text-sm font-medium text-gray-700">Device ID</label>
|
||||
<input
|
||||
className="w-full border px-3 py-2 rounded"
|
||||
placeholder="Device ID"
|
||||
value={form.deviceId}
|
||||
onChange={(e) => setForm({ ...form, deviceId: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<label className="block text-sm font-medium text-gray-700">Device Name</label>
|
||||
<input
|
||||
className="w-full border px-3 py-2 rounded"
|
||||
placeholder="Device Name"
|
||||
value={form.deviceName}
|
||||
onChange={(e) => setForm({ ...form, deviceName: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<label className="block text-sm font-medium text-gray-700">Device Type</label>
|
||||
<input
|
||||
className="w-full border px-3 py-2 rounded"
|
||||
placeholder="Device Type"
|
||||
value={form.deviceType}
|
||||
onChange={(e) => setForm({ ...form, deviceType: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<label className="block text-sm font-medium text-gray-700">Meter Status</label>
|
||||
<select
|
||||
className="w-full border px-3 py-2 rounded"
|
||||
value={form.meterStatus}
|
||||
onChange={(e) => setForm({ ...form, meterStatus: e.target.value })}
|
||||
>
|
||||
<option value="Installed">Installed</option>
|
||||
<option value="Uninstalled">Uninstalled</option>
|
||||
<option value="Maintenance">Maintenance</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<label className="block text-sm font-medium text-gray-700">Protocol Type</label>
|
||||
<input
|
||||
className="w-full border px-3 py-2 rounded"
|
||||
placeholder="Protocol Type"
|
||||
value={form.protocolType}
|
||||
onChange={(e) => setForm({ ...form, protocolType: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<label className="block text-sm font-medium text-gray-700">Supply Types</label>
|
||||
<input
|
||||
className="w-full border px-3 py-2 rounded"
|
||||
placeholder="Supply Types"
|
||||
value={form.supplyTypes}
|
||||
onChange={(e) => setForm({ ...form, supplyTypes: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<label className="block text-sm font-medium text-gray-700">Usage Analysis Type</label>
|
||||
<input
|
||||
className="w-full border px-3 py-2 rounded"
|
||||
placeholder="Usage Analysis Type"
|
||||
value={form.usageAnalysisType}
|
||||
onChange={(e) => setForm({ ...form, usageAnalysisType: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<label className="block text-sm font-medium text-gray-700">Account Number</label>
|
||||
<input
|
||||
className="w-full border px-3 py-2 rounded"
|
||||
placeholder="Account Number (optional)"
|
||||
value={form.accountNumber || ""}
|
||||
onChange={(e) => setForm({ ...form, accountNumber: e.target.value || null })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<label className="block text-sm font-medium text-gray-700">User Name</label>
|
||||
<input
|
||||
className="w-full border px-3 py-2 rounded"
|
||||
placeholder="User Name (optional)"
|
||||
value={form.userName || ""}
|
||||
onChange={(e) => setForm({ ...form, userName: e.target.value || null })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<label className="block text-sm font-medium text-gray-700">User Address</label>
|
||||
<input
|
||||
className="w-full border px-3 py-2 rounded"
|
||||
placeholder="User Address (optional)"
|
||||
value={form.userAddress || ""}
|
||||
onChange={(e) => setForm({ ...form, userAddress: e.target.value || null })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<label className="block text-sm font-medium text-gray-700">Price No.</label>
|
||||
<input
|
||||
className="w-full border px-3 py-2 rounded"
|
||||
placeholder="Price No. (optional)"
|
||||
value={form.priceNo || ""}
|
||||
onChange={(e) => setForm({ ...form, priceNo: e.target.value || null })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<label className="block text-sm font-medium text-gray-700">Price Name</label>
|
||||
<input
|
||||
className="w-full border px-3 py-2 rounded"
|
||||
placeholder="Price Name (optional)"
|
||||
value={form.priceName || ""}
|
||||
onChange={(e) => setForm({ ...form, priceName: e.target.value || null })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<label className="block text-sm font-medium text-gray-700">DMA Partition</label>
|
||||
<input
|
||||
className="w-full border px-3 py-2 rounded"
|
||||
placeholder="DMA Partition (optional)"
|
||||
value={form.dmaPartition || ""}
|
||||
onChange={(e) => setForm({ ...form, dmaPartition: e.target.value || null })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<label className="block text-sm font-medium text-gray-700">Installed Time</label>
|
||||
<input
|
||||
type="datetime-local"
|
||||
className="w-full border px-3 py-2 rounded"
|
||||
value={form.installedTime ? new Date(form.installedTime).toISOString().slice(0, 16) : ""}
|
||||
onChange={(e) => setForm({ ...form, installedTime: new Date(e.target.value).toISOString() })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-2 pt-3">
|
||||
<button onClick={() => setShowModal(false)}>Cancel</button>
|
||||
|
||||
@@ -1,95 +1,23 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Plus, Trash2, Pencil, RefreshCcw } from "lucide-react";
|
||||
import MaterialTable from "@material-table/core";
|
||||
|
||||
/* ================= TYPES ================= */
|
||||
interface Project {
|
||||
id: string;
|
||||
areaName: string;
|
||||
deviceSN: string;
|
||||
deviceName: string;
|
||||
deviceType: string;
|
||||
deviceStatus: "ACTIVE" | "INACTIVE";
|
||||
operator: string;
|
||||
installedTime: string;
|
||||
communicationTime: string;
|
||||
instructionManual: string;
|
||||
}
|
||||
|
||||
/* ================= MOCK DATA ================= */
|
||||
const mockProjects: Project[] = [
|
||||
{
|
||||
id: "1",
|
||||
areaName: "Zona Norte",
|
||||
deviceSN: "SN-001",
|
||||
deviceName: "Sensor Alpha",
|
||||
deviceType: "Flow Meter",
|
||||
deviceStatus: "ACTIVE",
|
||||
operator: "Juan Pérez",
|
||||
installedTime: "2024-01-10",
|
||||
communicationTime: "2024-01-11",
|
||||
instructionManual: "Manual Alpha",
|
||||
},
|
||||
{
|
||||
id: "2",
|
||||
areaName: "Zona Centro",
|
||||
deviceSN: "SN-002",
|
||||
deviceName: "Sensor Beta",
|
||||
deviceType: "Pressure Meter",
|
||||
deviceStatus: "INACTIVE",
|
||||
operator: "María López",
|
||||
installedTime: "2024-02-05",
|
||||
communicationTime: "2024-02-06",
|
||||
instructionManual: "Manual Beta",
|
||||
},
|
||||
{
|
||||
id: "3",
|
||||
areaName: "Zona Sur",
|
||||
deviceSN: "SN-003",
|
||||
deviceName: "Sensor Gamma",
|
||||
deviceType: "Flow Meter",
|
||||
deviceStatus: "ACTIVE",
|
||||
operator: "Carlos Ruiz",
|
||||
installedTime: "2024-03-01",
|
||||
communicationTime: "2024-03-02",
|
||||
instructionManual: "Manual Gamma",
|
||||
},
|
||||
];
|
||||
|
||||
/* ================= API ================= */
|
||||
const API_URL = "/api/v2/tables/m05u6wpquvdbv3c/records";
|
||||
|
||||
const fetchProjects = async (): Promise<Project[]> => {
|
||||
const res = await fetch(API_URL);
|
||||
const data = await res.json();
|
||||
|
||||
return data.records.map((r: any) => ({
|
||||
id: r.id,
|
||||
areaName: r.fields["Area Name"] ?? "",
|
||||
deviceSN: r.fields["Device S/N"] ?? "",
|
||||
deviceName: r.fields["Device Name"] ?? "",
|
||||
deviceType: r.fields["Device Type"] ?? "",
|
||||
deviceStatus:
|
||||
r.fields["Device Status"] === "INACTIVE"
|
||||
? "INACTIVE"
|
||||
: "ACTIVE",
|
||||
operator: r.fields["Operator"] ?? "",
|
||||
installedTime: r.fields["Installed Time"] ?? "",
|
||||
communicationTime: r.fields["Communication Time"] ?? "",
|
||||
instructionManual: r.fields["Instruction Manual"] ?? "",
|
||||
}));
|
||||
};
|
||||
import {
|
||||
Project,
|
||||
fetchProjects,
|
||||
createProject as apiCreateProject,
|
||||
updateProject as apiUpdateProject,
|
||||
deleteProject as apiDeleteProject,
|
||||
} from "../../api/projects";
|
||||
|
||||
/* ================= COMPONENT ================= */
|
||||
export default function ProjectsPage() {
|
||||
const [projects, setProjects] = useState<Project[]>([]);
|
||||
const [activeProject, setActiveProject] =
|
||||
useState<Project | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [activeProject, setActiveProject] = useState<Project | null>(null);
|
||||
const [search, setSearch] = useState("");
|
||||
|
||||
const [showModal, setShowModal] = useState(false);
|
||||
const [editingId, setEditingId] =
|
||||
useState<string | null>(null);
|
||||
const [editingId, setEditingId] = useState<string | null>(null);
|
||||
|
||||
const emptyProject: Omit<Project, "id"> = {
|
||||
areaName: "",
|
||||
@@ -103,20 +31,19 @@ export default function ProjectsPage() {
|
||||
instructionManual: "",
|
||||
};
|
||||
|
||||
const [form, setForm] =
|
||||
useState<Omit<Project, "id">>(emptyProject);
|
||||
const [form, setForm] = useState<Omit<Project, "id">>(emptyProject);
|
||||
|
||||
/* ================= LOAD ================= */
|
||||
const loadProjects = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const data = await fetchProjects();
|
||||
if (data.length === 0) {
|
||||
setProjects(mockProjects);
|
||||
} else {
|
||||
setProjects(data);
|
||||
}
|
||||
} catch {
|
||||
setProjects(mockProjects);
|
||||
setProjects(data);
|
||||
} catch (error) {
|
||||
console.error("Error loading projects:", error);
|
||||
setProjects([]);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -124,37 +51,54 @@ export default function ProjectsPage() {
|
||||
loadProjects();
|
||||
}, []);
|
||||
|
||||
/* ================= CRUD ================= */
|
||||
const handleSave = () => {
|
||||
if (editingId) {
|
||||
setProjects((prev) =>
|
||||
prev.map((p) =>
|
||||
p.id === editingId
|
||||
? { ...p, ...form }
|
||||
: p
|
||||
)
|
||||
);
|
||||
} else {
|
||||
setProjects((prev) => [
|
||||
...prev,
|
||||
{ id: Date.now().toString(), ...form },
|
||||
]);
|
||||
}
|
||||
|
||||
setShowModal(false);
|
||||
setEditingId(null);
|
||||
setForm(emptyProject);
|
||||
setActiveProject(null);
|
||||
const handleSave = async () => {
|
||||
try {
|
||||
if (editingId) {
|
||||
const updatedProject = await apiUpdateProject(editingId, form);
|
||||
setProjects((prev) =>
|
||||
prev.map((p) => (p.id === editingId ? updatedProject : p))
|
||||
);
|
||||
} else {
|
||||
const newProject = await apiCreateProject(form);
|
||||
setProjects((prev) => [...prev, newProject]);
|
||||
}
|
||||
|
||||
setShowModal(false);
|
||||
setEditingId(null);
|
||||
setForm(emptyProject);
|
||||
setActiveProject(null);
|
||||
} catch (error) {
|
||||
console.error("Error saving project:", error);
|
||||
alert(
|
||||
`Error saving project: ${
|
||||
error instanceof Error ? error.message : "Please try again."
|
||||
}`
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = () => {
|
||||
const handleDelete = async () => {
|
||||
if (!activeProject) return;
|
||||
setProjects((prev) =>
|
||||
prev.filter(
|
||||
(p) => p.id !== activeProject.id
|
||||
)
|
||||
|
||||
const confirmDelete = window.confirm(
|
||||
`Are you sure you want to delete the project "${activeProject.deviceName}"?`
|
||||
);
|
||||
setActiveProject(null);
|
||||
|
||||
if (!confirmDelete) return;
|
||||
|
||||
try {
|
||||
await apiDeleteProject(activeProject.id);
|
||||
setProjects((prev) => prev.filter((p) => p.id !== activeProject.id));
|
||||
setActiveProject(null);
|
||||
} catch (error) {
|
||||
console.error("Error deleting project:", error);
|
||||
alert(
|
||||
`Error deleting project: ${
|
||||
error instanceof Error ? error.message : "Please try again."
|
||||
}`
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
/* ================= FILTER ================= */
|
||||
@@ -172,17 +116,12 @@ export default function ProjectsPage() {
|
||||
<div
|
||||
className="rounded-xl shadow p-6 text-white flex justify-between items-center"
|
||||
style={{
|
||||
background:
|
||||
"linear-gradient(135deg, #4c5f9e, #2a355d, #566bb8)",
|
||||
background: "linear-gradient(135deg, #4c5f9e, #2a355d, #566bb8)",
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">
|
||||
Project Management
|
||||
</h1>
|
||||
<p className="text-sm text-blue-100">
|
||||
Projects registered
|
||||
</p>
|
||||
<h1 className="text-2xl font-bold">Project Management</h1>
|
||||
<p className="text-sm text-blue-100">Projects registered</p>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-3">
|
||||
@@ -248,6 +187,7 @@ export default function ProjectsPage() {
|
||||
{/* TABLE */}
|
||||
<MaterialTable
|
||||
title="Projects"
|
||||
isLoading={loading}
|
||||
columns={[
|
||||
{ title: "Area Name", field: "areaName" },
|
||||
{ title: "Device S/N", field: "deviceSN" },
|
||||
@@ -274,21 +214,25 @@ export default function ProjectsPage() {
|
||||
{ title: "Instruction Manual", field: "instructionManual" },
|
||||
]}
|
||||
data={filtered}
|
||||
onRowClick={(_, rowData) =>
|
||||
setActiveProject(rowData as Project)
|
||||
}
|
||||
onRowClick={(_, rowData) => setActiveProject(rowData as Project)}
|
||||
options={{
|
||||
search: false,
|
||||
paging: true,
|
||||
sorting: true,
|
||||
rowStyle: (rowData) => ({
|
||||
backgroundColor:
|
||||
activeProject?.id ===
|
||||
(rowData as Project).id
|
||||
activeProject?.id === (rowData as Project).id
|
||||
? "#EEF2FF"
|
||||
: "#FFFFFF",
|
||||
}),
|
||||
}}
|
||||
localization={{
|
||||
body: {
|
||||
emptyDataSourceMessage: loading
|
||||
? "Loading projects..."
|
||||
: "No projects found. Click 'Add' to create your first project.",
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -300,46 +244,74 @@ export default function ProjectsPage() {
|
||||
{editingId ? "Edit Project" : "Add Project"}
|
||||
</h2>
|
||||
|
||||
<input className="w-full border px-3 py-2 rounded" placeholder="Area Name"
|
||||
<input
|
||||
className="w-full border px-3 py-2 rounded"
|
||||
placeholder="Area Name"
|
||||
value={form.areaName}
|
||||
onChange={(e) => setForm({ ...form, areaName: e.target.value })} />
|
||||
onChange={(e) => setForm({ ...form, areaName: e.target.value })}
|
||||
/>
|
||||
|
||||
<input className="w-full border px-3 py-2 rounded" placeholder="Device S/N"
|
||||
<input
|
||||
className="w-full border px-3 py-2 rounded"
|
||||
placeholder="Device S/N"
|
||||
value={form.deviceSN}
|
||||
onChange={(e) => setForm({ ...form, deviceSN: e.target.value })} />
|
||||
onChange={(e) => setForm({ ...form, deviceSN: e.target.value })}
|
||||
/>
|
||||
|
||||
<input className="w-full border px-3 py-2 rounded" placeholder="Device Name"
|
||||
<input
|
||||
className="w-full border px-3 py-2 rounded"
|
||||
placeholder="Device Name"
|
||||
value={form.deviceName}
|
||||
onChange={(e) => setForm({ ...form, deviceName: e.target.value })} />
|
||||
onChange={(e) => setForm({ ...form, deviceName: e.target.value })}
|
||||
/>
|
||||
|
||||
<input className="w-full border px-3 py-2 rounded" placeholder="Device Type"
|
||||
<input
|
||||
className="w-full border px-3 py-2 rounded"
|
||||
placeholder="Device Type"
|
||||
value={form.deviceType}
|
||||
onChange={(e) => setForm({ ...form, deviceType: e.target.value })} />
|
||||
onChange={(e) => setForm({ ...form, deviceType: e.target.value })}
|
||||
/>
|
||||
|
||||
<input className="w-full border px-3 py-2 rounded" placeholder="Operator"
|
||||
<input
|
||||
className="w-full border px-3 py-2 rounded"
|
||||
placeholder="Operator"
|
||||
value={form.operator}
|
||||
onChange={(e) => setForm({ ...form, operator: e.target.value })} />
|
||||
onChange={(e) => setForm({ ...form, operator: e.target.value })}
|
||||
/>
|
||||
|
||||
<input className="w-full border px-3 py-2 rounded" placeholder="Installed Time"
|
||||
<input
|
||||
className="w-full border px-3 py-2 rounded"
|
||||
placeholder="Installed Time"
|
||||
value={form.installedTime}
|
||||
onChange={(e) => setForm({ ...form, installedTime: e.target.value })} />
|
||||
onChange={(e) =>
|
||||
setForm({ ...form, installedTime: e.target.value })
|
||||
}
|
||||
/>
|
||||
|
||||
<input className="w-full border px-3 py-2 rounded" placeholder="Communication Time"
|
||||
<input
|
||||
className="w-full border px-3 py-2 rounded"
|
||||
placeholder="Communication Time"
|
||||
value={form.communicationTime}
|
||||
onChange={(e) => setForm({ ...form, communicationTime: e.target.value })} />
|
||||
onChange={(e) =>
|
||||
setForm({ ...form, communicationTime: e.target.value })
|
||||
}
|
||||
/>
|
||||
|
||||
<input className="w-full border px-3 py-2 rounded" placeholder="Instruction Manual"
|
||||
<input
|
||||
className="w-full border px-3 py-2 rounded"
|
||||
placeholder="Instruction Manual"
|
||||
value={form.instructionManual}
|
||||
onChange={(e) => setForm({ ...form, instructionManual: e.target.value })} />
|
||||
onChange={(e) =>
|
||||
setForm({ ...form, instructionManual: e.target.value })
|
||||
}
|
||||
/>
|
||||
|
||||
<button
|
||||
onClick={() =>
|
||||
setForm({
|
||||
...form,
|
||||
deviceStatus:
|
||||
form.deviceStatus === "ACTIVE"
|
||||
? "INACTIVE"
|
||||
: "ACTIVE",
|
||||
form.deviceStatus === "ACTIVE" ? "INACTIVE" : "ACTIVE",
|
||||
})
|
||||
}
|
||||
className="w-full border rounded px-3 py-2"
|
||||
@@ -348,9 +320,7 @@ export default function ProjectsPage() {
|
||||
</button>
|
||||
|
||||
<div className="flex justify-end gap-2 pt-3">
|
||||
<button onClick={() => setShowModal(false)}>
|
||||
Cancel
|
||||
</button>
|
||||
<button onClick={() => setShowModal(false)}>Cancel</button>
|
||||
<button
|
||||
onClick={handleSave}
|
||||
className="bg-[#4c5f9e] text-white px-4 py-2 rounded"
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import tailwindcss from "@tailwindcss/vite"
|
||||
import { defineConfig } from "vite";
|
||||
import react from "@vitejs/plugin-react";
|
||||
import tailwindcss from "@tailwindcss/vite";
|
||||
|
||||
// https://vitejs.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [react(),tailwindcss()],
|
||||
plugins: [react(), tailwindcss()],
|
||||
|
||||
server: {
|
||||
host: '0.0.0.0', // Esto permite que el servidor escuche en todas las IP disponibles
|
||||
port: 5173, // Puerto por defecto de Vite (puedes cambiarlo si lo deseas)
|
||||
allowedHosts: [
|
||||
"localhost",
|
||||
"127.0.0.1",
|
||||
"reyna-compressive-shaunna.ngrok-free.dev",
|
||||
],
|
||||
port: 5173,
|
||||
},
|
||||
|
||||
})
|
||||
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user