Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 | import { useState } from "react";
import {
ScenarioRead,
useCoreScenarioPartialUpdateMutation,
useMssUploadCreateMutation,
useMssDeleteCreateMutation,
} from "@/api/apiStore.gen";
import { Upload, Maximize2, X, Loader2 } from "lucide-react";
import { useProjectId } from "@/hooks/project";
import DebouncedInput from "@/ahuora-design-system/ui/debounced-input";
import { Button } from "@/ahuora-design-system/ui/button";
import { ToolTipCover } from "@/ahuora-design-system/ui/tooltip";
import {
AlertDialog,
AlertDialogContent,
AlertDialogHeader,
} from "@/ahuora-design-system/ui/alert-dialog";
import { toast } from "sonner";
import { GenericDataViewer } from "./GenericDataViewer";
import { Label } from "@/ahuora-design-system/ui/label";
import { useLazySolarRetrieveQuery } from "@/api/apiStore.gen";
type SolarDataRow = Record<string, string | number>;
export function LiveSolarData({
optimization,
onAdded,
}: {
optimization: ScenarioRead;
onAdded: () => void;
}) {
const id = useProjectId();
const [latitude, setLatitude] = useState("-36.3981");
const [longitude, setLongitude] = useState("174.6689");
const [fromDate, setFromDate] = useState("2019-01-01");
const [toDate, setToDate] = useState("2019-12-31");
const [isDialogOpen, setIsDialogOpen] = useState(false);
const [solarData, setSolarData] = useState<SolarDataRow[]>([]);
const [isUploading, setIsUploading] = useState(false); //
const [uploadMSS] = useMssUploadCreateMutation();
const [deleteMSS] = useMssDeleteCreateMutation();
const [updateOptimization] = useCoreScenarioPartialUpdateMutation();
const [triggerSolarFetch, { isFetching }] = useLazySolarRetrieveQuery();
/** Fetch Solar Data */
const handleSubmit = async () => {
try {
const args = {
lat: latitude,
lon: longitude,
scenario_id: optimization.id,
flowsheet: id,
from_date: fromDate,
to_date: toDate,
};
const rawResult = await triggerSolarFetch(args).unwrap();
setSolarData(rawResult.data!);
toast.success("Solar data fetched successfully!");
} catch (err) {
console.error("Lazy query error:", err);
toast.error("Failed to fetch solar data");
}
};
/** Upload Solar Data */
const handleUploadClick = async () => {
Iif (solarData.length === 0) {
toast.warning("No solar data available to upload.");
return;
}
setIsUploading(true); //
try {
const uploadData: Record<string, number[]> = {};
const keys = Object.keys(solarData[0]);
keys.forEach((key) => {
const numericValues = solarData
.map((row) => Number(row[key]))
.filter((val) => !isNaN(val));
Iif (numericValues.length === solarData.length) {
uploadData[key] = numericValues;
}
});
const res = await uploadMSS({
uploadData: { flowsheet: id, data: uploadData, scenario: optimization.id },
});
Iif ("error" in res) {
toast.error(`Upload failed: ${res.error?.message || "Unknown error"}`);
return;
}
await updateOptimization({
id: optimization.id,
patchedScenario: { Uploaded_fileName: "Live Solar Data", is_LiveData: true },
});
toast.success("Live solar data uploaded!");
onAdded?.(); //
} catch (err) {
console.error("Upload error:", err);
toast.error("Upload failed");
} finally {
setIsUploading(false); //
}
};
const clearFile = async () => {
try {
await deleteMSS({ deleteData: { flowsheet: id, scenario: optimization.id } });
await updateOptimization({
id: optimization.id,
patchedScenario: { Uploaded_fileName: "", is_LiveData: false },
});
setSolarData([]);
toast.success("Solar data deleted");
} catch (error) {
console.error("Clear file error:", error);
toast.error("Could not delete solar data");
}
};
return (
<div className="relative">
{/* Greyed-out container during uploading */}
<div className={`space-y-4 p-4 bg-muted items-center rounded border transition ${isUploading ? "opacity-50 pointer-events-none" : ""}`}>
{/* Coordinates */}
<div className="flex gap-4">
<div className="flex-1">
<Label htmlFor="latitude">Latitude</Label>
<DebouncedInput id="latitude" value={latitude} onUpdate={(v) => setLatitude(v.toString())} className="w-full p-2" />
</div>
<div className="flex-1">
<Label htmlFor="longitude">Longitude</Label>
<DebouncedInput id="longitude" value={longitude} onUpdate={(v) => setLongitude(v.toString())} className="w-full p-2" />
</div>
</div>
{/* Dates */}
<div className="flex gap-4 mt-4">
<div className="flex-1">
<Label htmlFor="fromDate">From Date</Label>
<DebouncedInput id="fromDate" value={fromDate} onUpdate={(v) => setFromDate(v.toString())} className="w-full p-2" />
</div>
<div className="flex-1">
<Label htmlFor="toDate">To Date</Label>
<DebouncedInput id="toDate" value={toDate} onUpdate={(v) => setToDate(v.toString())} className="w-full p-2" />
</div>
</div>
{/* Action Buttons */}
<div className="flex flex-col sm:flex-row sm:items-center justify-center gap-1 mt-4">
<Button size="sm" variant="outline" onClick={handleSubmit} disabled={isFetching}>
{isFetching ? "Loading..." : "Get Solar Data"}
</Button>
{/* Status + Tools */}
<div className="flex items-center px-2 py-1 bg-secondary text-secondary-foreground whitespace-nowrap rounded-full gap-2">
<span className="text-md">{solarData.length > 0 ? "Data Found" : "No Data Found"}</span>
{solarData.length > 0 && (
<>
<ToolTipCover content="Maximise" asChild>
<Maximize2 size={17} className="cursor-pointer hover:stroke-zinc-400" onClick={() => setIsDialogOpen(true)} />
</ToolTipCover>
<ToolTipCover content="Remove file" asChild>
<X size={18} className="cursor-pointer hover:stroke-rose-700" onClick={clearFile} />
</ToolTipCover>
<ToolTipCover content="Upload Solar Data" asChild>
<Upload size={18} className="cursor-pointer hover:stroke-zinc-400" onClick={handleUploadClick} />
</ToolTipCover>
</>
)}
</div>
</div>
{/* Data Preview Modal */}
<AlertDialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
<AlertDialogContent className="relative flex flex-col justify-between p-6">
<AlertDialogHeader>
<div className="flex items-center justify-between pb-4">
<h3 className="text-base font-semibold truncate">Solar Data Preview</h3>
<button onClick={() => setIsDialogOpen(false)} className="text-muted-foreground hover:text-foreground transition">
<X size={18} />
</button>
</div>
</AlertDialogHeader>
<div className="flex-grow overflow-auto max-h-[60vh]">
<GenericDataViewer data={solarData} />
</div>
</AlertDialogContent>
</AlertDialog>
</div>
{/* Overlay during upload */}
{isUploading && (
<div className="absolute inset-0 flex flex-col items-center justify-center bg-black bg-opacity-40 rounded">
<Loader2 size={30} className="animate-spin text-white mb-2" />
<span className="text-md ">Uploading...</span>
</div>
)}
</div>
);
}
|