mirror of
https://github.com/R0m1k3/LogiFlow.git
synced 2026-10-11 17:27:31 +02:00
Add weather information display and configuration options
Integrate weather data fetching, display in a widget, and provide a settings page for configuration. Replit-Commit-Author: Agent Replit-Commit-Session-Id: d43bd811-9372-45a7-8ac9-4a954c0538e1 Replit-Commit-Checkpoint-Type: full_checkpoint Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/1957c339-2757-4d1f-8e92-e9f71a1ce58e/d43bd811-9372-45a7-8ac9-4a954c0538e1/BIZe1t3
This commit is contained in:
1 parent
48bfc884ed
commit
e70e860097
9 files changed
+863
-4
No files matched your search
+116
-1
@@ -36,12 +36,15 @@ import {
|
||||
insertTaskSchema,
|
||||
insertNocodbConfigSchema,
|
||||
insertSavTicketSchema,
|
||||
insertSavTicketHistorySchema
|
||||
insertSavTicketHistorySchema,
|
||||
insertWeatherDataSchema,
|
||||
insertWeatherSettingsSchema
|
||||
} from "@shared/schema";
|
||||
import { hasPermission } from "@shared/permissions";
|
||||
import { z } from "zod";
|
||||
import { invoiceVerificationService } from "./invoiceVerification";
|
||||
import { backupService } from "./backupService";
|
||||
import { weatherService } from "./weatherService.js";
|
||||
|
||||
export async function registerRoutes(app: Express): Promise<Server> {
|
||||
// Health check endpoint for Docker
|
||||
@@ -2753,6 +2756,118 @@ RÉSUMÉ DU SCAN
|
||||
}
|
||||
});
|
||||
|
||||
// Weather routes
|
||||
app.get('/api/weather/settings', isAuthenticated, requireAdmin, async (req: any, res) => {
|
||||
try {
|
||||
const settings = await storage.getWeatherSettings();
|
||||
res.json(settings);
|
||||
} catch (error) {
|
||||
console.error("Error fetching weather settings:", error);
|
||||
res.status(500).json({ message: "Failed to fetch weather settings" });
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/weather/settings', isAuthenticated, requireAdmin, async (req: any, res) => {
|
||||
try {
|
||||
const data = insertWeatherSettingsSchema.parse(req.body);
|
||||
const settings = await storage.createWeatherSettings(data);
|
||||
res.json(settings);
|
||||
} catch (error) {
|
||||
console.error("Error creating weather settings:", error);
|
||||
if (error instanceof z.ZodError) {
|
||||
return res.status(400).json({ message: "Validation error", errors: error.errors });
|
||||
}
|
||||
res.status(500).json({ message: "Failed to create weather settings" });
|
||||
}
|
||||
});
|
||||
|
||||
app.put('/api/weather/settings/:id', isAuthenticated, requireAdmin, async (req: any, res) => {
|
||||
try {
|
||||
const id = parseInt(req.params.id);
|
||||
const data = insertWeatherSettingsSchema.partial().parse(req.body);
|
||||
const settings = await storage.updateWeatherSettings(id, data);
|
||||
res.json(settings);
|
||||
} catch (error) {
|
||||
console.error("Error updating weather settings:", error);
|
||||
if (error instanceof z.ZodError) {
|
||||
return res.status(400).json({ message: "Validation error", errors: error.errors });
|
||||
}
|
||||
res.status(500).json({ message: "Failed to update weather settings" });
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/weather/test-connection', isAuthenticated, requireAdmin, async (req: any, res) => {
|
||||
try {
|
||||
const { apiKey, location } = req.body;
|
||||
|
||||
if (!apiKey || !location) {
|
||||
return res.status(400).json({ message: "API key and location are required" });
|
||||
}
|
||||
|
||||
const result = await weatherService.testApiConnection(apiKey, location);
|
||||
res.json(result);
|
||||
} catch (error) {
|
||||
console.error("Error testing weather API connection:", error);
|
||||
res.status(500).json({ message: "Failed to test API connection" });
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/weather/current', isAuthenticated, async (req: any, res) => {
|
||||
try {
|
||||
const settings = await storage.getWeatherSettings();
|
||||
|
||||
if (!settings || !settings.isActive) {
|
||||
return res.status(404).json({ message: "Weather service not configured or disabled" });
|
||||
}
|
||||
|
||||
const today = new Date().toISOString().split('T')[0];
|
||||
const previousYearDate = weatherService.getPreviousYearDate();
|
||||
|
||||
// Check if we already have today's data
|
||||
let currentYearData = await storage.getWeatherData(today, true);
|
||||
let previousYearData = await storage.getWeatherData(previousYearDate, false);
|
||||
|
||||
// Fetch current year data if not in cache
|
||||
if (!currentYearData) {
|
||||
console.log("🌤️ Fetching current weather data from API");
|
||||
const apiData = await weatherService.fetchCurrentWeather(settings);
|
||||
if (apiData) {
|
||||
const weatherData = weatherService.convertApiDataToWeatherData(apiData, settings.location, true);
|
||||
if (weatherData) {
|
||||
currentYearData = await storage.createWeatherData(weatherData);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fetch previous year data if not in cache
|
||||
if (!previousYearData) {
|
||||
console.log("🌤️ Fetching previous year weather data from API");
|
||||
const apiData = await weatherService.fetchPreviousYearWeather(settings, previousYearDate);
|
||||
if (apiData) {
|
||||
const weatherData = weatherService.convertApiDataToWeatherData(apiData, settings.location, false);
|
||||
if (weatherData) {
|
||||
previousYearData = await storage.createWeatherData(weatherData);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
res.json({
|
||||
currentYear: currentYearData ? {
|
||||
...currentYearData,
|
||||
icon: weatherService.getWeatherIcon(currentYearData.icon)
|
||||
} : null,
|
||||
previousYear: previousYearData ? {
|
||||
...previousYearData,
|
||||
icon: weatherService.getWeatherIcon(previousYearData.icon)
|
||||
} : null,
|
||||
location: settings.location
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error fetching weather data:", error);
|
||||
res.status(500).json({ message: "Failed to fetch weather data" });
|
||||
}
|
||||
});
|
||||
|
||||
// Create server instance
|
||||
const httpServer = createServer(app);
|
||||
|
||||
|
||||
@@ -14,6 +14,8 @@ import {
|
||||
invoiceVerificationCache,
|
||||
savTickets,
|
||||
savTicketHistory,
|
||||
weatherData,
|
||||
weatherSettings,
|
||||
type User,
|
||||
type UpsertUser,
|
||||
type Group,
|
||||
@@ -55,6 +57,10 @@ import {
|
||||
type InsertSavTicketHistory,
|
||||
type SavTicketWithRelations,
|
||||
type SavTicketHistoryWithCreator,
|
||||
type WeatherData,
|
||||
type InsertWeatherData,
|
||||
type WeatherSettings,
|
||||
type InsertWeatherSettings,
|
||||
} from "@shared/schema";
|
||||
import { db } from "./db";
|
||||
import { eq, and, inArray, desc, sql, gte, lte, lt, or, isNull, isNotNull, asc } from "drizzle-orm";
|
||||
@@ -187,6 +193,15 @@ export interface IStorage {
|
||||
resolvedTickets: number;
|
||||
criticalTickets: number;
|
||||
}>;
|
||||
|
||||
// Weather operations
|
||||
getWeatherSettings(): Promise<WeatherSettings | undefined>;
|
||||
createWeatherSettings(settings: InsertWeatherSettings): Promise<WeatherSettings>;
|
||||
updateWeatherSettings(id: number, settings: Partial<InsertWeatherSettings>): Promise<WeatherSettings>;
|
||||
getWeatherData(date: string, isCurrentYear: boolean): Promise<WeatherData | undefined>;
|
||||
createWeatherData(data: InsertWeatherData): Promise<WeatherData>;
|
||||
updateWeatherData(id: number, data: Partial<InsertWeatherData>): Promise<WeatherData>;
|
||||
deleteOldWeatherData(daysToKeep: number): Promise<void>;
|
||||
}
|
||||
|
||||
export class DatabaseStorage implements IStorage {
|
||||
@@ -1748,6 +1763,63 @@ export class DatabaseStorage implements IStorage {
|
||||
|
||||
return stats;
|
||||
}
|
||||
|
||||
// Weather operations
|
||||
async getWeatherSettings(): Promise<WeatherSettings | undefined> {
|
||||
const [settings] = await db.select().from(weatherSettings).limit(1);
|
||||
return settings;
|
||||
}
|
||||
|
||||
async createWeatherSettings(settingsData: InsertWeatherSettings): Promise<WeatherSettings> {
|
||||
const [settings] = await db.insert(weatherSettings).values(settingsData).returning();
|
||||
return settings;
|
||||
}
|
||||
|
||||
async updateWeatherSettings(id: number, settingsData: Partial<InsertWeatherSettings>): Promise<WeatherSettings> {
|
||||
const [settings] = await db
|
||||
.update(weatherSettings)
|
||||
.set({ ...settingsData, updatedAt: new Date() })
|
||||
.where(eq(weatherSettings.id, id))
|
||||
.returning();
|
||||
return settings;
|
||||
}
|
||||
|
||||
async getWeatherData(date: string, isCurrentYear: boolean): Promise<WeatherData | undefined> {
|
||||
const [data] = await db
|
||||
.select()
|
||||
.from(weatherData)
|
||||
.where(and(
|
||||
eq(weatherData.date, date),
|
||||
eq(weatherData.isCurrentYear, isCurrentYear)
|
||||
))
|
||||
.limit(1);
|
||||
return data;
|
||||
}
|
||||
|
||||
async createWeatherData(data: InsertWeatherData): Promise<WeatherData> {
|
||||
const [weatherInfo] = await db.insert(weatherData).values(data).returning();
|
||||
return weatherInfo;
|
||||
}
|
||||
|
||||
async updateWeatherData(id: number, data: Partial<InsertWeatherData>): Promise<WeatherData> {
|
||||
const [weatherInfo] = await db
|
||||
.update(weatherData)
|
||||
.set({ ...data, updatedAt: new Date() })
|
||||
.where(eq(weatherData.id, id))
|
||||
.returning();
|
||||
return weatherInfo;
|
||||
}
|
||||
|
||||
async deleteOldWeatherData(daysToKeep: number): Promise<void> {
|
||||
const cutoffDate = new Date();
|
||||
cutoffDate.setDate(cutoffDate.getDate() - daysToKeep);
|
||||
|
||||
await db
|
||||
.delete(weatherData)
|
||||
.where(lt(weatherData.createdAt, cutoffDate));
|
||||
|
||||
console.log(`🧹 Deleted weather data older than ${daysToKeep} days`);
|
||||
}
|
||||
}
|
||||
|
||||
// MemStorage class for development
|
||||
@@ -3109,6 +3181,66 @@ export class MemStorage implements IStorage {
|
||||
this.idCounters.savTicket = 6;
|
||||
console.log('✅ SAV test data initialized with 5 tickets and comprehensive history');
|
||||
}
|
||||
|
||||
// Weather operations
|
||||
async getWeatherSettings(): Promise<WeatherSettings | undefined> {
|
||||
// In memory storage, return a default setting for development
|
||||
return {
|
||||
id: 1,
|
||||
apiKey: "6PSHYLBJB9EEYNZ7NDQ5BPGBZ", // Token fourni par l'utilisateur
|
||||
location: "Nancy, France",
|
||||
isActive: true,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date()
|
||||
};
|
||||
}
|
||||
|
||||
async createWeatherSettings(settings: InsertWeatherSettings): Promise<WeatherSettings> {
|
||||
// For development, we'll just return the created settings with an ID
|
||||
return {
|
||||
id: 1,
|
||||
...settings,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date()
|
||||
};
|
||||
}
|
||||
|
||||
async updateWeatherSettings(id: number, settings: Partial<InsertWeatherSettings>): Promise<WeatherSettings> {
|
||||
const existing = await this.getWeatherSettings();
|
||||
return {
|
||||
...existing!,
|
||||
...settings,
|
||||
updatedAt: new Date()
|
||||
};
|
||||
}
|
||||
|
||||
async getWeatherData(date: string, isCurrentYear: boolean): Promise<WeatherData | undefined> {
|
||||
// In development, return some mock data for testing
|
||||
return undefined; // Will trigger API calls
|
||||
}
|
||||
|
||||
async createWeatherData(data: InsertWeatherData): Promise<WeatherData> {
|
||||
return {
|
||||
id: 1,
|
||||
...data,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date()
|
||||
};
|
||||
}
|
||||
|
||||
async updateWeatherData(id: number, data: Partial<InsertWeatherData>): Promise<WeatherData> {
|
||||
const existing = await this.getWeatherData(data.date || "", data.isCurrentYear || true);
|
||||
return {
|
||||
...existing!,
|
||||
...data,
|
||||
updatedAt: new Date()
|
||||
};
|
||||
}
|
||||
|
||||
async deleteOldWeatherData(daysToKeep: number): Promise<void> {
|
||||
// In development, this is a no-op
|
||||
console.log(`🧹 DEV: Would delete weather data older than ${daysToKeep} days`);
|
||||
}
|
||||
}
|
||||
|
||||
// Use MemStorage in development, DatabaseStorage in production
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
import { WeatherData, WeatherSettings } from "../shared/schema.js";
|
||||
|
||||
export interface WeatherApiResponse {
|
||||
days: Array<{
|
||||
datetime: string;
|
||||
tempmax: number;
|
||||
tempmin: number;
|
||||
icon: string;
|
||||
conditions: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface WeatherDisplayData {
|
||||
currentYear: WeatherData | null;
|
||||
previousYear: WeatherData | null;
|
||||
}
|
||||
|
||||
export class WeatherService {
|
||||
private baseUrl = "https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline";
|
||||
|
||||
/**
|
||||
* Récupère les données météo actuelles depuis l'API Visual Crossing
|
||||
*/
|
||||
async fetchCurrentWeather(settings: WeatherSettings): Promise<WeatherApiResponse | null> {
|
||||
try {
|
||||
const url = `${this.baseUrl}/${encodeURIComponent(settings.location)}?unitGroup=metric&include=days&key=${settings.apiKey}&contentType=json`;
|
||||
|
||||
const response = await fetch(url);
|
||||
if (!response.ok) {
|
||||
console.error(`Weather API error: ${response.status} ${response.statusText}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.error("Erreur lors de la récupération de la météo actuelle:", error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Récupère les données météo de l'année précédente pour la même date
|
||||
*/
|
||||
async fetchPreviousYearWeather(settings: WeatherSettings, targetDate: string): Promise<WeatherApiResponse | null> {
|
||||
try {
|
||||
const url = `${this.baseUrl}/${encodeURIComponent(settings.location)}?unitGroup=metric&include=days&key=${settings.apiKey}&contentType=json&forecastBasisDate=${targetDate}`;
|
||||
|
||||
const response = await fetch(url);
|
||||
if (!response.ok) {
|
||||
console.error(`Weather API error for previous year: ${response.status} ${response.statusText}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.error("Erreur lors de la récupération de la météo de l'année précédente:", error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convertit les données de l'API en format WeatherData
|
||||
*/
|
||||
convertApiDataToWeatherData(apiData: WeatherApiResponse, location: string, isCurrentYear: boolean): WeatherData | null {
|
||||
if (!apiData.days || apiData.days.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const todayData = apiData.days[0];
|
||||
|
||||
return {
|
||||
id: 0, // Sera généré par la base de données
|
||||
date: todayData.datetime,
|
||||
location,
|
||||
tempMax: todayData.tempmax.toString(),
|
||||
tempMin: todayData.tempmin.toString(),
|
||||
icon: todayData.icon,
|
||||
conditions: todayData.conditions,
|
||||
isCurrentYear,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date()
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Calcule la date de l'année précédente pour la même date
|
||||
*/
|
||||
getPreviousYearDate(date: Date = new Date()): string {
|
||||
const previousYear = new Date(date);
|
||||
previousYear.setFullYear(date.getFullYear() - 1);
|
||||
return previousYear.toISOString().split('T')[0]; // Format YYYY-MM-DD
|
||||
}
|
||||
|
||||
/**
|
||||
* Convertit l'icône météo en format d'affichage
|
||||
*/
|
||||
getWeatherIcon(iconCode: string): string {
|
||||
const iconMap: { [key: string]: string } = {
|
||||
'clear-day': '☀️',
|
||||
'clear-night': '🌙',
|
||||
'partly-cloudy-day': '⛅',
|
||||
'partly-cloudy-night': '☁️',
|
||||
'cloudy': '☁️',
|
||||
'rain': '🌧️',
|
||||
'snow': '❄️',
|
||||
'wind': '💨',
|
||||
'fog': '🌫️',
|
||||
'thunder': '⛈️',
|
||||
'hail': '🌨️'
|
||||
};
|
||||
|
||||
return iconMap[iconCode] || '🌤️';
|
||||
}
|
||||
|
||||
/**
|
||||
* Valide les paramètres de configuration météo
|
||||
*/
|
||||
validateWeatherSettings(settings: Partial<WeatherSettings>): { isValid: boolean; errors: string[] } {
|
||||
const errors: string[] = [];
|
||||
|
||||
if (!settings.apiKey || settings.apiKey.trim().length === 0) {
|
||||
errors.push("La clé API Visual Crossing est requise");
|
||||
}
|
||||
|
||||
if (!settings.location || settings.location.trim().length === 0) {
|
||||
errors.push("La localisation est requise");
|
||||
}
|
||||
|
||||
// Vérification basique du format de la clé API Visual Crossing
|
||||
if (settings.apiKey && settings.apiKey.length < 10) {
|
||||
errors.push("La clé API semble invalide (trop courte)");
|
||||
}
|
||||
|
||||
return {
|
||||
isValid: errors.length === 0,
|
||||
errors
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Test de connexion à l'API météo
|
||||
*/
|
||||
async testApiConnection(apiKey: string, location: string): Promise<{ success: boolean; message: string }> {
|
||||
try {
|
||||
const testUrl = `${this.baseUrl}/${encodeURIComponent(location)}?unitGroup=metric&include=days&key=${apiKey}&contentType=json`;
|
||||
|
||||
const response = await fetch(testUrl);
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
if (data.days && data.days.length > 0) {
|
||||
return { success: true, message: "Connexion réussie à l'API météo" };
|
||||
} else {
|
||||
return { success: false, message: "Aucune donnée météo trouvée pour cette localisation" };
|
||||
}
|
||||
} else if (response.status === 401) {
|
||||
return { success: false, message: "Clé API invalide" };
|
||||
} else if (response.status === 404) {
|
||||
return { success: false, message: "Localisation introuvable" };
|
||||
} else {
|
||||
return { success: false, message: `Erreur API: ${response.status} ${response.statusText}` };
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Erreur test API météo:", error);
|
||||
return { success: false, message: "Erreur de connexion à l'API météo" };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const weatherService = new WeatherService();
|
||||
Reference in new issue
Block a user