Compare commits
49 Commits
dca3fc62ca
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| d2dd91929a | |||
| d015e83d6c | |||
| 8ff0b99c71 | |||
| 0e16ac68d3 | |||
| 2038c23ea4 | |||
| 15646fd7c3 | |||
| 38de9d94e2 | |||
| 62a1a0285f | |||
| dfc7aa1d2e | |||
| d0c4550984 | |||
| 25310716fd | |||
| 70320d1959 | |||
| fb31ab4d8d | |||
| 8baa92459e | |||
| c7bbe7f375 | |||
| 413d640724 | |||
| 75d3f4904d | |||
| 77a7e60ab4 | |||
| f60e85c6a8 | |||
| 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 |
3
.gitignore
vendored
@@ -706,6 +706,9 @@ docker-compose.override.yml
|
||||
.env.local
|
||||
.env.*.local
|
||||
|
||||
# Vite / frontend build output
|
||||
dist/
|
||||
|
||||
# OS generated files
|
||||
.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
|
||||
WORKDIR /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
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:9.0 AS runtime
|
||||
WORKDIR /app
|
||||
COPY --from=build /app .
|
||||
RUN mkdir -p /app/My_StaticFiles
|
||||
RUN mkdir -p /app/files
|
||||
ENTRYPOINT ["dotnet", "GreenHome.Api.dll"]
|
||||
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.)
|
||||
@@ -4,6 +4,7 @@
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<NuGetAudit>false</NuGetAudit>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -1,25 +1,32 @@
|
||||
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 IDeepSeekService deepSeekService;
|
||||
private readonly IAIProfileService aiProfileService;
|
||||
private readonly IAIQueryService aiQueryService;
|
||||
private readonly ILogger<AIController> logger;
|
||||
|
||||
public AIController(
|
||||
IDeepSeekService deepSeekService,
|
||||
IAIProfileService aiProfileService,
|
||||
IAIQueryService aiQueryService,
|
||||
ILogger<AIController> logger)
|
||||
{
|
||||
this.deepSeekService = deepSeekService;
|
||||
this.aiProfileService = aiProfileService;
|
||||
this.aiQueryService = aiQueryService;
|
||||
this.logger = logger;
|
||||
}
|
||||
@@ -27,10 +34,8 @@ public class AIController : ControllerBase
|
||||
/// <summary>
|
||||
/// Send a simple question to the AI and get a response
|
||||
/// </summary>
|
||||
/// <param name="request">Question request</param>
|
||||
/// <returns>AI response</returns>
|
||||
[HttpPost("ask")]
|
||||
public async Task<IActionResult> AskQuestion([FromBody] SimpleQuestionRequest request)
|
||||
public async Task<IActionResult> AskQuestion([FromBody] SimpleQuestionRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
var stopwatch = Stopwatch.StartNew();
|
||||
|
||||
@@ -43,7 +48,6 @@ public class AIController : ControllerBase
|
||||
|
||||
logger.LogInformation("Processing AI question: {Question}", request.Question);
|
||||
|
||||
// Build chat request to get token information
|
||||
var messages = new List<ChatMessage>();
|
||||
if (!string.IsNullOrWhiteSpace(request.SystemPrompt))
|
||||
{
|
||||
@@ -51,33 +55,19 @@ public class AIController : ControllerBase
|
||||
}
|
||||
messages.Add(new ChatMessage { Role = "user", Content = request.Question });
|
||||
|
||||
var chatRequest = new ChatRequest { Messages = messages };
|
||||
var chatResponse = await deepSeekService.AskAsync(chatRequest);
|
||||
var result = await aiProfileService.AskAsync(messages, cancellationToken: cancellationToken);
|
||||
|
||||
stopwatch.Stop();
|
||||
|
||||
if (chatResponse == null || chatResponse.Choices == null || !chatResponse.Choices.Any())
|
||||
if (result.Response == null || result.Response.Choices == null || !result.Response.Choices.Any())
|
||||
{
|
||||
return StatusCode(500, new { error = "No response received from AI" });
|
||||
}
|
||||
|
||||
var answer = chatResponse.Choices.FirstOrDefault()?.Message?.Content ?? "";
|
||||
var answer = result.Response.Choices.FirstOrDefault()?.Message?.Content ?? "";
|
||||
|
||||
// Save to database
|
||||
var aiQuery = new AIQuery
|
||||
{
|
||||
Question = request.Question,
|
||||
Answer = answer,
|
||||
DeviceId = request.DeviceId,
|
||||
UserId = request.UserId,
|
||||
Model = chatResponse.Model,
|
||||
PromptTokens = chatResponse.Usage?.PromptTokens ?? 0,
|
||||
CompletionTokens = chatResponse.Usage?.CompletionTokens ?? 0,
|
||||
TotalTokens = chatResponse.Usage?.TotalTokens ?? 0,
|
||||
ResponseTimeMs = stopwatch.ElapsedMilliseconds
|
||||
};
|
||||
|
||||
await aiQueryService.SaveQueryAsync(aiQuery);
|
||||
var aiQuery = BuildQuery(result, request.Question, answer, request.DeviceId, request.UserId, null, stopwatch.ElapsedMilliseconds);
|
||||
await aiQueryService.SaveQueryAsync(aiQuery, cancellationToken);
|
||||
|
||||
return Ok(new
|
||||
{
|
||||
@@ -90,6 +80,8 @@ public class AIController : ControllerBase
|
||||
completion = aiQuery.CompletionTokens,
|
||||
total = aiQuery.TotalTokens
|
||||
},
|
||||
costUsd = aiQuery.CostUsd,
|
||||
profileId = aiQuery.ProfileId,
|
||||
responseTimeMs = aiQuery.ResponseTimeMs,
|
||||
timestamp = DateTime.UtcNow
|
||||
});
|
||||
@@ -104,10 +96,8 @@ public class AIController : ControllerBase
|
||||
/// <summary>
|
||||
/// Send a complex chat request with multiple messages to the AI
|
||||
/// </summary>
|
||||
/// <param name="request">Extended chat request with deviceId</param>
|
||||
/// <returns>AI chat response</returns>
|
||||
[HttpPost("chat")]
|
||||
public async Task<IActionResult> Chat([FromBody] ExtendedChatRequest request)
|
||||
public async Task<IActionResult> Chat([FromBody] ExtendedChatRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
var stopwatch = Stopwatch.StartNew();
|
||||
|
||||
@@ -120,46 +110,41 @@ public class AIController : ControllerBase
|
||||
|
||||
logger.LogInformation("Processing AI chat with {MessageCount} messages", request.Messages.Count);
|
||||
|
||||
var chatRequest = new ChatRequest
|
||||
{
|
||||
Messages = request.Messages,
|
||||
Model = request.Model,
|
||||
Temperature = request.Temperature,
|
||||
MaxTokens = request.MaxTokens
|
||||
};
|
||||
|
||||
var response = await deepSeekService.AskAsync(chatRequest);
|
||||
// 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 (response == null || response.Choices == null || !response.Choices.Any())
|
||||
if (result.Response == null || result.Response.Choices == null || !result.Response.Choices.Any())
|
||||
{
|
||||
return StatusCode(500, new { error = "No response received from AI" });
|
||||
}
|
||||
|
||||
// Extract question and answer
|
||||
var userMessage = request.Messages.LastOrDefault(m => m.Role == "user");
|
||||
var question = userMessage?.Content ?? "Complex chat";
|
||||
var answer = response.Choices.FirstOrDefault()?.Message?.Content ?? "";
|
||||
var answer = result.Response.Choices.FirstOrDefault()?.Message?.Content ?? "";
|
||||
|
||||
// Save to database
|
||||
var aiQuery = new AIQuery
|
||||
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
|
||||
{
|
||||
Question = question,
|
||||
Answer = answer,
|
||||
DeviceId = request.DeviceId,
|
||||
UserId = request.UserId,
|
||||
Model = response.Model,
|
||||
Temperature = request.Temperature,
|
||||
PromptTokens = response.Usage?.PromptTokens ?? 0,
|
||||
CompletionTokens = response.Usage?.CompletionTokens ?? 0,
|
||||
TotalTokens = response.Usage?.TotalTokens ?? 0,
|
||||
ResponseTimeMs = stopwatch.ElapsedMilliseconds
|
||||
};
|
||||
|
||||
await aiQueryService.SaveQueryAsync(aiQuery);
|
||||
|
||||
return Ok(response);
|
||||
response.Id,
|
||||
response.Object,
|
||||
response.Created,
|
||||
response.Model,
|
||||
response.Choices,
|
||||
response.Usage,
|
||||
costUsd = aiQuery.CostUsd,
|
||||
profileId = aiQuery.ProfileId,
|
||||
responseTimeMs = aiQuery.ResponseTimeMs
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -171,10 +156,8 @@ public class AIController : ControllerBase
|
||||
/// <summary>
|
||||
/// Get suggestions for smart home automation based on device data
|
||||
/// </summary>
|
||||
/// <param name="request">Device context request</param>
|
||||
/// <returns>AI suggestions</returns>
|
||||
[HttpPost("suggest")]
|
||||
public async Task<IActionResult> GetSuggestions([FromBody] SuggestionRequest request)
|
||||
public async Task<IActionResult> GetSuggestions([FromBody] SuggestionRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
var stopwatch = Stopwatch.StartNew();
|
||||
|
||||
@@ -193,33 +176,19 @@ public class AIController : ControllerBase
|
||||
new ChatMessage { Role = "user", Content = question }
|
||||
};
|
||||
|
||||
var chatRequest = new ChatRequest { Messages = messages };
|
||||
var chatResponse = await deepSeekService.AskAsync(chatRequest);
|
||||
var result = await aiProfileService.AskAsync(messages, cancellationToken: cancellationToken);
|
||||
|
||||
stopwatch.Stop();
|
||||
|
||||
if (chatResponse == null || chatResponse.Choices == null || !chatResponse.Choices.Any())
|
||||
if (result.Response == null || result.Response.Choices == null || !result.Response.Choices.Any())
|
||||
{
|
||||
return StatusCode(500, new { error = "No suggestions received from AI" });
|
||||
}
|
||||
|
||||
var answer = chatResponse.Choices.FirstOrDefault()?.Message?.Content ?? "";
|
||||
var answer = result.Response.Choices.FirstOrDefault()?.Message?.Content ?? "";
|
||||
|
||||
// Save to database
|
||||
var aiQuery = new AIQuery
|
||||
{
|
||||
Question = question,
|
||||
Answer = answer,
|
||||
DeviceId = request.DeviceId,
|
||||
UserId = request.UserId,
|
||||
Model = chatResponse.Model,
|
||||
PromptTokens = chatResponse.Usage?.PromptTokens ?? 0,
|
||||
CompletionTokens = chatResponse.Usage?.CompletionTokens ?? 0,
|
||||
TotalTokens = chatResponse.Usage?.TotalTokens ?? 0,
|
||||
ResponseTimeMs = stopwatch.ElapsedMilliseconds
|
||||
};
|
||||
|
||||
await aiQueryService.SaveQueryAsync(aiQuery);
|
||||
var aiQuery = BuildQuery(result, question, answer, request.DeviceId, request.UserId, null, stopwatch.ElapsedMilliseconds);
|
||||
await aiQueryService.SaveQueryAsync(aiQuery, cancellationToken);
|
||||
|
||||
return Ok(new
|
||||
{
|
||||
@@ -231,6 +200,8 @@ public class AIController : ControllerBase
|
||||
completion = aiQuery.CompletionTokens,
|
||||
total = aiQuery.TotalTokens
|
||||
},
|
||||
costUsd = aiQuery.CostUsd,
|
||||
profileId = aiQuery.ProfileId,
|
||||
responseTimeMs = aiQuery.ResponseTimeMs,
|
||||
timestamp = DateTime.UtcNow
|
||||
});
|
||||
@@ -246,12 +217,12 @@ public class AIController : ControllerBase
|
||||
/// Get AI query history for a device
|
||||
/// </summary>
|
||||
[HttpGet("history/device/{deviceId}")]
|
||||
public async Task<IActionResult> GetDeviceHistory(int deviceId, [FromQuery] int take = 50)
|
||||
public async Task<IActionResult> GetDeviceHistory(int deviceId, [FromQuery] int take = 50, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
var queries = await aiQueryService.GetDeviceQueriesAsync(deviceId, take);
|
||||
var totalTokens = await aiQueryService.GetDeviceTotalTokensAsync(deviceId);
|
||||
var queries = await aiQueryService.GetDeviceQueriesAsync(deviceId, take, cancellationToken);
|
||||
var totalTokens = await aiQueryService.GetDeviceTotalTokensAsync(deviceId, cancellationToken);
|
||||
|
||||
return Ok(new
|
||||
{
|
||||
@@ -263,7 +234,9 @@ public class AIController : ControllerBase
|
||||
q.TotalTokens,
|
||||
q.PromptTokens,
|
||||
q.CompletionTokens,
|
||||
q.CostUsd,
|
||||
q.Model,
|
||||
q.ProfileId,
|
||||
q.ResponseTimeMs,
|
||||
q.CreatedAt
|
||||
}),
|
||||
@@ -281,11 +254,11 @@ public class AIController : ControllerBase
|
||||
/// Get AI query statistics
|
||||
/// </summary>
|
||||
[HttpGet("stats")]
|
||||
public async Task<IActionResult> GetStats()
|
||||
public async Task<IActionResult> GetStats(CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var stats = await aiQueryService.GetStatsAsync();
|
||||
var stats = await aiQueryService.GetStatsAsync(cancellationToken);
|
||||
return Ok(stats);
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -294,6 +267,42 @@ public class AIController : ControllerBase
|
||||
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>
|
||||
@@ -301,24 +310,9 @@ public class AIController : ControllerBase
|
||||
/// </summary>
|
||||
public class SimpleQuestionRequest
|
||||
{
|
||||
/// <summary>
|
||||
/// The question to ask the AI
|
||||
/// </summary>
|
||||
public required string Question { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Optional system prompt to set context for the AI
|
||||
/// </summary>
|
||||
public string? SystemPrompt { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Optional device ID to associate with this query
|
||||
/// </summary>
|
||||
public int? DeviceId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Optional user ID to associate with this query
|
||||
/// </summary>
|
||||
public int? UserId { get; set; }
|
||||
}
|
||||
|
||||
@@ -328,7 +322,7 @@ public class SimpleQuestionRequest
|
||||
public class ExtendedChatRequest
|
||||
{
|
||||
public required List<ChatMessage> Messages { get; set; }
|
||||
public string Model { get; set; } = "deepseek-chat";
|
||||
public string? Model { get; set; }
|
||||
public double? Temperature { get; set; }
|
||||
public int? MaxTokens { get; set; }
|
||||
public int? DeviceId { get; set; }
|
||||
@@ -340,19 +334,7 @@ public class ExtendedChatRequest
|
||||
/// </summary>
|
||||
public class SuggestionRequest
|
||||
{
|
||||
/// <summary>
|
||||
/// Context about devices and their current state
|
||||
/// </summary>
|
||||
public required string DeviceContext { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Device ID for this suggestion request
|
||||
/// </summary>
|
||||
public int? DeviceId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// User ID for this suggestion request
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -52,5 +52,23 @@ public class AuthController : ControllerBase
|
||||
var canResend = await authService.CanResendCodeAsync(mobile, cancellationToken);
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
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 = "خطا در آپلود آواتار" });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -208,5 +208,85 @@ public class DevicePostsController : ControllerBase
|
||||
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 = "خطا در آپلود ویس" });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,13 +8,16 @@ namespace GreenHome.Api.Controllers;
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -56,5 +59,196 @@ public class PowerOutageController : ControllerBase
|
||||
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 GreenHome.Application;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace GreenHome.Api.Controllers;
|
||||
|
||||
@@ -19,9 +22,9 @@ public class TelemetryController : ControllerBase
|
||||
}
|
||||
|
||||
[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);
|
||||
return Ok(result);
|
||||
}
|
||||
@@ -29,38 +32,115 @@ public class TelemetryController : ControllerBase
|
||||
[HttpGet("AddData")]
|
||||
public async Task<ActionResult<string>> Create([FromQuery] TelemetryDto telementry, [FromQuery] string? lastUpdateDate, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
telementry.TimestampUtc = DateTime.UtcNow;
|
||||
telementry.RelayStates = ParseRelayStates(Request.Query);
|
||||
var id = await telemetryService.AddAsync(telementry, cancellationToken);
|
||||
|
||||
string? message;
|
||||
|
||||
var parts = new List<string> { $"ID:{id}" };
|
||||
var deviceId = telementry.DeviceId;
|
||||
|
||||
if (deviceId > 0)
|
||||
{
|
||||
message = await alertService.CheckAndSendAlertsAsync(deviceId, telementry, cancellationToken);
|
||||
if(!string.IsNullOrEmpty(message))
|
||||
// 1. Check alerts and power status
|
||||
var alertResult = await alertService.CheckAndSendAlertsAsync(deviceId, telementry, cancellationToken);
|
||||
if (alertResult != null)
|
||||
{
|
||||
return Ok(message);
|
||||
if (alertResult.Messages.Count > 0)
|
||||
{
|
||||
parts.Add($"A:{alertResult.Messages.Count}");
|
||||
parts.Add($"R:{alertResult.Recipients}");
|
||||
parts.Add($"M:{string.Join("@", alertResult.Messages)}");
|
||||
}
|
||||
|
||||
if (alertResult.PowerStatus != null)
|
||||
{
|
||||
parts.Add($"P:{alertResult.PowerStatus}");
|
||||
}
|
||||
}
|
||||
|
||||
// Check if relay conditions have been updated since lastUpdateDate
|
||||
if (deviceId > 0 && !string.IsNullOrEmpty(lastUpdateDate))
|
||||
// 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)
|
||||
// {
|
||||
// return Ok(new { conditions = relayConditions });
|
||||
// }
|
||||
|
||||
var hasUpdates = await alertConditionService.HasUpdatedConditionsAsync(deviceId, parsedDate, cancellationToken);
|
||||
if(hasUpdates)
|
||||
return Ok("Relay");
|
||||
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(id + "");
|
||||
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>
|
||||
@@ -106,4 +186,11 @@ public class TelemetryController : ControllerBase
|
||||
var result = await telemetryService.GetActiveMonthsAsync(deviceId, year, cancellationToken);
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,26 @@
|
||||
# مرحله build
|
||||
# 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
|
||||
WORKDIR /src
|
||||
COPY . .
|
||||
RUN dotnet restore
|
||||
RUN dotnet publish -c Release -o /app
|
||||
|
||||
# مرحله runtime
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS runtime
|
||||
COPY ./src/ .
|
||||
|
||||
# Copy built frontend from previous stage
|
||||
COPY --from=frontend-build /app/dist /src/GreenHome.Api/wwwroot/
|
||||
|
||||
RUN dotnet restore GreenHome.Api/GreenHome.Api.csproj
|
||||
RUN dotnet publish GreenHome.Api/GreenHome.Api.csproj -c Release -o /app
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:9.0 AS runtime
|
||||
WORKDIR /app
|
||||
COPY --from=build /app .
|
||||
EXPOSE 8080
|
||||
RUN mkdir -p /app/My_StaticFiles
|
||||
RUN mkdir -p /app/files
|
||||
ENTRYPOINT ["dotnet", "GreenHome.Api.dll"]
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -4,9 +4,11 @@
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<NuGetAudit>false</NuGetAudit>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="5.1.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.0" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.9">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
|
||||
@@ -1,33 +1,86 @@
|
||||
using FluentValidation;
|
||||
using GreenHome.AI.DeepSeek;
|
||||
using Microsoft.AspNetCore.Mvc.Versioning;
|
||||
using GreenHome.Application;
|
||||
using GreenHome.Infrastructure;
|
||||
using GreenHome.Infrastructure.Data;
|
||||
using GreenHome.Sms.Ippanel;
|
||||
using GreenHome.VoiceCall.Avanak;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.StaticFiles;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.FileProviders;
|
||||
using Scalar.AspNetCore;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// Add services to the container.
|
||||
builder.Services.AddControllers();
|
||||
// ============================================================
|
||||
// 1. Service Registration
|
||||
// ============================================================
|
||||
|
||||
ConfigureCoreServices(builder);
|
||||
ConfigureCors(builder);
|
||||
ConfigureExternalServices(builder);
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// ============================================================
|
||||
// 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();
|
||||
|
||||
// Application/Infrastructure DI
|
||||
// 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>();
|
||||
|
||||
// CORS Configuration
|
||||
// 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 =>
|
||||
{
|
||||
if (builder.Environment.IsDevelopment())
|
||||
{
|
||||
// در محیط Development همه origin ها مجاز هستند
|
||||
policy
|
||||
.AllowAnyOrigin()
|
||||
.AllowAnyHeader()
|
||||
@@ -35,7 +88,6 @@ builder.Services.AddCors(options =>
|
||||
}
|
||||
else
|
||||
{
|
||||
// در محیط Production فقط دامنههای مشخص
|
||||
policy
|
||||
.WithOrigins(
|
||||
"http://green.nabaksoft.ir",
|
||||
@@ -49,47 +101,41 @@ builder.Services.AddCors(options =>
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
builder.Services.AddDbContext<GreenHome.Infrastructure.GreenHomeDbContext>(options =>
|
||||
void ConfigureExternalServices(WebApplicationBuilder builder)
|
||||
{
|
||||
options.UseSqlServer(builder.Configuration.GetConnectionString("Default"));
|
||||
});
|
||||
builder.Services.AddScoped<GreenHome.Application.IDeviceService, GreenHome.Infrastructure.DeviceService>();
|
||||
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>();
|
||||
builder.Services.AddScoped<GreenHome.Application.IAlertConditionService, GreenHome.Infrastructure.AlertConditionService>();
|
||||
builder.Services.AddScoped<GreenHome.Application.ISunCalculatorService, GreenHome.Infrastructure.SunCalculatorService>();
|
||||
builder.Services.AddScoped<GreenHome.Application.IAIQueryService, GreenHome.Infrastructure.AIQueryService>();
|
||||
builder.Services.AddScoped<GreenHome.Application.IDailyReportService, GreenHome.Infrastructure.DailyReportService>();
|
||||
builder.Services.AddScoped<GreenHome.Application.IAlertLogService, GreenHome.Infrastructure.AlertLogService>();
|
||||
builder.Services.AddScoped<GreenHome.Application.IUserDailyReportService, GreenHome.Infrastructure.UserDailyReportService>();
|
||||
builder.Services.AddScoped<GreenHome.Application.IChecklistService, GreenHome.Infrastructure.ChecklistService>();
|
||||
builder.Services.AddScoped<GreenHome.Application.IMonthlyReportService, GreenHome.Infrastructure.MonthlyReportService>();
|
||||
builder.Services.AddScoped<GreenHome.Application.IDevicePostService, GreenHome.Infrastructure.DevicePostService>();
|
||||
builder.Services.AddScoped<GreenHome.Application.IDeviceTokenService, GreenHome.Infrastructure.DeviceTokenService>();
|
||||
|
||||
// SMS Service Configuration
|
||||
builder.Services.AddIppanelSms(builder.Configuration);
|
||||
|
||||
// Voice Call Service Configuration
|
||||
builder.Services.AddAvanakVoiceCall(builder.Configuration);
|
||||
|
||||
// AI Service Configuration
|
||||
builder.Services.AddDeepSeek(builder.Configuration);
|
||||
}
|
||||
|
||||
var app = builder.Build();
|
||||
// ============================================================
|
||||
// Middleware & Pipeline Methods
|
||||
// ============================================================
|
||||
|
||||
// Apply pending migrations automatically
|
||||
using (var scope = app.Services.CreateScope())
|
||||
void ApplyMigrations(WebApplication app)
|
||||
{
|
||||
using var scope = app.Services.CreateScope();
|
||||
var services = scope.ServiceProvider;
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var logger = services.GetRequiredService<ILogger<Program>>();
|
||||
@@ -97,28 +143,45 @@ using (var scope = app.Services.CreateScope())
|
||||
}
|
||||
}
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
void ConfigureMiddleware(WebApplication app)
|
||||
{
|
||||
app.MapOpenApi();
|
||||
app.MapScalarApiReference();
|
||||
|
||||
if (!app.Environment.IsDevelopment())
|
||||
{
|
||||
app.UseHttpsRedirection();
|
||||
}
|
||||
|
||||
app.UseCors(CorsPolicy);
|
||||
app.UseCors("DefaultCors");
|
||||
app.UseAuthorization();
|
||||
}
|
||||
|
||||
void ConfigureStaticFiles(WebApplication app)
|
||||
{
|
||||
var provider = new FileExtensionContentTypeProvider();
|
||||
provider.Mappings[".amr"] = "audio/amr";
|
||||
provider.Mappings[".apk"] = "application/vnd.android.package-archive";
|
||||
|
||||
// Serve existing My_StaticFiles folder
|
||||
app.UseStaticFiles(new StaticFileOptions
|
||||
{
|
||||
FileProvider = new PhysicalFileProvider(
|
||||
Path.Combine(builder.Environment.ContentRootPath, "My_StaticFiles")),
|
||||
Path.Combine(app.Environment.ContentRootPath, "My_StaticFiles")),
|
||||
RequestPath = "/My_StaticFiles",
|
||||
ContentTypeProvider = provider
|
||||
});
|
||||
|
||||
app.MapControllers();
|
||||
// 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.Run();
|
||||
// Serve the SPA from wwwroot (Vite build output)
|
||||
app.UseDefaultFiles();
|
||||
app.UseStaticFiles();
|
||||
}
|
||||
|
||||
@@ -5,8 +5,12 @@
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"Database": {
|
||||
"Provider": "Postgres"
|
||||
},
|
||||
"ConnectionStrings": {
|
||||
"Default": "Server=87.107.108.119;TrustServerCertificate=True;Database=GreenHomeDb;User Id=sa;Password=qwER12#$110"
|
||||
"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"
|
||||
|
||||
@@ -18,5 +18,13 @@
|
||||
"DefaultTemperature": 1.0
|
||||
},
|
||||
|
||||
"Auth": {
|
||||
"TokenSecret": "CHANGE_ME_USE_A_STRONG_RANDOM_SECRET_AT_LEAST_32_CHARS"
|
||||
},
|
||||
|
||||
"Admin": {
|
||||
"OnlineWindowMinutes": 15
|
||||
},
|
||||
|
||||
"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,409 +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? Voltage { get; set; }
|
||||
public decimal? BatteryVoltage { get; set; }
|
||||
public decimal? BatteryPercent { get; set; }
|
||||
public byte? Power { get; set; }
|
||||
public byte? OldPower { 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 DateTime? ServerTimestampUtc { get; set; }
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
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; } = 15;
|
||||
public int MinimumCallIntervalMinutes { get; set; } = 60;
|
||||
public decimal? AreaSquareMeters { get; set; }
|
||||
|
||||
public int UploadIntervalMin { get; set; } = 5;
|
||||
public string DevicePhoneNumber { get; set; } = string.Empty;
|
||||
public Domain.SimCardType? SimCardType { get; set; }
|
||||
public int RelayCount { get; set; } = 4;
|
||||
public string SmsRecievers { get; set; } = string.Empty;
|
||||
public string? TokenCode { get; set; }
|
||||
public string? VerificationCode { get; set; }
|
||||
public DateTime? TokenExpiresAt { get; set; }
|
||||
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public DateTime UpdatedAt { get; set; }
|
||||
}
|
||||
|
||||
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; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DTO for relay alert conditions (notificationType > 0)
|
||||
/// </summary>
|
||||
public sealed class RelayConditionDto
|
||||
{
|
||||
public int Enabled { get; set; }
|
||||
public int TimeType { get; set; }
|
||||
public string Relay { get; set; } = string.Empty;
|
||||
public List<RelayRuleDto> Rules { get; set; } = new();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DTO for relay condition rules
|
||||
/// </summary>
|
||||
public sealed class RelayRuleDto
|
||||
{
|
||||
public string Sensor { get; set; } = string.Empty;
|
||||
public string Op { get; set; } = string.Empty;
|
||||
public decimal V1 { get; set; }
|
||||
public decimal? V2 { get; set; }
|
||||
}
|
||||
|
||||
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; }
|
||||
}
|
||||
|
||||
public sealed class DailyReportRequest
|
||||
{
|
||||
public required int DeviceId { get; set; }
|
||||
public required string PersianDate { get; set; } // yyyy/MM/dd
|
||||
}
|
||||
|
||||
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; }
|
||||
}
|
||||
|
||||
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; }
|
||||
}
|
||||
|
||||
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; }
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
public sealed class UserDailyReportDto
|
||||
{
|
||||
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 UserFamily { get; set; } = string.Empty;
|
||||
public string PersianDate { get; set; } = string.Empty;
|
||||
public string Title { get; set; } = string.Empty;
|
||||
public string Observations { get; set; } = string.Empty;
|
||||
public string Operations { get; set; } = string.Empty;
|
||||
public string? Notes { get; set; }
|
||||
public List<ReportImageDto> Images { get; set; } = new();
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public DateTime UpdatedAt { get; set; }
|
||||
}
|
||||
|
||||
public sealed class ReportImageDto
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string FileName { get; set; } = string.Empty;
|
||||
public string FilePath { get; set; } = string.Empty;
|
||||
public string ContentType { get; set; } = string.Empty;
|
||||
public long FileSize { get; set; }
|
||||
public string? Description { get; set; }
|
||||
public DateTime UploadedAt { get; set; }
|
||||
}
|
||||
|
||||
public sealed class CreateUserDailyReportRequest
|
||||
{
|
||||
public required int DeviceId { get; set; }
|
||||
public required int UserId { get; set; }
|
||||
public required string PersianDate { get; set; }
|
||||
public required string Title { get; set; }
|
||||
public required string Observations { get; set; }
|
||||
public required string Operations { get; set; }
|
||||
public string? Notes { get; set; }
|
||||
}
|
||||
|
||||
public sealed class UpdateUserDailyReportRequest
|
||||
{
|
||||
public required int Id { get; set; }
|
||||
public required string Title { get; set; }
|
||||
public required string Observations { get; set; }
|
||||
public required string Operations { get; set; }
|
||||
public string? Notes { get; set; }
|
||||
}
|
||||
|
||||
public sealed class UserDailyReportFilter
|
||||
{
|
||||
public int? DeviceId { get; set; }
|
||||
public int? UserId { get; set; }
|
||||
public string? PersianDate { get; set; }
|
||||
public int? Year { get; set; }
|
||||
public int? Month { get; set; }
|
||||
public int Page { get; set; } = 1;
|
||||
public int PageSize { get; set; } = 20;
|
||||
}
|
||||
|
||||
// DTOs برای مدیریت توکن دستگاه
|
||||
|
||||
/// <summary>
|
||||
/// درخواست دریافت فاصله زمانی آپلود
|
||||
/// </summary>
|
||||
public sealed class GetUploadIntervalRequest
|
||||
{
|
||||
public int? DeviceId { get; set; }
|
||||
public string? DevicePhoneNumber { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// پاسخ دریافت فاصله زمانی آپلود
|
||||
/// </summary>
|
||||
public sealed class GetUploadIntervalResponse
|
||||
{
|
||||
public bool Success { get; set; }
|
||||
public string? Message { get; set; }
|
||||
public int? UploadIntervalMin { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// درخواست دریافت توکن دستگاه
|
||||
/// </summary>
|
||||
public sealed class RequestDeviceTokenRequest
|
||||
{
|
||||
public required string DevicePhoneNumber { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// پاسخ دریافت توکن دستگاه
|
||||
/// </summary>
|
||||
public sealed class RequestDeviceTokenResponse
|
||||
{
|
||||
public bool Success { get; set; }
|
||||
public string? Message { get; set; }
|
||||
public string? TokenCode { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// درخواست تایید توکن دستگاه
|
||||
/// </summary>
|
||||
public sealed class VerifyDeviceTokenRequest
|
||||
{
|
||||
public required string DevicePhoneNumber { get; set; }
|
||||
public required string VerificationCode { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// پاسخ تایید توکن دستگاه
|
||||
/// </summary>
|
||||
public sealed class VerifyDeviceTokenResponse
|
||||
{
|
||||
public bool Success { get; set; }
|
||||
public string? Message { get; set; }
|
||||
public string? EncodedSettings { 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; }
|
||||
}
|
||||
@@ -77,4 +77,3 @@ public sealed class CompleteChecklistItemRequest
|
||||
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; }
|
||||
}
|
||||
32
src/GreenHome.Application/Dtos/Device/DeviceSettingsDto.cs
Normal file
@@ -0,0 +1,32 @@
|
||||
namespace GreenHome.Application;
|
||||
|
||||
public sealed class DeviceSettingsDto
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public int DeviceId { get; set; }
|
||||
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; } = 15;
|
||||
public int MinimumCallIntervalMinutes { get; set; } = 60;
|
||||
public decimal? AreaSquareMeters { get; set; }
|
||||
|
||||
public int UploadIntervalMin { get; set; } = 5;
|
||||
public string DevicePhoneNumber { get; set; } = string.Empty;
|
||||
public Domain.SimCardType? SimCardType { get; set; }
|
||||
public int RelayCount { get; set; } = 4;
|
||||
public string SmsRecievers { get; set; } = string.Empty;
|
||||
public string? TokenCode { get; set; }
|
||||
public string? VerificationCode { get; set; }
|
||||
public DateTime? TokenExpiresAt { get; set; }
|
||||
|
||||
public List<DeviceRelayDto> Relays { get; set; } = new();
|
||||
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public DateTime UpdatedAt { get; set; }
|
||||
}
|
||||
@@ -7,7 +7,12 @@ public sealed class DevicePostDto
|
||||
public int AuthorUserId { get; set; }
|
||||
public string AuthorName { get; set; } = string.Empty;
|
||||
public string AuthorFamily { get; set; } = string.Empty;
|
||||
public string? AuthorAvatar { get; set; }
|
||||
public Domain.DeviceMemberRole? AuthorRole { get; set; }
|
||||
public string Content { get; set; } = string.Empty;
|
||||
public Domain.DevicePostType PostType { get; set; } = Domain.DevicePostType.Text;
|
||||
public string? VoiceFilePath { get; set; }
|
||||
public int? VoiceDurationSeconds { get; set; }
|
||||
public List<DevicePostImageDto> Images { get; set; } = new();
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public DateTime? UpdatedAt { get; set; }
|
||||
@@ -44,3 +49,8 @@ public sealed class DevicePostFilter
|
||||
public int PageSize { get; set; } = 20;
|
||||
}
|
||||
|
||||
public sealed class CreateSensorSnapshotRequest
|
||||
{
|
||||
public required int DeviceId { get; set; }
|
||||
public required int AuthorUserId { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
namespace GreenHome.Application;
|
||||
|
||||
/// <summary>
|
||||
/// درخواست دریافت فاصله زمانی آپلود
|
||||
/// </summary>
|
||||
public sealed class GetUploadIntervalRequest
|
||||
{
|
||||
public int? DeviceId { get; set; }
|
||||
public string? DevicePhoneNumber { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// پاسخ دریافت فاصله زمانی آپلود
|
||||
/// </summary>
|
||||
public sealed class GetUploadIntervalResponse
|
||||
{
|
||||
public bool Success { get; set; }
|
||||
public string? Message { get; set; }
|
||||
public int? UploadIntervalMin { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
namespace GreenHome.Application;
|
||||
|
||||
/// <summary>
|
||||
/// درخواست دریافت توکن دستگاه
|
||||
/// </summary>
|
||||
public sealed class RequestDeviceTokenRequest
|
||||
{
|
||||
public required string DevicePhoneNumber { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// پاسخ دریافت توکن دستگاه
|
||||
/// </summary>
|
||||
public sealed class RequestDeviceTokenResponse
|
||||
{
|
||||
public bool Success { get; set; }
|
||||
public string? Message { get; set; }
|
||||
public string? TokenCode { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
namespace GreenHome.Application;
|
||||
|
||||
/// <summary>
|
||||
/// درخواست تایید توکن دستگاه
|
||||
/// </summary>
|
||||
public sealed class VerifyDeviceTokenRequest
|
||||
{
|
||||
public required string DevicePhoneNumber { get; set; }
|
||||
public required string VerificationCode { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// پاسخ تایید توکن دستگاه
|
||||
/// </summary>
|
||||
public sealed class VerifyDeviceTokenResponse
|
||||
{
|
||||
public bool Success { get; set; }
|
||||
public string? Message { get; set; }
|
||||
public string? EncodedSettings { get; set; }
|
||||
}
|
||||
@@ -1,10 +1,5 @@
|
||||
namespace GreenHome.Application;
|
||||
|
||||
public interface IMonthlyReportService
|
||||
{
|
||||
Task<MonthlyReportDto> GetMonthlyReportAsync(int deviceId, int year, int month, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
public sealed class MonthlyReportDto
|
||||
{
|
||||
public int DeviceId { get; set; }
|
||||
@@ -42,4 +37,3 @@ public sealed class MonthlyReportDto
|
||||
|
||||
public DateTime GeneratedAt { get; set; }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
namespace GreenHome.Application;
|
||||
|
||||
public sealed class PowerOutageLogDto
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public int DeviceId { get; set; }
|
||||
public string DeviceName { get; set; } = string.Empty;
|
||||
public byte PreviousPower { get; set; }
|
||||
public byte CurrentPower { get; set; }
|
||||
public string EventType { get; set; } = string.Empty; // "Connected" or "Disconnected"
|
||||
public string EventTypePersian { get; set; } = string.Empty; // "وصل" or "قطع"
|
||||
public DateTime TimestampUtc { get; set; }
|
||||
public DateTime ServerTimestampUtc { get; set; }
|
||||
public string PersianDate { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
public sealed class PowerOutageFilter
|
||||
{
|
||||
public int? EventType { get; set; } // 1 = Connected, 2 = Disconnected
|
||||
public DateTime? StartDateUtc { get; set; }
|
||||
public DateTime? EndDateUtc { get; set; }
|
||||
public int? PersianYear { get; set; }
|
||||
public int? PersianMonth { get; set; }
|
||||
public int Page { get; set; } = 1;
|
||||
public int PageSize { get; set; } = 20;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
namespace GreenHome.Application;
|
||||
|
||||
/// <summary>
|
||||
/// خلاصه قطعیهای برق یک دستگاه در یک بازه زمانی
|
||||
/// </summary>
|
||||
public sealed class PowerOutageSummaryDto
|
||||
{
|
||||
public int DeviceId { get; set; }
|
||||
public int TotalOutageCount { get; set; }
|
||||
public long TotalDowntimeSeconds { get; set; }
|
||||
public DateTime? StartDateUtc { get; set; }
|
||||
public DateTime? EndDateUtc { get; set; }
|
||||
public List<PowerOutagePairDto> Outages { get; set; } = new();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// یک جفت قطع و وصل برق (مدت زمان قطعی)
|
||||
/// </summary>
|
||||
public sealed class PowerOutagePairDto
|
||||
{
|
||||
public DateTime DisconnectedAt { get; set; }
|
||||
public DateTime? ConnectedAt { get; set; }
|
||||
public long? DurationSeconds { get; set; }
|
||||
}
|
||||
7
src/GreenHome.Application/Dtos/Telemetry/DayCount.cs
Normal file
@@ -0,0 +1,7 @@
|
||||
namespace GreenHome.Application;
|
||||
|
||||
public sealed class DayCount
|
||||
{
|
||||
public string PersianDate { get; set; } = string.Empty;
|
||||
public int Count { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
namespace GreenHome.Application;
|
||||
|
||||
public sealed class TelemetryBucketDto
|
||||
{
|
||||
public DateTime BucketStart { get; set; }
|
||||
public decimal MinTemperatureC { get; set; }
|
||||
public decimal MaxTemperatureC { get; set; }
|
||||
public decimal AvgTemperatureC { get; set; }
|
||||
public decimal MinHumidityPercent { get; set; }
|
||||
public decimal MaxHumidityPercent { get; set; }
|
||||
public decimal AvgHumidityPercent { get; set; }
|
||||
public decimal MinSoilPercent { get; set; }
|
||||
public decimal MaxSoilPercent { get; set; }
|
||||
public decimal AvgSoilPercent { get; set; }
|
||||
public int MinGasPPM { get; set; }
|
||||
public int MaxGasPPM { get; set; }
|
||||
public decimal AvgGasPPM { get; set; }
|
||||
public decimal MinLux { get; set; }
|
||||
public decimal MaxLux { get; set; }
|
||||
public decimal AvgLux { get; set; }
|
||||
public int Count { get; set; }
|
||||
}
|
||||
24
src/GreenHome.Application/Dtos/Telemetry/TelemetryDto.cs
Normal file
@@ -0,0 +1,24 @@
|
||||
namespace GreenHome.Application;
|
||||
|
||||
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? Voltage { get; set; }
|
||||
public decimal? BatteryVoltage { get; set; }
|
||||
public decimal? BatteryPercent { get; set; }
|
||||
public byte? Power { get; set; }
|
||||
public byte? OldPower { get; set; }
|
||||
public string? RelayStates { 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 DateTime? ServerTimestampUtc { get; set; }
|
||||
}
|
||||
11
src/GreenHome.Application/Dtos/Telemetry/TelemetryFilter.cs
Normal file
@@ -0,0 +1,11 @@
|
||||
namespace GreenHome.Application;
|
||||
|
||||
public sealed class TelemetryFilter
|
||||
{
|
||||
public int? DeviceId { get; set; }
|
||||
public DateTime? StartDateUtc { get; set; }
|
||||
public DateTime? EndDateUtc { get; set; }
|
||||
public DateTime? SinceUtc { get; set; }
|
||||
public int Page { get; set; } = 1;
|
||||
public int PageSize { get; set; } = 20;
|
||||
}
|
||||
21
src/GreenHome.Application/Dtos/Telemetry/TelemetryMinMax.cs
Normal file
@@ -0,0 +1,21 @@
|
||||
namespace GreenHome.Application;
|
||||
|
||||
public sealed class TelemetryMinMax
|
||||
{
|
||||
public decimal MinTemperatureC { get; set; }
|
||||
public decimal MaxTemperatureC { get; set; }
|
||||
public decimal AvgTemperatureC { get; set; }
|
||||
public decimal MinHumidityPercent { get; set; }
|
||||
public decimal MaxHumidityPercent { get; set; }
|
||||
public decimal AvgHumidityPercent { get; set; }
|
||||
public decimal MinSoilPercent { get; set; }
|
||||
public decimal MaxSoilPercent { get; set; }
|
||||
public decimal AvgSoilPercent { get; set; }
|
||||
public int MinGasPPM { get; set; }
|
||||
public int MaxGasPPM { get; set; }
|
||||
public decimal AvgGasPPM { get; set; }
|
||||
public decimal MinLux { get; set; }
|
||||
public decimal MaxLux { get; set; }
|
||||
public decimal AvgLux { get; set; }
|
||||
public int Count { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
namespace GreenHome.Application;
|
||||
|
||||
public sealed class CreateUserDailyReportRequest
|
||||
{
|
||||
public required int DeviceId { get; set; }
|
||||
public required int UserId { get; set; }
|
||||
public required string PersianDate { get; set; }
|
||||
public required string Title { get; set; }
|
||||
public required string Observations { get; set; }
|
||||
public required string Operations { get; set; }
|
||||
public string? Notes { get; set; }
|
||||
}
|
||||
|
||||
public sealed class UpdateUserDailyReportRequest
|
||||
{
|
||||
public required int Id { get; set; }
|
||||
public required string Title { get; set; }
|
||||
public required string Observations { get; set; }
|
||||
public required string Operations { get; set; }
|
||||
public string? Notes { get; set; }
|
||||
}
|
||||
|
||||
public sealed class UserDailyReportFilter
|
||||
{
|
||||
public int? DeviceId { get; set; }
|
||||
public int? UserId { get; set; }
|
||||
public string? PersianDate { get; set; }
|
||||
public int? Year { get; set; }
|
||||
public int? Month { get; set; }
|
||||
public int Page { get; set; } = 1;
|
||||
public int PageSize { get; set; } = 20;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
namespace GreenHome.Application;
|
||||
|
||||
public sealed class UserDailyReportDto
|
||||
{
|
||||
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 UserFamily { get; set; } = string.Empty;
|
||||
public string PersianDate { get; set; } = string.Empty;
|
||||
public string Title { get; set; } = string.Empty;
|
||||
public string Observations { get; set; } = string.Empty;
|
||||
public string Operations { get; set; } = string.Empty;
|
||||
public string? Notes { get; set; }
|
||||
public List<ReportImageDto> Images { get; set; } = new();
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public DateTime UpdatedAt { get; set; }
|
||||
}
|
||||
|
||||
public sealed class ReportImageDto
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string FileName { get; set; } = string.Empty;
|
||||
public string FilePath { get; set; } = string.Empty;
|
||||
public string ContentType { get; set; } = string.Empty;
|
||||
public long FileSize { get; set; }
|
||||
public string? Description { get; set; }
|
||||
public DateTime UploadedAt { get; set; }
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<NuGetAudit>false</NuGetAudit>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -33,27 +33,7 @@ public interface IAIQueryService
|
||||
Task<int> GetUserTotalTokensAsync(int userId, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Gets recent queries (all)
|
||||
/// </summary>
|
||||
Task<List<AIQuery>> GetRecentQueriesAsync(int take = 20, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Gets query statistics
|
||||
/// Gets AI query statistics (totals, averages, today's usage)
|
||||
/// </summary>
|
||||
Task<AIQueryStats> GetStatsAsync(CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Statistics about AI queries
|
||||
/// </summary>
|
||||
public class AIQueryStats
|
||||
{
|
||||
public int TotalQueries { get; set; }
|
||||
public int TotalTokensUsed { get; set; }
|
||||
public int TotalPromptTokens { get; set; }
|
||||
public int TotalCompletionTokens { get; set; }
|
||||
public double AverageResponseTimeMs { get; set; }
|
||||
public int TodayQueries { get; set; }
|
||||
public int TodayTokens { get; set; }
|
||||
}
|
||||
|
||||
28
src/GreenHome.Application/Interfaces/IAdminService.cs
Normal file
@@ -0,0 +1,28 @@
|
||||
using GreenHome.Application.Dtos.Admin;
|
||||
|
||||
namespace GreenHome.Application;
|
||||
|
||||
public interface IAdminService
|
||||
{
|
||||
Task<AdminDashboardDto> GetDashboardAsync(CancellationToken cancellationToken);
|
||||
Task<PagedResult<AdminUserListItemDto>> GetUsersAsync(AdminUserFilter filter, CancellationToken cancellationToken);
|
||||
Task<AdminUserDetailDto?> GetUserAsync(int id, CancellationToken cancellationToken);
|
||||
Task<UserMutationOutcome> SetUserRoleAsync(int id, Domain.UserRole role, int currentAdminId, CancellationToken cancellationToken);
|
||||
Task<UserMutationOutcome> SetUserStatusAsync(int id, bool isEnabled, int currentAdminId, CancellationToken cancellationToken);
|
||||
Task<PagedResult<AdminDeviceListItemDto>> GetDevicesAsync(AdminDeviceFilter filter, CancellationToken cancellationToken);
|
||||
Task<AdminDeviceDetailDto?> GetDeviceAsync(int id, CancellationToken cancellationToken);
|
||||
Task<AdminDeviceCreateResult> CreateDeviceAsync(AdminDeviceCreateRequest request, int currentAdminId, CancellationToken cancellationToken);
|
||||
Task<AdminSettingsUpdateResult> UpdateDeviceSettingsAsync(int deviceId, AdminDeviceSettingsUpdateRequest request, int currentAdminId, CancellationToken cancellationToken);
|
||||
Task<IReadOnlyList<AdminDeviceMemberDto>?> GetDeviceMembersAsync(int deviceId, CancellationToken cancellationToken);
|
||||
Task<IReadOnlyList<UsageDayDto>> GetUsageAsync(DateTime? from, DateTime? to, int? userId, CancellationToken cancellationToken);
|
||||
Task<PagedResult<AdminAlertItemDto>> GetAlertsAsync(AdminAlertFilter filter, CancellationToken cancellationToken);
|
||||
Task<PagedResult<AdminPostItemDto>> GetPostsAsync(AdminPostFilter filter, CancellationToken cancellationToken);
|
||||
Task<AdminPostDetailDto?> GetPostAsync(int id, CancellationToken cancellationToken);
|
||||
Task<bool> DeletePostAsync(int id, int currentAdminId, CancellationToken cancellationToken);
|
||||
Task<AdminDeviceTestResultDto> TestDeviceSmsAsync(int deviceId, int currentAdminId, CancellationToken cancellationToken);
|
||||
Task<AdminDeviceTestResultDto> TestDeviceVoiceAsync(int deviceId, int currentAdminId, CancellationToken cancellationToken);
|
||||
Task<IReadOnlyList<AdminUserGrowthRowDto>> GetUserGrowthReportAsync(DateTime from, DateTime to, CancellationToken cancellationToken);
|
||||
Task<IReadOnlyList<AdminDeviceUptimeRowDto>> GetDeviceUptimeReportAsync(DateTime from, DateTime to, CancellationToken cancellationToken);
|
||||
Task<IReadOnlyList<AdminUsageByUserRowDto>> GetUsageByUserReportAsync(DateTime from, DateTime to, CancellationToken cancellationToken);
|
||||
Task<PagedResult<AdminAuditLogDto>> GetAuditLogsAsync(AdminAuditLogFilter filter, CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -22,4 +22,3 @@ public interface IAlertConditionService
|
||||
|
||||
Task<bool> HasUpdatedConditionsAsync(int deviceId, DateTime? lastUpdateDate, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
@@ -6,4 +6,3 @@ public interface IAlertLogService
|
||||
Task<AlertLogDto?> GetAlertLogByIdAsync(int id, CancellationToken cancellationToken);
|
||||
Task<int> CreateAlertLogAsync(AlertLogDto dto, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ namespace GreenHome.Application;
|
||||
|
||||
public interface IAlertService
|
||||
{
|
||||
Task<string?> CheckAndSendAlertsAsync(int deviceId, TelemetryDto telemetry, CancellationToken cancellationToken);
|
||||
Task<AlertCheckResult?> CheckAndSendAlertsAsync(int deviceId, TelemetryDto telemetry, CancellationToken cancellationToken);
|
||||
Task SendPowerOutageAlertAsync(int deviceId, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
@@ -5,5 +5,5 @@ public interface IAuthService
|
||||
Task<SendCodeResponse> SendVerificationCodeAsync(SendCodeRequest request, CancellationToken cancellationToken);
|
||||
Task<VerifyCodeResponse> VerifyCodeAsync(VerifyCodeRequest request, CancellationToken cancellationToken);
|
||||
Task<bool> CanResendCodeAsync(string mobile, CancellationToken cancellationToken);
|
||||
Task<UserDto?> GetUserByTokenAsync(string token, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
@@ -9,4 +9,3 @@ public interface IChecklistService
|
||||
Task<List<ChecklistCompletionDto>> GetCompletionsByChecklistIdAsync(int checklistId, CancellationToken cancellationToken);
|
||||
Task<int> CompleteChecklistAsync(CompleteChecklistRequest request, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
@@ -14,4 +14,3 @@ public interface IDailyReportService
|
||||
|
||||
Task<DailyReportResponse> GetMonthlyAnalysisAsync(MonthlyAnalysisRequest request, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace GreenHome.Application;
|
||||
|
||||
public interface IDeviceMemberService
|
||||
{
|
||||
Task<IReadOnlyList<DeviceMemberDto>> ListByDeviceAsync(int deviceId, CancellationToken cancellationToken);
|
||||
Task<DeviceMemberDto> UpsertAsync(UpsertDeviceMemberRequest request, CancellationToken cancellationToken);
|
||||
Task DeleteAsync(int deviceId, int userId, CancellationToken cancellationToken);
|
||||
Task<bool> CanManageDeviceAsync(int actorUserId, int deviceId, CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -10,5 +10,6 @@ public interface IDevicePostService
|
||||
Task<int> AddImageToPostAsync(int postId, string fileName, string filePath, string contentType, long fileSize, CancellationToken cancellationToken);
|
||||
Task DeleteImageAsync(int imageId, CancellationToken cancellationToken);
|
||||
Task<bool> CanUserAccessDeviceAsync(int userId, int deviceId, CancellationToken cancellationToken);
|
||||
Task<int> CreateSensorSnapshotAsync(CreateSensorSnapshotRequest request, CancellationToken cancellationToken);
|
||||
Task SetPostVoiceAsync(int postId, string fileName, string filePath, string contentType, long fileSize, int? durationSeconds, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
namespace GreenHome.Application;
|
||||
namespace GreenHome.Application;
|
||||
|
||||
// Services
|
||||
public interface IDeviceService
|
||||
{
|
||||
Task<int> AddDeviceAsync(DeviceDto dto, CancellationToken cancellationToken);
|
||||
@@ -1,4 +1,4 @@
|
||||
namespace GreenHome.Application;
|
||||
namespace GreenHome.Application;
|
||||
|
||||
public interface IDeviceSettingsService
|
||||
{
|
||||
@@ -20,4 +20,3 @@ public interface IDeviceTokenService
|
||||
/// </summary>
|
||||
Task<VerifyDeviceTokenResponse> VerifyDeviceTokenAsync(VerifyDeviceTokenRequest request, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||