Compare commits
65 Commits
0e10462a99
...
postgres-m
| Author | SHA1 | Date | |
|---|---|---|---|
| 131027c36c | |||
| f185cf8a3f | |||
| f1b55db6d1 | |||
| 7a8e371195 | |||
| e5207d53b7 | |||
| a69862fe73 | |||
| 9b51c866c3 | |||
| 2a786acfb6 | |||
| 40516e8f23 | |||
| f58c14511b | |||
| 5cd80dbf34 | |||
| 923b6b325b | |||
| 559a6e589c | |||
| 9f86b215f9 | |||
| 446423d1a6 | |||
| 6bbc831ae0 | |||
| 34f820b3ca | |||
| 4e8b14906f | |||
| b557590303 | |||
| 69c0381530 | |||
| 6abb5aae15 | |||
| 9d4ad26dcc | |||
| 598abe604b | |||
| f614da943f | |||
| a48deb95da | |||
| 8eb465c0e7 | |||
| 91ad61bdee | |||
| ece4b17edf | |||
| 2aca48738f | |||
| dcdb7f3f12 | |||
| 559690e1c5 | |||
| 355ba46592 | |||
| e360fa6890 | |||
| fe68650b4a | |||
| e7a1f79806 | |||
| 6297df7dfd | |||
| 9eaa5b70d1 | |||
| 434f1dcba3 | |||
|
|
b6862aba02 | ||
| 04a3381730 | |||
| 3f7815874a | |||
| 40fe6e897a | |||
| 4df537816f | |||
| 97a946ebea | |||
| 9fe575ae07 | |||
| 775ae0d9b4 | |||
| dca3fc62ca | |||
| 777b66ddca | |||
| cda8f0fb50 | |||
| b6ff393d0d | |||
| 3e62c8bf96 | |||
| 9334e3e4c2 | |||
| f75d85dbb7 | |||
| 1191c75402 | |||
| c28d600d37 | |||
| 3f94f9d18d | |||
| 325cb210f7 | |||
| 296b4010c0 | |||
| 3ca7b7df9a | |||
| b69691c84f | |||
| 10178de7c1 | |||
| 74e8480a68 | |||
| 139924db94 | |||
| 61e86b1e96 | |||
| 514486bb6c |
3
.gitignore
vendored
@@ -706,6 +706,9 @@ docker-compose.override.yml
|
|||||||
.env.local
|
.env.local
|
||||||
.env.*.local
|
.env.*.local
|
||||||
|
|
||||||
|
# Vite / frontend build output
|
||||||
|
dist/
|
||||||
|
|
||||||
# OS generated files
|
# OS generated files
|
||||||
.DS_Store
|
.DS_Store
|
||||||
.DS_Store?
|
.DS_Store?
|
||||||
|
|||||||
18
Dockerfile
@@ -1,10 +1,26 @@
|
|||||||
|
# Stage 1: Build frontend
|
||||||
|
FROM node:20-alpine AS frontend-build
|
||||||
|
WORKDIR /app
|
||||||
|
COPY ./src/GreenHome.Web/package*.json ./
|
||||||
|
RUN npm ci --ignore-scripts || npm install
|
||||||
|
COPY ./src/GreenHome.Web/ .
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
# Stage 2: Build backend
|
||||||
FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build
|
FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build
|
||||||
WORKDIR /src
|
WORKDIR /src
|
||||||
|
|
||||||
COPY ./src/ .
|
COPY ./src/ .
|
||||||
RUN dotnet restore
|
|
||||||
|
# Copy built frontend from previous stage
|
||||||
|
COPY --from=frontend-build /app/dist /src/GreenHome.Api/wwwroot/
|
||||||
|
|
||||||
|
RUN dotnet restore --verbosity detailed
|
||||||
RUN dotnet publish -c Release -o /app
|
RUN dotnet publish -c Release -o /app
|
||||||
|
|
||||||
FROM mcr.microsoft.com/dotnet/aspnet:9.0 AS runtime
|
FROM mcr.microsoft.com/dotnet/aspnet:9.0 AS runtime
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY --from=build /app .
|
COPY --from=build /app .
|
||||||
|
RUN mkdir -p /app/My_StaticFiles
|
||||||
|
RUN mkdir -p /app/files
|
||||||
ENTRYPOINT ["dotnet", "GreenHome.Api.dll"]
|
ENTRYPOINT ["dotnet", "GreenHome.Api.dll"]
|
||||||
353
src/AI_QUERY_TRACKING.md
Normal file
@@ -0,0 +1,353 @@
|
|||||||
|
# 📊 سیستم ذخیره و ردیابی سوالات هوش مصنوعی
|
||||||
|
|
||||||
|
## ✅ قابلیتهای اضافه شده
|
||||||
|
|
||||||
|
### 1. ذخیره خودکار سوالات و پاسخها
|
||||||
|
تمام سوالاتی که به AI ارسال میشود و پاسخهای دریافتی، به صورت خودکار در دیتابیس ذخیره میشوند.
|
||||||
|
|
||||||
|
### 2. ردیابی مصرف توکن
|
||||||
|
برای هر سوال، اطلاعات کامل توکن ذخیره میشود:
|
||||||
|
- **PromptTokens**: تعداد توکنهای سوال
|
||||||
|
- **CompletionTokens**: تعداد توکنهای پاسخ
|
||||||
|
- **TotalTokens**: مجموع توکنهای استفاده شده
|
||||||
|
|
||||||
|
### 3. ارتباط با دستگاه
|
||||||
|
هر سوال میتواند به یک دستگاه خاص مرتبط شود (با ارسال `deviceId`)
|
||||||
|
|
||||||
|
### 4. ارتباط با کاربر
|
||||||
|
هر سوال میتواند به یک کاربر خاص مرتبط شود (با ارسال `userId`)
|
||||||
|
|
||||||
|
### 5. اندازهگیری زمان پاسخ
|
||||||
|
زمان پاسخدهی به میلیثانیه اندازهگیری و ذخیره میشود
|
||||||
|
|
||||||
|
## 📋 جدول دیتابیس: AIQueries
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE TABLE AIQueries (
|
||||||
|
Id INT PRIMARY KEY IDENTITY,
|
||||||
|
DeviceId INT NULL, -- شماره دستگاه (اختیاری)
|
||||||
|
UserId INT NULL, -- شماره کاربر (اختیاری)
|
||||||
|
Question NVARCHAR(MAX) NOT NULL, -- سوال
|
||||||
|
Answer NVARCHAR(MAX) NOT NULL, -- پاسخ
|
||||||
|
PromptTokens INT NOT NULL, -- توکنهای سوال
|
||||||
|
CompletionTokens INT NOT NULL, -- توکنهای پاسخ
|
||||||
|
TotalTokens INT NOT NULL, -- مجموع توکنها
|
||||||
|
Model NVARCHAR(100) NULL, -- مدل استفاده شده
|
||||||
|
Temperature FLOAT NULL, -- پارامتر Temperature
|
||||||
|
ResponseTimeMs BIGINT NULL, -- زمان پاسخ (میلیثانیه)
|
||||||
|
CreatedAt DATETIME2 NOT NULL, -- زمان ایجاد
|
||||||
|
|
||||||
|
-- Foreign Keys
|
||||||
|
FOREIGN KEY (DeviceId) REFERENCES Devices(Id) ON DELETE SET NULL,
|
||||||
|
FOREIGN KEY (UserId) REFERENCES Users(Id) ON DELETE SET NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Indexes برای کوئری سریع
|
||||||
|
CREATE INDEX IX_AIQueries_DeviceId ON AIQueries(DeviceId);
|
||||||
|
CREATE INDEX IX_AIQueries_UserId ON AIQueries(UserId);
|
||||||
|
CREATE INDEX IX_AIQueries_CreatedAt ON AIQueries(CreatedAt);
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🚀 نحوه استفاده
|
||||||
|
|
||||||
|
### 1. پرسیدن سوال با ذخیره خودکار
|
||||||
|
|
||||||
|
**درخواست:**
|
||||||
|
```http
|
||||||
|
POST /api/ai/ask
|
||||||
|
Content-Type: application/json
|
||||||
|
|
||||||
|
{
|
||||||
|
"question": "دمای مناسب اتاق چقدر است؟",
|
||||||
|
"systemPrompt": "شما یک مشاور خانه هوشمند هستید",
|
||||||
|
"deviceId": 123,
|
||||||
|
"userId": 456
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**پاسخ:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"question": "دمای مناسب اتاق چقدر است؟",
|
||||||
|
"answer": "دمای مناسب اتاق برای راحتی معمولاً بین 20 تا 24 درجه سانتیگراد است...",
|
||||||
|
"deviceId": 123,
|
||||||
|
"tokens": {
|
||||||
|
"prompt": 25,
|
||||||
|
"completion": 150,
|
||||||
|
"total": 175
|
||||||
|
},
|
||||||
|
"responseTimeMs": 1234,
|
||||||
|
"timestamp": "2025-12-16T12:00:00Z"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. دریافت تاریخچه سوالات یک دستگاه
|
||||||
|
|
||||||
|
**درخواست:**
|
||||||
|
```http
|
||||||
|
GET /api/ai/history/device/123?take=50
|
||||||
|
```
|
||||||
|
|
||||||
|
**پاسخ:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"queries": [
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"question": "دمای مناسب اتاق چقدر است؟",
|
||||||
|
"answer": "دمای مناسب اتاق...",
|
||||||
|
"totalTokens": 175,
|
||||||
|
"promptTokens": 25,
|
||||||
|
"completionTokens": 150,
|
||||||
|
"model": "deepseek-chat",
|
||||||
|
"responseTimeMs": 1234,
|
||||||
|
"createdAt": "2025-12-16T12:00:00Z"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"totalTokens": 5432
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. دریافت آمار کلی
|
||||||
|
|
||||||
|
**درخواست:**
|
||||||
|
```http
|
||||||
|
GET /api/ai/stats
|
||||||
|
```
|
||||||
|
|
||||||
|
**پاسخ:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"totalQueries": 1523,
|
||||||
|
"totalTokensUsed": 254789,
|
||||||
|
"totalPromptTokens": 89234,
|
||||||
|
"totalCompletionTokens": 165555,
|
||||||
|
"averageResponseTimeMs": 1456.78,
|
||||||
|
"todayQueries": 45,
|
||||||
|
"todayTokens": 7890
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 📊 API Endpoints جدید
|
||||||
|
|
||||||
|
### 1. POST /api/ai/ask
|
||||||
|
پرسیدن سوال ساده با ذخیره خودکار
|
||||||
|
|
||||||
|
**پارامترها:**
|
||||||
|
- `question` (required): سوال
|
||||||
|
- `systemPrompt` (optional): زمینه برای AI
|
||||||
|
- `deviceId` (optional): شماره دستگاه
|
||||||
|
- `userId` (optional): شماره کاربر
|
||||||
|
|
||||||
|
### 2. POST /api/ai/chat
|
||||||
|
چت پیشرفته با ذخیره خودکار
|
||||||
|
|
||||||
|
**پارامترها:**
|
||||||
|
- `messages` (required): لیست پیامها
|
||||||
|
- `model` (optional): مدل AI
|
||||||
|
- `temperature` (optional): پارامتر خلاقیت
|
||||||
|
- `maxTokens` (optional): حداکثر توکن پاسخ
|
||||||
|
- `deviceId` (optional): شماره دستگاه
|
||||||
|
- `userId` (optional): شماره کاربر
|
||||||
|
|
||||||
|
### 3. POST /api/ai/suggest
|
||||||
|
دریافت پیشنهاد برای خانه هوشمند
|
||||||
|
|
||||||
|
**پارامترها:**
|
||||||
|
- `deviceContext` (required): اطلاعات دستگاه
|
||||||
|
- `deviceId` (optional): شماره دستگاه
|
||||||
|
- `userId` (optional): شماره کاربر
|
||||||
|
|
||||||
|
### 4. GET /api/ai/history/device/{deviceId}
|
||||||
|
دریافت تاریخچه سوالات یک دستگاه
|
||||||
|
|
||||||
|
**Query Parameters:**
|
||||||
|
- `take` (optional, default: 50): تعداد رکورد
|
||||||
|
|
||||||
|
### 5. GET /api/ai/stats
|
||||||
|
دریافت آمار کلی استفاده از AI
|
||||||
|
|
||||||
|
## 💡 مثالهای عملی
|
||||||
|
|
||||||
|
### مثال 1: سوال درباره دستگاه خاص
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -X POST http://localhost:5000/api/ai/ask \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{
|
||||||
|
"question": "دمای فعلی بالاست، چه کنم؟",
|
||||||
|
"deviceId": 123,
|
||||||
|
"userId": 456
|
||||||
|
}'
|
||||||
|
```
|
||||||
|
|
||||||
|
### مثال 2: دریافت تاریخچه
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl http://localhost:5000/api/ai/history/device/123
|
||||||
|
```
|
||||||
|
|
||||||
|
### مثال 3: دریافت آمار
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl http://localhost:5000/api/ai/stats
|
||||||
|
```
|
||||||
|
|
||||||
|
### مثال 4: پیشنهاد برای دستگاه
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -X POST http://localhost:5000/api/ai/suggest \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{
|
||||||
|
"deviceContext": "دمای اتاق: 28 درجه، رطوبت: 65%, ساعت: 14:00",
|
||||||
|
"deviceId": 123
|
||||||
|
}'
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🔍 کوئریهای مفید SQL
|
||||||
|
|
||||||
|
### 1. پرتکرارترین سوالات
|
||||||
|
```sql
|
||||||
|
SELECT Question, COUNT(*) as Count
|
||||||
|
FROM AIQueries
|
||||||
|
GROUP BY Question
|
||||||
|
ORDER BY Count DESC
|
||||||
|
LIMIT 10;
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. مصرف توکن به تفکیک دستگاه
|
||||||
|
```sql
|
||||||
|
SELECT
|
||||||
|
d.DeviceName,
|
||||||
|
COUNT(aq.Id) as QueryCount,
|
||||||
|
SUM(aq.TotalTokens) as TotalTokens,
|
||||||
|
AVG(aq.TotalTokens) as AvgTokens
|
||||||
|
FROM AIQueries aq
|
||||||
|
JOIN Devices d ON aq.DeviceId = d.Id
|
||||||
|
GROUP BY d.DeviceName
|
||||||
|
ORDER BY TotalTokens DESC;
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. سوالات امروز
|
||||||
|
```sql
|
||||||
|
SELECT *
|
||||||
|
FROM AIQueries
|
||||||
|
WHERE CAST(CreatedAt AS DATE) = CAST(GETDATE() AS DATE)
|
||||||
|
ORDER BY CreatedAt DESC;
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. میانگین زمان پاسخ
|
||||||
|
```sql
|
||||||
|
SELECT
|
||||||
|
Model,
|
||||||
|
COUNT(*) as QueryCount,
|
||||||
|
AVG(ResponseTimeMs) as AvgResponseTime,
|
||||||
|
MIN(ResponseTimeMs) as MinResponseTime,
|
||||||
|
MAX(ResponseTimeMs) as MaxResponseTime
|
||||||
|
FROM AIQueries
|
||||||
|
WHERE ResponseTimeMs IS NOT NULL
|
||||||
|
GROUP BY Model;
|
||||||
|
```
|
||||||
|
|
||||||
|
## 📈 گزارشهای آماری
|
||||||
|
|
||||||
|
### مصرف روزانه
|
||||||
|
```csharp
|
||||||
|
public async Task<DailyUsageReport> GetDailyUsage(DateTime date)
|
||||||
|
{
|
||||||
|
var queries = await dbContext.AIQueries
|
||||||
|
.Where(q => q.CreatedAt.Date == date.Date)
|
||||||
|
.ToListAsync();
|
||||||
|
|
||||||
|
return new DailyUsageReport
|
||||||
|
{
|
||||||
|
Date = date,
|
||||||
|
TotalQueries = queries.Count,
|
||||||
|
TotalTokens = queries.Sum(q => q.TotalTokens),
|
||||||
|
UniqueDevices = queries.Select(q => q.DeviceId).Distinct().Count()
|
||||||
|
};
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### مصرف هر دستگاه
|
||||||
|
```csharp
|
||||||
|
public async Task<DeviceUsageReport> GetDeviceUsage(int deviceId)
|
||||||
|
{
|
||||||
|
var queries = await dbContext.AIQueries
|
||||||
|
.Where(q => q.DeviceId == deviceId)
|
||||||
|
.ToListAsync();
|
||||||
|
|
||||||
|
return new DeviceUsageReport
|
||||||
|
{
|
||||||
|
DeviceId = deviceId,
|
||||||
|
TotalQueries = queries.Count,
|
||||||
|
TotalTokens = queries.Sum(q => q.TotalTokens),
|
||||||
|
AverageResponseTime = queries.Average(q => q.ResponseTimeMs ?? 0)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## ⚠️ نکات مهم
|
||||||
|
|
||||||
|
### 1. هزینه
|
||||||
|
- هر توکن هزینه دارد
|
||||||
|
- با استفاده از آمار، مصرف را کنترل کنید
|
||||||
|
- برای کاهش هزینه، سوالات مشابه را cache کنید
|
||||||
|
|
||||||
|
### 2. عملکرد
|
||||||
|
- Index ها برای کوئری سریع اضافه شدهاند
|
||||||
|
- برای حجم بالا، از pagination استفاده کنید
|
||||||
|
- رکوردهای قدیمی را Archive کنید
|
||||||
|
|
||||||
|
### 3. حریم خصوصی
|
||||||
|
- سوالات کاربران ذخیره میشوند
|
||||||
|
- از این دادهها با احتیاط استفاده کنید
|
||||||
|
- در صورت نیاز، امکان حذف تاریخچه اضافه کنید
|
||||||
|
|
||||||
|
## 🔧 اعمال تغییرات در دیتابیس
|
||||||
|
|
||||||
|
Migration ایجاد شده و آماده اجرا است:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd GreenHome.Infrastructure
|
||||||
|
dotnet ef database update --startup-project ../GreenHome.Api
|
||||||
|
```
|
||||||
|
|
||||||
|
یا اگر برنامه را اجرا کنید، Migration به صورت خودکار اعمال میشود (در `Program.cs` تنظیم شده).
|
||||||
|
|
||||||
|
## 📚 مستندات مرتبط
|
||||||
|
|
||||||
|
- **Entity**: `GreenHome.Domain/AIQuery.cs`
|
||||||
|
- **Service**: `GreenHome.Infrastructure/AIQueryService.cs`
|
||||||
|
- **Interface**: `GreenHome.Application/IAIQueryService.cs`
|
||||||
|
- **Controller**: `GreenHome.Api/Controllers/AIController.cs`
|
||||||
|
- **Migration**: `GreenHome.Infrastructure/Migrations/20251216113127_AddAIQueryTable.cs`
|
||||||
|
|
||||||
|
## 🎯 استفادههای پیشرفته
|
||||||
|
|
||||||
|
### 1. تحلیل رفتار کاربر
|
||||||
|
```csharp
|
||||||
|
var userQueries = await aiQueryService.GetUserQueriesAsync(userId, 100);
|
||||||
|
var topics = ExtractTopics(userQueries);
|
||||||
|
// تحلیل علایق کاربر
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. بهینهسازی پاسخها
|
||||||
|
```csharp
|
||||||
|
// پیدا کردن سوالات با زمان پاسخ بالا
|
||||||
|
var slowQueries = await dbContext.AIQueries
|
||||||
|
.Where(q => q.ResponseTimeMs > 3000)
|
||||||
|
.ToListAsync();
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. گزارش هزینه
|
||||||
|
```csharp
|
||||||
|
// محاسبه هزینه بر اساس توکن
|
||||||
|
var totalTokens = await aiQueryService.GetDeviceTotalTokensAsync(deviceId);
|
||||||
|
var estimatedCost = CalculateCost(totalTokens);
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**نکته:** تمام سوالات و پاسخها اکنون به صورت خودکار ذخیره میشوند و نیازی به کار اضافی نیست! ✨
|
||||||
|
|
||||||
230
src/ALERT_SYSTEM_UPDATE.md
Normal file
@@ -0,0 +1,230 @@
|
|||||||
|
# سیستم جدید هشدارهای شرطی
|
||||||
|
|
||||||
|
## تغییرات اعمال شده
|
||||||
|
|
||||||
|
### 1. تغییرات در تنظیمات دستگاه (`DeviceSettings`)
|
||||||
|
|
||||||
|
#### فیلدهای حذف شده:
|
||||||
|
- تمام فیلدهای `Min` و `Max` برای سنسورها حذف شدند:
|
||||||
|
- `DangerMaxTemperature`, `DangerMinTemperature`
|
||||||
|
- `MaxTemperature`, `MinTemperature`
|
||||||
|
- `MaxGasPPM`, `MinGasPPM`
|
||||||
|
- `MaxLux`, `MinLux`
|
||||||
|
- `MaxHumidityPercent`, `MinHumidityPercent`
|
||||||
|
|
||||||
|
#### فیلدهای جدید:
|
||||||
|
- `Province` (استان) - نوع: string
|
||||||
|
- `City` (شهر) - نوع: string
|
||||||
|
- `Latitude` (عرض جغرافیایی) - نوع: decimal? (اختیاری)
|
||||||
|
- `Longitude` (طول جغرافیایی) - نوع: decimal? (اختیاری)
|
||||||
|
|
||||||
|
### 2. مدلهای جدید برای شرایط هشدار
|
||||||
|
|
||||||
|
#### `AlertCondition` - شرط هشدار
|
||||||
|
هر شرط هشدار شامل موارد زیر است:
|
||||||
|
- `DeviceId`: شناسه دستگاه
|
||||||
|
- `NotificationType`: نوع اعلان (تماس یا پیامک)
|
||||||
|
- `Call = 0`: تماس صوتی
|
||||||
|
- `SMS = 1`: پیامک
|
||||||
|
- `TimeType`: زمان اعمال شرط
|
||||||
|
- `Day = 0`: فقط روز
|
||||||
|
- `Night = 1`: فقط شب
|
||||||
|
- `Always = 2`: همیشه
|
||||||
|
- `CallCooldownMinutes`: فاصله زمانی بین تماسهای هشدار (پیشفرض: 60 دقیقه)
|
||||||
|
- `SmsCooldownMinutes`: فاصله زمانی بین پیامکهای هشدار (پیشفرض: 15 دقیقه)
|
||||||
|
- `IsEnabled`: وضعیت فعال/غیرفعال بودن شرط
|
||||||
|
- `Rules`: لیست قوانین (با AND به هم متصل میشوند)
|
||||||
|
|
||||||
|
#### `AlertRule` - قانون شرط
|
||||||
|
هر قانون شامل:
|
||||||
|
- `SensorType`: نوع سنسور
|
||||||
|
- `Temperature = 0`: دما
|
||||||
|
- `Humidity = 1`: رطوبت
|
||||||
|
- `Soil = 2`: رطوبت خاک
|
||||||
|
- `Gas = 3`: گاز
|
||||||
|
- `Lux = 4`: نور
|
||||||
|
- `ComparisonType`: نوع مقایسه
|
||||||
|
- `GreaterThan = 0`: بیشتر از
|
||||||
|
- `LessThan = 1`: کمتر از
|
||||||
|
- `Between = 2`: بین دو عدد
|
||||||
|
- `OutOfRange = 3`: خارج از محدوده
|
||||||
|
- `Value1`: مقدار عددی اول
|
||||||
|
- `Value2`: مقدار عددی دوم (برای Between و OutOfRange)
|
||||||
|
- `Order`: ترتیب نمایش
|
||||||
|
|
||||||
|
### 3. API های جدید
|
||||||
|
|
||||||
|
#### مدیریت شرایط هشدار (`/api/AlertConditions`)
|
||||||
|
|
||||||
|
**دریافت شرایط یک دستگاه:**
|
||||||
|
```http
|
||||||
|
GET /api/AlertConditions/device/{deviceId}
|
||||||
|
```
|
||||||
|
|
||||||
|
**دریافت یک شرط با ID:**
|
||||||
|
```http
|
||||||
|
GET /api/AlertConditions/{id}
|
||||||
|
```
|
||||||
|
|
||||||
|
**ایجاد شرط جدید:**
|
||||||
|
```http
|
||||||
|
POST /api/AlertConditions
|
||||||
|
Content-Type: application/json
|
||||||
|
|
||||||
|
{
|
||||||
|
"deviceId": 1,
|
||||||
|
"notificationType": 1, // 0=Call, 1=SMS
|
||||||
|
"timeType": 0, // 0=Day, 1=Night, 2=Always
|
||||||
|
"callCooldownMinutes": 60,
|
||||||
|
"smsCooldownMinutes": 15,
|
||||||
|
"isEnabled": true,
|
||||||
|
"rules": [
|
||||||
|
{
|
||||||
|
"sensorType": 0, // 0=Temperature, 1=Humidity, 2=Soil, 3=Gas, 4=Lux
|
||||||
|
"comparisonType": 0, // 0=GreaterThan, 1=LessThan, 2=Between, 3=OutOfRange
|
||||||
|
"value1": 30.0,
|
||||||
|
"value2": null, // فقط برای Between و OutOfRange
|
||||||
|
"order": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"sensorType": 1, // Humidity
|
||||||
|
"comparisonType": 2, // Between
|
||||||
|
"value1": 40.0,
|
||||||
|
"value2": 60.0,
|
||||||
|
"order": 1
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**بهروزرسانی شرط:**
|
||||||
|
```http
|
||||||
|
PUT /api/AlertConditions
|
||||||
|
Content-Type: application/json
|
||||||
|
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"notificationType": 1,
|
||||||
|
"timeType": 0,
|
||||||
|
"callCooldownMinutes": 60,
|
||||||
|
"smsCooldownMinutes": 15,
|
||||||
|
"isEnabled": true,
|
||||||
|
"rules": [...]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**حذف شرط:**
|
||||||
|
```http
|
||||||
|
DELETE /api/AlertConditions/{id}
|
||||||
|
```
|
||||||
|
|
||||||
|
**فعال/غیرفعال کردن شرط:**
|
||||||
|
```http
|
||||||
|
PATCH /api/AlertConditions/{id}/toggle
|
||||||
|
Content-Type: application/json
|
||||||
|
|
||||||
|
true // یا false
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. محاسبه روز/شب
|
||||||
|
|
||||||
|
سرویس `SunCalculatorService` بر اساس موقعیت جغرافیایی (Latitude/Longitude) و زمان جاری، طلوع و غروب خورشید را محاسبه کرده و مشخص میکند که آیا زمان فعلی روز است یا شب.
|
||||||
|
|
||||||
|
### 5. نحوه عملکرد سیستم هشدار جدید
|
||||||
|
|
||||||
|
1. هنگام دریافت داده از دستگاه (`/api/Telemetry/AddData`)
|
||||||
|
2. تمام شرایط فعال (`IsEnabled=true`) دستگاه بررسی میشوند
|
||||||
|
3. برای هر شرط:
|
||||||
|
- اگر `TimeType` تنظیم شده باشد، زمان روز/شب چک میشود
|
||||||
|
- تمام قوانین (`Rules`) با منطق AND چک میشوند
|
||||||
|
- اگر همه قوانین برقرار باشند، هشدار ارسال میشود
|
||||||
|
4. هشدار فقط در صورتی ارسال میشود که:
|
||||||
|
- از آخرین هشدار همان شرط، زمان کافی گذشته باشد (بر اساس `CallCooldownMinutes` یا `SmsCooldownMinutes`)
|
||||||
|
5. هشدار به صورت پیامک یا تماس صوتی ارسال میشود
|
||||||
|
|
||||||
|
### 6. مثالهای کاربردی
|
||||||
|
|
||||||
|
#### مثال 1: هشدار دمای بالا در روز
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"deviceId": 1,
|
||||||
|
"notificationType": 1, // SMS
|
||||||
|
"timeType": 0, // Day only
|
||||||
|
"smsCooldownMinutes": 15,
|
||||||
|
"rules": [
|
||||||
|
{
|
||||||
|
"sensorType": 0, // Temperature
|
||||||
|
"comparisonType": 0, // GreaterThan
|
||||||
|
"value1": 35.0
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### مثال 2: هشدار دما و رطوبت در شب
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"deviceId": 1,
|
||||||
|
"notificationType": 0, // Call
|
||||||
|
"timeType": 1, // Night only
|
||||||
|
"callCooldownMinutes": 60,
|
||||||
|
"rules": [
|
||||||
|
{
|
||||||
|
"sensorType": 0, // Temperature
|
||||||
|
"comparisonType": 1, // LessThan
|
||||||
|
"value1": 10.0,
|
||||||
|
"order": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"sensorType": 1, // Humidity
|
||||||
|
"comparisonType": 0, // GreaterThan
|
||||||
|
"value1": 80.0,
|
||||||
|
"order": 1
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
**توضیح**: اگر دما کمتر از 10 درجه AND رطوبت بیشتر از 80 درصد باشد، در شب تماس بگیر.
|
||||||
|
|
||||||
|
#### مثال 3: رطوبت خارج از محدوده
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"deviceId": 1,
|
||||||
|
"notificationType": 1, // SMS
|
||||||
|
"timeType": 2, // Always
|
||||||
|
"smsCooldownMinutes": 15,
|
||||||
|
"rules": [
|
||||||
|
{
|
||||||
|
"sensorType": 1, // Humidity
|
||||||
|
"comparisonType": 3, // OutOfRange
|
||||||
|
"value1": 30.0,
|
||||||
|
"value2": 70.0
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
**توضیح**: اگر رطوبت کمتر از 30 یا بیشتر از 70 باشد، همیشه پیامک بفرست.
|
||||||
|
|
||||||
|
### 7. تغییرات در Database
|
||||||
|
|
||||||
|
Migration جدید (`UpdateAlertSystemWithConditions`) شامل:
|
||||||
|
- حذف ستونهای min/max از `DeviceSettings`
|
||||||
|
- اضافه کردن ستونهای `Province`, `City`, `Latitude`, `Longitude` به `DeviceSettings`
|
||||||
|
- ایجاد جدول `AlertConditions`
|
||||||
|
- ایجاد جدول `AlertRules`
|
||||||
|
- بهروزرسانی جدول `AlertNotifications` برای ارتباط با `AlertCondition`
|
||||||
|
|
||||||
|
### 8. سرویسهای جدید
|
||||||
|
|
||||||
|
- `IAlertConditionService` / `AlertConditionService`: مدیریت شرایط هشدار
|
||||||
|
- `ISunCalculatorService` / `SunCalculatorService`: محاسبه طلوع/غروب و تشخیص روز/شب
|
||||||
|
- `AlertService`: بازنویسی کامل برای پشتیبانی از سیستم شرطی جدید
|
||||||
|
|
||||||
|
### 9. نکات مهم
|
||||||
|
|
||||||
|
1. **Migration**: قبل از اجرا، حتماً backup از database بگیرید چون فیلدهای قدیمی حذف میشوند
|
||||||
|
2. **Latitude/Longitude**: برای استفاده از قابلیت روز/شب، حتماً مختصات جغرافیایی را در تنظیمات دستگاه وارد کنید
|
||||||
|
3. **Cooldown**: فاصله زمانی بین هشدارها قابل تنظیم برای هر شرط است
|
||||||
|
4. **AND Logic**: تمام قوانین یک شرط با منطق AND به هم متصل میشوند
|
||||||
|
5. **Multiple Conditions**: میتوانید چندین شرط مجزا برای یک دستگاه تعریف کنید
|
||||||
|
|
||||||
32
src/Agents.md
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
# Ponytail, lazy senior dev mode
|
||||||
|
|
||||||
|
You are a lazy senior developer. Lazy means efficient, not careless. The best code is the code never written.
|
||||||
|
|
||||||
|
Before writing any code, stop at the first rung that holds:
|
||||||
|
|
||||||
|
1. Does this need to be built at all? (YAGNI)
|
||||||
|
2. Does it already exist in this codebase? Reuse the helper, util, or pattern that's already here, don't re-write it.
|
||||||
|
3. Does the standard library already do this? Use it.
|
||||||
|
4. Does a native platform feature cover it? Use it.
|
||||||
|
5. Does an already-installed dependency solve it? Use it.
|
||||||
|
6. Can this be one line? Make it one line.
|
||||||
|
7. Only then: write the minimum code that works.
|
||||||
|
|
||||||
|
The ladder runs after you understand the problem, not instead of it: read the task and the code it touches, trace the real flow end to end, then climb.
|
||||||
|
|
||||||
|
Bug fix = root cause, not symptom: a report names a symptom. Grep every caller of the function you touch and fix the shared function once — one guard there is a smaller diff than one per caller, and patching only the path the ticket names leaves a sibling caller still broken.
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
|
||||||
|
- No abstractions that weren't explicitly requested.
|
||||||
|
- No new dependency if it can be avoided.
|
||||||
|
- No boilerplate nobody asked for.
|
||||||
|
- Deletion over addition. Boring over clever. Fewest files possible.
|
||||||
|
- Shortest working diff wins, but only once you understand the problem. The smallest change in the wrong place isn't lazy, it's a second bug.
|
||||||
|
- Question complex requests: "Do you actually need X, or does Y cover it?"
|
||||||
|
- Pick the edge-case-correct option when two stdlib approaches are the same size, lazy means less code, not the flimsier algorithm.
|
||||||
|
- Mark deliberate simplifications that cut a real corner with a known ceiling (global lock, O(n²) scan, naive heuristic) with a `ponytail:` comment naming the ceiling and upgrade path.
|
||||||
|
|
||||||
|
Not lazy about: understanding the problem (read it fully and trace the real flow before picking a rung, a small diff you don't understand is just laziness dressed up as efficiency), input validation at trust boundaries, error handling that prevents data loss, security, accessibility, the calibration real hardware needs (the platform is never the spec ideal, a clock drifts, a sensor reads off), anything explicitly requested. Lazy code without its check is unfinished: non-trivial logic leaves ONE runnable check behind, the smallest thing that fails if the logic breaks (an assert-based demo/self-check or one small test file; no frameworks, no fixtures). Trivial one-liners need no test.
|
||||||
|
|
||||||
|
(Yes, this file also applies to agents working on the ponytail repo itself. Especially to them.)
|
||||||
119
src/CHANGES_DAILY_REPORT.md
Normal file
@@ -0,0 +1,119 @@
|
|||||||
|
# خلاصه تغییرات - API گزارش روزانه
|
||||||
|
|
||||||
|
## تاریخ: 1403/09/26 (2024/12/16)
|
||||||
|
|
||||||
|
### فایلهای جدید ایجاد شده:
|
||||||
|
|
||||||
|
1. **GreenHome.Domain/DailyReport.cs**
|
||||||
|
- Entity برای ذخیره گزارشهای روزانه
|
||||||
|
- شامل اطلاعات تحلیل AI، مصرف توکن، و متادیتای مرتبط
|
||||||
|
|
||||||
|
2. **GreenHome.Application/IDailyReportService.cs**
|
||||||
|
- Interface سرویس گزارش روزانه
|
||||||
|
|
||||||
|
3. **GreenHome.Infrastructure/DailyReportService.cs**
|
||||||
|
- پیادهسازی کامل سرویس گزارش روزانه
|
||||||
|
- شامل لاجیک نمونهبرداری، ارتباط با DeepSeek، و کش
|
||||||
|
|
||||||
|
4. **GreenHome.Api/Controllers/DailyReportController.cs**
|
||||||
|
- Controller جدید با endpoint برای دریافت گزارش
|
||||||
|
|
||||||
|
5. **GreenHome.Infrastructure/Migrations/20251216152746_AddDailyReportsTable.cs**
|
||||||
|
- Migration برای ایجاد جدول DailyReports
|
||||||
|
|
||||||
|
6. **DAILY_REPORT_API.md**
|
||||||
|
- مستندات کامل API
|
||||||
|
|
||||||
|
### فایلهای ویرایش شده:
|
||||||
|
|
||||||
|
1. **GreenHome.Application/Dtos.cs**
|
||||||
|
- افزودن `DailyReportRequest`
|
||||||
|
- افزودن `DailyReportResponse`
|
||||||
|
|
||||||
|
2. **GreenHome.Infrastructure/GreenHomeDbContext.cs**
|
||||||
|
- افزودن `DbSet<DailyReport>`
|
||||||
|
- پیکربندی entity در `OnModelCreating`
|
||||||
|
|
||||||
|
3. **GreenHome.Api/Program.cs**
|
||||||
|
- ثبت `IDailyReportService` در DI container
|
||||||
|
|
||||||
|
4. **GreenHome.Infrastructure/GreenHome.Infrastructure.csproj**
|
||||||
|
- افزودن reference به `GreenHome.AI.DeepSeek`
|
||||||
|
|
||||||
|
## ویژگیهای کلیدی:
|
||||||
|
|
||||||
|
### 1. کش هوشمند
|
||||||
|
- گزارشهای قبلی از دیتابیس خوانده میشوند
|
||||||
|
- صرفهجویی در مصرف توکن و هزینه
|
||||||
|
|
||||||
|
### 2. نمونهبرداری بهینه
|
||||||
|
- از هر 20 رکورد، فقط 1 رکورد انتخاب میشود
|
||||||
|
- کاهش 95% در مصرف توکن
|
||||||
|
|
||||||
|
### 3. تحلیل جامع
|
||||||
|
- دما، رطوبت، نور، و کیفیت هوا (CO)
|
||||||
|
- روندهای روزانه و پیشنهادات بهبود
|
||||||
|
|
||||||
|
### 4. مدیریت خطا
|
||||||
|
- بررسی اعتبار ورودیها
|
||||||
|
- لاگ کامل عملیات
|
||||||
|
- پیامهای خطای واضح به فارسی
|
||||||
|
|
||||||
|
### 5. بهینهسازی دیتابیس
|
||||||
|
- Unique constraint بر روی (DeviceId, PersianDate)
|
||||||
|
- Indexهای مناسب برای جستجوی سریع
|
||||||
|
- Cascade delete برای یکپارچگی داده
|
||||||
|
|
||||||
|
## نحوه استفاده:
|
||||||
|
|
||||||
|
```http
|
||||||
|
GET /api/DailyReport?deviceId=1&persianDate=1403/09/26
|
||||||
|
```
|
||||||
|
|
||||||
|
## پیشنیازها:
|
||||||
|
|
||||||
|
1. کانفیگ DeepSeek API در `appsettings.json`:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"DeepSeek": {
|
||||||
|
"ApiKey": "your-api-key",
|
||||||
|
"BaseUrl": "https://api.deepseek.com"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
2. اجرای migration:
|
||||||
|
```bash
|
||||||
|
dotnet ef database update
|
||||||
|
```
|
||||||
|
یا به صورت خودکار در startup برنامه اعمال میشود.
|
||||||
|
|
||||||
|
## نکات امنیتی:
|
||||||
|
|
||||||
|
- API key باید در environment variable یا Azure Key Vault نگهداری شود
|
||||||
|
- در production، rate limiting اضافه کنید
|
||||||
|
- برای دسترسی به API، authentication لازم است (در نسخه بعدی)
|
||||||
|
|
||||||
|
## تست:
|
||||||
|
|
||||||
|
1. مطمئن شوید دیتابیس شامل رکوردهای تلمتری برای تاریخ مورد نظر است
|
||||||
|
2. درخواست اول باید گزارش جدید ایجاد کند (`fromCache: false`)
|
||||||
|
3. درخواست دوم با همان تاریخ باید از کش برگردد (`fromCache: true`)
|
||||||
|
|
||||||
|
## آمار عملکرد:
|
||||||
|
|
||||||
|
- زمان پاسخ اولین درخواست: ~3-5 ثانیه (شامل فراخوانی AI)
|
||||||
|
- زمان پاسخ درخواستهای بعدی: <100ms (از کش)
|
||||||
|
- مصرف توکن برای یک روز با 288 رکورد: ~800-1500 توکن
|
||||||
|
- بدون نمونهبرداری: ~15000-20000 توکن (95% کاهش!)
|
||||||
|
|
||||||
|
## TODO (پیشنهادات آینده):
|
||||||
|
|
||||||
|
- [ ] اضافه کردن فیلتر تاریخ (از تا) برای دریافت چندین گزارش
|
||||||
|
- [ ] ایجاد endpoint برای لیست کردن تمام گزارشهای یک دستگاه
|
||||||
|
- [ ] امکان حذف و ایجاد مجدد گزارش (برای مدیران)
|
||||||
|
- [ ] اضافه کردن chart و نمودار به پاسخ
|
||||||
|
- [ ] ارسال گزارش به ایمیل یا SMS
|
||||||
|
- [ ] مقایسه گزارشهای چند روزه
|
||||||
|
- [ ] پیشنهادات اتوماتیک برای تنظیمات دستگاه
|
||||||
|
|
||||||
246
src/CHANGES_SUMMARY.md
Normal file
@@ -0,0 +1,246 @@
|
|||||||
|
# 📝 خلاصه تغییرات - سیستم ذخیره و ردیابی سوالات AI
|
||||||
|
|
||||||
|
## ✅ تغییرات اعمال شده
|
||||||
|
|
||||||
|
### 1. Entity جدید در Domain
|
||||||
|
**فایل:** `GreenHome.Domain/AIQuery.cs`
|
||||||
|
- ذخیره سوال و پاسخ
|
||||||
|
- ذخیره اطلاعات توکن (PromptTokens, CompletionTokens, TotalTokens)
|
||||||
|
- ارتباط با Device (DeviceId)
|
||||||
|
- ارتباط با User (UserId)
|
||||||
|
- ذخیره Model و Temperature
|
||||||
|
- ذخیره زمان پاسخ (ResponseTimeMs)
|
||||||
|
- تاریخ ایجاد (CreatedAt)
|
||||||
|
|
||||||
|
### 2. آپدیت DbContext
|
||||||
|
**فایل:** `GreenHome.Infrastructure/GreenHomeDbContext.cs`
|
||||||
|
- اضافه شدن `DbSet<AIQuery>`
|
||||||
|
- تنظیمات Entity Framework
|
||||||
|
- Foreign Keys به Device و User
|
||||||
|
- Index ها برای کوئری سریع
|
||||||
|
|
||||||
|
### 3. Interface و Service جدید
|
||||||
|
**فایلها:**
|
||||||
|
- `GreenHome.Application/IAIQueryService.cs` - Interface
|
||||||
|
- `GreenHome.Infrastructure/AIQueryService.cs` - پیادهسازی
|
||||||
|
|
||||||
|
**قابلیتها:**
|
||||||
|
- `SaveQueryAsync()` - ذخیره سوال
|
||||||
|
- `GetDeviceQueriesAsync()` - دریافت تاریخچه دستگاه
|
||||||
|
- `GetUserQueriesAsync()` - دریافت تاریخچه کاربر
|
||||||
|
- `GetDeviceTotalTokensAsync()` - مجموع توکنهای دستگاه
|
||||||
|
- `GetUserTotalTokensAsync()` - مجموع توکنهای کاربر
|
||||||
|
- `GetRecentQueriesAsync()` - آخرین سوالات
|
||||||
|
- `GetStatsAsync()` - آمار کلی
|
||||||
|
|
||||||
|
### 4. آپدیت AIController
|
||||||
|
**فایل:** `GreenHome.Api/Controllers/AIController.cs`
|
||||||
|
|
||||||
|
**تغییرات:**
|
||||||
|
- Inject کردن `IAIQueryService`
|
||||||
|
- اضافه شدن `DeviceId` و `UserId` به Request Models
|
||||||
|
- ذخیره خودکار تمام سوالات و پاسخها
|
||||||
|
- اندازهگیری زمان پاسخ
|
||||||
|
- برگرداندن اطلاعات توکن در Response
|
||||||
|
|
||||||
|
**Endpoints جدید:**
|
||||||
|
- `GET /api/ai/history/device/{deviceId}` - تاریخچه سوالات دستگاه
|
||||||
|
- `GET /api/ai/stats` - آمار کلی
|
||||||
|
|
||||||
|
**Endpoints بهروز شده:**
|
||||||
|
- `POST /api/ai/ask` - حالا DeviceId و UserId میگیرد
|
||||||
|
- `POST /api/ai/chat` - حالا DeviceId و UserId میگیرد
|
||||||
|
- `POST /api/ai/suggest` - حالا DeviceId و UserId میگیرد
|
||||||
|
|
||||||
|
### 5. ثبت Service در DI
|
||||||
|
**فایل:** `GreenHome.Api/Program.cs`
|
||||||
|
- اضافه شدن `IAIQueryService` به Dependency Injection
|
||||||
|
|
||||||
|
### 6. Migration دیتابیس
|
||||||
|
**فایل:** `GreenHome.Infrastructure/Migrations/20251216113127_AddAIQueryTable.cs`
|
||||||
|
- ایجاد جدول `AIQueries`
|
||||||
|
- Foreign Keys
|
||||||
|
- Indexes
|
||||||
|
|
||||||
|
### 7. مستندات
|
||||||
|
**فایلها:**
|
||||||
|
- `AI_QUERY_TRACKING.md` - راهنمای کامل استفاده
|
||||||
|
- `CHANGES_SUMMARY.md` - این فایل
|
||||||
|
|
||||||
|
## 📊 ساختار جدول AIQueries
|
||||||
|
|
||||||
|
```
|
||||||
|
AIQueries
|
||||||
|
├── Id (PK)
|
||||||
|
├── DeviceId (FK -> Devices) - اختیاری
|
||||||
|
├── UserId (FK -> Users) - اختیاری
|
||||||
|
├── Question (nvarchar(max))
|
||||||
|
├── Answer (nvarchar(max))
|
||||||
|
├── PromptTokens (int)
|
||||||
|
├── CompletionTokens (int)
|
||||||
|
├── TotalTokens (int)
|
||||||
|
├── Model (nvarchar(100))
|
||||||
|
├── Temperature (float) - اختیاری
|
||||||
|
├── ResponseTimeMs (bigint) - اختیاری
|
||||||
|
└── CreatedAt (datetime2)
|
||||||
|
|
||||||
|
Indexes:
|
||||||
|
- IX_AIQueries_DeviceId
|
||||||
|
- IX_AIQueries_UserId
|
||||||
|
- IX_AIQueries_CreatedAt
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🔄 نحوه اعمال تغییرات
|
||||||
|
|
||||||
|
### گزینه 1: خودکار (پیشنهادی)
|
||||||
|
فقط برنامه را اجرا کنید، Migration به صورت خودکار اعمال میشود:
|
||||||
|
```bash
|
||||||
|
cd GreenHome.Api
|
||||||
|
dotnet run
|
||||||
|
```
|
||||||
|
|
||||||
|
### گزینه 2: دستی
|
||||||
|
```bash
|
||||||
|
cd GreenHome.Infrastructure
|
||||||
|
dotnet ef database update --startup-project ../GreenHome.Api
|
||||||
|
```
|
||||||
|
|
||||||
|
## 📖 مثال استفاده
|
||||||
|
|
||||||
|
### قبل از تغییرات:
|
||||||
|
```json
|
||||||
|
POST /api/ai/ask
|
||||||
|
{
|
||||||
|
"question": "دمای مناسب چند است?"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### بعد از تغییرات:
|
||||||
|
```json
|
||||||
|
POST /api/ai/ask
|
||||||
|
{
|
||||||
|
"question": "دمای مناسب چند است؟",
|
||||||
|
"deviceId": 123,
|
||||||
|
"userId": 456
|
||||||
|
}
|
||||||
|
|
||||||
|
// Response:
|
||||||
|
{
|
||||||
|
"question": "دمای مناسب چند است؟",
|
||||||
|
"answer": "بین 20 تا 24 درجه...",
|
||||||
|
"deviceId": 123,
|
||||||
|
"tokens": {
|
||||||
|
"prompt": 15,
|
||||||
|
"completion": 85,
|
||||||
|
"total": 100
|
||||||
|
},
|
||||||
|
"responseTimeMs": 1234,
|
||||||
|
"timestamp": "2025-12-16T12:00:00Z"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🎯 مزایای جدید
|
||||||
|
|
||||||
|
1. ✅ **ردیابی کامل** - تمام سوالات و پاسخها ذخیره میشوند
|
||||||
|
2. ✅ **مدیریت هزینه** - میزان دقیق مصرف توکن قابل محاسبه است
|
||||||
|
3. ✅ **تحلیل عملکرد** - زمان پاسخدهی اندازهگیری میشود
|
||||||
|
4. ✅ **تاریخچه** - سوالات قبلی هر دستگاه قابل مشاهده است
|
||||||
|
5. ✅ **آمار** - آمار کلی و تفصیلی در دسترس است
|
||||||
|
6. ✅ **گزارشگیری** - امکان تولید گزارشهای مختلف
|
||||||
|
|
||||||
|
## 🔍 دریافت اطلاعات
|
||||||
|
|
||||||
|
### تاریخچه یک دستگاه:
|
||||||
|
```bash
|
||||||
|
GET /api/ai/history/device/123?take=50
|
||||||
|
```
|
||||||
|
|
||||||
|
### آمار کلی:
|
||||||
|
```bash
|
||||||
|
GET /api/ai/stats
|
||||||
|
```
|
||||||
|
|
||||||
|
### در کد C#:
|
||||||
|
```csharp
|
||||||
|
// تاریخچه دستگاه
|
||||||
|
var queries = await aiQueryService.GetDeviceQueriesAsync(123);
|
||||||
|
|
||||||
|
// مجموع توکنها
|
||||||
|
var totalTokens = await aiQueryService.GetDeviceTotalTokensAsync(123);
|
||||||
|
|
||||||
|
// آمار
|
||||||
|
var stats = await aiQueryService.GetStatsAsync();
|
||||||
|
```
|
||||||
|
|
||||||
|
## 📈 آمار قابل دسترسی
|
||||||
|
|
||||||
|
از endpoint `/api/ai/stats` میتوانید این اطلاعات را دریافت کنید:
|
||||||
|
- تعداد کل سوالات
|
||||||
|
- مجموع توکنهای استفاده شده
|
||||||
|
- توکنهای Prompt
|
||||||
|
- توکنهای Completion
|
||||||
|
- میانگین زمان پاسخ
|
||||||
|
- سوالات امروز
|
||||||
|
- توکنهای امروز
|
||||||
|
|
||||||
|
## ⚡ تغییرات Breaking
|
||||||
|
|
||||||
|
هیچ! تمام تغییرات backward compatible هستند:
|
||||||
|
- `deviceId` و `userId` اختیاری هستند
|
||||||
|
- API های قبلی همچنان کار میکنند
|
||||||
|
- فقط قابلیتهای جدید اضافه شدهاند
|
||||||
|
|
||||||
|
## 🧪 تست
|
||||||
|
|
||||||
|
### تست ذخیره سوال:
|
||||||
|
```bash
|
||||||
|
curl -X POST http://localhost:5000/api/ai/ask \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{
|
||||||
|
"question": "تست ذخیره سوال",
|
||||||
|
"deviceId": 1
|
||||||
|
}'
|
||||||
|
```
|
||||||
|
|
||||||
|
### تست دریافت تاریخچه:
|
||||||
|
```bash
|
||||||
|
curl http://localhost:5000/api/ai/history/device/1
|
||||||
|
```
|
||||||
|
|
||||||
|
### تست آمار:
|
||||||
|
```bash
|
||||||
|
curl http://localhost:5000/api/ai/stats
|
||||||
|
```
|
||||||
|
|
||||||
|
## 📚 فایلهای تغییر یافته
|
||||||
|
|
||||||
|
```
|
||||||
|
✅ Domain Layer:
|
||||||
|
- GreenHome.Domain/AIQuery.cs (جدید)
|
||||||
|
|
||||||
|
✅ Application Layer:
|
||||||
|
- GreenHome.Application/IAIQueryService.cs (جدید)
|
||||||
|
|
||||||
|
✅ Infrastructure Layer:
|
||||||
|
- GreenHome.Infrastructure/GreenHomeDbContext.cs (آپدیت)
|
||||||
|
- GreenHome.Infrastructure/AIQueryService.cs (جدید)
|
||||||
|
- GreenHome.Infrastructure/Migrations/20251216113127_AddAIQueryTable.cs (جدید)
|
||||||
|
|
||||||
|
✅ API Layer:
|
||||||
|
- GreenHome.Api/Controllers/AIController.cs (آپدیت)
|
||||||
|
- GreenHome.Api/Program.cs (آپدیت)
|
||||||
|
|
||||||
|
✅ Documentation:
|
||||||
|
- AI_QUERY_TRACKING.md (جدید)
|
||||||
|
- CHANGES_SUMMARY.md (جدید)
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🎉 آماده استفاده!
|
||||||
|
|
||||||
|
تمام تغییرات اعمال شده و سیستم آماده است. فقط کافی است:
|
||||||
|
1. برنامه را اجرا کنید
|
||||||
|
2. از API استفاده کنید
|
||||||
|
3. سوالات به صورت خودکار ذخیره میشوند!
|
||||||
|
|
||||||
|
برای اطلاعات بیشتر، فایل `AI_QUERY_TRACKING.md` را مطالعه کنید.
|
||||||
|
|
||||||
142
src/CHANGES_SUMMARY_ALERT_SYSTEM.md
Normal file
@@ -0,0 +1,142 @@
|
|||||||
|
# خلاصه تغییرات سیستم هشدار شرطی
|
||||||
|
|
||||||
|
## 📋 خلاصه کلی
|
||||||
|
|
||||||
|
سیستم هشدار قدیمی که بر اساس حداقل و حداکثر ثابت برای هر سنسور کار میکرد، به یک سیستم **شرطی پیشرفته** تبدیل شد که امکان تعریف شرایط پیچیده و انعطافپذیر را فراهم میکند.
|
||||||
|
|
||||||
|
## 🎯 ویژگیهای جدید
|
||||||
|
|
||||||
|
### 1. سیستم شرطگذاری پیشرفته
|
||||||
|
- تعریف نامحدود شرط برای هر دستگاه
|
||||||
|
- ترکیب چندین قانون با منطق AND
|
||||||
|
- انتخاب نوع اعلان (تماس یا پیامک) برای هر شرط
|
||||||
|
- تنظیم زمان اعمال شرط (روز، شب، همیشه)
|
||||||
|
|
||||||
|
### 2. مدیریت زمان هوشمند
|
||||||
|
- محاسبه خودکار طلوع و غروب خورشید بر اساس موقعیت جغرافیایی
|
||||||
|
- فیلتر کردن هشدارها بر اساس روز/شب بودن
|
||||||
|
- اضافه شدن فیلدهای استان، شهر، Latitude، Longitude به تنظیمات دستگاه
|
||||||
|
|
||||||
|
### 3. کنترل Cooldown جداگانه
|
||||||
|
- تنظیم فاصله زمانی مجزا برای تماس (پیشفرض 60 دقیقه)
|
||||||
|
- تنظیم فاصله زمانی مجزا برای پیامک (پیشفرض 15 دقیقه)
|
||||||
|
- قابل تنظیم برای هر شرط به صورت جداگانه
|
||||||
|
|
||||||
|
### 4. انواع مقایسه
|
||||||
|
- بیشتر از (GreaterThan)
|
||||||
|
- کمتر از (LessThan)
|
||||||
|
- بین دو عدد (Between)
|
||||||
|
- خارج از محدوده (OutOfRange)
|
||||||
|
|
||||||
|
## 🗂️ فایلهای ایجاد شده
|
||||||
|
|
||||||
|
### Domain Layer
|
||||||
|
- `GreenHome.Domain/AlertCondition.cs` - مدل شرط هشدار
|
||||||
|
- `GreenHome.Domain/AlertCondition.cs` (enums) - SensorType, ComparisonType, AlertNotificationType, AlertTimeType
|
||||||
|
|
||||||
|
### Application Layer
|
||||||
|
- `GreenHome.Application/IAlertConditionService.cs` - Interface سرویس مدیریت شرایط
|
||||||
|
- `GreenHome.Application/ISunCalculatorService.cs` - Interface محاسبه طلوع/غروب
|
||||||
|
- تغییرات در `GreenHome.Application/Dtos.cs` - DTOs جدید
|
||||||
|
|
||||||
|
### Infrastructure Layer
|
||||||
|
- `GreenHome.Infrastructure/AlertConditionService.cs` - سرویس مدیریت شرایط
|
||||||
|
- `GreenHome.Infrastructure/SunCalculatorService.cs` - سرویس محاسبه خورشید
|
||||||
|
- تغییرات در `GreenHome.Infrastructure/AlertService.cs` - بازنویسی کامل
|
||||||
|
- Migration جدید: `UpdateAlertSystemWithConditions`
|
||||||
|
|
||||||
|
### API Layer
|
||||||
|
- `GreenHome.Api/Controllers/AlertConditionsController.cs` - Controller جدید
|
||||||
|
|
||||||
|
## 🔄 فایلهای تغییر یافته
|
||||||
|
|
||||||
|
1. **GreenHome.Domain/DeviceSettings.cs**
|
||||||
|
- حذف فیلدهای Min/Max سنسورها
|
||||||
|
- اضافه فیلدهای Province, City, Latitude, Longitude
|
||||||
|
|
||||||
|
2. **GreenHome.Domain/AlertNotification.cs**
|
||||||
|
- تغییر از AlertType به AlertConditionId
|
||||||
|
- اضافه NotificationType
|
||||||
|
|
||||||
|
3. **GreenHome.Infrastructure/GreenHomeDbContext.cs**
|
||||||
|
- پیکربندی جداول جدید
|
||||||
|
- تغییر پیکربندی DeviceSettings و AlertNotifications
|
||||||
|
|
||||||
|
4. **GreenHome.Application/MappingProfile.cs**
|
||||||
|
- اضافه Mapping های جدید برای AlertCondition و AlertRule
|
||||||
|
|
||||||
|
5. **GreenHome.Api/Program.cs**
|
||||||
|
- ثبت IAlertConditionService
|
||||||
|
- ثبت ISunCalculatorService
|
||||||
|
|
||||||
|
6. **GreenHome.Infrastructure/GreenHome.Infrastructure.csproj**
|
||||||
|
- اضافه reference به GreenHome.VoiceCall.Avanak
|
||||||
|
|
||||||
|
## 📊 تغییرات Database
|
||||||
|
|
||||||
|
### جداول جدید:
|
||||||
|
- **AlertConditions**: شرایط هشدار
|
||||||
|
- **AlertRules**: قوانین مربوط به هر شرط
|
||||||
|
|
||||||
|
### جداول تغییر یافته:
|
||||||
|
- **DeviceSettings**:
|
||||||
|
- حذف: DangerMaxTemperature, DangerMinTemperature, MaxTemperature, MinTemperature, MaxGasPPM, MinGasPPM, MaxLux, MinLux, MaxHumidityPercent, MinHumidityPercent
|
||||||
|
- اضافه: Province, City, Latitude, Longitude
|
||||||
|
|
||||||
|
- **AlertNotifications**:
|
||||||
|
- حذف: AlertType
|
||||||
|
- اضافه: AlertConditionId, NotificationType
|
||||||
|
|
||||||
|
## 🔌 API Endpoints جدید
|
||||||
|
|
||||||
|
```
|
||||||
|
GET /api/AlertConditions/device/{deviceId} - لیست شرایط یک دستگاه
|
||||||
|
GET /api/AlertConditions/{id} - دریافت یک شرط
|
||||||
|
POST /api/AlertConditions - ایجاد شرط جدید
|
||||||
|
PUT /api/AlertConditions - بهروزرسانی شرط
|
||||||
|
DELETE /api/AlertConditions/{id} - حذف شرط
|
||||||
|
PATCH /api/AlertConditions/{id}/toggle - فعال/غیرفعال کردن شرط
|
||||||
|
```
|
||||||
|
|
||||||
|
## ⚙️ نحوه استفاده
|
||||||
|
|
||||||
|
### مثال ایجاد شرط:
|
||||||
|
```json
|
||||||
|
POST /api/AlertConditions
|
||||||
|
{
|
||||||
|
"deviceId": 1,
|
||||||
|
"notificationType": 1, // SMS
|
||||||
|
"timeType": 0, // Day only
|
||||||
|
"smsCooldownMinutes": 15,
|
||||||
|
"rules": [
|
||||||
|
{
|
||||||
|
"sensorType": 0, // Temperature
|
||||||
|
"comparisonType": 0, // GreaterThan
|
||||||
|
"value1": 35.0,
|
||||||
|
"order": 0
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
این شرط میگوید: **اگر در روز، دما بیشتر از 35 درجه شد، هر 15 دقیقه یکبار پیامک بفرست.**
|
||||||
|
|
||||||
|
## ⚠️ نکات مهم
|
||||||
|
|
||||||
|
1. **Migration**: حتماً قبل از اجرای migration از database بکآپ بگیرید
|
||||||
|
2. **Data Loss**: فیلدهای قدیمی Min/Max حذف میشوند و قابل بازگشت نیستند
|
||||||
|
3. **Location**: برای استفاده از قابلیت Day/Night، باید Latitude و Longitude را در تنظیمات دستگاه وارد کنید
|
||||||
|
4. **Backward Compatibility**: سیستم قدیمی دیگر کار نمیکند و باید شرایط جدید تعریف شوند
|
||||||
|
|
||||||
|
## 📝 TODO برای آینده
|
||||||
|
|
||||||
|
- [ ] پیادهسازی کامل تماس صوتی (در حال حاضر placeholder است)
|
||||||
|
- [ ] اضافه کردن تستهای واحد
|
||||||
|
- [ ] اضافه کردن Validation برای DTOs
|
||||||
|
- [ ] پیادهسازی Logging بهتر برای Debug
|
||||||
|
- [ ] اضافه کردن Dashboard برای مشاهده تاریخچه هشدارها
|
||||||
|
|
||||||
|
## 📚 مستندات
|
||||||
|
|
||||||
|
برای اطلاعات بیشتر، فایل `ALERT_SYSTEM_UPDATE.md` را مطالعه کنید.
|
||||||
|
|
||||||
145
src/DAILY_REPORT_API.md
Normal file
@@ -0,0 +1,145 @@
|
|||||||
|
# API گزارش تحلیل روزانه گلخانه
|
||||||
|
|
||||||
|
این API برای دریافت تحلیل هوشمصنوعی روزانه از دادههای تلمتری گلخانه طراحی شده است.
|
||||||
|
|
||||||
|
## اندپوینت
|
||||||
|
|
||||||
|
```
|
||||||
|
GET /api/DailyReport
|
||||||
|
```
|
||||||
|
|
||||||
|
## پارامترها
|
||||||
|
|
||||||
|
| پارامتر | نوع | الزامی | توضیحات |
|
||||||
|
|---------|-----|--------|----------|
|
||||||
|
| `deviceId` | int | بله | شناسه دستگاه |
|
||||||
|
| `persianDate` | string | بله | تاریخ شمسی به فرمت `yyyy/MM/dd` (مثال: `1403/09/26`) |
|
||||||
|
|
||||||
|
## مثال درخواست
|
||||||
|
|
||||||
|
```http
|
||||||
|
GET /api/DailyReport?deviceId=1&persianDate=1403/09/26
|
||||||
|
```
|
||||||
|
|
||||||
|
## پاسخ موفق (200 OK)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"id": 15,
|
||||||
|
"deviceId": 1,
|
||||||
|
"deviceName": "گلخانه اول",
|
||||||
|
"persianDate": "1403/09/26",
|
||||||
|
"analysis": "**وضعیت کلی:**\n\nدر طول روز 1403/09/26، شرایط گلخانه به طور کلی مطلوب بوده است. دمای متوسط حدود 25 درجه سانتیگراد، رطوبت 65 درصد و نور کافی (حدود 5000 لوکس) ثبت شده است. کیفیت هوا نیز با مقادیر CO در محدوده ایمن (کمتر از 100 PPM) مناسب بوده است.\n\n**روندهای مشاهده شده:**\n\n- دما در طول روز از 18 درجه صبح به 32 درجه ظهر رسیده و سپس کاهش یافته است.\n- رطوبت هوا در ساعات ظهر کاهش یافته ولی شب مجدداً افزایش یافته.\n- نور در ساعات صبح تا عصر در حد مطلوب و شب صفر بوده است.\n- مقادیر CO در کل روز در سطح ایمن باقی مانده.\n\n**نکات و هشدارها:**\n\n- دمای ظهر (32 درجه) کمی بالاست. توصیه میشود سیستم تهویه را بهبود دهید.\n- رطوبت شب بیش از حد است (85 درصد) که ممکن است منجر به رشد قارچ شود.\n\n**پیشنهادات:**\n\n1. نصب سیستم سایهبان خودکار برای کنترل دمای ظهر\n2. استفاده از هواکش در شب برای کاهش رطوبت\n3. بررسی سیستم آبیاری برای جلوگیری از رطوبت اضافی",
|
||||||
|
"recordCount": 288,
|
||||||
|
"sampledRecordCount": 15,
|
||||||
|
"totalTokens": 1250,
|
||||||
|
"createdAt": "2024-12-16T14:30:00Z",
|
||||||
|
"fromCache": false
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## پاسخهای خطا
|
||||||
|
|
||||||
|
### 400 Bad Request
|
||||||
|
درخواست نامعتبر (شناسه دستگاه یا فرمت تاریخ اشتباه)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"error": "تاریخ شمسی باید به فرمت yyyy/MM/dd باشد"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 404 Not Found
|
||||||
|
دستگاه یا دادهای برای تاریخ مورد نظر یافت نشد
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"error": "هیچ رکوردی برای دستگاه 1 در تاریخ 1403/09/26 یافت نشد"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 500 Internal Server Error
|
||||||
|
خطای سرور (مثلاً خطا در ارتباط با DeepSeek API)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"error": "خطای سرور در پردازش درخواست"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## نحوه عملکرد
|
||||||
|
|
||||||
|
1. **بررسی کش:** ابتدا سیستم چک میکند آیا برای این دستگاه و تاریخ، گزارشی قبلاً ایجاد شده یا نه. اگر وجود داشته باشد، همان گزارش برگردانده میشود (`fromCache: true`) و توکن جدیدی مصرف نمیشود.
|
||||||
|
|
||||||
|
2. **استخراج دادهها:** اگر گزارش موجود نباشد، تمام رکوردهای تلمتری آن روز از دیتابیس استخراج میشوند.
|
||||||
|
|
||||||
|
3. **نمونهبرداری:** دادهها بر اساس زمان سورت میشوند و سپس از هر 20 رکورد، فقط رکورد اول انتخاب میشود. این کار برای کاهش مصرف توکن و بهینهسازی هزینه انجام میشود.
|
||||||
|
|
||||||
|
4. **ارسال به AI:** دادههای نمونهبرداری شده در قالب یک جدول ساختاریافته به DeepSeek API ارسال میشوند با درخواست تحلیل خلاصه.
|
||||||
|
|
||||||
|
5. **ذخیرهسازی:** پاسخ دریافتی به همراه اطلاعات مصرف توکن در دیتابیس ذخیره میشود.
|
||||||
|
|
||||||
|
6. **بازگشت نتیجه:** گزارش تحلیل به کاربر برگردانده میشود.
|
||||||
|
|
||||||
|
## فیلدهای تحلیل شده
|
||||||
|
|
||||||
|
API دادههای زیر را برای تحلیل در نظر میگیرد:
|
||||||
|
|
||||||
|
- **زمان** (TimestampUtc) - زمان ثبت داده
|
||||||
|
- **دما** (TemperatureC) - دمای محیط به درجه سانتیگراد
|
||||||
|
- **رطوبت** (HumidityPercent) - درصد رطوبت هوا
|
||||||
|
- **نور** (Lux) - شدت نور به لوکس
|
||||||
|
- **CO** (GasPPM) - مقدار گاز CO به PPM
|
||||||
|
|
||||||
|
## مدیریت توکن
|
||||||
|
|
||||||
|
- هر درخواست جدید توکن مصرف میکند (معمولاً 800-1500 توکن)
|
||||||
|
- گزارشهای cache شده هیچ توکن اضافی مصرف نمیکنند
|
||||||
|
- نمونهبرداری 1 از 20 رکورد، مصرف توکن را تا 95% کاهش میدهد
|
||||||
|
- اطلاعات دقیق مصرف توکن در فیلد `totalTokens` برگردانده میشود
|
||||||
|
|
||||||
|
## جدول دیتابیس
|
||||||
|
|
||||||
|
گزارشها در جدول `DailyReports` ذخیره میشوند:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE TABLE DailyReports (
|
||||||
|
Id INT PRIMARY KEY IDENTITY(1,1),
|
||||||
|
DeviceId INT NOT NULL,
|
||||||
|
PersianDate NVARCHAR(10) NOT NULL,
|
||||||
|
PersianYear INT NOT NULL,
|
||||||
|
PersianMonth INT NOT NULL,
|
||||||
|
PersianDay INT NOT NULL,
|
||||||
|
Analysis NVARCHAR(MAX) NOT NULL,
|
||||||
|
RecordCount INT NOT NULL,
|
||||||
|
SampledRecordCount INT NOT NULL,
|
||||||
|
PromptTokens INT NOT NULL,
|
||||||
|
CompletionTokens INT NOT NULL,
|
||||||
|
TotalTokens INT NOT NULL,
|
||||||
|
Model NVARCHAR(100),
|
||||||
|
CreatedAt DATETIME2 NOT NULL,
|
||||||
|
ResponseTimeMs BIGINT,
|
||||||
|
CONSTRAINT FK_DailyReports_Devices FOREIGN KEY (DeviceId)
|
||||||
|
REFERENCES Devices(Id) ON DELETE CASCADE,
|
||||||
|
CONSTRAINT UQ_DailyReports_DeviceDate UNIQUE (DeviceId, PersianDate)
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
## نکات مهم
|
||||||
|
|
||||||
|
1. **یکتایی گزارش:** برای هر دستگاه و تاریخ، فقط یک گزارش ذخیره میشود (UNIQUE constraint)
|
||||||
|
2. **کش خودکار:** سیستم به طور خودکار از گزارشهای قبلی استفاده میکند
|
||||||
|
3. **حذف cascade:** با حذف دستگاه، تمام گزارشهای آن نیز حذف میشوند
|
||||||
|
4. **زمان ایران:** زمانها در API به timezone ایران (UTC+3:30) تبدیل میشوند
|
||||||
|
5. **خطاهای لاگ:** تمام خطاها و عملیات در لاگ سیستم ثبت میشوند
|
||||||
|
|
||||||
|
## Migration
|
||||||
|
|
||||||
|
برای اعمال تغییرات دیتابیس، migration زیر را اجرا کنید:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
dotnet ef database update --project GreenHome.Infrastructure --startup-project GreenHome.Api
|
||||||
|
```
|
||||||
|
|
||||||
|
یا به صورت خودکار در startup برنامه اعمال میشود.
|
||||||
|
|
||||||
358
src/DEEPSEEK_INTEGRATION.md
Normal file
@@ -0,0 +1,358 @@
|
|||||||
|
# 🎉 سرویس DeepSeek با موفقیت به پروژه GreenHome اضافه شد!
|
||||||
|
|
||||||
|
## ✅ کارهای انجام شده
|
||||||
|
|
||||||
|
### 1. پروژه جدید: GreenHome.AI.DeepSeek
|
||||||
|
یک کتابخانه کامل و مستقل برای اتصال به API DeepSeek ایجاد شد.
|
||||||
|
|
||||||
|
**فایلهای ایجاد شده:**
|
||||||
|
- ✅ `IDeepSeekService.cs` - Interface سرویس
|
||||||
|
- ✅ `DeepSeekService.cs` - پیادهسازی با HttpClient
|
||||||
|
- ✅ `DeepSeekOptions.cs` - کلاس تنظیمات
|
||||||
|
- ✅ `Models.cs` - مدلهای Request/Response
|
||||||
|
- ✅ `ServiceCollectionExtensions.cs` - Dependency Injection
|
||||||
|
|
||||||
|
**مستندات:**
|
||||||
|
- 📚 `README.md` - مستندات کامل فارسی
|
||||||
|
- 📖 `USAGE_FA.md` - راهنمای استفاده
|
||||||
|
- ⚡ `QUICKSTART.md` - راهنمای سریع شروع
|
||||||
|
- 📋 `SUMMARY.md` - خلاصه پروژه
|
||||||
|
|
||||||
|
### 2. Controller جدید: AIController
|
||||||
|
یک API Controller با 3 endpoint اصلی:
|
||||||
|
|
||||||
|
```
|
||||||
|
POST /api/ai/ask - پرسیدن سوال ساده
|
||||||
|
POST /api/ai/chat - چت پیشرفته با تاریخچه
|
||||||
|
POST /api/ai/suggest - دریافت پیشنهادات برای خانه هوشمند
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. تنظیمات
|
||||||
|
|
||||||
|
**Program.cs:**
|
||||||
|
```csharp
|
||||||
|
using GreenHome.AI.DeepSeek;
|
||||||
|
// ...
|
||||||
|
builder.Services.AddDeepSeek(builder.Configuration);
|
||||||
|
```
|
||||||
|
|
||||||
|
**appsettings.json:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"DeepSeek": {
|
||||||
|
"BaseUrl": "https://api.deepseek.com",
|
||||||
|
"ApiKey": "YOUR_DEEPSEEK_API_KEY_HERE",
|
||||||
|
"DefaultModel": "deepseek-chat",
|
||||||
|
"DefaultTemperature": 1.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🎯 قابلیتها
|
||||||
|
|
||||||
|
✅ **اتصال به API رسمی DeepSeek**
|
||||||
|
- پشتیبانی کامل از Chat Completion API
|
||||||
|
- سازگار با استاندارد OpenAI
|
||||||
|
|
||||||
|
✅ **دو روش استفاده**
|
||||||
|
- `AskSimpleAsync()` - برای سوالات ساده
|
||||||
|
- `AskAsync()` - برای چت پیشرفته با تاریخچه
|
||||||
|
|
||||||
|
✅ **پیکربندی آسان**
|
||||||
|
- Configuration از appsettings.json
|
||||||
|
- پشتیبانی از User Secrets (Development)
|
||||||
|
- پشتیبانی از Environment Variables (Production)
|
||||||
|
|
||||||
|
✅ **امکانات پیشرفته**
|
||||||
|
- تنظیم Temperature (خلاقیت AI)
|
||||||
|
- تنظیم MaxTokens (طول پاسخ)
|
||||||
|
- انتخاب Model
|
||||||
|
- System Prompt برای زمینهسازی
|
||||||
|
|
||||||
|
✅ **Production Ready**
|
||||||
|
- Logging کامل
|
||||||
|
- مدیریت خطا
|
||||||
|
- HttpClient Factory
|
||||||
|
- Dependency Injection
|
||||||
|
- Timeout Management
|
||||||
|
|
||||||
|
## 📖 نحوه استفاده
|
||||||
|
|
||||||
|
### در Controller:
|
||||||
|
```csharp
|
||||||
|
public class MyController : ControllerBase
|
||||||
|
{
|
||||||
|
private readonly IDeepSeekService _ai;
|
||||||
|
|
||||||
|
public MyController(IDeepSeekService ai)
|
||||||
|
{
|
||||||
|
_ai = ai;
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost("analyze")]
|
||||||
|
public async Task<IActionResult> AnalyzeData(string data)
|
||||||
|
{
|
||||||
|
var result = await _ai.AskSimpleAsync(
|
||||||
|
$"تحلیل کن: {data}",
|
||||||
|
"شما یک متخصص خانه هوشمند هستید"
|
||||||
|
);
|
||||||
|
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### در Service:
|
||||||
|
```csharp
|
||||||
|
public class SmartHomeService
|
||||||
|
{
|
||||||
|
private readonly IDeepSeekService _ai;
|
||||||
|
|
||||||
|
public SmartHomeService(IDeepSeekService ai)
|
||||||
|
{
|
||||||
|
_ai = ai;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<string> GetSuggestion(double temp, int humidity)
|
||||||
|
{
|
||||||
|
return await _ai.AskSimpleAsync(
|
||||||
|
$"دمای {temp}°C و رطوبت {humidity}% داریم. چه کنیم؟"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🚀 شروع کار
|
||||||
|
|
||||||
|
### گام 1: دریافت API Key
|
||||||
|
1. به https://platform.deepseek.com بروید
|
||||||
|
2. ثبتنام کنید
|
||||||
|
3. API Key بسازید
|
||||||
|
|
||||||
|
### گام 2: تنظیم API Key
|
||||||
|
```bash
|
||||||
|
# Development (User Secrets)
|
||||||
|
dotnet user-secrets set "DeepSeek:ApiKey" "YOUR_KEY_HERE"
|
||||||
|
|
||||||
|
# Production (Environment Variable)
|
||||||
|
export DeepSeek__ApiKey="YOUR_KEY_HERE"
|
||||||
|
```
|
||||||
|
|
||||||
|
### گام 3: اجرا و تست
|
||||||
|
```bash
|
||||||
|
cd GreenHome.Api
|
||||||
|
dotnet run
|
||||||
|
|
||||||
|
# تست با curl
|
||||||
|
curl -X POST http://localhost:5000/api/ai/ask \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{"question":"سلام! کار میکنی؟"}'
|
||||||
|
```
|
||||||
|
|
||||||
|
## 📊 Swagger UI
|
||||||
|
بعد از اجرا، به آدرس زیر بروید:
|
||||||
|
```
|
||||||
|
http://localhost:5000/swagger
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🌟 مثالهای کاربردی
|
||||||
|
|
||||||
|
### 1. تحلیل سنسور
|
||||||
|
```csharp
|
||||||
|
var sensorData = $@"
|
||||||
|
دمای اتاق خواب: {bedroom.Temperature}°C
|
||||||
|
رطوبت: {bedroom.Humidity}%
|
||||||
|
کیفیت هوا: {airQuality}
|
||||||
|
نور: {lightLevel} لوکس
|
||||||
|
";
|
||||||
|
|
||||||
|
var analysis = await _ai.AskSimpleAsync(
|
||||||
|
$"تحلیل کن و پیشنهاد بده:\n{sensorData}",
|
||||||
|
"شما یک متخصص خانه هوشمند هستید"
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. دستیار صوتی
|
||||||
|
```csharp
|
||||||
|
public async Task<string> ProcessVoiceCommand(string command)
|
||||||
|
{
|
||||||
|
var response = await _ai.AskSimpleAsync(
|
||||||
|
command,
|
||||||
|
"شما دستیار صوتی خانه هوشمند هستید. پاسخ کوتاه و مفید بده."
|
||||||
|
);
|
||||||
|
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. چت با حافظه
|
||||||
|
```csharp
|
||||||
|
var conversation = new List<ChatMessage>
|
||||||
|
{
|
||||||
|
new() { Role = "system", Content = "شما دستیار خانه هوشمند هستید" }
|
||||||
|
};
|
||||||
|
|
||||||
|
// اضافه کردن تاریخچه از database
|
||||||
|
foreach (var msg in history)
|
||||||
|
{
|
||||||
|
conversation.Add(new ChatMessage
|
||||||
|
{
|
||||||
|
Role = msg.Role,
|
||||||
|
Content = msg.Content
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// پیام جدید کاربر
|
||||||
|
conversation.Add(new ChatMessage
|
||||||
|
{
|
||||||
|
Role = "user",
|
||||||
|
Content = userMessage
|
||||||
|
});
|
||||||
|
|
||||||
|
var response = await _ai.AskAsync(new ChatRequest
|
||||||
|
{
|
||||||
|
Messages = conversation
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. هشدار هوشمند
|
||||||
|
```csharp
|
||||||
|
public async Task<string> GenerateAlert(TelemetryRecord record)
|
||||||
|
{
|
||||||
|
if (record.Temperature > 30)
|
||||||
|
{
|
||||||
|
return await _ai.AskSimpleAsync(
|
||||||
|
$"دمای {record.Temperature} درجه است. چه هشداری بدهیم؟",
|
||||||
|
"پیام هشدار کوتاه و واضح بنویس"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 💡 نکات مهم
|
||||||
|
|
||||||
|
### امنیت
|
||||||
|
⚠️ **هرگز API Key را در Git commit نکنید!**
|
||||||
|
- از User Secrets در Development
|
||||||
|
- از Environment Variables در Production
|
||||||
|
|
||||||
|
### هزینه
|
||||||
|
💰 **هر درخواست هزینه دارد**
|
||||||
|
- بر اساس تعداد توکن
|
||||||
|
- پاسخهای مشابه را Cache کنید
|
||||||
|
- MaxTokens را محدود کنید
|
||||||
|
|
||||||
|
### عملکرد
|
||||||
|
⚡ **بهینهسازی**
|
||||||
|
- درخواستهای طولانی = زمان بیشتر
|
||||||
|
- Temperature پایینتر = سریعتر
|
||||||
|
- Cache برای سوالات تکراری
|
||||||
|
|
||||||
|
## 🐛 عیبیابی
|
||||||
|
|
||||||
|
| خطا | دلیل | راه حل |
|
||||||
|
|-----|------|--------|
|
||||||
|
| 401 Unauthorized | API Key نامعتبر | بررسی API Key |
|
||||||
|
| 429 Too Many Requests | درخواست زیاد | صبر کنید |
|
||||||
|
| Timeout | درخواست طولانی | MaxTokens را کاهش دهید |
|
||||||
|
| Connection Error | اینترنت قطع | بررسی اتصال |
|
||||||
|
|
||||||
|
## 📚 مستندات
|
||||||
|
|
||||||
|
### در پروژه:
|
||||||
|
- **کامل:** `GreenHome.AI.DeepSeek/README.md`
|
||||||
|
- **سریع:** `GreenHome.AI.DeepSeek/QUICKSTART.md`
|
||||||
|
- **استفاده:** `GreenHome.AI.DeepSeek/USAGE_FA.md`
|
||||||
|
- **خلاصه:** `GreenHome.AI.DeepSeek/SUMMARY.md`
|
||||||
|
|
||||||
|
### آنلاین:
|
||||||
|
- https://platform.deepseek.com/docs
|
||||||
|
- https://platform.deepseek.com/api-docs
|
||||||
|
- https://platform.deepseek.com/pricing
|
||||||
|
|
||||||
|
## 🎓 مثالهای بیشتر
|
||||||
|
|
||||||
|
### Automation Rule Generator
|
||||||
|
```csharp
|
||||||
|
public async Task<string> GenerateAutomationRule(string description)
|
||||||
|
{
|
||||||
|
var prompt = $@"
|
||||||
|
یک قانون اتوماسیون بساز:
|
||||||
|
{description}
|
||||||
|
|
||||||
|
فرمت خروجی JSON:
|
||||||
|
{{
|
||||||
|
""trigger"": ""..."",
|
||||||
|
""condition"": ""..."",
|
||||||
|
""action"": ""...""
|
||||||
|
}}
|
||||||
|
";
|
||||||
|
|
||||||
|
return await _ai.AskSimpleAsync(prompt);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Energy Optimization
|
||||||
|
```csharp
|
||||||
|
public async Task<EnergyReport> AnalyzeEnergyUsage(EnergyData data)
|
||||||
|
{
|
||||||
|
var analysis = await _ai.AskSimpleAsync(
|
||||||
|
$"مصرف برق: {data.PowerUsage}W، روشنایی: {data.LightCount}، کولر: {data.ACStatus}. چطور بهینه کنیم?",
|
||||||
|
"شما متخصص صرفهجویی انرژی هستید"
|
||||||
|
);
|
||||||
|
|
||||||
|
return ParseEnergyReport(analysis);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Natural Language Control
|
||||||
|
```csharp
|
||||||
|
public async Task<DeviceCommand> ParseCommand(string text)
|
||||||
|
{
|
||||||
|
var json = await _ai.AskSimpleAsync(
|
||||||
|
$@"این دستور را به JSON تبدیل کن: ""{text}""
|
||||||
|
فرمت: {{""device"": ""..."", ""action"": ""..."", ""value"": ""...""}}",
|
||||||
|
"فقط JSON خروجی بده، توضیح ندهید"
|
||||||
|
);
|
||||||
|
|
||||||
|
return JsonSerializer.Deserialize<DeviceCommand>(json);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## ✨ امکانات آینده
|
||||||
|
|
||||||
|
بعداً میتوانید اضافه کنید:
|
||||||
|
- [ ] Streaming Response (real-time)
|
||||||
|
- [ ] Function Calling (control devices)
|
||||||
|
- [ ] Image Analysis (camera feeds)
|
||||||
|
- [ ] Voice Integration
|
||||||
|
- [ ] Multi-language Support
|
||||||
|
- [ ] Context Memory in Database
|
||||||
|
- [ ] Rate Limiting
|
||||||
|
- [ ] Response Caching
|
||||||
|
- [ ] Analytics & Monitoring
|
||||||
|
|
||||||
|
## 🤝 مشارکت
|
||||||
|
|
||||||
|
برای گزارش مشکل یا پیشنهاد:
|
||||||
|
1. Issue در GitHub بسازید
|
||||||
|
2. یا تغییرات را Pull Request کنید
|
||||||
|
|
||||||
|
## 📄 لایسنس
|
||||||
|
|
||||||
|
این پروژه تحت لایسنس MIT است.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🎉 تمام! آماده استفاده است!
|
||||||
|
|
||||||
|
حالا میتوانید:
|
||||||
|
1. ✅ API Key بگیرید
|
||||||
|
2. ✅ در appsettings قرار دهید
|
||||||
|
3. ✅ برنامه را اجرا کنید
|
||||||
|
4. ✅ از AI در پروژه استفاده کنید
|
||||||
|
|
||||||
|
**موفق باشید! 🚀**
|
||||||
|
|
||||||
243
src/DEVICE_TOKEN_API.md
Normal file
@@ -0,0 +1,243 @@
|
|||||||
|
# API مدیریت توکن و تنظیمات دستگاه
|
||||||
|
|
||||||
|
این سند توضیح دهنده API های جدید اضافه شده برای مدیریت توکن و تنظیمات دستگاه است.
|
||||||
|
|
||||||
|
## تغییرات در مدل داده
|
||||||
|
|
||||||
|
### فیلدهای جدید در `DeviceSettings`
|
||||||
|
|
||||||
|
1. **UploadIntervalMin** (int): فاصله زمانی آپلود داده به دقیقه (پیشفرض: 5)
|
||||||
|
2. **DevicePhoneNumber** (string): شماره تلفن دستگاه
|
||||||
|
3. **SimCardType** (enum, nullable): نوع سیمکارت (همراه اول/ایرانسل/رایتل)
|
||||||
|
4. **TokenCode** (string, nullable): کد توکن 5 رقمی
|
||||||
|
5. **VerificationCode** (string, nullable): کد تایید 5 رقمی
|
||||||
|
6. **TokenExpiresAt** (DateTime, nullable): تاریخ انقضای توکن
|
||||||
|
|
||||||
|
### Enum نوع سیمکارت
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
public enum SimCardType
|
||||||
|
{
|
||||||
|
Hamrahe_Aval = 1, // همراه اول
|
||||||
|
Irancell = 2, // ایرانسل
|
||||||
|
Rightel = 3 // رایتل
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## API Endpoints
|
||||||
|
|
||||||
|
### 1. دریافت فاصله زمانی آپلود
|
||||||
|
|
||||||
|
**GET** `/api/DeviceToken/upload-interval`
|
||||||
|
|
||||||
|
دریافت مقدار `UPLOAD_INTERVAL_MIN` بر اساس شناسه دستگاه یا شماره تلفن.
|
||||||
|
|
||||||
|
#### پارامترها (Query String)
|
||||||
|
|
||||||
|
- `deviceId` (int, optional): شناسه دستگاه
|
||||||
|
- `devicePhoneNumber` (string, optional): شماره تلفن دستگاه
|
||||||
|
|
||||||
|
**نکته:** حداقل یکی از پارامترها باید ارسال شود.
|
||||||
|
|
||||||
|
#### مثال درخواست
|
||||||
|
|
||||||
|
```http
|
||||||
|
GET /api/DeviceToken/upload-interval?devicePhoneNumber=09123456789
|
||||||
|
```
|
||||||
|
|
||||||
|
#### پاسخ موفق
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"message": null,
|
||||||
|
"uploadIntervalMin": 5
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### پاسخ خطا
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": false,
|
||||||
|
"message": "دستگاه یافت نشد",
|
||||||
|
"uploadIntervalMin": null
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 2. درخواست توکن دستگاه
|
||||||
|
|
||||||
|
**POST** `/api/DeviceToken/request-token`
|
||||||
|
|
||||||
|
تولید کد توکن 5 رقمی و ارسال آن از طریق پیامک به شماره دستگاه.
|
||||||
|
|
||||||
|
#### بدنه درخواست (JSON)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"devicePhoneNumber": "09123456789"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### مثال درخواست
|
||||||
|
|
||||||
|
```http
|
||||||
|
POST /api/DeviceToken/request-token
|
||||||
|
Content-Type: application/json
|
||||||
|
|
||||||
|
{
|
||||||
|
"devicePhoneNumber": "09123456789"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### پاسخ موفق
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"message": "کد تایید با موفقیت ارسال شد",
|
||||||
|
"tokenCode": "12345"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**نکته:** پیامک حاوی کد توکن به شماره مشخص شده ارسال میشود. کد دارای اعتبار 10 دقیقه است.
|
||||||
|
|
||||||
|
#### محاسبه کد تایید
|
||||||
|
|
||||||
|
کد تایید بر اساس فرمول زیر محاسبه میشود:
|
||||||
|
|
||||||
|
```
|
||||||
|
VerificationCode = (TokenCode × 7 + 12345) % 100000
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3. تایید توکن دستگاه
|
||||||
|
|
||||||
|
**POST** `/api/DeviceToken/verify-token`
|
||||||
|
|
||||||
|
تایید کد تایید و ارسال تنظیمات کدشده دستگاه از طریق پیامک.
|
||||||
|
|
||||||
|
#### بدنه درخواست (JSON)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"devicePhoneNumber": "09123456789",
|
||||||
|
"verificationCode": "98765"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### مثال درخواست
|
||||||
|
|
||||||
|
```http
|
||||||
|
POST /api/DeviceToken/verify-token
|
||||||
|
Content-Type: application/json
|
||||||
|
|
||||||
|
{
|
||||||
|
"devicePhoneNumber": "09123456789",
|
||||||
|
"verificationCode": "98765"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### پاسخ موفق
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"message": "تنظیمات با موفقیت ارسال شد",
|
||||||
|
"encodedSettings": "RGV2aWNlMDF8NQ=="
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**نکته:** تنظیمات به صورت کدشده Base64 ارسال میشود. فرمت قبل از کدگذاری: `{DeviceName}|{UploadIntervalMin}`
|
||||||
|
|
||||||
|
#### پاسخ خطا
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": false,
|
||||||
|
"message": "کد تایید نادرست است",
|
||||||
|
"encodedSettings": null
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 4. بروزرسانی تنظیمات دستگاه
|
||||||
|
|
||||||
|
**PUT** `/api/DeviceSettings`
|
||||||
|
|
||||||
|
API موجود که حالا فیلدهای جدید را نیز پشتیبانی میکند.
|
||||||
|
|
||||||
|
#### بدنه درخواست (JSON)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"deviceId": 1,
|
||||||
|
"province": "تهران",
|
||||||
|
"city": "تهران",
|
||||||
|
"productType": "گلخانه",
|
||||||
|
"uploadIntervalMin": 5,
|
||||||
|
"devicePhoneNumber": "09123456789",
|
||||||
|
"simCardType": 1,
|
||||||
|
"minimumSmsIntervalMinutes": 15,
|
||||||
|
"minimumCallIntervalMinutes": 60
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## فلوی کاری (Workflow)
|
||||||
|
|
||||||
|
### سناریو: دریافت تنظیمات دستگاه
|
||||||
|
|
||||||
|
1. **دستگاه درخواست توکن میکند:**
|
||||||
|
```http
|
||||||
|
POST /api/DeviceToken/request-token
|
||||||
|
Body: { "devicePhoneNumber": "09123456789" }
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **سرور کد توکن تولید و ارسال میکند:**
|
||||||
|
- کد توکن 5 رقمی: مثلاً `12345`
|
||||||
|
- کد تایید محاسبه شده: `(12345 × 7 + 12345) % 100000 = 98760`
|
||||||
|
- پیامک حاوی کد توکن به شماره دستگاه ارسال میشود
|
||||||
|
|
||||||
|
3. **دستگاه کد تایید را محاسبه و ارسال میکند:**
|
||||||
|
```http
|
||||||
|
POST /api/DeviceToken/verify-token
|
||||||
|
Body: {
|
||||||
|
"devicePhoneNumber": "09123456789",
|
||||||
|
"verificationCode": "98760"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
4. **سرور تنظیمات کدشده را ارسال میکند:**
|
||||||
|
- تنظیمات: `Device01|5`
|
||||||
|
- Base64: `RGV2aWNlMDF8NQ==`
|
||||||
|
- پیامک حاوی تنظیمات کدشده به شماره دستگاه ارسال میشود
|
||||||
|
|
||||||
|
5. **دستگاه تنظیمات را decode کرده و اعمال میکند**
|
||||||
|
|
||||||
|
## نکات امنیتی
|
||||||
|
|
||||||
|
1. کد توکن فقط 10 دقیقه اعتبار دارد
|
||||||
|
2. پس از تایید موفق، کدهای توکن و تایید از دیتابیس پاک میشوند
|
||||||
|
3. کدگذاری Base64 یک کدگذاری ساده است و برای امنیت بیشتر میتوان از روشهای پیچیدهتر استفاده کرد
|
||||||
|
|
||||||
|
## Migration
|
||||||
|
|
||||||
|
Migration با نام `AddDeviceTokenAndPhoneFields` ایجاد و به دیتابیس اعمال شده است.
|
||||||
|
|
||||||
|
برای اعمال دستی (در صورت نیاز):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
dotnet ef database update --project GreenHome.Infrastructure --startup-project GreenHome.Api
|
||||||
|
```
|
||||||
|
|
||||||
|
## تست API ها
|
||||||
|
|
||||||
|
میتوانید از Swagger UI (که در حالت Development در `/scalar/v1` در دسترس است) برای تست API ها استفاده کنید.
|
||||||
|
|
||||||
|
یا از ابزارهایی مانند Postman/Insomnia با استفاده از نمونههای بالا.
|
||||||
|
|
||||||
33
src/GreenHome.AI.DeepSeek/DeepSeekOptions.cs
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
namespace GreenHome.AI.DeepSeek;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Configuration options for DeepSeek AI service
|
||||||
|
/// </summary>
|
||||||
|
public sealed class DeepSeekOptions
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// DeepSeek API base URL
|
||||||
|
/// </summary>
|
||||||
|
public string BaseUrl { get; set; } = "https://api.deepseek.com";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// DeepSeek API key (required)
|
||||||
|
/// </summary>
|
||||||
|
public required string ApiKey { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Default model to use
|
||||||
|
/// </summary>
|
||||||
|
public string DefaultModel { get; set; } = "deepseek-chat";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Default temperature for responses (0-2)
|
||||||
|
/// </summary>
|
||||||
|
public double DefaultTemperature { get; set; } = 1.0;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Default maximum tokens for responses
|
||||||
|
/// </summary>
|
||||||
|
public int? DefaultMaxTokens { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
124
src/GreenHome.AI.DeepSeek/DeepSeekService.cs
Normal file
@@ -0,0 +1,124 @@
|
|||||||
|
using System.Net.Http.Json;
|
||||||
|
using System.Text.Json;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
namespace GreenHome.AI.DeepSeek;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// DeepSeek AI service implementation
|
||||||
|
/// </summary>
|
||||||
|
public sealed class DeepSeekService : IDeepSeekService
|
||||||
|
{
|
||||||
|
private readonly HttpClient httpClient;
|
||||||
|
private readonly DeepSeekOptions options;
|
||||||
|
private readonly ILogger<DeepSeekService> logger;
|
||||||
|
|
||||||
|
public DeepSeekService(
|
||||||
|
HttpClient httpClient,
|
||||||
|
DeepSeekOptions options,
|
||||||
|
ILogger<DeepSeekService> logger)
|
||||||
|
{
|
||||||
|
this.httpClient = httpClient;
|
||||||
|
this.options = options;
|
||||||
|
this.logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<ChatResponse?> AskAsync(
|
||||||
|
ChatRequest request,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// Set defaults if not provided
|
||||||
|
if (string.IsNullOrEmpty(request.Model))
|
||||||
|
{
|
||||||
|
request.Model = options.DefaultModel;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!request.Temperature.HasValue)
|
||||||
|
{
|
||||||
|
request.Temperature = options.DefaultTemperature;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!request.MaxTokens.HasValue && options.DefaultMaxTokens.HasValue)
|
||||||
|
{
|
||||||
|
request.MaxTokens = options.DefaultMaxTokens;
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.LogInformation("Sending chat request to DeepSeek AI with {MessageCount} messages",
|
||||||
|
request.Messages.Count);
|
||||||
|
|
||||||
|
var response = await httpClient.PostAsJsonAsync(
|
||||||
|
"v1/chat/completions",
|
||||||
|
request,
|
||||||
|
cancellationToken);
|
||||||
|
|
||||||
|
response.EnsureSuccessStatusCode();
|
||||||
|
|
||||||
|
var result = await response.Content.ReadFromJsonAsync<ChatResponse>(
|
||||||
|
cancellationToken: cancellationToken);
|
||||||
|
|
||||||
|
logger.LogInformation("Received response from DeepSeek AI, used {TotalTokens} tokens",
|
||||||
|
result?.Usage?.TotalTokens ?? 0);
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
catch (HttpRequestException ex)
|
||||||
|
{
|
||||||
|
logger.LogError(ex, "HTTP error while communicating with DeepSeek AI");
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.LogError(ex, "Unexpected error while calling DeepSeek AI");
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<string?> AskSimpleAsync(
|
||||||
|
string question,
|
||||||
|
string? systemPrompt = null,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var messages = new List<ChatMessage>();
|
||||||
|
|
||||||
|
// Add system prompt if provided
|
||||||
|
if (!string.IsNullOrWhiteSpace(systemPrompt))
|
||||||
|
{
|
||||||
|
messages.Add(new ChatMessage
|
||||||
|
{
|
||||||
|
Role = "system",
|
||||||
|
Content = systemPrompt
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add user question
|
||||||
|
messages.Add(new ChatMessage
|
||||||
|
{
|
||||||
|
Role = "user",
|
||||||
|
Content = question
|
||||||
|
});
|
||||||
|
|
||||||
|
var request = new ChatRequest
|
||||||
|
{
|
||||||
|
Model = options.DefaultModel,
|
||||||
|
Messages = messages,
|
||||||
|
Temperature = options.DefaultTemperature,
|
||||||
|
MaxTokens = options.DefaultMaxTokens
|
||||||
|
};
|
||||||
|
|
||||||
|
var response = await AskAsync(request, cancellationToken);
|
||||||
|
|
||||||
|
// Extract the text content from the response
|
||||||
|
return response?.Choices?.FirstOrDefault()?.Message?.Content;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.LogError(ex, "Error in AskSimpleAsync for question: {Question}", question);
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
16
src/GreenHome.AI.DeepSeek/GreenHome.AI.DeepSeek.csproj
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net9.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<NuGetAudit>false</NuGetAudit>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="10.0.1" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Http" Version="10.0.1" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.1" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
25
src/GreenHome.AI.DeepSeek/IDeepSeekService.cs
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
namespace GreenHome.AI.DeepSeek;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Interface for DeepSeek AI service
|
||||||
|
/// </summary>
|
||||||
|
public interface IDeepSeekService
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Sends a chat request to DeepSeek AI and gets a response
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The chat request containing messages</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token</param>
|
||||||
|
/// <returns>The AI response</returns>
|
||||||
|
Task<ChatResponse?> AskAsync(ChatRequest request, CancellationToken cancellationToken = default);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Sends a simple question to DeepSeek AI and gets a text response
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="question">The question to ask</param>
|
||||||
|
/// <param name="systemPrompt">Optional system prompt to set context</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token</param>
|
||||||
|
/// <returns>The AI response text</returns>
|
||||||
|
Task<string?> AskSimpleAsync(string question, string? systemPrompt = null, CancellationToken cancellationToken = default);
|
||||||
|
}
|
||||||
|
|
||||||
129
src/GreenHome.AI.DeepSeek/Models.cs
Normal file
@@ -0,0 +1,129 @@
|
|||||||
|
using System.Text.Json.Serialization;
|
||||||
|
|
||||||
|
namespace GreenHome.AI.DeepSeek;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Request to ask a question to DeepSeek AI
|
||||||
|
/// </summary>
|
||||||
|
public sealed class ChatRequest
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// The model to use (default: deepseek-chat)
|
||||||
|
/// </summary>
|
||||||
|
public string Model { get; set; } = "deepseek-chat";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The messages to send to the AI
|
||||||
|
/// </summary>
|
||||||
|
public required List<ChatMessage> Messages { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Temperature for response randomness (0-2, default: 1)
|
||||||
|
/// </summary>
|
||||||
|
public double? Temperature { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Maximum tokens in the response
|
||||||
|
/// </summary>
|
||||||
|
[JsonPropertyName("max_tokens")]
|
||||||
|
public int? MaxTokens { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A single message in the chat
|
||||||
|
/// </summary>
|
||||||
|
public sealed class ChatMessage
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Role of the message sender (system, user, or assistant)
|
||||||
|
/// </summary>
|
||||||
|
public required string Role { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Content of the message
|
||||||
|
/// </summary>
|
||||||
|
public required string Content { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Response from DeepSeek AI
|
||||||
|
/// </summary>
|
||||||
|
public sealed class ChatResponse
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Unique ID for the chat completion
|
||||||
|
/// </summary>
|
||||||
|
public string? Id { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Object type (e.g., "chat.completion")
|
||||||
|
/// </summary>
|
||||||
|
public string? Object { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Unix timestamp of when the completion was created
|
||||||
|
/// </summary>
|
||||||
|
public long Created { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The model used for the completion
|
||||||
|
/// </summary>
|
||||||
|
public string? Model { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The completion choices
|
||||||
|
/// </summary>
|
||||||
|
public List<ChatChoice>? Choices { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Usage statistics for the request
|
||||||
|
/// </summary>
|
||||||
|
public ChatUsage? Usage { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A choice in the chat completion response
|
||||||
|
/// </summary>
|
||||||
|
public sealed class ChatChoice
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Index of the choice
|
||||||
|
/// </summary>
|
||||||
|
public int Index { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The message from the AI
|
||||||
|
/// </summary>
|
||||||
|
public ChatMessage? Message { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Reason for completion finish
|
||||||
|
/// </summary>
|
||||||
|
[JsonPropertyName("finish_reason")]
|
||||||
|
public string? FinishReason { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Token usage statistics
|
||||||
|
/// </summary>
|
||||||
|
public sealed class ChatUsage
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Number of tokens in the prompt
|
||||||
|
/// </summary>
|
||||||
|
[JsonPropertyName("prompt_tokens")]
|
||||||
|
public int PromptTokens { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Number of tokens in the completion
|
||||||
|
/// </summary>
|
||||||
|
[JsonPropertyName("completion_tokens")]
|
||||||
|
public int CompletionTokens { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Total number of tokens used
|
||||||
|
/// </summary>
|
||||||
|
[JsonPropertyName("total_tokens")]
|
||||||
|
public int TotalTokens { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
126
src/GreenHome.AI.DeepSeek/QUICKSTART.md
Normal file
@@ -0,0 +1,126 @@
|
|||||||
|
# 🚀 راهنمای سریع شروع - 5 دقیقه!
|
||||||
|
|
||||||
|
## مرحله 1: دریافت API Key (2 دقیقه)
|
||||||
|
|
||||||
|
1. به https://platform.deepseek.com بروید
|
||||||
|
2. روی "Sign Up" کلیک کنید (یا Login اگر قبلاً ثبتنام کردهاید)
|
||||||
|
3. وارد Dashboard شوید
|
||||||
|
4. از منوی سمت چپ، گزینه "API Keys" را انتخاب کنید
|
||||||
|
5. روی "Create API Key" کلیک کنید
|
||||||
|
6. یک نام برای کلید انتخاب کنید (مثلاً "GreenHome")
|
||||||
|
7. کلید را کپی کنید ⚠️ (فقط یک بار نمایش داده میشود!)
|
||||||
|
|
||||||
|
## مرحله 2: تنظیم API Key (1 دقیقه)
|
||||||
|
|
||||||
|
فایل `appsettings.json` را باز کنید و API Key را جایگزین کنید:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"DeepSeek": {
|
||||||
|
"ApiKey": "اینجا-کلید-خود-را-بگذارید"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## مرحله 3: اجرای برنامه (1 دقیقه)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd GreenHome.Api
|
||||||
|
dotnet run
|
||||||
|
```
|
||||||
|
|
||||||
|
## مرحله 4: تست API (1 دقیقه)
|
||||||
|
|
||||||
|
### با Swagger:
|
||||||
|
1. مرورگر را باز کنید: http://localhost:5000/swagger
|
||||||
|
2. endpoint `/api/ai/ask` را باز کنید
|
||||||
|
3. روی "Try it out" کلیک کنید
|
||||||
|
4. این را در Body بگذارید:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"question": "سلام! آیا کار میکنی؟"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
5. روی "Execute" کلیک کنید
|
||||||
|
6. پاسخ را ببینید! ✅
|
||||||
|
|
||||||
|
### با Curl:
|
||||||
|
```bash
|
||||||
|
curl -X POST http://localhost:5000/api/ai/ask \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{"question":"سلام! آیا کار میکنی؟"}'
|
||||||
|
```
|
||||||
|
|
||||||
|
### با Postman:
|
||||||
|
1. Postman را باز کنید
|
||||||
|
2. یک درخواست POST جدید بسازید
|
||||||
|
3. URL: `http://localhost:5000/api/ai/ask`
|
||||||
|
4. Headers: `Content-Type: application/json`
|
||||||
|
5. Body (raw JSON):
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"question": "سلام! آیا کار میکنی؟"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
6. Send را بزنید!
|
||||||
|
|
||||||
|
## 🎉 تبریک! شما آمادهاید!
|
||||||
|
|
||||||
|
اکنون میتوانید از AI در پروژه خود استفاده کنید.
|
||||||
|
|
||||||
|
## مثالهای آماده برای تست:
|
||||||
|
|
||||||
|
### 1. سوال درباره خانه هوشمند:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"question": "چگونه میتوانم مصرف برق خانه را کاهش دهم؟"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. دریافت پیشنهاد:
|
||||||
|
**Endpoint:** POST `/api/ai/suggest`
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"deviceContext": "دمای اتاق: 28 درجه، رطوبت: 65%، ساعت: 14:00"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. سوال با زمینه خاص:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"question": "بهترین دمای کولر برای خواب چیست؟",
|
||||||
|
"systemPrompt": "شما یک متخصص خانه هوشمند و بهینهسازی انرژی هستید."
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## ❓ مشکل دارید؟
|
||||||
|
|
||||||
|
### خطا: 401 Unauthorized
|
||||||
|
- ✅ بررسی کنید API Key را صحیح کپی کردهاید
|
||||||
|
- ✅ فاصله اضافی ندارد
|
||||||
|
- ✅ در appsettings.json به درستی قرار دارد
|
||||||
|
|
||||||
|
### خطا: Connection Refused
|
||||||
|
- ✅ مطمئن شوید برنامه اجرا شده است (`dotnet run`)
|
||||||
|
- ✅ پورت صحیح است (معمولاً 5000 یا 5001)
|
||||||
|
|
||||||
|
### خطا: 429 Too Many Requests
|
||||||
|
- ✅ کمی صبر کنید (1-2 دقیقه)
|
||||||
|
- ✅ تعداد درخواستهای شما زیاد بوده است
|
||||||
|
|
||||||
|
## 📚 مستندات بیشتر
|
||||||
|
|
||||||
|
- مستندات کامل: [README.md](README.md)
|
||||||
|
- راهنمای استفاده: [USAGE_FA.md](USAGE_FA.md)
|
||||||
|
- خلاصه پروژه: [SUMMARY.md](SUMMARY.md)
|
||||||
|
|
||||||
|
## 🎯 مرحله بعدی
|
||||||
|
|
||||||
|
اکنون میتوانید:
|
||||||
|
1. ✅ از AI در Controller های خود استفاده کنید
|
||||||
|
2. ✅ پیشنهادات هوشمند برای کاربران ارائه دهید
|
||||||
|
3. ✅ تحلیل دادههای سنسورها را انجام دهید
|
||||||
|
4. ✅ چتبات هوشمند بسازید
|
||||||
|
|
||||||
|
موفق باشید! 🚀
|
||||||
|
|
||||||
399
src/GreenHome.AI.DeepSeek/README.md
Normal file
@@ -0,0 +1,399 @@
|
|||||||
|
# GreenHome.AI.DeepSeek
|
||||||
|
|
||||||
|
سرویس هوش مصنوعی DeepSeek برای پروژه GreenHome
|
||||||
|
|
||||||
|
## درباره DeepSeek
|
||||||
|
|
||||||
|
DeepSeek یک مدل هوش مصنوعی پیشرفته است که میتوانید از آن برای:
|
||||||
|
- پاسخ به سوالات کاربران
|
||||||
|
- تحلیل دادههای خانه هوشمند
|
||||||
|
- ارائه پیشنهادات بهینهسازی
|
||||||
|
- تولید محتوای هوشمند
|
||||||
|
|
||||||
|
## نصب و راهاندازی
|
||||||
|
|
||||||
|
### 1. اضافه کردن Reference به پروژه
|
||||||
|
|
||||||
|
در فایل `.csproj` پروژه خود:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\GreenHome.AI.DeepSeek\GreenHome.AI.DeepSeek.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. دریافت API Key
|
||||||
|
|
||||||
|
1. به وبسایت [DeepSeek](https://platform.deepseek.com/) بروید
|
||||||
|
2. ثبتنام کنید یا وارد حساب کاربری خود شوید
|
||||||
|
3. از بخش API Keys، یک کلید API جدید بسازید
|
||||||
|
4. کلید را کپی کنید (فقط یک بار نمایش داده میشود!)
|
||||||
|
|
||||||
|
### 3. ثبت سرویس در Program.cs
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
using GreenHome.AI.DeepSeek;
|
||||||
|
|
||||||
|
// روش 1: استفاده از Configuration (پیشنهادی)
|
||||||
|
builder.Services.AddDeepSeek(builder.Configuration);
|
||||||
|
|
||||||
|
// روش 2: استفاده از Configuration Section
|
||||||
|
builder.Services.AddDeepSeek(builder.Configuration.GetSection("DeepSeek"));
|
||||||
|
|
||||||
|
// روش 3: تنظیم دستی
|
||||||
|
builder.Services.AddDeepSeek(options =>
|
||||||
|
{
|
||||||
|
options.ApiKey = "YOUR_API_KEY_HERE";
|
||||||
|
options.BaseUrl = "https://api.deepseek.com";
|
||||||
|
options.DefaultModel = "deepseek-chat";
|
||||||
|
options.DefaultTemperature = 1.0;
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. تنظیمات در appsettings.json
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"DeepSeek": {
|
||||||
|
"BaseUrl": "https://api.deepseek.com",
|
||||||
|
"ApiKey": "YOUR_DEEPSEEK_API_KEY_HERE",
|
||||||
|
"DefaultModel": "deepseek-chat",
|
||||||
|
"DefaultTemperature": 1.0,
|
||||||
|
"DefaultMaxTokens": 2000
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**نکته امنیتی:** هرگز API Key خود را در کد یا repository قرار ندهید! از Environment Variables یا User Secrets استفاده کنید.
|
||||||
|
|
||||||
|
#### استفاده از User Secrets (Development)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
dotnet user-secrets init
|
||||||
|
dotnet user-secrets set "DeepSeek:ApiKey" "YOUR_API_KEY_HERE"
|
||||||
|
```
|
||||||
|
|
||||||
|
#### استفاده از Environment Variables (Production)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export DeepSeek__ApiKey="YOUR_API_KEY_HERE"
|
||||||
|
```
|
||||||
|
|
||||||
|
## استفاده در کنترلرها
|
||||||
|
|
||||||
|
### تزریق سرویس
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
public class AIController : ControllerBase
|
||||||
|
{
|
||||||
|
private readonly IDeepSeekService deepSeekService;
|
||||||
|
|
||||||
|
public AIController(IDeepSeekService deepSeekService)
|
||||||
|
{
|
||||||
|
this.deepSeekService = deepSeekService;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### سوال ساده
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
var response = await deepSeekService.AskSimpleAsync(
|
||||||
|
"چگونه میتوانم مصرف انرژی خانه را کاهش دهم؟"
|
||||||
|
);
|
||||||
|
|
||||||
|
Console.WriteLine(response);
|
||||||
|
```
|
||||||
|
|
||||||
|
### سوال با System Prompt
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
var systemPrompt = "شما یک مشاور خانه هوشمند هستید.";
|
||||||
|
var question = "بهترین دمای کولر برای صرفهجویی انرژی چقدر است؟";
|
||||||
|
|
||||||
|
var response = await deepSeekService.AskSimpleAsync(question, systemPrompt);
|
||||||
|
```
|
||||||
|
|
||||||
|
### چت پیشرفته با تاریخچه
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
var request = new ChatRequest
|
||||||
|
{
|
||||||
|
Model = "deepseek-chat",
|
||||||
|
Messages = new List<ChatMessage>
|
||||||
|
{
|
||||||
|
new ChatMessage
|
||||||
|
{
|
||||||
|
Role = "system",
|
||||||
|
Content = "شما یک دستیار هوشمند خانه هوشمند هستید."
|
||||||
|
},
|
||||||
|
new ChatMessage
|
||||||
|
{
|
||||||
|
Role = "user",
|
||||||
|
Content = "دمای فعلی 28 درجه است"
|
||||||
|
},
|
||||||
|
new ChatMessage
|
||||||
|
{
|
||||||
|
Role = "assistant",
|
||||||
|
Content = "باشه، دمای فعلی خانه را دریافت کردم."
|
||||||
|
},
|
||||||
|
new ChatMessage
|
||||||
|
{
|
||||||
|
Role = "user",
|
||||||
|
Content = "آیا باید کولر را روشن کنم؟"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Temperature = 0.7,
|
||||||
|
MaxTokens = 1000
|
||||||
|
};
|
||||||
|
|
||||||
|
var response = await deepSeekService.AskAsync(request);
|
||||||
|
var answer = response?.Choices?.FirstOrDefault()?.Message?.Content;
|
||||||
|
```
|
||||||
|
|
||||||
|
## API Endpoints
|
||||||
|
|
||||||
|
سرویس شامل 3 endpoint اصلی است:
|
||||||
|
|
||||||
|
### 1. POST /api/ai/ask
|
||||||
|
پرسیدن یک سوال ساده
|
||||||
|
|
||||||
|
**Request Body:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"question": "چگونه میتوانم دمای خانه را کنترل کنم؟",
|
||||||
|
"systemPrompt": "شما یک مشاور خانه هوشمند هستید."
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"question": "چگونه میتوانم دمای خانه را کنترل کنم؟",
|
||||||
|
"answer": "برای کنترل دمای خانه میتوانید از ترموستات هوشمند استفاده کنید...",
|
||||||
|
"timestamp": "2025-12-16T10:30:00Z"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. POST /api/ai/chat
|
||||||
|
چت پیشرفته با تاریخچه
|
||||||
|
|
||||||
|
**Request Body:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"model": "deepseek-chat",
|
||||||
|
"messages": [
|
||||||
|
{
|
||||||
|
"role": "system",
|
||||||
|
"content": "شما یک دستیار هوشمند هستید."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "user",
|
||||||
|
"content": "سلام"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"temperature": 0.7,
|
||||||
|
"maxTokens": 2000
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"id": "chatcmpl-xxx",
|
||||||
|
"object": "chat.completion",
|
||||||
|
"created": 1702735200,
|
||||||
|
"model": "deepseek-chat",
|
||||||
|
"choices": [
|
||||||
|
{
|
||||||
|
"index": 0,
|
||||||
|
"message": {
|
||||||
|
"role": "assistant",
|
||||||
|
"content": "سلام! چطور میتونم کمکتون کنم؟"
|
||||||
|
},
|
||||||
|
"finishReason": "stop"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"usage": {
|
||||||
|
"promptTokens": 20,
|
||||||
|
"completionTokens": 15,
|
||||||
|
"totalTokens": 35
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. POST /api/ai/suggest
|
||||||
|
دریافت پیشنهادات برای بهینهسازی خانه هوشمند
|
||||||
|
|
||||||
|
**Request Body:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"deviceContext": "دمای اتاق: 28°C، رطوبت: 65%، ساعت: 14:00"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"suggestions": "با توجه به دمای بالای 28 درجه، توصیه میشود کولر را روشن کنید...",
|
||||||
|
"timestamp": "2025-12-16T10:30:00Z"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## مثالهای کاربردی
|
||||||
|
|
||||||
|
### 1. تحلیل دادههای سنسور
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
var deviceData = $@"
|
||||||
|
دمای اتاق خواب: {temperature}°C
|
||||||
|
رطوبت: {humidity}%
|
||||||
|
کیفیت هوا: {airQuality}
|
||||||
|
ساعت: {DateTime.Now:HH:mm}
|
||||||
|
";
|
||||||
|
|
||||||
|
var systemPrompt = "شما یک مشاور خانه هوشمند هستید که بر اساس دادههای سنسورها پیشنهاد میدهید.";
|
||||||
|
|
||||||
|
var response = await deepSeekService.AskSimpleAsync(
|
||||||
|
$"وضعیت خانه: {deviceData}\nچه کاری باید انجام دهم؟",
|
||||||
|
systemPrompt
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. پاسخ به سوالات کاربر
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
[HttpPost("ask")]
|
||||||
|
public async Task<IActionResult> Ask([FromBody] string question)
|
||||||
|
{
|
||||||
|
var answer = await deepSeekService.AskSimpleAsync(question);
|
||||||
|
return Ok(new { question, answer });
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. دستیار هوشمند با حافظه
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
// ذخیره تاریخچه در session یا database
|
||||||
|
var conversationHistory = GetConversationHistory(userId);
|
||||||
|
|
||||||
|
var request = new ChatRequest
|
||||||
|
{
|
||||||
|
Messages = conversationHistory.Select(m => new ChatMessage
|
||||||
|
{
|
||||||
|
Role = m.Role,
|
||||||
|
Content = m.Content
|
||||||
|
}).ToList()
|
||||||
|
};
|
||||||
|
|
||||||
|
// اضافه کردن پیام جدید کاربر
|
||||||
|
request.Messages.Add(new ChatMessage
|
||||||
|
{
|
||||||
|
Role = "user",
|
||||||
|
Content = userMessage
|
||||||
|
});
|
||||||
|
|
||||||
|
var response = await deepSeekService.AskAsync(request);
|
||||||
|
|
||||||
|
// ذخیره پاسخ در تاریخچه
|
||||||
|
SaveToHistory(userId, response);
|
||||||
|
```
|
||||||
|
|
||||||
|
## پارامترها
|
||||||
|
|
||||||
|
### Temperature
|
||||||
|
- **مقدار:** 0 تا 2
|
||||||
|
- **پیشفرض:** 1.0
|
||||||
|
- **توضیح:** هر چه عدد بالاتر باشد، پاسخها خلاقانهتر و تصادفیتر هستند
|
||||||
|
|
||||||
|
### MaxTokens
|
||||||
|
- **توضیح:** حداکثر تعداد توکن در پاسخ
|
||||||
|
- **توصیه:** برای پاسخهای کوتاه: 500، برای پاسخهای بلند: 2000
|
||||||
|
|
||||||
|
### Model
|
||||||
|
- **مقدار:** `deepseek-chat` (پیشفرض)
|
||||||
|
- **توضیح:** مدل مورد استفاده برای تولید پاسخ
|
||||||
|
|
||||||
|
## نکات مهم
|
||||||
|
|
||||||
|
1. **هزینه:** هر درخواست به DeepSeek بر اساس تعداد توکنهای استفاده شده هزینه دارد
|
||||||
|
2. **Rate Limiting:** محدودیت تعداد درخواست در واحد زمان را رعایت کنید
|
||||||
|
3. **Timeout:** درخواستهای AI ممکن است طولانی باشند (پیشفرض: 60 ثانیه)
|
||||||
|
4. **خطاها:** همیشه خطاها را مدیریت کنید و پیام مناسب به کاربر نمایش دهید
|
||||||
|
5. **امنیت:** API Key را محرمانه نگه دارید
|
||||||
|
|
||||||
|
## عیبیابی
|
||||||
|
|
||||||
|
### خطای 401 Unauthorized
|
||||||
|
- بررسی کنید که API Key صحیح است
|
||||||
|
- مطمئن شوید که در configuration به درستی تنظیم شده است
|
||||||
|
|
||||||
|
### خطای 429 Too Many Requests
|
||||||
|
- به محدودیت rate limit رسیدهاید
|
||||||
|
- کمی صبر کنید و دوباره تلاش کنید
|
||||||
|
|
||||||
|
### خطای Timeout
|
||||||
|
- درخواست خیلی طولانی است
|
||||||
|
- MaxTokens را کاهش دهید یا Timeout را افزایش دهید
|
||||||
|
|
||||||
|
## مثال کامل
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
using GreenHome.AI.DeepSeek;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
|
[ApiController]
|
||||||
|
[Route("api/[controller]")]
|
||||||
|
public class SmartHomeAIController : ControllerBase
|
||||||
|
{
|
||||||
|
private readonly IDeepSeekService _ai;
|
||||||
|
private readonly ILogger<SmartHomeAIController> _logger;
|
||||||
|
|
||||||
|
public SmartHomeAIController(
|
||||||
|
IDeepSeekService ai,
|
||||||
|
ILogger<SmartHomeAIController> logger)
|
||||||
|
{
|
||||||
|
_ai = ai;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost("analyze")]
|
||||||
|
public async Task<IActionResult> AnalyzeHome([FromBody] HomeData data)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var prompt = $@"
|
||||||
|
دادههای خانه هوشمند:
|
||||||
|
- دمای داخل: {data.Temperature}°C
|
||||||
|
- رطوبت: {data.Humidity}%
|
||||||
|
- مصرف برق: {data.PowerUsage}W
|
||||||
|
- تعداد افراد: {data.OccupancyCount}
|
||||||
|
|
||||||
|
لطفاً تحلیل کامل ارائه دهید و پیشنهادات بهینهسازی بدهید.
|
||||||
|
";
|
||||||
|
|
||||||
|
var systemPrompt = "شما یک متخصص خانه هوشمند هستید.";
|
||||||
|
|
||||||
|
var analysis = await _ai.AskSimpleAsync(prompt, systemPrompt);
|
||||||
|
|
||||||
|
return Ok(new { analysis, timestamp = DateTime.UtcNow });
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error analyzing home data");
|
||||||
|
return StatusCode(500, "خطا در تحلیل دادهها");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## منابع
|
||||||
|
|
||||||
|
- [DeepSeek Documentation](https://platform.deepseek.com/docs)
|
||||||
|
- [API Reference](https://platform.deepseek.com/api-docs)
|
||||||
|
- [Pricing](https://platform.deepseek.com/pricing)
|
||||||
|
|
||||||
|
## پشتیبانی
|
||||||
|
|
||||||
|
در صورت بروز مشکل، لطفاً یک Issue در GitHub ایجاد کنید.
|
||||||
|
|
||||||
200
src/GreenHome.AI.DeepSeek/SUMMARY.md
Normal file
@@ -0,0 +1,200 @@
|
|||||||
|
# خلاصه سرویس DeepSeek برای GreenHome
|
||||||
|
|
||||||
|
## ✅ کارهای انجام شده
|
||||||
|
|
||||||
|
### 1. ساختار پروژه
|
||||||
|
- ✅ پروژه `GreenHome.AI.DeepSeek` ایجاد شد
|
||||||
|
- ✅ به Solution اضافه شد
|
||||||
|
- ✅ Reference در پروژه API افزوده شد
|
||||||
|
- ✅ بستههای NuGet نصب شدند
|
||||||
|
|
||||||
|
### 2. فایلهای ایجاد شده
|
||||||
|
|
||||||
|
#### Core Files:
|
||||||
|
- ✅ `IDeepSeekService.cs` - Interface سرویس
|
||||||
|
- ✅ `DeepSeekService.cs` - پیادهسازی سرویس
|
||||||
|
- ✅ `DeepSeekOptions.cs` - تنظیمات
|
||||||
|
- ✅ `Models.cs` - مدلهای درخواست و پاسخ
|
||||||
|
- ✅ `ServiceCollectionExtensions.cs` - ثبت سرویس در DI
|
||||||
|
|
||||||
|
#### API Controller:
|
||||||
|
- ✅ `AIController.cs` - 3 endpoint برای استفاده از AI
|
||||||
|
|
||||||
|
#### Documentation:
|
||||||
|
- ✅ `README.md` - مستندات کامل (فارسی)
|
||||||
|
- ✅ `USAGE_FA.md` - راهنمای سریع (فارسی)
|
||||||
|
- ✅ `SUMMARY.md` - این فایل
|
||||||
|
|
||||||
|
### 3. تنظیمات
|
||||||
|
|
||||||
|
#### Program.cs
|
||||||
|
```csharp
|
||||||
|
using GreenHome.AI.DeepSeek;
|
||||||
|
// ...
|
||||||
|
builder.Services.AddDeepSeek(builder.Configuration);
|
||||||
|
```
|
||||||
|
|
||||||
|
#### appsettings.json
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"DeepSeek": {
|
||||||
|
"BaseUrl": "https://api.deepseek.com",
|
||||||
|
"ApiKey": "YOUR_DEEPSEEK_API_KEY_HERE",
|
||||||
|
"DefaultModel": "deepseek-chat",
|
||||||
|
"DefaultTemperature": 1.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 📋 API Endpoints
|
||||||
|
|
||||||
|
### 1. POST /api/ai/ask
|
||||||
|
پرسیدن سوال ساده از AI
|
||||||
|
|
||||||
|
**Request:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"question": "سوال شما",
|
||||||
|
"systemPrompt": "زمینه و کنتکست (اختیاری)"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. POST /api/ai/chat
|
||||||
|
چت پیشرفته با تاریخچه
|
||||||
|
|
||||||
|
**Request:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"messages": [
|
||||||
|
{"role": "system", "content": "..."},
|
||||||
|
{"role": "user", "content": "..."}
|
||||||
|
],
|
||||||
|
"temperature": 0.7,
|
||||||
|
"maxTokens": 2000
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. POST /api/ai/suggest
|
||||||
|
دریافت پیشنهادات برای خانه هوشمند
|
||||||
|
|
||||||
|
**Request:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"deviceContext": "دمای اتاق: 28°C، رطوبت: 65%"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🎯 ویژگیها
|
||||||
|
|
||||||
|
- ✅ اتصال به API رسمی DeepSeek
|
||||||
|
- ✅ پشتیبانی از چت ساده و پیشرفته
|
||||||
|
- ✅ قابلیت تنظیم Temperature و MaxTokens
|
||||||
|
- ✅ Logging کامل
|
||||||
|
- ✅ مدیریت خطا
|
||||||
|
- ✅ استفاده از HttpClient Factory
|
||||||
|
- ✅ Dependency Injection
|
||||||
|
- ✅ Configuration از appsettings.json
|
||||||
|
- ✅ مستندات کامل فارسی
|
||||||
|
|
||||||
|
## 🚀 نحوه استفاده
|
||||||
|
|
||||||
|
### در Controller:
|
||||||
|
```csharp
|
||||||
|
public class MyController : ControllerBase
|
||||||
|
{
|
||||||
|
private readonly IDeepSeekService _ai;
|
||||||
|
|
||||||
|
public MyController(IDeepSeekService ai)
|
||||||
|
{
|
||||||
|
_ai = ai;
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost]
|
||||||
|
public async Task<IActionResult> Ask(string question)
|
||||||
|
{
|
||||||
|
var answer = await _ai.AskSimpleAsync(question);
|
||||||
|
return Ok(answer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### در Service:
|
||||||
|
```csharp
|
||||||
|
public class MyService
|
||||||
|
{
|
||||||
|
private readonly IDeepSeekService _ai;
|
||||||
|
|
||||||
|
public MyService(IDeepSeekService ai)
|
||||||
|
{
|
||||||
|
_ai = ai;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<string> GetSuggestion(string context)
|
||||||
|
{
|
||||||
|
return await _ai.AskSimpleAsync(
|
||||||
|
$"پیشنهاد بده: {context}",
|
||||||
|
"شما یک مشاور خانه هوشمند هستید"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## ⚙️ پیشنیازها
|
||||||
|
|
||||||
|
1. دریافت API Key از https://platform.deepseek.com
|
||||||
|
2. قرار دادن API Key در appsettings.json
|
||||||
|
3. اطمینان از اتصال اینترنت
|
||||||
|
|
||||||
|
## ⚠️ نکات مهم
|
||||||
|
|
||||||
|
1. **امنیت:** API Key را در Git commit نکنید
|
||||||
|
2. **هزینه:** هر درخواست بر اساس توکن هزینه دارد
|
||||||
|
3. **محدودیت:** Rate limiting وجود دارد
|
||||||
|
4. **Timeout:** درخواستها ممکن است کند باشند (60 ثانیه)
|
||||||
|
|
||||||
|
## 🔧 عیبیابی
|
||||||
|
|
||||||
|
| خطا | دلیل | راه حل |
|
||||||
|
|-----|------|--------|
|
||||||
|
| 401 Unauthorized | API Key نامعتبر | بررسی API Key در appsettings.json |
|
||||||
|
| 429 Too Many Requests | تعداد درخواست زیاد | کمی صبر کنید (1-2 دقیقه) |
|
||||||
|
| Timeout | درخواست طولانی | MaxTokens را کاهش دهید |
|
||||||
|
|
||||||
|
## 📚 مستندات
|
||||||
|
|
||||||
|
- مستندات کامل: [README.md](README.md)
|
||||||
|
- راهنمای سریع: [USAGE_FA.md](USAGE_FA.md)
|
||||||
|
- وبسایت DeepSeek: https://platform.deepseek.com
|
||||||
|
- API Docs: https://platform.deepseek.com/api-docs
|
||||||
|
|
||||||
|
## ✨ مثالهای کاربردی
|
||||||
|
|
||||||
|
### تحلیل دادههای سنسور
|
||||||
|
```csharp
|
||||||
|
var data = $"دمای اتاق: {temp}°C، رطوبت: {humidity}%";
|
||||||
|
var suggestion = await _ai.AskSimpleAsync(
|
||||||
|
$"تحلیل کن: {data}",
|
||||||
|
"شما متخصص خانه هوشمند هستید"
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
### چت با حافظه
|
||||||
|
```csharp
|
||||||
|
var messages = new List<ChatMessage>
|
||||||
|
{
|
||||||
|
new() { Role = "system", Content = "شما دستیار هوشمند هستید" },
|
||||||
|
new() { Role = "user", Content = "سلام" },
|
||||||
|
// ... تاریخچه قبلی
|
||||||
|
new() { Role = "user", Content = "پیام جدید" }
|
||||||
|
};
|
||||||
|
|
||||||
|
var response = await _ai.AskAsync(new ChatRequest
|
||||||
|
{
|
||||||
|
Messages = messages
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🎉 آماده استفاده!
|
||||||
|
|
||||||
|
پروژه کامل شده و آماده استفاده است. فقط API Key خود را در appsettings.json قرار دهید و از AI استفاده کنید! 🚀
|
||||||
|
|
||||||
110
src/GreenHome.AI.DeepSeek/ServiceCollectionExtensions.cs
Normal file
@@ -0,0 +1,110 @@
|
|||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
|
||||||
|
namespace GreenHome.AI.DeepSeek;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Extension methods for registering DeepSeek AI service
|
||||||
|
/// </summary>
|
||||||
|
public static class ServiceCollectionExtensions
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Adds DeepSeek AI service to the service collection
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="services">The service collection</param>
|
||||||
|
/// <param name="configuration">Configuration root</param>
|
||||||
|
/// <returns>The service collection for chaining</returns>
|
||||||
|
public static IServiceCollection AddDeepSeek(
|
||||||
|
this IServiceCollection services,
|
||||||
|
IConfiguration configuration)
|
||||||
|
{
|
||||||
|
return services.AddDeepSeek(configuration.GetSection("DeepSeek"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Adds DeepSeek AI service to the service collection
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="services">The service collection</param>
|
||||||
|
/// <param name="configurationSection">Configuration section for DeepSeek</param>
|
||||||
|
/// <returns>The service collection for chaining</returns>
|
||||||
|
public static IServiceCollection AddDeepSeek(
|
||||||
|
this IServiceCollection services,
|
||||||
|
IConfigurationSection? configurationSection = null)
|
||||||
|
{
|
||||||
|
// Configure options
|
||||||
|
DeepSeekOptions? options = null;
|
||||||
|
if (configurationSection != null)
|
||||||
|
{
|
||||||
|
options = configurationSection.Get<DeepSeekOptions>();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options == null)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException(
|
||||||
|
"DeepSeek configuration section is missing. " +
|
||||||
|
"Please add 'DeepSeek' section to your appsettings.json with 'ApiKey' property.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(options.ApiKey))
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException(
|
||||||
|
"DeepSeek ApiKey is required. " +
|
||||||
|
"Please add 'ApiKey' to the 'DeepSeek' section in your appsettings.json.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Register options as singleton
|
||||||
|
services.AddSingleton(options);
|
||||||
|
|
||||||
|
// Register HttpClient and service
|
||||||
|
services.AddHttpClient<IDeepSeekService, DeepSeekService>(client =>
|
||||||
|
{
|
||||||
|
// Ensure BaseUrl ends with / for proper relative path handling
|
||||||
|
var baseUrl = options.BaseUrl.TrimEnd('/') + "/";
|
||||||
|
client.BaseAddress = new Uri(baseUrl);
|
||||||
|
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"Bearer {options.ApiKey}");
|
||||||
|
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
|
||||||
|
client.Timeout = TimeSpan.FromSeconds(60); // AI requests may take longer
|
||||||
|
});
|
||||||
|
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Adds DeepSeek AI service to the service collection with explicit options
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="services">The service collection</param>
|
||||||
|
/// <param name="configureOptions">Action to configure options</param>
|
||||||
|
/// <returns>The service collection for chaining</returns>
|
||||||
|
public static IServiceCollection AddDeepSeek(
|
||||||
|
this IServiceCollection services,
|
||||||
|
Action<DeepSeekOptions> configureOptions)
|
||||||
|
{
|
||||||
|
var options = new DeepSeekOptions
|
||||||
|
{
|
||||||
|
ApiKey = string.Empty // Will be set by configureOptions
|
||||||
|
};
|
||||||
|
configureOptions(options);
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(options.ApiKey))
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException(
|
||||||
|
"DeepSeek ApiKey is required.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Register options as singleton
|
||||||
|
services.AddSingleton(options);
|
||||||
|
|
||||||
|
// Register HttpClient and service
|
||||||
|
services.AddHttpClient<IDeepSeekService, DeepSeekService>(client =>
|
||||||
|
{
|
||||||
|
var baseUrl = options.BaseUrl.TrimEnd('/') + "/";
|
||||||
|
client.BaseAddress = new Uri(baseUrl);
|
||||||
|
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"Bearer {options.ApiKey}");
|
||||||
|
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
|
||||||
|
client.Timeout = TimeSpan.FromSeconds(60);
|
||||||
|
});
|
||||||
|
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
186
src/GreenHome.AI.DeepSeek/USAGE_FA.md
Normal file
@@ -0,0 +1,186 @@
|
|||||||
|
# راهنمای سریع استفاده از سرویس DeepSeek
|
||||||
|
|
||||||
|
## نصب و راهاندازی
|
||||||
|
|
||||||
|
### گام 1: دریافت API Key
|
||||||
|
|
||||||
|
1. به آدرس https://platform.deepseek.com بروید
|
||||||
|
2. ثبتنام کنید یا وارد شوید
|
||||||
|
3. از منوی API Keys یک کلید جدید بسازید
|
||||||
|
4. کلید را کپی کنید (مهم: فقط یک بار نمایش داده میشود!)
|
||||||
|
|
||||||
|
### گام 2: تنظیم API Key
|
||||||
|
|
||||||
|
API Key خود را در فایل `appsettings.json` قرار دهید:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"DeepSeek": {
|
||||||
|
"ApiKey": "کلید-API-خود-را-اینجا-قرار-دهید"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**هشدار امنیتی:** هرگز API Key را در Git commit نکنید!
|
||||||
|
|
||||||
|
### گام 3: اجرای برنامه
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd GreenHome.Api
|
||||||
|
dotnet run
|
||||||
|
```
|
||||||
|
|
||||||
|
## استفاده از API
|
||||||
|
|
||||||
|
سرویس روی آدرس `http://localhost:5000` (یا پورت دیگری که تنظیم کردهاید) اجرا میشود.
|
||||||
|
|
||||||
|
### 1. پرسیدن یک سوال ساده
|
||||||
|
|
||||||
|
**درخواست:**
|
||||||
|
```http
|
||||||
|
POST /api/ai/ask
|
||||||
|
Content-Type: application/json
|
||||||
|
|
||||||
|
{
|
||||||
|
"question": "چگونه میتوانم مصرف انرژی خانه را کاهش دهم؟"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**پاسخ:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"question": "چگونه میتوانم مصرف انرژی خانه را کاهش دهم؟",
|
||||||
|
"answer": "برای کاهش مصرف انرژی خانه میتوانید از راهکارهای زیر استفاده کنید:\n1. از لامپهای LED استفاده کنید\n2. ترموستات هوشمند نصب کنید\n3. عایقبندی خانه را بهبود دهید...",
|
||||||
|
"timestamp": "2025-12-16T10:30:00Z"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. دریافت پیشنهادات برای خانه هوشمند
|
||||||
|
|
||||||
|
**درخواست:**
|
||||||
|
```http
|
||||||
|
POST /api/ai/suggest
|
||||||
|
Content-Type: application/json
|
||||||
|
|
||||||
|
{
|
||||||
|
"deviceContext": "دمای فعلی: 28 درجه، رطوبت: 65%، ساعت: 14:00، تعداد افراد در خانه: 2 نفر"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**پاسخ:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"suggestions": "با توجه به شرایط فعلی، پیشنهادات زیر را دارم:\n- دمای 28 درجه کمی بالا است، روشن کردن کولر با دمای 24-25 درجه توصیه میشود\n- رطوبت 65% در محدوده مناسب است\n- در این ساعت از روز (14:00) پردهها را بکشید تا آفتاب مستقیم وارد نشود",
|
||||||
|
"timestamp": "2025-12-16T10:30:00Z"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. چت پیشرفته
|
||||||
|
|
||||||
|
**درخواست:**
|
||||||
|
```http
|
||||||
|
POST /api/ai/chat
|
||||||
|
Content-Type: application/json
|
||||||
|
|
||||||
|
{
|
||||||
|
"messages": [
|
||||||
|
{
|
||||||
|
"role": "system",
|
||||||
|
"content": "شما یک دستیار هوشمند خانه هوشمند هستید."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "user",
|
||||||
|
"content": "دمای خانه 18 درجه است"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "assistant",
|
||||||
|
"content": "درجه حرارت 18 درجه را دریافت کردم. این دما کمی پایین است."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "user",
|
||||||
|
"content": "چه کار کنم؟"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"temperature": 0.7
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## مثالهای Curl
|
||||||
|
|
||||||
|
### سوال ساده
|
||||||
|
```bash
|
||||||
|
curl -X POST http://localhost:5000/api/ai/ask \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{"question":"بهترین دمای کولر برای خواب چیست؟"}'
|
||||||
|
```
|
||||||
|
|
||||||
|
### دریافت پیشنهاد
|
||||||
|
```bash
|
||||||
|
curl -X POST http://localhost:5000/api/ai/suggest \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{"deviceContext":"دمای اتاق خواب: 26 درجه، ساعت: 22:00"}'
|
||||||
|
```
|
||||||
|
|
||||||
|
## استفاده در کد C#
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
using GreenHome.AI.DeepSeek;
|
||||||
|
|
||||||
|
public class MyService
|
||||||
|
{
|
||||||
|
private readonly IDeepSeekService _ai;
|
||||||
|
|
||||||
|
public MyService(IDeepSeekService ai)
|
||||||
|
{
|
||||||
|
_ai = ai;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<string> GetAdvice()
|
||||||
|
{
|
||||||
|
var answer = await _ai.AskSimpleAsync(
|
||||||
|
"چگونه خانه هوشمند خود را امنتر کنم؟"
|
||||||
|
);
|
||||||
|
|
||||||
|
return answer ?? "پاسخی دریافت نشد";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## نکات مهم
|
||||||
|
|
||||||
|
### هزینه
|
||||||
|
- هر درخواست به API DeepSeek هزینه دارد
|
||||||
|
- بر اساس تعداد توکنهای استفاده شده محاسبه میشود
|
||||||
|
- برای کاهش هزینه، سوالات را مختصر و مفید بپرسید
|
||||||
|
|
||||||
|
### محدودیتها
|
||||||
|
- تعداد درخواست در دقیقه محدود است
|
||||||
|
- اگر خطای 429 دریافت کردید، کمی صبر کنید
|
||||||
|
|
||||||
|
### بهینهسازی
|
||||||
|
- از `temperature` پایینتر (0.3-0.7) برای پاسخهای دقیقتر استفاده کنید
|
||||||
|
- `maxTokens` را برای کنترل طول پاسخ تنظیم کنید
|
||||||
|
- پاسخهای تکراری را cache کنید
|
||||||
|
|
||||||
|
## عیبیابی
|
||||||
|
|
||||||
|
### خطا: 401 Unauthorized
|
||||||
|
- API Key را چک کنید
|
||||||
|
- مطمئن شوید که در appsettings.json صحیح است
|
||||||
|
|
||||||
|
### خطا: 429 Too Many Requests
|
||||||
|
- به محدودیت تعداد درخواست رسیدهاید
|
||||||
|
- 1-2 دقیقه صبر کنید
|
||||||
|
|
||||||
|
### خطا: Timeout
|
||||||
|
- درخواست طولانی است
|
||||||
|
- `maxTokens` را کاهش دهید
|
||||||
|
- timeout را افزایش دهید
|
||||||
|
|
||||||
|
## پشتیبانی
|
||||||
|
|
||||||
|
برای سوالات و مشکلات:
|
||||||
|
- مستندات کامل: [README.md](README.md)
|
||||||
|
- وبسایت DeepSeek: https://platform.deepseek.com
|
||||||
|
- مستندات API: https://platform.deepseek.com/api-docs
|
||||||
|
|
||||||
340
src/GreenHome.Api/Controllers/AIController.cs
Normal file
@@ -0,0 +1,340 @@
|
|||||||
|
using GreenHome.AI.DeepSeek;
|
||||||
|
using GreenHome.Application;
|
||||||
|
using GreenHome.Domain;
|
||||||
|
using GreenHome.Infrastructure.Services.AI;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using System.Diagnostics;
|
||||||
|
|
||||||
|
namespace GreenHome.Api.Controllers;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// AI endpoints. Every request is routed through the active AI profile
|
||||||
|
/// (see admin → AI Profiles); when no profile is active it falls back to the
|
||||||
|
/// configured legacy DeepSeek service. Each query is logged with its tokens
|
||||||
|
/// and estimated cost (CostUsd) for per-profile usage reporting.
|
||||||
|
/// </summary>
|
||||||
|
[ApiController]
|
||||||
|
[Route("api/[controller]")]
|
||||||
|
public class AIController : ControllerBase
|
||||||
|
{
|
||||||
|
private readonly IAIProfileService aiProfileService;
|
||||||
|
private readonly IAIQueryService aiQueryService;
|
||||||
|
private readonly ILogger<AIController> logger;
|
||||||
|
|
||||||
|
public AIController(
|
||||||
|
IAIProfileService aiProfileService,
|
||||||
|
IAIQueryService aiQueryService,
|
||||||
|
ILogger<AIController> logger)
|
||||||
|
{
|
||||||
|
this.aiProfileService = aiProfileService;
|
||||||
|
this.aiQueryService = aiQueryService;
|
||||||
|
this.logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Send a simple question to the AI and get a response
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("ask")]
|
||||||
|
public async Task<IActionResult> AskQuestion([FromBody] SimpleQuestionRequest request, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var stopwatch = Stopwatch.StartNew();
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(request.Question))
|
||||||
|
{
|
||||||
|
return BadRequest(new { error = "Question is required" });
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.LogInformation("Processing AI question: {Question}", request.Question);
|
||||||
|
|
||||||
|
var messages = new List<ChatMessage>();
|
||||||
|
if (!string.IsNullOrWhiteSpace(request.SystemPrompt))
|
||||||
|
{
|
||||||
|
messages.Add(new ChatMessage { Role = "system", Content = request.SystemPrompt });
|
||||||
|
}
|
||||||
|
messages.Add(new ChatMessage { Role = "user", Content = request.Question });
|
||||||
|
|
||||||
|
var result = await aiProfileService.AskAsync(messages, cancellationToken: cancellationToken);
|
||||||
|
|
||||||
|
stopwatch.Stop();
|
||||||
|
|
||||||
|
if (result.Response == null || result.Response.Choices == null || !result.Response.Choices.Any())
|
||||||
|
{
|
||||||
|
return StatusCode(500, new { error = "No response received from AI" });
|
||||||
|
}
|
||||||
|
|
||||||
|
var answer = result.Response.Choices.FirstOrDefault()?.Message?.Content ?? "";
|
||||||
|
|
||||||
|
var aiQuery = BuildQuery(result, request.Question, answer, request.DeviceId, request.UserId, null, stopwatch.ElapsedMilliseconds);
|
||||||
|
await aiQueryService.SaveQueryAsync(aiQuery, cancellationToken);
|
||||||
|
|
||||||
|
return Ok(new
|
||||||
|
{
|
||||||
|
question = request.Question,
|
||||||
|
answer = answer,
|
||||||
|
deviceId = request.DeviceId,
|
||||||
|
tokens = new
|
||||||
|
{
|
||||||
|
prompt = aiQuery.PromptTokens,
|
||||||
|
completion = aiQuery.CompletionTokens,
|
||||||
|
total = aiQuery.TotalTokens
|
||||||
|
},
|
||||||
|
costUsd = aiQuery.CostUsd,
|
||||||
|
profileId = aiQuery.ProfileId,
|
||||||
|
responseTimeMs = aiQuery.ResponseTimeMs,
|
||||||
|
timestamp = DateTime.UtcNow
|
||||||
|
});
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.LogError(ex, "Error processing AI question");
|
||||||
|
return StatusCode(500, new { error = "An error occurred while processing your question" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Send a complex chat request with multiple messages to the AI
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("chat")]
|
||||||
|
public async Task<IActionResult> Chat([FromBody] ExtendedChatRequest request, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var stopwatch = Stopwatch.StartNew();
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (request.Messages == null || !request.Messages.Any())
|
||||||
|
{
|
||||||
|
return BadRequest(new { error = "At least one message is required" });
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.LogInformation("Processing AI chat with {MessageCount} messages", request.Messages.Count);
|
||||||
|
|
||||||
|
// ponytail: the active profile's model wins over request.Model — analysis is
|
||||||
|
// always supposed to run on the configured profile; temperature/maxTokens still apply.
|
||||||
|
var result = await aiProfileService.AskAsync(
|
||||||
|
request.Messages,
|
||||||
|
temperature: request.Temperature,
|
||||||
|
maxTokens: request.MaxTokens,
|
||||||
|
cancellationToken: cancellationToken);
|
||||||
|
|
||||||
|
stopwatch.Stop();
|
||||||
|
|
||||||
|
if (result.Response == null || result.Response.Choices == null || !result.Response.Choices.Any())
|
||||||
|
{
|
||||||
|
return StatusCode(500, new { error = "No response received from AI" });
|
||||||
|
}
|
||||||
|
|
||||||
|
var userMessage = request.Messages.LastOrDefault(m => m.Role == "user");
|
||||||
|
var question = userMessage?.Content ?? "Complex chat";
|
||||||
|
var answer = result.Response.Choices.FirstOrDefault()?.Message?.Content ?? "";
|
||||||
|
|
||||||
|
var aiQuery = BuildQuery(result, question, answer, request.DeviceId, request.UserId, request.Temperature, stopwatch.ElapsedMilliseconds);
|
||||||
|
await aiQueryService.SaveQueryAsync(aiQuery, cancellationToken);
|
||||||
|
|
||||||
|
var response = result.Response;
|
||||||
|
return Ok(new
|
||||||
|
{
|
||||||
|
response.Id,
|
||||||
|
response.Object,
|
||||||
|
response.Created,
|
||||||
|
response.Model,
|
||||||
|
response.Choices,
|
||||||
|
response.Usage,
|
||||||
|
costUsd = aiQuery.CostUsd,
|
||||||
|
profileId = aiQuery.ProfileId,
|
||||||
|
responseTimeMs = aiQuery.ResponseTimeMs
|
||||||
|
});
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.LogError(ex, "Error processing AI chat");
|
||||||
|
return StatusCode(500, new { error = "An error occurred while processing your chat request" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Get suggestions for smart home automation based on device data
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("suggest")]
|
||||||
|
public async Task<IActionResult> GetSuggestions([FromBody] SuggestionRequest request, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var stopwatch = Stopwatch.StartNew();
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var systemPrompt = @"شما یک مشاور هوشمند خانه هوشمند هستید. بر اساس دادههای دستگاههای IoT، پیشنهادهای عملی و مفید برای بهینهسازی مصرف انرژی، راحتی و امنیت ارائه دهید. پاسخ را به زبان فارسی و به صورت خلاصه و کاربردی بنویسید.";
|
||||||
|
|
||||||
|
var question = $@"وضعیت فعلی دستگاههای خانه هوشمند:
|
||||||
|
{request.DeviceContext}
|
||||||
|
|
||||||
|
لطفاً پیشنهادات خود را برای بهبود وضعیت ارائه دهید.";
|
||||||
|
|
||||||
|
var messages = new List<ChatMessage>
|
||||||
|
{
|
||||||
|
new ChatMessage { Role = "system", Content = systemPrompt },
|
||||||
|
new ChatMessage { Role = "user", Content = question }
|
||||||
|
};
|
||||||
|
|
||||||
|
var result = await aiProfileService.AskAsync(messages, cancellationToken: cancellationToken);
|
||||||
|
|
||||||
|
stopwatch.Stop();
|
||||||
|
|
||||||
|
if (result.Response == null || result.Response.Choices == null || !result.Response.Choices.Any())
|
||||||
|
{
|
||||||
|
return StatusCode(500, new { error = "No suggestions received from AI" });
|
||||||
|
}
|
||||||
|
|
||||||
|
var answer = result.Response.Choices.FirstOrDefault()?.Message?.Content ?? "";
|
||||||
|
|
||||||
|
var aiQuery = BuildQuery(result, question, answer, request.DeviceId, request.UserId, null, stopwatch.ElapsedMilliseconds);
|
||||||
|
await aiQueryService.SaveQueryAsync(aiQuery, cancellationToken);
|
||||||
|
|
||||||
|
return Ok(new
|
||||||
|
{
|
||||||
|
suggestions = answer,
|
||||||
|
deviceId = request.DeviceId,
|
||||||
|
tokens = new
|
||||||
|
{
|
||||||
|
prompt = aiQuery.PromptTokens,
|
||||||
|
completion = aiQuery.CompletionTokens,
|
||||||
|
total = aiQuery.TotalTokens
|
||||||
|
},
|
||||||
|
costUsd = aiQuery.CostUsd,
|
||||||
|
profileId = aiQuery.ProfileId,
|
||||||
|
responseTimeMs = aiQuery.ResponseTimeMs,
|
||||||
|
timestamp = DateTime.UtcNow
|
||||||
|
});
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.LogError(ex, "Error getting AI suggestions");
|
||||||
|
return StatusCode(500, new { error = "An error occurred while getting suggestions" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Get AI query history for a device
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet("history/device/{deviceId}")]
|
||||||
|
public async Task<IActionResult> GetDeviceHistory(int deviceId, [FromQuery] int take = 50, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var queries = await aiQueryService.GetDeviceQueriesAsync(deviceId, take, cancellationToken);
|
||||||
|
var totalTokens = await aiQueryService.GetDeviceTotalTokensAsync(deviceId, cancellationToken);
|
||||||
|
|
||||||
|
return Ok(new
|
||||||
|
{
|
||||||
|
queries = queries.Select(q => new
|
||||||
|
{
|
||||||
|
q.Id,
|
||||||
|
q.Question,
|
||||||
|
q.Answer,
|
||||||
|
q.TotalTokens,
|
||||||
|
q.PromptTokens,
|
||||||
|
q.CompletionTokens,
|
||||||
|
q.CostUsd,
|
||||||
|
q.Model,
|
||||||
|
q.ProfileId,
|
||||||
|
q.ResponseTimeMs,
|
||||||
|
q.CreatedAt
|
||||||
|
}),
|
||||||
|
totalTokens
|
||||||
|
});
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.LogError(ex, "Error getting device history");
|
||||||
|
return StatusCode(500, new { error = "An error occurred" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Get AI query statistics
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet("stats")]
|
||||||
|
public async Task<IActionResult> GetStats(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var stats = await aiQueryService.GetStatsAsync(cancellationToken);
|
||||||
|
return Ok(stats);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.LogError(ex, "Error getting stats");
|
||||||
|
return StatusCode(500, new { error = "An error occurred" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Builds an AIQuery row from a profile ask result, attaching profile,
|
||||||
|
/// tokens and the estimated cost.
|
||||||
|
/// </summary>
|
||||||
|
private static AIQuery BuildQuery(
|
||||||
|
AIAskResult result,
|
||||||
|
string question,
|
||||||
|
string answer,
|
||||||
|
int? deviceId,
|
||||||
|
int? userId,
|
||||||
|
double? temperature,
|
||||||
|
long responseTimeMs)
|
||||||
|
{
|
||||||
|
var profile = result.Profile;
|
||||||
|
var usage = result.Response!.Usage;
|
||||||
|
|
||||||
|
var query = new AIQuery
|
||||||
|
{
|
||||||
|
Question = question,
|
||||||
|
Answer = answer,
|
||||||
|
DeviceId = deviceId,
|
||||||
|
UserId = userId,
|
||||||
|
Model = result.Response.Model,
|
||||||
|
ProfileId = profile?.Id,
|
||||||
|
CostUsd = profile != null
|
||||||
|
? IAIProfileService.EstimateCost(profile.PromptPricePer1M, profile.CompletionPricePer1M, usage?.PromptTokens ?? 0, usage?.CompletionTokens ?? 0)
|
||||||
|
: 0m,
|
||||||
|
Temperature = temperature,
|
||||||
|
PromptTokens = usage?.PromptTokens ?? 0,
|
||||||
|
CompletionTokens = usage?.CompletionTokens ?? 0,
|
||||||
|
TotalTokens = usage?.TotalTokens ?? 0,
|
||||||
|
ResponseTimeMs = responseTimeMs
|
||||||
|
};
|
||||||
|
return query;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Simple question request model
|
||||||
|
/// </summary>
|
||||||
|
public class SimpleQuestionRequest
|
||||||
|
{
|
||||||
|
public required string Question { get; set; }
|
||||||
|
public string? SystemPrompt { get; set; }
|
||||||
|
public int? DeviceId { get; set; }
|
||||||
|
public int? UserId { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Extended chat request with device tracking
|
||||||
|
/// </summary>
|
||||||
|
public class ExtendedChatRequest
|
||||||
|
{
|
||||||
|
public required List<ChatMessage> Messages { get; set; }
|
||||||
|
public string? Model { get; set; }
|
||||||
|
public double? Temperature { get; set; }
|
||||||
|
public int? MaxTokens { get; set; }
|
||||||
|
public int? DeviceId { get; set; }
|
||||||
|
public int? UserId { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Suggestion request for smart home automation
|
||||||
|
/// </summary>
|
||||||
|
public class SuggestionRequest
|
||||||
|
{
|
||||||
|
public required string DeviceContext { get; set; }
|
||||||
|
public int? DeviceId { get; set; }
|
||||||
|
public int? UserId { get; set; }
|
||||||
|
}
|
||||||
456
src/GreenHome.Api/Controllers/AdminController.cs
Normal file
@@ -0,0 +1,456 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Text;
|
||||||
|
using GreenHome.Api.Filters;
|
||||||
|
using GreenHome.Application;
|
||||||
|
using GreenHome.Application.Dtos.Admin;
|
||||||
|
using GreenHome.Domain;
|
||||||
|
using GreenHome.Infrastructure.Services.AI;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
|
namespace GreenHome.Api.Controllers;
|
||||||
|
|
||||||
|
[ApiController]
|
||||||
|
[Route("api/admin")]
|
||||||
|
[ServiceFilter(typeof(AdminAuthFilter))]
|
||||||
|
public sealed class AdminController : ControllerBase
|
||||||
|
{
|
||||||
|
private readonly IAdminService _adminService;
|
||||||
|
private readonly IAIProfileService _aiProfileService;
|
||||||
|
|
||||||
|
public AdminController(IAdminService adminService, IAIProfileService aiProfileService)
|
||||||
|
{
|
||||||
|
_adminService = adminService;
|
||||||
|
_aiProfileService = aiProfileService;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== Dashboard ====================
|
||||||
|
|
||||||
|
[HttpGet("dashboard")]
|
||||||
|
public async Task<ActionResult<AdminDashboardDto>> Dashboard(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var result = await _adminService.GetDashboardAsync(cancellationToken);
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== Users ====================
|
||||||
|
|
||||||
|
[HttpGet("users")]
|
||||||
|
public async Task<ActionResult<PagedResult<AdminUserListItemDto>>> Users(
|
||||||
|
[FromQuery] string? search,
|
||||||
|
[FromQuery] int page = 1,
|
||||||
|
[FromQuery] int pageSize = 20,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
var filter = new AdminUserFilter
|
||||||
|
{
|
||||||
|
Search = search,
|
||||||
|
Page = Math.Max(1, page),
|
||||||
|
PageSize = Math.Clamp(pageSize, 1, 100)
|
||||||
|
};
|
||||||
|
|
||||||
|
var result = await _adminService.GetUsersAsync(filter, cancellationToken);
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("users/{id:int}")]
|
||||||
|
public async Task<ActionResult<AdminUserDetailDto>> GetUser(int id, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var result = await _adminService.GetUserAsync(id, cancellationToken);
|
||||||
|
return result is null ? NotFound() : Ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPut("users/{id:int}/role")]
|
||||||
|
public async Task<IActionResult> SetUserRole(int id, [FromBody] ChangeUserRoleRequest request, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var currentAdminId = ((UserDto)HttpContext.Items["AdminUser"]!).Id;
|
||||||
|
var outcome = await _adminService.SetUserRoleAsync(id, request.Role, currentAdminId, cancellationToken);
|
||||||
|
return outcome switch
|
||||||
|
{
|
||||||
|
UserMutationOutcome.Ok => Ok(new { success = true }),
|
||||||
|
UserMutationOutcome.NotFound => NotFound(),
|
||||||
|
UserMutationOutcome.ConflictSelf => Conflict(new { message = "نمیتوانید نقش خود را تغییر دهید" }),
|
||||||
|
UserMutationOutcome.ConflictLastAdmin => Conflict(new { message = "آخرین مدیر را نمیتوان تغییر نقش داد" }),
|
||||||
|
_ => NotFound()
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPut("users/{id:int}/status")]
|
||||||
|
public async Task<IActionResult> SetUserStatus(int id, [FromBody] ChangeUserStatusRequest request, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var currentAdminId = ((UserDto)HttpContext.Items["AdminUser"]!).Id;
|
||||||
|
var outcome = await _adminService.SetUserStatusAsync(id, request.IsEnabled, currentAdminId, cancellationToken);
|
||||||
|
return outcome switch
|
||||||
|
{
|
||||||
|
UserMutationOutcome.Ok => Ok(new { success = true }),
|
||||||
|
UserMutationOutcome.NotFound => NotFound(),
|
||||||
|
UserMutationOutcome.ConflictSelf => Conflict(new { message = "نمیتوانید اکانت خود را غیرفعال کنید" }),
|
||||||
|
UserMutationOutcome.ConflictLastAdmin => Conflict(new { message = "آخرین مدیر فعال را نمیتوان غیرفعال کرد" }),
|
||||||
|
_ => NotFound()
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== Devices ====================
|
||||||
|
|
||||||
|
[HttpGet("devices")]
|
||||||
|
public async Task<ActionResult<PagedResult<AdminDeviceListItemDto>>> Devices(
|
||||||
|
[FromQuery] string? search,
|
||||||
|
[FromQuery] int page = 1,
|
||||||
|
[FromQuery] int pageSize = 20,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
var filter = new AdminDeviceFilter
|
||||||
|
{
|
||||||
|
Search = search,
|
||||||
|
Page = Math.Max(1, page),
|
||||||
|
PageSize = Math.Clamp(pageSize, 1, 100)
|
||||||
|
};
|
||||||
|
|
||||||
|
var result = await _adminService.GetDevicesAsync(filter, cancellationToken);
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("devices/{id:int}")]
|
||||||
|
public async Task<ActionResult<AdminDeviceDetailDto>> GetDevice(int id, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var result = await _adminService.GetDeviceAsync(id, cancellationToken);
|
||||||
|
return result is null ? NotFound() : Ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost("devices")]
|
||||||
|
public async Task<IActionResult> CreateDevice([FromBody] AdminDeviceCreateRequest request, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var currentAdminId = ((UserDto)HttpContext.Items["AdminUser"]!).Id;
|
||||||
|
var result = await _adminService.CreateDeviceAsync(request, currentAdminId, cancellationToken);
|
||||||
|
return result.Outcome switch
|
||||||
|
{
|
||||||
|
AdminDeviceCreateOutcome.Ok => Ok(new { id = result.DeviceId, deviceName = result.DeviceName }),
|
||||||
|
AdminDeviceCreateOutcome.UserNotFound => NotFound(new { message = "کاربر مورد نظر یافت نشد" }),
|
||||||
|
AdminDeviceCreateOutcome.ConflictDuplicateName => Conflict(new { message = result.Message }),
|
||||||
|
_ => BadRequest(new { message = result.Message })
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPut("devices/{id:int}/settings")]
|
||||||
|
public async Task<IActionResult> UpdateDeviceSettings(int id, [FromBody] AdminDeviceSettingsUpdateRequest request, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var currentAdminId = ((UserDto)HttpContext.Items["AdminUser"]!).Id;
|
||||||
|
var result = await _adminService.UpdateDeviceSettingsAsync(id, request, currentAdminId, cancellationToken);
|
||||||
|
if (result.NotFound) return NotFound(new { message = "دستگاه یافت نشد" });
|
||||||
|
if (result.Message is not null) return BadRequest(new { message = result.Message });
|
||||||
|
return Ok(new { success = true });
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("devices/{id:int}/settings")]
|
||||||
|
public async Task<ActionResult<AdminDeviceDetailDto>> GetDeviceSettings(int id, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var result = await _adminService.GetDeviceAsync(id, cancellationToken);
|
||||||
|
return result is null ? NotFound(new { message = "دستگاه یافت نشد" }) : Ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("devices/{id:int}/members")]
|
||||||
|
public async Task<ActionResult<IReadOnlyList<AdminDeviceMemberDto>>> GetDeviceMembers(int id, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var result = await _adminService.GetDeviceMembersAsync(id, cancellationToken);
|
||||||
|
return result is null ? NotFound(new { message = "دستگاه یافت نشد" }) : Ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== Usage ====================
|
||||||
|
|
||||||
|
[HttpGet("usage")]
|
||||||
|
public async Task<ActionResult<IReadOnlyList<UsageDayDto>>> Usage(
|
||||||
|
[FromQuery] DateTime? from,
|
||||||
|
[FromQuery] DateTime? to,
|
||||||
|
[FromQuery] int? userId,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
var result = await _adminService.GetUsageAsync(from, to, userId, cancellationToken);
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== Alerts ====================
|
||||||
|
|
||||||
|
[HttpGet("alerts")]
|
||||||
|
public async Task<ActionResult<PagedResult<AdminAlertItemDto>>> Alerts(
|
||||||
|
[FromQuery] int? deviceId,
|
||||||
|
[FromQuery] Domain.AlertStatus? status,
|
||||||
|
[FromQuery] DateTime? from,
|
||||||
|
[FromQuery] DateTime? to,
|
||||||
|
[FromQuery] int page = 1,
|
||||||
|
[FromQuery] int pageSize = 20,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
var filter = new AdminAlertFilter
|
||||||
|
{
|
||||||
|
DeviceId = deviceId,
|
||||||
|
Status = status,
|
||||||
|
From = from,
|
||||||
|
To = to,
|
||||||
|
Page = Math.Max(1, page),
|
||||||
|
PageSize = Math.Clamp(pageSize, 1, 100)
|
||||||
|
};
|
||||||
|
|
||||||
|
var result = await _adminService.GetAlertsAsync(filter, cancellationToken);
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== Posts ====================
|
||||||
|
|
||||||
|
[HttpGet("posts")]
|
||||||
|
public async Task<ActionResult<PagedResult<AdminPostItemDto>>> Posts(
|
||||||
|
[FromQuery] int? deviceId,
|
||||||
|
[FromQuery] int? authorUserId,
|
||||||
|
[FromQuery] Domain.DevicePostType? postType,
|
||||||
|
[FromQuery] DateTime? from,
|
||||||
|
[FromQuery] DateTime? to,
|
||||||
|
[FromQuery] int page = 1,
|
||||||
|
[FromQuery] int pageSize = 20,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
var filter = new AdminPostFilter
|
||||||
|
{
|
||||||
|
DeviceId = deviceId,
|
||||||
|
AuthorUserId = authorUserId,
|
||||||
|
PostType = postType,
|
||||||
|
From = from,
|
||||||
|
To = to,
|
||||||
|
Page = Math.Max(1, page),
|
||||||
|
PageSize = Math.Clamp(pageSize, 1, 100)
|
||||||
|
};
|
||||||
|
|
||||||
|
var result = await _adminService.GetPostsAsync(filter, cancellationToken);
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("posts/{id:int}")]
|
||||||
|
public async Task<ActionResult<AdminPostDetailDto>> GetPost(int id, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var result = await _adminService.GetPostAsync(id, cancellationToken);
|
||||||
|
return result is null ? NotFound(new { message = "پست یافت نشد" }) : Ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpDelete("posts/{id:int}")]
|
||||||
|
public async Task<IActionResult> DeletePost(int id, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var currentAdminId = ((UserDto)HttpContext.Items["AdminUser"]!).Id;
|
||||||
|
var deleted = await _adminService.DeletePostAsync(id, currentAdminId, cancellationToken);
|
||||||
|
return deleted ? Ok(new { success = true }) : NotFound();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== Device Debug ====================
|
||||||
|
|
||||||
|
[HttpPost("devices/{id:int}/test-sms")]
|
||||||
|
public async Task<ActionResult<AdminDeviceTestResultDto>> TestDeviceSms(int id, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var currentAdminId = ((UserDto)HttpContext.Items["AdminUser"]!).Id;
|
||||||
|
var result = await _adminService.TestDeviceSmsAsync(id, currentAdminId, cancellationToken);
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost("devices/{id:int}/test-voice")]
|
||||||
|
public async Task<ActionResult<AdminDeviceTestResultDto>> TestDeviceVoice(int id, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var currentAdminId = ((UserDto)HttpContext.Items["AdminUser"]!).Id;
|
||||||
|
var result = await _adminService.TestDeviceVoiceAsync(id, currentAdminId, cancellationToken);
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== Reports ====================
|
||||||
|
|
||||||
|
[HttpGet("reports/users")]
|
||||||
|
public async Task<IActionResult> ReportUsers(
|
||||||
|
[FromQuery] DateTime? from, [FromQuery] DateTime? to, [FromQuery] bool csv, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var (f, t) = ResolveReportRange(from, to);
|
||||||
|
var rows = await _adminService.GetUserGrowthReportAsync(f, t, cancellationToken);
|
||||||
|
if (csv)
|
||||||
|
return ToCsvFile("report-users",
|
||||||
|
new[] { "تاریخ", "کاربران جدید", "کاربران فعال" },
|
||||||
|
rows.Select(r => new[] { r.Date.ToString("yyyy-MM-dd"), r.NewUsers.ToString(CultureInfo.InvariantCulture), r.ActiveUsers.ToString(CultureInfo.InvariantCulture) }), t);
|
||||||
|
return Ok(rows);
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("reports/devices-uptime")]
|
||||||
|
public async Task<IActionResult> ReportDeviceUptime(
|
||||||
|
[FromQuery] DateTime? from, [FromQuery] DateTime? to, [FromQuery] bool csv, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var (f, t) = ResolveReportRange(from, to);
|
||||||
|
var rows = await _adminService.GetDeviceUptimeReportAsync(f, t, cancellationToken);
|
||||||
|
if (csv)
|
||||||
|
return ToCsvFile("report-devices-uptime",
|
||||||
|
new[] { "دستگاه", "مالک", "کل روزها", "روزهای آنلاین", "درصد آنلاین" },
|
||||||
|
rows.Select(r => new[] { r.DeviceName, r.OwnerName, r.TotalDays.ToString(CultureInfo.InvariantCulture), r.OnlineDays.ToString(CultureInfo.InvariantCulture), r.OnlinePercent.ToString(CultureInfo.InvariantCulture) }), t);
|
||||||
|
return Ok(rows);
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("reports/usage-by-user")]
|
||||||
|
public async Task<IActionResult> ReportUsageByUser(
|
||||||
|
[FromQuery] DateTime? from, [FromQuery] DateTime? to, [FromQuery] bool csv, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var (f, t) = ResolveReportRange(from, to);
|
||||||
|
var rows = await _adminService.GetUsageByUserReportAsync(f, t, cancellationToken);
|
||||||
|
if (csv)
|
||||||
|
return ToCsvFile("report-usage-by-user",
|
||||||
|
new[] { "نام", "نام خانوادگی", "موبایل", "پیامک", "تماس صوتی", "درخواست هوش مصنوعی", "توکن هوش مصنوعی" },
|
||||||
|
rows.Select(r => new[] { r.Name, r.Family, r.Mobile, r.Sms.ToString(CultureInfo.InvariantCulture), r.VoiceCall.ToString(CultureInfo.InvariantCulture), r.AiQueries.ToString(CultureInfo.InvariantCulture), r.AiTokens.ToString(CultureInfo.InvariantCulture) }), t);
|
||||||
|
return Ok(rows);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ponytail: day boundary is UTC (whole system is UTC); if user timezone matters later, make report range timezone-aware.
|
||||||
|
private static (DateTime From, DateTime To) ResolveReportRange(DateTime? from, DateTime? to)
|
||||||
|
{
|
||||||
|
var t = (to ?? DateTime.UtcNow).Date;
|
||||||
|
var f = (from ?? t.AddDays(-6)).Date;
|
||||||
|
return (f, t);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ponytail: CSV via StringBuilder — fine at report size; swap for a streaming writer if reports grow.
|
||||||
|
private static FileContentResult ToCsvFile(string name, string[] headers, IEnumerable<string[]> rows, DateTime reportDate)
|
||||||
|
{
|
||||||
|
var sb = new StringBuilder();
|
||||||
|
sb.Append('\uFEFF'); // UTF-8 BOM so Excel detects Persian correctly
|
||||||
|
sb.Append(string.Join(",", headers.Select(EscapeCsv))).Append('\n');
|
||||||
|
foreach (var row in rows)
|
||||||
|
sb.Append(string.Join(",", row.Select(EscapeCsv))).Append('\n');
|
||||||
|
var result = new FileContentResult(Encoding.UTF8.GetBytes(sb.ToString()), "text/csv; charset=utf-8");
|
||||||
|
result.FileDownloadName = $"{name}-{reportDate:yyyy-MM-dd}.csv";
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string EscapeCsv(string? value)
|
||||||
|
{
|
||||||
|
var v = value ?? string.Empty;
|
||||||
|
return v.Contains(',') || v.Contains('"') || v.Contains('\n') ? $"\"{v.Replace("\"", "\"\"")}\"" : v;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== Audit Log ====================
|
||||||
|
|
||||||
|
[HttpGet("audit-logs")]
|
||||||
|
public async Task<ActionResult<PagedResult<AdminAuditLogDto>>> AuditLogs(
|
||||||
|
[FromQuery] int? adminId,
|
||||||
|
[FromQuery] int page = 1,
|
||||||
|
[FromQuery] int pageSize = 20,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
var filter = new AdminAuditLogFilter
|
||||||
|
{
|
||||||
|
AdminId = adminId,
|
||||||
|
Page = Math.Max(1, page),
|
||||||
|
PageSize = Math.Clamp(pageSize, 1, 100)
|
||||||
|
};
|
||||||
|
|
||||||
|
var result = await _adminService.GetAuditLogsAsync(filter, cancellationToken);
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== AI Profiles ====================
|
||||||
|
|
||||||
|
[HttpGet("ai-profiles")]
|
||||||
|
public async Task<ActionResult<List<AIProfileDto>>> AiProfiles(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var result = await _aiProfileService.GetProfilesAsync(cancellationToken);
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost("ai-profiles")]
|
||||||
|
public async Task<IActionResult> CreateAiProfile([FromBody] AIProfileCreateRequest request, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var currentAdminId = ((UserDto)HttpContext.Items["AdminUser"]!).Id;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = await _aiProfileService.CreateProfileAsync(request, currentAdminId, cancellationToken);
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
catch (ArgumentException ex)
|
||||||
|
{
|
||||||
|
return BadRequest(new { message = ex.Message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPut("ai-profiles/{id:int}")]
|
||||||
|
public async Task<IActionResult> UpdateAiProfile(int id, [FromBody] AIProfileUpdateRequest request, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var currentAdminId = ((UserDto)HttpContext.Items["AdminUser"]!).Id;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = await _aiProfileService.UpdateProfileAsync(id, request, currentAdminId, cancellationToken);
|
||||||
|
return result is null ? NotFound() : Ok(result);
|
||||||
|
}
|
||||||
|
catch (ArgumentException ex)
|
||||||
|
{
|
||||||
|
return BadRequest(new { message = ex.Message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpDelete("ai-profiles/{id:int}")]
|
||||||
|
public async Task<IActionResult> DeleteAiProfile(int id, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var currentAdminId = ((UserDto)HttpContext.Items["AdminUser"]!).Id;
|
||||||
|
var success = await _aiProfileService.DeleteProfileAsync(id, currentAdminId, cancellationToken);
|
||||||
|
return success ? Ok(new { success = true }) : NotFound();
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost("ai-profiles/{id:int}/activate")]
|
||||||
|
public async Task<IActionResult> ActivateAiProfile(int id, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var currentAdminId = ((UserDto)HttpContext.Items["AdminUser"]!).Id;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = await _aiProfileService.ActivateProfileAsync(id, currentAdminId, cancellationToken);
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
catch (KeyNotFoundException)
|
||||||
|
{
|
||||||
|
return NotFound();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("ai-profiles/{id:int}/models")]
|
||||||
|
public async Task<IActionResult> GetAiProfileModels(int id, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var models = await _aiProfileService.GetModelsAsync(id, cancellationToken);
|
||||||
|
return Ok(models);
|
||||||
|
}
|
||||||
|
catch (KeyNotFoundException)
|
||||||
|
{
|
||||||
|
return NotFound();
|
||||||
|
}
|
||||||
|
catch (Exception)
|
||||||
|
{
|
||||||
|
return StatusCode(502, new { message = "خطا در دریافت لیست مدلها از سرویس" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost("ai-profiles/{id:int}/refresh-balance")]
|
||||||
|
public async Task<IActionResult> RefreshAiProfileBalance(int id, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var balance = await _aiProfileService.RefreshBalanceAsync(id, cancellationToken);
|
||||||
|
return Ok(balance is null
|
||||||
|
? new { success = false, message = "دریافت موجودی برای این سرویس در دسترس نیست" }
|
||||||
|
: new { success = true, balance });
|
||||||
|
}
|
||||||
|
catch (KeyNotFoundException)
|
||||||
|
{
|
||||||
|
return NotFound();
|
||||||
|
}
|
||||||
|
catch (Exception)
|
||||||
|
{
|
||||||
|
return StatusCode(502, new { message = "خطا در دریافت موجودی از سرویس" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("ai-profiles/{id:int}/usage/daily")]
|
||||||
|
public async Task<ActionResult<List<AIProfileUsageDayDto>>> GetAiProfileUsage(
|
||||||
|
int id,
|
||||||
|
[FromQuery] DateTime? from,
|
||||||
|
[FromQuery] DateTime? to,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var (f, t) = ResolveReportRange(from, to);
|
||||||
|
var result = await _aiProfileService.GetUsageByDayAsync(id, f, t.AddDays(1), cancellationToken);
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
}
|
||||||
95
src/GreenHome.Api/Controllers/AlertConditionsController.cs
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using GreenHome.Application;
|
||||||
|
|
||||||
|
namespace GreenHome.Api.Controllers;
|
||||||
|
|
||||||
|
[ApiController]
|
||||||
|
[Route("api/[controller]")]
|
||||||
|
public class AlertConditionsController : ControllerBase
|
||||||
|
{
|
||||||
|
private readonly IAlertConditionService alertConditionService;
|
||||||
|
|
||||||
|
public AlertConditionsController(IAlertConditionService alertConditionService)
|
||||||
|
{
|
||||||
|
this.alertConditionService = alertConditionService;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// دریافت تمام شرایط هشدار یک دستگاه
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet("device/{deviceId}")]
|
||||||
|
public async Task<ActionResult<IReadOnlyList<AlertConditionDto>>> GetByDeviceId(int deviceId, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var result = await alertConditionService.GetByDeviceIdAsync(deviceId, cancellationToken);
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// دریافت یک شرط هشدار با ID
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet("{id}")]
|
||||||
|
public async Task<ActionResult<AlertConditionDto>> GetById(int id, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var result = await alertConditionService.GetByIdAsync(id, cancellationToken);
|
||||||
|
if (result == null)
|
||||||
|
{
|
||||||
|
return NotFound();
|
||||||
|
}
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ایجاد شرط هشدار جدید
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost]
|
||||||
|
public async Task<ActionResult<int>> Create(CreateAlertConditionRequest request, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var id = await alertConditionService.CreateAsync(request, cancellationToken);
|
||||||
|
return Ok(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// بهروزرسانی شرط هشدار
|
||||||
|
/// </summary>
|
||||||
|
[HttpPut]
|
||||||
|
public async Task<ActionResult> Update(UpdateAlertConditionRequest request, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
await alertConditionService.UpdateAsync(request, cancellationToken);
|
||||||
|
return Ok();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// حذف شرط هشدار
|
||||||
|
/// </summary>
|
||||||
|
[HttpDelete("{id}")]
|
||||||
|
public async Task<ActionResult> Delete(int id, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
await alertConditionService.DeleteAsync(id, cancellationToken);
|
||||||
|
return Ok();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// فعال/غیرفعال کردن شرط هشدار
|
||||||
|
/// </summary>
|
||||||
|
[HttpPatch("{id}/toggle")]
|
||||||
|
public async Task<ActionResult> ToggleEnabled(int id, [FromBody] bool isEnabled, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var result = await alertConditionService.ToggleEnabledAsync(id, isEnabled, cancellationToken);
|
||||||
|
if (!result)
|
||||||
|
{
|
||||||
|
return NotFound();
|
||||||
|
}
|
||||||
|
return Ok();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// دریافت شرایط هشدار رلهای (notificationType > 0) برای یک دستگاه
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet("relay/{deviceId}")]
|
||||||
|
public async Task<ActionResult<object>> GetRelayConditions(int deviceId, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var conditions = await alertConditionService.GetRelayConditionsAsync(deviceId, cancellationToken);
|
||||||
|
return Ok(new { conditions });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
62
src/GreenHome.Api/Controllers/AlertLogsController.cs
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using GreenHome.Application;
|
||||||
|
|
||||||
|
namespace GreenHome.Api.Controllers;
|
||||||
|
|
||||||
|
[ApiController]
|
||||||
|
[Route("api/[controller]")]
|
||||||
|
public class AlertLogsController : ControllerBase
|
||||||
|
{
|
||||||
|
private readonly IAlertLogService _alertLogService;
|
||||||
|
|
||||||
|
public AlertLogsController(IAlertLogService alertLogService)
|
||||||
|
{
|
||||||
|
_alertLogService = alertLogService;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// دریافت لیست لاگهای هشدار با فیلتر و صفحهبندی
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet]
|
||||||
|
public async Task<ActionResult<PagedResult<AlertLogDto>>> GetAlertLogs(
|
||||||
|
[FromQuery] int? deviceId,
|
||||||
|
[FromQuery] int? userId,
|
||||||
|
[FromQuery] Domain.AlertType? alertType,
|
||||||
|
[FromQuery] Domain.AlertStatus? status,
|
||||||
|
[FromQuery] DateTime? startDate,
|
||||||
|
[FromQuery] DateTime? endDate,
|
||||||
|
[FromQuery] int page = 1,
|
||||||
|
[FromQuery] int pageSize = 20,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
var filter = new AlertLogFilter
|
||||||
|
{
|
||||||
|
DeviceId = deviceId,
|
||||||
|
UserId = userId,
|
||||||
|
AlertType = alertType,
|
||||||
|
Status = status,
|
||||||
|
StartDate = startDate,
|
||||||
|
EndDate = endDate,
|
||||||
|
Page = page,
|
||||||
|
PageSize = pageSize
|
||||||
|
};
|
||||||
|
|
||||||
|
var result = await _alertLogService.GetAlertLogsAsync(filter, cancellationToken);
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// دریافت جزئیات کامل یک لاگ هشدار
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet("{id}")]
|
||||||
|
public async Task<ActionResult<AlertLogDto>> GetAlertLogById(int id, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var result = await _alertLogService.GetAlertLogByIdAsync(id, cancellationToken);
|
||||||
|
if (result == null)
|
||||||
|
{
|
||||||
|
return NotFound(new { error = $"لاگ هشدار با شناسه {id} یافت نشد" });
|
||||||
|
}
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -52,5 +52,23 @@ public class AuthController : ControllerBase
|
|||||||
var canResend = await authService.CanResendCodeAsync(mobile, cancellationToken);
|
var canResend = await authService.CanResendCodeAsync(mobile, cancellationToken);
|
||||||
return Ok(new { canResend });
|
return Ok(new { canResend });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[HttpGet("me")]
|
||||||
|
public async Task<ActionResult<UserDto>> Me(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var authHeader = Request.Headers.Authorization.ToString();
|
||||||
|
var token = authHeader.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)
|
||||||
|
? authHeader.Substring("Bearer ".Length).Trim()
|
||||||
|
: null;
|
||||||
|
|
||||||
|
if (string.IsNullOrEmpty(token))
|
||||||
|
return Unauthorized();
|
||||||
|
|
||||||
|
var user = await authService.GetUserByTokenAsync(token, cancellationToken);
|
||||||
|
if (user == null)
|
||||||
|
return Unauthorized();
|
||||||
|
|
||||||
|
return Ok(user);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
98
src/GreenHome.Api/Controllers/ChecklistsController.cs
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using GreenHome.Application;
|
||||||
|
|
||||||
|
namespace GreenHome.Api.Controllers;
|
||||||
|
|
||||||
|
[ApiController]
|
||||||
|
[Route("api/[controller]")]
|
||||||
|
public class ChecklistsController : ControllerBase
|
||||||
|
{
|
||||||
|
private readonly IChecklistService _checklistService;
|
||||||
|
|
||||||
|
public ChecklistsController(IChecklistService checklistService)
|
||||||
|
{
|
||||||
|
_checklistService = checklistService;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// دریافت چکلیست فعال یک دستگاه
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet("active/{deviceId}")]
|
||||||
|
public async Task<ActionResult<ChecklistDto>> GetActiveChecklist(int deviceId, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var result = await _checklistService.GetActiveChecklistByDeviceIdAsync(deviceId, cancellationToken);
|
||||||
|
if (result == null)
|
||||||
|
{
|
||||||
|
return NotFound(new { error = "چکلیست فعالی برای این دستگاه یافت نشد" });
|
||||||
|
}
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// دریافت تمام چکلیستهای یک دستگاه
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet("device/{deviceId}")]
|
||||||
|
public async Task<ActionResult<List<ChecklistDto>>> GetChecklists(int deviceId, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var result = await _checklistService.GetChecklistsByDeviceIdAsync(deviceId, cancellationToken);
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// دریافت جزئیات یک چکلیست
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet("{id}")]
|
||||||
|
public async Task<ActionResult<ChecklistDto>> GetChecklistById(int id, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var result = await _checklistService.GetChecklistByIdAsync(id, cancellationToken);
|
||||||
|
if (result == null)
|
||||||
|
{
|
||||||
|
return NotFound(new { error = $"چکلیست با شناسه {id} یافت نشد" });
|
||||||
|
}
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ایجاد چکلیست جدید (چکلیست قبلی غیرفعال میشود)
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost]
|
||||||
|
public async Task<ActionResult<int>> CreateChecklist(
|
||||||
|
CreateChecklistRequest request,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var id = await _checklistService.CreateChecklistAsync(request, cancellationToken);
|
||||||
|
return Ok(new { id, message = "چکلیست با موفقیت ایجاد شد و چکلیست قبلی غیرفعال شد" });
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// دریافت سابقه تکمیلهای یک چکلیست
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet("{checklistId}/completions")]
|
||||||
|
public async Task<ActionResult<List<ChecklistCompletionDto>>> GetCompletions(
|
||||||
|
int checklistId,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var result = await _checklistService.GetCompletionsByChecklistIdAsync(checklistId, cancellationToken);
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ثبت تکمیل چکلیست
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("complete")]
|
||||||
|
public async Task<ActionResult<int>> CompleteChecklist(
|
||||||
|
CompleteChecklistRequest request,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var id = await _checklistService.CompleteChecklistAsync(request, cancellationToken);
|
||||||
|
return Ok(new { id, message = "چکلیست با موفقیت تکمیل شد" });
|
||||||
|
}
|
||||||
|
catch (InvalidOperationException ex)
|
||||||
|
{
|
||||||
|
return NotFound(new { error = ex.Message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
143
src/GreenHome.Api/Controllers/DailyReportController.cs
Normal file
@@ -0,0 +1,143 @@
|
|||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using GreenHome.Application;
|
||||||
|
|
||||||
|
namespace GreenHome.Api.Controllers;
|
||||||
|
|
||||||
|
[ApiController]
|
||||||
|
[Route("api/[controller]")]
|
||||||
|
public class DailyReportController : ControllerBase
|
||||||
|
{
|
||||||
|
private readonly IDailyReportService _dailyReportService;
|
||||||
|
private readonly ILogger<DailyReportController> _logger;
|
||||||
|
|
||||||
|
public DailyReportController(
|
||||||
|
IDailyReportService dailyReportService,
|
||||||
|
ILogger<DailyReportController> logger)
|
||||||
|
{
|
||||||
|
_dailyReportService = dailyReportService;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// دریافت یا ایجاد گزارش تحلیل روزانه گلخانه
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="deviceId">شناسه دستگاه</param>
|
||||||
|
/// <param name="persianDate">تاریخ شمسی به فرمت yyyy/MM/dd</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token</param>
|
||||||
|
/// <returns>گزارش تحلیل روزانه</returns>
|
||||||
|
[HttpGet]
|
||||||
|
public async Task<ActionResult<DailyReportResponse>> GetDailyReport(
|
||||||
|
[FromQuery] int deviceId,
|
||||||
|
[FromQuery] string persianDate,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (deviceId <= 0)
|
||||||
|
{
|
||||||
|
return BadRequest(new { error = "شناسه دستگاه نامعتبر است" });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(persianDate))
|
||||||
|
{
|
||||||
|
return BadRequest(new { error = "تاریخ نباید خالی باشد" });
|
||||||
|
}
|
||||||
|
|
||||||
|
var request = new DailyReportRequest
|
||||||
|
{
|
||||||
|
DeviceId = deviceId,
|
||||||
|
PersianDate = persianDate.Trim()
|
||||||
|
};
|
||||||
|
|
||||||
|
var result = await _dailyReportService.GetOrCreateDailyReportAsync(request, cancellationToken);
|
||||||
|
|
||||||
|
_logger.LogInformation(
|
||||||
|
"گزارش روزانه برای دستگاه {DeviceId} و تاریخ {Date} با موفقیت برگشت داده شد (FromCache: {FromCache})",
|
||||||
|
deviceId, persianDate, result.FromCache);
|
||||||
|
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
catch (ArgumentException ex)
|
||||||
|
{
|
||||||
|
_logger.LogWarning(ex, "درخواست نامعتبر برای دستگاه {DeviceId} و تاریخ {Date}", deviceId, persianDate);
|
||||||
|
return BadRequest(new { error = ex.Message });
|
||||||
|
}
|
||||||
|
catch (InvalidOperationException ex)
|
||||||
|
{
|
||||||
|
_logger.LogWarning(ex, "خطا در پردازش گزارش روزانه برای دستگاه {DeviceId} و تاریخ {Date}", deviceId, persianDate);
|
||||||
|
return NotFound(new { error = ex.Message });
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "خطای سرور در دریافت گزارش روزانه برای دستگاه {DeviceId} و تاریخ {Date}", deviceId, persianDate);
|
||||||
|
return StatusCode(500, new { error = "خطای سرور در پردازش درخواست" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// دریافت تحلیل هفتگی
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet("weekly")]
|
||||||
|
public async Task<ActionResult<DailyReportResponse>> GetWeeklyAnalysis(
|
||||||
|
[FromQuery] int deviceId,
|
||||||
|
[FromQuery] string startDate,
|
||||||
|
[FromQuery] string endDate,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var request = new WeeklyAnalysisRequest
|
||||||
|
{
|
||||||
|
DeviceId = deviceId,
|
||||||
|
StartDate = startDate.Trim(),
|
||||||
|
EndDate = endDate.Trim()
|
||||||
|
};
|
||||||
|
|
||||||
|
var result = await _dailyReportService.GetWeeklyAnalysisAsync(request, cancellationToken);
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
catch (InvalidOperationException ex)
|
||||||
|
{
|
||||||
|
return BadRequest(new { error = ex.Message });
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error getting weekly analysis");
|
||||||
|
return StatusCode(500, new { error = "خطا در دریافت تحلیل هفتگی" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// دریافت تحلیل ماهانه
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet("monthly")]
|
||||||
|
public async Task<ActionResult<DailyReportResponse>> GetMonthlyAnalysis(
|
||||||
|
[FromQuery] int deviceId,
|
||||||
|
[FromQuery] int year,
|
||||||
|
[FromQuery] int month,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var request = new MonthlyAnalysisRequest
|
||||||
|
{
|
||||||
|
DeviceId = deviceId,
|
||||||
|
Year = year,
|
||||||
|
Month = month
|
||||||
|
};
|
||||||
|
|
||||||
|
var result = await _dailyReportService.GetMonthlyAnalysisAsync(request, cancellationToken);
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
catch (InvalidOperationException ex)
|
||||||
|
{
|
||||||
|
return BadRequest(new { error = ex.Message });
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error getting monthly analysis");
|
||||||
|
return StatusCode(500, new { error = "خطا در دریافت تحلیل ماهانه" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
120
src/GreenHome.Api/Controllers/DeviceMembersController.cs
Normal file
@@ -0,0 +1,120 @@
|
|||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using GreenHome.Application;
|
||||||
|
|
||||||
|
namespace GreenHome.Api.Controllers;
|
||||||
|
|
||||||
|
[ApiController]
|
||||||
|
[Route("api/[controller]")]
|
||||||
|
public class DeviceMembersController : ControllerBase
|
||||||
|
{
|
||||||
|
private readonly IDeviceMemberService _memberService;
|
||||||
|
private readonly IWebHostEnvironment _environment;
|
||||||
|
private readonly ILogger<DeviceMembersController> _logger;
|
||||||
|
|
||||||
|
public DeviceMembersController(
|
||||||
|
IDeviceMemberService memberService,
|
||||||
|
IWebHostEnvironment environment,
|
||||||
|
ILogger<DeviceMembersController> logger)
|
||||||
|
{
|
||||||
|
_memberService = memberService;
|
||||||
|
_environment = environment;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>لیست اعضای تیم یک دستگاه</summary>
|
||||||
|
[HttpGet]
|
||||||
|
public async Task<ActionResult<IReadOnlyList<DeviceMemberDto>>> List(
|
||||||
|
[FromQuery] int deviceId,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var result = await _memberService.ListByDeviceAsync(deviceId, cancellationToken);
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>افزودن یا ویرایش عضو تیم</summary>
|
||||||
|
[HttpPost]
|
||||||
|
public async Task<ActionResult<DeviceMemberDto>> Upsert(
|
||||||
|
[FromBody] UpsertDeviceMemberRequest request,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = await _memberService.UpsertAsync(request, cancellationToken);
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error upserting device member");
|
||||||
|
return BadRequest(new { error = ex.Message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>حذف عضو تیم</summary>
|
||||||
|
[HttpDelete]
|
||||||
|
public async Task<ActionResult> Delete(
|
||||||
|
[FromQuery] int deviceId,
|
||||||
|
[FromQuery] int userId,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await _memberService.DeleteAsync(deviceId, userId, cancellationToken);
|
||||||
|
return Ok(new { message = "عضو با موفقیت حذف شد" });
|
||||||
|
}
|
||||||
|
catch (InvalidOperationException ex)
|
||||||
|
{
|
||||||
|
return NotFound(new { error = ex.Message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>بررسی مجوز مدیریت تیم</summary>
|
||||||
|
[HttpGet("can-manage")]
|
||||||
|
public async Task<ActionResult<bool>> CanManage(
|
||||||
|
[FromQuery] int actorUserId,
|
||||||
|
[FromQuery] int deviceId,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var canManage = await _memberService.CanManageDeviceAsync(actorUserId, deviceId, cancellationToken);
|
||||||
|
return Ok(new { canManage });
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>آپلود آواتار عضو</summary>
|
||||||
|
[HttpPost("avatar")]
|
||||||
|
[Consumes("multipart/form-data")]
|
||||||
|
public async Task<ActionResult<string>> UploadAvatar(
|
||||||
|
[FromForm] IFormFile file,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (file == null || file.Length == 0)
|
||||||
|
return BadRequest(new { error = "فایل انتخاب نشده است" });
|
||||||
|
|
||||||
|
var allowedTypes = new[] { "image/jpeg", "image/jpg", "image/png", "image/webp" };
|
||||||
|
if (!allowedTypes.Contains(file.ContentType.ToLower()))
|
||||||
|
return BadRequest(new { error = "فقط فایلهای تصویری مجاز هستند" });
|
||||||
|
|
||||||
|
if (file.Length > 2 * 1024 * 1024)
|
||||||
|
return BadRequest(new { error = "حجم آواتار نباید بیشتر از 2 مگابایت باشد" });
|
||||||
|
|
||||||
|
var uploadsFolder = Path.Combine(_environment.WebRootPath ?? "wwwroot", "uploads", "avatars");
|
||||||
|
Directory.CreateDirectory(uploadsFolder);
|
||||||
|
|
||||||
|
var fileName = $"{Guid.NewGuid()}{Path.GetExtension(file.FileName)}";
|
||||||
|
var filePath = Path.Combine(uploadsFolder, fileName);
|
||||||
|
|
||||||
|
await using (var stream = new FileStream(filePath, FileMode.Create))
|
||||||
|
{
|
||||||
|
await file.CopyToAsync(stream, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
var relativePath = $"/uploads/avatars/{fileName}";
|
||||||
|
return Ok(new { avatarPath = relativePath, message = "آواتار با موفقیت آپلود شد" });
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error uploading avatar");
|
||||||
|
return StatusCode(500, new { error = "خطا در آپلود آواتار" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
292
src/GreenHome.Api/Controllers/DevicePostsController.cs
Normal file
@@ -0,0 +1,292 @@
|
|||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using GreenHome.Application;
|
||||||
|
|
||||||
|
namespace GreenHome.Api.Controllers;
|
||||||
|
|
||||||
|
[ApiController]
|
||||||
|
[Route("api/[controller]")]
|
||||||
|
public class DevicePostsController : ControllerBase
|
||||||
|
{
|
||||||
|
private readonly IDevicePostService _postService;
|
||||||
|
private readonly ILogger<DevicePostsController> _logger;
|
||||||
|
private readonly IWebHostEnvironment _environment;
|
||||||
|
|
||||||
|
public DevicePostsController(
|
||||||
|
IDevicePostService postService,
|
||||||
|
ILogger<DevicePostsController> logger,
|
||||||
|
IWebHostEnvironment environment)
|
||||||
|
{
|
||||||
|
_postService = postService;
|
||||||
|
_logger = logger;
|
||||||
|
_environment = environment;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// دریافت پستهای گروه مجازی دستگاه (تایملاین)
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet]
|
||||||
|
public async Task<ActionResult<PagedResult<DevicePostDto>>> GetPosts(
|
||||||
|
[FromQuery] int deviceId,
|
||||||
|
[FromQuery] int? authorUserId,
|
||||||
|
[FromQuery] int page = 1,
|
||||||
|
[FromQuery] int pageSize = 20,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
var filter = new DevicePostFilter
|
||||||
|
{
|
||||||
|
DeviceId = deviceId,
|
||||||
|
AuthorUserId = authorUserId,
|
||||||
|
Page = page,
|
||||||
|
PageSize = pageSize
|
||||||
|
};
|
||||||
|
|
||||||
|
var result = await _postService.GetPostsAsync(filter, cancellationToken);
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// دریافت جزئیات یک پست
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet("{id}")]
|
||||||
|
public async Task<ActionResult<DevicePostDto>> GetPostById(int id, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var result = await _postService.GetPostByIdAsync(id, cancellationToken);
|
||||||
|
if (result == null)
|
||||||
|
{
|
||||||
|
return NotFound(new { error = $"پست با شناسه {id} یافت نشد" });
|
||||||
|
}
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ایجاد پست جدید در گروه مجازی
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost]
|
||||||
|
public async Task<ActionResult<int>> CreatePost(
|
||||||
|
CreateDevicePostRequest request,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var id = await _postService.CreatePostAsync(request, cancellationToken);
|
||||||
|
return Ok(new { id, message = "پست با موفقیت ایجاد شد" });
|
||||||
|
}
|
||||||
|
catch (UnauthorizedAccessException ex)
|
||||||
|
{
|
||||||
|
return Unauthorized(new { error = ex.Message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ویرایش پست
|
||||||
|
/// </summary>
|
||||||
|
[HttpPut]
|
||||||
|
public async Task<ActionResult> UpdatePost(
|
||||||
|
UpdateDevicePostRequest request,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await _postService.UpdatePostAsync(request, cancellationToken);
|
||||||
|
return Ok(new { message = "پست با موفقیت ویرایش شد" });
|
||||||
|
}
|
||||||
|
catch (InvalidOperationException ex)
|
||||||
|
{
|
||||||
|
return NotFound(new { error = ex.Message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// حذف پست
|
||||||
|
/// </summary>
|
||||||
|
[HttpDelete("{id}")]
|
||||||
|
public async Task<ActionResult> DeletePost(int id, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await _postService.DeletePostAsync(id, cancellationToken);
|
||||||
|
return Ok(new { message = "پست با موفقیت حذف شد" });
|
||||||
|
}
|
||||||
|
catch (InvalidOperationException ex)
|
||||||
|
{
|
||||||
|
return NotFound(new { error = ex.Message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// آپلود تصویر برای پست
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("{postId}/images")]
|
||||||
|
[Consumes("multipart/form-data")]
|
||||||
|
public async Task<ActionResult<int>> UploadImage(
|
||||||
|
int postId,
|
||||||
|
[FromForm] IFormFile file,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (file == null || file.Length == 0)
|
||||||
|
{
|
||||||
|
return BadRequest(new { error = "فایل انتخاب نشده است" });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate file type
|
||||||
|
var allowedTypes = new[] { "image/jpeg", "image/jpg", "image/png", "image/gif", "image/webp" };
|
||||||
|
if (!allowedTypes.Contains(file.ContentType.ToLower()))
|
||||||
|
{
|
||||||
|
return BadRequest(new { error = "فقط فایلهای تصویری مجاز هستند" });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate file size (max 5MB)
|
||||||
|
if (file.Length > 5 * 1024 * 1024)
|
||||||
|
{
|
||||||
|
return BadRequest(new { error = "حجم فایل نباید بیشتر از 5 مگابایت باشد" });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create upload directory
|
||||||
|
var uploadsFolder = Path.Combine(_environment.WebRootPath ?? "wwwroot", "uploads", "posts");
|
||||||
|
Directory.CreateDirectory(uploadsFolder);
|
||||||
|
|
||||||
|
// Generate unique filename
|
||||||
|
var fileName = $"{Guid.NewGuid()}_{Path.GetFileName(file.FileName)}";
|
||||||
|
var filePath = Path.Combine(uploadsFolder, fileName);
|
||||||
|
|
||||||
|
// Save file
|
||||||
|
using (var stream = new FileStream(filePath, FileMode.Create))
|
||||||
|
{
|
||||||
|
await file.CopyToAsync(stream, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save to database
|
||||||
|
var relativePath = $"/uploads/posts/{fileName}";
|
||||||
|
var imageId = await _postService.AddImageToPostAsync(
|
||||||
|
postId,
|
||||||
|
file.FileName,
|
||||||
|
relativePath,
|
||||||
|
file.ContentType,
|
||||||
|
file.Length,
|
||||||
|
cancellationToken);
|
||||||
|
|
||||||
|
_logger.LogInformation("Image uploaded for post {PostId}: {ImageId}", postId, imageId);
|
||||||
|
|
||||||
|
return Ok(new { imageId, filePath = relativePath, message = "تصویر با موفقیت آپلود شد" });
|
||||||
|
}
|
||||||
|
catch (InvalidOperationException ex)
|
||||||
|
{
|
||||||
|
return NotFound(new { error = ex.Message });
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error uploading image for post {PostId}", postId);
|
||||||
|
return StatusCode(500, new { error = "خطا در آپلود تصویر" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// حذف تصویر از پست
|
||||||
|
/// </summary>
|
||||||
|
[HttpDelete("images/{imageId}")]
|
||||||
|
public async Task<ActionResult> DeleteImage(int imageId, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await _postService.DeleteImageAsync(imageId, cancellationToken);
|
||||||
|
return Ok(new { message = "تصویر با موفقیت حذف شد" });
|
||||||
|
}
|
||||||
|
catch (InvalidOperationException ex)
|
||||||
|
{
|
||||||
|
return NotFound(new { error = ex.Message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// بررسی دسترسی کاربر به دستگاه
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet("access/{userId}/{deviceId}")]
|
||||||
|
public async Task<ActionResult<bool>> CheckAccess(int userId, int deviceId, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var hasAccess = await _postService.CanUserAccessDeviceAsync(userId, deviceId, cancellationToken);
|
||||||
|
return Ok(new { hasAccess });
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ایجاد پست اسنپشات وضعیت سنسورها و رلهها
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("sensor-snapshot")]
|
||||||
|
public async Task<ActionResult<int>> CreateSensorSnapshot(
|
||||||
|
CreateSensorSnapshotRequest request,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var id = await _postService.CreateSensorSnapshotAsync(request, cancellationToken);
|
||||||
|
return Ok(new { id, message = "وضعیت سنسورها و رلهها ارسال شد" });
|
||||||
|
}
|
||||||
|
catch (UnauthorizedAccessException ex)
|
||||||
|
{
|
||||||
|
return Unauthorized(new { error = ex.Message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// آپلود فایل صوتی (ویس) برای پست
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("{postId}/voice")]
|
||||||
|
[Consumes("multipart/form-data")]
|
||||||
|
public async Task<ActionResult> UploadVoice(
|
||||||
|
int postId,
|
||||||
|
[FromForm] IFormFile file,
|
||||||
|
[FromForm] int? durationSeconds,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (file == null || file.Length == 0)
|
||||||
|
return BadRequest(new { error = "فایل انتخاب نشده است" });
|
||||||
|
|
||||||
|
var allowedTypes = new[]
|
||||||
|
{
|
||||||
|
"audio/webm", "audio/ogg", "audio/mp4", "audio/mpeg",
|
||||||
|
"audio/wav", "audio/x-wav", "audio/amr", "audio/aac", "audio/m4a"
|
||||||
|
};
|
||||||
|
if (!allowedTypes.Contains(file.ContentType.ToLower()))
|
||||||
|
return BadRequest(new { error = "فرمت فایل صوتی مجاز نیست" });
|
||||||
|
|
||||||
|
if (file.Length > 10 * 1024 * 1024)
|
||||||
|
return BadRequest(new { error = "حجم فایل صوتی نباید بیشتر از 10 مگابایت باشد" });
|
||||||
|
|
||||||
|
var uploadsFolder = Path.Combine(_environment.WebRootPath ?? "wwwroot", "uploads", "voice");
|
||||||
|
Directory.CreateDirectory(uploadsFolder);
|
||||||
|
|
||||||
|
var fileName = $"{Guid.NewGuid()}{Path.GetExtension(file.FileName)}";
|
||||||
|
var filePath = Path.Combine(uploadsFolder, fileName);
|
||||||
|
|
||||||
|
await using (var stream = new FileStream(filePath, FileMode.Create))
|
||||||
|
{
|
||||||
|
await file.CopyToAsync(stream, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
var relativePath = $"/uploads/voice/{fileName}";
|
||||||
|
await _postService.SetPostVoiceAsync(
|
||||||
|
postId,
|
||||||
|
file.FileName,
|
||||||
|
relativePath,
|
||||||
|
file.ContentType,
|
||||||
|
file.Length,
|
||||||
|
durationSeconds,
|
||||||
|
cancellationToken);
|
||||||
|
|
||||||
|
return Ok(new { filePath = relativePath, message = "ویس با موفقیت آپلود شد" });
|
||||||
|
}
|
||||||
|
catch (InvalidOperationException ex)
|
||||||
|
{
|
||||||
|
return NotFound(new { error = ex.Message });
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error uploading voice for post {PostId}", postId);
|
||||||
|
return StatusCode(500, new { error = "خطا در آپلود ویس" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
128
src/GreenHome.Api/Controllers/DeviceTokenController.cs
Normal file
@@ -0,0 +1,128 @@
|
|||||||
|
using GreenHome.Application;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
|
namespace GreenHome.Api.Controllers;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// کنترلر مدیریت توکن و تنظیمات دستگاه
|
||||||
|
/// </summary>
|
||||||
|
[ApiController]
|
||||||
|
[Route("api/[controller]")]
|
||||||
|
public class DeviceTokenController : ControllerBase
|
||||||
|
{
|
||||||
|
private readonly IDeviceTokenService deviceTokenService;
|
||||||
|
private readonly ILogger<DeviceTokenController> logger;
|
||||||
|
|
||||||
|
public DeviceTokenController(
|
||||||
|
IDeviceTokenService deviceTokenService,
|
||||||
|
ILogger<DeviceTokenController> logger)
|
||||||
|
{
|
||||||
|
this.deviceTokenService = deviceTokenService;
|
||||||
|
this.logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// دریافت فاصله زمانی آپلود دستگاه
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="deviceId">شناسه دستگاه (اختیاری)</param>
|
||||||
|
/// <param name="devicePhoneNumber">شماره تلفن دستگاه (اختیاری)</param>
|
||||||
|
/// <returns>فاصله زمانی آپلود به دقیقه</returns>
|
||||||
|
[HttpGet("upload-interval")]
|
||||||
|
public async Task<ActionResult<GetUploadIntervalResponse>> GetUploadInterval(
|
||||||
|
[FromQuery] int? deviceId,
|
||||||
|
[FromQuery] string? devicePhoneNumber,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
if (!deviceId.HasValue && string.IsNullOrWhiteSpace(devicePhoneNumber))
|
||||||
|
{
|
||||||
|
return BadRequest(new GetUploadIntervalResponse
|
||||||
|
{
|
||||||
|
Success = false,
|
||||||
|
Message = "حداقل یکی از پارامترهای deviceId یا devicePhoneNumber باید ارسال شود"
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
var request = new GetUploadIntervalRequest
|
||||||
|
{
|
||||||
|
DeviceId = deviceId,
|
||||||
|
DevicePhoneNumber = devicePhoneNumber
|
||||||
|
};
|
||||||
|
|
||||||
|
var result = await deviceTokenService.GetUploadIntervalAsync(request, cancellationToken);
|
||||||
|
|
||||||
|
if (!result.Success)
|
||||||
|
{
|
||||||
|
return NotFound(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// درخواست توکن دستگاه (تولید و ارسال کد از طریق پیامک)
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">درخواست شامل شماره تلفن دستگاه</param>
|
||||||
|
/// <returns>نتیجه درخواست</returns>
|
||||||
|
[HttpPost("request-token")]
|
||||||
|
public async Task<ActionResult<RequestDeviceTokenResponse>> RequestToken(
|
||||||
|
[FromBody] RequestDeviceTokenRequest request,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(request.DevicePhoneNumber))
|
||||||
|
{
|
||||||
|
return BadRequest(new RequestDeviceTokenResponse
|
||||||
|
{
|
||||||
|
Success = false,
|
||||||
|
Message = "شماره تلفن دستگاه الزامی است"
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
var result = await deviceTokenService.RequestDeviceTokenAsync(request, cancellationToken);
|
||||||
|
|
||||||
|
if (!result.Success)
|
||||||
|
{
|
||||||
|
return BadRequest(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// تایید توکن دستگاه (ارسال تنظیمات کدشده از طریق پیامک)
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">درخواست شامل شماره تلفن و کد تایید</param>
|
||||||
|
/// <returns>نتیجه تایید و تنظیمات کدشده</returns>
|
||||||
|
[HttpPost("verify-token")]
|
||||||
|
public async Task<ActionResult<VerifyDeviceTokenResponse>> VerifyToken(
|
||||||
|
[FromBody] VerifyDeviceTokenRequest request,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(request.DevicePhoneNumber))
|
||||||
|
{
|
||||||
|
return BadRequest(new VerifyDeviceTokenResponse
|
||||||
|
{
|
||||||
|
Success = false,
|
||||||
|
Message = "شماره تلفن دستگاه الزامی است"
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(request.VerificationCode))
|
||||||
|
{
|
||||||
|
return BadRequest(new VerifyDeviceTokenResponse
|
||||||
|
{
|
||||||
|
Success = false,
|
||||||
|
Message = "کد تایید الزامی است"
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
var result = await deviceTokenService.VerifyDeviceTokenAsync(request, cancellationToken);
|
||||||
|
|
||||||
|
if (!result.Success)
|
||||||
|
{
|
||||||
|
return BadRequest(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
62
src/GreenHome.Api/Controllers/MonthlyReportController.cs
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using GreenHome.Application;
|
||||||
|
|
||||||
|
namespace GreenHome.Api.Controllers;
|
||||||
|
|
||||||
|
[ApiController]
|
||||||
|
[Route("api/[controller]")]
|
||||||
|
public class MonthlyReportController : ControllerBase
|
||||||
|
{
|
||||||
|
private readonly IMonthlyReportService _monthlyReportService;
|
||||||
|
private readonly ILogger<MonthlyReportController> _logger;
|
||||||
|
|
||||||
|
public MonthlyReportController(
|
||||||
|
IMonthlyReportService monthlyReportService,
|
||||||
|
ILogger<MonthlyReportController> logger)
|
||||||
|
{
|
||||||
|
_monthlyReportService = monthlyReportService;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// دریافت گزارش آماری ماهانه
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet]
|
||||||
|
public async Task<ActionResult<MonthlyReportDto>> GetMonthlyReport(
|
||||||
|
[FromQuery] int deviceId,
|
||||||
|
[FromQuery] int year,
|
||||||
|
[FromQuery] int month,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (deviceId <= 0)
|
||||||
|
{
|
||||||
|
return BadRequest(new { error = "شناسه دستگاه نامعتبر است" });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (month < 1 || month > 12)
|
||||||
|
{
|
||||||
|
return BadRequest(new { error = "ماه باید بین 1 تا 12 باشد" });
|
||||||
|
}
|
||||||
|
|
||||||
|
var result = await _monthlyReportService.GetMonthlyReportAsync(deviceId, year, month, cancellationToken);
|
||||||
|
|
||||||
|
_logger.LogInformation(
|
||||||
|
"گزارش ماهانه برای دستگاه {DeviceId} و ماه {Month}/{Year} ایجاد شد",
|
||||||
|
deviceId, month, year);
|
||||||
|
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
catch (InvalidOperationException ex)
|
||||||
|
{
|
||||||
|
return NotFound(new { error = ex.Message });
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error generating monthly report");
|
||||||
|
return StatusCode(500, new { error = "خطا در ایجاد گزارش ماهانه" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
254
src/GreenHome.Api/Controllers/PowerOutageController.cs
Normal file
@@ -0,0 +1,254 @@
|
|||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using GreenHome.Application;
|
||||||
|
|
||||||
|
namespace GreenHome.Api.Controllers;
|
||||||
|
|
||||||
|
[ApiController]
|
||||||
|
[Route("api/[controller]")]
|
||||||
|
public class PowerOutageController : ControllerBase
|
||||||
|
{
|
||||||
|
private readonly IAlertService _alertService;
|
||||||
|
private readonly IPowerOutageLogService _powerOutageLogService;
|
||||||
|
private readonly ILogger<PowerOutageController> _logger;
|
||||||
|
|
||||||
|
public PowerOutageController(
|
||||||
|
IAlertService alertService,
|
||||||
|
IPowerOutageLogService powerOutageLogService,
|
||||||
|
ILogger<PowerOutageController> logger)
|
||||||
|
{
|
||||||
|
_alertService = alertService;
|
||||||
|
_powerOutageLogService = powerOutageLogService;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ارسال هشدار قطع برق برای یک دستگاه
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="deviceId">شناسه دستگاه</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token</param>
|
||||||
|
/// <returns>نتیجه عملیات</returns>
|
||||||
|
[HttpPost]
|
||||||
|
public async Task<ActionResult> SendPowerOutageAlert(
|
||||||
|
[FromQuery] int deviceId,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (deviceId <= 0)
|
||||||
|
{
|
||||||
|
return BadRequest(new { error = "شناسه دستگاه نامعتبر است" });
|
||||||
|
}
|
||||||
|
|
||||||
|
await _alertService.SendPowerOutageAlertAsync(deviceId, cancellationToken);
|
||||||
|
|
||||||
|
_logger.LogInformation("Power outage alert processed for device {DeviceId}", deviceId);
|
||||||
|
|
||||||
|
return Ok(new {
|
||||||
|
success = true,
|
||||||
|
message = "هشدار قطع برق با موفقیت ارسال شد"
|
||||||
|
});
|
||||||
|
}
|
||||||
|
catch (InvalidOperationException ex)
|
||||||
|
{
|
||||||
|
_logger.LogWarning(ex, "Invalid operation for power outage alert: DeviceId={DeviceId}", deviceId);
|
||||||
|
return BadRequest(new { error = ex.Message });
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error sending power outage alert: DeviceId={DeviceId}", deviceId);
|
||||||
|
return StatusCode(500, new { error = "خطا در ارسال هشدار قطع برق" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// دریافت لیست رویدادهای قطع و وصل برق یک دستگاه
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="deviceId">شناسه دستگاه</param>
|
||||||
|
/// <param name="startUtc">شروع بازه (UTC)</param>
|
||||||
|
/// <param name="endUtc">پایان بازه (UTC)</param>
|
||||||
|
/// <param name="eventType">نوع رویداد: 1 = وصل, 2 = قطع (اختیاری)</param>
|
||||||
|
/// <param name="page">شماره صفحه</param>
|
||||||
|
/// <param name="pageSize">تعداد در هر صفحه</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token</param>
|
||||||
|
/// <returns>لیست رویدادها</returns>
|
||||||
|
[HttpGet("logs")]
|
||||||
|
public async Task<ActionResult<PagedResult<PowerOutageLogDto>>> GetLogs(
|
||||||
|
[FromQuery] int deviceId,
|
||||||
|
[FromQuery] DateTime? startUtc,
|
||||||
|
[FromQuery] DateTime? endUtc,
|
||||||
|
[FromQuery] int? eventType,
|
||||||
|
[FromQuery] int page = 1,
|
||||||
|
[FromQuery] int pageSize = 20,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (deviceId <= 0)
|
||||||
|
{
|
||||||
|
return BadRequest(new { error = "شناسه دستگاه نامعتبر است" });
|
||||||
|
}
|
||||||
|
|
||||||
|
var filter = new PowerOutageFilter
|
||||||
|
{
|
||||||
|
EventType = eventType,
|
||||||
|
StartDateUtc = startUtc,
|
||||||
|
EndDateUtc = endUtc,
|
||||||
|
Page = page,
|
||||||
|
PageSize = pageSize
|
||||||
|
};
|
||||||
|
|
||||||
|
var result = await _powerOutageLogService.ListAsync(deviceId, filter, cancellationToken);
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error getting power outage logs: DeviceId={DeviceId}", deviceId);
|
||||||
|
return StatusCode(500, new { error = "خطا در دریافت لیست رویدادهای برق" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// دریافت خلاصه قطعیهای برق یک دستگاه در یک بازه زمانی
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="deviceId">شناسه دستگاه</param>
|
||||||
|
/// <param name="startUtc">شروع بازه (UTC)</param>
|
||||||
|
/// <param name="endUtc">پایان بازه (UTC)</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token</param>
|
||||||
|
/// <returns>خلاصه قطعیها شامل تعداد قطعیها و مجموع مدت زمان قطعی</returns>
|
||||||
|
[HttpGet("summary")]
|
||||||
|
public async Task<ActionResult<PowerOutageSummaryDto>> GetSummary(
|
||||||
|
[FromQuery] int deviceId,
|
||||||
|
[FromQuery] DateTime? startUtc,
|
||||||
|
[FromQuery] DateTime? endUtc,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (deviceId <= 0)
|
||||||
|
{
|
||||||
|
return BadRequest(new { error = "شناسه دستگاه نامعتبر است" });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get all outage events within the date range
|
||||||
|
var filter = new PowerOutageFilter
|
||||||
|
{
|
||||||
|
StartDateUtc = startUtc,
|
||||||
|
EndDateUtc = endUtc,
|
||||||
|
PageSize = int.MaxValue
|
||||||
|
};
|
||||||
|
|
||||||
|
var result = await _powerOutageLogService.ListAsync(deviceId, filter, cancellationToken);
|
||||||
|
|
||||||
|
var outages = result.Items.Where(x => x.CurrentPower == 0).ToList();
|
||||||
|
var connections = result.Items.Where(x => x.CurrentPower == 1).ToList();
|
||||||
|
|
||||||
|
// For outages that don't have a matching connect within the range,
|
||||||
|
// look beyond the end date to find when power was restored
|
||||||
|
var unmatchedOutages = outages
|
||||||
|
.Where(o => !connections.Any(c => c.TimestampUtc > o.TimestampUtc))
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
if (unmatchedOutages.Count > 0 && endUtc.HasValue)
|
||||||
|
{
|
||||||
|
// Fetch any connect events after the range end for unmatched outages
|
||||||
|
var extendedFilter = new PowerOutageFilter
|
||||||
|
{
|
||||||
|
StartDateUtc = endUtc.Value,
|
||||||
|
PageSize = int.MaxValue
|
||||||
|
};
|
||||||
|
|
||||||
|
var extendedResult = await _powerOutageLogService.ListAsync(deviceId, extendedFilter, cancellationToken);
|
||||||
|
var futureConnections = extendedResult.Items.Where(x => x.CurrentPower == 1).ToList();
|
||||||
|
connections.AddRange(futureConnections);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate total downtime by pairing disconnects with subsequent connects
|
||||||
|
long totalDowntimeSeconds = 0;
|
||||||
|
var pairedOutages = new List<PowerOutagePairDto>();
|
||||||
|
|
||||||
|
foreach (var outage in outages)
|
||||||
|
{
|
||||||
|
// Find the next connect event after this outage
|
||||||
|
var nextConnect = connections
|
||||||
|
.Where(c => c.TimestampUtc > outage.TimestampUtc)
|
||||||
|
.OrderBy(c => c.TimestampUtc)
|
||||||
|
.FirstOrDefault();
|
||||||
|
|
||||||
|
if (nextConnect != null)
|
||||||
|
{
|
||||||
|
var duration = (nextConnect.TimestampUtc - outage.TimestampUtc).TotalSeconds;
|
||||||
|
totalDowntimeSeconds += (long)duration;
|
||||||
|
|
||||||
|
pairedOutages.Add(new PowerOutagePairDto
|
||||||
|
{
|
||||||
|
DisconnectedAt = outage.TimestampUtc,
|
||||||
|
ConnectedAt = nextConnect.TimestampUtc,
|
||||||
|
DurationSeconds = (long)duration
|
||||||
|
});
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// Still disconnected (no subsequent connect found anywhere)
|
||||||
|
pairedOutages.Add(new PowerOutagePairDto
|
||||||
|
{
|
||||||
|
DisconnectedAt = outage.TimestampUtc,
|
||||||
|
ConnectedAt = null,
|
||||||
|
DurationSeconds = null
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var summary = new PowerOutageSummaryDto
|
||||||
|
{
|
||||||
|
DeviceId = deviceId,
|
||||||
|
TotalOutageCount = outages.Count,
|
||||||
|
TotalDowntimeSeconds = totalDowntimeSeconds,
|
||||||
|
StartDateUtc = startUtc,
|
||||||
|
EndDateUtc = endUtc,
|
||||||
|
Outages = pairedOutages
|
||||||
|
};
|
||||||
|
|
||||||
|
return Ok(summary);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error getting power outage summary: DeviceId={DeviceId}", deviceId);
|
||||||
|
return StatusCode(500, new { error = "خطا در دریافت خلاصه قطعیهای برق" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// مهاجرت دادههای قدیمی از جدول Telemetry به PowerOutageLogs
|
||||||
|
/// این اندپوینت یکبار مصرف است - بعد از اجرا میتوانید آن را غیرفعال کنید
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="deviceId">اختیاری - اگر داده شود فقط برای همان دستگاه مهاجرت میکند</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token</param>
|
||||||
|
/// <returns>تعداد رکوردهای مهاجرت داده شده</returns>
|
||||||
|
[HttpPost("migrate")]
|
||||||
|
public async Task<ActionResult> MigrateFromTelemetry(
|
||||||
|
[FromQuery] int? deviceId,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_logger.LogInformation("Starting migration from Telemetry to PowerOutageLogs...");
|
||||||
|
|
||||||
|
var count = await _powerOutageLogService.MigrateFromTelemetryAsync(deviceId, cancellationToken);
|
||||||
|
|
||||||
|
_logger.LogInformation("Migration completed: {Count} records inserted", count);
|
||||||
|
|
||||||
|
return Ok(new
|
||||||
|
{
|
||||||
|
success = true,
|
||||||
|
message = $"مهاجرت با موفقیت انجام شد. {count} رکورد به جدول PowerOutageLogs اضافه شد.",
|
||||||
|
recordsInserted = count
|
||||||
|
});
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error during migration from Telemetry to PowerOutageLogs");
|
||||||
|
return StatusCode(500, new { error = $"خطا در مهاجرت دادهها: {ex.Message}" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -1,5 +1,8 @@
|
|||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using GreenHome.Application;
|
using GreenHome.Application;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
|
||||||
namespace GreenHome.Api.Controllers;
|
namespace GreenHome.Api.Controllers;
|
||||||
|
|
||||||
@@ -9,57 +12,158 @@ public class TelemetryController : ControllerBase
|
|||||||
{
|
{
|
||||||
private readonly ITelemetryService telemetryService;
|
private readonly ITelemetryService telemetryService;
|
||||||
private readonly IAlertService alertService;
|
private readonly IAlertService alertService;
|
||||||
|
private readonly IAlertConditionService alertConditionService;
|
||||||
|
|
||||||
public TelemetryController(ITelemetryService telemetryService, IAlertService alertService)
|
public TelemetryController(ITelemetryService telemetryService, IAlertService alertService, IAlertConditionService alertConditionService)
|
||||||
{
|
{
|
||||||
this.telemetryService = telemetryService;
|
this.telemetryService = telemetryService;
|
||||||
this.alertService = alertService;
|
this.alertService = alertService;
|
||||||
|
this.alertConditionService = alertConditionService;
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpGet]
|
[HttpGet]
|
||||||
public async Task<ActionResult<PagedResult<TelemetryDto>>> List([FromQuery] int? deviceId, [FromQuery] DateTime? startUtc, [FromQuery] DateTime? endUtc, [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken cancellationToken = default)
|
public async Task<ActionResult<PagedResult<TelemetryDto>>> List([FromQuery] int? deviceId, [FromQuery] DateTime? startUtc, [FromQuery] DateTime? endUtc, [FromQuery] DateTime? sinceUtc, [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
var filter = new TelemetryFilter { DeviceId = deviceId, StartDateUtc = startUtc, EndDateUtc = endUtc, Page = page, PageSize = pageSize };
|
var filter = new TelemetryFilter { DeviceId = deviceId, StartDateUtc = startUtc, EndDateUtc = endUtc, SinceUtc = sinceUtc, Page = page, PageSize = pageSize };
|
||||||
var result = await telemetryService.ListAsync(filter, cancellationToken);
|
var result = await telemetryService.ListAsync(filter, cancellationToken);
|
||||||
return Ok(result);
|
return Ok(result);
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpGet("AddData")]
|
[HttpGet("AddData")]
|
||||||
public async Task<ActionResult<int>> Create(string deviceName, decimal temperatureC, decimal humidityPercent,
|
public async Task<ActionResult<string>> Create([FromQuery] TelemetryDto telementry, [FromQuery] string? lastUpdateDate, CancellationToken cancellationToken)
|
||||||
decimal soilPercent, int gasPPM, decimal lux, CancellationToken cancellationToken)
|
|
||||||
{
|
{
|
||||||
TelemetryDto dto = new TelemetryDto
|
telementry.TimestampUtc = DateTime.UtcNow;
|
||||||
{
|
telementry.RelayStates = ParseRelayStates(Request.Query);
|
||||||
DeviceName = deviceName,
|
var id = await telemetryService.AddAsync(telementry, cancellationToken);
|
||||||
TemperatureC = temperatureC,
|
|
||||||
HumidityPercent = humidityPercent,
|
var parts = new List<string> { $"ID:{id}" };
|
||||||
SoilPercent = soilPercent,
|
var deviceId = telementry.DeviceId;
|
||||||
GasPPM = gasPPM,
|
|
||||||
Lux = lux,
|
|
||||||
TimestampUtc = DateTime.UtcNow
|
|
||||||
};
|
|
||||||
var id = await telemetryService.AddAsync(dto, cancellationToken);
|
|
||||||
|
|
||||||
// Check and send alerts if needed (fire and forget)
|
|
||||||
_ = Task.Run(async () =>
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
// Get deviceId from the saved telemetry record
|
|
||||||
var deviceId = dto.DeviceId;
|
|
||||||
if (deviceId > 0)
|
if (deviceId > 0)
|
||||||
{
|
{
|
||||||
await alertService.CheckAndSendAlertsAsync(deviceId, dto, cancellationToken);
|
// 1. Check alerts and power status
|
||||||
}
|
var alertResult = await alertService.CheckAndSendAlertsAsync(deviceId, telementry, cancellationToken);
|
||||||
}
|
if (alertResult != null)
|
||||||
catch
|
|
||||||
{
|
{
|
||||||
// Log error but don't fail the request
|
if (alertResult.Messages.Count > 0)
|
||||||
// Errors are logged in AlertService
|
{
|
||||||
|
parts.Add($"A:{alertResult.Messages.Count}");
|
||||||
|
parts.Add($"R:{alertResult.Recipients}");
|
||||||
|
parts.Add($"M:{string.Join("@", alertResult.Messages)}");
|
||||||
}
|
}
|
||||||
}, cancellationToken);
|
|
||||||
|
|
||||||
return Ok(id);
|
if (alertResult.PowerStatus != null)
|
||||||
|
{
|
||||||
|
parts.Add($"P:{alertResult.PowerStatus}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Check relay conditions update
|
||||||
|
if (!string.IsNullOrEmpty(lastUpdateDate))
|
||||||
|
{
|
||||||
|
var parsedDate = ParseLastUpdateDate(lastUpdateDate);
|
||||||
|
var relayConditions = await alertConditionService.GetUpdatedRelayConditionsAsync(deviceId, parsedDate, cancellationToken);
|
||||||
|
if (relayConditions.Count > 0)
|
||||||
|
{
|
||||||
|
parts.Add("RU:1");
|
||||||
|
parts.Add($"RL:{relayConditions.Count}");
|
||||||
|
parts.Add($"RC:{EncodeRelayConditions(relayConditions)}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return Ok(string.Join("|", parts));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Encode relay conditions into a compact string format for STM32 parsing.
|
||||||
|
/// Format (relays separated by |):
|
||||||
|
/// E{enabled}R{relayIndex}{groups}
|
||||||
|
/// Group (OR between groups):
|
||||||
|
/// G{action} where action = 0 (turn on) | 1 (turn off)
|
||||||
|
/// followed by its conditions joined by & (AND inside a group):
|
||||||
|
/// Sensor condition: S{sensor}O{op}V{value1}[,{value2}]
|
||||||
|
/// Time condition: T{start}-{end} (minutes from midnight)
|
||||||
|
/// Time ranges with start > end cross midnight (e.g. T1200-360 = 20:00..06:00);
|
||||||
|
/// the device must treat that as (now >= start || now < end).
|
||||||
|
/// </summary>
|
||||||
|
private static string EncodeRelayConditions(IReadOnlyList<RelayConditionDto> conditions)
|
||||||
|
{
|
||||||
|
return string.Join("|", conditions.Select(c =>
|
||||||
|
{
|
||||||
|
var groups = new List<string>();
|
||||||
|
groups.AddRange(c.On.Select(g => EncodeGroup(g, 0)));
|
||||||
|
groups.AddRange(c.Off.Select(g => EncodeGroup(g, 1)));
|
||||||
|
return $"E{c.Enabled}R{c.RelayIndex}{string.Concat(groups)}";
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string EncodeGroup(RelayGroupDto group, int action)
|
||||||
|
{
|
||||||
|
return $"G{action}{string.Join("&", group.Conditions.Select(EncodeCondition))}";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string EncodeCondition(RelayRuleDto condition)
|
||||||
|
{
|
||||||
|
if (condition.Kind == 1)
|
||||||
|
{
|
||||||
|
return $"T{condition.Start ?? 0}-{condition.End ?? 0}";
|
||||||
|
}
|
||||||
|
|
||||||
|
var encoded = $"S{condition.Sensor}O{condition.Op}V{condition.V1}";
|
||||||
|
if (condition.V2.HasValue)
|
||||||
|
encoded += $",{condition.V2.Value}";
|
||||||
|
|
||||||
|
return encoded;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Collect relay states from query params r1, r2, ... (missing relay = off/0).
|
||||||
|
/// </summary>
|
||||||
|
private static string? ParseRelayStates(IQueryCollection query)
|
||||||
|
{
|
||||||
|
var entries = new List<(int Index, string Value)>();
|
||||||
|
foreach (var key in query.Keys)
|
||||||
|
{
|
||||||
|
var match = Regex.Match(key, @"^r(\d+)$", RegexOptions.IgnoreCase);
|
||||||
|
if (!match.Success || !int.TryParse(match.Groups[1].Value, out var index) || index <= 0)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
entries.Add((index, query[key].ToString() == "1" ? "1" : "0"));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (entries.Count == 0)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
var states = new string[entries.Max(e => e.Index)];
|
||||||
|
Array.Fill(states, "0");
|
||||||
|
foreach (var entry in entries)
|
||||||
|
states[entry.Index - 1] = entry.Value;
|
||||||
|
|
||||||
|
return string.Join(",", states);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Parse date string in format: yyyy/MM/dd-HH:mm
|
||||||
|
/// </summary>
|
||||||
|
private static DateTime? ParseLastUpdateDate(string dateStr)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(dateStr))
|
||||||
|
return null;
|
||||||
|
|
||||||
|
// Try parsing as yyyy/MM/dd-HH:mm
|
||||||
|
if (DateTime.TryParseExact(dateStr, "yyyy/MM/dd-HH:mm", null, System.Globalization.DateTimeStyles.None, out var result))
|
||||||
|
{
|
||||||
|
return DateTime.SpecifyKind(result, DateTimeKind.Utc);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Try parsing as yyyy-MM-dd HH:mm (ISO-like)
|
||||||
|
if (DateTime.TryParseExact(dateStr, "yyyy-MM-dd HH:mm", null, System.Globalization.DateTimeStyles.None, out var result2))
|
||||||
|
{
|
||||||
|
return DateTime.SpecifyKind(result2, DateTimeKind.Utc);
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpGet("minmax")]
|
[HttpGet("minmax")]
|
||||||
@@ -82,4 +186,11 @@ public class TelemetryController : ControllerBase
|
|||||||
var result = await telemetryService.GetActiveMonthsAsync(deviceId, year, cancellationToken);
|
var result = await telemetryService.GetActiveMonthsAsync(deviceId, year, cancellationToken);
|
||||||
return Ok(result);
|
return Ok(result);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[HttpGet("aggregate")]
|
||||||
|
public async Task<ActionResult<IReadOnlyList<TelemetryBucketDto>>> Aggregate([FromQuery] int deviceId, [FromQuery] DateTime? startUtc, [FromQuery] DateTime? endUtc, [FromQuery] int bucketMinutes = 15, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
var result = await telemetryService.GetAggregatedAsync(deviceId, startUtc, endUtc, bucketMinutes, cancellationToken);
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
210
src/GreenHome.Api/Controllers/UserDailyReportsController.cs
Normal file
@@ -0,0 +1,210 @@
|
|||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using GreenHome.Application;
|
||||||
|
|
||||||
|
namespace GreenHome.Api.Controllers;
|
||||||
|
|
||||||
|
[ApiController]
|
||||||
|
[Route("api/[controller]")]
|
||||||
|
public class UserDailyReportsController : ControllerBase
|
||||||
|
{
|
||||||
|
private readonly IUserDailyReportService _reportService;
|
||||||
|
private readonly ILogger<UserDailyReportsController> _logger;
|
||||||
|
private readonly IWebHostEnvironment _environment;
|
||||||
|
|
||||||
|
public UserDailyReportsController(
|
||||||
|
IUserDailyReportService reportService,
|
||||||
|
ILogger<UserDailyReportsController> logger,
|
||||||
|
IWebHostEnvironment environment)
|
||||||
|
{
|
||||||
|
_reportService = reportService;
|
||||||
|
_logger = logger;
|
||||||
|
_environment = environment;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// دریافت لیست گزارشهای روزانه کاربران با فیلتر
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet]
|
||||||
|
public async Task<ActionResult<PagedResult<UserDailyReportDto>>> GetReports(
|
||||||
|
[FromQuery] int? deviceId,
|
||||||
|
[FromQuery] int? userId,
|
||||||
|
[FromQuery] string? persianDate,
|
||||||
|
[FromQuery] int? year,
|
||||||
|
[FromQuery] int? month,
|
||||||
|
[FromQuery] int page = 1,
|
||||||
|
[FromQuery] int pageSize = 20,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
var filter = new UserDailyReportFilter
|
||||||
|
{
|
||||||
|
DeviceId = deviceId,
|
||||||
|
UserId = userId,
|
||||||
|
PersianDate = persianDate,
|
||||||
|
Year = year,
|
||||||
|
Month = month,
|
||||||
|
Page = page,
|
||||||
|
PageSize = pageSize
|
||||||
|
};
|
||||||
|
|
||||||
|
var result = await _reportService.GetReportsAsync(filter, cancellationToken);
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// دریافت جزئیات یک گزارش روزانه
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet("{id}")]
|
||||||
|
public async Task<ActionResult<UserDailyReportDto>> GetReportById(int id, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var result = await _reportService.GetReportByIdAsync(id, cancellationToken);
|
||||||
|
if (result == null)
|
||||||
|
{
|
||||||
|
return NotFound(new { error = $"گزارش با شناسه {id} یافت نشد" });
|
||||||
|
}
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ایجاد گزارش روزانه جدید
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost]
|
||||||
|
public async Task<ActionResult<int>> CreateReport(
|
||||||
|
CreateUserDailyReportRequest request,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var id = await _reportService.CreateReportAsync(request, cancellationToken);
|
||||||
|
return Ok(new { id, message = "گزارش با موفقیت ایجاد شد" });
|
||||||
|
}
|
||||||
|
catch (ArgumentException ex)
|
||||||
|
{
|
||||||
|
return BadRequest(new { error = ex.Message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ویرایش گزارش روزانه
|
||||||
|
/// </summary>
|
||||||
|
[HttpPut]
|
||||||
|
public async Task<ActionResult> UpdateReport(
|
||||||
|
UpdateUserDailyReportRequest request,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await _reportService.UpdateReportAsync(request, cancellationToken);
|
||||||
|
return Ok(new { message = "گزارش با موفقیت ویرایش شد" });
|
||||||
|
}
|
||||||
|
catch (InvalidOperationException ex)
|
||||||
|
{
|
||||||
|
return NotFound(new { error = ex.Message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// حذف گزارش روزانه
|
||||||
|
/// </summary>
|
||||||
|
[HttpDelete("{id}")]
|
||||||
|
public async Task<ActionResult> DeleteReport(int id, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await _reportService.DeleteReportAsync(id, cancellationToken);
|
||||||
|
return Ok(new { message = "گزارش با موفقیت حذف شد" });
|
||||||
|
}
|
||||||
|
catch (InvalidOperationException ex)
|
||||||
|
{
|
||||||
|
return NotFound(new { error = ex.Message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// آپلود تصویر برای گزارش روزانه
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("{reportId}/images")]
|
||||||
|
[Consumes("multipart/form-data")]
|
||||||
|
public async Task<ActionResult<int>> UploadImage(
|
||||||
|
int reportId,
|
||||||
|
[FromForm] IFormFile file,
|
||||||
|
[FromForm] string? description,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (file == null || file.Length == 0)
|
||||||
|
{
|
||||||
|
return BadRequest(new { error = "فایل انتخاب نشده است" });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate file type
|
||||||
|
var allowedTypes = new[] { "image/jpeg", "image/jpg", "image/png", "image/gif", "image/webp" };
|
||||||
|
if (!allowedTypes.Contains(file.ContentType.ToLower()))
|
||||||
|
{
|
||||||
|
return BadRequest(new { error = "فقط فایلهای تصویری مجاز هستند" });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate file size (max 5MB)
|
||||||
|
if (file.Length > 5 * 1024 * 1024)
|
||||||
|
{
|
||||||
|
return BadRequest(new { error = "حجم فایل نباید بیشتر از 5 مگابایت باشد" });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create upload directory
|
||||||
|
var uploadsFolder = Path.Combine(_environment.WebRootPath ?? "wwwroot", "uploads", "reports");
|
||||||
|
Directory.CreateDirectory(uploadsFolder);
|
||||||
|
|
||||||
|
// Generate unique filename
|
||||||
|
var fileName = $"{Guid.NewGuid()}_{Path.GetFileName(file.FileName)}";
|
||||||
|
var filePath = Path.Combine(uploadsFolder, fileName);
|
||||||
|
|
||||||
|
// Save file
|
||||||
|
using (var stream = new FileStream(filePath, FileMode.Create))
|
||||||
|
{
|
||||||
|
await file.CopyToAsync(stream, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save to database
|
||||||
|
var relativePath = $"/uploads/reports/{fileName}";
|
||||||
|
var imageId = await _reportService.AddImageToReportAsync(
|
||||||
|
reportId,
|
||||||
|
file.FileName,
|
||||||
|
relativePath,
|
||||||
|
file.ContentType,
|
||||||
|
file.Length,
|
||||||
|
description,
|
||||||
|
cancellationToken);
|
||||||
|
|
||||||
|
_logger.LogInformation("Image uploaded for report {ReportId}: {ImageId}", reportId, imageId);
|
||||||
|
|
||||||
|
return Ok(new { imageId, filePath = relativePath, message = "تصویر با موفقیت آپلود شد" });
|
||||||
|
}
|
||||||
|
catch (InvalidOperationException ex)
|
||||||
|
{
|
||||||
|
return NotFound(new { error = ex.Message });
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error uploading image for report {ReportId}", reportId);
|
||||||
|
return StatusCode(500, new { error = "خطا در آپلود تصویر" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// حذف تصویر از گزارش
|
||||||
|
/// </summary>
|
||||||
|
[HttpDelete("images/{imageId}")]
|
||||||
|
public async Task<ActionResult> DeleteImage(int imageId, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await _reportService.DeleteImageAsync(imageId, cancellationToken);
|
||||||
|
return Ok(new { message = "تصویر با موفقیت حذف شد" });
|
||||||
|
}
|
||||||
|
catch (InvalidOperationException ex)
|
||||||
|
{
|
||||||
|
return NotFound(new { error = ex.Message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -270,3 +270,4 @@ public class VoiceCallTestController : ControllerBase
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
154
src/GreenHome.Api/Controllers/WeatherController.cs
Normal file
@@ -0,0 +1,154 @@
|
|||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.Extensions.Caching.Memory;
|
||||||
|
using System.Net.Http.Headers;
|
||||||
|
|
||||||
|
namespace GreenHome.Api.Controllers;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Proxy for external weather services (Open-Meteo / Nominatim) with tiered caching:
|
||||||
|
/// - current conditions : 30 minutes
|
||||||
|
/// - forecast : 6 hours
|
||||||
|
/// - historical archive : 30 days (historical data never changes)
|
||||||
|
/// - reverse geocoding : 30 days (location name rarely changes)
|
||||||
|
/// </summary>
|
||||||
|
[ApiController]
|
||||||
|
[Route("api/[controller]")]
|
||||||
|
public class WeatherController : ControllerBase
|
||||||
|
{
|
||||||
|
private const double DefaultLatitude = 34.39674800; // Kahak Qom
|
||||||
|
private const double DefaultLongitude = 50.86594800; // Kahak Qom
|
||||||
|
|
||||||
|
private static readonly TimeSpan CurrentTtl = TimeSpan.FromMinutes(30);
|
||||||
|
private static readonly TimeSpan ForecastTtl = TimeSpan.FromHours(6);
|
||||||
|
private static readonly TimeSpan HistoricalTtl = TimeSpan.FromDays(30);
|
||||||
|
private static readonly TimeSpan LocationTtl = TimeSpan.FromDays(30);
|
||||||
|
|
||||||
|
private readonly IHttpClientFactory _httpClientFactory;
|
||||||
|
private readonly IMemoryCache _cache;
|
||||||
|
private readonly ILogger<WeatherController> _logger;
|
||||||
|
|
||||||
|
public WeatherController(
|
||||||
|
IHttpClientFactory httpClientFactory,
|
||||||
|
IMemoryCache cache,
|
||||||
|
ILogger<WeatherController> logger)
|
||||||
|
{
|
||||||
|
_httpClientFactory = httpClientFactory;
|
||||||
|
_cache = cache;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Current conditions only (temperature, humidity, wind, weather code). Cached 30 minutes.</summary>
|
||||||
|
[HttpGet("current")]
|
||||||
|
public Task<IActionResult> Current(
|
||||||
|
[FromQuery] double latitude = DefaultLatitude,
|
||||||
|
[FromQuery] double longitude = DefaultLongitude,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
const string query = "current=temperature_2m,relative_humidity_2m,weather_code,wind_speed_10m&timezone=Asia/Tehran";
|
||||||
|
return GetOrAddAsync(
|
||||||
|
$"weather:current:{latitude}:{longitude}",
|
||||||
|
"https://api.open-meteo.com/v1/forecast",
|
||||||
|
$"latitude={latitude}&longitude={longitude}&{query}",
|
||||||
|
CurrentTtl,
|
||||||
|
cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Hourly + daily forecast (no current, which is fetched separately). Cached 6 hours.</summary>
|
||||||
|
[HttpGet("forecast")]
|
||||||
|
public Task<IActionResult> Forecast(
|
||||||
|
[FromQuery] double latitude = DefaultLatitude,
|
||||||
|
[FromQuery] double longitude = DefaultLongitude,
|
||||||
|
[FromQuery] int forecastDays = 7,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
const string query = "hourly=temperature_2m,relative_humidity_2m,weather_code,precipitation"
|
||||||
|
+ "&daily=weather_code,temperature_2m_max,temperature_2m_min,precipitation_sum,precipitation_probability_max,uv_index_max,sunshine_duration,wind_speed_10m_max"
|
||||||
|
+ "&timezone=Asia/Tehran";
|
||||||
|
|
||||||
|
return GetOrAddAsync(
|
||||||
|
$"weather:forecast:{latitude}:{longitude}:{forecastDays}",
|
||||||
|
"https://api.open-meteo.com/v1/forecast",
|
||||||
|
$"latitude={latitude}&longitude={longitude}&{query}&forecast_days={forecastDays}",
|
||||||
|
ForecastTtl,
|
||||||
|
cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Historical archive data for a past date range. Cached 30 days.</summary>
|
||||||
|
[HttpGet("historical")]
|
||||||
|
public Task<IActionResult> Historical(
|
||||||
|
[FromQuery] double latitude = DefaultLatitude,
|
||||||
|
[FromQuery] double longitude = DefaultLongitude,
|
||||||
|
[FromQuery] string? start_date = null,
|
||||||
|
[FromQuery] string? end_date = null,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
const string query = "daily=weather_code,temperature_2m_max,temperature_2m_min,precipitation_sum,wind_speed_10m_max,sunshine_duration&timezone=Asia/Tehran";
|
||||||
|
|
||||||
|
var cacheKey = $"weather:historical:{latitude}:{longitude}:{start_date}:{end_date}";
|
||||||
|
var urlQuery = $"latitude={latitude}&longitude={longitude}&start_date={start_date}&end_date={end_date}&{query}";
|
||||||
|
|
||||||
|
return GetOrAddAsync(
|
||||||
|
cacheKey,
|
||||||
|
"https://archive-api.open-meteo.com/v1/archive",
|
||||||
|
urlQuery,
|
||||||
|
HistoricalTtl,
|
||||||
|
cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Reverse geocoding (coordinates -> location name). Cached 30 days.</summary>
|
||||||
|
[HttpGet("location")]
|
||||||
|
public Task<IActionResult> Location(
|
||||||
|
[FromQuery] double latitude = DefaultLatitude,
|
||||||
|
[FromQuery] double longitude = DefaultLongitude,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
var cacheKey = $"weather:location:{latitude}:{longitude}";
|
||||||
|
var url = $"https://nominatim.openstreetmap.org/reverse?format=json&lat={latitude}&lon={longitude}&zoom=10&addressdetails=1&accept-language=fa,en";
|
||||||
|
|
||||||
|
return GetOrAddAsync(
|
||||||
|
cacheKey,
|
||||||
|
url,
|
||||||
|
null,
|
||||||
|
LocationTtl,
|
||||||
|
cancellationToken,
|
||||||
|
userAgent: "GreenHome/1.0 (greenhouse weather proxy)");
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<IActionResult> GetOrAddAsync(
|
||||||
|
string cacheKey,
|
||||||
|
string baseUrl,
|
||||||
|
string? queryString,
|
||||||
|
TimeSpan ttl,
|
||||||
|
CancellationToken cancellationToken,
|
||||||
|
string? userAgent = null)
|
||||||
|
{
|
||||||
|
if (_cache.TryGetValue(cacheKey, out string? cachedJson))
|
||||||
|
{
|
||||||
|
return Content(cachedJson!, "application/json");
|
||||||
|
}
|
||||||
|
|
||||||
|
var url = string.IsNullOrEmpty(queryString) ? baseUrl : $"{baseUrl}?{queryString}";
|
||||||
|
|
||||||
|
var client = _httpClientFactory.CreateClient();
|
||||||
|
if (!string.IsNullOrEmpty(userAgent))
|
||||||
|
{
|
||||||
|
client.DefaultRequestHeaders.UserAgent.ParseAdd(userAgent);
|
||||||
|
}
|
||||||
|
|
||||||
|
var response = await client.GetAsync(url, cancellationToken);
|
||||||
|
|
||||||
|
if (!response.IsSuccessStatusCode)
|
||||||
|
{
|
||||||
|
_logger.LogWarning(
|
||||||
|
"Upstream weather service returned {StatusCode} for {Url}",
|
||||||
|
(int)response.StatusCode,
|
||||||
|
url);
|
||||||
|
return StatusCode((int)response.StatusCode, "Upstream weather service error");
|
||||||
|
}
|
||||||
|
|
||||||
|
var json = await response.Content.ReadAsStringAsync(cancellationToken);
|
||||||
|
_cache.Set(cacheKey, json, ttl);
|
||||||
|
|
||||||
|
return Content(json, "application/json");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,11 +2,15 @@
|
|||||||
FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build
|
FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build
|
||||||
WORKDIR /src
|
WORKDIR /src
|
||||||
COPY . .
|
COPY . .
|
||||||
RUN dotnet restore
|
# Publish ONLY the API project: the build context contains the whole
|
||||||
RUN dotnet publish -c Release -o /app
|
# solution, and publishing the sln would dump every project's
|
||||||
|
# appsettings.json into /app (last one wins) — e.g. DataCopy's
|
||||||
|
# overwrote the API's and broke IppanelSms startup.
|
||||||
|
RUN dotnet restore GreenHome.Api/GreenHome.Api.csproj
|
||||||
|
RUN dotnet publish GreenHome.Api/GreenHome.Api.csproj -c Release -o /app
|
||||||
|
|
||||||
# مرحله runtime
|
# مرحله runtime
|
||||||
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS runtime
|
FROM mcr.microsoft.com/dotnet/aspnet:9.0 AS runtime
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY --from=build /app .
|
COPY --from=build /app .
|
||||||
EXPOSE 8080
|
EXPOSE 8080
|
||||||
|
|||||||
60
src/GreenHome.Api/Filters/AdminAuthFilter.cs
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
using GreenHome.Application;
|
||||||
|
using GreenHome.Domain;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.AspNetCore.Mvc.Filters;
|
||||||
|
|
||||||
|
namespace GreenHome.Api.Filters;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Guards all api/admin/* endpoints:
|
||||||
|
/// - missing/invalid/expired token -> 401
|
||||||
|
/// - valid token but Role != Admin -> 403
|
||||||
|
/// Role is always read from the server-side user lookup (IAuthService.GetUserByTokenAsync
|
||||||
|
/// does a DB lookup), never from client-provided claims.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class AdminAuthFilter : IAsyncActionFilter
|
||||||
|
{
|
||||||
|
private readonly IAuthService _authService;
|
||||||
|
|
||||||
|
public AdminAuthFilter(IAuthService authService)
|
||||||
|
{
|
||||||
|
_authService = authService;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
|
||||||
|
{
|
||||||
|
var header = context.HttpContext.Request.Headers.Authorization.ToString();
|
||||||
|
var token = header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)
|
||||||
|
? header["Bearer ".Length..].Trim()
|
||||||
|
: null;
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(token))
|
||||||
|
{
|
||||||
|
context.Result = new UnauthorizedObjectResult(new { message = "Token ارسال نشده است" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var user = await _authService.GetUserByTokenAsync(token, context.HttpContext.RequestAborted);
|
||||||
|
|
||||||
|
if (user == null)
|
||||||
|
{
|
||||||
|
// invalid/expired token OR disabled user
|
||||||
|
context.Result = new UnauthorizedObjectResult(new { message = "Token نامعتبر است" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (user.Role != UserRole.Admin)
|
||||||
|
{
|
||||||
|
context.Result = new ObjectResult(new { message = "دسترسی شما به این بخش مجاز نیست" })
|
||||||
|
{
|
||||||
|
StatusCode = StatusCodes.Status403Forbidden
|
||||||
|
};
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// expose the authenticated admin to the controller without a second DB round-trip
|
||||||
|
context.HttpContext.Items["AdminUser"] = user;
|
||||||
|
|
||||||
|
await next();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,19 +1,24 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>net9.0</TargetFramework>
|
<TargetFramework>net9.0</TargetFramework>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<NuGetAudit>false</NuGetAudit>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="5.1.0" />
|
||||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.0" />
|
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.0" />
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.9">
|
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.9">
|
||||||
<PrivateAssets>all</PrivateAssets>
|
<PrivateAssets>all</PrivateAssets>
|
||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
</PackageReference>
|
</PackageReference>
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="9.0.9" />
|
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="9.0.9" />
|
||||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
|
<PackageReference Include="Scalar.AspNetCore" Version="2.11.6" />
|
||||||
|
<Content Include="My_StaticFiles\**">
|
||||||
|
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||||
|
</Content>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
@@ -21,6 +26,7 @@
|
|||||||
<ProjectReference Include="..\GreenHome.Infrastructure\GreenHome.Infrastructure.csproj" />
|
<ProjectReference Include="..\GreenHome.Infrastructure\GreenHome.Infrastructure.csproj" />
|
||||||
<ProjectReference Include="..\GreenHome.Sms.Ippanel\GreenHome.Sms.Ippanel.csproj" />
|
<ProjectReference Include="..\GreenHome.Sms.Ippanel\GreenHome.Sms.Ippanel.csproj" />
|
||||||
<ProjectReference Include="..\GreenHome.VoiceCall.Avanak\GreenHome.VoiceCall.Avanak.csproj" />
|
<ProjectReference Include="..\GreenHome.VoiceCall.Avanak\GreenHome.VoiceCall.Avanak.csproj" />
|
||||||
|
<ProjectReference Include="..\GreenHome.AI.DeepSeek\GreenHome.AI.DeepSeek.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
1
src/GreenHome.Api/My_StaticFiles/calltest.html
Normal file
@@ -0,0 +1 @@
|
|||||||
|
TY09192530212#https://ghback.nabaksoft.ir/My_StaticFiles/output.amr
|
||||||
BIN
src/GreenHome.Api/My_StaticFiles/output.amr
Normal file
1
src/GreenHome.Api/My_StaticFiles/smsTest.html
Normal file
@@ -0,0 +1 @@
|
|||||||
|
TT09192530212#سلام خوبی
|
||||||
@@ -1,69 +1,141 @@
|
|||||||
using FluentValidation;
|
using FluentValidation;
|
||||||
|
using GreenHome.AI.DeepSeek;
|
||||||
|
using Microsoft.AspNetCore.Mvc.Versioning;
|
||||||
using GreenHome.Application;
|
using GreenHome.Application;
|
||||||
using GreenHome.Infrastructure;
|
using GreenHome.Infrastructure;
|
||||||
|
using GreenHome.Infrastructure.Data;
|
||||||
using GreenHome.Sms.Ippanel;
|
using GreenHome.Sms.Ippanel;
|
||||||
using GreenHome.VoiceCall.Avanak;
|
using GreenHome.VoiceCall.Avanak;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.AspNetCore.StaticFiles;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.FileProviders;
|
||||||
|
using Scalar.AspNetCore;
|
||||||
|
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
|
||||||
// Add services to the container.
|
// ============================================================
|
||||||
builder.Services.AddControllers();
|
// 1. Service Registration
|
||||||
builder.Services.AddEndpointsApiExplorer();
|
// ============================================================
|
||||||
builder.Services.AddSwaggerGen();
|
|
||||||
|
|
||||||
// Application/Infrastructure DI
|
ConfigureCoreServices(builder);
|
||||||
builder.Services.AddAutoMapper(typeof(GreenHome.Application.MappingProfile));
|
ConfigureCors(builder);
|
||||||
builder.Services.AddValidatorsFromAssemblyContaining<GreenHome.Application.DeviceDtoValidator>();
|
ConfigureExternalServices(builder);
|
||||||
|
|
||||||
// CORS for Next.js dev (adjust origins as needed)
|
var app = builder.Build();
|
||||||
const string CorsPolicy = "DefaultCors";
|
|
||||||
builder.Services.AddCors(options =>
|
// ============================================================
|
||||||
|
// 2. Pipeline Configuration
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
ApplyMigrations(app);
|
||||||
|
ConfigureMiddleware(app);
|
||||||
|
ConfigureStaticFiles(app);
|
||||||
|
app.MapControllers();
|
||||||
|
|
||||||
|
// SPA fallback: serve index.html for non-API routes (client-side routing)
|
||||||
|
app.MapFallbackToFile("index.html");
|
||||||
|
|
||||||
|
app.Run();
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// Service Registration Methods
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
void ConfigureCoreServices(WebApplicationBuilder builder)
|
||||||
{
|
{
|
||||||
|
// API versioning: existing controllers stay unversioned (default v1.0, same URLs).
|
||||||
|
// New v2 controllers use [ApiVersion("2.0")] + [Route("api/v2/[controller]")] (or [Route("api/v2")] prefix).
|
||||||
|
builder.Services
|
||||||
|
.AddApiVersioning(options =>
|
||||||
|
{
|
||||||
|
options.DefaultApiVersion = new ApiVersion(1, 0);
|
||||||
|
options.AssumeDefaultVersionWhenUnspecified = true;
|
||||||
|
options.ReportApiVersions = true;
|
||||||
|
options.ApiVersionReader = new UrlSegmentApiVersionReader();
|
||||||
|
})
|
||||||
|
.AddMvc();
|
||||||
|
builder.Services.AddEndpointsApiExplorer();
|
||||||
|
builder.Services.AddOpenApi();
|
||||||
|
|
||||||
|
// Caching & HTTP client factory (used by WeatherController proxy with tiered caching)
|
||||||
|
builder.Services.AddMemoryCache();
|
||||||
|
builder.Services.AddHttpClient();
|
||||||
|
|
||||||
|
builder.Services.AddAutoMapper(typeof(GreenHome.Application.MappingProfile));
|
||||||
|
builder.Services.AddValidatorsFromAssemblyContaining<GreenHome.Application.DeviceDtoValidator>();
|
||||||
|
|
||||||
|
// Admin panel auth filter (used via [ServiceFilter] on AdminController)
|
||||||
|
builder.Services.AddScoped<GreenHome.Api.Filters.AdminAuthFilter>();
|
||||||
|
|
||||||
|
builder.Services.AddInfrastructure(builder.Configuration);
|
||||||
|
}
|
||||||
|
|
||||||
|
void ConfigureCors(WebApplicationBuilder builder)
|
||||||
|
{
|
||||||
|
const string CorsPolicy = "DefaultCors";
|
||||||
|
|
||||||
|
builder.Services.AddCors(options =>
|
||||||
|
{
|
||||||
options.AddPolicy(CorsPolicy, policy =>
|
options.AddPolicy(CorsPolicy, policy =>
|
||||||
|
{
|
||||||
|
if (builder.Environment.IsDevelopment())
|
||||||
|
{
|
||||||
|
policy
|
||||||
|
.AllowAnyOrigin()
|
||||||
|
.AllowAnyHeader()
|
||||||
|
.AllowAnyMethod();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
policy
|
policy
|
||||||
.WithOrigins(
|
.WithOrigins(
|
||||||
"http://green.nabaksoft.ir",
|
"http://green.nabaksoft.ir",
|
||||||
"https://green.nabaksoft.ir",
|
"https://green.nabaksoft.ir",
|
||||||
"http://gh1.nabaksoft.ir",
|
"http://gh1.nabaksoft.ir",
|
||||||
"https://gh1.nabaksoft.ir",
|
"https://gh1.nabaksoft.ir"
|
||||||
"http://localhost:3000",
|
|
||||||
"http://localhost:3000",
|
|
||||||
"http://127.0.0.1:3000",
|
|
||||||
"https://localhost:3000"
|
|
||||||
)
|
)
|
||||||
.AllowAnyHeader()
|
.AllowAnyHeader()
|
||||||
.AllowAnyMethod()
|
.AllowAnyMethod()
|
||||||
.AllowCredentials()
|
.AllowCredentials();
|
||||||
);
|
}
|
||||||
});
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
builder.Services.AddDbContext<GreenHome.Infrastructure.GreenHomeDbContext>(options =>
|
void ConfigureExternalServices(WebApplicationBuilder builder)
|
||||||
{
|
{
|
||||||
options.UseSqlServer(builder.Configuration.GetConnectionString("Default"));
|
builder.Services.AddIppanelSms(builder.Configuration);
|
||||||
});
|
builder.Services.AddAvanakVoiceCall(builder.Configuration);
|
||||||
builder.Services.AddScoped<GreenHome.Application.IDeviceService, GreenHome.Infrastructure.DeviceService>();
|
builder.Services.AddDeepSeek(builder.Configuration);
|
||||||
builder.Services.AddScoped<GreenHome.Application.ITelemetryService, GreenHome.Infrastructure.TelemetryService>();
|
}
|
||||||
builder.Services.AddScoped<GreenHome.Application.IDeviceSettingsService, GreenHome.Infrastructure.DeviceSettingsService>();
|
|
||||||
builder.Services.AddScoped<GreenHome.Application.IAuthService, GreenHome.Infrastructure.AuthService>();
|
|
||||||
builder.Services.AddScoped<GreenHome.Application.IAlertService, GreenHome.Infrastructure.AlertService>();
|
|
||||||
|
|
||||||
// SMS Service Configuration
|
// ============================================================
|
||||||
builder.Services.AddIppanelSms(builder.Configuration);
|
// Middleware & Pipeline Methods
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
// Voice Call Service Configuration
|
void ApplyMigrations(WebApplication app)
|
||||||
builder.Services.AddAvanakVoiceCall(builder.Configuration);
|
|
||||||
|
|
||||||
var app = builder.Build();
|
|
||||||
|
|
||||||
// Apply pending migrations automatically
|
|
||||||
using (var scope = app.Services.CreateScope())
|
|
||||||
{
|
{
|
||||||
|
using var scope = app.Services.CreateScope();
|
||||||
var services = scope.ServiceProvider;
|
var services = scope.ServiceProvider;
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var context = services.GetRequiredService<GreenHome.Infrastructure.GreenHomeDbContext>();
|
var context = services.GetRequiredService<GreenHomeDbContext>();
|
||||||
|
var provider = app.Configuration["Database:Provider"] ?? "SqlServer";
|
||||||
|
|
||||||
|
if (provider == "Postgres")
|
||||||
|
{
|
||||||
|
// Soft-migration path: Postgres starts empty. EnsureCreated() is
|
||||||
|
// idempotent — it builds the full schema from the model only when no
|
||||||
|
// tables exist yet, and is a no-op once schema + data are in place.
|
||||||
|
context.Database.EnsureCreated();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
context.Database.Migrate();
|
context.Database.Migrate();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
var logger = services.GetRequiredService<ILogger<Program>>();
|
var logger = services.GetRequiredService<ILogger<Program>>();
|
||||||
@@ -71,19 +143,45 @@ using (var scope = app.Services.CreateScope())
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Configure the HTTP request pipeline.
|
void ConfigureMiddleware(WebApplication app)
|
||||||
//if (app.Environment.IsDevelopment())
|
|
||||||
{
|
{
|
||||||
app.UseSwagger();
|
app.MapOpenApi();
|
||||||
app.UseSwaggerUI();
|
app.MapScalarApiReference();
|
||||||
|
|
||||||
|
if (!app.Environment.IsDevelopment())
|
||||||
|
{
|
||||||
|
app.UseHttpsRedirection();
|
||||||
|
}
|
||||||
|
|
||||||
|
app.UseCors("DefaultCors");
|
||||||
|
app.UseAuthorization();
|
||||||
}
|
}
|
||||||
|
|
||||||
app.UseHttpsRedirection();
|
void ConfigureStaticFiles(WebApplication app)
|
||||||
|
{
|
||||||
|
var provider = new FileExtensionContentTypeProvider();
|
||||||
|
provider.Mappings[".amr"] = "audio/amr";
|
||||||
|
provider.Mappings[".apk"] = "application/vnd.android.package-archive";
|
||||||
|
|
||||||
app.UseCors(CorsPolicy);
|
// Serve existing My_StaticFiles folder
|
||||||
|
app.UseStaticFiles(new StaticFileOptions
|
||||||
|
{
|
||||||
|
FileProvider = new PhysicalFileProvider(
|
||||||
|
Path.Combine(app.Environment.ContentRootPath, "My_StaticFiles")),
|
||||||
|
RequestPath = "/My_StaticFiles",
|
||||||
|
ContentTypeProvider = provider
|
||||||
|
});
|
||||||
|
|
||||||
app.UseAuthorization();
|
// Serve new files folder for APK and other downloads
|
||||||
|
app.UseStaticFiles(new StaticFileOptions
|
||||||
|
{
|
||||||
|
FileProvider = new PhysicalFileProvider(
|
||||||
|
Path.Combine(app.Environment.ContentRootPath, "files")),
|
||||||
|
RequestPath = "/files",
|
||||||
|
ContentTypeProvider = provider
|
||||||
|
});
|
||||||
|
|
||||||
app.MapControllers();
|
// Serve the SPA from wwwroot (Vite build output)
|
||||||
|
app.UseDefaultFiles();
|
||||||
app.Run();
|
app.UseStaticFiles();
|
||||||
|
}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||||
},
|
},
|
||||||
"dotnetRunMessages": true,
|
"dotnetRunMessages": true,
|
||||||
"applicationUrl": "http://localhost:5064"
|
"applicationUrl": "http://127.0.0.1:5064"
|
||||||
},
|
},
|
||||||
"https": {
|
"https": {
|
||||||
"commandName": "Project",
|
"commandName": "Project",
|
||||||
@@ -14,7 +14,7 @@
|
|||||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||||
},
|
},
|
||||||
"dotnetRunMessages": true,
|
"dotnetRunMessages": true,
|
||||||
"applicationUrl": "https://localhost:7274;http://localhost:5064"
|
"applicationUrl": "https://127.0.0.1:7274;http://127.0.0.1:5064"
|
||||||
},
|
},
|
||||||
"IIS Express": {
|
"IIS Express": {
|
||||||
"commandName": "IISExpress",
|
"commandName": "IISExpress",
|
||||||
|
|||||||
@@ -4,5 +4,20 @@
|
|||||||
"Default": "Information",
|
"Default": "Information",
|
||||||
"Microsoft.AspNetCore": "Warning"
|
"Microsoft.AspNetCore": "Warning"
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"Database": {
|
||||||
|
"Provider": "Postgres"
|
||||||
|
},
|
||||||
|
"ConnectionStrings": {
|
||||||
|
"Default": "Server=.;Integrated Security=False;Trusted_Connection=True;Encrypt=false;MultipleActiveResultSets=true;Database=GreenHomeDb;",
|
||||||
|
"Postgres": "Host=localhost;Port=5432;Database=greenhome;Username=greenhome;Password=greenhome"
|
||||||
|
},
|
||||||
|
"AvanakVoiceCall": {
|
||||||
|
"Token": "A948B776B90CFD919B0EC60929714136CCB49DDB"
|
||||||
|
},
|
||||||
|
"IppanelSms": {
|
||||||
|
"BaseUrl": "https://edge.ippanel.com/v1",
|
||||||
|
"AuthorizationToken": "YTA1Zjk3N2EtNzkwOC00ZTg5LWFjZmYtZGEyZDAyNjNlZWQxM2Q2ZDVjYWE0MTA2Yzc1NDYzZDY1Y2VkMjlhMzcwNjA=",
|
||||||
|
"DefaultSender": "+983000505"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -11,5 +11,20 @@
|
|||||||
"AuthorizationToken": "YTA1Zjk3N2EtNzkwOC00ZTg5LWFjZmYtZGEyZDAyNjNlZWQxM2Q2ZDVjYWE0MTA2Yzc1NDYzZDY1Y2VkMjlhMzcwNjA=",
|
"AuthorizationToken": "YTA1Zjk3N2EtNzkwOC00ZTg5LWFjZmYtZGEyZDAyNjNlZWQxM2Q2ZDVjYWE0MTA2Yzc1NDYzZDY1Y2VkMjlhMzcwNjA=",
|
||||||
"DefaultSender": "+983000505"
|
"DefaultSender": "+983000505"
|
||||||
},
|
},
|
||||||
|
"DeepSeek": {
|
||||||
|
"BaseUrl": "https://api.deepseek.com",
|
||||||
|
"ApiKey": "sk-4470fc1a003a445e92f357dbe123e5a4",
|
||||||
|
"DefaultModel": "deepseek-chat",
|
||||||
|
"DefaultTemperature": 1.0
|
||||||
|
},
|
||||||
|
|
||||||
|
"Auth": {
|
||||||
|
"TokenSecret": "CHANGE_ME_USE_A_STRONG_RANDOM_SECRET_AT_LEAST_32_CHARS"
|
||||||
|
},
|
||||||
|
|
||||||
|
"Admin": {
|
||||||
|
"OnlineWindowMinutes": 15
|
||||||
|
},
|
||||||
|
|
||||||
"AllowedHosts": "*"
|
"AllowedHosts": "*"
|
||||||
}
|
}
|
||||||
19
src/GreenHome.Api/wwwroot/assets/AnalysisTab-C68ADY84.js
Normal file
1
src/GreenHome.Api/wwwroot/assets/WeatherTab-CRtiHhGA.js
Normal file
@@ -0,0 +1 @@
|
|||||||
|
import{j as s,T as g,P as N,S as b,W as v,r,i as m,f as T,a as W,b as E,Q as S,c as w,L as C,E as L,B as M,R as H,M as P,d as k}from"./index-BNRf8j5s.js";function O({weatherData:e,selectedDate:a}){return s.jsx("div",{className:"space-y-6",children:s.jsxs("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden",children:[s.jsx("div",{className:"bg-blue-600 p-5",children:s.jsxs("div",{className:"text-center text-white",children:[s.jsx("p",{className:"text-sm opacity-90 mb-1",children:"📅 وضعیت آب و هوای روز"}),s.jsx("p",{className:"text-xl font-bold",children:a})]})}),s.jsxs("div",{className:"p-4 grid grid-cols-2 gap-3",children:[s.jsx(g,{weatherData:e,isToday:!1}),s.jsx(N,{weatherData:e}),s.jsx(b,{weatherData:e}),s.jsx(v,{weatherData:e})]})]})})}function R({selectedDate:e}){const[a,t]=r.useState(null),[h,o]=r.useState(!1),[c,n]=r.useState(null),[f,d]=r.useState(null),[j,i]=r.useState("در حال دریافت..."),x=r.useCallback(async()=>{if(!a){o(!0),n(null);try{const l=m(e),[p,y]=await Promise.all([l?T():W(e),E(S,w)]);t(p),i(y)}catch(l){console.error("Error loading weather:",l),n("خطا در دریافت اطلاعات آب و هوا. لطفاً دوباره تلاش کنید."),i("کهک قم، ایران")}finally{o(!1)}}},[e,a]);if(r.useEffect(()=>{t(null),n(null),d(null),i("در حال دریافت...")},[e]),h)return s.jsx(C,{message:"در حال دریافت اطلاعات آب و هوا...",fullScreen:!1});if(c)return s.jsx(L,{message:c,action:s.jsx(M,{onClick:()=>{t(null),x()},variant:"primary",icon:H,children:"تلاش مجدد"})});if(!a)return x(),null;const u=m(e);return s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2 text-gray-600",children:[s.jsx(P,{className:"w-5 h-5 text-sky-500"}),s.jsx("span",{className:"font-medium",children:j})]}),s.jsx("span",{className:"text-xs text-gray-400",children:u?"پیشبینی هواشناسی برای مدیریت گلخانه":"وضعیت آب و هوای روز انتخاب شده"})]}),u?s.jsx(k,{weatherData:a,expandedDayIndex:f,onDayToggle:d}):s.jsx(O,{weatherData:a,selectedDate:e})]})}export{R as WeatherTab};
|
||||||
417
src/GreenHome.Api/wwwroot/assets/index-BNRf8j5s.js
Normal file
1
src/GreenHome.Api/wwwroot/assets/index-DiVRKiu2.css
Normal file
1
src/GreenHome.Api/wwwroot/file.svg
Normal file
@@ -0,0 +1 @@
|
|||||||
|
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>
|
||||||
|
After Width: | Height: | Size: 391 B |
BIN
src/GreenHome.Api/wwwroot/fonts/vazirmatn/Vazirmatn-Black.woff2
Normal file
BIN
src/GreenHome.Api/wwwroot/fonts/vazirmatn/Vazirmatn-Bold.woff2
Normal file
BIN
src/GreenHome.Api/wwwroot/fonts/vazirmatn/Vazirmatn-Light.woff2
Normal file
BIN
src/GreenHome.Api/wwwroot/fonts/vazirmatn/Vazirmatn-Medium.woff2
Normal file
BIN
src/GreenHome.Api/wwwroot/fonts/vazirmatn/Vazirmatn-Thin.woff2
Normal file
BIN
src/GreenHome.Api/wwwroot/fonts/vazirmatn/Vazirmatn[wght].woff2
Normal file
72
src/GreenHome.Api/wwwroot/fonts/vazirmatn/style.css
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
/* Generated by script */
|
||||||
|
@font-face {
|
||||||
|
font-family: Vazirmatn;
|
||||||
|
src: url('Vazirmatn-Thin.woff2') format('woff2');
|
||||||
|
font-weight: 100;
|
||||||
|
font-style: normal;
|
||||||
|
font-display: swap;
|
||||||
|
}
|
||||||
|
|
||||||
|
@font-face {
|
||||||
|
font-family: Vazirmatn;
|
||||||
|
src: url('Vazirmatn-ExtraLight.woff2') format('woff2');
|
||||||
|
font-weight: 200;
|
||||||
|
font-style: normal;
|
||||||
|
font-display: swap;
|
||||||
|
}
|
||||||
|
|
||||||
|
@font-face {
|
||||||
|
font-family: Vazirmatn;
|
||||||
|
src: url('Vazirmatn-Light.woff2') format('woff2');
|
||||||
|
font-weight: 300;
|
||||||
|
font-style: normal;
|
||||||
|
font-display: swap;
|
||||||
|
}
|
||||||
|
|
||||||
|
@font-face {
|
||||||
|
font-family: Vazirmatn;
|
||||||
|
src: url('Vazirmatn-Regular.woff2') format('woff2');
|
||||||
|
font-weight: 400;
|
||||||
|
font-style: normal;
|
||||||
|
font-display: swap;
|
||||||
|
}
|
||||||
|
|
||||||
|
@font-face {
|
||||||
|
font-family: Vazirmatn;
|
||||||
|
src: url('Vazirmatn-Medium.woff2') format('woff2');
|
||||||
|
font-weight: 500;
|
||||||
|
font-style: normal;
|
||||||
|
font-display: swap;
|
||||||
|
}
|
||||||
|
|
||||||
|
@font-face {
|
||||||
|
font-family: Vazirmatn;
|
||||||
|
src: url('Vazirmatn-SemiBold.woff2') format('woff2');
|
||||||
|
font-weight: 600;
|
||||||
|
font-style: normal;
|
||||||
|
font-display: swap;
|
||||||
|
}
|
||||||
|
|
||||||
|
@font-face {
|
||||||
|
font-family: Vazirmatn;
|
||||||
|
src: url('Vazirmatn-Bold.woff2') format('woff2');
|
||||||
|
font-weight: 700;
|
||||||
|
font-style: normal;
|
||||||
|
font-display: swap;
|
||||||
|
}
|
||||||
|
|
||||||
|
@font-face {
|
||||||
|
font-family: Vazirmatn;
|
||||||
|
src: url('Vazirmatn-ExtraBold.woff2') format('woff2');
|
||||||
|
font-weight: 800;
|
||||||
|
font-style: normal;
|
||||||
|
font-display: swap;
|
||||||
|
}
|
||||||
|
|
||||||
|
@font-face {
|
||||||
|
font-family: Vazirmatn;
|
||||||
|
src: url('Vazirmatn-Black.woff2') format('woff2');
|
||||||
|
font-weight: 900;
|
||||||
|
font-style: normal;
|
||||||
|
font-display: swap;
|
||||||
|
}
|
||||||
1
src/GreenHome.Api/wwwroot/globe.svg
Normal file
@@ -0,0 +1 @@
|
|||||||
|
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>
|
||||||
|
After Width: | Height: | Size: 1.0 KiB |
1
src/GreenHome.Api/wwwroot/icon-192.png
Normal file
@@ -0,0 +1 @@
|
|||||||
|
PNG_PLACEHOLDER_192
|
||||||
1
src/GreenHome.Api/wwwroot/icon-512.png
Normal file
@@ -0,0 +1 @@
|
|||||||
|
PNG_PLACEHOLDER_512
|
||||||
21
src/GreenHome.Api/wwwroot/index.html
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="fa" dir="rtl">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
||||||
|
<meta name="theme-color" content="#16a34a" />
|
||||||
|
<meta name="application-name" content="GreenHome" />
|
||||||
|
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||||
|
<meta name="apple-mobile-web-app-status-bar-style" content="default" />
|
||||||
|
<meta name="apple-mobile-web-app-title" content="GreenHome" />
|
||||||
|
<meta name="mobile-web-app-capable" content="yes" />
|
||||||
|
<link rel="apple-touch-icon" href="/icon-512.png" />
|
||||||
|
<link rel="stylesheet" href="/fonts/vazirmatn/style.css" />
|
||||||
|
<title>GreenHome</title>
|
||||||
|
<script type="module" crossorigin src="/assets/index-BNRf8j5s.js"></script>
|
||||||
|
<link rel="stylesheet" crossorigin href="/assets/index-DiVRKiu2.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
|
||||||
|
</body>
|
||||||
0
src/GreenHome.Api/wwwroot/manifest.json
Normal file
1
src/GreenHome.Api/wwwroot/next.svg
Normal file
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>
|
||||||
|
After Width: | Height: | Size: 1.3 KiB |
193
src/GreenHome.Api/wwwroot/sw.js
Normal file
@@ -0,0 +1,193 @@
|
|||||||
|
const CACHE_NAME = 'greenhome-1780331120215';
|
||||||
|
const STATIC_CACHE_NAME = 'greenhome-static-1780331120215';
|
||||||
|
|
||||||
|
// Static assets to cache on install
|
||||||
|
const STATIC_FILES_TO_CACHE = [
|
||||||
|
'/',
|
||||||
|
'/manifest.json',
|
||||||
|
'/icon-192.png',
|
||||||
|
'/icon-512.png',
|
||||||
|
];
|
||||||
|
|
||||||
|
// Check if request is for static assets
|
||||||
|
function isStaticAsset(url) {
|
||||||
|
return (
|
||||||
|
url.includes('/_next/static/') ||
|
||||||
|
url.includes('/_next/image') ||
|
||||||
|
url.match(/\.(js|css|woff|woff2|ttf|eot|svg|png|jpg|jpeg|gif|webp|ico)$/i)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if request is for external API (skip caching)
|
||||||
|
function isExternalApiRequest(url) {
|
||||||
|
return url.startsWith('http') && !url.startsWith(self.location.origin);
|
||||||
|
}
|
||||||
|
|
||||||
|
self.addEventListener('install', (event) => {
|
||||||
|
event.waitUntil(
|
||||||
|
(async () => {
|
||||||
|
const cache = await caches.open(STATIC_CACHE_NAME);
|
||||||
|
try {
|
||||||
|
await cache.addAll(STATIC_FILES_TO_CACHE);
|
||||||
|
} catch (error) {
|
||||||
|
console.log('Some static files failed to cache:', error);
|
||||||
|
}
|
||||||
|
// Don't skip waiting automatically - let user decide when to update
|
||||||
|
// await self.skipWaiting();
|
||||||
|
})()
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
self.addEventListener('activate', (event) => {
|
||||||
|
event.waitUntil(
|
||||||
|
(async () => {
|
||||||
|
await self.clients.claim();
|
||||||
|
|
||||||
|
// Remove old caches
|
||||||
|
const keys = await caches.keys();
|
||||||
|
await Promise.all(
|
||||||
|
keys
|
||||||
|
.filter((key) => key !== CACHE_NAME && key !== STATIC_CACHE_NAME)
|
||||||
|
.map((key) => caches.delete(key))
|
||||||
|
);
|
||||||
|
})()
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Listen for messages from clients (e.g., when user clicks update button)
|
||||||
|
self.addEventListener('message', (event) => {
|
||||||
|
if (event.data && event.data.type === 'SKIP_WAITING') {
|
||||||
|
self.skipWaiting().then(() => {
|
||||||
|
// Notify all clients about update
|
||||||
|
return self.clients.matchAll();
|
||||||
|
}).then((clients) => {
|
||||||
|
clients.forEach((client) => {
|
||||||
|
client.postMessage({ type: 'SW_UPDATED' });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
self.addEventListener('fetch', (event) => {
|
||||||
|
const { request } = event;
|
||||||
|
const url = new URL(request.url);
|
||||||
|
|
||||||
|
// Skip non-GET requests and external API requests
|
||||||
|
if (request.method !== 'GET' || isExternalApiRequest(url.href)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle navigation requests (pages)
|
||||||
|
if (request.mode === 'navigate') {
|
||||||
|
event.respondWith(
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
// Try network first
|
||||||
|
const preloadResponse = await event.preloadResponse;
|
||||||
|
if (preloadResponse) {
|
||||||
|
const cache = await caches.open(CACHE_NAME);
|
||||||
|
cache.put(request, preloadResponse.clone());
|
||||||
|
return preloadResponse;
|
||||||
|
}
|
||||||
|
|
||||||
|
const networkResponse = await fetch(request);
|
||||||
|
|
||||||
|
// Cache successful responses
|
||||||
|
if (networkResponse.ok) {
|
||||||
|
const cache = await caches.open(CACHE_NAME);
|
||||||
|
cache.put(request, networkResponse.clone());
|
||||||
|
}
|
||||||
|
|
||||||
|
return networkResponse;
|
||||||
|
} catch (error) {
|
||||||
|
// Network failed, try cache
|
||||||
|
const cache = await caches.open(CACHE_NAME);
|
||||||
|
const cachedResponse = await cache.match(request);
|
||||||
|
|
||||||
|
if (cachedResponse) {
|
||||||
|
return cachedResponse;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback to home page if available
|
||||||
|
const homePage = await cache.match('/');
|
||||||
|
if (homePage) {
|
||||||
|
return homePage;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Last resort: return offline page
|
||||||
|
return new Response('Offline - No internet connection', {
|
||||||
|
status: 503,
|
||||||
|
statusText: 'Service Unavailable',
|
||||||
|
headers: { 'Content-Type': 'text/html' },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
})()
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle static assets (Cache First strategy)
|
||||||
|
if (isStaticAsset(url.href)) {
|
||||||
|
event.respondWith(
|
||||||
|
(async () => {
|
||||||
|
const cache = await caches.open(STATIC_CACHE_NAME);
|
||||||
|
const cachedResponse = await cache.match(request);
|
||||||
|
|
||||||
|
if (cachedResponse) {
|
||||||
|
return cachedResponse;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const networkResponse = await fetch(request);
|
||||||
|
|
||||||
|
// Cache successful responses
|
||||||
|
if (networkResponse.ok) {
|
||||||
|
cache.put(request, networkResponse.clone());
|
||||||
|
}
|
||||||
|
|
||||||
|
return networkResponse;
|
||||||
|
} catch (error) {
|
||||||
|
// If network fails and no cache, return error
|
||||||
|
return new Response('Resource not available offline', {
|
||||||
|
status: 503,
|
||||||
|
statusText: 'Service Unavailable',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
})()
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle other requests (Network First strategy)
|
||||||
|
event.respondWith(
|
||||||
|
(async () => {
|
||||||
|
const cache = await caches.open(CACHE_NAME);
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Try network first
|
||||||
|
const networkResponse = await fetch(request);
|
||||||
|
|
||||||
|
// Cache successful responses
|
||||||
|
if (networkResponse.ok) {
|
||||||
|
cache.put(request, networkResponse.clone());
|
||||||
|
}
|
||||||
|
|
||||||
|
return networkResponse;
|
||||||
|
} catch (error) {
|
||||||
|
// Network failed, try cache
|
||||||
|
const cachedResponse = await cache.match(request);
|
||||||
|
|
||||||
|
if (cachedResponse) {
|
||||||
|
return cachedResponse;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return error if no cache available
|
||||||
|
return new Response('Resource not available offline', {
|
||||||
|
status: 503,
|
||||||
|
statusText: 'Service Unavailable',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
})()
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 30 KiB |
|
After Width: | Height: | Size: 30 KiB |
1
src/GreenHome.Api/wwwroot/vercel.svg
Normal file
@@ -0,0 +1 @@
|
|||||||
|
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>
|
||||||
|
After Width: | Height: | Size: 128 B |
3
src/GreenHome.Api/wwwroot/version.json
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
{
|
||||||
|
"version": "1780331120215"
|
||||||
|
}
|
||||||
1
src/GreenHome.Api/wwwroot/window.svg
Normal file
@@ -0,0 +1 @@
|
|||||||
|
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>
|
||||||
|
After Width: | Height: | Size: 385 B |
1
src/GreenHome.Api/wwwroot/workbox-00a24876.js
Normal file
@@ -1,140 +0,0 @@
|
|||||||
using Domain = GreenHome.Domain;
|
|
||||||
|
|
||||||
namespace GreenHome.Application;
|
|
||||||
|
|
||||||
// DTOs
|
|
||||||
public sealed class DeviceDto
|
|
||||||
{
|
|
||||||
public int Id { get; set; }
|
|
||||||
public string DeviceName { get; set; } = string.Empty;
|
|
||||||
public int UserId { get; set; }
|
|
||||||
public string UserName { get; set; } = string.Empty;
|
|
||||||
public string UserFamily { get; set; } = string.Empty;
|
|
||||||
public string UserMobile { get; set; } = string.Empty;
|
|
||||||
public string Location { get; set; } = string.Empty;
|
|
||||||
public string NeshanLocation { get; set; } = string.Empty;
|
|
||||||
}
|
|
||||||
|
|
||||||
public sealed class TelemetryDto
|
|
||||||
{
|
|
||||||
public int Id { get; set; }
|
|
||||||
public int DeviceId { get; set; }
|
|
||||||
public string DeviceName { get; set; }
|
|
||||||
public DateTime TimestampUtc { get; set; }
|
|
||||||
public decimal TemperatureC { get; set; }
|
|
||||||
public decimal HumidityPercent { get; set; }
|
|
||||||
public decimal SoilPercent { get; set; }
|
|
||||||
public int GasPPM { get; set; }
|
|
||||||
public decimal Lux { get; set; }
|
|
||||||
public int PersianYear { get; set; }
|
|
||||||
public int PersianMonth { get; set; }
|
|
||||||
public string PersianDate { get; set; } = string.Empty;
|
|
||||||
}
|
|
||||||
|
|
||||||
public sealed class TelemetryFilter
|
|
||||||
{
|
|
||||||
public int? DeviceId { get; set; }
|
|
||||||
public DateTime? StartDateUtc { get; set; }
|
|
||||||
public DateTime? EndDateUtc { get; set; }
|
|
||||||
public int Page { get; set; } = 1;
|
|
||||||
public int PageSize { get; set; } = 20;
|
|
||||||
}
|
|
||||||
|
|
||||||
public sealed class PagedResult<T>
|
|
||||||
{
|
|
||||||
public required IReadOnlyList<T> Items { get; init; }
|
|
||||||
public required int TotalCount { get; init; }
|
|
||||||
public required int Page { get; init; }
|
|
||||||
public required int PageSize { get; init; }
|
|
||||||
}
|
|
||||||
|
|
||||||
public sealed class TelemetryMinMax
|
|
||||||
{
|
|
||||||
public decimal MinTemperatureC { get; set; }
|
|
||||||
public decimal MaxTemperatureC { get; set; }
|
|
||||||
public decimal MinHumidityPercent { get; set; }
|
|
||||||
public decimal MaxHumidityPercent { get; set; }
|
|
||||||
public decimal MinSoilPercent { get; set; }
|
|
||||||
public decimal MaxSoilPercent { get; set; }
|
|
||||||
public int MinGasPPM { get; set; }
|
|
||||||
public int MaxGasPPM { get; set; }
|
|
||||||
public decimal MinLux { get; set; }
|
|
||||||
public decimal MaxLux { get; set; }
|
|
||||||
}
|
|
||||||
|
|
||||||
public sealed class DayCount
|
|
||||||
{
|
|
||||||
public string PersianDate { get; set; } = string.Empty;
|
|
||||||
public int Count { get; set; }
|
|
||||||
}
|
|
||||||
|
|
||||||
public sealed class SendCodeRequest
|
|
||||||
{
|
|
||||||
public required string Mobile { get; set; }
|
|
||||||
}
|
|
||||||
|
|
||||||
public sealed class SendCodeResponse
|
|
||||||
{
|
|
||||||
public bool Success { get; set; }
|
|
||||||
public string? Message { get; set; }
|
|
||||||
public int ResendAfterSeconds { get; set; } = 120;
|
|
||||||
}
|
|
||||||
|
|
||||||
public sealed class VerifyCodeRequest
|
|
||||||
{
|
|
||||||
public required string Mobile { get; set; }
|
|
||||||
public required string Code { get; set; }
|
|
||||||
}
|
|
||||||
|
|
||||||
public sealed class VerifyCodeResponse
|
|
||||||
{
|
|
||||||
public bool Success { get; set; }
|
|
||||||
public string? Message { get; set; }
|
|
||||||
public string? Token { get; set; }
|
|
||||||
public UserDto? User { get; set; }
|
|
||||||
}
|
|
||||||
|
|
||||||
public sealed class UserDto
|
|
||||||
{
|
|
||||||
public int Id { get; set; }
|
|
||||||
public string Mobile { get; set; } = string.Empty;
|
|
||||||
public string Name { get; set; } = string.Empty;
|
|
||||||
public string Family { get; set; } = string.Empty;
|
|
||||||
public Domain.UserRole Role { get; set; }
|
|
||||||
}
|
|
||||||
|
|
||||||
public sealed class DeviceFilter
|
|
||||||
{
|
|
||||||
public int? UserId { get; set; }
|
|
||||||
public string? Search { get; set; } // جستجو در نام دستگاه، نام صاحب، نام خانوادگی صاحب، Location
|
|
||||||
public int Page { get; set; } = 1;
|
|
||||||
public int PageSize { get; set; } = 10;
|
|
||||||
}
|
|
||||||
|
|
||||||
public sealed class DeviceSettingsDto
|
|
||||||
{
|
|
||||||
public int Id { get; set; }
|
|
||||||
public int DeviceId { get; set; }
|
|
||||||
public string DeviceName { get; set; } = string.Empty;
|
|
||||||
|
|
||||||
// Temperature settings
|
|
||||||
public decimal DangerMaxTemperature { get; set; }
|
|
||||||
public decimal DangerMinTemperature { get; set; }
|
|
||||||
public decimal MaxTemperature { get; set; }
|
|
||||||
public decimal MinTemperature { get; set; }
|
|
||||||
|
|
||||||
// Gas settings
|
|
||||||
public int MaxGasPPM { get; set; }
|
|
||||||
public int MinGasPPM { get; set; }
|
|
||||||
|
|
||||||
// Light settings
|
|
||||||
public decimal MaxLux { get; set; }
|
|
||||||
public decimal MinLux { get; set; }
|
|
||||||
|
|
||||||
// Humidity settings
|
|
||||||
public decimal MaxHumidityPercent { get; set; }
|
|
||||||
public decimal MinHumidityPercent { get; set; }
|
|
||||||
|
|
||||||
public DateTime CreatedAt { get; set; }
|
|
||||||
public DateTime UpdatedAt { get; set; }
|
|
||||||
}
|
|
||||||
100
src/GreenHome.Application/Dtos/AI/AIProfileDtos.cs
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
using GreenHome.Domain;
|
||||||
|
|
||||||
|
namespace GreenHome.Application;
|
||||||
|
|
||||||
|
// ==================== AI Profile ====================
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// An AI profile as shown in the admin list, with aggregated usage.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class AIProfileDto
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
public string Name { get; set; } = string.Empty;
|
||||||
|
public AIProvider Provider { get; set; }
|
||||||
|
public string BaseUrl { get; set; } = string.Empty;
|
||||||
|
public string Model { get; set; } = string.Empty;
|
||||||
|
public bool IsActive { get; set; }
|
||||||
|
public double? Temperature { get; set; }
|
||||||
|
public decimal? PromptPricePer1M { get; set; }
|
||||||
|
public decimal? CompletionPricePer1M { get; set; }
|
||||||
|
|
||||||
|
// Last known balance (may be null if the provider has no balance endpoint)
|
||||||
|
public decimal? BalanceUsd { get; set; }
|
||||||
|
public string? BalanceCurrency { get; set; }
|
||||||
|
public DateTime? BalanceUpdatedAt { get; set; }
|
||||||
|
|
||||||
|
// Aggregated usage for this profile (from the AIQueries log)
|
||||||
|
public int QueryCount { get; set; }
|
||||||
|
public int TotalPromptTokens { get; set; }
|
||||||
|
public int TotalCompletionTokens { get; set; }
|
||||||
|
public int TotalTokens { get; set; }
|
||||||
|
public decimal TotalCostUsd { get; set; }
|
||||||
|
|
||||||
|
public DateTime CreatedAt { get; set; }
|
||||||
|
public DateTime UpdatedAt { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class AIProfileCreateRequest
|
||||||
|
{
|
||||||
|
public required string Name { get; set; }
|
||||||
|
public AIProvider Provider { get; set; }
|
||||||
|
public string? BaseUrl { get; set; }
|
||||||
|
public required string ApiKey { get; set; }
|
||||||
|
public required string Model { get; set; }
|
||||||
|
public double? Temperature { get; set; }
|
||||||
|
public int? MaxTokens { get; set; }
|
||||||
|
public decimal? PromptPricePer1M { get; set; }
|
||||||
|
public decimal? CompletionPricePer1M { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class AIProfileUpdateRequest
|
||||||
|
{
|
||||||
|
public required string Name { get; set; }
|
||||||
|
public AIProvider Provider { get; set; }
|
||||||
|
public string? BaseUrl { get; set; }
|
||||||
|
public required string ApiKey { get; set; }
|
||||||
|
public required string Model { get; set; }
|
||||||
|
public double? Temperature { get; set; }
|
||||||
|
public int? MaxTokens { get; set; }
|
||||||
|
public decimal? PromptPricePer1M { get; set; }
|
||||||
|
public decimal? CompletionPricePer1M { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Best-effort account balance for a provider (null = unavailable).
|
||||||
|
/// </summary>
|
||||||
|
public sealed class AIBalance
|
||||||
|
{
|
||||||
|
public decimal Amount { get; set; }
|
||||||
|
public string? Currency { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== AI Profile Usage ====================
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Aggregated usage for a single profile.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class AIProfileUsageDto
|
||||||
|
{
|
||||||
|
public int QueryCount { get; set; }
|
||||||
|
public int TotalPromptTokens { get; set; }
|
||||||
|
public int TotalCompletionTokens { get; set; }
|
||||||
|
public int TotalTokens { get; set; }
|
||||||
|
public decimal TotalCostUsd { get; set; }
|
||||||
|
public decimal? BalanceUsd { get; set; }
|
||||||
|
public string? BalanceCurrency { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// One day of AI usage for a profile (for charting).
|
||||||
|
/// </summary>
|
||||||
|
public sealed class AIProfileUsageDayDto
|
||||||
|
{
|
||||||
|
public DateOnly Date { get; set; }
|
||||||
|
public int QueryCount { get; set; }
|
||||||
|
public int PromptTokens { get; set; }
|
||||||
|
public int CompletionTokens { get; set; }
|
||||||
|
public int TotalTokens { get; set; }
|
||||||
|
public decimal CostUsd { get; set; }
|
||||||
|
}
|
||||||
42
src/GreenHome.Application/Dtos/AI/AIQueryStats.cs
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
namespace GreenHome.Application;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Statistics about AI query usage
|
||||||
|
/// </summary>
|
||||||
|
public sealed class AIQueryStats
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Total number of queries made
|
||||||
|
/// </summary>
|
||||||
|
public int TotalQueries { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Total tokens used across all queries
|
||||||
|
/// </summary>
|
||||||
|
public int TotalTokensUsed { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Total prompt tokens used
|
||||||
|
/// </summary>
|
||||||
|
public int TotalPromptTokens { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Total completion tokens used
|
||||||
|
/// </summary>
|
||||||
|
public int TotalCompletionTokens { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Average response time in milliseconds
|
||||||
|
/// </summary>
|
||||||
|
public double AverageResponseTimeMs { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Number of queries made today
|
||||||
|
/// </summary>
|
||||||
|
public int TodayQueries { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Total tokens used today
|
||||||
|
/// </summary>
|
||||||
|
public int TodayTokens { get; set; }
|
||||||
|
}
|
||||||
339
src/GreenHome.Application/Dtos/Admin/AdminDtos.cs
Normal file
@@ -0,0 +1,339 @@
|
|||||||
|
using Domain = GreenHome.Domain;
|
||||||
|
|
||||||
|
namespace GreenHome.Application.Dtos.Admin;
|
||||||
|
|
||||||
|
// ==================== Dashboard ====================
|
||||||
|
|
||||||
|
public sealed class AdminDashboardDto
|
||||||
|
{
|
||||||
|
public int TotalUsers { get; set; }
|
||||||
|
public int TotalDevices { get; set; }
|
||||||
|
public int OnlineDevices { get; set; }
|
||||||
|
public int OfflineDevices { get; set; }
|
||||||
|
public int AlertsLast24h { get; set; }
|
||||||
|
public int SmsLast7Days { get; set; }
|
||||||
|
public int AiQueriesLast7Days { get; set; }
|
||||||
|
|
||||||
|
/// <summary>تعداد SMS بر اساس روز برای ۷ روز اخیر (sparkline)</summary>
|
||||||
|
public IReadOnlyList<UsageDayDto> SmsDailyLast7Days { get; set; } = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== Users ====================
|
||||||
|
|
||||||
|
public sealed class AdminUserFilter
|
||||||
|
{
|
||||||
|
public string? Search { get; set; }
|
||||||
|
public int Page { get; set; } = 1;
|
||||||
|
public int PageSize { get; set; } = 20;
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class AdminUserListItemDto
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
public string Name { get; set; } = string.Empty;
|
||||||
|
public string Family { get; set; } = string.Empty;
|
||||||
|
public string Mobile { get; set; } = string.Empty;
|
||||||
|
public Domain.UserRole Role { get; set; }
|
||||||
|
public bool IsDisabled { get; set; }
|
||||||
|
public int DeviceCount { get; set; }
|
||||||
|
public DateTime? LastLoginAt { get; set; }
|
||||||
|
public DateTime CreatedAt { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class AdminUserDetailDto
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
public string Name { get; set; } = string.Empty;
|
||||||
|
public string Family { get; set; } = string.Empty;
|
||||||
|
public string Mobile { get; set; } = string.Empty;
|
||||||
|
public Domain.UserRole Role { get; set; }
|
||||||
|
public bool IsDisabled { get; set; }
|
||||||
|
public DateTime CreatedAt { get; set; }
|
||||||
|
public DateTime? LastLoginAt { get; set; }
|
||||||
|
public IReadOnlyList<AdminDeviceListItemDto> Devices { get; set; } = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class ChangeUserRoleRequest
|
||||||
|
{
|
||||||
|
public Domain.UserRole Role { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class ChangeUserStatusRequest
|
||||||
|
{
|
||||||
|
public bool IsEnabled { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// نتیجه تغییر نقش/وضعیت کاربر توسط admin.
|
||||||
|
/// </summary>
|
||||||
|
public enum UserMutationOutcome
|
||||||
|
{
|
||||||
|
Ok,
|
||||||
|
NotFound,
|
||||||
|
ConflictSelf,
|
||||||
|
ConflictLastAdmin
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== Devices ====================
|
||||||
|
|
||||||
|
public sealed class AdminDeviceFilter
|
||||||
|
{
|
||||||
|
public string? Search { get; set; }
|
||||||
|
public int Page { get; set; } = 1;
|
||||||
|
public int PageSize { get; set; } = 20;
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class AdminDeviceListItemDto
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
public string DeviceName { get; set; } = string.Empty;
|
||||||
|
public string Location { get; set; } = string.Empty;
|
||||||
|
public string OwnerName { get; set; } = string.Empty;
|
||||||
|
public string OwnerMobile { get; set; } = string.Empty;
|
||||||
|
public bool IsOnline { get; set; }
|
||||||
|
public DateTime? LastTelemetryAt { get; set; }
|
||||||
|
public decimal? TemperatureC { get; set; }
|
||||||
|
public decimal? HumidityPercent { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class AdminDeviceDetailDto
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
public string DeviceName { get; set; } = string.Empty;
|
||||||
|
public string Location { get; set; } = string.Empty;
|
||||||
|
public string OwnerName { get; set; } = string.Empty;
|
||||||
|
public string OwnerFamily { get; set; } = string.Empty;
|
||||||
|
public string OwnerMobile { get; set; } = string.Empty;
|
||||||
|
public bool IsOnline { get; set; }
|
||||||
|
public int MemberCount { get; set; }
|
||||||
|
|
||||||
|
public string? ProductType { get; set; }
|
||||||
|
public string? Province { get; set; }
|
||||||
|
public string? City { get; set; }
|
||||||
|
public string? DevicePhoneNumber { get; set; }
|
||||||
|
public int? UploadIntervalMin { get; set; }
|
||||||
|
public int? RelayCount { get; set; }
|
||||||
|
public string? NeshanLocation { get; set; }
|
||||||
|
public decimal? Latitude { get; set; }
|
||||||
|
public decimal? Longitude { get; set; }
|
||||||
|
public int? MinimumSmsIntervalMinutes { get; set; }
|
||||||
|
public int? MinimumCallIntervalMinutes { get; set; }
|
||||||
|
public decimal? AreaSquareMeters { get; set; }
|
||||||
|
public Domain.SimCardType? SimCardType { get; set; }
|
||||||
|
public string? SmsRecievers { get; set; }
|
||||||
|
|
||||||
|
public IReadOnlyList<TelemetryDto> LastTelemetry { get; set; } = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== Devices: create / settings / members ====================
|
||||||
|
|
||||||
|
public sealed class AdminDeviceCreateRequest
|
||||||
|
{
|
||||||
|
public int UserId { get; set; }
|
||||||
|
public string DeviceName { get; set; } = string.Empty;
|
||||||
|
public string Location { get; set; } = string.Empty;
|
||||||
|
public string? NeshanLocation { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public enum AdminDeviceCreateOutcome
|
||||||
|
{
|
||||||
|
Ok,
|
||||||
|
UserNotFound,
|
||||||
|
ConflictDuplicateName,
|
||||||
|
Validation
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class AdminDeviceCreateResult
|
||||||
|
{
|
||||||
|
public AdminDeviceCreateOutcome Outcome { get; set; }
|
||||||
|
public int DeviceId { get; set; }
|
||||||
|
public string DeviceName { get; set; } = string.Empty;
|
||||||
|
/// <summary>پیام فارسی برای خطاهای Validation</summary>
|
||||||
|
public string Message { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class AdminDeviceSettingsUpdateRequest
|
||||||
|
{
|
||||||
|
public string DeviceName { get; set; } = string.Empty;
|
||||||
|
public string Province { get; set; } = string.Empty;
|
||||||
|
public string City { get; set; } = string.Empty;
|
||||||
|
public decimal? Latitude { get; set; }
|
||||||
|
public decimal? Longitude { get; set; }
|
||||||
|
public string ProductType { get; set; } = string.Empty;
|
||||||
|
public int MinimumSmsIntervalMinutes { get; set; }
|
||||||
|
public int MinimumCallIntervalMinutes { get; set; }
|
||||||
|
public decimal? AreaSquareMeters { get; set; }
|
||||||
|
public int UploadIntervalMin { get; set; }
|
||||||
|
public string DevicePhoneNumber { get; set; } = string.Empty;
|
||||||
|
public Domain.SimCardType? SimCardType { get; set; }
|
||||||
|
public int RelayCount { get; set; }
|
||||||
|
public string SmsRecievers { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Success = !NotFound && Message == null
|
||||||
|
/// </summary>
|
||||||
|
public sealed class AdminSettingsUpdateResult
|
||||||
|
{
|
||||||
|
public bool NotFound { get; set; }
|
||||||
|
public string? Message { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class AdminDeviceMemberDto
|
||||||
|
{
|
||||||
|
public int UserId { get; set; }
|
||||||
|
public string Name { get; set; } = string.Empty;
|
||||||
|
public string Family { get; set; } = string.Empty;
|
||||||
|
public string Mobile { get; set; } = string.Empty;
|
||||||
|
public string MemberName { get; set; } = string.Empty;
|
||||||
|
public string MemberFamily { get; set; } = string.Empty;
|
||||||
|
public Domain.DeviceMemberRole Role { get; set; }
|
||||||
|
public bool ReceiveAlerts { get; set; }
|
||||||
|
public string? AvatarPath { get; set; }
|
||||||
|
public bool IsOwner { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== Usage ====================
|
||||||
|
|
||||||
|
public sealed class UsageDayDto
|
||||||
|
{
|
||||||
|
public DateTime Date { get; set; }
|
||||||
|
public int SmsCount { get; set; }
|
||||||
|
public int VoiceCallCount { get; set; }
|
||||||
|
public int AiQueryCount { get; set; }
|
||||||
|
public int AiTokenCount { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== Alerts ====================
|
||||||
|
|
||||||
|
public sealed class AdminAlertFilter
|
||||||
|
{
|
||||||
|
public int? DeviceId { get; set; }
|
||||||
|
public Domain.AlertStatus? Status { get; set; }
|
||||||
|
public DateTime? From { get; set; }
|
||||||
|
public DateTime? To { get; set; }
|
||||||
|
public int Page { get; set; } = 1;
|
||||||
|
public int PageSize { get; set; } = 20;
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class AdminAlertItemDto
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
public int DeviceId { get; set; }
|
||||||
|
public string DeviceName { get; set; } = string.Empty;
|
||||||
|
public string OwnerName { get; set; } = string.Empty;
|
||||||
|
public string Message { get; set; } = string.Empty;
|
||||||
|
public Domain.AlertNotificationType NotificationType { get; set; }
|
||||||
|
public Domain.AlertStatus Status { get; set; }
|
||||||
|
public string? ErrorMessage { get; set; }
|
||||||
|
public DateTime SentAt { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== Posts ====================
|
||||||
|
|
||||||
|
public sealed class AdminPostFilter
|
||||||
|
{
|
||||||
|
public int? DeviceId { get; set; }
|
||||||
|
public int? AuthorUserId { get; set; }
|
||||||
|
public Domain.DevicePostType? PostType { get; set; }
|
||||||
|
public DateTime? From { get; set; }
|
||||||
|
public DateTime? To { get; set; }
|
||||||
|
public int Page { get; set; } = 1;
|
||||||
|
public int PageSize { get; set; } = 20;
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class AdminPostItemDto
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
public int DeviceId { get; set; }
|
||||||
|
public string DeviceName { get; set; } = string.Empty;
|
||||||
|
public int AuthorUserId { get; set; }
|
||||||
|
public string AuthorName { get; set; } = string.Empty;
|
||||||
|
public string Content { get; set; } = string.Empty;
|
||||||
|
public Domain.DevicePostType PostType { get; set; }
|
||||||
|
public int ImageCount { get; set; }
|
||||||
|
public bool HasVoice { get; set; }
|
||||||
|
public int? VoiceDurationSeconds { get; set; }
|
||||||
|
public DateTime CreatedAt { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class AdminPostDetailDto
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
public int DeviceId { get; set; }
|
||||||
|
public string DeviceName { get; set; } = string.Empty;
|
||||||
|
public string AuthorName { get; set; } = string.Empty;
|
||||||
|
public string AuthorFamily { get; set; } = string.Empty;
|
||||||
|
public Domain.DevicePostType PostType { get; set; }
|
||||||
|
public string Content { get; set; } = string.Empty;
|
||||||
|
public DateTime CreatedAt { get; set; }
|
||||||
|
public IReadOnlyList<AdminPostImageDto> Images { get; set; } = [];
|
||||||
|
public string? VoiceFilePath { get; set; }
|
||||||
|
public int? VoiceDurationSeconds { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class AdminPostImageDto
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
public string FileName { get; set; } = string.Empty;
|
||||||
|
public string FilePath { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== Device Debug ====================
|
||||||
|
|
||||||
|
public sealed class AdminDeviceTestResultDto
|
||||||
|
{
|
||||||
|
public bool Success { get; set; }
|
||||||
|
public string Message { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== Reports ====================
|
||||||
|
|
||||||
|
public sealed class AdminUserGrowthRowDto
|
||||||
|
{
|
||||||
|
public DateOnly Date { get; set; }
|
||||||
|
public int NewUsers { get; set; }
|
||||||
|
public int ActiveUsers { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class AdminDeviceUptimeRowDto
|
||||||
|
{
|
||||||
|
public int DeviceId { get; set; }
|
||||||
|
public string DeviceName { get; set; } = string.Empty;
|
||||||
|
public string OwnerName { get; set; } = string.Empty;
|
||||||
|
public int TotalDays { get; set; }
|
||||||
|
public int OnlineDays { get; set; }
|
||||||
|
public int OnlinePercent { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class AdminUsageByUserRowDto
|
||||||
|
{
|
||||||
|
public int UserId { get; set; }
|
||||||
|
public string Name { get; set; } = string.Empty;
|
||||||
|
public string Family { get; set; } = string.Empty;
|
||||||
|
public string Mobile { get; set; } = string.Empty;
|
||||||
|
public int Sms { get; set; }
|
||||||
|
public int VoiceCall { get; set; }
|
||||||
|
public int AiQueries { get; set; }
|
||||||
|
public int AiTokens { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== Audit Log ====================
|
||||||
|
|
||||||
|
public sealed class AdminAuditLogFilter
|
||||||
|
{
|
||||||
|
public int? AdminId { get; set; }
|
||||||
|
public int Page { get; set; } = 1;
|
||||||
|
public int PageSize { get; set; } = 20;
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class AdminAuditLogDto
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
public int AdminUserId { get; set; }
|
||||||
|
public string AdminName { get; set; } = string.Empty;
|
||||||
|
public string Action { get; set; } = string.Empty;
|
||||||
|
public string TargetId { get; set; } = string.Empty;
|
||||||
|
public string Details { get; set; } = string.Empty;
|
||||||
|
public DateTime At { get; set; }
|
||||||
|
}
|
||||||
29
src/GreenHome.Application/Dtos/Alert/AlertConditionDto.cs
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
using Domain = GreenHome.Domain;
|
||||||
|
|
||||||
|
namespace GreenHome.Application;
|
||||||
|
|
||||||
|
public sealed class AlertConditionDto
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
public int DeviceId { get; set; }
|
||||||
|
public string DeviceName { get; set; } = string.Empty;
|
||||||
|
public Domain.AlertNotificationType NotificationType { get; set; }
|
||||||
|
public Domain.AlertTimeType TimeType { get; set; }
|
||||||
|
public int CallCooldownMinutes { get; set; } = 60;
|
||||||
|
public int SmsCooldownMinutes { get; set; } = 15;
|
||||||
|
public bool IsEnabled { get; set; } = true;
|
||||||
|
public DateTime CreatedAt { get; set; }
|
||||||
|
public DateTime UpdatedAt { get; set; }
|
||||||
|
public List<AlertRuleDto> Rules { get; set; } = new();
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class AlertRuleDto
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
public int AlertConditionId { get; set; }
|
||||||
|
public Domain.SensorType SensorType { get; set; }
|
||||||
|
public Domain.ComparisonType ComparisonType { get; set; }
|
||||||
|
public decimal Value1 { get; set; }
|
||||||
|
public decimal? Value2 { get; set; }
|
||||||
|
public int Order { get; set; }
|
||||||
|
}
|
||||||
22
src/GreenHome.Application/Dtos/Alert/AlertLogDto.cs
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
using Domain = GreenHome.Domain;
|
||||||
|
|
||||||
|
namespace GreenHome.Application;
|
||||||
|
|
||||||
|
public sealed class AlertLogDto
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
public int DeviceId { get; set; }
|
||||||
|
public string DeviceName { get; set; } = string.Empty;
|
||||||
|
public int UserId { get; set; }
|
||||||
|
public string UserName { get; set; } = string.Empty;
|
||||||
|
public string UserMobile { get; set; } = string.Empty;
|
||||||
|
public int? AlertConditionId { get; set; }
|
||||||
|
public Domain.AlertType AlertType { get; set; }
|
||||||
|
public Domain.AlertNotificationType NotificationType { get; set; }
|
||||||
|
public string Message { get; set; } = string.Empty;
|
||||||
|
public Domain.AlertStatus Status { get; set; }
|
||||||
|
public string? ErrorMessage { get; set; }
|
||||||
|
public string PhoneNumber { get; set; } = string.Empty;
|
||||||
|
public DateTime SentAt { get; set; }
|
||||||
|
public long ProcessingTimeMs { get; set; }
|
||||||
|
}
|
||||||
15
src/GreenHome.Application/Dtos/Alert/AlertLogFilter.cs
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
using Domain = GreenHome.Domain;
|
||||||
|
|
||||||
|
namespace GreenHome.Application;
|
||||||
|
|
||||||
|
public sealed class AlertLogFilter
|
||||||
|
{
|
||||||
|
public int? DeviceId { get; set; }
|
||||||
|
public int? UserId { get; set; }
|
||||||
|
public Domain.AlertType? AlertType { get; set; }
|
||||||
|
public Domain.AlertStatus? Status { get; set; }
|
||||||
|
public DateTime? StartDate { get; set; }
|
||||||
|
public DateTime? EndDate { get; set; }
|
||||||
|
public int Page { get; set; } = 1;
|
||||||
|
public int PageSize { get; set; } = 20;
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
using Domain = GreenHome.Domain;
|
||||||
|
|
||||||
|
namespace GreenHome.Application;
|
||||||
|
|
||||||
|
public sealed class CreateAlertConditionRequest
|
||||||
|
{
|
||||||
|
public required int DeviceId { get; set; }
|
||||||
|
public required Domain.AlertNotificationType NotificationType { get; set; }
|
||||||
|
public required Domain.AlertTimeType TimeType { get; set; }
|
||||||
|
public int CallCooldownMinutes { get; set; } = 60;
|
||||||
|
public int SmsCooldownMinutes { get; set; } = 15;
|
||||||
|
public bool IsEnabled { get; set; } = true;
|
||||||
|
public required List<CreateAlertRuleRequest> Rules { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class CreateAlertRuleRequest
|
||||||
|
{
|
||||||
|
public required Domain.SensorType SensorType { get; set; }
|
||||||
|
public required Domain.ComparisonType ComparisonType { get; set; }
|
||||||
|
public required decimal Value1 { get; set; }
|
||||||
|
public decimal? Value2 { get; set; }
|
||||||
|
public int Order { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class UpdateAlertConditionRequest
|
||||||
|
{
|
||||||
|
public required int Id { get; set; }
|
||||||
|
public required Domain.AlertNotificationType NotificationType { get; set; }
|
||||||
|
public required Domain.AlertTimeType TimeType { get; set; }
|
||||||
|
public int CallCooldownMinutes { get; set; } = 60;
|
||||||
|
public int SmsCooldownMinutes { get; set; } = 15;
|
||||||
|
public bool IsEnabled { get; set; } = true;
|
||||||
|
public required List<CreateAlertRuleRequest> Rules { get; set; }
|
||||||
|
}
|
||||||
54
src/GreenHome.Application/Dtos/Alert/RelayConditionDto.cs
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
namespace GreenHome.Application;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// DTO for relay conditions sent to the device firmware.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class RelayConditionDto
|
||||||
|
{
|
||||||
|
public int Enabled { get; set; }
|
||||||
|
|
||||||
|
/// <summary>شناسه رله برای سازگاری با فریمور قبلی (مثلاً R1)</summary>
|
||||||
|
public string Relay { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>شماره رله (۱ تا RelayCount)</summary>
|
||||||
|
public int RelayIndex { get; set; }
|
||||||
|
|
||||||
|
/// <summary>نام نمایشی رله (فن، هیتر و ...)</summary>
|
||||||
|
public string Name { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>گروههای روشن شدن (OR بین گروهها)</summary>
|
||||||
|
public List<RelayGroupDto> On { get; set; } = new();
|
||||||
|
|
||||||
|
/// <summary>گروههای خاموش شدن (OR بین گروهها)</summary>
|
||||||
|
public List<RelayGroupDto> Off { get; set; } = new();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// یک گروه شرط (AND داخل گروه)
|
||||||
|
/// </summary>
|
||||||
|
public sealed class RelayGroupDto
|
||||||
|
{
|
||||||
|
/// <summary>برچسب اختیاری گروه برای لاگ/اعلان</summary>
|
||||||
|
public string? Label { get; set; }
|
||||||
|
|
||||||
|
public List<RelayRuleDto> Conditions { get; set; } = new();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// یک شرط واحد: سنسوری (Kind=0) یا زمانی (Kind=1)
|
||||||
|
/// </summary>
|
||||||
|
public sealed class RelayRuleDto
|
||||||
|
{
|
||||||
|
/// <summary>نوع شرط: 0 = سنسوری، 1 = زمانی</summary>
|
||||||
|
public int Kind { get; set; }
|
||||||
|
|
||||||
|
// سنسوری
|
||||||
|
public int? Sensor { get; set; }
|
||||||
|
public int? Op { get; set; }
|
||||||
|
public decimal? V1 { get; set; }
|
||||||
|
public decimal? V2 { get; set; }
|
||||||
|
|
||||||
|
// زمانی (دقیقه از نیمهشب)
|
||||||
|
public int? Start { get; set; }
|
||||||
|
public int? End { get; set; }
|
||||||
|
}
|
||||||
6
src/GreenHome.Application/Dtos/Auth/SendCodeRequest.cs
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
namespace GreenHome.Application;
|
||||||
|
|
||||||
|
public sealed class SendCodeRequest
|
||||||
|
{
|
||||||
|
public required string Mobile { get; set; }
|
||||||
|
}
|
||||||
8
src/GreenHome.Application/Dtos/Auth/SendCodeResponse.cs
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
namespace GreenHome.Application;
|
||||||
|
|
||||||
|
public sealed class SendCodeResponse
|
||||||
|
{
|
||||||
|
public bool Success { get; set; }
|
||||||
|
public string? Message { get; set; }
|
||||||
|
public int ResendAfterSeconds { get; set; } = 120;
|
||||||
|
}
|
||||||
13
src/GreenHome.Application/Dtos/Auth/UserDto.cs
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
using Domain = GreenHome.Domain;
|
||||||
|
|
||||||
|
namespace GreenHome.Application;
|
||||||
|
|
||||||
|
public sealed class UserDto
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
public string Mobile { get; set; } = string.Empty;
|
||||||
|
public string Name { get; set; } = string.Empty;
|
||||||
|
public string Family { get; set; } = string.Empty;
|
||||||
|
public Domain.UserRole Role { get; set; }
|
||||||
|
public bool IsDisabled { get; set; }
|
||||||
|
}
|
||||||
7
src/GreenHome.Application/Dtos/Auth/VerifyCodeRequest.cs
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
namespace GreenHome.Application;
|
||||||
|
|
||||||
|
public sealed class VerifyCodeRequest
|
||||||
|
{
|
||||||
|
public required string Mobile { get; set; }
|
||||||
|
public required string Code { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
namespace GreenHome.Application;
|
||||||
|
|
||||||
|
public sealed class VerifyCodeResponse
|
||||||
|
{
|
||||||
|
public bool Success { get; set; }
|
||||||
|
public string? Message { get; set; }
|
||||||
|
public string? Token { get; set; }
|
||||||
|
public UserDto? User { get; set; }
|
||||||
|
}
|
||||||
79
src/GreenHome.Application/Dtos/Checklist/ChecklistDto.cs
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
namespace GreenHome.Application;
|
||||||
|
|
||||||
|
public sealed class ChecklistDto
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
public int DeviceId { get; set; }
|
||||||
|
public string DeviceName { get; set; } = string.Empty;
|
||||||
|
public string Title { get; set; } = string.Empty;
|
||||||
|
public string? Description { get; set; }
|
||||||
|
public bool IsActive { get; set; }
|
||||||
|
public List<ChecklistItemDto> Items { get; set; } = new();
|
||||||
|
public DateTime CreatedAt { get; set; }
|
||||||
|
public int CreatedByUserId { get; set; }
|
||||||
|
public string CreatedByUserName { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class ChecklistItemDto
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
public string Title { get; set; } = string.Empty;
|
||||||
|
public string? Description { get; set; }
|
||||||
|
public int Order { get; set; }
|
||||||
|
public bool IsRequired { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class CreateChecklistRequest
|
||||||
|
{
|
||||||
|
public required int DeviceId { get; set; }
|
||||||
|
public required int CreatedByUserId { get; set; }
|
||||||
|
public required string Title { get; set; }
|
||||||
|
public string? Description { get; set; }
|
||||||
|
public required List<CreateChecklistItemRequest> Items { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class CreateChecklistItemRequest
|
||||||
|
{
|
||||||
|
public required string Title { get; set; }
|
||||||
|
public string? Description { get; set; }
|
||||||
|
public int Order { get; set; }
|
||||||
|
public bool IsRequired { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class ChecklistCompletionDto
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
public int ChecklistId { get; set; }
|
||||||
|
public string ChecklistTitle { get; set; } = string.Empty;
|
||||||
|
public int CompletedByUserId { get; set; }
|
||||||
|
public string CompletedByUserName { get; set; } = string.Empty;
|
||||||
|
public string PersianDate { get; set; } = string.Empty;
|
||||||
|
public List<ChecklistItemCompletionDto> ItemCompletions { get; set; } = new();
|
||||||
|
public string? Notes { get; set; }
|
||||||
|
public DateTime CompletedAt { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class ChecklistItemCompletionDto
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
public int ChecklistItemId { get; set; }
|
||||||
|
public string ItemTitle { get; set; } = string.Empty;
|
||||||
|
public bool IsChecked { get; set; }
|
||||||
|
public string? Note { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class CompleteChecklistRequest
|
||||||
|
{
|
||||||
|
public required int ChecklistId { get; set; }
|
||||||
|
public required int CompletedByUserId { get; set; }
|
||||||
|
public required string PersianDate { get; set; }
|
||||||
|
public required List<CompleteChecklistItemRequest> ItemCompletions { get; set; }
|
||||||
|
public string? Notes { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class CompleteChecklistItemRequest
|
||||||
|
{
|
||||||
|
public required int ChecklistItemId { get; set; }
|
||||||
|
public bool IsChecked { get; set; }
|
||||||
|
public string? Note { get; set; }
|
||||||
|
}
|
||||||
16
src/GreenHome.Application/Dtos/Common/AlertCheckResult.cs
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
namespace GreenHome.Application;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Result of alert checking, used by TelemetryController.Create to build the line-protocol response
|
||||||
|
/// </summary>
|
||||||
|
public sealed class AlertCheckResult
|
||||||
|
{
|
||||||
|
/// <summary>List of alert messages (condition alerts + power status)</summary>
|
||||||
|
public List<string> Messages { get; set; } = new();
|
||||||
|
|
||||||
|
/// <summary>Comma-separated recipient phone numbers</summary>
|
||||||
|
public string? Recipients { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Power status: "connected", "disconnected", or null if unchanged</summary>
|
||||||
|
public string? PowerStatus { get; set; }
|
||||||
|
}
|
||||||
9
src/GreenHome.Application/Dtos/Common/PagedResult.cs
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
namespace GreenHome.Application;
|
||||||
|
|
||||||
|
public sealed class PagedResult<T>
|
||||||
|
{
|
||||||
|
public required IReadOnlyList<T> Items { get; init; }
|
||||||
|
public required int TotalCount { get; init; }
|
||||||
|
public required int Page { get; init; }
|
||||||
|
public required int PageSize { get; init; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
namespace GreenHome.Application;
|
||||||
|
|
||||||
|
public sealed class DailyReportRequest
|
||||||
|
{
|
||||||
|
public required int DeviceId { get; set; }
|
||||||
|
public required string PersianDate { get; set; } // yyyy/MM/dd
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class WeeklyAnalysisRequest
|
||||||
|
{
|
||||||
|
public required int DeviceId { get; set; }
|
||||||
|
public required string StartDate { get; set; } // yyyy/MM/dd
|
||||||
|
public required string EndDate { get; set; } // yyyy/MM/dd
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class MonthlyAnalysisRequest
|
||||||
|
{
|
||||||
|
public required int DeviceId { get; set; }
|
||||||
|
public required int Year { get; set; }
|
||||||
|
public required int Month { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
namespace GreenHome.Application;
|
||||||
|
|
||||||
|
public sealed class DailyReportResponse
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
public int DeviceId { get; set; }
|
||||||
|
public string DeviceName { get; set; } = string.Empty;
|
||||||
|
public string PersianDate { get; set; } = string.Empty;
|
||||||
|
public string Analysis { get; set; } = string.Empty;
|
||||||
|
public int RecordCount { get; set; }
|
||||||
|
public int SampledRecordCount { get; set; }
|
||||||
|
public int TotalTokens { get; set; }
|
||||||
|
public DateTime CreatedAt { get; set; }
|
||||||
|
public bool FromCache { get; set; }
|
||||||
|
}
|
||||||
13
src/GreenHome.Application/Dtos/Device/DeviceDto.cs
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
namespace GreenHome.Application;
|
||||||
|
|
||||||
|
public sealed class DeviceDto
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
public string DeviceName { get; set; } = string.Empty;
|
||||||
|
public int UserId { get; set; }
|
||||||
|
public string UserName { get; set; } = string.Empty;
|
||||||
|
public string UserFamily { get; set; } = string.Empty;
|
||||||
|
public string UserMobile { get; set; } = string.Empty;
|
||||||
|
public string Location { get; set; } = string.Empty;
|
||||||
|
public string NeshanLocation { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
9
src/GreenHome.Application/Dtos/Device/DeviceFilter.cs
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
namespace GreenHome.Application;
|
||||||
|
|
||||||
|
public sealed class DeviceFilter
|
||||||
|
{
|
||||||
|
public int? UserId { get; set; }
|
||||||
|
public string? Search { get; set; }
|
||||||
|
public int Page { get; set; } = 1;
|
||||||
|
public int PageSize { get; set; } = 10;
|
||||||
|
}
|
||||||
26
src/GreenHome.Application/Dtos/Device/DeviceMemberDto.cs
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
using GreenHome.Domain;
|
||||||
|
|
||||||
|
namespace GreenHome.Application;
|
||||||
|
|
||||||
|
public sealed class DeviceMemberDto
|
||||||
|
{
|
||||||
|
public int DeviceId { get; set; }
|
||||||
|
public int UserId { get; set; }
|
||||||
|
public string Name { get; set; } = string.Empty;
|
||||||
|
public string Family { get; set; } = string.Empty;
|
||||||
|
public string Mobile { get; set; } = string.Empty;
|
||||||
|
public DeviceMemberRole Role { get; set; } = DeviceMemberRole.Worker;
|
||||||
|
public string? AvatarPath { get; set; }
|
||||||
|
public bool ReceiveAlerts { get; set; } = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class UpsertDeviceMemberRequest
|
||||||
|
{
|
||||||
|
public required int DeviceId { get; set; }
|
||||||
|
public required string Mobile { get; set; }
|
||||||
|
public string Name { get; set; } = string.Empty;
|
||||||
|
public string Family { get; set; } = string.Empty;
|
||||||
|
public DeviceMemberRole Role { get; set; } = DeviceMemberRole.Worker;
|
||||||
|
public bool ReceiveAlerts { get; set; } = true;
|
||||||
|
public string? AvatarPath { get; set; }
|
||||||
|
}
|
||||||
63
src/GreenHome.Application/Dtos/Device/DeviceRelayDto.cs
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
using Domain = GreenHome.Domain;
|
||||||
|
|
||||||
|
namespace GreenHome.Application;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// تنظیمات یک رله دستگاه
|
||||||
|
/// </summary>
|
||||||
|
public sealed class DeviceRelayDto
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
public int DeviceSettingsId { get; set; }
|
||||||
|
public int RelayIndex { get; set; }
|
||||||
|
public string Name { get; set; } = string.Empty;
|
||||||
|
public bool IsEnabled { get; set; } = true;
|
||||||
|
public Domain.RelayKind RelayKind { get; set; } = Domain.RelayKind.Generic;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// گروههای شرط رله. گروههای همعمل (روشن یا خاموش) با OR ترکیب میشوند
|
||||||
|
/// و شرایط داخل هر گروه با AND.
|
||||||
|
/// </summary>
|
||||||
|
public List<DeviceRelayRuleGroupDto> RuleGroups { get; set; } = new();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// یک گروه شرط برای روشن یا خاموش شدن رله
|
||||||
|
/// </summary>
|
||||||
|
public sealed class DeviceRelayRuleGroupDto
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
|
||||||
|
/// <summary>اقدام: روشن (On) یا خاموش (Off)</summary>
|
||||||
|
public Domain.RelayAction Action { get; set; } = Domain.RelayAction.On;
|
||||||
|
|
||||||
|
/// <summary>برچسب اختیاری گروه برای لاگ/اعلان</summary>
|
||||||
|
public string? Label { get; set; }
|
||||||
|
|
||||||
|
public int Order { get; set; }
|
||||||
|
|
||||||
|
public List<DeviceRelayRuleConditionDto> Conditions { get; set; } = new();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// یک شرط واحد داخل گروه (سنسوری یا زمانی)
|
||||||
|
/// </summary>
|
||||||
|
public sealed class DeviceRelayRuleConditionDto
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
|
||||||
|
/// <summary>نوع شرط: سنسوری (0) یا زمانی (1)</summary>
|
||||||
|
public Domain.RelayConditionType ConditionType { get; set; } = Domain.RelayConditionType.Sensor;
|
||||||
|
|
||||||
|
// ---- شرط سنسوری ----
|
||||||
|
public Domain.SensorType? SensorType { get; set; }
|
||||||
|
public Domain.ComparisonType? ComparisonType { get; set; }
|
||||||
|
public decimal? Value1 { get; set; }
|
||||||
|
public decimal? Value2 { get; set; }
|
||||||
|
|
||||||
|
// ---- شرط زمانی (دقیقه از نیمهشب) ----
|
||||||
|
public int? StartMinutes { get; set; }
|
||||||
|
public int? EndMinutes { get; set; }
|
||||||
|
|
||||||
|
public int Order { get; set; }
|
||||||
|
}
|
||||||